// admin-menu
$(document).ready(function(){
	$('li.headlink').hover(
		function() {$('ul', this).css('display', 'block');},
		function() {$('ul', this).css('display', 'none');});
});


function cargarRangoPrecio(elrango){ //hacks by herohat, 24 de nov. 2010
    $("#precio_desde").load("/app/rangos_precios.php", {cual: elrango, desde_hasta: 1}, function(){
         $('#precio_desde').show();
    });

    $("#precio_hasta").load("/app/rangos_precios.php", {cual: elrango, desde_hasta: 2}, function(){
         $('#precio_hasta').show();
    });
}

function enviar_amigo(){
    var theform = document.forms['form_enviaramigo'];

    var tunombre = theform.formamigo_tunombre.value;
    var tuemail = theform.formamigo_tuemail.value;
    var anombre = theform.formamigo_amigonombre.value;
    var aemail = theform.formamigo_amigoemail.value;
    var mensaje = theform.formamigo_mensaje.value;
    var propid = theform.formamigo_propid.value;
    var proptitulo = theform.formamigo_titulo.value;
    var lang = theform.formamigo_lang.value; 

    if(lang == 'es'){
        var texto = 'No se pudo enviar su mensaje, faltan datos excenciales';
        var texto2 = 'No se pudo enviar su mensaje, intentelo de nuevo mas tarde.';
        var texto4 = 'Su e-mail o el de su amigo es invalido';
        var texto3 = 'Su mensaje fue enviado';
    }else{
        texto = 'We can not send your message, the form have data empty';
        texto2 = 'We did not send your message, please try again later';
        texto4 = 'Your e-mail or yours friends s e-mail is not valid';
        texto3 = 'You message was sent';

    }


        $("#respuesta").load("/app/actions/procesar_enviar_amigo.php", {
            enombre: tunombre, eemail: tuemail, anombre: anombre, aemail: aemail, mensaje: mensaje, propid: propid, proptitulo: proptitulo, lang: lang},
        function(response){
             if(response == 1) alert(texto);
             else if(response == 2){alert(texto2);}
             else if(response == 3){alert(texto4);}
             else{
                 document.getElementById("form_enviaramigo").innerHTML="<div style='padding: 20px; color:green;'>"+texto3+"!</div>";
             }
        });
}

function getRegiones_lb(placement,argument){
	url = "/app/services/listbox_regiones.php?country="+argument;
	$(placement).load(url);
	return true;
}
function getProvincias_lb(placement,argument){
	url = "/app/services/listbox_provincias.php?country="+argument;
	$(placement).load(url);
	return true;
}
function getCiudades_lb(placement,argument){
	url = "/app/services/listbox_ciudades.php?state="+argument;
	$(placement).load(url);
	return true;
}
function getSectores_lb(placement,argument){
	url = "/app/services/listbox_sectores.php?city="+argument;
	$(placement).load(url);
	return true;
}
function getListBox(){
}
function loadProperty(id,title){
	window.location.hash = title;
	$(".contenido").hide("fast");
	url = "/app/services/property.php?propid="+id
	loadContent("#propiedad",url);
}
function loadMainPicture(propid){
	$("#prop-main-picture").load("/app/services/property_mainpicture.php?propid="+propid);
}
function loadPropertyPrice(propid){
}
function loadPropertyThumbnails(propid){
}
function loadPage(){
	
}


function advancedSearch(){	

        var theform = document.forms['busqueda_avanzada'];
	
	var tipo_casa		 = theform.tipo_casas.value;
	var tipo_comercial	 = theform.tipo_comerciales.value;
	var tipo_apartamento = theform.tipo_apartamentos.value;
	
	var alias_penthouse	 = theform.alias_penthouses.value;
	var alias_tienda	 = theform.alias_tiendas.value;
	var alias_solar		 = theform.alias_solares.value;
	var alias_finca		 = theform.alias_fincas.value;
	var alias_oficina	 = theform.alias_oficinas.value;
	var alias_nave		 = theform.alias_naves.value;
	
	var provincia		 = theform.provincia.value;
	var ciudad			 = theform.ciudad.value;
	var sector			 = theform.sector.value;

	var codigo			 = theform.codigo.value;
//	estado			 = theform.estado.value;
	var venta	 		 = theform.proposito_venta.value;
	var alquiler		 = theform.proposito_venta.value;
	var permuta			 = theform.proposito_venta.value;
	var alquileramueblado = theform.proposito_alquileramueblado.value;
	var alquilercompra	 = theform.proposito_alquilercompra.value;

	var precio_desde	 = theform.precio_desde.value;
	var precio_hasta	 = theform.precio_hasta.value;
//	area_construccion = theform.area_construccion.value;	
	var habitaciones	 = theform.habitaciones.value;
	var banos			 = theform.banos.value;
	var parqueos		 = theform.parqueos.value;
	
	var moneda = "";
	
//	moneda			 = theform.moneda.value;	
//moneda = document.forms['busqueda_avanzada'].moneda.value;
//moneda_sel = document.forms['busqueda_avanzada'].moneda.value;
	/* 24 de noviembre 2010, comentado pues carolina dijo que solo usariamos pesos...
         *moneda_sel = document.busqueda_avanzada.moneda;

	for (i=0; i<moneda_sel.length; i++){
	  if (moneda_sel[i].checked == true)
		  moneda = moneda_sel[i].value;
	} */

	//var query2 = "http://dreamhome.com.do/app/services/listing_properties.php?content=listing";
        var query2 = "listado.php?content=listing"; //hacks for herohat
	/*
	switch(1){
		case (provincia > 0): 
			query = addToQuery(query,"provincia_id",provincia);
			alert(provincia);
		case ciudad > 0:
			query = addToQuery(query,"ciudad_id",ciudad);	
		case sector > 0:
			query = addToQuery(query,"sector_id",sector);				
	}
	*/

        if(codigo.length > 0){
                //query2 = addToQuery(query2,"codigo",codigo);
                query2 = query2+"&codigo="+codigo;
        }else{
// UBICACION
		if(provincia > 0){
			query2 = addToQuery(query2,"provincia",provincia);
		}
		if(ciudad > 0){
			query2 = addToQuery(query2,"ciudad",ciudad);
		}
		if(sector > 0){
			query2 = addToQuery(query2,"sector",sector);
		}
// TIPOS
/*
	if(tipo_casa > 0){
			query2 = addToQuery(query2,"casa",tipo_casa);
		}
*/
		if(theform.tipo_casas.checked){
                        query2 = addToQuery(query2,"casa",tipo_casa);
		}

		if(theform.tipo_comerciales.checked){
			query2 = addToQuery(query2,"comercial",tipo_comercial);
		}
		if(theform.tipo_apartamentos.checked){
			query2 = addToQuery(query2,"apartamento",tipo_apartamento);
		}
// ALIAS
		if(theform.alias_penthouses.checked){
			query2 = addToQuery(query2,"penthouse",alias_penthouse);
		}
		if(theform.alias_tiendas.checked){
			query2 = addToQuery(query2,"tienda",alias_tienda);
		}
		if(theform.alias_solares.checked){
			query2 = addToQuery(query2,"solar",alias_solar);
		}
		if(theform.alias_fincas.checked){
			query2 = addToQuery(query2,"finca",alias_finca);
		}
		if(theform.alias_oficinas.checked){
			query2 = addToQuery(query2,"oficina",alias_oficina);
		}
		if(theform.alias_naves.checked){
			query2 = addToQuery(query2,"nave",alias_nave);
		}

// PROPOSITO

		if(theform.proposito_venta.checked){
			query2 = addToQuery(query2,"venta",1);
		}
		if(theform.proposito_alquiler.checked){
			query2 = addToQuery(query2,"alquiler",2);
		}
		if(theform.proposito_permuta.checked){
			query2 = addToQuery(query2,"permuta",5);
		}
		if(theform.proposito_alquileramueblado.checked){
			query2 = addToQuery(query2,"alquiler_amueblado",2);
		}
		if(theform.proposito_alquilercompra.checked){
			query2 = addToQuery(query2,"alquiler_amueblado",4);
		}

// OTROS
		if(codigo.length > 0){
			//query2 = addToQuery(query2,"codigo",codigo);
			query2 = query2+"&codigo="+codigo;
		}

		if(moneda.length > 0){
			query2 = query2+"&moneda="+moneda;
		}

		if(precio_desde >= 0){ //24 de nov. 2010 hack, puse:  >=, antes solo era  >
			query2 = addToQuery(query2,"precio_desde",precio_desde);
		}
		if(precio_hasta > 0){
			query2 = addToQuery(query2,"precio_hasta",precio_hasta);
		}
/*
		if(area_construccion > 0){
			query2 = addToQuery(query2,"area_construccion",area_construccion);
		}
*/
		if(habitaciones > 0){
			query2 = addToQuery(query2,"habitaciones",habitaciones);
		}
		if(banos > 0){
			query2 = addToQuery(query2,"banos",banos);
		}
		if(parqueos > 0){
			query2 = addToQuery(query2,"parqueos",parqueos);
		}
        }
	

	//$("#listado").hide();
	$("#caja_busqueda").hide();
	$("#featured_properties").hide();
	//$("#listado").load(query2);
	//$("#listado").show("slow");
        $("#esperando_result").show(); //hacks news by herohat
        //var url = query2;  
        //window.location = url;
        //alert(url);
        
        $("#listado").load("cargar_litado.php", {url: query2}, function(){
            //var url = query2;
            //window.location = url;
        });

	return false;
	
}

function setLanguage(lang){
	url = window.location
	//addToQuery no quiso trabajar aqui... nose porque
	//url = addToQuery(url,"locale",lang);
	url = window.location + "?&locale=" + lang
	window.location= url;
}

function addToQuery(a_query,a_tag,a_value){
	if(a_value > 0){
		a_query	= a_query + "&" + a_tag+"=" + a_value;
	}
	/*
	else{
		a_query	= "?" + a_query + "&" + a_tag+"=" + a_value;
	}
	*/
	return a_query;
}
function add2favorites(propid){
	alert("agregar a favoritos propiedad "+propid);
	return false;
}
function printProperty(propid){
	alert("imprimir propiedad "+propid);
	return false;
}
function sendProperty(propid){
	alert("enviar propiedad a un amigo"+propid);
	return false;
}

function readHash(){
	//alert("corriendo: readHash()");
	var content = "";
	var params = "";
	var i = 0;
	var hashcontent = window.location.hash.split("/");
		
	if( hashcontent[0].length > 0){
		content = hashcontent[0];
		switch(content){
			case '#property':
				proptitle = hashcontent[1];
				propid = hashcontent[2];
				propid.replace(/-/,"=");
				query = "content=property&locale=en&title="+proptitle + "&"+propid;
				break;
			case '#propiedad':
				//proptitle = hashcontent[1];					
				//propid = hashcontent[2];
				//propid = propid.replace(/-/,"=");
				//query = "content=property&locale=es&title="+proptitle + "&"+propid;
				query = "content=property&locale=es&title="+hashcontent[1]+ "&"+hashcontent[2].replace(/-/,"=");
				break;
			case '#listing':
				query = "content=listings&locale=en"+addFromHash(1,hashcontent);
				break;
			case '#listado':
				query = "content=listings&locale=es&"+addFromHash(1,hashcontent);
				break;				
			case '#search':
				query = "content=search&locale=en&"+addFromHash(1,hashcontent);
				break;
			case '#buscar':
				query = "content=search&locale=es&"+addFromHash(1,hashcontent);
				break;
			case '#agent':
				query = "content=agent&locale=en&"+addFromHash(1,hashcontent);
				break;
			case '#agente':
				query = "content=agent&locale=es&"+addFromHash(1,hashcontent);
				break;
			case 'agency':
				break;
			case 'agencia':
				break;
			case 'informacion':
				query = "content=contentpage&locale=es&"+addFromHash(1,hashcontent);
				break;	
			case 'information':
				query = "content=contentpage&locale=en&"+addFromHash(1,hashcontent);			
				break;				
		}	
		query = 'webservice.php?'+query;
		loadContent(content,query);
	}else{
//		loadContent("listado",'app/services/listing_properties.php?content=listings&locale=es');
		//window.location.hash = 'listado/locale-es';
		//readHash();
		loadContent("#listado",'webservice.php?content=listings&locale=es');
	}
}
function addFromHash(i,thehash){
	results = "";
	for( i ; i < thehash.length; i++ ){
		results += thehash[i].replace(/-/,"=")+"&";
	}
	return results;	
}
function loadContent(container,query){
	//alert("contenedor: "+container+" - query: "+query);
	$(container).show("fast");
	$(container).load(query);
}
function getProperty(){
	var propid = readURLParameter('prop');
//	loadContent("#propiedad",'/app/services/property.php?propid='+propid); 
	loadContent("#prop-main-picture",'/app/services/property_mainpicture.php?propid='+propid);
	loadContent("#prop-features",'/app/services/property_detalles.php?propid='+propid);
	loadContent("#prop-prices",'/app/services/property_prices.php?propid='+propid);	
	loadContent("#prop-thumbnails",'/app/services/property_thumbs.php?propid='+propid);	
	
//	$("#prop-main-picture").load("/app/services/property_mainpicture.php?propid=" + propid);
}

function readURLParameter(varname){
  varname = varname.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+varname+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function getRelatedProperties(container,query){
	query = "/app/services/property_related.php?"+query;
	loadContent(container,query);
//	alert("cargaremos "+query +" en #"+container);	
}
function paginateListings(query){
	$("#listado").load("/app/services/"+query);
}

function getProvincias_as(pais){
	url = "/app/services/getProvincias.php?pais="+pais;
	$("#as_provincia").load(url);	
}
function getCiudades_as(provincia){
	url = "/app/services/getCiudades.php?provincia="+provincia;
	$("#as_ciudad").load(url);	
}
function getSectores_as(ciudad){
	url = "/app/services/getSectores.php?ciudad="+ciudad;
	$("#as_sector").load(url);	
}

function removeFromFavorites(propid){
	url = "/app/favoritos.php?action=remove&prop="+propid;
	$("#hidden-container").load(url);
	$("#property_"+propid).hide("fast");
}
function mostrarBusqueda() {
	$("#caja_busqueda").load("/app/includes/modBusqueda.php");
	$("#caja_busqueda").show("slow");       
}


function comprobarCampos(valor,elcampo){
            if(valor == ''){
                $('#'+elcampo).addClass("destacaError");
                return 0;
            }else{
                return 1;
            }
}

function validarEmail(valor,elcampo){
    re=/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/
    if(!re.exec(valor))    {
        $('#'+elcampo).addClass("destacaError");
        alert('E-mail no valido');
        return 0;
    }else{
        return 1;
    }
}
