// screen variables
var screenWidth;
var screenHeight;
// current image var
var curImage
var curTitle;
var curDate;
var curDesc;
// new image variables
var newImage;
var newTitle;
var newDesc;
var newDate;
//ajax item
var imageCall;
// Image counter
var imageId = 1;
//fade counter
var fadeOutStart = 1;
var time_per_image = 3000;
//var image_base = "/slideshow/photos/";
var fading = 0;
//timeouts
var fadeCtrl;
var imagecontroler;
var fadeR;
// title bar
var TITLE;
var leftTitle;
var loaded = false;
var CLOSE;
//resize
var stop = 0;
//set hide var
var startPos = 0;
var endPos = -61;
//gallery open
var gallOpen;
var gallId;
var GalleryId = 0;
// MUSIC
var musicBox;
var MUSIC;
//onload items
var onloadTimer;
var onloadSet = 0;
//loaditng text
var loadingText = document.getElementById("loading_text");
var galleryChanging = 0;
var unique = 0;

IEfixHeight = getHeight();
IEfixWidth = getWidth();

function resizeWin(){
	//set stop = 1
	stop = 1;
	//set loader center

	//Kill Ajax
	if(imageCall){
		imageCall.abort();
	}
	
	loadingTable = document.getElementById("LOADERS");
	bottom = (getHeight()- 80) /2 ;
	if(loadingTable){
		loadingTable.style.bottom = bottom + "px";
	}
	
	//Get Images
	img1 = document.getElementById("current");
	img2 = document.getElementById("next");
	//get current image to load
	if(img1){
		imageId = img1.name;}
	//remove on load
	if(img1){
		img1.removeAttribute("onload");	}
	//remove on load
	if(img2){
		img2.removeAttribute("onload");	}
	//Clear fade ctrlTimeout
	if(fadeCtrl){
		clearTimeout(fadeCtrl);}	
	//clear imagecontrol timeout
	if(imagecontroler){
		clearTimeout(imagecontroler);}
	// clear fadeR timeout
	if(fadeR){
		clearTimeout(fadeR);}
	//clear data
	curImage = "";
	curTitle = "";
	curDate = "";
	curDesc = "";
	// new image variables
	newImage = "";
	newTitle = "";
	newDesc = "";
	newDate = "";
	// URL
	URL = "";
	
	//get body
	bodyz = document.getElementsByTagName("body")[0];
	
	
	//remove galleries menu
	gallBox = document.getElementById("galleries");
	gallText = document.getElementById("gallContent")
	gallClose = document.getElementById("gallClose");
	gallNext = document.getElementById("gallNext");
	gallLast = document.getElementById("gallLast");
	var loader = document.getElementById("gallLoader");
	if(loader){
	body.removeChild(loader);}
	//remove galleries menu	
	if(gallNext){	
	bodyz.removeChild(gallNext);}
	if(gallLast){
	bodyz.removeChild(gallLast);}
	if(gallBox){
	bodyz.removeChild(gallBox);}
	if(gallText){
	bodyz.removeChild(gallText);}
	if(gallClose){
	bodyz.removeChild(gallClose);}
	//Say its closed
	if(gallOpen){
		gallOpen = false;
	}
	
	CLICKS = 1;
	

// REMOVE IMAGES FROM PAGE

		

	//remove images method 1
	if(img1){
		document.body.removeChild(img1);
	}
	if(img2){
		document.body.removeChild(img2);
	}
		
	//Remove images method 2
	//get all images
	images = document.getElementsByTagName("img");
	//remove them
	for(i=0; i < images.length; i++){
		if(images[i]){
			 images[i].parentNode.removeChild(images[i]);
		}
	}



	//NO IMAGES IN GALLERY BOX
	no_image = document.getElementById("no_images");
	if(no_image){
		document.body.removeChild(no_image);
	}
	
	//title close button
	document.getElementById("close_button").style.display = "none";
	
	//reset gallery page
	gallStartPage = 1;
	//set stop = 0
	stop = 0;
	//start again
	startShow();
	
}



//call resizer
// window.onresize = resizeWin;

function ieResizeFix(){
	
	h = getHeight();
	w = getWidth();
	
	if(h != IEfixHeight || w != IEfixWidth){
		IEfixHeight = h
		IEfixWidth = w;
		resizeWin();
	}
	
	setTimeout("ieResizeFix()", 10);

}



/* -----------------	FIRST RUN --------------------------*/
/* Lets get the ball rolling!*/

function startShow(){
	musicbox = document.getElementById("music");
	MUSIC = "<object width='30' height='30'><param name='movie' value='" + root + "/slideshow/player.swf'></param><embed src='" + root + "/slideshow/player.swf' type='application/x-shockwave-flash' width='30px' height='30px'></embed></object>";
	if(galleryChanging == 1){
		// kill old player
		musicbox.innerHTML = "";
	}
	// start show
	if(stop == 0){
		/* Get the title objects*/
		TITLE = document.getElementById("title");
		leftTitle = document.getElementById("title_text_left");
		CLOSE = document.getElementById("close_button");
		// clear title text
		leftTitle.innerHTML =""
		// get current width
		screenWidth = getWidth();
		// get current screen height
		screenHeight = getHeight();
		// Make ajax item
		imageCall = makeAjaxItem();
		// put data together
		ajaxData = "id=" + imageId + "&width=" + screenWidth + "&height=" + screenHeight + "&galleryid=" + GalleryId; 
		//send ajax request
		sendAjax(imageCall,"POST",root + "/slideshow/includes/images.php", ajaxData);
		if(imageCall){
			imageCall.onreadystatechange = firstSrc;}
		}
}


//return from first run
function firstSrc(){
	if(stop == 0){
		//reset Rcount
		Rcount = 0;
		//get title bar
		titleID = document.getElementById("title");
		// setTiitle bar opacity
		titleID.style.opacity = 0.7;
		titleID.style.filter  = 'alpha(opacity='+ 70 +')'; 
		// php is done
			if(imageCall.readyState == 4){

				//it went ok ;]
				if(imageCall.status == 200){

			
					// store XML response into var
					sendBack = imageCall.responseXML;
					
					
					//get amount of galleries
					var total_galleries = imageId = sendBack.getElementsByTagName("galleries")[0].childNodes[0].nodeValue;
					
					if(parseInt(total_galleries) == 0){
							loadingText. innerHTML = "";
						topPositioning = (getHeight() /2) -30 ;
						leftPositioning = (getWidth()/2) -100 ;
						
						//create
						div = document.createElement("div");
						div.setAttribute("id","no_images");
						// height /  width
						div.style.height = "100px";
						div.style.width = "250px";
						// positioning
						div.style.position = "absolute";
						div.style.top = topPositioning + "px";
						div.style.left = leftPositioning + "px";
						//set s;tyling
						div.style.background = "#000";
						//set content
						div.innerHTML = "There are no galleries available";
						// add it
						document.body.appendChild(div);
						
					}
					
					else{					
					//currentId
					oldId = imageId;
					//get image count
					total_images = imageId = sendBack.getElementsByTagName("total")[0].childNodes[0].nodeValue;
					if(parseInt(total_images) == 0){
						loadingText. innerHTML = "";
						topPositioning = (getHeight() /2) -30 ;
						leftPositioning = (getWidth()/2) -100 ;
						
						//create
						div = document.createElement("div");
						div.setAttribute("id","no_images");
						// height /  width
						div.style.height = "100px";
						div.style.width = "250px";
						// positioning
						div.style.position = "absolute";
						div.style.top = topPositioning + "px";
						div.style.left = leftPositioning + "px";
						//set s;tyling
						div.style.background = "#000";
						//set content
						div.innerHTML = "There are no images this gallery";
						// add it
						document.body.appendChild(div);
						

					}
					else{
					// get new image count
					imageId = sendBack.getElementsByTagName("id")[0].childNodes[0].nodeValue;
					// get new image (image.jpg)
					curImage = sendBack.getElementsByTagName("url")[0].childNodes[0].nodeValue;
					// 	get new images title
					curTitle = 	sendBack.getElementsByTagName("title")[0].childNodes[0].nodeValue;
					// get new images description
					curDesc = sendBack.getElementsByTagName("description")[0].childNodes[0].nodeValue;
					// get browse width
					bWidth = getWidth();
					// get browser height
					bHeight = getHeight();
					// split date from the timestamp
					newDateSplit = sendBack.getElementsByTagName("dateadded")[0].childNodes[0].nodeValue.split(" ");
					// make date english
					sortDate = newDateSplit[0].split("-");
					// store date in var in right order
					curDate = sortDate[2] + "/" + sortDate[1] + "/" + sortDate[0];
					//new height
					curHeight = sendBack.getElementsByTagName("newheight")[0].childNodes[0].nodeValue;
					//new width
					curWidth = sendBack.getElementsByTagName("newwidth")[0].childNodes[0].nodeValue;
					//gallery id
					gallId = sendBack.getElementsByTagName("galleryid")[0].childNodes[0].nodeValue;
					// make new images url
					URL = root + "/slideshow/includes/image.php?width="+ curWidth + "&height=" + curHeight + "&img=" + curImage + "&bwidth=" +bWidth + "&bheight=" + bHeight + "&galleryid=" + gallId + "&r=" + unique+ "&t=" + time;
					
					
					
					//now create img 3 (the new next):
					var img1 = document.createElement("img");
					var img2 = document.createElement("img");
	    			img1.id = 'current'; //set its id
					img2.id = 'next'; // set back id	
					img1.src = URL;
					img1.setAttribute("onload", "showFirstImage(this);");
					//ie7 fix
					img1.onload = showFirstImage;
					//set url
					img2.src = URL;
					//set name as current Id
					// add the images
					document.body.appendChild(img1);
					document.body.appendChild(img2);	
					// set invisible till load
					img1.style.opacity = 0;
					img1.style.filter = 'alpha(opacity='+ (0 * 100) +')';
					img2.style.opacity = 0;
					img2.style.filter = 'alpha(opacity='+ (0 * 100) +')';
					//set image 1's name
					img1.setAttribute("name", oldId);
					//tell it its not loaded
					loaded = false;
						if(galleryChanging == 1){
							// load music
							musicbox.innerHTML = MUSIC;		
							galleryChanging = 0;
						}
					}
					//close no gallery else
					}
				//close if 200	
				}
			
			
			
			
			else{
				imageId++;
				startShow();	
			}
			
			
			//if ready state = 4
	
		}		
	//if stop == 0
	}
	//close function
}



function showFirstImage(item){
		if(stop == 0){
			loadingText.innerHTML = "";
			item = document.getElementById("current");
			item.style.opacity = fadeOutStart;
			item.style.filter = 'alpha(opacity='+ (fadeOutStart * 100) +')'; 
			//set title of current image
			setTitles();
			//start loop
			imageControl();
		}
}


/* ----------------- END FIRST RUN --------------------------*/



/* Looping functions */

function imageControl()
{
	if(stop == 0){
		// get current width
		screenWidth = getWidth();
		// get current screen height
		screenHeight = getHeight();
		// Make ajax item
		imageCall = makeAjaxItem();
		// put data together
		ajaxData = "id=" + imageId + "&width=" + screenWidth + "&height=" + screenHeight + "&galleryid=" + gallId; 
		//send ajax request
		sendAjax(imageCall,"POST",root + "/slideshow/includes/images.php", ajaxData);
		//were loading new image so say its not loaded
		loaded = false;
		// On script return do..
		imageCall.onreadystatechange = updateSrc;
		//check if we should fade?
		fadeControl();
	}
}	


function fadeControl(){
	if(stop == 0){
		//if not resized and the image has loaded
		if(loaded == true){
			// change next calues to current
			curTitle = newTitle;
			curDate = newDate;
			curDesc = newDesc;
			//fade in next image
			imagecontroler = setTimeout("fadeOut('current',50)", time_per_image);}
		else{
			//loop
			fadeCtrl = setTimeout("fadeControl()", 500);
		}
	}
}



// fadeOut function
// fades a layer out. 

function fadeOut(itemID, fadeSpeed) {
	if(stop == 0){

		//Say were fading
		fading = 1;
		// 	Set title box to empty
		leftTitle.innerHTML ="";	
		// remove Close button
		CLOSE.style.display = "none";
		// Start fading
		var theItem = document.getElementById(itemID);	
			theItem.style.opacity = fadeOutStart;
			theItem.style.filter = 'alpha(opacity='+ (fadeOutStart * 100) +')'; 
		// if the fadeout has reached the title opacity
		if(TITLE.style.opacity = (fadeOutStart + 0.1)){
			TITLE.style.opacity = fadeOutStart;
			TITLE.style.filter = 'alpha(opacity='+ (fadeOutStart * 100) +')'; 
		}
		// if the text needs fading
		if(leftTitle.style.opacity = (fadeOutStart + 0.1)){
			leftTitle.style.opacity = fadeOutStart;
			leftTitle.style.filter = 'alpha(opacity='+ (fadeOutStart * 100) +')'; 
		}
	
			
		if (fadeOutStart > 0) {
			fadeOutStart -= 0.1;
			fadeR = setTimeout('fadeOut("'+itemID+'", "'+fadeSpeed+'")', fadeSpeed);
		}
		else {
			//were done fadin
			fading = 0;
			//reset global fadeOutStart for next time:
			fadeOutStart = 1;	
			//set title of current image
			setTitles();	
			//and activate the function to update the ids:
			updateTheIds();
		}
	}
		
}



// updateTheIds function
function updateTheIds() {
	if(stop == 0){
		//img2 is the one that was on top, and has now faded out:
		var img2 = document.getElementById('current');
		document.body.removeChild(img2);
		img2name = img2.name;		
		
		//img1 is the new img2- give it the id, so it takes on the absolute positioning:
		var img1 = document.getElementById('next');
		img1name = img1.name;
		img1.id = 'current';
 	
		//now create img 3 (the new img1):
		var img3 = document.createElement("img");
	    img3.id = 'next'; //give it the id of the back image
	    img3.setAttribute("id","next");
		img3.src = URL;
		img3.setAttribute("name",(img1name + 1));
		document.body.appendChild(img3);
		

		//pause to display the new image for a few seconds, and start the loop over again:
		imageControl();
	}
	
	//nb, still need to handle preloading properly (don't change if next image isn't ready) 
	
	//and this script never stops looping (it appears to because in the end both images are img3.jpg) but we really 
	//need to set it to go back to the beginning, once it reaches the end. 

}



function showImage(){ 
			if(stop == 0){
				//			tell it its loaded
				loaded = true;	
				nextItem = document.getElementById('next');

				if(!nextItem){
					nextItem =nextID;
				}
				
				nextItem.style.opacity = fadeOutStart;
				nextItem.style.filter = 'alpha(opacity='+ (fadeOutStart * 100) +')';
				//clear onload marker
				onloadSet = 0; 
			}
}



/*|_____________________________________
/*|									    |
/*| 		Set title info				|
/*|_____________________________________|*/

function setTitles(){
	if(stop == 0){
		// IF bboth are empty
		if(curTitle == "EMPTY" && curDesc == "EMPTY"){
			//hide it
			TITLE.style.display = "none";
			leftTitle.style.display = "none";
		}
		//if titles set		
		else if (curTitle != "EMPTY" && curDesc == "EMPTY"){
			//reapear
			TITLE.style.display = "inline";
			leftTitle.style.display = "inline";
			CLOSE.style.display = "block";
			TITLE.style.bottom = "0px";
			//setOpacity
			TITLE.style.opacity = 0.7;
			leftTitle.style.opacity = 1;
			TITLE.style.filter = 'alpha(opacity='+ (0.7 * 100) +')'; 
			leftTitle.style.filter = 'alpha(opacity='+ (1 * 100) +')'; 
				// move into view
			leftTitle.style.bottom = "6px";
			
			//set content
			leftTitle.innerHTML = "<h4>" + curTitle + "</h4>";
		}
		
		else if (curTitle == "EMPTY" && curDesc != "EMPTY"){
			//reapear
			TITLE.style.display = "inline";
			leftTitle.style.display = "inline";
			CLOSE.style.display = "block";
			TITLE.style.bottom = "0px";
			//setOpacity
			TITLE.style.opacity = 0.7;
			leftTitle.style.opacity = 1;
			TITLE.style.filter = 'alpha(opacity='+ (0.7 * 100) +')'; 
			leftTitle.style.filter = 'alpha(opacity='+ (1 * 100) +')'; 
			// move into view
			leftTitle.style.bottom = "6px";
			//set content
			leftTitle.innerHTML = "<h4>&nbsp;</h4><span>"  + curDesc + "</span>"; 	
		}
		
		else if (curTitle != "EMPTY" && curDesc != "EMPTY"){
			//reapear
			TITLE.style.display = "inline";
			
			leftTitle.style.display = "inline";
			CLOSE.style.display = "block";
			TITLE.style.bottom = "0px";
			//setOpacity
			TITLE.style.opacity = 0.7;
			leftTitle.style.opacity = 1;
			TITLE.style.filter = 'alpha(opacity='+ (0.7 * 100) +')'; 
			leftTitle.style.filter = 'alpha(opacity='+ (1 * 100) +')'; 
			// move into view
			leftTitle.style.bottom = "6px";
	
			//setcontent
			leftTitle.innerHTML = "<h4>" + curTitle + "</h4><span>" + curDesc +"</span>" ;			
		}
		
		// Set font sizes
		h4 =document.getElementsByTagName("h4")[0];
		if((screenHeight + screenWidth) > 1400){
			leftTitle.style.fontSize = "9pt";
			if(h4){
			h4.fontSize = "10pt";}
		}
		else if((screenHeight + screenWidth) < 476){
				leftTitle.style.fontSize = "6pt";
				if(h4){
					h4.fontSize = "5pt";}
				}
			else{
			leftTitle.style.fontSize = "7pt";
			if(h4){
			h4.fontSize = "8pt";}
		}
	}
}
/* _____________________________________
/*|				Hide titles				|
/*|_____________________________________|*/

function hideTitle(){
		//Clear text
		leftTitle.innerHTML = "";
		CLOSE.style.display = "none";
		 if(TITLE.style.bottom == undefined || TITLE.style.bottom  == ""){
				TITLE.style.bottom = "0px";
				hidet = setTimeout("hideTitle()",10);
			}			
		else{
			//if it is over end pos
			if(parseInt(TITLE.style.bottom.split("px")[0]) > endPos){
				currentPos = parseInt(TITLE.style.bottom.split("px")[0]);
				currentPos -= 4;
				TITLE.style.bottom = currentPos + "px";
				hidet = setTimeout("hideTitle()",20);
		}
   }
}


/* _____________________________________
/*|										|*/
/*|				Ajax returns			|*/
/*|_____________________________________|*/
/* Return from getting next image*/
function updateSrc(){
	if(stop == 0){
		// php is done
		if(imageCall.readyState == 4){
			//it went ok ;]
			if(imageCall.status == 200){

				//incriment unique number
				unique++;
				// store XML response into var
				sendBack = imageCall.responseXML;
				//currentId
				oldId = imageId;
				// get new image count
				imageId = sendBack.getElementsByTagName("id")[0].childNodes[0].nodeValue;
				// get new image (image.jpg)
				newImage = sendBack.getElementsByTagName("url")[0].childNodes[0].nodeValue;
				// get new images title
				newTitle = 	sendBack.getElementsByTagName("title")[0].childNodes[0].nodeValue;
				// get new images description
				newDesc = sendBack.getElementsByTagName("description")[0].childNodes[0].nodeValue;
				// split date from the timestamp
				newDateSplit = sendBack.getElementsByTagName("dateadded")[0].childNodes[0].nodeValue.split(" ");
				// make date english
				sortDate = newDateSplit[0].split("-");
				// store date in var in right order
				newDate = sortDate[2] + "/" + sortDate[1] + "/" + sortDate[0];
				//new height
				newHeight = sendBack.getElementsByTagName("newheight")[0].childNodes[0].nodeValue;
				//new width
				newWidth = sendBack.getElementsByTagName("newwidth")[0].childNodes[0].nodeValue;
				//browserwidth
				bWidth = getWidth();
				//browserheight
				bHeight = getHeight();	
				//gallery id
				gallId = sendBack.getElementsByTagName("galleryid")[0].childNodes[0].nodeValue;
				//make img url
				URL = root + "/slideshow/includes/image.php?width=" + newWidth + "&height=" + newHeight + "&img=" + newImage + "&bwidth=" +bWidth + "&bheight=" + bHeight + "&galleryid=" + gallId + "&r=" + unique + "&t=" + time;
				//set image 1's name
				document.getElementById("next").setAttribute("name", oldId)
								
				//set image
				nextImages =document.getElementById("next");
				nextImages.setAttribute ("src",URL);

				nextImages.setAttribute("onload","showImage()");
				//ie7 fix
				document.getElementById("next").onload = showImage;//(nextImages); //function(){ showImage(nextImages);}	
				
			}
		else{

			imageId++;
			imageControl();	
			}
		}
	}
}





/* _____________________________________
/*|										|*/
/*|			AJAX PARTS 					|*/
/*|_____________________________________|*/


function makeAjaxItem(){
	if(stop == 0){
    	// Mozilla/Safari
    	if (window.XMLHttpRequest) 
    	{
    	    ajaxItem = new XMLHttpRequest();
   		 }
   		 // IE
    
		else if (window.ActiveXObject) 
    	{
    	    ajaxItem = new ActiveXObject("Microsoft.XMLHTTP");
    	}
    	return ajaxItem;
	}
}



//#Send ajax request. Data needed:
//# method (get/post) / script (do.php) / data string
function sendAjax(ajaxItem,method,script,data)
{
	//set sent method to lower so we only need to check if it equals "post" not Post, POST ect.
	action = method.toLowerCase();
	//check if its post or get
	if(action == "post")
	{
		//What to do method/script/asycronus
		ajaxItem.open(method, script,true);
		// header send for post only
		ajaxItem.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		ajaxItem.setRequestHeader("Content-length", data.length);
		ajaxItem.setRequestHeader("Connection", "close");
		//Send the request
		ajaxItem.send(data);
		
	}
	else
	{
	//What to do method/script/asycronus
	ajaxItem.open(method, script + "?" + data,true);
	//Send the request
	ajaxItem.send(null);
	}
}


/*|---------------------------------------|*/
/*|    Function to get screen height      |*/
/*|---------------------------------------|*/

function getHeight()
{
	
	//get heigh and width functions from http://www.webdeveloper.com/forum/showthread.php?t=161412
	if (self.innerHeight) // all except Explorer
	{
		scnHei = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
		// Explorer 6 Strict Mode
	{
		scnHei = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
	
		scnHei = document.document.body.clientHeight;
	}
	
	return scnHei;
}
 
/*|---------------------------------------|*/
/*|    Function to get screen width       |*/
/*|---------------------------------------|*/

function getWidth()
{
	// Get the width of 
	if (self.innerHeight) // all except Explorer
 	{
 		scnWid = self.innerWidth;
 	}
 	else if (document.documentElement && document.documentElement.clientHeight)
 		// Explorer 6 Strict Mode
 	{
 		scnWid = document.documentElement.clientWidth;
 	}
 	else if (document.body) // other Explorers
 	{
 		scnWid = document.document.body.clientWidth;
 	}
 	return scnWid;
}