// IXF1.11 :: Image cross-fade 
// *****************************************************
// DOM scripting by brothercake -- http://www.brothercake.com/
//******************************************************
//global object
var ixf = { 'clock' : null, 'count' : 1 }



var image_index=0;

//crossfade setup function
function crossfade()
{
	//if the timer is not already going
	if(ixf.clock == null)
	{
		//copy the image object 
		ixf.obj = arguments[0];
		
		//copy the image src argument 
		ixf.src = ixf.cache[image_index%ixf.imgsLen].src;
		
		//store the supported form of opacity
		if(typeof ixf.obj.style.opacity != 'undefined')
		{
			ixf.type = 'w3c';
		}
		else if(typeof ixf.obj.style.MozOpacity != 'undefined')
		{
			ixf.type = 'moz';
		}
		else if(typeof ixf.obj.style.KhtmlOpacity != 'undefined')
		{
			ixf.type = 'khtml';
		}
		else if(typeof ixf.obj.filters == 'object')
		{
			//weed out win/ie5.0 by testing the length of the filters collection (where filters is an object with no data)
			//then weed out mac/ie5 by testing first the existence of the alpha object (to prevent errors in win/ie5.0)
			//then the returned value type, which should be a number, but in mac/ie5 is an empty string
			ixf.type = (ixf.obj.filters.length > 0 && typeof ixf.obj.filters.alpha == 'object' && typeof ixf.obj.filters.alpha.opacity == 'number') ? 'ie' : 'none';
		}
		else
		{
			ixf.type = 'none';
		}
		
		//change the image alt text if defined
		if(typeof arguments[2] != 'undefined' && arguments[2] != '')
		{
			ixf.obj.alt = arguments[2];
		}
		
		//if any kind of opacity is supported
		if(ixf.type != 'none')
		{
			//create a new image object and append it to body
			//detecting support for namespaced element creation, in case we're in the XML DOM
			//ixf.newimg = document.getElementsByTagName('body')[0].appendChild((typeof document.createElementNS != 'undefined') ? document.createElementNS('http://www.w3.org/1999/xhtml', 'img') : document.createElement('img'));
			ixf.newimg = document.getElementById('slideshow').appendChild((typeof document.createElementNS != 'undefined') ? document.createElementNS('http://www.w3.org/1999/xhtml', 'img') : document.createElement('img'));

			//set positioning classname
			ixf.newimg.className = 'idupe';
			
			//set src to next image src
			ixf.newimg.src = ixf.cache[image_index++%ixf.imgsLen].src

			//move it to superimpose original image
			ixf.newimg.style.left = ixf.getRealPosition(ixf.obj, 'x') + 'px';
			ixf.newimg.style.top = ixf.getRealPosition(ixf.obj, 'y') + 'px';
			
			//copy and convert fade duration argument 
			ixf.length = parseInt(arguments[1], 10) * 1000;
			
			//create fade resolution argument as 20 steps per transition
			ixf.resolution = parseInt(arguments[1], 10) * 20;
			
			//start the timer
			ixf.clock = setInterval('ixf.crossfade()', ixf.length/ixf.resolution);
		}
		
		//otherwise if opacity is not supported
		else
		{
			//just do the image swap
			ixf.obj.src = ixf.src;
		}
		
	}
};


//crossfade timer function
ixf.crossfade = function()
{
	//decrease the counter on a linear scale
	ixf.count -= (1 / ixf.resolution);
	
	//if the counter has reached the bottom
	if(ixf.count < (1 / ixf.resolution))
	{
		//clear the timer
		clearInterval(ixf.clock);
		ixf.clock = null;
		
		//reset the counter
		ixf.count = 1;
		
		//set the original image to the src of the new image
		ixf.obj.src = ixf.src;
	}
	
	//set new opacity value on both elements
	//using whatever method is supported
	switch(ixf.type)
	{
		case 'ie' :
			ixf.obj.filters.alpha.opacity = ixf.count * 100;
			ixf.newimg.filters.alpha.opacity = (1 - ixf.count) * 100;
			break;
			
		case 'khtml' :
			ixf.obj.style.KhtmlOpacity = ixf.count;
			ixf.newimg.style.KhtmlOpacity = (1 - ixf.count);
			break;
			
		case 'moz' : 
			//restrict max opacity to prevent a visual popping effect in firefox
			ixf.obj.style.MozOpacity = (ixf.count == 1 ? 0.9999999 : ixf.count);
			ixf.newimg.style.MozOpacity = (1 - ixf.count);
			break;
			
		default : 
			//restrict max opacity to prevent a visual popping effect in firefox
			ixf.obj.style.opacity = (ixf.count == 1 ? 0.9999999 : ixf.count);
			ixf.newimg.style.opacity = (1 - ixf.count);
	}
	
	//now that we've gone through one fade iteration 
	//we can show the image that's fading in
	ixf.newimg.style.visibility = 'visible';
	
	//keep new image in position with original image
	//in case text size changes mid transition or something
	ixf.newimg.style.left = ixf.getRealPosition(ixf.obj, 'x') + 'px';
	ixf.newimg.style.top = ixf.getRealPosition(ixf.obj, 'y') + 'px';
	
	//if the counter is at the top, which is just after the timer has finished
	if(ixf.count == 1)
	{
		//remove the duplicate image
		ixf.newimg.parentNode.removeChild(ixf.newimg);
	}
};



//get real position method
ixf.getRealPosition = function()
{
	this.pos = (arguments[1] == 'x') ? arguments[0].offsetLeft : arguments[0].offsetTop;
	this.tmp = arguments[0].offsetParent;
	while(this.tmp != null)
	{
		this.pos += (arguments[1] == 'x') ? this.tmp.offsetLeft : this.tmp.offsetTop;
		this.tmp = this.tmp.offsetParent;
	}
	
	return this.pos;
};


// pXML points to a nodetree (the data payload of the message received from the server) from which we can
// extract all the data needed to build up the slideshow and kick it off
// pInterval is the delay between image transitions (specified in seconds)
run_slideshow = function( pBaseNode, pXML, pInterval )
{
    D.debugStartFunction("run_slideshow", arguments);

	// from the base node for this slideshow, i.e. pBaseNode, find out what its height and width styling attributes are
	// (IMGmaxHeight and IMGmaxWidth) since we will want to ensure that all thumbnails requested fit within these dimensions.
	D.debug( "pBaseNode = " + pBaseNode );
	D.debug( "pBaseNode.style = " + pBaseNode.style );
	IMGmaxHeight = pBaseNode.style.height.substr( 0, 3);
	IMGmaxWidth = pBaseNode.style.width.substr( 0, 3);
	D.debug( "Slideshow height = " + IMGmaxHeight + ", width = " + IMGmaxWidth );
	
	
	// fill up ixf.imgs array with the images referred to in the filelist nodetree passed in via pXML
	// Get the relative pathname
	relative_pathname = pXML.getElementsByTagName('dir');
	// relative_pathname[0].firstChild.nodeValue contains what we want
	
	images_in_slideshow = pXML.getElementsByTagName('filename');
	image_height = pXML.getElementsByTagName('height');
	image_width = pXML.getElementsByTagName('width');
	ixf.imgsLen = images_in_slideshow.length;
	ixf.imgs = new Array;
	for (var j=0; j<ixf.imgsLen; j++)
	{
        // Need to calculate Thumbnail dimensions so that thumbnail will fit within an IMG tag of IMGmaxHeight X IMGmaxWidth
        // Compare scaling factor for width and height and take smaller factor (greatest reduction) to ensure both dimensions
        // fit.
        
        var heightScale = IMGmaxHeight / image_height[j].firstChild.nodeValue;
        var widthScale = IMGmaxWidth / image_width[j].firstChild.nodeValue;
        
        scale = Math.min(heightScale, widthScale);
        var IMGheight = Math.floor(scale * image_height[j].firstChild.nodeValue + 0.5);
        var IMGwidth = Math.floor(scale * image_width[j].firstChild.nodeValue+ 0.5);

		ixf.imgs[j] = "./architecture/phpthumb/phpThumb.php?w=" + IMGwidth + "&h=" + IMGheight + "&src=../../" + relative_pathname[0].firstChild.nodeValue + "/" + images_in_slideshow[j].firstChild.nodeValue;
		D.debug( "image " + j + " URL is " + ixf.imgs[j] );
	}

	// pre-fetch (cache) the images
	ixf.cache = [];
	ixf.imgsLen = ixf.imgs.length;
	for(var i=0; i<ixf.imgsLen; i++)
	{
		ixf.cache[i] = new Image;
		ixf.cache[i].src = ixf.imgs[i];
	}
	
	// create <img id="slide_photo" src="one of the images" />
	slideshow_image_node = document.createElement('img');
	slideshow_image_node.setAttribute( "id", "slide_photo" );
	slideshow_image_node.setAttribute( "src", ixf.imgs[ixf.imgsLen-1] );

	// dynamically add this img node, and then apply the slideshow to this node
	pBaseNode.appendChild( slideshow_image_node );
	
	// invoke the transition function repeatedly
	// this is done simply having the transition function (i.e. crossfade) triggered by a timer
	// Note that the node passed in to the transition function is currently obtained by a
	// document-wide getElement call (document.getElementById('slide_photo')), but should probably
	// be as simple as passing in the node appended to the base node above, perhaps by
	// pBaseNode.getElementById('slide_photo') [note:not valid JS] or even simply slideshow_image_node
	clock = setInterval("crossfade(slideshow_image_node, '1.5', 'Slideshow');", pInterval * 1000);
	
    D.debugEndFunction();        
}