/**
 * @author Vladimir Cvetic over @ ferdinand.rs
 * @version 0.32
 * @date 22.12.2008
 * @requirements Prototype >= 1.6.0.3 && Scriptaculous >= 1.8.2
 * Real requeriments: Prototype >= 1.6.0.1 && Scriptaculous >= 1.8.1
 * @url http://ferdinand.rs/javascript/
 * @notes
 * fixed several IE6+ issues.
 * added .Pause() method.
 * added .CurrentSlide() method.
 * added .SlideCount() method.
**/
if (window.Ferdinand == undefined) Ferdinand = {};
Ferdinand.Slider = Class.create({
	REQUIRED_PROTOTYPE: '1.6.0.1',
	REQUIRED_SCRIPTACULOUS: '1.8.1',
	initialize: function(element, jsonbanners,tambotones,menuIzquierda, options) {
		//this.Requirements();

		Event.observe( document, 'unload', Event.unloadCache );
	
		element = $( element );
		this.element = element;
		this.botones = new Array();
		this.buttonselected=0;
		this.current_key=0;
		this.ispaused=false;
		this.jsonbanners=jsonbanners;
		this.tambotones=tambotones;
		this.alturaBotones="17px";

		// Alineamiento de los botones
		if (menuIzquierda == true || menuIzquierda == 1)
			this.menuIzquierda=true;
		else
			this.menuIzquierda=false;

		// --- Initial Json ---
		this.items = this.jsonbanners;
		
		// Google Analytics inicial
		for (var c=0; c<jsonbanners.length;c++)
		{
			googleAnalytics('/banners/Impresion/' + jsonbanners[c].nombre);
		}

		this.slide_count = this.items.length;

		this.options = options;
		this.options = Object.extend({
				effectDuration: 0.6,
				transitionDuration: 0.6,
				timeout:3500, 
				opacity:null, /*null for transparent png or value from 0 to 1 for css opacity*/
				background:'/webektest/imgs/iconos/banner_slider/background.png', /*if opacity is set to null, please provide transparent background image */
				loader: '/webektest/imgs/indicator.gif',
				next: '/webektest/imgs/iconos/banner_slider/next.png',
				previous: '/webektest/imgs/iconos/banner_slider/previous.png',
				active: '/webektest/imgs/iconos/banner_slider/activo.jpg',
				noactive: '/webektest/imgs/iconos/banner_slider/noactivo.jpg',
				pause: '/webektest/imgs/iconos/banner_slider/pausa.jpg',
				play: '/webektest/imgs/iconos/banner_slider/play.jpg',
				transparent: '/webektest/imgs/px.gif',
				type: 'json', /*placeholder for future releases*/
				url: this.jsonbanners,
				titleClass: 'title',
				excerptClass: 'tekst',
				wrapbg: '#000000',
				containerClass: 'ferdinand-slider'
			}, options || {});
			
		this.PNGFix();	

			
		if (this.options.containerClass!=null && this.options.containerClass!=false && this.options.containerClass!='') {
			this.element.setAttribute('class',this.options.containerClass);	
			this.element.setAttribute('className',this.options.containerClass);	
		}
		this.CreateSubElements();
	},
	PNGFix: function () {
		var version = parseFloat(navigator.appVersion.split('MSIE')[1]);
		if ((version >= 5.5) && (version < 7) && (document.body.filters)) {
			if (document.getElementsByClassName('ie-fix-opacity') == undefined)
				return;

			document.getElementsByClassName('ie-fix-opacity').each(function(poElement){
				// if IE5.5+ on win32, then display PNGs with AlphaImageLoader
				var cBGImg = poElement.currentStyle.backgroundImage;
				var cImage = cBGImg.substring(cBGImg.indexOf('"') + 1, cBGImg.lastIndexOf('"'));
						
				poElement.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + cImage + "', sizingMethod='scale')";
				poElement.style.backgroundImage = "none";
			});
		}
	},

	Requirements: function ()
	{
		function convertVersionString(versionString) {
	      var v = versionString.replace(/_.*|\./g, '');
	      v = parseInt(v + '0'.times(4-v.length));
	      return versionString.indexOf('_') > -1 ? v-1 : v;
	    }		

	    if ((typeof Scriptaculous == 'undefined') ||
			(typeof Effect == 'undefined') ||
			(convertVersionString(Scriptaculous.Version) <
			convertVersionString(this.REQUIRED_SCRIPTACULOUS))) {
				throw ("nSticker requires the Scriptaculous JavaScript framework >= " +
				this.REQUIRED_SCRIPTACULOUS);
		}
	    if ((typeof Prototype == 'undefined') ||
			(typeof Element == 'undefined') ||
			(typeof Element.Methods == 'undefined') ||
			(convertVersionString(Prototype.Version) <
			convertVersionString(this.REQUIRED_PROTOTYPE))) {
				throw ("nSticker requires the Prototype JavaScript framework >= " +
				this.REQUIRED_PROTOTYPE);
		}	
	},
	CreateSubElements: function ()
	{
		this.createelementslider();
		//this.loadercreate();
		this.loader_active = false;
		this.GetData();
		this.buttonscreate();
		this.buttonshooks();
	},
	
	createelementslider: function ()
	{
		this.elementoslider = new Element('img');
		this.elementoslider.setStyle({cssFloat: 'none'});
		this.element.appendChild(this.elementoslider);
	},
	
	loadercreate: function () {
		this.loader = new Element('img');
		this.loader.hide();
		this.loader.setAttribute('src',this.options.loader);
		this.element.appendChild(this.loader);
	},

	Next: function () {
		this.Go(this.current_key+1);		
	},
	Prev: function () {
		this.Go(this.current_key-1);		
	},
	Go: function (num) {
		if (this.loader_active==true) {
			return false;
		}
		if (this.timeoutInPlace)
		{
			clearTimeout(this.timeoutInPlace);
		}
		this.ShowWarp(num);		
	},	
	Pause: function () {
		clearTimeout(this.timeoutInPlace);
	},
	SlideCount: function () {
		return this.slide_count;
	},
	CurrentSlide: function () {
		return this.current_key;
	},
	navhide: function () {
		this.prevlink.hide();
		this.nextlink.hide();
	},
	
	GetData: function () {
		this.ShowWarp(0);
	},

	ShowWarp: function (key) {
		var itemkey = key+1;
		this.current_key = key;
		var item = this.items[key];
		this.no_next = false;
		this.no_prev = false;
		
		if (key==this.items.length) {
			this.no_next = true;
			this.GetData();
			return;
		}
		if (key==0) {
			this.no_prev = true;
		}
		
		if (this.tempcontent!=null)
		{
			this.tempcontent.stopObserving('load');
			this.tempcontent=null;
		}

		// Comprobar tipo a crear
		if (item.tipo==1)
		{
			this.tempcontent = new Element('img');
			this.tempcontent.setAttribute('src', item.content);
		}
		else if (item.tipo==2)
		{
			this.tempcontent = new Element('div');
			$(this.tempcontent).update(item.content);
		}
		
		if (item.tipo==2 || this.tempcontent.complete) {
			this.StartTransition(item, itemkey);
		} else {
			this.tempcontent.observe('load', function(){
				 this.StartTransition(item, itemkey);
			}.bindAsEventListener(this));				
		}
	},

	StartTransition: function (item, itemkey) {
				this.tempcontent.hide();
				new Effect.Fade(this.elementoslider, {
					from: 1.0, 
					to: 0.0, 
					duration: 
					this.options.effectDuration,
					afterFinish: function(){
						if (this.tempcontent.width != undefined && this.tempcontent.height != undefined)
						{
							this.element.style.width = this.tempcontent.width+'px';
							this.element.style.height = this.tempcontent.height+'px';
						}

            if (this.element!=null && this.element.firstDescendant()!=null) {
              this.element.firstDescendant().remove();
							var hijo=this.element.firstDescendant();
							hijo=null;
            }
						if (this.elementoslider!=null)
						{
							this.elementoslider.stopObserving('click');
							this.elementoslider=null;
						}
						this.elementoslider = this.tempcontent;
						this.elementoslider.style.cursor="pointer";
						// -- El enlace en toda la imagen
						if (item.url != undefined)
						{
							$(this.elementoslider).observe ("click", function() {
								googleAnalytics('/banners/click/' + item.nombre);

								if (!item.url.startsWith("javascript"))
									window.open (item.url);
								else
									eval(item.url);
							}.bindAsEventListener(this));
						}
						
						this.element.appendChild(this.elementoslider);									
						this.BeginSlide(item, itemkey);
					}.bind(this)});
	},

	BeginSlide: function (item, itemkey)
	{
		new Effect.Appear(this.elementoslider,{ 
						from: 0.0, to: 1.0, 
						duration: this.options.effectDuration,
						afterFinish: function(){	

						if (this.timeoutInPlace)
						{
							clearTimeout(this.timeoutInPlace);
						}

						if (this.ispaused) 
							return;

						this.activatebutton(itemkey-1);
						this.timeoutInPlace = setTimeout(function () { 
								this.ShowWarp(itemkey); 
						}.bind(this), item.timeout);
			}.bind(this)
		});
	},

	Pausar: function() {
		$(this.botones[this.slide_count]).src = this.options.play;
		this.ispaused = true;
		
		this.Pause();
	},

	Play: function () {
		$(this.botones[this.slide_count]).src = this.options.pause;
		this.ispaused = false;

		this.ShowWarp(this.buttonselected+1);
	},

	buttonscreate: function () {

		if (this.menuIzquierda)
			this.divbuttons=new Element ("div", { "id": "div_slider_buttons_" + this.element.id, "style" : "height: " + this.alturaBotones + "; width: " + this.tambotones + "px;" });
		else
			this.divbuttons=new Element ("div", { "id": "div_slider_buttons_" + this.element.id, "style" : "text-align:right; height: " + this.alturaBotones + "; width: " + this.tambotones + "px" });

		$(this.element).insert({Before: this.divbuttons });
		
		for (var i=this.slide_count; i>=0; i--)
		{
			// Separadores (3 px separacion)
			separador = new Element ("img", { "src" : this.options.transparent });
			separador2 = new Element ("img", { "src" : this.options.transparent });
			separador3 = new Element ("img", { "src" : this.options.transparent });
			$(this.divbuttons).insert( {top: separador});
			$(this.divbuttons).insert( {top: separador2});
			$(this.divbuttons).insert( {top: separador3});

			// Imagenes Botones
			this.botones[i]= new Element ("img", { "src" : this.options.noactive, "id" : "slider" + this.element.id + "botones_" + i}); 
			$(this.divbuttons).insert({top: this.botones[i]});
		}
		this.botones[0].src = this.options.active;
		this.botones[this.slide_count].src = this.options.pause;
	},

	buttonshooks: function () {
		for (var i=0; i<this.slide_count; i++)
		{
			this.cual=i;
			$(this.botones[i]).observe('click', function(e) 
			{ 
				var numpartes=Event.element(e).id.split("_").length;
				var cual=Event.element(e).id.split("_")[numpartes-1]*1; 
				this.botones[this.buttonselected].src=this.options.noactive;
				this.buttonselected=cual;
				this.botones[cual].src=this.options.active;

				this.ShowWarp(cual);
				this.Pausar();
			}.bindAsEventListener(this));
		}

		// Play - Pause Buttons
		$(this.botones[this.slide_count]).observe('click', function() 
		{ 
			if (this.ispaused)
				this.Play();
			else
				this.Pausar(); 
		}.bindAsEventListener(this));
	},

	activatebutton: function (newbutton) {
		$(this.botones[this.buttonselected]).src=this.options.noactive;
		this.buttonselected=newbutton;
		$(this.botones[newbutton]).src=this.options.active;
	},

	raton:function(evento){
			evento.element().setStyle({cursor:"move"});
	},

	removeChildSafe: function (el) {
		if (el==undefined || el==null) return;

    //before deleting el, recursively delete all of its children.
		if (el.childNodes!=undefined && el.childNodes!=null)
		{
			for (var i=0;i<el.childNodes.length;i++)
				removeChildSafe(el.childNodes[i]);
		}
    el.parentNode.removeChild(el);
	}
});
