/*
	JavaScript Document
 	Created by Ed Slocombe
 	www.eduardo.me.uk
 	Photo Gallery Javascript 
	Edited for http://www.cats83.co.uk
	Original can be found at: http://www.exeterflying.co.uk/gallery.js
*/

// Requires onload event to call function initPhotoGallery()
// Requires detection of browser - more specifically whether browser is IE or not
// It is assumed if browser is IE, variable isIE = 1
// Otherwise isIE = null

var isIE = null;

var galleryState = 'closed'; // Throughout script will either be 'open' or 'closed' 
var initialised_gallery = false;
var initialising_gallery = false;
var timeOutTime = 100;

var browserWidth;
var browserHeight;
var photoContainer_width = 640; // Set from CSS
var photoContainer_height = 540; // Set from CSS 
var photoCon_div; // PhotoContainer
var transBg_div; // TransparentBg
var photoObject; // Object that will hold the image
var photoCaption // Photo caption and photo numbering
var transBg_opacity_current = 0;
var transBg_opacity_start = 0;
var transBg_opacity_end = 0.5;
var transBg_opacity_increment = 0.2;
var photoCon_opacity_current = 0;
var photoCon_opacity_start = 0;
var photoCon_opacity_end = 1;
var photoCon_opacity_increment = 0.2;
var photoCon_pos_left;
var timer; 

var xmlDoc_gallery;
// Images must be labeled like so: group1.jpg, group2.jpg... where 'group' is photoDirectory
var photos = new Array(); // Array to hold captions, id should be equivalent
var photoGroups = new Array(); // Array to hold albums
var photoDirectory; // Where images for gallery are stored - retrived from XML file
var photoExtension; // Assuming all images are same file type - retrived from XML file
var totalNoPhotos; // Total number of photos in group - retrived from XML file
var currentPhotoNo; // Stores which photo is shown so can handle next and prev requests
var currentPhotoGroup; // Array which stores which album is being viewed (if none, then all photos are show)

var imageDirectory = 'images/galleryPhotos/';
var globalTempPhotoGroupId; // Variable to hold requested album id if called before gallery is instanitated


// Function to initiate gallery - Centres on page and gets objects by IDs
function initPhotoGallery(){
	if (initialised_gallery) drawGallery();
	else if (initialising_gallery) {} // do nothing - wait
	else {
		initialising_gallery = true;
		if (browser != browsers.OTHER) isIE = 1;
		
		// Set up objects
		photoCon_div = document.getElementById('photoContainer');
		transBg_div = document.getElementById('transparentPhotoBg');
		photoObject = document.getElementById('photoDiv');
		photoCaption = document.getElementById('caption');
		// Get browsers dimensions
		browserWidth = document.body.clientWidth;
		browserHeight = document.body.clientHeight;
		
		// Set photoContainer_div to centre in page
		photoCon_pos_left = (browserWidth - photoContainer_width) / 2;
		photoCon_div.style.left = photoCon_pos_left + 'px';
		
		// Import photo information from XML file
		importXML('xml/gallery.xml');
		
		// Set up arrow keys event handlers
		if (isIE) document.all;
		else document.layers;
		if (document.layers) document.captureEvents(Event.KEYPRESS);
		document.onkeypress = captureKeypress;
	}
}

// Function to control gallery photos by < and > on the keyboard
function captureKeypress(key){
    if (galleryState == 'open'){
		if (isIE){
			if (event.keyCode == 188) changePhoto('previous');
			if (event.keyCode == 190) changePhoto('next');
		}
		else {
			if (key.which == 44) changePhoto('previous');
			if (key.which == 46) changePhoto('next');
		}
	}
}
	

// Function to open gallery
function openGallery(photoNo){
	var innerHeight;
	if (window.innerHeight && window.scrollMaxY) {
		// Firefox
		innerHeight = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){
		// IE
		innerHeight = document.body.scrollHeight;
	} else { 
		// Others
		innerHeight = document.body.offsetHeight;
  	}
	
	var currentScrollY;
  	if(typeof(window.pageYOffset) == 'number') {
		// Netscape compliant
		currentScrollY = window.pageYOffset;
  	} else if(document.body && document.body.scrollTop) {
		// DOM compliant
		currentScrollY = document.body.scrollTop;
  	} else if(document.documentElement && document.documentElement.scrollTop) {
		// IE6 standards compliant mode
		currentScrollY= document.documentElement.scrollTop;
	}
  	
  	var heightOfBrowser;
	
	if(typeof(window.innerHeight) == 'number') {
		// Non-IE
		heightOfBrowser = window.innerHeight;
  	} else if(document.documentElement && document.documentElement.clientHeight) {
		// IE 6+ in 'standards compliant mode'
		heightOfBrowser = document.documentElement.clientHeight;
  	} else if(document.body && document.body.clientHeight) {
		// IE 4 compatible
		heightOfBrowser = document.body.clientWidth;
		heightOfBrowser = document.body.clientHeight;
  	}
	
	transBg_div.style.height = innerHeight+"px";
	if (!currentScrollY) currentScrollY = 0;
	var photoConTop = ((heightOfBrowser - photoContainer_height)/2 + currentScrollY);
	photoCon_div.style.top = photoConTop+"px";	
	photoCaption.style.left = "0px";
	
	galleryState = 'open';
	currentPhotoNo = photoNo;
	photoObject.innerHTML = '<img src="' + imageDirectory + currentPhotoGroup[currentPhotoNo].url + '" alt= "' + currentPhotoGroup[currentPhotoNo].caption + '" />';
	photoCaption.innerHTML = currentPhotoGroup[currentPhotoNo].caption + '&nbsp;&nbsp; | &nbsp;&nbsp;' + (currentPhotoNo+1) + ' of ' + totalNoPhotos;
	photoCon_div.style.display = 'inline';
	transBg_div.style.display = 'inline';
	fade_transBg('in');
}

// Function to show next and previous pictures 
function changePhoto(direction){
	switch (direction){
		case 'next':
			if (++currentPhotoNo > (totalNoPhotos-1)) currentPhotoNo = 0;
			break;
		case 'previous':
			if (--currentPhotoNo < 0) currentPhotoNo = totalNoPhotos-1;
			break;
	}
	photoObject.innerHTML = '<img src="' + imageDirectory + currentPhotoGroup[currentPhotoNo].url + '" alt= "' + currentPhotoGroup[currentPhotoNo].caption + '" />';
	photoCaption.innerHTML = currentPhotoGroup[currentPhotoNo].caption + '&nbsp;&nbsp; | &nbsp;&nbsp;' + (currentPhotoNo+1) + ' of ' + totalNoPhotos;
}

// Function to close gallery
function closeGallery(){
	photoCon_div.style.display = 'none';
	if (isIE) photoCon_div.style.filter= "alpha(opacity=" + photoCon_opacity_start*100 + ")";
	else photoCon_div.style.opacity = photoCon_opacity_start;
	photoCon_opacity_current = photoCon_opacity_start;
	fade_transBg('out');
	galleryState = 'closed';
}

// Function to fade background transparncy in and out on open and close respectively
function fade_transBg (direction, object_name){
	switch (direction){
		case 'out':
			if (transBg_opacity_current > transBg_opacity_start){
				transBg_opacity_current = transBg_opacity_current - transBg_opacity_increment;
				if (isIE) transBg_div.style.filter= "alpha(opacity=" + transBg_opacity_current*100 + ")";
				else transBg_div.style.opacity = transBg_opacity_current;
				timer = setTimeout('fade_transBg ("out")', timeOutTime);
			}
			else {transBg_div.style.display = 'none';}
			break;
		case 'in':
			if (transBg_opacity_current < transBg_opacity_end){
				transBg_opacity_current = transBg_opacity_current + transBg_opacity_increment;
				if (isIE) transBg_div.style.filter= "alpha(opacity=" + transBg_opacity_current*100 + ")";
				else transBg_div.style.opacity = transBg_opacity_current;
				timer = setTimeout('fade_transBg ("in")', timeOutTime);
			}
			else fadeIn_photoCon (); // Otherwise open photocontainer Div
			break;
	}
}

function temp(){
	if (isIE) photoCon_div.style.filter= "alpha(opacity=100)";
	else photoCon_div.style.opacity = 1;
}

// Function to fade in the photoContainer div when gallery is opened
function fadeIn_photoCon (){
	if (photoCon_opacity_current < photoCon_opacity_end){
		photoCon_opacity_current = photoCon_opacity_current + photoCon_opacity_increment;
		if (isIE) photoCon_div.style.filter= "alpha(opacity=" + photoCon_opacity_current*100 + ")";
		else photoCon_div.style.opacity = photoCon_opacity_current;
		timer = setTimeout('fadeIn_photoCon ("in")', timeOutTime);
	}
}

// Function to import XML files - in this instance - gallery.xml (information about photos)
function importXML(file){
	var pageRequest;
	pageRequest = (browser == browsers.OTHER)? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
	pageRequest.onreadystatechange = function() { getInfo (pageRequest) };
	pageRequest.open("GET", file, true);
	pageRequest.send(null);
}

// Function to retrive information from XML file
function getInfo(pageRequest){
	if (pageRequest.readyState == 4){
		if (pageRequest.status == readyStatus){
			xmlDoc_gallery = pageRequest.responseXML;
			// Get photo groups - why didn't I name it album at the begining?!
			if (xmlDoc_gallery.getElementsByTagName("group").length != 0){
				var group_tags = xmlDoc_gallery.getElementsByTagName("group");
				totalNoGroups = group_tags.length;
				for (j=0; j<totalNoGroups; j++){
					var tempObj = new Object();
					tempObj.id = group_tags[j].getAttribute('id');
					tempObj.name = group_tags[j].firstChild.nodeValue;
					tempObj.photos = new Array();
					photoGroups[tempObj.id] = tempObj;
				}
			}
			else photoGroups = null;
			
			// Get photos
			var photo_tags = xmlDoc_gallery.getElementsByTagName('photo');
			for (i=0; i < photo_tags.length; i++){
				var tempObj = new Object();
				tempObj.url = getTextByTagName(photo_tags[i], "url", 0);
				tempObj.caption = getTextByTagName(photo_tags[i], "caption", 0);
				tempObj.photoGroupId = -1;
				if (getTextByTagName(photo_tags[i], "photoGroupId", 0)){ 
					var photoGroupId = getTextByTagName(photo_tags[i], "photoGroupId", 0);
					tempObj.photoGroupId = photoGroupId;
					try { photoGroups[photoGroupId].photos.push(tempObj); }
					catch (e) {}
				}
				photos.push(tempObj);
			}
			
			initialised_gallery = true;
			
			if (globalTempPhotoGroupId){
				drawGallery(globalTempPhotoGroupId);
				globalTempPhotoGroupId = null;
			}
			else drawGallery();
		}
		else document.getElementById("right_col").innerHTML = "<p>An error has occured, please contact the <a href='mailto:ed.slocombe@googlemail.com'>webmaster</a>.</p>";
	}
}

function drawGallery(photoGroupId, setPageRequired)
{
	// REMOVE line below if using with anything but Cats83.co.uk 
	if (setPageRequired) manualPageChange("gallery");
	
	if (!initialised_gallery){
		if (!initialising_gallery) initPhotoGallery();
		globalTempPhotoGroupId = photoGroupId;
		return;
	}
	var numberPerRow = 4;
	var groupName;
	var noOfPhotos;
	var theHTML = "";
	var element = document.getElementById("right_col");
	
	theHTML += '<h1>Gallery</h1>';
	theHTML += '<p/><form>Album:<span class="gallery_dropDown">\n'; 
	if (photoGroups == null) theHTML += '<select id="gallery_albumSelector" disabled="true"><option value="all">All Photos</option>\n';
	else {
		theHTML += '<select id="gallery_albumSelector" onchange="drawGallery(this.value)">'; 
		if (photoGroupId == null) theHTML += '<option value="none">-- Select Album --</option>';
		if (photoGroupId == 'all') theHTML += '<option value="all" selected="selected">All Photos</option>';
		else theHTML += '<option value="all">All Photos</option>';
		for (i=0; i<photoGroups.length; i++){
			if (photoGroups[i] != null){
				theHTML += '<option value="'+photoGroups[i].id;
				if (i == photoGroupId) theHTML += ' selected="selected"';
				theHTML += '">'+photoGroups[i].name+'</option>';
			}
		}
	}
	theHTML += '</select></span></form>';
	if (photoGroupId || photoGroups == null){
		if (photoGroupId && photoGroupId != "all"){
			currentPhotoGroup = photoGroups[photoGroupId].photos;
			groupName = photoGroups[photoGroupId].name;
		}
		else {
			currentPhotoGroup = photos;
			groupName = "All";
		}
		totalNoPhotos = currentPhotoGroup.length;
		
		theHTML += '<br/><h1 class="gallery_h1">'+groupName+' Photos:</h1>';
		theHTML += 'Click on image to open it up in the image gallery.';
		
		// Layout the photos
		var counter = 0;
		theHTML += '<table id="gallery_table"><tr>';
		
		if (currentPhotoGroup.length == 0)
			theHTML += '<td colspan='+numberPerRow+' class="gallery_noBg">The are currently no photos in this album.</td></tr>';
		else {
			for (j=0; j<currentPhotoGroup.length; j++){
					counter++;
					if (counter%numberPerRow == 1) theHTML += '</tr><tr>';
					var url = currentPhotoGroup[j].url;
					var directories = url.split("/");
					var thisURL = url;
					var theDirectory = "";
					if (directories.length != 1){
						thisURL = directories[directories.length-1];
						for (k=0; k<(directories.length-1); k++) theDirectory += directories[k] + '/';
					}
					theHTML += '<td><img src="'+imageDirectory+theDirectory+'thumbnails/'+thisURL+'" alt="Image '+(j+1)+'" onclick="openGallery('+j+')" /></td>';
			}
		}
		theHTML += '</table>';
	}
	
	element.innerHTML = theHTML;
	
}

function getTextByTagName(parentElement, tagName, index, prefix)
{
	var result;
	try {
		if (prefix && isIE) result = parentElement.getElementsByTagName(prefix + ":" + tagName)[index];
		else result = parentElement.getElementsByTagName(tagName)[index];
		
		if (result) {
			if (result.childNodes.length > 1) return result.childNodes[1].nodeValue;
			else return result.firstChild.nodeValue;
		}
	} catch (e) {} 
	return null;//"n/a";
}
	