var imgArray;
var loadedArray = new Array();
var curindex = 0;
var swtch = 1;
var flag = 1;
var paused = 1;
var wait_time = 5000;
window.onload = prep;

function prep(){
	
	if ( document.getElementById('thumbs') ){
		var thumb_box = document.getElementById('thumbs');
		var links = thumb_box.getElementsByTagName("a");
		var link_num = links.length;
		
		if (document.getElementById('play_pause')){
			var pause_button = document.getElementById('play_pause');
			pause_button.onclick = function(){
				return playPause();
			}
		}
		
		for (var x=0; x < link_num; x++){
			links[x].onclick = function(){
				return getIndex(this);
			}
		}	
		
		document.onkeyup = whatKey;
		
		//http://cabin.com/photos/indoor/kitchen/3/
		//http://cabin.com/photos/outdoor/3/
		
		//http://cabin.com/photos.php?cat=indoor&sub=kitchen&img=3
		//http://cabin.com/photos.php?cat=indoor&img=3
		var url = document.URL;
		
		var query_string = url.split("?");
		var variables = query_string[1].split("&");
		var var_num = variables.length;

		for (var x=0; x < var_num; x++){
			if (variables[x].match('cat=') != null){
				var items = variables[x].split('cat=');
				var category = items[1];
			}
			
			if (variables[x].match('sub=') != null){
				var items = variables[x].split('sub=');
				var subcategory = items[1];
			}
		}
		
		if (subcategory === undefined){
			var requestUrl = 'cat='+category+'';
		} else {
			var requestUrl = 'cat='+category+'&sub='+subcategory+'';
		}
		
		var urlitems = url.split("/");
		var domain = urlitems[2];
		if (domain == '127.0.0.1'){
			makeRequest('http://'+domain+'/cabin/xml_images.php?'+requestUrl);
		} else {
			makeRequest('http://'+domain+'/xml_images.php?'+requestUrl+"");
		}
		
		
	}
}

function pause(){
	if (paused == 0){
		clearTimeout(slideshow);
		paused = 1;
		var pause = document.getElementById('play_pause');
		pause.src = 'images/play.jpg';
	}
}

function getIndex(url){
	
	pause();
	
	var docurl = document.URL;
	var urlitems = docurl.split("/");
	var domain = urlitems[2];
	
	if (domain == '127.0.0.1'){
		var removeText = 'http://127.0.0.1/cabin/photos/';
	} else {
		var removeText = 'http://'+domain+'/photos/';
	}
	var cat_info = url.href.replace(removeText, '');
	var items = cat_info.split("/");
	
	if (items.length == 3 ){
		var index = items[1];
	} else {
		var index = items[2];
	}
	
	index = validIndex(index);
	
	changeImg(index);
	return false;
}

function changeImg(index){
	if (index != curindex){
		//URL looks like http://127.0.0.1/cabin/photos/outdoor/1/
		//or http://127.0.0.1/cabin/photos/indoor/kitchen/1/
		try {
			var name = imgArray[index].firstChild.data;
			var picholder = document.getElementById('img_holder');
		} catch (err){
			alert(err);
		}
		try {
			if (flag == 1){
				flag = 0;
				if (loadedArray[index] == false){
					showLoader();
				}
				if (swtch == 1){
					var newimg = new Image();
					newimg.onload = function(){	
						var pic = document.createElement("img");
						pic.setAttribute("id", "slide2");
						pic.setAttribute("src", "images/photos/"+name+"");
						pic.setAttribute("alt", "");
						setOpacity(pic, 0);
						picholder.appendChild(pic);
						fadein("slide2", 0);
						fadeout("slide", 100);
						hideLoader();
					}
					newimg.src = "images/photos/"+name+"";
					swtch = 2;	
				} else {
					var newimg2 = new Image();
					newimg2.onload = function(){	
						var pic2 = document.createElement("img");
						pic2.setAttribute("id", "slide");
						pic2.setAttribute("src", "images/photos/"+name+"");
						pic2.setAttribute("alt", "");
						setOpacity(pic2, 0);
						picholder.appendChild(pic2);
						fadein("slide", 0);
						fadeout("slide2", 100);
						hideLoader();
					}
					newimg2.src = "images/photos/"+name+"";
					swtch = 1;	
					
				}
				curindex = index;
				loadedArray[index] = true;
				updateCounter(curindex);
				updateNav(curindex);
				///
				curindex = curindex*1;
				var next = validIndex(curindex + 1);
				if (paused == 0){
					slideshow = setTimeout("changeImg("+next+")", wait_time);
				}		
				//
			}
		} catch (err){
			alert(err);
			return false;
		}
	}
	return false;
	
}

function validIndex(index) {
	var img_num = imgArray.length;
	if (index < 0){
		index = img_num - 1;
	} else if (index >= img_num) {
		index = 0;
	}
	
	return index;
}

function showLoader(){
	
	
	var img_holder = document.getElementById('img_holder');
	
	var para = document.createElement('p');
	para.setAttribute('id', 'loading');
	
	var gif = new Image();
	gif.onload = function(){	
		var pic = document.createElement("img");
		pic.setAttribute("src", "images/load2.gif");
		pic.setAttribute("alt", "");
		para.appendChild( document.createTextNode('Loading') );
		para.appendChild( img_holder.appendChild(document.createElement('br')) );
		para.appendChild(pic);
	}
	gif.src = "images/load2.gif";
	img_holder.appendChild(para);
}

function hideLoader(){
	if ( document.getElementById('loading') ){
		var loader = document.getElementById('loading');
		loader.parentNode.removeChild(loader);
	}
}

function changeCaption(index)
{
	var cap_holder = document.getElementById('img_caption');
	removeChildren(cap_holder);
	if (captionArray[index].firstChild){
		var caption = document.createTextNode(captionArray[index].firstChild.data);
		cap_holder.appendChild(caption);
	} else {
		var caption = '';
	}
	
}

function removeChildren(obj){
	while (obj.childNodes.length >= 1){
		obj.removeChild(obj.firstChild);
	}
}

function updateCounter(number){
	var thumbs = document.getElementById('thumbs');
	var counters = thumbs.getElementsByTagName('a');
	var slide_num = counters.length;
	
	var counterArray = new Array();
	
	for (var n=0; n < slide_num; n++){
		if (counters[n].className == 'slide_link' || counters[n].className == 'current') {
			counterArray.push(counters[n]);
		}
	}
	
	counter_num = counterArray.length;

	for (var n=0; n < counter_num; n++){
		
		if (n == number){
			counterArray[n].className = 'current';
		} else {
			counterArray[n].className = 'slide_link';
		}
		
	}
}



function makeRequest(url) {
	var http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
			// See note below about this line
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		unLink();
		return false;
	}
	http_request.onreadystatechange = function() { alertContents(http_request); };
	http_request.open('GET', url, true);
	http_request.send(null);

}

function alertContents(http_request) {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var xmldoc = http_request.responseXML;
			imgArray = xmldoc.getElementsByTagName('image');
			
			//Reset all images 'loaded' status to false
			var img_count = imgArray.length
			for (var x=0; x < img_count; x++){
				loadedArray[x] = false;
			}
			
			captionArray = xmldoc.getElementsByTagName('caption');
			/*alert(imgArray[0].firstChild.data);*/
		} else {
			alert('There was a problem with the request.');
		}
	}

}

function setOpacity(obj, opacity) {
	opacity = (opacity == 100)?99.999:opacity;
	// IE/Win
	obj.style.filter = "alpha(opacity:"+opacity+")";
	// Safari<1.2, Konqueror
	obj.style.KHTMLOpacity = opacity/100;
	// Older Mozilla and Firefox
	obj.style.MozOpacity = opacity/100;
	// Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity/100;
}

function fadein(objId,opacity) {
	if (document.getElementById) {
		obj = document.getElementById(objId);
		
		if (opacity == 0){
			obj.style.visibility = "visible";
		}
		
		if (opacity <= 100) {
			setOpacity(obj, opacity);
			opacity += 10;
			window.setTimeout("fadein('"+objId+"',"+opacity+")", 50);
		} else if (opacity > 100){
			flag = 1;
		}
	}
}

function fadeout(objId,opacity) {
	if (document.getElementById) {
		obj = document.getElementById(objId);
		if (opacity == 0){
			obj.style.visibility = "hidden";
			var picholder = document.getElementById('img_holder');	
			var trash = picholder.getElementsByTagName("img");
			for (var d=0; d<trash.length; d++){
				if (trash[d].getAttribute('id') == objId){
					picholder.removeChild(trash[d]);
				}
			}
			changeCaption(curindex);
		}
		
		if (opacity >= 0) {
			setOpacity(obj, opacity);
			opacity = opacity - 10;
			window.setTimeout("fadeout('"+objId+"',"+opacity+")", 50);
		}
	}
}

function whatKey(e){
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	
	keycode = parseInt(keycode);

	//left arrow: 37 right arrow: 39
	if (keycode == 37 || keycode == 39){
		if (keycode == 37){
			var index = curindex-1;
		} else if (keycode == 39){
			var index = curindex+1;
		}
		
		var img_num = imgArray.length;
		if (index < 0){
			index = img_num - 1;
		} else if (index >= img_num) {
			index = 0;
		}
		
		pause();
		changeImg(index);
	}
}

function playPause()
{
	if (paused == 0){
		clearTimeout(slideshow);
		paused = 1;
	} else {
		var next = validIndex(curindex+1);
		slideshow = window.setTimeout("changeImg("+next+")", 100);
		paused = 0;
	}
	pauseImg();
}

function pauseImg(){
	var pause = document.getElementById('play_pause');
	if (paused == 1){
		pause.src = 'images/play.jpg';
	} else {
		pause.src = 'images/pause.jpg';
	}
}

function updateNav(number){
	
	var plus = document.getElementById('next');
	var minus = document.getElementById('prev');
	
	var theindex = number*1;
	var next;
	var prev;
	
	var img_num = imgArray.length;
	
	if (theindex >= img_num-1){
		next = 0;
		prev = theindex-1;
	}  else if (theindex <= 0){
		next = theindex+1;
		prev = img_num-1;
	} else {
		next = theindex+1;
		prev = theindex-1;
	}
	
	//photos/outdoor/1/ or photos/outdoor/backyard/1/
	var hrf = plus.getAttribute("href");
	var items = hrf.split('/');
	if (items.length == 4){
		var nexthref = items[0]+'/'+items[1]+'/'+next+'/';
		var prevhref = items[0]+'/'+items[1]+'/'+prev+'/';
	} else {
		var nexthref = items[0]+'/'+items[1]+'/'+items[2]+'/'+next+'/';
		var prevhref = items[0]+'/'+items[1]+'/'+items[2]+'/'+prev+'/';
	}
	
	plus.setAttribute("href", nexthref); 
	minus.setAttribute("href", prevhref);
}