var Banners = {
	init: function(){
		var count = 0;
		this.delay = 5000;
		this.interval = 60000;
		this.groups = [];
		if($type(this.items) != 'array'){
			for(var g in this.items){
				if(g != 's2'){
					this.groups[g] = {};
					this.groups[g].dimensiones = {'width':this.items[g][0].dimensiones[0]+'px','height':this.items[g][0].dimensiones[1]+'px'};
					this.groups[g].container = $('banner'+g).setStyles(this.groups[g].dimensiones).empty();
					this.groups[g].link = new Element('span',{'class':'link'}).setStyles(this.groups[g].dimensiones).addEvent('click',this.click.bind(this,[g])).inject(this.groups[g].container);
					this.groups[g].el = new Element('span').inject(this.groups[g].container);
					this.groups[g].request = new Request({url:BASE.www+'banners.ajax',onSuccess:this.onClick.bind(this)});
					this.groups[g].current = 0;
					this.putBanner(g,0);
					if(this.items[g].length>1){
						this.groups[g].link.addEvents({'mouseenter':this.stop.bind(this,[g]),'mouseleave':this.play.bind(this,[g])});
						this.start.delay(count*this.delay,this,g);
						count++;
					}
				}
			}
		}
	},

	start: function(g){
		this.play(g);
	},

	putBanner: function(g,i){
		var src = BASE.www+'img/banners/'+this.items[g][i].imagen;
		this.groups[g].link.set('href',this.items[g][i].href);
		if(fileExt(this.items[g][i].imagen)=='swf'){
			this.groups[g].el = new Swiff(src,{'width':this.groups[g].dimensiones.width.toInt(),'height':this.groups[g].dimensiones.height.toInt(),'params':{'scale':'exactfit'}}).replaces(this.groups[g].el);
		}else{
			this.groups[g].el = new Element('img',{src:src}).setStyles(this.groups[g].dimensiones).replaces(this.groups[g].el);
		}
		this.groups[g].request.action = 'update';
		this.groups[g].request.send({data:'action=UpdateAcceso&id='+this.items[g][i].id+'&accesos='+this.items[g][i].accesos});
	},

	walk: function(g){
		this.groups[g].current += this.groups[g].current+1<this.items[g].length ? 1 : -this.groups[g].current;
		var item = this.items[g][this.groups[g].current];
		if(!item.disabled && (item.limite<1 || item.accesos<item.limite)){
			this.putBanner(g,this.groups[g].current);
			item.accesos += 1;
		}else if(item.limite>0 && item.accesos==item.limite){
			this.items[g][this.groups[g].current].disabled = true;
			if(this.count(g)>1){
				this.walk(g);
			}
		}
	},

	count: function(g){
		var counter = 0;
		for(var i=0;i<this.items[g].length;i++){
			if(!this.items[g][i].disabled){
				counter++;
			}
		}
		return counter;
	},

	play: function(g){
		this.groups[g].timer = this.walk.periodical(this.interval,this,[g]);
	},

	stop: function(g){
		$clear(this.groups[g].timer);
	},

	click: function(g){
		Loading.show();
		this.stop(g);
		var item = this.items[g][this.groups[g].current];
		this.groups[g].request.cancel();
		this.groups[g].request.action = 'click';
		this.groups[g].request.send({data:'action=UpdateClick&id='+item.id+'&group='+g});
	},

	onClick: function(r){
		if(r!='true' && r!='false' && this.groups[r]){
			var href = this.items[r][this.groups[r].current].href;
			if(href.substr(0,4)=='http'){
				window.location = href;
			}else{
				if(href.substr(0,1)=='/'){
					href = href.substr(1);
				}
				window.location = BASE.www+href;
			}
		}
	}
};

var SendToFriend = {
	init: function(){
		this.validation = {
			nombre1: ['name',true],
			email1: ['email',true],
			nombre2: ['name',true],
			email2: ['email',true],
			mensaje: ['content',false]
		};

		this.buttons = {link:document.getElement('#aclinks .email')};

		if(this.buttons.link){
			this.tip = new Element('div',{'class':'iVtip hidden'}).addEvent('click',this.hideTip.bind(this)).inject(document.body);
			this.win = new sWin({klass:'window ws',overlay:$('body'),draggable:true}).setTitle('Enviar a un amigo','icon email');
			this.request = new Request({url:BASE.web+'sendfriend.ajax',onSuccess:function(r){if(this['on'+this.request.action]){this['on'+this.request.action](r);}}.bind(this),onFailure:onError});
			this.buildForm();

			this.buttons.link.addEvent('click',this.showForm.bind(this));
		}
	},

	requestSubmit: function(action,data){
		Loading.show();
		this.request.action = action;
		this.request.send({data:'action='+action+'&'+data});
	},

	buildForm: function(){
		this.inputs = {};
		var form = new Element('div',{'id':'sendFriendForm'}).inject(this.win.content);

		new Element('h3').set('html','Tu nombre: ').inject(form);
		this.inputs.nombre1 = new Element('input',{'type':'text','maxlength':'255','value':usuario_nombre}).inject(new Element('p').inject(form));

		new Element('h3').set('html','Tu email: ').inject(form);
		this.inputs.email1 = new Element('input',{'type':'text','maxlength':'255','value':usuario_email}).inject(new Element('p').inject(form));

		new Element('h3').set('html','Nombre de tu amigo: ').inject(form);
		this.inputs.nombre2 = new Element('input',{'type':'text','maxlength':'255'}).inject(new Element('p').inject(form));

		new Element('h3').set('html','Email de tu amigo: ').inject(form);
		this.inputs.email2 = new Element('input',{'type':'text','maxlength':'255'}).inject(new Element('p').inject(form));

		new Element('h3').set('html','Mensaje: ').inject(form);
		this.inputs.mensaje = new Element('textarea',{rows:4,cols:20}).inject(new Element('p').inject(form));

		this.inputs.nombre1.readOnly = this.inputs.email1.readOnly = loged;

		this.buttons.submit = new Element('button').set('html','Enviar &raquo;').addEvent('click',this.sendMail.bind(this)).inject(new Element('p').inject(form));
	},

	showForm: function(){
		this.win.setPosition(360,300).show();
	},

	hideForm: function(){
		this.win.close();
	},

	sendMail: function(){
		if(this.checkInputs(['nombre1','email1','nombre2','email2'],true)){
			this.hideForm();
			this.data = {url:window.location.href};
			$each(this.validation,function(v,l){
				this.data[l] = this.inputs[l].value;
			},this);
			this.requestSubmit('SendMail','data='+encodeURIComponent(JSON.encode(this.data)));
		}
	},

	checkInputs: function(ls,tip){
		this.hideTip();
		for(var i=0;i<ls.length;i++){
			var value = this.inputs[ls[i]].value = this.inputs[ls[i]].value.trim();
			if((value=='' && this.validation[ls[i]][1]) || (value!='' && !value.test(iRules[this.validation[ls[i]][0]].regx))){
				if(tip){
					this.showTip(this.inputs[ls[i]],(value==''?_lng.required:iRules[this.validation[ls[i]][0]].msg));
				}
				return false;
			}
		}
		return true;
	},

	// TOOL TIP
	showTip: function(input,msg){
		var position = input.getParent().getCoordinates();
		this.tip.set('html','<div><h3>Error!</h3><p>'+msg+'</p></div><div class="foot"></div>').setStyles({'left':(position.right-150)+'px','top':(position.bottom-36)+'px'}).removeClass('hidden');
		input.focus();
	},

	hideTip: function(){
		if(this.tip){
			this.tip.addClass('hidden');
		}
	},

	onSendMail: function(response){
		if(response=='true'){
			Loading.set('Enviado correctamente!','success');
		}else{
			Loading.set('No se pudo enviar!','success');
		}
		Loading.hide.delay(2000,Loading);
	}
};

var textSizer = {
	initialize: function(){
		this.min = 9;
		this.max = 14;
		this.current = 11;

		if(Cookie.read('textSizer')){
			this.current = Cookie.read('textSizer').toInt();
		}

		this.buttons = document.getElements('#textSizer span').associate(['dec','inc']);
		this.buttons.inc.addEvent('click',this.increase.bind(this));
		this.buttons.dec.addEvent('click',this.decrease.bind(this));

		this.setTextSize();
	},

	setTextSize: function(){
		$('body').setStyle('font-size',this.current+'px');
		Cookie.write('textSizer',this.current);
	},

	increase: function(){
		this.current += 1;
		if(this.current > this.max){
			this.current = this.max;
		}
		this.setTextSize();
	},

	decrease: function(){
		this.current -= 1;
		if(this.current < this.min){
			this.current = this.min;
		}
		this.setTextSize();
	}
};

window.addEvent('domready',function(){
	// imprimir pagina
	var printlink = document.getElement('#aclinks .print');
	if(printlink){
		printlink.addEvent('click',function(){
			window.print();
		});
	}

	// target _blank
	$$('a.blank').addEvent('click',function(e){
		new Event(e).stop();
		window.open(this.href);
	});

	// busqueda general
	var beforeSearch = function(e){
		new Event(e).stop();
		var input = webSearchButton.getPrevious();
		input.value = input.value.trim();
		if(input.value.length>2){
			webSearchForm.submit();
		}else{
			alert('No se permiten búsquedas de menos de 3 caracteres.');
		}
	};
	var webSearchForm = $('search').getFirst().addEvent('submit',beforeSearch);
	var webSearchButton = webSearchForm.getElement('span').addEvent('click',beforeSearch);

	// busqueda anuncions
	var adsSearchForm = $('busqueda');
	if(adsSearchForm){
		adsSearchForm = adsSearchForm.getElement('form').addEvent('submit',function(e){
			new Event(e).stop();
			var input = this.getElement('input');
			input.value = input.value.trim();
			if(input.value.length>2){
				adsSearchForm.submit();
			}else{
				alert('No se permiten búsquedas de menos de 3 caracteres.');
			}
		});
	}

	// busqueda noticias
	var newsSearchForm = $('side');
	if(newsSearchForm){
		newsSearchForm = newsSearchForm.getElement('form').addEvent('submit',function(e){
			new Event(e).stop();
			var input = this.getElement('input');
			input.value = input.value.trim();
			if(input.value.length>2){
				newsSearchForm.submit();
			}else{
				alert('No se permiten búsquedas de menos de 3 caracteres.');
			}
		});
	}

	
	
	
	// banners
	Banners.init();

	// textSizer
	textSizer.initialize();

	// enviar a amigo
	SendToFriend.init();
});
