//ccombobox
var Ccombobox = {
	initialize: function(){
		this.handles = document.getElements('#search_categorias,#search_marcas');
		this.blocks = [];

		this.handles.each(function(handle,i){
			this.blocks[i] = handle.addEvents({'click':this.show.pass([i], this)}).getNext().inject(document.body).addEvents({'mouseleave':this.hide.bind(this)});

			var selected = this.blocks[i].getElement('li.active a');
			if(selected){
				handle.getFirst().set('html',selected.get('text'));
			}
		},this);
	},

	show: function(i){
		this.current = i;
		if(this.blocks[i].hasClass('hidden')){
			var pos = this.handles[i].getPosition();
			var incremento_x = Browser.Engine.trident4 ? 1 : 2;
			var incremento_y = Browser.Engine.trident4 ? 17 : 17;
			this.blocks[i].setStyles({'left':(pos.x+incremento_x)+'px','top':(pos.y+incremento_y)+'px'}).removeClass('hidden');
		}else{
			this.hide();
		}
	},

	hide: function(){
		this.blocks[this.current].addClass('hidden');
	}
};
Ccombobox.initialize();

// contacto
var Contacto = {
	initialize: function(){
		this.win = false;

		document.id('navTop_contacto').getFirst().addEvent('click',this.showWin.bindWithEvent(this));
		document.id('navFoot').getLast().addEvent('click',this.showWin.bindWithEvent(this));
		document.getElements('.contact_link').each(function(el){
			el.addEvent('click',this.showWin.bindWithEvent(this));
		},this);
	},

	attributes: {
		nombres: ['text',true,''],
		apellidos: ['text',true,''],
		email: ['email',true,''],
		telefono: ['phone',false,''],
		mensaje: ['text',true,'']
	},

	build: function(){
		this.win = new Element('div',{'id':'contact_win','class':'hidden'}).inject(document.body);
		this.close = new Element('span',{'id':'contact_close'}).addEvent('click',this.hideWin.bind(this)).inject(this.win);
		this.overlay = new Overlay(false,100,{background:'#000',opacity:0.8});

		this.map = {};
		this.map.link = new Element('span',{'id':'map_handle','html':'ver mapa &raquo;','class':'est0'}).addEvent('click',this.toggleMap.bind(this)).inject(this.win);
		this.map.el = new Element('span',{'id':'map_el','class':'hidden'}).inject(this.win);
		this.map.initialized = false;

		this.info = document.id('contact_info').removeClass('hidden').inject(this.win);

		this.inputs = {};
		for(var k in this.attributes){
			switch(k){
				case 'mensaje':
					this.inputs[k] = new Element('textarea');
					break;
				default:
					this.inputs[k] = new Element('input');
			}
			this.inputs[k].set({'class': 'input','id': 'contact_input_'+k,'value': this.attributes[k][2]}).inject(this.win);
		}

		this.button = new Element('button',{'class':'input'}).set('html','&nbsp;').addEvent('click',this.send.bind(this)).inject(this.win);

		this.displayWin();
	},
	
	showMap: function(){
		if(!this.map.initialized){
			this.map.initialized = true;

			var myLatlng = new google.maps.LatLng(-12.116109,-77.041146);
			var myOptions = {zoom:16,center:myLatlng,mapTypeId:google.maps.MapTypeId.ROADMAP,disableDefaultUI:true};
			var map = new google.maps.Map(this.map.el, myOptions);
			var contentString = '<p>Hola <strong>mapa</strong> punto.</p>';
			var infowindow = new google.maps.InfoWindow({content:this.info.get('html')});
			var marker = new google.maps.Marker({position: myLatlng,map:map,title:'Uluru (Ayers Rock)'});
			google.maps.event.addListener(marker,'click',function(){infowindow.open(map,marker);});
			infowindow.open(map,marker);
		}
		this.win.addClass('cw_map');
		this.map.link.set('html','&laquo; ocultar mapa').removeClass('est0').addClass('est1');
		this.map.el.removeClass('hidden');
	},

	hideMap: function(){
		this.win.removeClass('cw_map');
		this.map.link.set('html','ver mapa &raquo;').removeClass('est1').addClass('est0');
		this.map.el.addClass('hidden');
	},

	toggleMap: function(){
		if(this.map.el.hasClass('hidden')){
			this.showMap();
		}else{
			this.hideMap();
		}
	},

	send: function(){
		if(this.checkData()){
			this.hideWin();
			Loading.show();
			this.request = new Request({url:BASE.ajax+'contacto.ajax',onSuccess:this.onComplete.bind(this),onFailure:onError});
			this.request.send({data:'action=Enviar&data='+encodeURIComponent(JSON.encode(this.data))});
		}else{
			alert('Debe llenar correctamente los campos solicitados.\nLos campos con (*) son obligatorios');
		}
	},

	onComplete: function(response){
		if(response=='true'){
			Loading.set('Su mensaje se ha enviado correctamente!','success');
			Loading.hide.delay(3000,Loading);
		}else{
			Loading.set('Error!','error');
		}
	},

	checkData: function(){
		this.data = {};
		for(var k in this.inputs){
			var value = this.data[k] = this.inputs[k].value = this.inputs[k].value.trim();
			var attr = this.attributes[k];
			if((value=='' || value==attr[2]) && attr[1]){
				return false;
			}
			if(!value.test(iRules[attr[0]].regx)){
				return false;
			}
		}
		return true;
	},

	displayWin: function(){
		if(!this.win){
			this.build();
		}else{
			this.overlay.show();

			this.win.setStyle('top',(document.getScroll().y+64)+'px').removeClass('hidden');
		}
	},

	showWin: function(e){
		new Event(e).stop();
		this.displayWin();
	},

	hideWin: function(){
		this.win.addClass('hidden');
		this.overlay.hide();
	}
};
Contacto.initialize();

var Headers = {
	initialize: function(){
		this.container = new Element('p').inject(new Element('div',{'id':'headers'}).inject('head'));

		this.items = [{'src':'01'},{'src':'02'},{'src':'03'},{'src':'04'}];

		this.current = false;
		this.walker = false;

		var srcs = [];
		this.items.each(function(item,i){
			srcs[i] = this.items[i].src = BASE.www+'img/headers/header_'+item.src+'.jpg';
		},this);

		this.load(srcs);
	},

	load: function(srcs){
		this.loader = new Asset.images(srcs,{
			onProgress: this.onLoad.bind(this),
			onComplete: this.onLoadAll.bind(this)
		});
	},

	create: function(i){
		this.items[i].el = new Element('span').adopt(new Element('img',{'src':this.items[i].src})).inject(this.container);
	},

	onLoad: function(i){
		if(i==0){
			this.create(0);
		}
	},

	onLoadAll: function(){
		this.items.each(function(item,i){
			if(i>0){
				this.create(i);
			}
		},this);
		delete this.loader;
		this.show(0);
		this.walker = this.next.periodical(5000,this);
	},

	show: function(i){
		this.items.each(function(item,j){
			if(j===i){
				this.items[j].el.setStyles({'z-index':2,'opacity':0,'display':'block'});
			}else if(j===this.current){
				this.items[j].el.setStyles({'z-index':1,'opacity':1,'display':'block'});
			}else{
				this.items[j].el.setStyles({'z-index':0,'opacity':0,'display':'none'});
			}
		},this);

		if(this.current===false){
			this.items[i].el.setStyle('opacity',1);
		}else{
			this.items[i].el.fade('in');
		}

		this.current = i;
	},

	next: function(){
		var i = this.current<this.items.length-1 ? this.current+1 : 0;
		this.show(i);
	}
};
Headers.initialize();

var NavTop = {
	initialize: function(){
		var keys = [];
		for(var k in this.colors){
			keys.push(k);
		}

		this.defaultk = 'home';

		this.container = document.id('navTop');
		this.items = this.container.getFirst().getChildren().associate(keys);

		this.titles = {};
		this.titles_container = new Element('p',{'id':'navTop_title'}).injectAfter(this.container);
		this.writing = false;

		for(var k in this.items){
			this.items[k].addEvents({
				'mouseenter': this.changeColor.pass([k], this),
				'mouseleave': this.restoreColor.bind(this)
			});
			if(this.items[k].hasClass('active')){
				this.defaultk = k;
			}

			var link = this.items[k].getElement('a');
			this.titles[k] = link.get('title');
			link.removeProperty('title');
		}

		this.restoreColor();
	},

	changeColor: function(k){
		$clear(this.writing);
		this.container.setStyle('background-color',this.colors[k]);
		this.titles_container.empty();
		if(!empty(this.titles[k])){
			this.current = {pos:0,total:this.titles[k].length,text:this.titles[k]};
			this.writing = this.write.periodical(20,this);
		}
	},

	restoreColor: function(){
		$clear(this.writing);
		this.container.setStyle('background-color',this.colors[this.defaultk]);
		this.titles_container.set('html',this.titles[this.defaultk]);
	},

	write: function(){
		if(this.current.pos>=this.current.total){
			$clear(this.writing);
		}else{
			this.titles_container.innerHTML += this.current.text.substr(this.current.pos,2);
			this.current.pos += 2;
		}
	}
};

var Busqueda = {
	initialize: function(){
		var ref = document.id('search_productos');
		if(ref){
			this.url = BASE.web+'?s=$';
			this.input = ref.getElement('input').addEvent('keyup',function(e){if(new Event(e).key=='enter'){this.submit();}}.bind(this));
			this.button = ref.getElement('button').addEvent('click',this.submit.bind(this));
		}
	},

	submit: function(){
		var text = this.input.value.clean();
		if(text.test(/[\w\d]{3,}/)){
			var url = this.url.replace('$',text.replace(/\s+/,'+'));
			redirect(url);
		}
	}
};
Busqueda.initialize();

var QuickLogin = {
	attributes: {
		email: ['email',true,'email'],
		clave: ['password',true,'******']
	},

	initialize: function(){
		this.form = document.id('userLogin');
		if(this.form){
			var inputs = this.form.getElements('input');
			this.inputs = inputs.associate(inputs.get('name'));

			$each(this.inputs,function(el,k){
				if(this.attributes[k]){
					el.addEvents({
						'focus': this.checkDefault.pass([k,true], this),
						'blur': this.checkDefault.pass([k,false], this),
						'keyup': function(e){
							var ev = new Event(e);
							if(ev.key=='enter'){
								this.submit();
							}
						}.bindWithEvent(this)
					}).set('value',this.attributes[k][2]);
				}
			},this);

			this.buttons = this.form.getElements('button').associate(['submit']);
			this.buttons.submit.addEvent('click',this.submit.bind(this));

			this.request = new Request({url:BASE.ajax+'usuario.ajax',onSuccess:function(r){this['on'+this.request.action](r);}.bind(this),onFailure:onError});
		}
	},

	checkDefault: function(k,mode){
		var _default = this.attributes[k][2];
		var _value = this.inputs[k].value.clean();
		if(mode){
			if(_value==_default){
				this.inputs[k].value = '';
			}
		}else{
			if(_value==''){
				this.inputs[k].value = _default;
			}
		}
	},

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

	submit: function(){
		if(this.checkForm()){
			var data = [];
			for(var k in this.inputs){
				data.push(k+'='+encodeURIComponent(this.inputs[k].value));
			}
			this.requestSubmit('UserLogin',data.join('&'));
			this.form.disabled = true;
		}
	},

	onUserLogin: function(response){
		switch(response){
			case 'true':
				redirect(this.redirect);
				break;
			case 'false':
				Loading.set('Error! Datos incorrectos','error');
				Loading.hide.delay(2000,Loading);
				break;
			default:
				alert(response);
		}
	},

	checkForm: function(){
		for(var k in this.inputs){
			var value = this.inputs[k].value = this.inputs[k].value.clean();
			var rule = iRules[this.attributes[k][0]];
			if((empty(value) && this.attributes[k][1]) || (!empty(value) && !value.test(rule.regx))){
				alert('Error '+k.toUpperCase()+':\n'+(empty(value)?_jlng.required:rule.msg));
				this.inputs[k].focus();
				return false;
			}
		}
		return true;
	}
};

var SuscribeRegister = {
	initialize: function(){
		this.form = document.id('subscribe');
		if(this.form){
			this.inputs = this.form.getElements('input').associate(['email']);
			this.buttons = this.form.getElements('button').associate(['submit']);
			this.buttons.submit.addEvent('click',this.submitForm.bind(this));
			this.request = new Request({url:BASE.ajax+'usuario.ajax',onFailure:onError,onSuccess:this.onComplete.bind(this)});
		}
	},

	submitForm: function(){
		if(this.checkForm()){
			Loading.show();
			this.request.send({data:'action=QuickRegister&lng='+LNG.code+'&email='+this.inputs.email.value});
		}
	},

	onComplete: function(response){
		if(response=='true'){
			this.inputs.email.value = '';
			Loading.set('Se suscribió correctamente.','success');
			Loading.hide.delay(3000,Loading);
		}else{
			Loading.set('Error!','error');
		}
	},

	checkForm: function(){
		if(!this.inputs.email.value.test(iRules.email.regx)){
			alert('Debe ingresar un email válido');
			this.inputs.email.focus();
			return false;
		}
		return true;
	}
};

var Reloj = {
	initialize: function(){
		this.el = document.id('pageDate');
		this.date = new Date(this.now[0],this.now[1]-1,this.now[2],this.now[3]-7,this.now[4],this.now[5]);
		this.walker = this.walk.periodical(1000,this);
	},

	fill: function(n){
		return n < 10 ? '0'+n : n;
	},

	walk: function(){
		this.date.setSeconds(this.date.getSeconds()+1);
		this.el.innerHTML =
			this.fill(this.date.getDate())+'.'+
			this.fill(this.date.getMonth()+1)+'.'+
			this.date.getFullYear()+' - '+
			this.fill(this.date.getHours())+':'+
			this.fill(this.date.getMinutes())+':'+
			this.fill(this.date.getSeconds())+' hrs';
	}
};

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

	//navCat
	var navCat = document.id('navCat');
	if(navCat){
		var navCat_active = navCat.getElement('a.active');
		if(navCat_active){
			var parent = navCat_active.getParent().getParent().getPrevious();
			while(parent.get('tag')=='a'){
				parent.addClass('more selected');
				parent.getNext().removeClass('hidden');
				parent = parent.getParent().getParent().getPrevious();
			}
			var subblock = navCat_active.getNext();
			if(subblock){
				subblock.removeClass('hidden');
			}
		}
	}

	//home flash banners
	var homeBanners = document.id('banner_top_flash');
	if(homeBanners){
		var $m = jQuery.noConflict();
		$m('#banner_top_flash').nivoSlider({
    directionNav: false ,
    controlNav:false,
    effect:"fade"   
  	});
		/*new Swiff(BASE.www+'img/banners/rotator.swf',{
			width: 750,
			height: 180,
			container: homeBanners,
			vars: {
				xmlPath: BASE.www+'img/banners/superior.xml',
				menu: 'false'
			}
		});*/
	}

	//suscribir boletin - quick register
	SuscribeRegister.initialize();

	//thumb preview
	new ImagesPreview(document.getElements('div.pprods p.image img,table.products_list a.image img'),{className:'productImagePreview',replace:['/thumb','']});
})();
