/*
"SL_SLIDER" module for Prototype-Scriptaculous
Copyright (c) 2008 Siloos s.n.c. - http://www.siloos.it
Authors: Silvio Zennaro & Luca Scarpa
Project page at http://www.siloos.it
***Last update: Aug 26th, 2008***
*/
/** CREAZIONE CLASSI **/
	var SL_SLIDER = Class.create({
		// INIZIALIZZAZIONE OGGETTO
		initialize: function(strcontainer_id, htmltitle) {
			this.maincontainer_id = strcontainer_id;
			this.title = htmltitle;
			this.listOfSections = [];
			this.actuallyShowing = -1;
			this.skipSectionDelay = 7; // in seconds
			this.transitionEffectsDuration = 1; // in seconds
			this.periodicalEx = null;
			this._animating = false;
			
			// Preload
			this.loadedImages = [];
			this.imagesLoaded = 0;
			
			this.onclick_onitems = '_blank'; // {null || _self || _blank}
			this.build();
		},
		
		
		/**
		 * 
		 */
		build: function () {
			var container_el = $(this.maincontainer_id);

			// checking main container			
			if (!container_el) {
				container_el = new Element('div', { 'id': this.maincontainer_id}).update("&nbsp;");
				$(document.body).insert(container_el, { position: 'bottom' });
			}
			
			// adding header
			var header_el = $(this.maincontainer_id+'_header');
			if (!header_el) {
				header_el = new Element('div', { 'id': this.maincontainer_id+'_header'}).update(this.title);
				container_el.insert(header_el, { position: 'bottom' });
			}
			
			// adding content
			var content_el = $(this.maincontainer_id+'_content');
			if (!content_el) {
				content_el = new Element('div', { 'id': this.maincontainer_id+'_content'}).update("&nbsp;");
				container_el.insert(content_el, { position: 'bottom' });
			}
			content_el.observe('mouseenter', function () { this.stop(); }.bind(this));
			content_el.observe('mouseleave', function () { this.restart(); }.bind(this));
			content_el.observe('click', function () { this.manageClickOnItems(); }.bind(this));
			
			// adding description
			var description_el = $(this.maincontainer_id+'_description');
			if (!description_el) {
				description_el = new Element('div', { 'id': this.maincontainer_id+'_description' }).update("&nbsp;");
				container_el.insert(description_el, { position: 'bottom' });
			}  
			description_el.setOpacity(0);

			/*description_el.observe('click', function () { this.manageClickOnItems(); }.bind(this));*/
			
			// adding footer
			var footer_el = $(this.maincontainer_id+'_footer');
			if (!footer_el) {
				footer_el = new Element('div', { 'id': this.maincontainer_id+'_footer'}).update("&nbsp;");
				container_el.insert(footer_el, { position: 'bottom' });
			}
			
			// adding left arrow
			var leftarrow_el = $(this.maincontainer_id+'_leftarrow');
			if (!leftarrow_el) {
				leftarrow_el = new Element('div', { 'id': this.maincontainer_id+'_leftarrow'}).update("&laquo;");
				container_el.insert(leftarrow_el, { position: 'bottom' });
			}
			leftarrow_el.observe('click', function () { this.showPrevItem(); }.bind(this))
						.observe('mouseenter', function () { this.stop(); }.bind(this))
						.observe('mouseleave', function () { this.restart(); }.bind(this));
			
			// adding right arrow
			var rightarrow_el = $(this.maincontainer_id+'_rightarrow');
			if (!rightarrow_el) {
				rightarrow_el = new Element('div', { 'id': this.maincontainer_id+'_rightarrow'}).update("&raquo;");
				container_el.insert(rightarrow_el, { position: 'bottom' });
			}
			rightarrow_el.observe('click', function () { this.showNextItem(false); }.bind(this))
						 .observe('mouseenter', function () { this.stop(); }.bind(this))
						 .observe('mouseleave', function () { this.restart(); }.bind(this));
		},
		
		/**
		 * Metodo che aggiunge un nuovo elemento (oggetto composto da description, url e link)
		 * alla lista di item dell'oggetto corrente
		 * @param {String} description : codice html da visualizzare come description dell'item
		 * @param {String} url : url dell'immagine da visualizzare come sfondo dell'item corrente
		 * @param {String} link: se impostato, l'indirizzo di destinazione che verrà visualizzato al clic dell'elemento
		 */
		addNewElement: function(description, imgurl, link) {		
			this.listOfSections[this.listOfSections.length] = {
				'description': description,
				'url': imgurl,
				'link': (link ? link : '')
			};
		},
		
		clear: function () {
			this.listOfSections = [];
		},
		
		preloadImages: function() {
			for(var i=0; i<this.listOfSections.length; i++){
				this.loadedImages[i] = new Image();
				this.loadedImages[i].onLoad = this.checkPreloadFinished();
				this.loadedImages[i].src = this.listOfSections[i].url;
			}
		},
		
		checkPreloadFinished: function(){
			this.imagesLoaded++;
			if (this.imagesLoaded == this.listOfSections.length) this.firePreloadFinish();
		},
		
		firePreloadFinish: function(){
			this.showNextItem();
			this.restart();
		},
		
		// metodo che fa partire la riproduzione automatica
		start: function () {
			this.preloadImages.bind(this).delay(2);		
		},
	
		restart: function () {
			this.periodicalEx = new PeriodicalExecuter(function() {
				this.showNextItem(true);
			}.bind(this), this.skipSectionDelay); // execute every x seconds
		},
		
		// metodo che ferma la riproduzione automatica
		stop: function () {
			if (this.periodicalEx != null) {
				this.periodicalEx.stop();
			} 
		},
		
		// metodo che sposta la visualizzazione al prossimo item in lista o, se wraparound è impostato a true e non ci sono altri elementi, al primo elemento della lista
		showNextItem: function (wraparound) {
			if (!this._animating) {
				if (this.actuallyShowing < this.listOfSections.length-1 || wraparound) {
					
					this.startChangingTransitions ();
					
					(function () {
						this.actuallyShowing = (this.actuallyShowing < this.listOfSections.length-1 ? this.actuallyShowing+1 : 0);
						
						this.changeToActualItem();
						this.refreshArrowsVisibility();
					}.bind(this).delay(this.transitionEffectsDuration));
					
				}
			}
		},
		
		showPrevItem: function (wraparound) {
			if (!this._animating) {
				if (this.actuallyShowing > 0 || wraparound) {
					
					this.startChangingTransitions ();
					
					(function () {
						this.actuallyShowing = (this.actuallyShowing > 0 ? this.actuallyShowing-1 : this.listOfSections.length-1);
						
						this.changeToActualItem();
						this.refreshArrowsVisibility();
					}.bind(this).delay(this.transitionEffectsDuration));
					
				}
			}
		},
		
		startChangingTransitions: function () {
			
			this._animating = true;
			
			var description_el = $(this.maincontainer_id+'_description');
			var content_el = $(this.maincontainer_id+'_content');

			var fadeInDelay = this.transitionEffectsDuration+0.2;
			content_el.fade({ duration: this.transitionEffectsDuration, from: 1.0, to: 0.001 });
			if (this.actuallyShowing >= 0) { // setting fade out effects
				description_el.fade({ duration: this.transitionEffectsDuration, from: 1.0, to: 0.001 });
			} 
			description_el.fade({ 
				duration: this.transitionEffectsDuration, 
				from: 0.0, 
				to: 1.0, 
				delay: fadeInDelay,
				afterFinish: function () {
					this._animating = false;
				}.bind(this)
			});
			content_el.fade({ duration: this.transitionEffectsDuration, from: 0.0, to: 1.0, delay: fadeInDelay });
				
		},
				
		// metodo che modifica immagine e descrizione  attuali con quelle dell'item attuale
		changeToActualItem: function () {
			var actualItem = this.listOfSections[this.actuallyShowing];
			$(this.maincontainer_id+'_content').setStyle({
				'background': 'url('+actualItem.url+')',
				'cursor': (this.onclick_onitems && actualItem.link != "" ? 'pointer' : 'auto')
			});
			$(this.maincontainer_id+'_description')
				/*.setStyle({'cursor': (this.onclick_onitems && actualItem.link != "" ? 'pointer' : 'auto')})*/
				.update(actualItem.description);
		},
		
		refreshArrowsVisibility: function () {
			// checkin left arrow
			if (this.actuallyShowing == 0) {
				$(this.maincontainer_id+'_leftarrow').setOpacity(0.3);
			} else $(this.maincontainer_id+'_leftarrow').setOpacity(1);
			// checkin right arrow
			if (this.actuallyShowing == this.listOfSections.length-1) {
				$(this.maincontainer_id+'_rightarrow').setOpacity(0.3);
			} else $(this.maincontainer_id+'_rightarrow').setOpacity(1);
		},
		
		manageClickOnItems: function () {
			if (!this._animating && this.onclick_onitems) {
				var actualItem = this.listOfSections[this.actuallyShowing];
				
				if (actualItem.link != "") {
					switch (this.onclick_onitems) {
						case '_blank': 
							window.open(actualItem.link);
						break;
						default: window.location.href = actualItem.link;
					}
					
				}
			}
		}
		
	});