////////////////////////////////////////////////
//
// Javascript behaviours for td-architects.eu
// Michael van Schaik, 2008 (GPL)
//
//////////////////////////////////////////

var targWidthSmall = 50;
var targHeightSmall = 20;
var targWidthBig = 570;
var scaleSteps = 10;
var borderSize = 10;
var maxDivsInCol = 60; // the number of divs per column we should try to find...
var intervalSpeed = 20;

if (navigator.userAgent.indexOf("Firefox")!=-1) { var firefox = 1; }

var columnDiv_list = [ "col1", "col2", "col3", "col4", "col5", "col6" ];

var interval = new Object();
// this contains the 'state' of the columns;
// 1 = website finished loading (menu normal)
// 2 = subcolumns maximized (columns invisible) (not used anymore)
// 3 = etc...
interval.state = 0;

window.onload = function() {
	//getWidths();
	//alert(column1_obj.width);
	interval.state = 1;
	//fitSubCols( 'col2', '3' )
	//showHideWholeStory('hidden');
	//showHideWholeStory('visible');
	setSpecialLinks();
	//setInterval(funcCall, intervalSpeed);
	//setInterval( refreshBgImg, 30*60000 ); // refresh the background every 30 minutes (30x60x1000)
	// provide the explanatory graphics;
	initgraph();
}

function show(message) {
	var showdiv = document.getElementById('showdiv');
	showdiv.innerHTML = showdiv.innerHTML+"<br />"+message;
}

///////////////
//
// refreshbackground
//
//////////
function refreshBgImg() {
	document.getElementsByTagName( 'body' )[0].style.backgroundImage = "url( './bg_img.php?"+Math.random() +"')";
}

///////////////
//
// general behaviours;
//
//////////
var scrollpos_old;
var scrollsteps = 10;
var scrolledsteps = 0;
var scrollinterval;
function setSpecialLinks() {
	var links = document.getElementsByTagName('a');
	for( var i=0; i<links.length; i++) {
		// imgLinks;
		if( links[i].href && links[i].rel == "jsLoadBigImg"){
			links[i].onclick = function(){
				var imgDiv = document.getElementById('bigPhoto_div');
//				imgDiv.innerHTML = "<center><img src=\""+this.href+"\" /></center>";
				var fileSplit = this.href.split("/");
				var fileName = fileSplit[fileSplit.length-1];
				imgDiv.innerHTML = "<center><a href=\"http://kobold.loud.nl/td/uploads/files/"+fileName+"\" target=\"_blank\"><img src=\""+this.href+"\" /></a></center>";
				return false;
			}
		}
		// internal links to full articles;
		if( links[i].href && links[i].rel == "jsLoadArticle"){
			links[i].onclick = function(){
				//window.alert('hit');
				showHideWholeStory('visible');
				//sendRequest('file.txt',handleRequest);
				
				//sendRequest('ajaxtest.php', 'loadText()');
				sendRequest(this.href+"&xmlhttp=1", loadText);
				//set links again for new html;

				//detect current scrollpos;
				if (navigator.appName == "Microsoft Internet Explorer"){scrollpos_old = document.body.scrollTop;} else {scrollpos_old = window.pageYOffset;}
				var scrollperstep = scrollpos_old / scrollsteps;
				scrollinterval = setInterval("scrollpage(0,"+-scrollperstep+");", 50);
				//console.log(scrollpos_old);
				
				return false;
			}
		}
		//closeDiv
		// internal links to full articles;
		if( links[i].href && links[i].rel == "closeDiv"){
			links[i].onclick = function(){
				loadText('Please wait...');
				showHideWholeStory('hidden');

				// scroll back to old position:
				var scrollperstep = scrollpos_old / scrollsteps;
				scrollinterval = setInterval("scrollpage(0,"+scrollperstep+");", 50);
				//console.log(scrollpos_old);

				return false;
			}
		}
	}
}

function scrollpage(xamount, yamount) {
	if (scrolledsteps < scrollsteps) {
		window.scrollBy(xamount, yamount); // horizontal and vertical scroll increments
		scrolledsteps +=1;
	} else {
		scrolledsteps = 0;
		clearInterval(scrollinterval);
	}
}

function loadText(htmlToLoad){
	var articleLoadDiv = document.getElementById('wholestory_bg');
	articleLoadDiv.innerHTML = htmlToLoad.responseText; 
}

function rescanLoadedText(htmlToLoad){
	// and yet again fuckin IE doesn't behave; (force loading of main image)
	var mainImg = document.getElementById('mainImg');
	//alert('hit');
	// try because some articles don't include image;
	try{
		var imgDiv = document.getElementById('bigPhoto_div');
		var fileSplit = mainImg.src.split("/");
		var fileName = fileSplit[fileSplit.length-1];
		imgDiv.innerHTML = "<center><a href=\"http://kobold.loud.nl/td/uploads/files/"+fileName+"\" target=\"_blank\"><img src=\"http://kobold.loud.nl/td/uploads/thumbnails/"+fileName+"\" /></a></center>";
	} catch(err) { 
		// do nothing if there's no images in the article
	}
	setSpecialLinks();
	//
	// a hack to scan new html and extract javascript, eval that javascript for included functions to work...
	//
	// re-eval javascript from htmlToLoad.responseText, which got loaded into imgDiv.innerHTML
	// try because some articles don't include image;
	try{
		var jsSnips = imgDiv.getElementsByTagName("script");
	} catch(err) { 
		// do nothing if there's no images in the article
	}
	//alert( imgDiv.getElementsByTagName("script") );
// 	for(var i=0; i<jsSnips.length; i++){
// 		alert(jsSnips[i]);
// 		alert(jsSnips[i].innerHTML);
// 		eval(jsSnips[i].innerHTML);//eval to make included js work
// 	}
	//eval(htmlToLoad.responseText);
	// re-run special links for newly loaded html
}

// continue this later; a function to write to page instead of object, because object is not seen via AJAZ
function writeFlash(divID, swfURL, imgURL, movWidth, movHeight, autoStart, allowFullScreen) {
	var flashDiv = document.getElementById(divID);
//<embed id="mediaplayer54" width="320" height="20" flashvars="file=http://kobold.loud.nl/joshan/uploads/files/42782ad1d4f37b7eba9cac506c4e84d0.Lightly_as_a_flock.wma.mp3&autostart=true" quality="high" name="mediaplayer54" style="" src="http://kobold.loud.nl/movieplayer/mediaplayer.swf" type="application/x-shockwave-flash"
	var htmlToWrite = "<embed ";
	htmlToWrite += "src=\"http://kobold.loud.nl/movieplayer/mediaplayer.swf\" ";
	htmlToWrite += "width=\""+movWidth+"\" ";
	htmlToWrite += "height=\""+movHeight+"\" ";
	htmlToWrite += "allowscriptaccess=\"always\" ";
	htmlToWrite += "allowfullscreen=\"true\" ";
	htmlToWrite += "flashvars=\"file="+swfURL+"&image="+imgURL+"&autostart="+autoStart+"&usefullscreen=true\" ";
	htmlToWrite += "type=\"application/x-shockwave-flash\" ";
	htmlToWrite += "/>"
	htmlToWrite = "<embed width=\"320\" height=\"260\" type=\"application/x-shockwave-flash\" flashvars=\"file=http://kobold.loud.nl/td/uploads/files/601fc1aff2211a091af05836cbb6080e.Beon1.wmv.flv&image=http://kobold.loud.nl/td/uploads/thumbnails/601fc1aff2211a091af05836cbb6080e.Beon1.wmv.jpg&autostart=true&usefullscreen=true\" allowfullscreen=\"true\" allowscriptaccess=\"always\" src=\"http://kobold.loud.nl/movieplayer/mediaplayer.swf\" />";
	flashDiv.innerHTML = htmlToWrite;
}

/*"<embed type=\"audio/ogg\" autoplay=\""+autoplay+"\" loop=\""+loop+"\" src=\""+url+"\" height=\""+m_height+"\" width=\""+m_width+"\" controller=\"true\" scale=\"aspect\">";*/

/*<embed 
  src="mediaplayer.swf" 
  width="300"
  height="300"
  allowscriptaccess="always"
  allowfullscreen="true"
  flashvars="file=playlist.xml&backcolor=0x000000&autostart=true"
/>*/

///////////////
//
// Show/hide maxedarticlediv;
//
//////////
function showHideWholeStory( display_val ) {
	//display_val = (document.getElementById(nr).style.display == 'none') ? 'block' : 'none';
	// instead: hidden or visible
	var displayDiv = document.getElementById('wholestory_cont');
	displayDiv.style.visibility = display_val;
	return false;
}

///////////////
//
// Scale Columns (horizontally):
//
//////////
function scaleCols_setInterv( hoverCol ) {
	if ( interval.state == 1 ) {
		var funcCall = "scaleCols('"+hoverCol+"')";
		interval.scaleCols_interv = setInterval(funcCall, intervalSpeed);
	}
}
function scaleCols_clearInterv() {
	clearInterval(interval.scaleCols_interv);
	//clearInterval(interval.fitSubCols_interv);
}
function scaleCols( hoverdiv ) {
	var activeObj = document.getElementById(hoverdiv);
	var currentwidth = activeObj.offsetWidth;
	var toScale = Math.round((targWidthBig-currentwidth)/scaleSteps);
	// change column width
	activeObj.style.width = currentwidth + toScale +"px"; 
	// change width of all (direct) children of column
	for ( var i=0; i < maxDivsInCol; i++ ) { // try for id 'colxdiv1' t/m 'colxdiv29'
		var divName = hoverdiv+"div"+i;
		var divFound = document.getElementById(divName);
		if(divFound){ // if the a div with that id is found...
			divFound.style.width = currentwidth + toScale - borderSize + "px";
		}
	}
	// itterate over all other columns and make them smaller (not the active one)
	for ( var i in columnDiv_list ) {
		var nothoverdiv = columnDiv_list[i]
		//show(nothoverdiv);
		if (nothoverdiv != hoverdiv) {
			var notactiveObj = document.getElementById(nothoverdiv);
			var currentwidth = notactiveObj.offsetWidth;
			var toScale = Math.round((targWidthSmall-currentwidth)/scaleSteps);
			notactiveObj.style.width = currentwidth+toScale +"px";
			// change width of all (direct) children of column
			for ( var i=0; i < maxDivsInCol; i++ ) { // try for id 'colxdiv1' t/m 'colxdiv29'
				var divName = nothoverdiv+"div"+i; // construct divnames to search for...
				var divFound = document.getElementById(divName);
				if(divFound){ // if the a div with that id is found...
					// make paragraphs invisible:
					if (i!=0 && firefox==1) {
						var divPsFound = divFound.getElementsByTagName('p');
					} else { divPsFound =''; }
					for( var j=1; j < divPsFound.length; j++ ) {
						divPsFound[j].style.display = 'none'; //'block' to make visible
					}
					divFound.style.width = currentwidth + toScale - borderSize + "px";
					
				}
			}
		}
	}
}

///////////////
//
// Scale Divs in Columns (vertically):
//
//////////
function scaleDivs_setInterv( hoverDiv, divsInCol ) {
	if ( interval.state == 1 ) {
		var funcCall = "scaleDivs('"+hoverDiv+"', '"+divsInCol+"')";
		interval.scaleDivs_interv = setInterval(funcCall, intervalSpeed);
	}
}
function scaleDivs_clearInterv() {
	clearInterval(interval.scaleDivs_interv);
}
function scaleDivs( hoverdiv, divsInCol ) {
	var divsVertic = Number(divsInCol);
	var activeObj = document.getElementById(hoverdiv);
	var parentHeight = activeObj.parentNode.offsetHeight - 60;
	var currentHeight = activeObj.offsetHeight;
	var targHeightBig = parentHeight-((divsVertic-1)*(targHeightSmall+borderSize));
	//show(targHeightBig);
	var toScale = Math.round((targHeightBig-currentHeight)/scaleSteps);
	// change column Height
	activeObj.style.height = currentHeight + toScale -borderSize +"px";
	// make paragraph visible (for firefox2's slow font rendering):
	if(firefox==1){
		var divPsFound = activeObj.getElementsByTagName('p');
		for( var j=1; j < divPsFound.length; j++ ) {
			divPsFound[j].style.display = 'block'; //'none' to make invisible
		}
	}
	// iterate over all other columns and make them smaller (not the active one)
	var divsBaseName = hoverdiv.substring(0, 7);
	for ( var i = 1; i <= divsVertic; i++ ) {
		var nothoverdiv = divsBaseName+i;
		if (nothoverdiv != hoverdiv) {
			var notactiveObj = document.getElementById(nothoverdiv);
			// make paragraph visible (for firefox2's slow font rendering):
			if(firefox==1){
				var divPsFound = notactiveObj.getElementsByTagName('p');
				for( var j=1; j < divPsFound.length; j++ ) {
					divPsFound[j].style.display = 'none'; //'block' to make invisible
				}
			}
			var currentHeight = notactiveObj.offsetHeight;
			var toScale = Math.round((targHeightSmall-currentHeight)/scaleSteps);
			// change column width
			notactiveObj.style.height = currentHeight + toScale -borderSize +"px";
		}
	}
}


///////////////
//
// infograph functionality;
//
//////////

function initgraph() {
	var graphdiv = document.getElementById('graph');
	//graphdivcolorbar.style.visibility = hidden;
	//graphdivcolorbar.style.height = '10px';
	//console.log(graphdivcolorbar.style.height);

	// Detect if the browser is IE or not.
	// If it is not IE, we assume that the browser is NS.
	var IE = document.all?true:false
	// If NS -- that is, !IE -- then set up for mouse capture
	if (!IE) document.captureEvents(Event.MOUSEMOVE)
	// Set-up to use getMouseXY function onMouseMove
	document.onmousemove = getMouseXY;
	// Temporary variables to hold mouse x-y pos.s
	var tempX = 0
	var tempY = 0
	
	// Main function to retrieve mouse x-y pos.s
	function getMouseXY(e) {
	if (IE) { // grab the x-y pos.s if browser is IE
		tempX = event.clientX + document.body.scrollLeft
		tempY = event.clientY + document.body.scrollTop
	} else {  // grab the x-y pos.s if browser is NS
		tempX = e.pageX
		tempY = e.pageY
	}  
	// catch possible negative values in NS4
	if (tempX < 0){tempX = 0}
	if (tempY < 0){tempY = 0}  
	// show the position values in the form named Show
	// in the text fields named MouseX and MouseY
	graphdiv.style.left = tempX+4+'px';
	graphdiv.style.top = tempY+'px';
	}
}

function showGraph(perc, kind) {
	var graphdiv = document.getElementById('graph');
	var graphdivcolorbar = document.getElementById('graphdivcolor');
	var graphdivinfo = document.getElementById('infotxt');
	graphdiv.style.display = 'block'; //'none';
	graphdivcolorbar.style.height = perc+'px';
	if( kind=='article' ) {
		graphdivinfo.innerHTML = '<p>This ARTICLE accounts for '+perc+'% of the total amount of hits within its CATEGORY.</p>'; }
	if( kind=='category' ) {
		graphdivinfo.innerHTML = '<p>This ARTICLE accounts for '+perc+'% of the total amount of hits within the WEBSITE.</p>'; }
	if( kind=='website' ) {
		graphdivinfo.innerHTML = '<p>This CATEGORY accounts for '+perc+'% of the total amount of hits within the WEBSITE.</p>'; }
}

function hideGraph() {
	var graphdiv = document.getElementById('graph');
	graphdiv.style.display = 'none';
}







///////////////
//
// XMLHTTPObject functions (by quirksmode, see: http://www.quirksmode.org/js/xmlhttp.html)
//
//////////
// set xml object once:

function sendRequest(url,callback,postData) {
	req = createXMLHTTPObject();
	if (!req) return;
	var method = (postData) ? "POST" : "GET";
	req.open(method,url,true);
	// the following doesn't work for all browsers, and we lose the browser info through using it too.
	//req.setRequestHeader('User-Agent','XMLHTTP/1.0');
	if (postData)
		req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
	req.onreadystatechange = function () {
		if (req.readyState != 4) { // If not finished yet, show 'loading' message.
			tmpCallback=new Object();
			tmpCallback.responseText="<h2>Loading, please wait...</h2>";
			callback(tmpCallback);
			return;
		}
		if (req.status != 200 && req.status != 304) {
			tmpCallback=new Object();
			tmpCallback.responseText="<p><span class=\"closebtn\"><a href=\"http://td-architects.eu/devel/\" rel=\"closeDiv\" title=\"Close article\" onclick=\"showHideWholeStory('hidden');\">&uarr;&uarr;</a></span>";
			callback(tmpCallback);
			rescanLoadedText(tmpCallback);
			alert('HTTP error ' + req.status);
			return;
		}
		//req.setContentType("text/html");
		callback(req);
		rescanLoadedText(req);
	}
	if (req.readyState == 4) return;
	req.send(postData);
}
var XMLHttpFactories = [
	function () {return new XMLHttpRequest()},
	function () {return new ActiveXObject("Msxml2.XMLHTTP")},
	function () {return new ActiveXObject("Msxml3.XMLHTTP")},
	function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];
function createXMLHTTPObject() {
	var xmlhttp = false;
	for (var i=0;i<XMLHttpFactories.length;i++) {
		try {
			xmlhttp = XMLHttpFactories[i]();
		}
		catch (e) {
			continue;
		}
		break;
	}
	return xmlhttp;
}

