// JavaScript Document


var G = {
	
	imgs : [],
	imgObj : '',
	current : 0,
	loaded: [],
	next : 0,
	
	loadGallery: function(){
		new Request.JSON({
			'url' : $('gallery-load-url').href,
			'method' : 'get',
			onSuccess: function(obj){
				for(i in obj){
					if(obj[i].index != 'yes'){
						G.imgs.push(obj[i]);
					}
				}
				console.log(G);
			}
		}).get();
	},
	
	hideImage: function(){
		var img = $('gallery-image');
		img.set('tween', {onComplete: G.loadImage});
		img.tween('opacity', 0);
	},
	
	showImage: function(){
		
		var img = $('gallery-image');
		img.src = this.src;
		img.alt = G.imgs[G.current].alt;
		if(! G.loaded.contains(this.src) ) G.loaded.push(this.src);
		img.set('tween', {onComplete:$empty});
		img.tween('opacity', 1);
	},
	
	loadImage: function(){
		var src = G.imgs[G.next].src;
		//if(! G.loaded.contains(src) ){
			G.imgObj.src = src;
		//}else{
			//console.log(G.imgs[i]);
			//G.showImage.call(G.imgs[i]);	
		//}
	},
	
	nextImage: function(){
		G.next = G.next + 1;
		if( G.next > (G.imgs.length - 1) )G.next = 0;
		G.hideImage();
	},
	
	previousImage: function(){
		G.next = G.next - 1;
		if( G.next < 0 ) G.next = G.imgs.length - 1;
		G.hideImage();
	},
		
	init: function(){
		G.loadGallery();
		G.imgObj = new Image();
		G.imgObj.onload = G.showImage;
		$('gallery-previous').addEvent('click', G.previousImage);
		$('gallery-next').addEvent('click', G.nextImage);
	}
	
}

window.addEvent('domready', G.init);
