var nofoc = new Array(115,120,139);
var SliderEx = new Class({
	Extends: Slider,
	set: function(step){
		this.step = step.limit(0, this.options.steps);
		this.fireEvent('onTick', this.toPosition(this.step));
		return this;
    },
	clickedElement: function(event){
		var dir = this.range < 0 ? -1 : 1;
		var position = event.page[this.axis] - this.element.getPosition()[this.axis] - this.half;
		position = position.limit(-this.options.offset, this.full -this.options.offset);
		this.step = Math.round(this.min + dir * this.toStep(position));
		this.checkStep();
		this.fireEvent('onTick', position);
	}
});

Fx.TweenEx = new Class({
	Extends: Fx.Tween,
	render: function(element, property, value){
		this.fireEvent('onMotionChange', value[0].value);
		element.setStyle(property, this.serve(value, this.options.unit));
	}
});

Element.implement({
	reflect: function(arg){
		var i = new Element('img').setProperty('src', arg.src);
		if (Browser.Engine.trident) {
			i.style.filter = 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity=30, style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy='+arg.height+')';
			i.setStyles({'width':'100%', 'height':'100%'});
			return new Element('div').adopt(i);
		} else {
			var can = new Element('canvas').setProperties({'width':arg.width, 'height':arg.height});
			if (can.getContext && !Browser.Engine.webkit419 ) {
				var ctx = can.getContext("2d");
				ctx.save();
				ctx.translate(0,arg.height-1);
				ctx.scale(1,-1);
				ctx.drawImage(i, 0, 0, arg.width, arg.height);
				ctx.restore();
				ctx.globalCompositeOperation = "destination-out";
				ctx.fillStyle = '#000';
				ctx.fillRect(0, arg.height*0.5, arg.width, arg.height);
				var gra = ctx.createLinearGradient(0, 0, 0, arg.height);					
				gra.addColorStop(1, "rgba(255, 255, 255, 1.0)");
				gra.addColorStop(0, "rgba(255, 255, 255, "+(1-0.3)+")");
				ctx.fillStyle = gra;
				ctx.fillRect(0, 0, arg.width, arg.height);
			}
			return can;
		}
	}
});

var NySlide = new Class({

	Implements: [Events, Options],
	
	options: {
		heightRatio: 0.31,
		startIndex: 0,
		interval: 5000,
		factor: 100,
		bgColor: '#ffffff',
		stylePath: 'style.css',
		useCaption: true,
		useResize: false,
		useSlider: true,
		useWindowResize: true,
		useMouseWheel: false,
		useKeyInput: false,
		useViewer: false
	},

	initialize: function(element, options){
		this.NySlide = element;
		this.setOptions(options);
		this.index = this.options.startIndex;
		this.factor = this.options.factor;
		this.isFull = true;
		this.isAutoPlay = false;
		this.isLoading = false;
		
		this.NySlide.addClass('ms').setStyles({
			'overflow':'hidden',
			'background-color':this.options.bgColor,
			'visibility':'hidden',
			'position':'relative'
		});
		
		if(!$chk($('msCSS'))){new Asset.css(this.options.stylePath,{id:'msCSS'});}
		if(this.options.useWindowResize){window.addEvent('resize', this.update.bind(this, true));}
		if(this.options.useMouseWheel){this.NySlide.addEvent('mousewheel', this.wheelTo.bind(this));}
		if(this.options.useKeyInput){document.addEvent('keydown', this.keyTo.bind(this));}
		
		this.getElements(this.NySlide);
	},
	
	getElements: function(el){
		this.master = {'images':[]};
		var els = el.getChildren();	
		if(els.length<=0) return;
		$$(els).each(function(e){
			var hash = $H(e.getElement('img').getProperties('src','title','alt','longdesc'));
			if(e.get('tag') == 'a'){hash.merge(e.getProperties('href','rel','target'));}
			hash = hash.getClean();
			this.master['images'].push(hash);
		}, this);
		this.clearMain();
	},
	
	loadJSON: function(url){
		if(!url || this.isLoading) return;
		this.isLoading = true;
		new Request.JSON({
			onComplete: function(data){
				if($chk(data)){
					this.master = data;
					this.index = this.options.startIndex;
					this.clearMain();
				}
			}.bind(this),
			onFailure: function(){
				this.isLoading = false;
				this.fireEvent('onChancel', 'Estamos en mantenimiento');
			}.bind(this)
		}, this).get(url);
	},
	
	loadHTML: function(url, filter){
		if(!url || !filter || this.isLoading) return;
		this.isLoading = true;
		new Request.HTML({
			onSuccess: function(tree, els, htm){
				this.getElements(new Element('div', {html: htm}).getChildren(filter));
				this.index = this.options.startIndex;
			}.bind(this),
			onFailure: function(){
				this.isLoading = false;
				this.fireEvent('onChancel', 'Estamos en mantenimiento');
			}.bind(this)
		}, this).get(url);
	},
	
	clearMain: function(){
		if(this.nav){
			new Fx.Tween(this.nav, 'bottom', {
				onComplete: function(){
					this.nav.dispose();
					if(this.cap) this.cap.dispose();
					this.NySlide.empty();
					this.createAniObj();
				}.bind(this)
			}).start(-50);
		}
		if(this.cap){this.cap.fade(0);}
		if(!this.nav && !this.cap){
			this.NySlide.empty();
			this.createAniObj();
		}
	},
	
	getNySlideElements: function(key){
		var els = [];
		this.master.images.each(function(el){ 
			els.push(el[key]); 
		});
		return els;
	},
	
	createAniObj: function(){
		this.aniObj = new Element('div').inject(this.NySlide);
		this.aniFx = new Fx.TweenEx(this.aniObj, 'left', {
			transition: Fx.Transitions.Expo.easeOut,
			link: 'cancel',
			duration: 750,
			onMotionChange: this.process.bind(this),
			onStart: this.flowStart.bind(this),
			onComplete: this.flowComplete.bind(this)
		});
		this.addLoader();
	},
	
	addLoader: function(){
		this.NySlide.store('height', 560);
		this.NySlide.addClass('load').setStyle('visibility', 'visible');
		new Fx.Tween(this.NySlide, 'height', {
			duration: 10,
			onComplete: this.preloadImg.bind(this)
		}).start(this.NySlide.retrieve('height'));
	},
	
	preloadImg: function(){
		this.loader = new Element('div').addClass('loader').inject(this.NySlide);
		var imgs = this.getNySlideElements('src');
		this.loadedImages = new Asset.images(imgs, {
		    onComplete: this.loaded.bind(this),
			onProgress: this.createNySlideElement.bind(this)
		});
	},
	
	createNySlideElement: function(counter, index){
		var object = this.getCurrent(index);
		object['width'] = this.loadedImages[index].width;
		object['height'] = this.loadedImages[index].height;

		var div = new Element('div').setStyles({
			'position':'absolute',
			'display':'none',
			'height': 370
		});
		var con = new Element('div').inject(div);
		var img = new Element('img', {
			'src': object.src,
			'styles':{
				'vertical-align':'bottom',
				'width':'100%',
				'height':'100%'
			}
		}).inject(con);

		div.inject(this.NySlide);

		img.addEvent('click', this.clickTo.bind(this, index));
		if(!this.options.useViewer) img.addEvent('dblclick', this.viewCallBack.bind(this, index));

		object['div'] = div;
		object['img'] = img;
		object['con'] = con;
		
		this.loader.set('html');
	},
	
	loaded: function(){
		this.iL = this.master.images.length-1;
		new Fx.Tween(this.loader, 'opacity', {
			duration : 10,
			onComplete: this.createUI.bind(this)
		}).start(0);
	},
	
	createUI: function(){
		this.NySlide.removeClass('load');
		this.loader.dispose();
		if(this.options.useCaption){
			this.cap = new Element('div').addClass('caption').set('opacity',0);
			this.NySlide.adopt(this.cap);
		}			
		if(this.options.useSlider){
			
			this.anterior =  $('anterior');
			this.siguiente = $('siguiente');
			this.logo = $('logo');
			
		}
		this.showUI();
	},
		
	update: function(e){
		if(e) return;
		this.oW = 3000;
		this.sz = this.oW;
		if(this.options.useSlider){	
			this.anterior.addEvent('click', this.prev.bind(this));
			this.siguiente.addEvent('click', this.forward.bind(this));
			this.logo.addEvent('click', this.first.bind(this));
		}
		this.glideTo(this.index);
		this.isLoading = false;
	},
	
	setScreen: function(){
		this.isFull = !this.isFull;
		if(this.isFull){
			this.holder = new Element('div').inject(this.NySlide,'after');
			this.NySlide.wraps(new Element('div').inject(document.body));
			this.NySlide.setStyles({'position':'absolute','z-index':'100','top':'','left':'0','width':window.getSize().x,'height':370});
			if(this.options.useWindowResize){
				this._initResize = this.initResize.bind(this);
				window.addEvent('resize', this._initResize);
			}
		} else {
			this.NySlide.wraps(this.holder);
			delete this.holder;
			window.removeEvent('resize', this._initResize);
			this.NySlide.setStyles({'position':'relative','z-index':'','top':'','left':'','width':'','height':370});
		}
		this.update();
	},
	
	initResize: function(){
		this.NySlide.setStyles({'width':window.getSize().x,'height':370});
		this.update();
	},
	
	getCurrent: function(index){
		return this.master.images[$chk(index) ? index : this.index];
	},
	
	flowStart: $empty,
	
	flowComplete: $empty,
	
	viewCallBack: function(index){
		if(this.index != index) return;
		var el = $H(this.getCurrent());
		var callBackObject = {};
		callBackObject['coords'] = el.img.getCoordinates();
		el.each(function(v, k){
			if($type(v) == 'number' || $type(v) == 'string') callBackObject[k] = v;
		}, this);
		this.fireEvent('onClickView', callBackObject);
	},
	first: function(){
		if(this.index > 0)
		this.clickTo(0);
	},
	prev: function(){
		if(this.index > 0) this.clickTo(this.index-1);
	},
	stop: function(){
		$clear(this.autoPlay);
		this.isAutoPlay = false;
		this.fireEvent('onAutoStop');
	},
	play: function(){
		this.autoPlay = this.auto.periodical(this.options.interval, this);
		this.isAutoPlay = true;
		this.fireEvent('onAutoPlay');
	},
	auto: function(){
		if(this.index < this.iL)
		this.next();
		else if(this.index == this.iL)
		this.clickTo(0);
	},
	forward: function(){
		if(this.index < this.iL)
		this.next();
		else if(this.index == this.iL)
		this.clickTo(0);
	},
	next: function(){
		if(this.index < this.iL) this.clickTo(this.index+1);
	},
	keyTo: function(e){
		e = new Event(e);
		switch (e.code){
			case 37:
				e.stop();
				this.prev();
				break;
			case 39:
				e.stop();
				this.next();
		}
	},
	wheelTo: function(e){
		e = new Event(e).stop();
		var d = e.wheel;
		if(e.preventDefault) e.preventDefault();		
		if(d > 0) this.prev();
		if(d < 0) this.next();
	},
	clickTo: function(index){
		if(this.index == index) return;
		this.aniFx.cancel();
		if(this.sli) this.sli.set(index);
		this.glideTo(index);
	},
	glideTo: function(index){
		var qwe = 0;
		var i=0;
		this.index = index;
		this.foc = nofoc[index];
		for (i=0;i<index;i++)
			{qwe+=nofoc[i];}
		if(this.cap) this.cap.set('html', this.getCurrent().title);
		this.aniFx.start(-qwe);
	},
	
	showUI: function(){
		if(this.cap) this.cap.fade(1);
		this.fireEvent('onStart');
		this.update();
	},

	process: function(x){
		var zI=this.iL,z,W,H,foc=this.foc,f=this.factor,sz=this.sz,oW=this.oW,div;
		var num = 0;
		with (Math) {
			this.master.images.each(function(el){
				div = el.div;
				if(x>-foc*10 && x<foc*10){
					z = 512;
					W = el.width;
					div.setStyle('height', 370 + 'px');
					div.setStyle('width', W + 'px' );
					div.setStyle('top', 147 + 'px' );
					div.setStyle('left', round(((x / z * sz) + sz) - (f * 5.055) / z * sz ) + 'px' ) ;
					div.setStyle('z-index', x < 0 ? zI++ : zI--);
					div.setStyle('display', 'block');
				} else {
					div.setStyle('display', 'none');
				}
				x += el.width / 5.85;
				nofoc[num]= el.width / 5.85;
				num += 1;
				});
		}
	}
});

window.addEvent('domready', function(){
	$$('.NySlideieze').each(function(NySlide){
		new NySlide(NySlide);
	});
});