//=======================================================\\
//                    13thparallel.org                   \\
//                   Copyright (c) 2002                  \\ 
//   see (13thparallel.org/?title=about) for more info   \\
//=======================================================\\

// &#187; >> &#171; <<

var h1titles = new Array();
var columns;
var cachedcolumns = new Array();
var firstinitcall=1;
var idcache;
var actif=null;
var rootIssue = "";

var navigateString = "navigate";

function CalculateAndDrawNextColumn() {
	sDate = new Date();
	document.getElementById("debug").innerHTML += "--nc-"+sDate;
	Columns.popFragment(Columns.remainingText, colWidth, colHeight);
	doColumnsAndLinksFragment(Columns.cols);
	columns = Columns.cols;
	numCols = columns.length - 1;
	if (Columns.remainingText == "") {
		window.clearInterval(actif);
		AfterAllColumnDrawn();
	}
}

function AfterAllColumnDrawn() {

/*	if (!cachedcolumns[idcache]) {
	columns = Columns.cols;
	cachedcolumns[idcache] = Columns.cols;
	} else {
	  columns = cachedcolumns[idcache];
	}*/

	columns = Columns.cols;

	while (columns.length < 2) columns.push("<p>&nbsp;</p>");
	numCols = columns.length - 1;
		
	// Extract the column titles
	sDate = new Date();
	document.getElementById("debug").innerHTML += "<b>--gct--</b>"+sDate;
	colTitles = getColumnTitles();

	// Setting the UI controls
	document.getElementById("divTitles").innerHTML = ": "+navigateString;
	document.getElementById("divContentsToggle").innerHTML = '<a href="#" onclick="toggleContents(); return false;" class="contents" id="anchorArrow">»</a>';
	
	// Hide loading cover
	document.getElementById("divLoading").style.visibility = "hidden";

	// Scroll to chapter specified by URI
	scrollToChapter(chapter);

	// Fix Location Bar
	setLocationBar();

	// Sort out issue specific contents AND site contents
	objSiteContents = new make("divSiteContents");
	objIssueContents = new make("divIssueContents");
	objIssueContents.elm.innerHTML = "";
	for (var i = 0; i < 100; i++) {
		if (h1titles[i]) {
			objIssueContents.elm.innerHTML += "<a href=\"#\" onclick=\"scrollTo("+i+"); return false;\" class=\"contents\">"+h1titles[i]+"</a> - ";
		}
	} 
	objToggContents = new make("divContentsToggle");

	if(heading != "home" && issueName != "information") {
		objIssueContents.show();
		objToggContents.show();
		objIssueContents.moveTo(15 - objIssueContents.elm.offsetWidth -200, objIssueContents.elm.offsetTop);
	}

	
	// Get rid of pesky outlines
	destroyEvilLinkOutlines();
	toggleContents();
	toggleContents();
	if (document.getElementById('divLoading2'))
	{document.getElementById('divLoading2').style.visibility = "hidden";}


}

function calculateColumns() {

//if (document.getElementById('divLoading2'))
//{document.getElementById('divLoading2').style.visibility = "visible";}
	document.getElementById("divLoading").style.visibility = "hidden";


//	  columns = Columns.splitText(document.getElementById('divContent').innerHTML, colWidth, colHeight);

	Columns.cols = null;
	Columns.idxCol = 0;
	Columns.remainingText = document.getElementById('divContent').innerHTML;

	sDate = new Date();
	document.getElementById("debug").innerHTML += "--nc-"+sDate;
//	doColumnsAndLinksFragment(Columns.cols);

// give a chance to see the drawing...
	actif = window.setInterval('CalculateAndDrawNextColumn()',5);

}

function init(idx) {
	if (!document.getElementById 
	|| !document.getElementsByTagName 
	|| !document.createElement 
	|| typeof document.getElementsByTagName("head")[0].innerHTML == "undefined"
	|| (window.showModalDialog && navigator.userAgent.toLowerCase().indexOf("mac") > -1)) {
		return;
	}

	sDate = new Date();
	document.getElementById("debug").innerHTML += "Entering init ("+idx+")<br>"+sDate;


	if (firstinitcall && document.getElementById('divContent1'))
	{ firstinitcall=0; 
          document.getElementById('divContent').innerHTML=document.getElementById('divContent1').innerHTML;
	}
	idcache = idx;
	// Position the canvas div
	setCanvas();
	window.onresize = setCanvas;

	// Set fontsize
	Text.size = parseInt(GetCookie ("fontsize", 11));

	document.getElementById("divPage").style.fontSize = Text.size + Text.unit;
	document.getElementById("divSizer").style.fontSize = Text.size + Text.unit;

	// Split content into columns


	sDate = new Date();
	document.getElementById("debug").innerHTML += "--bcc-"+sDate;
	window.setTimeout('calculateColumns()',5);
//	calculateColumns();
	sDate = new Date();
	document.getElementById("debug").innerHTML += "---"+sDate;

}

//window.onload = init;

// Position the canvas div
function setCanvas() {
	document.getElementById("divCanvas").style.position = "absolute";
// ce qui permet de mettre position:relative et margin:auto avant que ce setCanvas soit appelé
	canvas = new getCanvas();
	var canvasLeft = (canvas.w - document.getElementById("divCanvas").offsetWidth) / 2;
//	var canvasLeft = 0;
//	var canvasTop = (canvas.h - document.getElementById("divCanvas").offsetHeight) / 3;
	var canvasTop = 20;
	if (canvasLeft < 0) canvasLeft = 0;
	if (canvasTop < 0) canvasTop = 0;
	document.getElementById("divCanvas").style.left = canvasLeft + "px";
	document.getElementById("divCanvas").style.top = canvasTop + "px";
}


// Text object for changing text size
var Text = {
	size : parseInt(GetCookie("fontsize", 11)),
	unit : "px",
	
	doSize : function(num) {
		Text.size += num;
		if (Text.size < 1) Text.size = 1;
		SetCookie ("fontsize", Text.size, 24*365);
		document.getElementById("divPage").style.fontSize = Text.size + Text.unit;
		document.getElementById("divSizer").style.fontSize = Text.size + Text.unit;
		init();
		if (currentCol > columns.length - 2) {
			currentCol = columns.length - 2;
			objLink.moveTo(32 + currentCol*10, objLink.y);
			objSlider.moveTo(-currentCol*360, objSlider.y);
			setLocationBar();
		}
	}
}


// Place columns in div tags and create links
function doColumnsAndLinksFragment(columns) {
	var tx = "";
	var links = '<img src="/images/13/1x1.gif" height="1" width="31" alt="" />';
	
	for (var i=0; i<columns.length; i++) {
//		tx += '<div id="divColumn' + i + '" style="font-size:8pt;border: solid blue 1px;position: absolute; top: 0px; left: ' + (i*(colWidth+colSpace)+colSpace) + 'px; width: ' + colWidth + 'px; height: ' + colHeight + 'px;">'
		tx += '<div id="divColumn' + i + '" style="position: absolute; top: 0px; left: ' + (i*(colWidth+colSpace)+colSpace) + 'px; width: ' + colWidth + 'px; height: ' + colHeight + 'px;">'
		tx += columns[i];
/*		c = columns[i];
		c = c.replace(/&/g,"&amp;");
		c = c.replace(/</g,"&lt;");
		c = c.replace(/>/g,"&gt;");
		tx += c;//.slice(600); */
		tx += '</div>';
		links += '<a href="#" onclick="scrollTo('+i+'); return false;" onmouseover="showTitle('+i+'); window.status=\'\'; return true;" onmouseout="resetTitle(); window.status=\'\';"><img src="/images/13/nav_square.gif" border="0" height="12" width="10" alt="" /></a>';
	}
	if (!objSlider) {objSlider = new make("divPageSlider");}
	if (!objLink) {objLink = new make("divLinkBlock");}
//	objSlider.elm.innerHTML = tx;
	
	document.getElementById("divPageSlider").innerHTML = tx;
	var tempLinks = document.getElementById("divLinks");
	tempLinks.innerHTML = links;
	document.getElementById("divTitles").style.left = tempLinks.offsetLeft + tempLinks.offsetWidth + 1 + "px";
}

function doColumnsAndLinks() {
	var tx = "";
	var links = '<img src="/images/13/1x1.gif" height="1" width="31" alt="" />';
	for (var i=0; i<columns.length; i++) {
		tx += '<div id="divColumn' + i + '" style="position: absolute; top: 0px; left: ' + (i*(colWidth+colSpace)+colSpace) + 'px; width: ' + colWidth + 'px; height: ' + colHeight + 'px;">'
		tx += columns[i];
		tx += '</div>';
		links += '<a href="#" onclick="scrollTo('+i+'); return false;" onmouseover="showTitle('+i+'); window.status=\'\'; return true;" onmouseout="resetTitle(); window.status=\'\';"><img src="/images/13/nav_square.gif" border="0" height="12" width="10" alt="" /></a>';
	}
	objSlider = new make("divPageSlider");
	objLink = new make("divLinkBlock");
	objSlider.elm.innerHTML = tx;
	
	var tempLinks = document.getElementById("divLinks");
	tempLinks.innerHTML = links;
	document.getElementById("divTitles").style.left = tempLinks.offsetLeft + tempLinks.offsetWidth + 1 + "px";
}

function removeTags(xstr) {
	return xstr.replace(/<\/?[^>]+>/gi,"");
}

// Extract the column titles
function getColumnTitles() {
	var headers = new Array();
	var titles = new Array();
	var img = null;

	if (!levelTitle) {levelTitle=1;}

	for (var i = 0; i < h1titles.length; i++) {
		h1titles[i] =  null;
	}
	
// attention, cette methode n'assure qu'un titre par colonne, ce qui est
// bien pour la navigation du bas, mais moins pratique pour pouvoir faire
// des scrollToChapter vers tous les h1..h6, meme quand ils sont plusieurs
// dans une meme colonne. TODO
	for (var i = 0; i < 100; i++) {
		if (!document.getElementById("divColumn" + i)) break;
		
		for (var j = 6; j >= 1; j--) {
// on va de 6 a 1 pour que le header le plus important soit retenu
			headers = document.getElementById("divColumn" + i).getElementsByTagName("h" + j);
			if (!headers || headers.length == 0) continue;
			
			img = headers[0].getElementsByTagName("img")[0];
			

			if (headers[0].innerText) {
				titles[i] = headers[0].innerText.toLowerCase();
			} else if (img && img.title) {
				titles[i] = img.title.toLowerCase();
			} else if (img && img.alt) {
				titles[i] = img.alt.toLowerCase();
			} else /* emulation de innerText pour les browsers !IE */ {
				titles[i] = removeTags(headers[0].innerHTML.toLowerCase());
			}

			if (j == levelTitle) {
				var h1t = headers[0].cloneNode(true);
				if (h1t.getElementsByTagName("img")[0]) {
					h1t.getElementsByTagName("img")[0].height=12;
				}
				h1titles.push(h1t.innerHTML);
			}
/*
			if (!titles[i] && img && img.title) {
				titles[i] = img.title.toLowerCase();
				if (j == levelTitle) {h1titles.push(titles[i]);}
				break;
			}
			else if (img && img.alt){
				titles[i] = img.alt.toLowerCase();
				if (j == levelTitle) {h1titles.push(titles[i]);}
				break;
			}
*/
		}
		if (!titles[i] && i == 0) titles[i] = navigateString;
		if (!titles[i] && i != 0) titles[i] = titles[i-1];
	}
	return titles;
}


// Takes a chapter name and scrolls to it (if it exists).
function scrollToChapter(c) {
	var chapter = c;
document.getElementById("debug").innerHTML += "<br>Chapter["+chapter+"]";

	// Set it to scroll to the right chapter.
	var i = 0;
	while (colTitles[i] != chapter && i < colTitles.length) { i++; document.getElementById("debug").innerHTML += "<br>["+i+"]["+colTitles[i]+"]"}
	if (i != colTitles.length) scrollTo(i);
	return false;
}


// Fix Location Bar
function setLocationBar() {
	if (currentCol != 0) chapter = colTitles[currentCol];
	else chapter = "";

//	if (heading == "undefined") {var heading = "";}
//	if (issueName == "undefined") {var issueName = "";}
var heading = "";
//var issueName = "";	
	//set up location bar:
	objLocation = new make("divLocation");
	var strLocation = '&nbsp;&nbsp;&nbsp;&nbsp;<strong>';
	if(issue=="none" || issue=="") {
		strLocation += '<a href="'+rootIssue+'/?title=' + heading;
	} else if(!heading || heading=="home" ) {
		var monthNo = issue.getMonth()+1;
		if(monthNo < 10) monthNo = "0" + monthNo;
		strLocation += '<a href="'+rootIssue+'/?issue=' + issue.getFullYear() + "." + monthNo;
//		strLocation += '<a href="/wimax/issue' + monthNo + issue.getFullYear() + ".html";
	} else {
		var monthNo = issue.getMonth()+1;
		if(monthNo < 10) monthNo = "0" + monthNo;
		strLocation += '<a href="'+rootIssue+'/?issue=' + issue.getFullYear() + "." + monthNo + '&amp;title=' + heading;
	}

	if(chapter) strLocation  += '&chapter=' + chapter;
	strLocation += '">vous êtes dans</a>:';
	strLocation += '</strong> &nbsp;' + issueName + ' » ';
	strLocation += heading.replace(/\_/," ");
//	objLocation.elm.innerHTML = strLocation;
//	return;
	if(chapter) strLocation += ' » ';
	strLocation += chapter.replace(/\_/," ");
	
	objLocation.elm.innerHTML = strLocation;
}


// Get rid of pesky outlines
function destroyEvilLinkOutlines() {
	var lnks = document.links ? document.links : document.getElementsByTagName ? document.getElementsByTagName("a") : null;
	if (lnks) {
		for (var m = 0; lnks[m]; m++) {
			lnks[m].onfocus = function(){ this.blur() };
		}
	}
}


function scrollTo(i) {
	if (columns.length > 2) {
		currentCol = i;
		if (currentCol < 0) currentCol = 0;
		if (currentCol >= numCols - 1) currentCol = numCols - 1;
		setPos();
	}
}


function scrollLeftArrow() {
	if (currentCol > 0) {
		currentCol--;
		setPos();
	}
}


function scrollRightArrow() {
	if (currentCol < numCols - 1) {
		currentCol++;
		setPos();
	}
}


function setPos() {
	objLink.timeSlide(32 + currentCol*10, objLink.y, 1500, -0.999, null, true);
	objSlider.timeSlide(-currentCol*(colWidth+colSpace), objSlider.y, 1500, -0.999, null, true);
	setLocationBar();
}


function showTitle(num) {
	document.getElementById("divTitles").innerHTML = ":&nbsp;" + colTitles[num];
}


function resetTitle() {
	document.getElementById("divTitles").innerHTML = ": "+navigateString;
}

	
function openPrintVersion() {
	var url = "printversion.php" + location.search;
	var newWindow = window.open(url);
	newWindow.focus();
}


// Toggle issue specific contents
var contentState = false;
function toggleContents() {
	if (contentState) {
		objIssueContents.timeSlide(15-objIssueContents.elm.offsetWidth-2738, objIssueContents.elm.offsetTop, 1500, -0.999, null, true);
		objSiteContents.timeSlide(15, objSiteContents.elm.offsetTop, 1500, -0.999, null, true);
		contentState = false;
		document.getElementById("anchorArrow").innerHTML = "»";
		document.getElementById("divContentsToggleRight").innerHTML = "";
	}
	else {
		objIssueContents.timeSlide(15, objIssueContents.elm.offsetTop, 1500, -0.999, null, true);
		objSiteContents.timeSlide(0-objSiteContents.elm.offsetWidth, objSiteContents.elm.offsetTop, 1500, -0.999, null, true);
		contentState = true;
		document.getElementById("anchorArrow").innerHTML = "«";
		if (objIssueContents.elm.offsetWidth > 738) {document.getElementById("divContentsToggleRight").innerHTML = '<a href="#" onclick="slideIssueContents(); return false;" class="contents" id="anchorArrowRight" title="faire défiler les titres">»</a>';}
	}
}

function slideIssueContents() {
	objIssueContents.timeSlide(objIssueContents.elm.offsetLeft-400, objIssueContents.elm.offsetTop, 1500, -0.999, null, true);
}

// Precache the images used for rollovers and that are inserted by innerHTML
//precache("/images/13/nav_text.gif");
//precache("/images/13/nav_square.gif");

//var arrow_left_off = precache("/images/13/arrow_left.gif");
//var arrow_left_on = precache("/images/13/arrow_left2.gif");
//var arrow_right_off = precache("/images/13/arrow_right.gif");
//var arrow_right_on = precache("/images/13/arrow_right2.gif");


// $ # ^ % % A % * P ^ O * & % C * & A ^ L % ^ $ Y ^ % * P & ^ S % $ & E # # %
