var request;
var thisYear;
var selectedYear;
var currentCaption = 0;
var isIE = 0;
var currentEventSet;
var nextPhoto;
var timerID;
var tempImage;

function initPage(eventId, imageNo)
{
	var today = new Date();
	thisYear = today.getYear();

	if (navigator.appName == "Microsoft Internet Explorer" )
	{
		isIE = 1;
	}

	if(window.XMLHttpRequest){		
		request = new XMLHttpRequest();	
		eventRequest = new XMLHttpRequest();	
		yearRequest = new XMLHttpRequest();	
	}
	else if (window.ActiveXObject){
		yearRequest = new ActiveXObject("Microsoft.XMLHTTP");
		eventRequest = new ActiveXObject("Microsoft.XMLHTTP");
		request = new ActiveXObject("Microsoft.XMLHTTP");
	}

	if (thisYear < 1000)	// some browsers return 2007 as 107!
	{
		thisYear += 1900;
	}

	setYear(thisYear);
	
	if (eventId != -1)
	{
		loadEventImages(eventId);
	
		if (imageNo != -1)
		{
			showPhoto(eventId,imageNo);
		}	
	}
}

function loadYearImages(year)
{		
	yearRequest.open('GET', 'XMLEventsByYear.php?year=' + year, true);

	yearRequest.onreadystatechange = processEventsByYear;	
	yearRequest.send('');
}

function processEventsByYear(){

	switch(yearRequest.readyState)	{
		case 1:	// loading
			
			break;
		case 4:	//ready

			var text = '';

			var xmlDoc = yearRequest.responseXML.documentElement;

			if (xmlDoc != null)
			{
				var events = xmlDoc.getElementsByTagName("event");		

				if (events != null)
				{			
					for (i=0; i< events.length;i++ )
					{

						var title = events[i].childNodes[0].firstChild.nodeValue;
						var eventId = events[i].childNodes[1].firstChild.nodeValue;
						var thumbUrl = events[i].childNodes[2].firstChild.nodeValue;
						var thumbWidth = events[i].childNodes[2].getAttribute("width");
						var thumbHeight = events[i].childNodes[2].getAttribute("height");
						var date = events[i].childNodes[3].firstChild.nodeValue;

						text = text + '<div id="imageContainer" style="width: '+thumbWidth+'px ;height: '+thumbHeight+'px;"><a href="javascript:loadEventImages(' + eventId + ')">';												
						text = text + '<img id="imgEvt' + eventId + '" width="' + thumbWidth + '" height="' + thumbHeight + '" class="thumbnail" src="' + thumbUrl + '" alt="" onMouseOver="showCaption(\'imgEvt' + eventId + '\')" />';
						text = text + '<div id="imgEvt' + eventId + 'C" class="imageCaption" style=";width: '+thumbWidth+'px ;height: '+thumbHeight+'px;display:none" onMouseOut="hideCaption(\'imgEvt' + eventId + '\')">' + title + '<br\><br\>' + date;
						text = text + '</div></a></div>';						
					}
				}
			}

			document.getElementById('eventImages').innerHTML = text;
			document.getElementById('year').innerHTML = selectedYear;

			break;
	}
}

function loadEventImages(eventId)
{

	document.getElementById('eventTitle').innerHTML = 'Loading...'; 
	document.getElementById('eventDate').innerHTML = '...please wait';
	document.getElementById('eventDownloadLink').href = 'photoEventDownload.php?event_id=' + eventId;

	eventRequest.open('GET', 'XMLPhotosByEvent.php?event_id=' + eventId, true);

	eventRequest.onreadystatechange = processPhotosByEvent;	
	eventRequest.send('');
}


function processPhotosByEvent()
{
	switch(eventRequest.readyState)	{
		case 1:	// loading
			
			break;
		case 4:	//ready

			var text = '';

			var xmlDoc = eventRequest.responseXML.documentElement;

			if (xmlDoc != null)
			{				
				var photos = xmlDoc.getElementsByTagName("photo");		
				var event = xmlDoc.getElementsByTagName("eventDetails");				

				if (event != null)
				{
					var eventId = event[0].childNodes[2].firstChild.nodeValue;

					if (photos != null)
					{			
						for (i=0; i< photos.length;i++ )
						{						

							var photoId = photos[i].childNodes[1].firstChild.nodeValue;
							var thumbUrl = photos[i].childNodes[3].firstChild.nodeValue;
							var thumbWidth = photos[i].childNodes[3].getAttribute("width");
							var thumbHeight = photos[i].childNodes[3].getAttribute("height");

							text = text + '<div style="float:left;width:150px;height:150px;background:#white; border:5px solid white;overflow:hidden">';
							text = text + '<a href="javascript:showPhoto('+ eventId +',' + i +')">';
							text = text + '<img id="thumb-' + eventId + '-' + i + '" class="grid-thumb" width="' + thumbWidth + '" height="' + thumbHeight + '" src="' + thumbUrl + '" /></a>';
							text = text + '</div>';
						}
					}
				
					document.getElementById('eventTitle').innerHTML = event[0].childNodes[0].firstChild.nodeValue;
					
					if (event[0].childNodes[3] != null)
					{
						var mapURL = Url.decode(event[0].childNodes[3].firstChild.nodeValue);													
						document.getElementById('eventTitle').innerHTML = document.getElementById('eventTitle').innerHTML + '&nbsp<a target="_new" href="' + mapURL + '">[View Map]</a>';
					}
					
					document.getElementById('eventDate').innerHTML = event[0].childNodes[1].firstChild.nodeValue;
				}
			}

			document.getElementById('imageGrid').innerHTML = text;

			break;
	}
}

function loadPhotoDetails(eventId,imgNo)
{
	request.open('GET', 'XMLPhotoDetails.php?event_id=' + eventId + '&img_no=' + imgNo, true);

	request.onreadystatechange = processPhotosDetails;	
	request.send('');
}


function processPhotosDetails()
{
	switch(request.readyState)	{
		case 1:	// loading
			
			break;
		case 4:	//ready

			var text = '';

			var xmlDoc = request.responseXML.documentElement;

			if (xmlDoc != null)
			{				

				var photo = xmlDoc.getElementsByTagName("details");		

				if (photo != null)
				{			
					
					var photoTitle = photo[0].childNodes[0].firstChild.nodeValue;
					var photoUrl = photo[0].childNodes[1].firstChild.nodeValue;
					var photoWidth = photo[0].childNodes[1].getAttribute("width");
					var photoHeight = photo[0].childNodes[1].getAttribute("height");
					var eventId = photo[0].childNodes[2].firstChild.nodeValue;
					var imageNo = parseInt(photo[0].childNodes[3].firstChild.nodeValue);					
					var author = photo[0].childNodes[4].firstChild.nodeValue;
					var photoCount = parseInt(photo[0].childNodes[5].firstChild.nodeValue);
					var hasFullsize = parseInt(photo[0].childNodes[6].firstChild.nodeValue);
					var photoId = parseInt(photo[0].childNodes[7].firstChild.nodeValue);
					var hasVideo = parseInt(photo[0].childNodes[8].firstChild.nodeValue);
					
					mainPhoto = document.getElementById('mainImage');

					document.getElementById('mainImageTitle').innerHTML = photoTitle + '&nbsp;(' + (imageNo+1) + '/' + photoCount + ')';
					document.getElementById('mainImageAuthor').innerHTML = '&copy;' + author;

					document.getElementById('firstButton').href = 'JavaScript:showPhoto(' + eventId + ',0)';
					document.getElementById('prevButton').href = 'JavaScript:showPhoto(' + eventId + ',' + (imageNo-1) + ')';
					document.getElementById('nextButton').href = 'JavaScript:showPhoto(' + eventId + ',' + (imageNo+1) + ')';
					document.getElementById('lastButton').href = 'JavaScript:showPhoto(' + eventId + ',' + (photoCount - 1) + ')';

					if (imageNo <= 0)
					{
						document.getElementById('firstButton').style.visibility = 'hidden';
						document.getElementById('prevButton').style.visibility = 'hidden';
					}
					else
					{
						document.getElementById('firstButton').style.visibility = '';
						document.getElementById('prevButton').style.visibility = '';
					}

					if (imageNo >= (photoCount-1))
					{
						document.getElementById('nextButton').style.visibility = 'hidden';
						document.getElementById('lastButton').style.visibility = 'hidden';
						nextPhoto = 0;		// loop slideshow (button's don't loop)
					}
					else
					{
						document.getElementById('nextButton').style.visibility = '';
						document.getElementById('lastButton').style.visibility = '';
						nextPhoto =  imageNo + 1;		// next slideshow photo
					}

					if (hasFullsize)
					{
						document.getElementById('downloadButton').style.visibility = '';
						document.getElementById('downloadLink').href = 'photoDownload.php?photo_id=' + photoId;
					}
					else
					{
						document.getElementById('downloadButton').style.visibility = 'hidden';
					}

					currentEventSet = eventId;	// slideshow needs to know which event we're watching

					if (hasVideo)
					{
						document.getElementById('mainVideo').style.display = '';
						document.getElementById('mainImage').style.display = 'none';
						document.getElementById('fullSizeWindow').style.display = 'block';
					
						var s1 = new SWFObject("mediaplayer/mediaplayer.swf","mediaplayer","640","500","7");
						s1.addParam("allowfullscreen","true");
						s1.addVariable("width","640");
						s1.addVariable("height","500");
						s1.addVariable("file","../videos/" + photoId + ".flv");
						s1.addVariable("image","../photos/" + photoId + ".jpg");
						s1.write("mainVideo");
						
						mainVideo.width = photoWidth;
						mainVideo.height = photoHeight;
						
						
					}
					else
					{					
						document.getElementById('mainVideo').style.display = 'none';
						document.getElementById('mainImage').style.display = '';
						document.getElementById('fullSizeWindow').style.display = 'block';
											
						mainPhoto.src = document.getElementById('thumb-' + eventId + '-' + imageNo).src;						
						mainPhoto.width = photoWidth;
						mainPhoto.height = photoHeight;

						tempImage = new Image();

						tempImage.width = photoWidth;
						tempImage.height = photoHeight;
						tempImage.src = photoUrl;
						tempImage.onLoad = swapMainTemp('mainImage');
					}
				}
			}

			break;
	}
}

function swapMainTemp(image)
{
	document.getElementById(image).src = tempImage.src;
}


function incYear()
{
	var year = parseInt(document.getElementById('year').innerHTML);
	setYear(year + 1);
}

function decYear()
{
	var year = parseInt(document.getElementById('year').innerHTML);
	setYear(year - 1);
}

function setYear(year)
{

	selectedYear = year;

	if (year >= thisYear)
	{
		document.getElementById('incButton').style.visibility = 'hidden';
	}
	else
	{
		document.getElementById('incButton').style.visibility = 'visible';
	}


	if (year <= 2001)	// first year photos avalible
	{
		document.getElementById('decButton').style.visibility = 'hidden';
	}
	else
	{
		document.getElementById('decButton').style.visibility = 'visible';
	}

	document.getElementById('year').innerHTML = 'Loading...';
	loadYearImages(year);	
}

function showCaption(imageName)
{
	var image = document.getElementById(imageName);
	var caption = document.getElementById(imageName + 'C');

	if (caption != null)
	{				
		if (currentCaption != 0)
		{
			hideCaption(currentCaption)
		}
/*
		// IE and firefox don't seem to work the same here
		if (isIE == 1)
		{
			caption.style.pixelLeft = event.srcElement.offsetLeft;
			caption.style.pixelTop = event.srcElement.offsetTop;
			border = 6;
		}
		else
		{
			posn = findPos(image);
			caption.style.left = posn[0];
			caption.style.top = posn[1];
			//border = -4;
		}
		
		posn = findPos(image);
		caption.style.left = posn[0];
		caption.style.top = posn[1];
		border = 0;
		

		caption.style.width = image.clientWidth + "px";// + border;
		caption.style.height = image.clientHeight + "px";// + border;
*/
		caption.style.display = '';
		currentCaption = imageName;
	}
}

function hideCaption(imageName)
{
	var caption = document.getElementById(imageName + 'C');

	if (caption != null)
	{
		caption.style.display='none';
		currentCaption = 0;
	}
}

function hidePhoto()
{
	stopSlideshow();
	document.getElementById('fullSizeWindow').style.display = 'none';
}

function showPhoto(eventId,imageNo)
{
	pageSize = getPageSize();
	document.getElementById('fullSizeWindow').style.left = (pageSize.windowWidth/2 ) - (900/2);	
	document.getElementById('fullSizeWindow').style.top = document.body.scrollTop + 10;
	loadPhotoDetails(eventId,imageNo);
}


function startSlideshow()
{
	document.getElementById('playButton').style.display = 'none';
	document.getElementById('stopButton').style.display = '';
	timerID  = setTimeout("slideAdvance()", 5000);

}

function stopSlideshow()
{
	document.getElementById('playButton').style.display = '';
	document.getElementById('stopButton').style.display = 'none';
	clearTimeout(timerID);
}

function slideAdvance()
{
//	alert(currentEventSet);
	showPhoto(currentEventSet,nextPhoto);
	timerID  = setTimeout("slideAdvance()", 5000);
}







// thanks to quirksmode for this
function findPos(obj) {
	var curleft = curtop = 0;
	
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop


		while (obj = obj.offsetParent) {

			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}

	return [curleft,curtop];
}



function getPageSize (){
    var xScroll, yScroll;

    if (window.innerHeight && window.scrollMaxY) {  
      xScroll = document.body.scrollWidth;
      yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
      xScroll = document.body.scrollWidth;
      yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
      xScroll = document.body.offsetWidth;
      yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;

    if (self.innerHeight) {  // all except Explorer
      windowWidth = self.innerWidth;
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowWidth = document.documentElement.clientWidth;
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowWidth = document.body.clientWidth;
      windowHeight = document.body.clientHeight;
    }  
    var pageHeight, pageWidth;

    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
      pageHeight = windowHeight;
    } else { 
      pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){  
      pageWidth = windowWidth;
    } else {
      pageWidth = xScroll;
    }

    return {pageWidth: pageWidth ,pageHeight: pageHeight , windowWidth: windowWidth, windowHeight: windowHeight};
  }

  
  /**
*
* URL encode / decode
* http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}
  