

Gallery = {

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    properties
    
*/ 
    galleryDirName: null, //Variable which holds name of gallery directory
	oXHR: null, //Variable used to store reference to Ajax call
	oXHRListener: 1, //Variable used to time the Ajax call
	oXML: null, //Variable to store reference to xml tree
	oImages: new Array(), //Variable to store reference to literal objects of every gallery item
	originalImage: null, //Variable to hold reference to image stored in page before the gallery loads
	
	galleryHolder: null, //Variable to store reference to gallery holder
	imgHolder: null, //Variable to store reference to image holder
	loadingImg: false, //Variable set to true while new image is loading
	curImg: null, //Varialbe to store reference to current image
	newImg: null, //Varialbe to store reference to new image to be loaded
    
	

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    methods
    
*/

//Method to get the name of the directory of the gallery
/*
	getGalleryDirName: function()
	{
		var oAnchor = document.getElementById('galleryLink');
		//Check if anchor tag exists and the href attribute is set
		if(!oAnchor || !oAnchor.tagName || oAnchor.tagName.toLowerCase() != 'a' || !oAnchor.getAttribute('href'))return;
		
		//Retrieve reference to gallery
		var sHref = oAnchor.getAttribute('href');
		
		//Check if href attribute is valid
		if(sHref.indexOf('galleries/') == -1)return;
		
		//Split url
		var aHref = sHref.split('/');
		
		//if array is set and last index item is not valid return
		if(aHref.length > 0 && aHref[aHref.length - 1].length == 0)return;
		
		//Assign file name to 'galleryDirName
		this.galleryDirName = aHref[aHref.length - 1].trim();
			
	},
*/

//Method to check whether the galery exists
	galleryLinkExist: function()
	{
		var oAnchor = document.getElementById('galleryLink');
		
		//If a link could not be found
		if(!oAnchor)return false;
		
		if(!oAnchor.tagName 
		   || oAnchor.tagName.toLowerCase() != 'a')
		{
			if(LOG)LOG.printH1('ERROR: The link for the gallery with the attribute \'id="galleryLink"\' could not be found.');	
			return false;
		}
		
		//If the link href attribute is empty
		if(!oAnchor.getAttribute('href')
		   || oAnchor.getAttribute('href').length == 0)
		{
			if(LOG)LOG.printH1('ERROR: The \'href\' attribute for the gallery link is not set.');	
			return false;	
		}
		
		return true;
	},
/*	
//Method to load the xml file with the gallery details
	getGalleryXML: function()
	{
		//If Ajax call has not been made yet
		if(!this.oXHR)
		{
			if(LOG)LOG.printH2('Created oXHR object');
			//Create Ajax call
			this.oXHR = DH.createXHR();
			var num = Math.floor(Math.random() * 1000);
    		//this.oXHR.open('GET',('galleries/' + this.galleryDirName + '/gallery.xml?num=' + num),true);
			this.oXHR.open('GET',('gallery.xml?num=' + num),true);
    		this.oXHR.send(null);
			//Set timeout to call function again in 100 miliseconds
			setTimeout('Gallery.getGalleryXML()',100);			
			return;
		}
		
		//If response has been received
		if(this.oXHR.readyState == 4)
		{
			//If status is OK
			if(this.oXHR.status == 200 || this.oXHR.status == 304)
			{
				if(LOG)LOG.printH2('Ajax call successful');
				
				//Read XML file into object variable named oXML
				this.parseGalleryFileStrAsXML(this.oXHR.responseText);
				
				//If the file has loaded
				if(this.oXML)
				{
					//Read oXML contents into object array
					this.loadXMLIntoArray();
					if(LOG)LOG.printH1('Loading XML into array');
					//this.printImageArrayToLOG();
					
					//Reset page prior to loading gallery
					if(LOG)LOG.printH1('Reset page');
					this.resetArticle();
					if(LOG)LOG.printH1('originalImage.source = ' + this.originalImage.source);
					
					//Rearrange image array and make sure original image is displayed first
					if(LOG)LOG.printH1('Rearranging image array');
					this.rearrangeImages();
					
					//this.printImageArrayToLOG();
					
					this.attachGallery();
				}
				
			} else {//If status not ok
				if(LOG)LOG.printH2('Ajax call not successful');
			}
		} else { //If call has not been successfull
			//If the call has not reached the number of iterations
			if(this.oXHRListener < 200)
			{
				setTimeout('Gallery.getGalleryXML()',100);
				this.oXHRListener++;
				return;
			}
		}
	},
	
*/

//Method to load the xml file with the gallery details
	getGalleryXML: function()
	{
		
		//if(LOG)LOG.printH2('Created oXHR object');
		//Create Ajax call
		this.oXHR = DH.createXHR();
		var num = Math.floor(Math.random() * 1000);
    	this.oXHR.open('GET',('gallery.xml?num=' + num),true);
		
		this.oXHR.onreadystatechange = function()
		{
			if(Gallery.oXHR.readyState == 4 && (Gallery.oXHR.status == 200 || Gallery.oXHR.status == 304))
			{
				//Read XML file into object variable named oXML
				Gallery.parseGalleryFileStrAsXML(Gallery.oXHR.responseText);
				
				if(Gallery.oXML)
				{
					
					//Read oXML contents into object array
					Gallery.loadXMLIntoArray();
					
					//If the image array has any corrupt entry display error table
					if(!Gallery.hasImageNotOk())
					{
						//Reset page prior to loading gallery
						if(Gallery.resetArticle())
						{
							Gallery.rearrangeImages();
							Gallery.attachGallery();
						}
					} else {
						if(Gallery.oImages.length == 0)
						{
							LOG.printH1('ERROR: The file \'gallery.xml\' does not contain any valid entries.');		
						} else {
							LOG.printH1('ERROR: The file \'gallery.xml\' has invalid entries. Please observe the row(s) marked in black bellow:');	
							Gallery.printImageArrayToLOG();
						}
					}
					
					
					
				}
			} else if(Gallery.oXHR.readyState == 4 && Gallery.oXHR.status == 404) {
				LOG.printH1('ERROR: The file \'gallery.xml\' could not be found.');		
			}
		};
	
		this.oXHR.send(null);
		
	},
//Method which parses string as XML object	
	parseGalleryFileStrAsXML: function(sText)
	{
		//In case browser is internet explorer
		if(window.ActiveXObject)
		{
			var oXML = new ActiveXObject("Microsoft.XMLDOM");
			oXML.async="false";
			oXML.loadXML(sText);
			} else { //In case it's any other browser than internet explorer
				var oDOMParser = new DOMParser();
				var oXML = oDOMParser.parseFromString(sText,"text/xml");
			}
			
			if(typeof oXML == 'object')//if file has been loaded
			{
				this.oXML = oXML;
			} else {
				LOG.printH1('ERROR: XML file could not be parsed. Please check its accuracy.');	
			}
	},
	
	loadXMLIntoArray: function()
	{
		//Get reference to images
		var oImages = this.oXML.getElementsByTagName('Image');
		
		//If there are no images
		if(oImages.length == 0)
		{
			LOG.printH1('ERROR: The system was not able to detect any \'Image\' tags in the XML file. Please check the accuracy of those tags.');
			return;
		}
		
		for(var i = 0; i < oImages.length; i++)
		{
			
			//var imgOK = true; //Variable used to flag errors in xml file
			
			//Get reference
			var filename = oImages[i].getElementsByTagName('Filename');
			
			//If there is no reference or
			if((filename.length == 0) 
				|| (!filename[0].firstChild)
				|| (filename[0].firstChild.nodeValue.length == 0))
			{
				//imgOK = false;
				filename = null;
			} else {
				filename = filename[0].firstChild.nodeValue;
			}
			
			//Get description text
			var description = oImages[i].getElementsByTagName('Description');
			
			//If there is no description
			if((description.length == 0) 
				|| (!description[0].firstChild)
				|| (description[0].firstChild.nodeValue.length == 0))
			{
				//imgOK = false;
				description = null;
			} else {
				description = description[0].firstChild.nodeValue;
			}
			
			this.oImages.push({
				'filename': filename,
				'description': description,
				'ok': (!filename ? false : true)				  
			});	
		}
		
	},
	
	printImageArrayToLOG: function()
	{
		for(var i = 0; i < this.oImages.length; i++)
		{
			var imgArray = new Array();
			imgArray.push((i + 1).toString());
				
			//Append filanem
			var ul = document.createElement('ul');
			var li = document.createElement('li');
			var strong = document.createElement('strong');
			strong.appendChild(document.createTextNode('Filename: '));
			li.appendChild(strong);
			li.appendChild(document.createTextNode(!this.oImages[i].filename ? 'Not set' : this.oImages[i].filename));
			ul.appendChild(li);
			
			//Append description
			var li = document.createElement('li');
			var strong = document.createElement('strong');
			strong.appendChild(document.createTextNode('Description: '));
			li.appendChild(strong);
			li.appendChild(document.createTextNode(!this.oImages[i].description ? 'Not set' : this.oImages[i].description));
			ul.appendChild(li);	
			
			imgArray.push(ul);
				
			if(this.oImages[i].ok)
			{	
				LOG.printTable(imgArray, null);
			} else {
				LOG.printTable(imgArray, 'error');
			}
		}
	},
	
	resetArticle: function()
	{
		//Get reference to gallery link
		var oLink = document.getElementById('galleryLink');
		
		if(!oLink) return false;
		
		//Reset image - it returns the href and alt attributes. It returns false otherwise
		this.originalImage = this.resetArticleImage();
		//Create gallery holder
		
		
		var div = document.createElement('div');
		div.setAttribute('id','gallery');
		
		//Insert gallery holder
		oLink.parentNode.insertBefore(div,oLink);
		
		//Remove link from document
		oLink.parentNode.removeChild(oLink);
		
		return true;
	},
	
	resetArticleImage: function()
	{
		//Get reference to gallery link
		var oLink = document.getElementById('galleryLink');	
		if(!oLink) return false;
		
		//Get reference to big image
		for(var i = 0; i < 3; i++)
		{
			//If there is no previous sibling return
			if(!oLink.previousSibling)return false;
			if(oLink.previousSibling.tagName && oLink.previousSibling.tagName.toLowerCase() == 'img')
			{
				var details = {
					'source': (oLink.previousSibling.getAttribute('src') ? oLink.previousSibling.getAttribute('src') : null),
					'alt': (oLink.previousSibling.getAttribute('alt') ? oLink.previousSibling.getAttribute('alt') : null)
				};
				oLink.previousSibling.parentNode.removeChild(oLink.previousSibling);
				return details;
			}
			oLink = oLink.previousSibling;
		}
		return false;
	},
	
	attachGallery: function()
	{
		if(!(this.galleryHolder = document.getElementById('gallery')))
		{
			setTimeout('Gallery.attachGallery()',100);	
			return;
		}
		//Get first ok image
		var oImg = this.getFirstOkImage();
		
		//Attach image
		var img = document.createElement('img');
		img.className = 'slideshowImage';
		img.src = oImg.filename;
		if(oImg.description)
		{
			img.setAttribute('alt',oImg.description);	
		}
		
		var imgHolder = document.createElement('div');
		imgHolder.appendChild(img);
		this.galleryHolder.appendChild(imgHolder);
		
		var ul = document.createElement('ul');
		
		for(var i = 0; i < this.oImages.length; i++)
		{
			var a = document.createElement('a');
			a.setAttribute('href',this.oImages[i].filename);
			a.appendChild(document.createTextNode(this.oImages[i].filename.split('.')[0]));
			
			DH.addEvent(a,'click',function(W3CEvent){
				var target = DH.stopEvent(W3CEvent);
				Gallery.newImg = Gallery.getImageByFilename(target.getAttribute('href'));
				Gallery.loadNewImg();							   
			});
			
			var li = document.createElement('li');
			li.appendChild(a);
			
			ul.appendChild(li);
		}
		
		this.galleryHolder.appendChild(ul);
	},
	
	loadNewImg: function()
	{
		//if(LOG)LOG.printH2('loading new image');
		
		//Attach image cover in order to indicate the image is loading
		if(this.attachImgCover())
		{
			//Reset image reference
			this.newImg.ref = null;
			
			//Attach load event
			this.newImg.ref = document.createElement('img');
			DH.addEvent(this.newImg.ref,'load',function(){
				Gallery.onNewImgLoad();
			});
			//Attach error event
			DH.addEvent(this.newImg.ref,'error',function(){
				Gallery.onNewImgError();
			});	
			
			this.newImg.ref.src = this.newImg.filename;
			
		} else {
			
			//if(LOG)LOG.printH1('error loading image');	
		}
	},
	
	onNewImgLoad: function()
	{
		//if(LOG)LOG.printH2('image loaded');	
		
		var imgHolder = this.galleryHolder.getElementsByTagName('div')[0];
		
		//Set newImg as background-image
		imgHolder.style.backgroundImage = 'url(' + this.newImg.filename + ')';
		
		if(this.removeImgCover())//curImg will now reference newImg
		{
			//Remove current image
			var oldImg = imgHolder.getElementsByTagName('img')[0];
			oldImg.parentNode.removeChild(oldImg);
			
			//Attach new image
			if(this.curImg.description)this.curImg.ref.setAttribute('alt',this.curImg.description);
			imgHolder.appendChild(this.curImg.ref);
			/*
			var newImg = document.createElement('img');
			if(this.newImg.description)newImg.setAttribute('alt',newImg.description);
			newImg.src = 
			*/
		}
	},
	
	onNewImgError: function()
	{
		if(LOG)LOG.printH2('image not loaded');	
	},
	/*
	toggleLinks: function()
	{
		var anchors = this.galleryHolder.getElementsByTagName('a');
		for(var i = 0; i < anchors.length; i++)
		{
			anchors[i].enabled = anchors[i].enabled ? false : true;	
		}
	},
	*/
	
	attachImgCover: function()
	{
		this.imgHolder = this.galleryHolder.getElementsByTagName('div');
		if(typeof this.imgHolder[0] == 'undefined')return false;
		this.imgHolder = this.imgHolder[0];
		
		this.curImg = this.getImageByFilename(document.getElementById('gallery').getElementsByTagName('img')[0].getAttribute('src'));
		if(!this.curImg)return false;
		
		//Check reference to new image
		if(!this.newImg)return false;
		//if(LOG)LOG.printH2('this.newImg');
		//Set loadingImg to true to avoid further clicks
		this.loadingImg = true;
			
		var	imgCover = document.createElement('div');
		this.imgHolder.appendChild(imgCover);
		
		return true;
	},
	
	removeImgCover: function()
	{
		var imgCover = this.imgHolder.getElementsByTagName('div');
		if(typeof imgCover[0] == 'undefined')return false;
		
		//Remove cover
		imgCover[0].parentNode.removeChild(imgCover[0]);
		
		//Reset variables
		this.loadingImg = false;
		this.curImg = this.newImg;
		this.newImg = null;
		
		return true;
	},
	
	getFirstOkImage: function()
	{
		
		for(var i = 0; i < this.oImages.length; i++)
		{
			if(this.oImages[i].ok)
			{
				return this.oImages[i];	
			}
		}
		return null;
	},
	
	getImageByFilename: function(fname)
	{
		for(var i = 0; i < this.oImages.length; i++)
		{
			if(fname.indexOf(this.oImages[i].filename) != -1)
			{
				return this.oImages[i];	
			}
		}
		return null;	
	},
	
	hasAtLeastOneOkImage: function()
	{
		for(var i = 0; i < this.oImages.length; i++)
		{
			if(this.oImages[i].ok)return true;	
		}
		return false;	
	},
	
	hasImageNotOk: function()
	{
		if(this.oImages.length == 0)return true;
		
		for(var i = 0; i < this.oImages.length; i++)
		{
			if(!this.oImages[i].ok)return true;	
		}
		return false;	
	},
	
	rearrangeImages: function()
	{
		
		//If original image details exist
		if(!this.originalImage 
		   || !this.originalImage.source
		   || this.originalImage.source.length == 0)return;
		
		//Loop through image array in order to locate the position of the first image
		for(var i = 0; i < this.oImages.length; i++)
		{
			if(this.originalImage.source.indexOf(this.oImages[i].filename) != -1)
			{
				//if(LOG)LOG.printH1('rearrangeImages() - image found at index ' + i);
				var ImageIndex = i;
				var ImageTemp = this.oImages[0];
				this.oImages[0] = this.oImages[i];
				this.oImages[i] = ImageTemp;
				break;
			}
		}
		//this.printImageArrayToLOG();
		return;
	},
	
//Method to preload images
	preloadImageArray: function()
	{
		if(!this.oImages
		   || this.oImages.length == 0)
		{
			return;	
		}
		
		for(var i = 0; i < this.oImages.length; i++)
		{
			if(this.oImages[i].ok)
			{
				this.oImages[i].ref = document.createElement('img');
				this.oImages[i].ref.src = this.oImages[i].filename;
			} else {
				this.oImages[i].ref = null;	
			}
		}
	},
	
//Init method
	init: function()
	{
		/*
		//Get gallery dir name
		this.getGalleryDirName();	
		
		if(this.galleryDirName)
		{
			if(LOG)LOG.printH1('Start of Ajax call');
			this.getGalleryXML();	
		}
		*/
		
		
		if(!this.galleryLinkExist())return;
		
		//if(LOG)LOG.printH2('Start of Ajax call');
		//Load xml file
		this.getGalleryXML();
		
		
		
		
	}
	
}

/*---------------------------------------------------------------------------------------------------------------------------------------------------------------
*/


