//fade.js - on timer, select new ads, load them indirectly, and fade them into and out of the dom
//2008.09.08 for jetsolutions
//2008.03.16 as ads.js for macthemes, luke mckenzie, theclockspot.com

//assumes mootools.js

//pseudocode:
//get xml via ajax (NOT mootools right now)
//parse xml into an array
//load new img (for second round - first round was placed by php)
//set timer for updating (for second round)
//....
//timer fires
//if ads haven't loaded, set timer and break
//if they have
	//fade out dom elements?
	//update dom elements
	//fade in dom elements?
	//load new img (for third round etc.)
	//set timer (for third round etc.)

//var pathtohome = '../../'; PHP HEADER SETS THIS KTHX

//variables from the xml
var pause = '';
var fade = '';
var path = '';
var fadeimage = []; //all the possible images
var fadeimageBackup = []; //for restoring fadeimage after items have been removed from it
//vars used as ajax results etc
var req = ''; //ajax request for xml
var reqFade = ''; //images metadata; reqFade = [title,imageurl,linkurl]
var reqFadeImg = ''; //images (actual data)
var reqFadeFx = '' //mootools fx objects (one for each image well)
var reqFadeCount = 0; //counts images as they arrive from server
var reqFadeWhich = true; //visibility switch: if true, imagelinks-na; if false, imagelinks-nb

function getAjaxRequestObj() {
	//returns ajax request object appropriate for browser, if possible
	//this is all Luke, not mootools
	var request = null;
	try {
	  request = new XMLHttpRequest();
	} catch (trymicrosoft) {
	  try {
	    request = new ActiveXObject("Msxml2.XMLHTTP");
	  } catch (othermicrosoft) {
	    try {
	      request = new ActiveXObject("Microsoft.XMLHTTP");
	    } catch (failed) {
	      request = null;
	    }
	  }
	}
	if (request == null) alert("Error creating request object!");
	return request;
}

function initFade() {
	//create request object and ask for xml
	req = getAjaxRequestObj();
	req.open("GET", pathtohome+"design/header-home/fade.xml", true); //true=asynchronous
	req.onreadystatechange = initFadeUpdate;
	req.send(null);
}

if(flipimages) window.addEvent('domready', initFade); //moo //can you do this with onload? I tried and failed :/

/*function initReqFade() {
	
}*/
function initReqFadeFx() {
		//Why am I animating both ads to crossfade? Why not simply fade one in and out atop the other?
		//Well, I am worried that having two linked imgs atop one another might be a problem. It seems less reliable.
		//Furthermore, the animation seems smoother on Mac browsers, and eliminates a bit of Win IE7 glitching
		reqFadeFx = new Array();
		//This one acts upon imagelinks-na
		reqFadeFx[0] = new Fx.Style(document.getElementById("headerimg1"), 'opacity', {
			duration: (fade*1)*1000, //mathify
			transition: Fx.Transitions.Quad.easeOut
			//onComplete: updateFade2
		}); //moo
		//This one acts upon imabelinks-nb
		reqFadeFx[1] = new Fx.Style(document.getElementById("headerimg2"), 'opacity', {
			duration: (fade*1)*1000, //mathify
			transition: Fx.Transitions.Quad.easeOut
		}); //moo
}

function initFadeUpdate() { //ajax callback for when xml arrives
	//when xml arrives, isolate dynamic ads and put them in fadeimage[]
	if(req.readyState == 4) {
		if(req.status == 200) {
			var xmlDoc = req.responseXML;
			//var xmlDoc = req;
			//expecting: <fadeimages pause fade path> <fadeimage static title image link> </fadeimages>
			var fadeimagesNodeList = xmlDoc.getElementsByTagName("fadeimages");
			pause = fadeimagesNodeList.item(0).getAttribute("pause");
			fade = fadeimagesNodeList.item(0).getAttribute("fade");
			path = fadeimagesNodeList.item(0).getAttribute("path");
				if(path.substring(path.length-1)!='/') path+='/'; //needs us a trailing slash
			mode = fadeimagesNodeList.item(0).getAttribute("mode");
			var fadeimageNodeList = fadeimagesNodeList.item(0).getElementsByTagName("fadeimage");
			k=0; //number of entries into array - increments with each addition,
				//so we don't have nulls in the entries which are static
			for(i=0;i<fadeimageNodeList.length;i++) {
				j=fadeimageNodeList.item(i); //in place of the foreach in fadeimages.php
				fadeimage[k] = [j.getAttribute("title"), j.getAttribute("image"), j.getAttribute("link")];
				k++;
			}
			//set the backup for fadeimage
			for(i=0;i<fadeimage.length;i++) { fadeimageBackup[i] = fadeimage[i]; }
			//set up the mootools transitions
			initReqFadeFx(); //moo
			//load the next set of ads
			loadNewFade();
			//set timeout for updating ads
			setTimeout('updateFade()',(pause*1)*1000);
		} else { //if the status isn't 200, this will alert us to problems //FIX EVERYWHERE
			var msgs = 'Error! Retrieval came back with status '+req.status+'.';
			var bitsy = req.getResponseHeader("Status");
			if(bitsy) msgs += '\n\n'+bitsy;
			alert(msgs);
		} //close if req.status = 200
	}
}

function loadNewFade() {
	//set reqFade as info for current round of images
	while(true) {
			//if we've used up all possible ads but still need more, revert fadeimage from backup early
			//if(fadeimage.length==0) revertDynamicFade();
			//select random ad in fadeimage[]
			j=$random(0,fadeimage.length-1); //moo
			//if it's not a duplicate of what was in the well last time
						//alert('fadeimage[j] is '+fadeimage[j]+'... 0 <= '+j+' < '+fadeimage.length);
			if(reqFade[1]!=fadeimage[j][1]) {
				reqFade = fadeimage[j]; //apply change
				fadeimage.splice(j,1); //remove option from fadeimage
				break; //bust out of the loop
			} //else, if it was duplicate, the while loop needs to try again on a different option
			fadeimage.splice(j,1); //remove option from fadeimage anyway
	}
	//having selected the images for this round, revert fadeimage from the backup
	revertDynamicFade();
	//load up images asynchronously - ajax isn't needed, though
	reqFadeImg = new Image();
	reqFadeImg.onLoad = loadedAd();
	reqFadeImg.src = path+reqFade[1]; //reqFade[i] = [title,imageurl,linkurl]
}
/*function setReqFadeOrder(mode) {
	//We're using reqFadeOrder[n] to specify the order of loading, if other than 'all' or 'order.'
	switch(mode) {
		case 'random':
			var dumbArray = [];
			for(s=0;s<numads;s++) dumbArray[s] = s; //create array of options
			for(s=0;s<numads;s++) {
				//note this is pretty much just like what happens in loadNewFade()
				t=$random(0,dumbArray.length-1); //moo
				reqFadeOrder[s]=dumbArray[t];
				dumbArray.splice(t,1);
				//in the end dumbArray will have nothing in it
			}
			break;
		case 'all': break;
		case 'order': break;
		//In these two special cases, the procedures don't need variables in reqFadeOrder[] to do their job.
	}
}*/
function revertDynamicFade() { //reverts fadeimage[] from fadeimageBackup[]	
	for(q=0;q<fadeimageBackup.length;q++) { fadeimage[q] = fadeimageBackup[q]; }
				//fadeimage == fadeimageBackup doesn't work because
				//it creates reference rather than equivalent data
				//is there a more efficient way to do this than the one I've chosen?
}
function loadedAd() { //runs when an ad image is loaded - increments reqFadeCount
	reqFadeCount++;
}
function updateFade(w) {
	//updateFade() is run after a timeout set by initFadeUpdate() or updateFade() itself.
	//By the time updateFade() runs, we're hoping all ads have loaded into reqFadeImg[],
	//which would be indicated by reqFadeCount == numads.
	//If that's not the case, updateFade() sets a one-second timeout for itself.
	//So, theoretically, if a given image never loads, these timeouts go on indefinitely and it stalls.
	if(reqFadeCount==1) { //if all the ads have loaded
		updateAd();
		updateFadeDone();
	} else setTimeout('updateFade(null)',1000);
}
function updateFadeDone() {
	reqFadeWhich = !reqFadeWhich; //flip the flag
	reqFadeCount=0; //set the load counter back to zero
	loadNewFade(); //load next set of ads
	setTimeout('updateFade(null)',(pause*1)*1000); //set timeout for updating them
}
function updateAd() {
	//which is which
	var oldAd = document.getElementById("headerimg"+(reqFadeWhich?'1':'2'));
	var newAd = document.getElementById("headerimg"+(reqFadeWhich?'2':'1'));
	var urlbox = document.getElementById("headerlink");
	//place new stuff in the hidden div
	newAd.innerHTML = "<img class='headerimg' src='" + path + reqFade[1] + "'>"
	urlbox.innerHTML = "<a href='" + reqFade[2] + "' title='" + reqFade[0] + "'></a>";
	//do the fades
	//reqFadeFx[i].start((reqFadeWhich?0:1),(reqFadeWhich?1:0)); //that you'd do if only fading b
	reqFadeFx[(reqFadeWhich?0:1)].start('1','0'); //fade out the old one
	reqFadeFx[(reqFadeWhich?1:0)].start('0','1'); //fade in the new one
}