	/*
 *  Copyright 2006, 2007, 2008 by Jens Boje
 *  Name    : SimpleViewerHTML 
			  Based on imago by  Jens Boje (azarai@codeboje.de)
			  http://codeboje.de/contact/
 *  Version : 0.1
 *  Author  : Andrew Zoechbauer
	Terms of Use:
			Imago may be used in any kinds of personal and/or commercial projects. 
			Redistribution or reselling to other companies or third parties is prohibited.
			Specifically, no Redistribution as part of a content management system or online hosting solution.
*/

// Changing Meta items: Change XML function, vars passed to GalleryImage.class and 'Meta Info' below.

var MaxImageHeight = 500; 
var MaxImageWidth = 725;
var NarrowImageWidth = 525; // the max width for the tall image layout
var NarrowImageHeight =  570;// the max height for the tall image layout
var metaWidthWide = 200; // width of meta info in wide picture layout
var metaWidthNarrow = 150;


var stageWidth = 770;

var GalleryImage = new Class({
	initialize: function(fileName, title, caption, client, role, photographer, thumbURL, imageURL) {
		this.fileName = fileName;
		this.thumbURL = thumbURL;
		this.imageURL = imageURL;

// Meta Info
		this.title = title;
		this.caption = caption;
		this.client = client;
		this.photographer = photographer;
		this.role = role;
// End Meta
	},
	getFileName: function() {
		return this.fileName;
	},
	getProjectTitle: function() {
	return '<div id="projectTitle">'+ this.title + '</div>';
	},
	getCaption: function() {
		return this.caption;
	},
	getMeta: function() {
    var photoReturn = "";
    
    if (this.photographer) {
    photoReturn = '<div id="photographer">Photographer: ' + this.photographer +'</div>';
    }
    
    
    //console.log(this.photographer);
    
    
		return '<div id="client">Client: '+ this.client + '</div>' + photoReturn + '<div id="role">My Role: '+this.role+'</div>'
	//		return '<div id="client">'+this.client +'</div>'+ '<div id="photographer">'+ this.photographer + '</div>' + '<div id="role">'+this.role+'</div>';
	//		return '<div id="client">'+this.client +'</div>'+ '<div id="photographer">'+ this.photographer + '</div>' + '<div id="projectTitle">'+ this.title + '</div>'+'<div id="role">'+this.role+'</div>';
	},
	
	getID: function() {

	var myString = this.getFileName();
	myString = myString.split(".");
	return 'id_' + myString[0];
		//return 'id_' + this.getFileName();
	},
	getThumbURL: function() {
		return this.thumbURL;
	},
	getImageURL: function() {
		return this.imageURL;
	}	
});

var Gallery = new Class({
	initialize: function() {
		this.prefetching = null;
		this.menuDivPosition = 'top';
		this.thumbnailColumns="3";
		this.thumbnailRows="3";
		eval($('imagogallery').innerHTML);
		this.createLayout();
		this.menuDiv = $('imagoThumbMenu');
		this.menuDivContainer = $('imagoThumbnailsContainer');
		this.images = new Array();

		this.lastThumbImageIndex=0;
		this.lastThumbsOnCurrentPage=0;
		this.thumbsPerPage = this.thumbnailRows * this.thumbnailColumns;
		this.title ='';
		this.indexCurrentImage =0;
	},
	addImage: function(img) {
		var counter=0;
		if (this.images.length !=0) {
			counter = this.images.length;
		}
		this.images[counter]=img;
	},
	getThumbImage: function(index) {
		if(this.images != null && this.images.length != 0 && index <= this.images.length) {
			if(this.images[index] != null) {
				var img = new Element("img");
				img.setProperty('src',  this.images[index].getThumbURL());
				img.addClass('imago_thumbImg');
				img.setProperty('alt',  this.images[index].getCaption());
				img.setProperty('id', this.images[index].getID());
				img.onclick = this.switchImage.bind(this.images[index]);
				return img;			
			}
		}
		return null;
	},
	getCurrentThumbTable: function() {
		var thumbTable = new Element("div");
		var thumbContainer = new Element("div", {'id':'thumbNailContainer'});		
		var thumbTableBody = new Element("div", {'id':'thumbNailBar'});		
		 
		thumbTable.setProperty('id', 'imagoCurrentThumbTable');
		var counter = this.lastThumbImageIndex;
		if (this.lastThumbImageIndex == 0) {
		//	ElementHelper.hide('imagoNavPrevLink');
			ElementHelper.show('imagoNavPrevLink'); // andrew messing around -- replace with ..PrevLink
		} else {
			ElementHelper.show('imagoNavPrevLink');
		}
		this.lastThumbsOnCurrentPage =0;
		//for(i=0;i<this.thumbnailRows;i++) { 
		for(i=0;i<this.images.length ;i++) { 
		  var tr = new Element("li");
				  var td = new Element("li");  
				  if (this.getThumbImage(counter) != null) {
					  td.appendChild(this.getThumbImage(counter));
					  counter++;
					  //this.lastThumbsOnCurrentPage++;
				  } else {
					  ElementHelper.hide('imagoNavNextLink');
				  }
				  tr.appendChild(td);
		  thumbTableBody.appendChild(td);
	 	}
	 	
	 	thumbTable.appendChild(thumbTableBody);
	 	this.lastThumbImageIndex = counter;
	 	return thumbTable;
	},
	thumbMenuNext: function() {
		//alert('hubert');
// andrew editing
//		$j('#imagoCurrentThumbTable').scrollTo( '+=500px', 800 );
//	var hubertus = $j('#thumbNailBar li:eq(5)').children();
	
//var hubertus = $j("imagoCurrentThumbTable:contains('2696')")

//var hubertus = $j('gallery/Emerald_52nd/thumb/IMG_2696.jpg');
//var hubertus = $j("#imagoCurrentThumbTable").find("#id_IMG_2499/./jpg");


//.attr({src: "gallery/Emerald_52nd/thumb/IMG_2696.jpg" });




	$j('#imagoCurrentThumbTable').scrollTo( '+=500px', 800 );

		
		 
		//var hubertf = $j("#id_IMG_2499.jpg");
		//alert (hubertf);
		// imagoThumbMenu
		
	},
	
	/* Original function!
	thumbMenuNext: function() {
		if (this.images.length>this.lastThumbImageIndex) {
			$('imagoCurrentThumbTable').remove();
			this.menuDiv.appendChild(this.getCurrentThumbTable());
		}	
	},
	*/
	
	
	/* Original function!
	thumbMenuPrev: function() {
		if(this.lastThumbImageIndex > this.thumbsPerPage) {
			this.lastThumbImageIndex -= (this.lastThumbsOnCurrentPage + this.thumbsPerPage);
			if(this.lastThumbImageIndex<0) {
				this.lastThumbImageIndex=0;
			}
			$('imagoCurrentThumbTable').remove();
// andrew			imagoThumbnailsContainer

this.menuDivContainer.appendChild(this.getCurrentThumbTable());
			//this.menuDiv.appendChild(this.getCurrentThumbTable());
		}	
	},
	
	*/
	thumbMenuPrev: function() {	
	$j('#imagoCurrentThumbTable').scrollTo( '-=588px', 800 );
	},
	nextImage: function() {
		if(this.indexCurrentImage +1 < this.images.length) {
			if(this.indexCurrentImage +1 >= this.lastThumbImageIndex) {
			
				this.thumbMenuNext(this);				
			}
			doSwitchImage = this.switchImage.bind(this.images[this.indexCurrentImage +1]);
			doSwitchImage();
		}
		
		
	/* ANDREW START */	
			//var hubertus = $j('#id_IMG_2791');
//			var hubertus = $j('div li:eq('+'14'+')');
	
	var scrollToThumb = $j('#thumbNailBar li:eq('+ (this.indexCurrentImage - 3) +')').children();
	//console.log(scrollToThumb);
	$j('#imagoCurrentThumbTable').scrollTo( scrollToThumb, 800 );
	
	/* ANDREW END */	
	
	},
	previousImage: function() {
		if(this.indexCurrentImage -1 >= 0) {
			if(this.indexCurrentImage -1< (this.lastThumbImageIndex - this.lastThumbsOnCurrentPage)) {
			//	this.thumbMenuPrev(this);				
			}
			doSwitchImage = this.switchImage.bind(this.images[this.indexCurrentImage -1]);
			doSwitchImage();
		}
		/* ANDREW START */	
		var scrollToThumb = $j('#thumbNailBar li:eq('+ (this.indexCurrentImage - 3) +')').children();
		$j('#imagoCurrentThumbTable').scrollTo( scrollToThumb, 800 );
		/* ANDREW END */	
	},	
	showGallery: function() {
		var navPrevLink = new Element("a");
		navPrevLink.className = 'imago_navPrev';
		navPrevLink.setProperty('id', 'imagoNavPrevLink');
		navPrevLink.onclick = this.thumbMenuPrev.bind(this);
		this.menuDiv.appendChild(navPrevLink);

//andrew!!
		ElementHelper.hide('imagoNavPrevLink');

		var navNextLink = new Element("a");
		navNextLink.className = 'imago_navNext';
		navNextLink.setProperty('id', 'imagoNavNextLink');
		navNextLink.onclick = this.thumbMenuNext.bind(this); //andrew
		// andrew $$('td:first-child');
		//this.imagoThumbnailsContainer.appendChild(navNextLink);	
		this.menuDiv.appendChild(navNextLink);	
		ElementHelper.hide('imagoNavNextLink');
		
					var img = new Element("img");
		img.setProperty('id', 'imagoCurrentImg');
		img.setProperty('alt', this.images[0].getCaption());
		img.setProperty('title', this.images[0].getCaption());
		img.setProperty('src', this.images[0].getImageURL());
		
//		if (this.images.length>this.thumbsPerPage) {
		if (1==1) {
			ElementHelper.show('imagoNavNextLink');
		}
		this.menuDiv.appendChild(this.getCurrentThumbTable());
		if(this.prefetching != null) {
			this.prefetchImages();
		}


		
		if(this.title != null && this.title != "")
		//changed now
			ElementHelper.setInnerHTML('imagoGalleryCaption',this.caption);
//			ElementHelper.setInnerHTML('imagoGalleryCaption',this.title);
		else
			ElementHelper.setInnerHTML('imagoGalleryCaption',"&nbsp;");
			
		ElementHelper.setInnerHTML('imagoCurrentImageCaption',this.images[0].getCaption());	
		ElementHelper.setInnerHTML('projectTitle',this.images[0].getProjectTitle());	
		ElementHelper.setInnerHTML('imagoCurrentImageMeta',this.images[0].getMeta());	

		this.setCurrentSelection(this.images[0].getID());
		img.addEvent('load', gallery.applyLayoutFixes.bind(this.images[0]));
		img.setProperty('src', this.images[0].getImageURL());
		img.injectInside('imagoCurrentImageDiv');
		
		
		
		var nextImageLink = new Element("a");
		nextImageLink.className = 'imago_navNextImage';
		nextImageLink.setProperty('id', 'imagoNextImageLink');
		nextImageLink.setProperty('href', '#');
		nextImageLink.setProperty('accesskey', 'n');
		nextImageLink.onclick = this.nextImage.bind(this);
		nextImageLink.injectAfter('imagoCurrentImg');	
		ElementHelper.hide('imagoNextImageLink');
		
		if (this.images.length>1) {
			ElementHelper.show('imagoNextImageLink');
		}
		
		var prevImageLink = new Element("a");
		prevImageLink.className = 'imago_navPreviousImage';
		prevImageLink.setProperty('id', 'imagoPreviousImageLink');
		prevImageLink.setProperty('href', '#');
		prevImageLink.setProperty('accesskey', 'p');
		prevImageLink.onclick = this.previousImage.bind(this);
		prevImageLink.injectBefore('imagoCurrentImg');
		ElementHelper.hide('imagoPreviousImageLink');
		ElementHelper.hide('imagoLoadingDiv');
		ElementHelper.hide('imagoCurrentImageLoadingDiv');
		
		document.addEvent('keydown', gallery.handleKey.bind(this));
	},
	handleKey : function(event) {
		var keycode = event.keyCode;
		switch(keycode) {
			// left arrow
			case 37:		// firefox
			case 63234:		// safari
				prv = gallery.previousImage.bind(this);
				prv();
				break;
			// right arrow
			case 39:		// firefox
			case 63235:		// safari
				nxt = gallery.nextImage.bind(this);
				nxt();
				break;						
		}
	},	
	switchImage: function() {
		$('imagoCurrentImageLoadingDiv').setStyle('width', $('imagoCurrentImg').getSize().size.x);
		$('imagoCurrentImageLoadingDiv').setStyle('height', $('imagoCurrentImg').getSize().size.y);
		ElementHelper.show('imagoCurrentImageLoadingDiv');
		file = this.getImageURL();
		caption = this.getCaption();
		client = this.getMeta();
		if ($(gallery.getCurrentSelection()) != null) {
			$(gallery.getCurrentSelection()).removeClass('imago_selectedThumb');
		}
		cimage = this;
		gallery.setCurrentSelection(this.getID());
		var myFx = new Fx.Style('imagoCurrentImg', 'opacity', {duration:100, onComplete: function() {
			oldSrc = $('imagoCurrentImg').getProperty('src');
		
			$('imagoCurrentImg').addEvent('load', gallery.fadeIn.bind(cimage));
    		$('imagoCurrentImg').setProperty('src', file);
			$('imagoCurrentImg').setProperty('alt', caption);
			$('imagoCurrentImg').setProperty('title', caption);
			$('imagoCurrentImg').setProperty('client', client);
    				
			ElementHelper.setInnerHTML('imagoCurrentImageCaption',caption);
			//andrew
			ElementHelper.setInnerHTML('imagoCurrentImageMeta',client);
			
			if (window.opera) {
			    $('imagoCurrentImg').removeEvents('load');
				fireFadein = gallery.fadeIn.bind(cimage);
				fireFadein();
	        }
		}, onStart: function() {
		  	$('imagoCurrentImg').removeEvents('load');
	      	cimage.img = new Image();
			cimage.img.src = file;
    }}).custom(1,0);
	},
	fadeIn: function() {
        i = this.img;
		ElementHelper.hide('imagoCurrentImageLoadingDiv');
		// andrew image scaling function. Works!!!
		
		// calculating layout
		var newImageHeight = i.height;
		var newImageWidth = i.width;
		var newImageRatio = newImageWidth / newImageHeight;

        // test to see if image fits wide layout
        if (newImageRatio >= 1) {   // wide Layout
            var maxImageWidthN = MaxImageWidth;
            var maxImageHeightN = MaxImageHeight;
            var narrowImage = false;
        } else {                    // Narrow layout
            var maxImageWidthN = NarrowImageWidth;
            var maxImageHeightN = NarrowImageHeight;
            var narrowImage = true;
        }

        // test to see which side to scale
        var widthRatio = maxImageWidthN / newImageWidth;
        var heightRatio = maxImageHeightN / newImageHeight;
        //console.log('widthRatio:'+widthRatio+'  heightRatio:'+heightRatio);
        if (widthRatio >= heightRatio) {
            //console.log('scaling according to heightRatio');
            newImageHeightOutput = newImageHeight * heightRatio;
            newImageWidthOutput = newImageWidth * heightRatio;
        } else {
            newImageHeightOutput = newImageHeight * widthRatio;
            newImageWidthOutput = newImageWidth * widthRatio;
        }
        //Adapt the layout
        if (narrowImage) {
            // narrow layout
			$('imagoCurrentImageCaption').setStyles({float:'left',width: '150px', margin: '0 0 20px 0', height: 'auto'});
			$('imagoCurrentImageMeta').setStyles({float: 'left', width: '150px', margin: '0 0 0 25px', clear: 'left'});
			$('imagoCurrentImageDiv').setStyles({top: '45px', visibility: 'visible'});
		} else {
            // wide layout
			$('imagoCurrentImageCaption').setStyles({float:'left', width: '500px', margin: '0 0 0 0', height:'55px'});
			$('imagoCurrentImageMeta').setStyles({float: 'right', width: metaWidthWide+'px', margin: '0 0 0 0', clear:'none'});
			$('imagoCurrentImageDiv').setStyles({left: '0px', top: '100px', visibility: 'visible'});
		}
                        
        $('imagoCurrentImg').setStyles({width: newImageWidthOutput + 'px', height: newImageHeightOutput + 'px'});        

        gallery.applyLayoutFixes(narrowImage);

		var myFx = new Fx.Style('imagoCurrentImg', 'opacity', {duration:200}).custom(0,1);
		if (gallery.indexCurrentImage +1 == gallery.images.length) {
			ElementHelper.hide('imagoNextImageLink');
		} else {
			ElementHelper.show('imagoNextImageLink');
		}
		if (gallery.indexCurrentImage == 0) {
			ElementHelper.hide('imagoPreviousImageLink');
		} else {
			ElementHelper.show('imagoPreviousImageLink');
		}
	},

	applyLayoutFixes: function(isNarrow) {
    	var narrowImage
        // apply special layout fixes if gallery has just been loaded
        if (!window.firstload || (1 == 1)) {
            window.firstload = "true";
            i = $('imagoCurrentImg');
            var newImageHeight = i.getSize().size.y;
            var newImageWidth = i.getSize().size.x;
    		var newImageRatio = newImageWidth / newImageHeight;
            // test to see if image fits wide layout
            if (newImageRatio >= 1) {   // wide Layout
                var maxImageWidthN = MaxImageWidth;
                var maxImageHeightN = MaxImageHeight;
                narrowImage = false;
            } else {                    // Narrow layout
                var maxImageWidthN = NarrowImageWidth;
                var maxImageHeightN = NarrowImageHeight;
                narrowImage = true;
            }
            // test to see which side to scale
            var widthRatio = maxImageWidthN / newImageWidth;
            var heightRatio = maxImageHeightN / newImageHeight;
            //console.log('widthRatio:'+widthRatio+'  heightRatio:'+heightRatio);
            if (widthRatio >= heightRatio) {
                //console.log('scaling according to heightRatio');
                newImageHeightOutput = newImageHeight * heightRatio;
                newImageWidthOutput = newImageWidth * heightRatio;
            } else {
                newImageHeightOutput = newImageHeight * widthRatio;
                newImageWidthOutput = newImageWidth * widthRatio;
            }
		}

		//Adapt the layout
		if (narrowImage) {
			// narrow layout
			//alert('its a narrow one narrowImage:'+narrowImage+' isNarrow:'+isNarrow);
			$('imagoCurrentImageCaption').setStyles({float:'left',width: '150px', margin: '0 0 20px 0', height: 'auto'});
			$('imagoCurrentImageMeta').setStyles({float: 'left', width: '150px', margin: '0 0 0 25px', clear: 'left'});
			$('imagoCurrentImageDiv').setStyles({top: '45px', visibility: 'visible'});
		} else {
			// wide layout
			$('imagoCurrentImageCaption').setStyles({float:'left', width: '500px', margin: '0 0 0 0', height:'55px'});
			$('imagoCurrentImageMeta').setStyles({float: 'right', width: metaWidthWide+'px', margin: '0 0 0 0', clear:'none'});
			$('imagoCurrentImageDiv').setStyles({left: '0px', top: '100px', visibility: 'visible'});
		}
						
		i.setStyles({width: newImageWidthOutput + 'px', height: newImageHeightOutput + 'px'});    
		var imgLeftPos = (stageWidth /2) - (newImageWidthOutput / 2);
		if (narrowImage && (imgLeftPos < (metaWidthNarrow + 35))){
			imgLeftPos = metaWidthNarrow + 35;
		}
		
		$('imagoCurrentImageDiv').setStyle('left', imgLeftPos);
		$('imagoCurrentImageDiv').setStyle('width', newImageWidthOutput);
		$('imagoFrame').setStyle('width', '745px');
		//$('imagoFrame').setStyle('width', $('imagoCurrentImg').getSize().size.x);
		$('imagoNextImageLink').setStyle('height', $('imagoCurrentImg').getSize().size.y);
		$('imagoPreviousImageLink').setStyle('height', $('imagoCurrentImg').getSize().size.y);
//        $j('#imagoCurrentImageCaption').jScrollPane({});
// END INSERT



/*
            var newImageRatio = newImageWidth / newImageHeight;	
            var imageDisplayRatio = MaxImageWidth / MaxImageHeight;
        // adjusting the size of the image to be displayed
            if (newImageHeight > MaxImageHeight) { 		// it's too tall
                newImageHeight = MaxImageHeight;
                newImageWidth = newImageHeight * newImageRatio;
                if (newImageWidth > MaxImageWidth) {  // is scaled width now too wide?
                    newImageWidth = MaxImageWidth;
                    newImageHeight = newImageWidth / newImageRatio;
                }
            } else {
                if (newImageWidth > MaxImageWidth) { // it's too wide
                    newImageWidth = MaxImageWidth;
                    newImageHeight = newImageWidth / newImageRatio;
                }		
            }
            
            var narrowImage = 0;
        // adaptive size (pt 1) !!!
            if (newImageWidth < NarrowImageWidth) {
                narrowImage = 1;
        //alert ('it"s a narrow one. Width:'+i.width+' Height:'+i.height);
                $('imagoCurrentImageCaption').setStyles({width: '150px', margin: '0 0 20px 0'});
                $('imagoCurrentImageMeta').setStyles({float: 'none', width: '150px', margin: '0 0 20px 0'});
                $('imagoCurrentImageDiv').setStyles({left: '180px', top: '45px'});
            } else {
        // alert ('it"s a WIDE one. Width:'+i.width+' Height:'+i.height);
                narrowImage = 0;
                $('imagoCurrentImageCaption').setStyles({width: '400px', margin: '0 0 0 0'});
                $('imagoCurrentImageMeta').setStyles({float: 'right', width: metaWidthWide+'px', margin: '0 0 0 0'});
                $('imagoCurrentImageDiv').setStyles({left: '0px', top: '90px'});
            }
            
            if (narrowImage) {
                newImageHeight = NarrowImageHeight;
                newImageWidth = newImageHeight * newImageRatio;
            }
            i.setStyles({height: newImageHeight + 'px'});
        }
        
        
        
        var imgWidth = $('imagoCurrentImg').getSize().size.x;
        var imgLeftPos = (stageWidth /2) - (imgWidth / 2);
        
        
        
        */

        
	},

    getCurrentSelection: function() {
		return this.selection;
	},
	setCurrentSelection: function(selection) {
		this.selection = selection;
		$(this.selection).addClass('imago_selectedThumb');
		for (var i = 0; i < this.images.length; i++) {
			if(this.images[i].getID() == this.selection) {
				this.indexCurrentImage = i;
			}
		}		
	},
	prefetchImages: function() {
		var thumbURLs = new Array();
		var imageURLs = new Array();
		for(var i=0; i< this.images.length; i++) {
			thumbURLs.push(this.images[i].getThumbURL());
			imageURLs.push(this.images[i].getImageURL());
			// andrew alert(imageURLs);
		}
		
		new Asset.images(imageURLs[0]);
		
		function loadImagesConsecutively(srcs, complete, error){
			var imgs = [];
			function loadImage(i){
				if("undefined" !== typeof(srcs[i])){
					imgs[i] = new Asset.image(srcs[i], {
						onload: function(){
							loadImage(i + 1);
						},
						onerror: function(){
							if("function" === $type(error)){
								error(i, imgs[i], imgs);
							}
						}
					});
				} else{
					//complete(imgs);
				}
			}
			loadImage(0);
		}
	//	loadImagesConsecutively(imageURLs[0]);
		//loadImagesConsecutively(thumbURLs);
		loadImagesConsecutively(imageURLs);
		
		
		/*
		new Asset.images(thumbURLs, {
		    onComplete: function(){
			    if(gallery.prefetching == 'all') {
			    
					new Asset.images(imageURLs[i], {
					    onComplete: function(){
							// andrew edit
							var picsLoaded = true;
							alert ('Pics have loaded');
							// end andrew edit
					    }
					});
				}
		    }
		});
		*/
		
	},	
	createLayout: function() {
		var menuLayout = '<div id="imagoThumbMenu"><div id="imagoThumbnailsContainer"></div></div>';
	//	var menuLayout = '<div id="imagoThumbMenu"><h3 id="imagoGalleryCaption"></h3></div>';
		var layout = '';
		if (this.menuDivPosition == 'top') {
			layout = layout + menuLayout;
		}
		layout = layout +
			'<div id="imagoFrame">' +
			'<div id="projectTitle"></div>' +
			'<p id="imagoCurrentImageCaption"></p>' +
			'<div id="imagoCurrentImageMeta" ></div>' + 
			'<div id="imagoCurrentImageLoadingDiv"></div>' +
			'<a id="imagoError">Gallery definition or Gallery server not available.</a>' +
			'<div id="imagoCurrentImageDiv">' +
			'<div id="imagoCurrentImageLoadingDiv" ></div>' +
			'</div>' +
			'<h3 id="imagoGalleryCaption" ></h3>' + 
			'</div>';
		 layout = layout +
			'<div id="imagoLoadingDiv"></div>';

		ElementHelper.setInnerHTML('imagogallery', layout);
	}
});

var GalleryLoader = new Class({
    initialize: function(galleryFileName, baseURL, albumName){
		this.galleryFileName= galleryFileName;
		this.baseURL= baseURL;
		this.albumName = albumName;
    },
    load: function() {
    	try {
	    	 ElementHelper.show('imagoLoadingDiv');
			 ElementHelper.setOpacity('imagoLoadingDiv', 0.5);
			this.specialLoading();
    	} catch(e) {
    		this.error("Can't load the config");
		}
    },
    finished: function() {  
   		gallery.showGallery();
//   		gallery.switchImage();
   		//alert('DONE');
    },
    error: function(msg) {
    	$('imagoError').setText(msg);
    	ElementHelper.show('imagoError');
    	 ElementHelper.hide('imagoLoadingDiv');
    },
    specialLoading: function() {
        this.albumBaseURL = "";
        if (this.baseURL != null) {
	        this.albumBaseURL = this.baseURL + "/";
        }
		if (this.albumName != null) {
			this.albumBaseURL = this.albumBaseURL + this.albumName + "/";
		}
		var myAjax = new Ajax(this.albumBaseURL + this.galleryFileName, {method: 'get', onComplete: function() {
			if(this.response.xml != null) {
				gallery.loader.readGalleryXML(this.response.xml);	
			} else {
				gallery.loader.error("Retrieved empty gallery config");	
			}
		}, onFailure: function(){
			if (this.transport.status == 0 && this.transport.responseXML) {
				//assume we are running local                
                if (window.ie) {
                    // strange workaround for ie
                    var result = this.transport.responseXML;
                    if (!result.documentElement && this.transport.responseStream) {
                        result.load(this.transport.responseStream);
                    }
                }
				gallery.loader.readGalleryXML(this.transport.responseXML);
			} else {
				gallery.loader.error("Can't connect to server and retrieve the gallery config");
                //console.log ("The BaseURL passed on is:"+this.baseURL);	
			}
		}}).request();
    },
    readGalleryXML:function(galleryXML) {
			gallery.thumbnailColumns=getAttributeValue(galleryXML, 'simpleviewerGallery', 'thumbnailColumns');
			gallery.thumbnailRows=getAttributeValue(galleryXML, 'simpleviewerGallery', 'thumbnailRows');
			thumbnailPath=getAttributeValue(galleryXML, 'simpleviewerGallery', 'thumbPath');
			imagePath=getAttributeValue(galleryXML, 'simpleviewerGallery', 'imagePath');
			gallery.thumbsPerPage = gallery.thumbnailRows * gallery.thumbnailColumns;
			gallery.title = getAttributeValue(galleryXML, 'simpleviewerGallery', 'title');
			
		    var images = galleryXML.getElementsByTagName('image');
			for (var i=0;i<images.length;i++) {
			
			
				// Change Meta info items here			
				title = getNodeValue(images[i], 'title');
				if (title == null) {
					title = "&nbsp;";
				}
				caption = getNodeValue(images[i], 'caption');
				if (caption == null) {
					caption = "&nbsp;";
				}
				client = getNodeValue(images[i], 'client');
				//console.log( client);
				if (client == null) {
					client = "&nbsp;";
				}
				//andrew!!!!
				var role = getNodeValue(images[i], 'role');
				//console.log(role);
				if (role == null) {
					role = "&nbsp;";
				}
				photographer = getNodeValue(images[i], 'photographer');
				if (photographer == null) {
//					photographer = '';
				}

				// End of Meta section				
								
				var fileName = getNodeValue(images[i], 'filename');
				gallery.addImage(new GalleryImage(fileName, title, caption, client, role, photographer, this.albumBaseURL + thumbnailPath + fileName, this.albumBaseURL + imagePath + fileName));
			}
			gallery.loader.finished();
		}
});

var FlickrLoader = GalleryLoader.extend({
    initialize: function(){
    },
    specialLoading: function() {
    	new MooPix().callFlickrUrl({ method: 'flickr.photos.getRecent', per_page: '15' });
		jsonFlickrApi = function(rsp){
			if (rsp.stat == 'ok' ){
				if (rsp.photos){
					for(var i=0;i <rsp.photos.photo.length; i++) {
						var url = 'http://static.flickr.com/'+rsp.photos.photo[i].server+'/'+rsp.photos.photo[i].id+'_'+rsp.photos.photo[i].secret; 
						gallery.addImage(new GalleryImage(rsp.photos.photo[i].id,rsp.photos.photo[i].title, url +'_s.jpg', url+'.jpg'));
					}
					gallery.title = 'Latest Flickr Photos';
					gallery.loader.finished();
				}
			} else {
				gallery.loader.error("Can't load photos from flickr");
			}
		}
    }
});

var SmugmugLoader = GalleryLoader.extend({
    initialize: function(albumId, showCaptions){
	    this.albumId = albumId;
	    this.showCaptions = showCaptions;
    },
    specialLoading: function() {
	    new MooSmug().callSmugmug({ method: 'smugmug.login.anonymously' });
		jsonSmugmugApi = function(rsp){
				if (rsp.stat == 'ok' ){
					if (rsp.Login){
						gallery.loader.sessionId = rsp.Login.Session.id;
						new MooSmug().callSmugmug({ method: 'smugmug.albums.getInfo', AlbumID: gallery.loader.albumId, SessionID: gallery.loader.sessionId });
					} else if (rsp.Album) {
						gallery.title = rsp.Album.Title;
						new MooSmug().callSmugmug({ method: 'smugmug.images.get', AlbumID: gallery.loader.albumId, Heavy : gallery.loader.showCaptions, SessionID: gallery.loader.sessionId });
					} else if (rsp.Images) {
						for(var i=0;i <rsp.Images.length; i++) {
							var url ='http://smugmug.com/photos/' + rsp.Images[i].id;
							var caption = "";
							if (gallery.loader.showCaptions) {
								caption =rsp.Images[i].Caption;
							}
							gallery.addImage(new GalleryImage(rsp.Images[i].id, caption, url + '-75x75.jpg', url+ '-M.jpg'));
						}					
						gallery.loader.finished();						
					}
				} else {
					gallery.loader.error("Can't load photos from smugmug");
				}
		}
    }
});


//inspired by mooshow
var ImagoElement = new Class({
    initialize: function(){
    
    },
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	getHeight: function(element) {
	   	element = $(element);
	   	return element.offsetHeight; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	},	
	hide: function(element) {
      	element = $(element);
      	element.style.display = 'none';
  	},
  	show: function(element) {
      	element = $(element);
      	element.style.display = 'inline';
  	},
	setOpacity: function(element,opacity) {
    	element = $(element);
    	element.style.opacity = opacity; 
	}
});

var ElementHelper = new ImagoElement();

function getNodeValue(obj,tag) {
	child = obj.getElementsByTagName(tag)[0].firstChild;
	if(child != null) {
		return child.nodeValue;
	} 
	return null;
}

function getAttributeValue(obj,tag, attr) {
	return obj.getElementsByTagName(tag)[0].getAttribute(attr);
}
//inspired by mooshow
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}
//var gallery;
function start() {
	gallery = new Gallery();
	gallery.loader.load();
}

addLoadEvent(start);
