/*
 *  Copyright 2006, 2007 by Jens Boje
 *  Name    : Imago 
 *  Version : 0.4
 *  Author  : Jens Boje (azarai@codeboje.de)
              http://codeboje.de/contact/
	Terms of Use:
			Imago may be used in any kinds of personal and/or commercial projects. 
			Redistributed or reselling to other companies or third parties is prohibited.
			Please ensure that the Imago download link is clearly visible.
*/

var GalleryImage = new Class({
	initialize: function(fileName, title, thumbURL, imageURL) {
		this.fileName = fileName;
		this.title = title;
		this.thumbURL = thumbURL;
		this.imageURL = imageURL;
	},
	getFileName: function() {
		return this.fileName;
	},
	getTitle: function() {
		return this.title;
	},
	getID: function() {
		return 'id_' + this.getFileName();
	},
	getThumbURL: function() {
		return this.thumbURL;
	},
	getImageURL: function() {
		return this.imageURL;
	}	
});

var Gallery = new Class({
	initialize: function() {
		this.prefetching = null;
		this.createLayout();
		this.currentImageDiv = $('imagoCurrentImage');
		this.menuDiv = $('imagoThumbMenu');
		this.images = new Array();
		this.thumbnailColumns="3";
		this.thumbnailRows="4";
		this.lastThumbImageIndex=0;
		this.lastThumbsOnCurrentPage=0;
		this.thumbsPerPage = this.thumbnailRows * this.thumbnailColumns;
		this.title ='';
		this.loader.load();
	},
	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].getTitle());
				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("table");
		var thumbTableBody = new Element("TBODY");		
		 
		thumbTable.setProperty('id', 'imagoCurrentThumbTable');
		thumbTable.setProperty('class', 'imago_currentThumbTable');
		var counter = this.lastThumbImageIndex;
		if (this.lastThumbImageIndex == 0) {
			ElementHelper.hide('imagoNavPrevLink');
		} else {
			ElementHelper.show('imagoNavPrevLink');
		}
		this.lastThumbsOnCurrentPage =0;
		for(i=0;i<this.thumbnailRows;i++) { 
		  var tr = new Element("tr");
		  		for(j=0;j<this.thumbnailColumns;j++) { 
				  var td = new Element("td");
				  if (this.getThumbImage(counter) != null) {
					  td.appendChild(this.getThumbImage(counter));
					  counter++;
					  this.lastThumbsOnCurrentPage++;
					  if(this.images.length>this.thumbsPerPage) {
						  ElementHelper.show('imagoNavNextLink');
					  }
				  } else {
					  ElementHelper.hide('imagoNavNextLink');
				  }
				  tr.appendChild(td);
			 	}
		  thumbTableBody.appendChild(tr);
	 	}
	 	thumbTable.appendChild(thumbTableBody);
	 	this.lastThumbImageIndex = counter;
	 	return thumbTable;
	},
	thumbMenuNext: function() {
		if (this.images.length>this.lastThumbImageIndex) {
			$('imagoCurrentThumbTable').remove();
			this.menuDiv.appendChild(this.getCurrentThumbTable());
		}	
	},
	thumbMenuPrev: function() {
		if(this.lastThumbImageIndex > this.thumbsPerPage) {
			this.lastThumbImageIndex -= (this.lastThumbsOnCurrentPage + this.thumbsPerPage);
			if(this.lastThumbImageIndex<0) {
				this.lastThumbImageIndex=0;
			}
			$('imagoCurrentThumbTable').remove();
			this.menuDiv.appendChild(this.getCurrentThumbTable());
		}	
	},	
	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);
		ElementHelper.hide('imagoNavPrevLink');

		var navNextLink = new Element("a");
		navNextLink.className = 'imago_navNext';
		navNextLink.setProperty('id', 'imagoNavNextLink');
		navNextLink.onclick = this.thumbMenuNext.bind(this);
		this.menuDiv.appendChild(navNextLink);	
		ElementHelper.hide('imagoNavNextLink');
		
		if (this.images.length>this.thumbsPerPage) {
			ElementHelper.show('imagoNavNextLink');
		}
		this.menuDiv.appendChild(this.getCurrentThumbTable());
		if(this.prefetching != null) {
			this.prefetchImages();
		}
		
		var img = new Element("img");
		img.setProperty('src', this.images[0].getImageURL());
		img.setProperty('id', 'imagoCurrentImg');
		img.setProperty('alt', this.images[0].getTitle());
		img.setProperty('title', this.images[0].getTitle());
		if (this.showShoppingCart == 'yes') {
			$('add2cart').setProperty('href', 'javascript:picturetransfer("' + "/" + gallery.albumName + '/' + this.images[0].getFileName() + '");');
		}
		ElementHelper.setInnerHTML('imagoGalleryTitle',this.title);		
		ElementHelper.setInnerHTML('imagoCurrentImageTitle',this.images[0].getTitle());
		this.setCurrentSelection(this.images[0].getID());
		this.currentImageDiv.appendChild(img);
		
		ElementHelper.hide('imagoDivLoading');
	},
	switchImage: function() {
		ElementHelper.show('imagoLoading');
		file = this.getImageURL();
		title = this.getTitle();
		if ($(gallery.getCurrentSelection()) != null) {
			$(gallery.getCurrentSelection()).removeClass('imago_selectedThumb');
		}
		gallery.setCurrentSelection(this.getID());
		var myFx = new Fx.Style('imagoCurrentImg', 'opacity', {duration:750, onComplete: function() {
				oldSrc = $('imagoCurrentImg').getProperty('src');
				$('imagoCurrentImg').setProperty('src', file);
				$('imagoCurrentImg').setProperty('alt', title);
				$('imagoCurrentImg').setProperty('title', title);
				$('imagoCurrentImg').addEvent('load', gallery.fadeIn.bind(this));
				ElementHelper.setInnerHTML('imagoCurrentImageTitle',title);
				if(oldSrc == $('imagoCurrentImg').getProperty('src')) {
					$('imagoCurrentImg').fireEvent('load', null, 0);
				}
		}}).custom(1,0);
	},
	fadeIn: function() {
		
		if (this.showShoppingCart == 'yes') {
			$('add2cart').setProperty('href', 'javascript:picturetransfer("' + "/" + gallery.albumName + '/' + fileName + '");');
		}
		ElementHelper.hide('imagoLoading');
		var myFx = new Fx.Style('imagoCurrentImg', 'opacity', {duration:750}).custom(0,1);
	},	
	getCurrentSelection: function() {
		return this.selection;
	},
	setCurrentSelection: function(selection) {
		this.selection = selection;
		$(this.selection).addClass('imago_selectedThumb');
	},
	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());
		}
		new Asset.images(thumbURLs, {
		    onComplete: function(){
			    if(gallery.prefetching == 'all') {
					new Asset.images(imageURLs, {
					    onComplete: function(){
					    }
					});
				}
		    }
		});
		
	},	
	createLayout: function() {
		eval($('imagogallery').innerHTML);
		var cart = '';
		if (this.showShoppingCart == 'no') {
			cart = '<div class="imago_cart"><a class="imago_cart" id="add2cart"><img src="styles/img/add2cart.gif" alt="Bild bestellen" title="Bild bestellen"/></a><br/><span class="imago_shoppinginfo">' +
			this.orderInfo + '</span></div>'
		} 
		var layout = '' + 
			'<div id="imagoThumbMenu" class="imago_thumbMenu" ><div id="imagoGalleryTitle" class="imago_galleryTitle" ></div></div>' +
			'<div class="imago_frame">' +
			'<div id="imagoCurrentImage" class="imago_currentImage"><img src="styles/img/loading.gif" id="imagoLoading" class="imago_loading" />' +
			'<a id="imagoError" class="imago_error" >Gallery definition or Gallery server not available.</a></div>' +
			'<div class="imago_cititle"><span id="imagoCurrentImageTitle" class="imago_cititle" ></span></div>' + 
			cart + 
			'</div><div id="imagoDivLoading" class="imago_loading"><img src="styles/img/loading.gif" /><br/>loading...</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('imagoDivLoading');
			ElementHelper.setOpacity('imagoDivLoading', 0.5);
			this.specialLoading();
    	} catch(e) {
    		this.error("Can't load the config");
		}
    },
    finished: function() {  
   		gallery.showGallery();
    },
    error: function(msg) {
    	$('imagoError').setText(msg);
    	ElementHelper.show('imagoError');
    	ElementHelper.hide('imagoDivLoading');
    },
    specialLoading: function() {
        var albumBaseURL = "";
        if (this.baseURL != null) {
	        albumBaseURL = this.baseURL + "/";
        }
		if (this.albumName != null) {
			albumBaseURL = albumBaseURL + this.albumName + "/";
		}
		var myAjax = new Ajax(albumBaseURL + this.galleryFileName, {method: 'get', onComplete: function() {
			gallery.thumbnailColumns=getAttributeValue(this.response.xml, 'simpleviewerGallery', 'thumbnailColumns');
			gallery.thumbnailRows=getAttributeValue(this.response.xml, 'simpleviewerGallery', 'thumbnailRows');
			thumbnailPath=getAttributeValue(this.response.xml, 'simpleviewerGallery', 'thumbPath');
			imagePath=getAttributeValue(this.response.xml, 'simpleviewerGallery', 'imagePath');
			gallery.thumbsPerPage = gallery.thumbnailRows * gallery.thumbnailColumns;
			gallery.title = getAttributeValue(this.response.xml, 'simpleviewerGallery', 'title');
			
		    var images = this.response.xml.getElementsByTagName('image');
			for (var i=0;i<images.length;i++) {
				caption = getNodeValue(images[i], 'caption');
				if (caption == null) {
					caption = "&nbsp;";
				}
				var fileName = getNodeValue(images[i], 'filename');
				gallery.addImage(new GalleryImage(fileName,caption, albumBaseURL + thumbnailPath + fileName, albumBaseURL + imagePath + fileName));
			}
			gallery.loader.finished();
		}, onFailure: function(){
			gallery.loader.error("Can't connect to server and retrieve the gallery config");
		}}).request();
    }
});

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");
			}
		}
    }
});

//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();
}

addLoadEvent(start);