/*
    This file is part of JonDesign's SmoothGallery v2.1beta1.

    JonDesign's SmoothGallery is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    JonDesign's SmoothGallery is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with JonDesign's SmoothGallery; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

    Main Developer: Jonathan Schemoul (JonDesign: http://www.jondesign.net/)
*/

var gallerySet = new Class({
	Extends: gallery,
	initialize: function(element, options) {
		this.setOptions({
			manualSetData: [],
			gallerySelector: "div.galleryElement",
			galleryTitleSelector: "div.nome_nascosto",
			textGallerySelector: '',
			textShowGallerySelector: '',
			textGalleryInfo: '{0} pictures',
			startWithSelector: true,
			/* Changing default options */
			textShowCarousel: '',
			/*textShowCarousel: '{0}/{1} Pictures',*/
			carouselPreloader: false
		});
		this.setOptions(options);
		this.gallerySet = this.options.manualSetData;
		//this.addEvent('onPopulated', this.createGallerySelectorTab.bind(this));
		this.addEvent('onPopulated', this.createGallerySelector.bind(this));
		this.startWithSelectorFn = this.toggleGallerySelector.pass(true, this);
		if (this.options.startWithSelector)
			this.addEvent('onGallerySelectorCreated', this.startWithSelectorFn);
		this.parent(element, this.options);
	},
	populateData: function() {
		options = this.options;
		var data = $A(this.gallerySet);
		this.populateFrom.getElements(options.gallerySelector).each(function (galEl) {
			currentGalArrayPlace = 0;
			galleryDict = {
				title: galEl.getElement(options.galleryTitleSelector).innerHTML,
				elements: []
			}
			galleryDict.elements.extend(this.populateGallery(galEl, 0));
			data.extend([galleryDict]);
			if (this.options.destroyAfterPopulate)
				galEl.dispose();
		}, this);
		this.gallerySet = data;
		this.galleryData = data[0].elements;
		this.currentGallery = 0;
		// visualizzo la descrizione del primo elemento caricato
		document.getElementById('info_realizzazione').innerHTML=this.gallerySet[0].title;
		this.fireEvent('onPopulated');
	},
	changeGallery: function(number)
	{
		if (number!=this.currentGallery)
		{
			this.changeData(this.gallerySet[number].elements);
			this.maxIter = this.gallerySet[number].elements.length;
			this.currentGallery = number;
			//this.gallerySelectorBtn.set('html', this.gallerySet[number].title);
			//document.getElementById('info_realizzazione').innerHTML=this.gallerySet[number].title;
			this.fireEvent('onGalleryChanged');
		}
		// visualizzo la descrizione dell'elemento cliccato
		document.getElementById('info_realizzazione').innerHTML=this.gallerySet[number].title;
		//this.toggleGallerySelector(true);
	},
	/*
	createGallerySelectorTab: function() {
		this.gallerySelectorBtn = new Element('a').addClass('gallerySelectorBtn').setProperties({
			title: this.options.textShowGallerySelector
		}).set('html', this.options.textShowGallerySelector).addEvent(
			'click',
			function(){ this.toggleGallerySelector(true); }.bind(this)
		).injectInside(this.galleryElement);
		this.addEvent('onShowCarousel', function(){this.gallerySelectorBtn.setStyle('zIndex', 10)}.bind(this));
		this.addEvent('onCarouselHidden', function(){this.gallerySelectorBtn.setStyle('zIndex', 15)}.bind(this));
	},
	*/
	createGallerySelector: function() {
		this.content = document.getElementById('content');
		this.gallerySelector = new Fx.Morph(
			new Element('div').addClass(
				'gallerySelector'
			).injectInside(
				this.content
			).setStyles({
				/*'display': 'none',
				'opacity': '0'*/
			})
		);
		/*
			this.gallerySelectorTitle = 
			new Element('h2').set('html', 
				this.options.textGallerySelector
			).injectInside(this.gallerySelector.element);
		var gallerySelectorHeight = this.galleryElement.offsetHeight - 50 - 10 - 2;
		*/
		/* navigazione: creazione lista per frecce di scorrimento */
		this.navigation =	new Element('ul').injectInside(this.gallerySelector.element);
		this.navigation.setAttribute('id','navigation');
		this.liLeft = new Element('li').injectInside(this.navigation);
		this.aLeft = new Element('a').injectInside(this.liLeft);
		this.aLeft.setAttribute('id','scroll_left');
		this.aLeft.setAttribute('href','#');
		this.aLeft.set('html', 'Left');
		this.liRight = new Element('li').injectInside(this.navigation);
		this.aRight = new Element('a').injectInside(this.liRight);
		this.aRight.setAttribute('id','scroll_right');
		this.aRight.setAttribute('href','#');
		this.aRight.set('html', 'Right');
		/* fine navigazione: creazione lista per frecce di scorrimento */

		this.gallerySelectorWrapper = new Fx.Morph(
			new Element('div').addClass(
				'gallerySelectorWrapper'
			).injectInside(this.gallerySelector.element).setStyles({'overflow': 'hidden'})
		);
		
		//this.gallerySelectorWrapper.setAttribute('id','gallerySelectorWrapper');
		
		//this.gallerySelectorWrapper.setAttribute('id','gallerySelectorWrapper');
		//this.gallerySelectorWrapper.setStyle('overflow','hidden');
		this.gallerySelectorInner = new Element('ul').addClass('gallerySelectorInner').injectInside(this.gallerySelectorWrapper.element);
		this.gallerySelectorInner.setAttribute('id', 'gallerySelectorInner');
	
		/*
		this.gallerySelectorWrapper.scroller = new Scroller(this.gallerySelectorWrapper.element, {
			area: 101,
			velocity: 0.3
		}).start();
		*/
		
		this.aLeft.addEvent('click', function() {
		// get the current position of the gallery element
		var gallerySelectorInner = document.getElementById("gallerySelectorInner");
		var x = parseInt(gallerySelectorInner.style.left);
		if (x % 101 == 0) {
		moveSlideshow("gallerySelectorInner",x+101,0,10);
			if (document.getElementById('scroll_right'))
			{
				document.getElementById('scroll_right').setStyle('display','block');
			}
		}

		if (x == 0 || x == -101)
		{
			this.setStyle('display','none');
		}
		return false;
		});

		this.aRight.addEvent('click', function() {
			
		// get the current position of the gallery element
		var gallerySelectorInner = document.getElementById("gallerySelectorInner");
		var li = gallerySelectorInner.getElementsByTagName("li");
		var n_foto = li.length;
			
			//conto quanti elementi ci sono per fermare lo scorrimento verso sinistra (tot - i primi 6), e li trasformo in numero negativo
			var n_foto = li.length-6;
			n_foto = n_foto-(n_foto*2);
			
			var x = parseInt(gallerySelectorInner.style.left);

			if (x % 101 == 0 && x>n_foto*101) {
			moveSlideshow("gallerySelectorInner",x-101,0,10);
				if (document.getElementById('scroll_left'))
				{
					document.getElementById('scroll_left').setStyle('display','block');
				}
			}
			
			if (x == (n_foto+1)*101)
			{
				this.setStyle('display','none');
			}
		
		return false;
		});
		
		this.createGalleryButtons();
		this.fireEvent('onGallerySelectorCreated');
		},
	
	
		
	createGalleryButtons: function () {
		var galleryButtonWidth = 95;
		this.gallerySet.each(function(galleryItem, index){
			var button = new Element('li').addClass('galleryButton').injectInside(
				this.gallerySelectorInner
			);
			
			galleryItem.button = button;
			var thumbnail = "";
			if (this.options.showCarousel)
				thumbnail = galleryItem.elements[0].thumbnail;
			else
				thumbnail = galleryItem.elements[0].image;
			/*new Element('div').addClass('preview').setStyles(
				'backgroundImage',
				"url('" + thumbnail + "')"
			).injectInside(button);*/
			
			this.img = new Element('img').addClass('preview').injectInside(button);
			this.img.setAttribute('src',thumbnail);
			this.img.addEvents({
				'mouseover': function(myself){
					myself.button.addClass('hover');
				}.pass(galleryItem, this),
				'mouseout': function(myself){
					myself.button.removeClass('hover');
				}.pass(galleryItem, this),
				'click': function(myself, number){
					this.changeGallery.pass(number,this)();
				}.pass([galleryItem, index], this)
			}).setStyle('width', galleryButtonWidth);
			
			/*new Element('h3').set('html', galleryItem.title).injectInside(button);*/
			/*new Element('p').addClass('info').set('html', formatString(this.options.textGalleryInfo, galleryItem.elements.length)).injectInside(button);*/
		}, this);
		//new Element('br').injectInside(this.gallerySelectorInner).setStyle('clear','both');
		/* navigazione: misura orizzontale */
		var innerLi = this.gallerySelectorInner.getElementsByTagName("li");
		var numLi = innerLi.length;
		var innerWidth = numLi * 101;
		this.gallerySelectorInner.setStyle('width', innerWidth+'px');
		/* fine navigazione: misura orizzontale */
		/*navigazione: posizione iniziale */
		this.gallerySelectorInner.setStyle('top',0+'px');
		this.gallerySelectorInner.setStyle('left',0+'px');
		/*navigazione: fine posizione iniziale */
		/* navigazione: se le foto sono meno di 7, disattivo lo scorrimento */
		var gallerySelectorInner = document.getElementById("gallerySelectorInner");
		var li = gallerySelectorInner.getElementsByTagName("li");
		var n_foto = li.length;

		if (n_foto<7) {
		document.getElementById('scroll_left').setStyle('display','none');
		document.getElementById('scroll_right').setStyle('display','none');
		}else{
		// sinistro disattivato	
		document.getElementById('scroll_left').setStyle('display','none');
		}
		/*fine */
	},
	
	
	toggleGallerySelector: function() {
			this.gallerySelector.start({'opacity' : 0.9}).element.setStyle('display','block');
	},
	
	initHistory: function() {
		this.fireEvent('onHistoryInit');
		this.historyKey = this.galleryElement.id + '-gallery';
		if (this.options.customHistoryKey)
			this.historyKey = this.options.customHistoryKey();
		this.history = new History.Route({
			defaults: [1,1],
			pattern: this.historyKey + '\\((\\d+)\\)-picture\\((\\d+)\\)',
			generate: function(values) {
				return [this.historyKey, '(', values[0], ')', '-picture','(', values[1], ')'].join('');
			}.bind(this),
			onMatch: function(values, defaults) {
				this.changeGallery.pass(parseInt(values[0]) - 1, this).delay(10);
				if(this.gallerySelector)
					this.toggleGallerySelector.pass(true, this).delay(500);
				this.goTo.pass(parseInt(values[1]) - 1, this).delay(101);
			}.bind(this)
		});
		updateHistory = function(){
			this.history.setValues([this.currentGallery + 1, this.currentIter + 1]);
			this.history.defaults=[this.currentGallery + 1, this.currentIter + 1];
		}.bind(this);		
		
		this.addEvent('onChanged', updateHistory);
		this.addEvent('onGalleryChanged', updateHistory);
		this.fireEvent('onHistoryInited');
	},
	

	moveSlideshow: function(elementID,final_x,final_y,interval) {
		
		if (!document.getElementById) return false;
	    
	    // if the element does not exist we have nothing to do
	    if (!document.getElementById(elementID)) return false;
	    var elem = document.getElementById(elementID);
	    
	    // the slideshow events stack up and the animation is not smooth anymore
	    if (elem.movement) {
		clearTimeout(elem.movement);
	    }
	    
	    // current slideshow position
	    var xpos = parseInt(elem.style.left);
	    var ypos = parseInt(elem.style.top);
	    if (xpos == final_x && ypos == final_y) {
		return true;
	    }
	    
	    // restrict moving to white area
	    if (final_x <= -elem.max_x) {
		final_x = -elem.max_x;
	    }
	    if (final_x > 0) {
		    final_x = 0;
	    }
    
	    // animation bit (taken from the book DOM Scripting by Jeremy Keith)
	    if (xpos < final_x) {
		var dist = Math.ceil((final_x - xpos)/10);
		xpos = xpos + dist;
	    }
	    if (xpos > final_x) {
		var dist = Math.ceil((xpos - final_x)/10);
		xpos = xpos - dist;
	    }
	  
	    // again, restrict showing white area
	    if (xpos <= -elem.max_x) {
		    xpos = -elem.max_x;
	    }
	    if (xpos > 0) {
		    xpos = 0;
	    }
	    
	    // fix the elements position
	    elem.style.left = xpos + "px";
	    elem.style.top = ypos + "px";
	    
	    // and set up the event again after an interval
	    var repeat = "moveSlideshow('"+elementID+"',"+final_x+","+final_y+","+interval+")";
	    elem.movement = setTimeout(repeat,interval);
	}
	
	


	
});
