/**
* Prototype/Scriptaculous Scrolling/Fading Image Gallery
*
* Version: 1.0
*
**/

var Gallery = Class.create({
	initialize: function(id, defaultImage,json) {
		this.gallery = $(id);
		current = 0;
		this.imageBlock = "";
		//this.json = json;
		totalPanes = 0;
		slideshowTimeout = "";
		this.paginationScrollPos = 0;
		this.newPaginationWidth = 0;
		//this.galleryDefaults = "";
		this.options = {
            imageNum: "imageNumber",
            imagePrev: "imagePrev",
            imageNext: "imageNext"
		}
		
		// Show the first bubble image
		$(json.images[0].thumb_src).show();
		
		var imageBlock = "";
		var paginationBlock = "";
		
		//Build the initial view for the images and get gallery defaults
		json.images.each(function(s, imageCount) {
			totalPanes++;
			//Build image list
			//Check for alt text on image so you don't get 'undefined'
			imageAlt = (json.images[imageCount]['alt'] != "") ? json.images[imageCount]['alt'] : "";
						
			imageBlock+= '<div id="galleryImage'+imageCount+'">';
			if(json.images[imageCount]['href']) imageBlock+= '<a href="'+json.images[imageCount]['href']+'" target="_blank">';
			imageBlock+= '<img src="'+json.images[imageCount]['src']+'" title="'+json.images[imageCount]['alt']+'" alt="'+json.images[imageCount]['alt']+'" />';
			if(json.images[imageCount]['href']) imageBlock+= '</a>';
			imageBlock+= '</div>';
			//Build pagination list
			if(imageCount == 0) { var paginationClass = 'selected' } else { var paginationClass = 'imageNumber'; }
			paginationBlock += '<div class="paginationLink" id="link'+imageCount+'"><a href="#" class="'+paginationClass+'" id="image'+imageCount+'">'+(parseInt(imageCount)+1)+'</a></div>\n';
		});
	
		$('imageContainer').update(imageBlock);
		if(totalPanes > 1) {
			$('galleryPaginationScroller').update(paginationBlock);
		}

		
		this.galleryInitialise(json);
		
		if(totalPanes > 1) {
			this.slideShow(json);
		}
	},
	galleryInitialise: function(json) {
		//Configure the containers for the gallery to be the correct width and height
		//if(json.images.length > 1) {
			$('bottomPanel').setStyle({'height': json.galleryDefaults['bottomPanelHeight']+'px'});
		//} else {
			//$('bottomPanel').hide();	
		//}
		$('imageContainer').setStyle({'width':(json.galleryDefaults['galleryWidth']*totalPanes)+json.galleryDefaults['galleryWidth']+'px'});
		$('galleryContainer').setStyle({'width':json.galleryDefaults['galleryWidth']+'px','height':json.galleryDefaults['galleryHeight']+'px'});
		$('imageOuterContainer').setStyle({'width':json.galleryDefaults['galleryWidth']+'px','height':json.galleryDefaults['galleryHeight']+'px'});
		//$('pagination').setStyle({'max-width':json.galleryDefaults['galleryWidth']+'px','width':json.galleryDefaults['galleryWidth']+'px'});
		
		//Get gallery info
		var clickHandler =  this.clickHandler.bindAsEventListener(this,json);
        this.gallery.observe('click', clickHandler);
		
		//Add galleryType specific style for positioning
		for(var i=0;i<totalPanes;i++) {
			Element.addClassName('galleryImage'+i,json.galleryDefaults['galleryType']+'Image');	
		}
				
		//Add extra styles needed for fading
		if(json.galleryDefaults['galleryType'] == "fade" && totalPanes > 0) {
			Element.removeClassName('galleryImage0','fadeImage');
			Element.addClassName('galleryImage0','fadeImage-initial');
			for(var fadeBuilder=1;fadeBuilder<totalPanes;fadeBuilder++) {
				$('galleryImage'+fadeBuilder).setStyle({display: 'none'});
			}
		}
		
		
		newPaginationWidth = (json.galleryDefaults['paginationCount']*json.galleryDefaults['paginationButtonWidth']);
		var buttonWidth = json.galleryDefaults['paginationButtonWidth'];
		$('galleryPaginationContainer').setStyle('width:'+newPaginationWidth+'px');
		$('galleryPaginationScroller').select('div.paginationLink').each(function (w) { 
			w.setStyle({'width': buttonWidth+'px' }) ;
		});
		
		
		if ( json.images[0]['title'] != '') {
			$('galleryDescription').update("<h3>"+json.images[0]['title']+"</h3>" + json.images[0]['desc']);
		} else {
			$('galleryDescription').hide();	
		}
	},
	
	clickHandler: function(e,json) {
        var el = e.element();
		if(el.hasClassName(this.options.imageNum)) {
            this.endSlideShow();
			this.changeImage(el,true,json);	
        } else if(el.hasClassName(this.options.imagePrev)) {
			this.endSlideShow();	
			this.prevImage(json);		
		} else if(el.hasClassName(this.options.imageNext)) {
			this.endSlideShow();	
			this.nextImage(json);
		}
    },
	
	changeImage: function(el,getAttr,json) {
		if(getAttr == true) {
			var elementId = el.getAttribute('id');
			var newcurrent = elementId.replace("image","");
		} else {
			var newcurrent = el;
		}
		
		var newImageId = newcurrent;
		var oldXPos = current;
		
		
		if(json.galleryDefaults['galleryType'] == "slide") {
			if(newcurrent > current) {
				new Effect.Move("imageContainer", {
					x: -(newcurrent*json.galleryDefaults['galleryWidth']), 
					duration:json.galleryDefaults['changeSpeed'], 
					delay:0, 
					y: 0, 
					mode: 'absolute', 
					queue: 'front',
					transition: Effect.Transitions.sinoidal
				});
		
			} else if(newcurrent < current) {
				new Effect.Move("imageContainer", {
					x: ((current-newcurrent)*json.galleryDefaults['galleryWidth']), 
					duration:json.galleryDefaults['changeSpeed'], 
					delay:0, 
					y: 0, 
					mode: 'relative', 
					queue: 'front',
					transition: Effect.Transitions.sinoidal
				
				});
			}
		} else if(json.galleryDefaults['galleryType'] == "fade") {
			if(oldXPos != newImageId) {
				$('galleryImage'+newImageId).appear({ duration: json.galleryDefaults['changeSpeed'] });
				$('galleryImage'+oldXPos).fade({ duration: json.galleryDefaults['changeSpeed'] });
			}
		}
		
		//Set new current value
		current = newcurrent;
		
		// Changes the bubbles
		this.changeBubbles(json.images[current].thumb_src);
		
		//Check and change the pagination
		this.changePagination(current,oldXPos,getAttr,false,json);
		//Change the title and description for the image
		this.changeTitle(current,json);
	},
	
	changeBubbles: function (id) {
		
		// Hide all
		$$('.gallery-bubbles img').each( function(k,v) {

			if (k.hasClassName('current')) {
				k.fade({duration:0.9, queue:{scope:'bubbles', position:'start'}});
				$(id).removeClassName('current');
			} else {
				k.hide();
			}
			
		});
		
		// Show the one
		new Effect.Appear($(id), {duration:0.9, queue:{scope:'bubbles', position:'end'}});
		$(id).addClassName('current');
		
	},
	
	prevImage: function(json) {
		if(current > 0 && totalPanes > 0) {
			this.changeImage(parseInt(current)-1,false,json);
		}
	},
	
	nextImage: function(json) {
		if(slideshowTimeout && current == (totalPanes-1)) {
			//current = 0;
			this.changeImage(0,false,json);
			this.changePagination(0,(totalPanes-1),false,true,json);
		} else {
			if(current < (totalPanes-1)) {
				this.changeImage(parseInt(current)+1,false,json);
			} else if(current == (totalPanes-1) && slideshowTimeout) {
				this.changeImage(0,false,json);
				this.changePagination(0,(totalPanes-1),false,false,json);
			}
		}
	},	
	
	changePagination: function(elNum,oldelNum,getAttr,resetPagination,json) {
		//Handle displaying of previous button
		if(current == 0 || totalPanes <= 1) {
			//new Effect.Opacity('galleryPrevButtonContainer', { from:1.0,to:0.3});
			//$('galleryPrevButtonContainer').update(json.galleryDefaults['previousLinkText']);
		} else if((elNum > oldelNum) && elNum > 0) {
			/*if($('galleryPrevButtonContainer').getOpacity() < '0.4') {
				var addPrevLink = new Element('a', { 'class': 'imagePrev', 'href': '#', 'id': 'galleryPrevButton' }).update(json.galleryDefaults['previousLinkText']);
				$('galleryPrevButtonContainer').update(addPrevLink);
				new Effect.Opacity('galleryPrevButtonContainer', { from:0.3,to:1.0});
				
			}/**/
			if(getAttr) {
				//Get the scroll position of the pagination relative to the image number and pagination count
				var paginationNum = 0;
				for(var paginationNumCount=0;paginationNumCount<elNum;paginationNumCount++) {
					paginationNum++;
					if(paginationNum == json.galleryDefaults['paginationCount']) {
						paginationNum = 0;
					}
				}
				this.paginationScrollPos = paginationNum;
			} else {
				if(this.paginationScrollPos < json.galleryDefaults['paginationCount']) {
					this.paginationScrollPos++;
				} else {
					this.paginationScrollPos = json.galleryDefaults['paginationCount'];
				}
			}
		}
		
		//Handle displaying of next button
		if(current == (totalPanes-1) || totalPanes <= 1) {
			//new Effect.Opacity('galleryNextButtonContainer', { from:1.0,to:0.3});
			//$('galleryNextButtonContainer').update(json.galleryDefaults['nextLinkText']);
		} else if((elNum < oldelNum) && elNum < totalPanes) {		
			/*if($('galleryNextButtonContainer').getOpacity() < '0.4') {
				var addNextLink = new Element('a', { 'class': 'imageNext', 'href': '#', 'id': 'galleryNextButton' }).update(json.galleryDefaults['nextLinkText']);
				$('galleryNextButtonContainer').update(addNextLink);
				new Effect.Opacity('galleryNextButtonContainer', { from:0.3,to:1.0});
			}/**/
			if(getAttr) {
				//Get the scroll position of the pagination relative to the image number and pagination count
				var paginationNum = 0;
				for(var paginationNumCount=0;paginationNumCount<elNum;paginationNumCount++) {
					paginationNum++;
					if(paginationNum == json.galleryDefaults['paginationCount']) {
						paginationNum = 0;
					}
				}
				this.paginationScrollPos = paginationNum;
			} else {
				if(this.paginationScrollPos > 0) {
					this.paginationScrollPos--;
				} else {
					this.paginationScrollPos = json.galleryDefaults['paginationCount'];
				}
			}
		}
		
		//Scroll the pagination container
		if(elNum > oldelNum) {
			if(this.paginationScrollPos == json.galleryDefaults['paginationCount']) {
				new Effect.Move("galleryPaginationScroller", {
					x: -((elNum*json.galleryDefaults['paginationButtonWidth'])+10), 
					duration:json.galleryDefaults['changeSpeed'], 
					delay:0, 
					y: 0, 
					mode: 'absolute', 
					queue: 'end',
					transition: Effect.Transitions.sinoidal
				});
			this.paginationScrollPos = 0;
			}
		} else if(elNum < oldelNum) {
			//Reset pagination display if reset is called (when the scroller loops through)
			if(resetPagination == true) { 
				thisPaginationWidth = 0;
				var positionType = 'absolute'; 
			} else { 
				//Fix for scrolling amount if imageNum is double figures
				if(elNum < 8) {
					thisPaginationWidth = (newPaginationWidth+5);
				} else {
					thisPaginationWidth = newPaginationWidth;
				}
				var positionType = 'relative';
			}
			
			if(this.paginationScrollPos == json.galleryDefaults['paginationCount']) {
				new Effect.Move("galleryPaginationScroller", {
					x: parseInt(thisPaginationWidth), 
					duration:json.galleryDefaults['changeSpeed'], 
					delay:0, 
					y: 0, 
					mode: positionType, 
					queue: 'end',
					transition: Effect.Transitions.sinoidal
				});
			this.paginationScrollPos--;
			}
			
			//Reset the pagination scroller if reset is called (when the scroller loops through)
			if(resetPagination == true) {
				this.paginationScrollPos = 0;
			}
			//alert(this.paginationScrollPos);
		}
		
		//Style the selected image number link
		$('galleryPaginationScroller').select('a').each(function (w) { 
			w.removeClassName('selected');
			w.addClassName('imageNumber');
		});
		//$('image'+elNum).removeClassName('imageNumber');
		$('image'+elNum).addClassName('selected');
	},
	
	changeTitle: function(el,json) {
		var title = "";
		var desc = "";
		if(json.images[el]['title']) { title = json.images[el]['title']; }
		if(json.images[el]['desc']) { desc = json.images[el]['desc']; }
		
		if ( title != '') {
			$('galleryDescription').update("<h3>"+title+"</h3>" + desc);
		} else {
			$('galleryDescription').hide();	
		}
	
		/*new Effect.Opacity('galleryDescription', { 
			queue:'front',
			duration: 0.25,
			transition: Effect.Transitions.linear,
			from: 1.0, 
			to: 0.0,
			delay: 0.0,
			afterFinish: function callback() {/**/
	
			//}
		//});
	},
	
	slideShow: function(json) {
		slideshowTimeout = setInterval(function(){gallery.nextImage(json);}, json.galleryDefaults['changeInterval']);	
		
	},
	
	endSlideShow: function() {
		clearInterval(slideshowTimeout);
	}
	
});


document.observe("dom:loaded", function() {
	try {
    	if(jsonObj) {
			gallery = new Gallery("galleryContainer", 1,jsonObj);
		}
	} catch(e) {
      variablename=[];
	}
});




