var ornamentIDs = new Array();	// array of ornament IDs
var totalOrnaments = 0;			// total number of Ornaments on this tree
var lastLoadedSlide = 0;		// highest number slide loaded
var slideHolderPos = 100;		// initalize slide holder position
var scrollTimer;				// scroll timer handle;
var scrollAmount = 100;			// amount to scroll
var scrollDelay = 100;			// how often to scroll (ms)
var scrollCount = 0;			// counts the number of times doScroll is involked to create an accelleration effect
var scrollCountMax = 20;		// number of steps to create the accelleration over
var gettingSlides = false;		// flag for getting ornaments
var fetchSize = 8;				// number of ornaments to get per fetch
var httpDone = true;			// making http request flag
var requests = new Array();		// array for queueing requests
var nextRequest = 0;			// next request to make from queue
var nextFreeRequest = 0;		// next available space in queue
var slideShowIndex = -1;			// position in slideshow
var slideShowTimer = 0;			// slideshow timer handle
var slideShowInterval = 3000;	// initial slideshow speed
var autoScrollStart = 0;		// auto scroll starting position
var autoScrollEnd = 0;			// auto scroll ending position
var autoScrollSmInc = 0;		// auto scroll small increment
var autoScrollSteps = 0;		// number of steps in auto scroll sequence
var autoScrollCurStep = 0;		// current step in auto scroll sequence

var xmlhttp=false;
if (navigator.userAgent.indexOf("msie")) {
	 try {
	  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	 } catch (e) {
	  try {
	   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	  } catch (E) {
	   xmlhttp = false;
	  }
	 }
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  xmlhttp = new XMLHttpRequest();
}

function HTTPget(url)					// adds requests to the queue, and execetes the it if the queue is free
{
	requests[nextFreeRequest] = url;	// store to queue
	nextFreeRequest += 1;				// increment pointer to next free request
	//alert(url + "\n" + httpDone + "\n" + nextFreeRequest + "\n" + nextRequest);	// print queue data for debug
	if (httpDone) procHttpQueue();		// no current request, process this one immediately
}

function procHttpQueue()	// makes requests from the queue
{
	if (nextRequest < nextFreeRequest)			// there's at least one request in the queue
	{
		httpDone = false;							// set flag
		xmlhttp.open("GET", requests[nextRequest],true);				// make reuqest
		xmlhttp.onreadystatechange=alertContents;
		xmlhttp.send(null);
		nextRequest += 1;		// increment pointer
	} else {					// queue is empty
		nextRequest = 0;		// reset queue pointers
		nextFreeRequest = 0;	// to conserve memory
	}
}

function alertContents()
{
	var response = new Array();						// set up array to receive responses
	if (xmlhttp.readyState == 4)				// check for request complete
	{
		if (xmlhttp.status == 200)				// check for ok status
		{
			result = xmlhttp.responseText;		// get response
			response = splitAtBr(result); 		// split result at first \n
			switch (response[0])				// get the response type and handle it
			{
				case "ornamentIDs":
					procOrnamentIDs(response[1]);	// send to ornament list handler
					break;
				case "ornamentSlides":
					procOrnamentSlides(response[1]);	// send to ornament slide handler
					break;
				case "treeList":
					procTrees(response[1]);	// send to ornament slide handler
					break;
				default:
					alert("Unknown response received\n" + result);	// something went wrong
			}
		} else {
			alert('There was a problem with the request.\n' + xmlhttp.status);
		}
		httpDone = true;		// reset flag
		procHttpQueue();		// check the queue for more requests
	}
}

function loadPage()
{
	new_delay(3);				// set initial slideshow delay
	getTrees();					// get initial set of trees
	getOrnamentIDs(2, "", "");	// get list of ornaments
}

function getOrnamentIDs(treeID, locName, locDesc) // loads a list of ornament IDs
{
	HTTPget('scripts/getOrnamentIDs.php?id=' + treeID);	// get list of IDs
	dLocName.innerHTML = "<b>Name:</b> " + unescape(locName);
	dLocDescription.innerHTML = "<b>Description:</b> " + unescape(locDesc);
	totalOrnaments = 0;		// reset slide counters
	lastLoadedSlide = 0;
	document.forms.search.terms.value = "Search";
	stopSlideshow();
}

function procOrnamentIDs(list)	// process received ornament IDs
{
	ornamentIDs = list.split(",");	// make into an array
	allSlides.innerHTML = "";		// clear existing list
	totalOrnaments = ornamentIDs.length	// store totol number of ornaments
	allOrnamentsLoaded = false;		// reset flag
	slideHolderPos = 100;			// reset slide holder position
	allSlides.style.left = slideHolderPos;	// move element
	getOrnamentSlides(0);	// load initial ornaments
	slideShowIndex = -1;		// reset slideshow
}

function getOrnamentSlides(start)		// process received ornament slides
{
	var requestString = "";						// initalize request string
	var endIndex = lastLoadedSlide + fetchSize;
	if (endIndex > totalOrnaments) endIndex = totalOrnaments; // upper limit check
	if (start != endIndex)							// we're not out of ornaments
	{
		for (var i = start; i < endIndex; i++)		// loop through values
			requestString += ornamentIDs[i]+",";	// add id to string
		HTTPget('scripts/getSlides.php?id='+requestString);		// request slides
		gettingSlides = true;		// set flag
	} else {						// out of ornaments
		allOrnamentsLoaded = true;	// set flag
	}	
}

function procOrnamentSlides(slideStr)	// puts received ornament slides in the slide list
{
	response = new Array();				// array to handle parsed response
	response = splitAtBr(slideStr);		// split into count and html
	allSlides.innerHTML += response[1];		// add to the already existing slides
	lastLoadedSlide = lastLoadedSlide*1 + response[0]*1;	// update total ornament counter
	gettingSlides = false;				// reset flag
}


function getTrees() // loads a list of trees
{
	HTTPget('scripts/getTrees.php');	// get list of IDs
}

function procTrees(response)	// puts the list of trees on the page
{
	treeList.innerHTML = response;	// write to list
}

function scroll(dir)	// handle scrolling timers on user click
{
	switch (dir)
	{
		case -1:
		case 1:
			scrollCount = 0;	// reset accelleration counter
			doScroll(dir);	// scroll immediately for user response
			scrollTimer = setInterval("doScroll("+dir+")", scrollDelay);	// left or right, set timer
			break;
		default:
			clearInterval(scrollTimer);
	}
	stopSlideshow();
}

function doScroll(dir)	// scroll the slides on an interval
{
	var scale;		// scale of full step for acceleration
	if (scrollCount < scrollCountMax) scrollCount++;	// calculate accelleration
	scale = scrollCount / scrollCountMax;				// calculate scale factor for accelleration
	slideHolderPos += Math.round(scrollAmount * scale) * dir;	// calculate new position
	slideHolderPos = checkScrollLimits(slideHolderPos);	// check scrolling limits
	allSlides.style.left = Math.round(slideHolderPos);	// move element
	
	checkPreFetch();	// see if we need more ornaments
}

function splitAtBr(string)
{
	lineBr = string.indexOf("\n");		// find first line break
	responseType = string.substr(0,lineBr);	// get response type (before \n)
	responseValue = string.substr(lineBr+1);	// get the rest of the response to pass to function
	
	return Array(responseType, responseValue);	// return as an array
}

function loadImage(img, width, height, locname, locdesc, name, desc, year, id)		// put an ornament in the main image
{
	document.images.mainimage.src = img;
	document.images.mainimage.width = width;
	document.images.mainimage.height = height;
	dName.innerHTML = unescape(name);
	if (year != "") dName.innerHTML += " (" + unescape(year) + ")";	// add year when it's provided
	dDescription.innerHTML = unescape(desc);
	dLocName.innerHTML = "<b>Name:</b> " + unescape(locname);
	dLocDescription.innerHTML = "<b>Description:</b> " + unescape(locdesc);
	slideShowIndex =  findSlide(id);
}

function searchOrnaments(terms)
{
	HTTPget('scripts/getSearchIDs.php?s=' + document.forms.search.terms.value);
	totalOrnaments = 0;		// reset slide counters
	lastLoadedSlide = 0;
	stopSlideshow();
}

function stopSlideshow()
{
	clearTimeout(slideShowTimer);	// setup slideshow
}

function startSlideshow()
{
	slideShowIndex++;	// increment counter
	if (slideShowIndex >= lastLoadedSlide) slideShowIndex = 0;	// wrap to begining of slideshow
	slideInfo = getSlideInfo(ornamentIDs[slideShowIndex]);		// get the slide info
	
	slideShowTimer = setTimeout("startSlideshow()", slideShowInterval);
}

function getSlideInfo(id)
{
	slide = document.getElementById("slide" + id);	// get slide element
	slideContent = slide.innerHTML;					// read html
	
	startIndex = slideContent.indexOf("loadImage(");		// find start of javascript
	endIndex = slideContent.indexOf("); return false;");	// find end of javascript
	loadCmd = slideContent.substr(startIndex, endIndex - 24);	// read whole command	
	
	eval(loadCmd);			// call javascript in div tag to load image
	startAutoScroll(id);	// scroll to that image in the slide holder
	return true;
}

function startAutoScroll(endSlide)
{
	autoScrollCurStep = 0;							// reset counter
	endSlideIndex = findSlide(endSlide);			// get index of ending slide
	autoScrollStart = slideHolderPos;				// store starting position
	autoScrollEnd = 415-(endSlideIndex)*170;		// calculate end position
	autoScrollEnd = checkScrollLimits(autoScrollEnd);	// check scrolling limits

	autoScrollSteps = Math.round((slideShowInterval/3)/scrollDelay);	// number of steps in scroll sequence
	halfSteps = Math.round(autoScrollSteps /2);	// half the number of steps in the scroll sequence
	totalSmallSteps = (halfSteps*(halfSteps-1))/2+halfSteps;	// total number of half steps that will be scrolled
	autoScrollSmInc = (autoScrollEnd - autoScrollStart)/totalSmallSteps/2;	// smallest increment to scroll by
	
	setTimeout("doAutoScroll()", scrollDelay);	// set up timer

}

function doAutoScroll()
{
	autoScrollCurStep++;					// increment counter
	if (autoScrollCurStep < (autoScrollSteps / 2))		// less than half way through
	{
		slideHolderPos += autoScrollCurStep * autoScrollSmInc;	// change position by increasing size
	} else {	// more than half way through
		slideHolderPos += (autoScrollSteps - autoScrollCurStep +1) * autoScrollSmInc;	// change position by decreasing size
	}
	//if (autoScrollCurStep == (autoScrollSteps)) slideHolderPos = autoScrollEnd;	// force end position to correct for rounding errors
	
	slideHolderPos = checkScrollLimits(slideHolderPos);	// check limits	
	allSlides.style.left = Math.round(slideHolderPos);	// move element
	
	if (autoScrollCurStep < (autoScrollSteps)) setTimeout("doAutoScroll()", scrollDelay);	// set up timer again
	
	checkPreFetch();	// see if we need more ornaments
}

function findSlide(slideID)
{
	for (var i = 0; i <= totalOrnaments; i++)
		if (ornamentIDs[i] == slideID) return i;	// found it, return value and end loop
	return 0;	// nothing found, default to the first ornament
}

function checkPreFetch()
{
	if ((slideHolderPos + lastLoadedSlide * 170 < 860 + 170 * 3) && !gettingSlides && !allOrnamentsLoaded)	// if we're near the right edge (within 3 slides) and don't have a request already and aren't done getting ornaments
	getOrnamentSlides(lastLoadedSlide);
}

function checkScrollLimits(pos)
{
	if (pos > 100) pos = 100;	// check limits
	if (pos + lastLoadedSlide * 170 < 860) pos = -(lastLoadedSlide * 170) + 860;
	return pos;	// return updated limit, or original if ok
}

function new_delay(delay) {
	slideShowInterval = delay*1000;
	delay1.innerHTML = hilight_selection(1,delay,'1');
	delay3.innerHTML = hilight_selection(3,delay,'3');
	delay5.innerHTML = hilight_selection(5,delay,'5');
	delay10.innerHTML = hilight_selection(10,delay,'10');
	delay30.innerHTML = hilight_selection(30,delay,'30');
}

function hilight_selection(test, value, text)
{
	return (test == value) ? "<span style='background: #003000; color: #FFFFFF; padding-right: 4px; padding-left: 4px;'>" + text + "</span>" : "<span style='padding-left: 4px; padding-right: 4px;'>" + text + "</span>";
}

