var inmoKit = {
	base: function(){
		Dethcuts.compile();
		inmoKit.show_reloj();
		$("#idioma_activo").click(function(){
			$("#lista_idiomas").slideToggle("fast");
			return false;
		});
		$("body").click(function(){
			if(!$("#lista_idiomas").is(":hidden")) $("#lista_idiomas").slideUp();
		});
		$("#lista_idiomas").click(function(event){
			event.stopPropagation();
		});
		$("#top_menu li:has(ul)").hover(function(e){
			$(this).children("span").removeClass('span_sub_menu').addClass("span_sub_menu_hover");
			if($(this).children("ul").is(":hidden")) $(this).children("ul").slideDown("fast");
		}, function(e){
			$(this).children("ul").slideUp("fast", function(){
				$(this).prev("span").removeClass('span_sub_menu_hover').addClass("span_sub_menu");
			});
		});
		$("input[name='operacion']").change(function() {
			inmoKit.componer_buscador($(this).val(), true);
			ajax_buscador.maneja_opciones(IDIOMA, $(this));
		});
		$("#submit_buscador").click(function(){
			$("#frm_buscador").submit();
			return false;
		});
		$("#sl_tipo_alquiler, #sl_tipo, #sl_poblacion").change(function(){
			ajax_buscador.maneja_opciones(IDIOMA, $(this));
		});	
		$("#fav_delete").click(function(){
			Dethcuts.clear();
			$("#chk_fav").attr('disabled', true);
			$("#chk_fav").attr('checked', false);
			return false;
		});

	},
	altominimo: function(){
		if($("#col_herramientas").height() > ($("#altominimo").height()+72)) $("#altominimo").css("height", $("#col_herramientas").height()-72);
	},
	carrusel: function(){
		$('#galeria_thumbs_wrap').tinycarousel({duration:500});
		$("a[rel='galeria']").colorbox({slideshow:true,slideshowSpeed:3000,slideshowAuto:false,opacity:0.8})
	},
	iniciar_buscador: function(){
		$("#fds_operacion input").customInput();
		inmoKit.componer_buscador($("input[name='operacion']:checked").val(), false);
	},
	componer_buscador: function(modo, update_range) {
		switch(modo){
			case 'ZZ' : //compra
				$("#frm_buscador").attr("action", PATHIDIOMA+"comprar/");
				$("#chks_alquiler").hide();
				$("#fds_personas").hide();
				$("#fds_inmueble").show();
				$("#fds_habitaciones").show();
				$("#fds_precio").show();
				$("#fds_superficie").show();
				$("#fds_opciones").show();
				
				//manejamos poblacion/edificio
				$("#fds_poblacion span").text(POBLACION);
				break;
			
			case 'TA' : //alquiler
				$("#frm_buscador").attr("action", PATHIDIOMA+"alquilar/");
				$("#fds_inmueble").hide();
				$("#fds_superficie").hide();
				$("#fds_precio").hide();
				$("#fds_habitaciones").show();
				$("#fds_personas").show();
				$("#fds_opciones").show();
				$("#chks_alquiler").show();

				//manejamos poblacion/edificio
				$("#fds_poblacion span").text(EDIFICIO);				
				break;
				
			case 'TT' : //traspaso	
				$("#frm_buscador").attr("action", PATHIDIOMA+"comprar/");
				$("#fds_opciones").hide();
				$("#fds_habitaciones").hide();
				$("#fds_precio").hide();
				$("#fds_personas").hide();
				$("#fds_superficie").show();
				
				//deschecar todos los chekboxes
				$("input:checkbox").attr("checked", false);
				
				//manejamos poblacion/edificio
				$("#fds_poblacion span").text(POBLACION);
				break;
				
			case 'TR' : //trueque
				$("#frm_buscador").attr("action", PATHIDIOMA+"comprar/");
				$("#chks_alquiler").hide();
				$("#fds_precio").hide();
				$("#fds_personas").hide();		
				$("#fds_habitaciones").show();
				$("#fds_superficie").show();
				$("#fds_opciones").show();
				
				//manejamos poblacion/edificio
				$("#fds_poblacion span").text(POBLACION);					
				break;
		}
		inmoKit.altominimo();
	},
	banner: function(){
		$('#bann').cycle({ 
			fx: 'fade',
			speed: 700, 
			timeout: 4000,
			//pause: 1,
			next: '#banner_next',
			prev: '#banner_prev'
		});	
	},
	show_reloj: function(){
		setInterval(function(){
			var currentTime = new Date();
			var dia = currentTime.getDate();
			if(dia<10) dia = '0' + dia;
			var mes = currentTime.getMonth() + 1;
			if(mes<10) mes = '0' + mes;
			var ano = currentTime.getFullYear();
			var hora = currentTime.getHours();
			if(hora<10) hora = '0' + hora;
			var minuto = currentTime.getMinutes();
			if(minuto<10) minuto = '0' + minuto;
			var segundos = currentTime.getSeconds();
			if(segundos<10) segundos = '0' + segundos;
			var fecha = dia + '/' + mes + '/' + ano + ' ' + hora + ':' + minuto + ':' + segundos;
			$("#top_fecha").text(fecha);	
		}, 1000);
	},
	click_a_detalle: function(el){
		$(el).click(function() {
			var frm = $("#frm_params");
			if(frm){frm.attr('action', $(this).attr('href'));frm.submit();}
			return false;
		});
	},
	getfavoritos: function(){
		if(Dethcuts.valores()!=undefined){
			$("#txtFavoritos").val(Dethcuts.valores());
			$("#chk_fav").removeAttr("disabled");
			$("#chk_fav").attr('checked', true);
		} else {
			$("#chk_fav").attr("disabled", "disabled").removeAttr("checked");
		}		
	},
	click_favoritos: function(id, ref, url){
		$("#lnk_favoritos").click(function(){
			if(Dethcuts.esta_en_favoritos(id)){
				Dethcuts.remove(id);
				$("#lnk_favoritos").text(ADDFAV).effect("bounce", { times:3, distance:9, direction:'right' }, 150);
			} else {
				$(window).scrollTo($(".caja_herramientas").get(2), 2600);
				$(this).effect("transfer", { to: $("#shortcuts") }, 2500, function(){
					Dethcuts.add(id,ref,url);
					$("#lnk_favoritos").text(REMOVEFAV);
				});				
			}
			return false;
		});
	},
	click_herramientas: function(){
		$("#lnk_tools").click(function(){
			$(this).toggleClass("herramientas_up")
			$("#lista_tools").toggle();
			return false;
		});
	}
};
var ajax_buscador = {
	maneja_opciones: function(){
		var el = arguments[1].attr("id");
		var params = 'operacion=' + $('input[name=operacion]:checked').val() + '&tipo_inmueble=' + $('#sl_tipo').val() + '&idioma=' + arguments[0];
		if(el=='sl_poblacion') params += '&poblacion=' + $('#sl_poblacion').val();
		if(el=='sl_tipo_alquiler') params += '&tipo_alquiler=' + $('#sl_tipo_alquiler').val();
		
		$.ajax({
			type: 'GET',
			url: PATH + 'includes_frontend/json-buscador.asp',
			contentType: 'application/json; charset=utf-8',
			dataType: 'json',
			data: params,
			cache: false,
			success: function(data) {
				if(el!='sl_tipo' && el!='sl_poblacion') ajax_buscador.crea_opciones(data.tipos_inmuebles, 'sl_tipo');
				if(el!='sl_poblacion') ajax_buscador.crea_opciones(data.poblaciones, 'sl_poblacion');
				if(el!='sl_situacion') ajax_buscador.crea_opciones(data.situaciones, 'sl_situacion');
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				alert('Error: ' + errorThrown);
			},
			beforeSend: function (XMLHttpRequest) {
				$('#frm_buscador select').each(function(){
					$(this).attr('disabled', 'disabled');
				});
			},
			complete: function (XMLHttpRequest, textStatus) {
				$('#frm_buscador select').each(function(){
					$(this).removeAttr('disabled');
				});
			}
		});
	},
	crea_opciones: function(data, sl_id){
		var el = $('#'+sl_id);
		el.find('option:gt(0)').remove();
		if(data){
			$.each(data, function(i,item){
				el.append($('<option></option>').attr('value',item.v).text(item.t));
			});
		}
	}
};
var tools = {
	number_format: function(a, b, c, d) {
		a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
		e = a + '';
		f = e.split('.');
		if (!f[0]) {f[0] = '0';}
		if (!f[1]) {f[1] = '';}
		if (f[1].length < b) {
			g = f[1];
			for (i=f[1].length + 1; i <= b; i++) {
				g += '0';
			}
			f[1] = g;
		}
		if(d != '' && f[0].length > 3) {
			h = f[0];
			f[0] = '';
			for(j = 3; j < h.length; j+=3) {
				i = h.slice(h.length - j, h.length - j + 3);
				f[0] = d + i +  f[0] + '';
			}
			j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
			f[0] = j + f[0];
		}
		c = (b <= 0) ? '' : c;
		return f[0] + c + f[1];
	}
};
jQuery.fn.slideFadeToggle = function(speed, easing, callback){
  return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
};
jQuery.fn.customInput = function(){
	$(this).each(function(i){	
		if($(this).is('[type=checkbox],[type=radio]')){
			var input = $(this);
			var label = $('label[for='+input.attr('id')+']');
			var inputType = (input.is('[type=checkbox]')) ? 'checkbox' : 'radio';
			var allInputs = $('input[name='+input.attr('name')+']');
			label.hover(
				function(){ 
					if(!input.is(':checked')){ 
						$(this).addClass('hover'); 
					} 
				},
				function(){ $(this).removeClass('hover'); }
			);		
			input.bind('updateState', function(){	
				if (input.is(':checked')) {
					if (input.is(':radio')) {				
						allInputs.each(function(){
							$('label[for='+$(this).attr('id')+']').removeClass('checked');
						});		
					};
					label.addClass('checked');
				} else {
					label.removeClass('checked');
				}
										
			})
			.trigger('updateState')
			.click(function(){ 
				$(this).trigger('updateState'); 
			})
		}
	});
};
var Dethcuts = {
	id : "shortcuts" ,
	rawCuts : "" ,
	extantCuts : "" ,
	name : "" ,
	source : "" ,
	cutsArray : []
}
Dethcuts.add = function(id,name,source) {
	this.rawCuts = unescape(document.cookie);
	if (this.rawCuts.indexOf("dethcuts")>-1) {
		var start = this.rawCuts.indexOf("dethcuts")+9;
		var end = (this.rawCuts.indexOf(";",start)>-1) ? this.rawCuts.indexOf(";",start) : this.rawCuts.length;
		this.extantCuts = this.rawCuts.substring(start,end);
		if (this.extantCuts.indexOf(id)>-1) {
			return;
		} else {
			document.cookie = "dethcuts=" + this.extantCuts + "#" + id + "|" + name + "@" + source + "; expires=Mon, 28 Dec 2020 00:00:00; path=/;";
		}
	} else {
		document.cookie = "dethcuts=" + id + "|" + name + "@" + source + "; expires=Mon, 28 Dec 2020 00:00:00; path=/;";
	}
	this.compile();
}
Dethcuts.remove = function(id){
	this.rawCuts = unescape(document.cookie);
	if (this.rawCuts.indexOf("dethcuts")>-1) {
		var start = this.rawCuts.indexOf("dethcuts")+9;
		var end = (this.rawCuts.indexOf(";",start)>-1) ? this.rawCuts.indexOf(";",start) : this.rawCuts.length;
		this.extantCuts = this.rawCuts.substring(start,end);
		this.cutsArray = this.extantCuts.split("#");
		var temp = "";
		var cont = 0;
		for (i=0;i<this.cutsArray.length;i++){
			var idp = this.cutsArray[i].substring(0,this.cutsArray[i].indexOf("|"));
			var name = this.cutsArray[i].substring(this.cutsArray[i].indexOf("|")+1,this.cutsArray[i].indexOf("@"));
			var src = this.cutsArray[i].substring(this.cutsArray[i].indexOf("@")+1,this.cutsArray[i].length);
			if(idp!=id){
				if(cont>0) temp += "#";
				temp += idp + "|" + name + "@" + src;
				cont += 1;
			}
		}
		if(cont>0){
			temp = "dethcuts=" + temp + "; expires=Mon, 28 Dec 2020 00:00:00; path=/;";
			document.cookie = temp;
			this.compile();
		} else {
			this.clear()
		}
	}
}
Dethcuts.valores = function(){
	this.rawCuts = unescape(document.cookie);
	if (this.rawCuts.indexOf("dethcuts")>-1) {
		var start = this.rawCuts.indexOf("dethcuts")+9;
		var end = (this.rawCuts.indexOf(";",start)>-1) ? this.rawCuts.indexOf(";",start) : this.rawCuts.length;
		this.extantCuts = this.rawCuts.substring(start,end)
		this.cutsArray = this.extantCuts.split("#")
		var temp = "";
		for (i=0;i<this.cutsArray.length;i++) {
			var name = this.cutsArray[i].substring(this.cutsArray[i].indexOf("|")+1,this.cutsArray[i].indexOf("@"));
			temp +=  "##" + name;
		} 
		return temp;
	}
}
Dethcuts.compile = function(){
	this.rawCuts = unescape(document.cookie);
	if (this.rawCuts.indexOf("dethcuts")>-1) {
		var start = this.rawCuts.indexOf("dethcuts")+9;
		var end = (this.rawCuts.indexOf(";",start)>-1) ? this.rawCuts.indexOf(";",start) : this.rawCuts.length;
		this.extantCuts = this.rawCuts.substring(start,end);
		this.cutsArray = this.extantCuts.split("#");
		var temp = "";
		for (i=0;i<this.cutsArray.length;i++){
			var name = this.cutsArray[i].substring(this.cutsArray[i].indexOf("|")+1,this.cutsArray[i].indexOf("@"));
			var src = this.cutsArray[i].substring(this.cutsArray[i].indexOf("@")+1,this.cutsArray[i].length);
			temp += "<a href='" + src + "'>&raquo; " + name + "</a>";
		}
		this.write(temp);
	} else return
}
Dethcuts.esta_en_favoritos = function(id){
	this.rawCuts = unescape(document.cookie);
	if (this.rawCuts.indexOf("dethcuts")>-1) {
		var start = this.rawCuts.indexOf("dethcuts")+9;
		var end = (this.rawCuts.indexOf(";",start)>-1) ? this.rawCuts.indexOf(";",start) : this.rawCuts.length;
		this.extantCuts = this.rawCuts.substring(start,end);
		this.cutsArray = this.extantCuts.split("#");
		for (i=0;i<this.cutsArray.length;i++){
			if(id==this.cutsArray[i].substring(0,this.cutsArray[i].indexOf("|"))) return true;
		}
	}
	return false;
}
Dethcuts.compile_button = function(id){
	if(this.esta_en_favoritos(id)){
		document.getElementById("lnk_favoritos").innerHTML = REMOVEFAV;
	}
}
Dethcuts.write = function(str){
	document.getElementById(this.id).innerHTML = str
}
Dethcuts.clear = function() {
	document.cookie = "dethcuts=; expires=Thu, 01 Jan 1970 00:00:01; path=/;";
	$("#shortcuts").html("<span>" + ELEMENTOS + "</span>");
}
