// JavaScript Document
var id_activa = "";
var result = new Array();
var x = 0;
var y = 0;
var ultima_url = "";
var pest_activa = "pestanya_home";
var class_activa = "pestanya pestanya_home";
var zona_activa = "";
var zona_activa2 = "";
var euro = "&euro;";
var euro_mes ="&euro;/mes";
var ant;

function rent_over(obj){    
    if(obj.src != "imagenes/boton_alquiler_mouseover.jpg"){
         obj.src = "imagenes/boton_alquiler_mouseover.jpg";   
    }
}

function rent_out(obj){
   
    if(obj.src != "imagenes/boton_alquiler.jpg" && ant != "/imagenes/boton_alquiler_selec.jpg"){
         obj.src = "imagenes/boton_alquiler.jpg";   
    }
    if(ant == "/imagenes/boton_alquiler_selec.jpg"){
          obj.src = ant;
    }
}

//Resalta la imatge seleccionada en el detall del pis
function resaltar(id){
    
    var obj = document.getElementById(id);
    obj.style.backgroundColor = "#ffe899";
    quitarResaltado(id);
}

//Treu el resaltat en seleccionar una altra imatge
function quitarResaltado(id){
    var i = new Number(new String(id).charAt(0));
    for (var n = 0; n <= 9; n++)  {
        var obj = document.getElementById(n + "pis");
        if (i != n) {
            if (obj) obj.style.backgroundColor = "#e5eff7";
        }    
    }    
}

//Mostra el div de mouseover en passar per sobre de una zona
function mostrar(szIdOcultar,szIdMostrar){  
    if (szIdMostrar != zona_activa){  
        if(document.getElementById(szIdOcultar)) {
            if(document.getElementById(szIdOcultar).style.display != "none") document.getElementById(szIdOcultar).style.display = "none";
        }       
        if(document.getElementById(szIdMostrar)) {
           if(document.getElementById(szIdMostrar).style.display != "") document.getElementById(szIdMostrar).style.display = "";     }     
    }                                     
}

//Mostra el div de seleccionat al clickar una de les zones
function mostrar_click(szIdOcultar,szIdMostrar){  
    
    if (szIdMostrar != zona_activa){    
        if(document.getElementById(zona_activa)) {
            document.getElementById(zona_activa).style.display = "";
            document.getElementById(zona_activa2).style.display = "none";
            document.getElementById(zona_activa2).style.backgroundColor = "#ffffee";
        }
        if(document.getElementById(szIdOcultar)) {
            if(document.getElementById(szIdOcultar).style.display != "none"){
                document.getElementById(szIdOcultar).style.display = "none";
                document.getElementById(szIdOcultar).style.backgroundColor = "#ffeda9";
            } 
        }       
        if(document.getElementById(szIdMostrar)) {
           if(document.getElementById(szIdMostrar).style.display != ""){
               document.getElementById(szIdMostrar).style.display = "";
               //
           }      
        } 
        zona_activa = szIdMostrar; 
        zona_activa2 = szIdOcultar;  
        
        mostrar(szIdMostrar, szIdOcultar);
    }                                  
}

//Carrega una direccio (document) en el lloc indicat 
function load_url(addres,local,params,functionAfter){    
    //alert("Adress: "+addres+"\nLocal: "+local+"\nParams: "+params+"\nfunctionAfter: "+functionAfter);
    $.ajax({
     type: "post",
     url: addres ,
     dataType: "text",
     data: params,
     cache: false,
     complete: functionAfter,
     error: function(request,error) {     
          if(error != "") {
           $("#"+local).html(request.responseText);
          }
      },
      success: function(request) {   
          $("#"+local).html(request);
      } 
    });
}

//Idem que load_url pero agrega un comentari a les observacions del contacte quan demanem info de un pis
function load_url_contacto(addres, local, param1, param2){
    var functionAfter = function(){
         document.getElementById("observaciones_contacto").value = "Deseo recibir información sobre la "+param1+", ubicada en "+param2+".";         
     }
    //alert(local);
    $.ajax({
     type: "post",
     url: addres ,
     dataType: "text",
     cache: false,
     complete: functionAfter,
     error: function(request,error) {     
          if(error != "") {
           $("#"+local).html(request.responseText);
          }
      },
      success: function(request) {   
          $("#"+local).html(request);
      } 
    });
}


//Valida que el formulari de contacti estigui llest per a ser enviat
function valida_envia_mail(){
    if(document.getElementById('nombre_contacto')){
        if(document.getElementById('nombre_contacto').value == ""){
            document.getElementById('lbl_error').innerHTML = "Debe introducir el nombre de contacto";
            return false;    
        }    
    }
    if(document.getElementById('telefono_contacto')){
        if(document.getElementById('telefono_contacto').value == ""){
            document.getElementById('lbl_error').innerHTML = "Debe el tel&eacute;fono de contacto";
            return false;    
        }    
    }
    if(document.getElementById('correo_contacto')){
        if(document.getElementById('correo_contacto').value == ""){
            document.getElementById('lbl_error').innerHTML = "Debe introducir un mail de contacto";
            return false;    
        }    
    }
    szUrl = "contacto/contacto.php"
    szParams = "nombre=" + document.getElementById('nombre_contacto').value;
    szParams += "&direccion=" + document.getElementById('direccion_contacto').value;
    szParams += "&tele=" + document.getElementById('telefono_contacto').value;
    szParams += "&poblacion=" + document.getElementById('poblacion_contacto').value;
    szParams += "&provincia=" + document.getElementById('provincia_contacto').value;
    szParams += "&correo=" + document.getElementById('correo_contacto').value;
    szParams += "&obs=" + document.getElementById('observaciones_contacto').value; 
   
    document.getElementById('lbl_error').innerHTML = "";
    
    var funcionafter = function limpia(request){
        if(request.responseText.indexOf("Mensaje enviado correctamente") > 0){
            document.getElementById('nombre_contacto').value = "";
            document.getElementById('direccion_contacto').value = "";
            document.getElementById('telefono_contacto').value = "";
            document.getElementById('poblacion_contacto').value = "";
            document.getElementById('provincia_contacto').value = "";
            document.getElementById('correo_contacto').value = "";
            document.getElementById('observaciones_contacto').value = "";      
        }
    } 
    load_url(szUrl,"lbl_error",szParams,funcionafter);
}
                   
//Carrega la imatge seleccionada en el detall del pis 
function carga_imatge(img){
    document.getElementById("imatgeGran").src = "enterprise/web" + img;
}

/*function clicka_buscar(){
    document.getElementById("boton_buscar").style.backgroundImage="url('imagenes/boton_buscar_selec.jpg')";
}

function desclicka_buscar(){
    document.getElementById("boton_buscar").style.backgroundImage="url('imagenes/boton_buscar.jpg')"; 
}*/

//Retorna el tipus d'immoble en text rebent el value del selector del portal
function retorna_tipus(conti,tipus){
    //alert(tipus);
    var nom_tipus;           
    switch(tipus){
        case "t01":
        nom_tipus = "Casa";
        break;
        case "t02":
        nom_tipus = "Piso";
        break;
        case "t03":
        nom_tipus = "Ático";
        break;
        case "t04":
        nom_tipus = "Local";
        break;
        default: 
        nom_tipus = "No especificado";
    }
    document.getElementById(conti).innerHTML=nom_tipus;
}

//Retorna la opció de l'immoble en text rebent el value del selector del portal
function retorna_opcio(conti,opcio){
    //alert(opcio);
    var opc;
    if (opcio == "c01"){
        opc = "COMPRA";
    }else{
        opc = "ALQUILER";
    }
    document.getElementById(conti).innerHTML=opc;
}

//Retorna el nombre d'habitacions de l'immoble en text rebent el value del selector del portal
function retorna_habs(conti, habs){
    var num_habs;
    switch(habs){
        case "h01":
        num_habs = "1";
        break;
        case "h02":
        num_habs = "2";
        break;
        case "h03":
        num_habs = "3";
        break;
        case "h04":
        num_habs = "4";
        break;
        case "h05":
        num_habs = "Más de 4";
        break;
        default: 
        num_habs = "No especificado";
    }
    document.getElementById(conti).innerHTML=num_habs;
}

function carrega_pis_seguent(){
    if (result[(x+1)]){
       load_url('/enterprise/web/gc_search.php?tipo=3&entidad=2&plantilla=13&id=' + result[(x+1)],'div_resultado_busqueda');
     }
}

function carrega_pis_anterior(){
    if (result[(x-1)]){
       load_url('/enterprise/web/gc_search.php?tipo=3&entidad=2&plantilla=13&id=' + result[(x-1)],'div_resultado_busqueda');
    }  
}

function init_botones(){

    if (result[(x-1)]){
        if(document.getElementById("pis_anterior")) document.getElementById("pis_anterior").style.display="";
    }
    else{
        if(document.getElementById("pis_anterior"))document.getElementById("pis_anterior").style.display="none";
    } 
    
    if (result[(x+1)]){
        if(document.getElementById("pis_seguent"))document.getElementById("pis_seguent").style.display="";
    }
    else{
        if(document.getElementById("pis_seguent"))document.getElementById("pis_seguent").style.display="none";
    }  
}

//Marca com actiu l'immoble seleccionat per a saber quins pisos s'han de mostrar com a anterior i seguent
function immoble_actiu(id){
    id_activa = id;
    for (i= 0; i < result.length;i++){
        if (result[i] == id){
            x = i;
        }
    } 
    init_botones();
}

//Inicialita l'array d'immobles
function inicialitza_inmobles(){
    result = new Array();
    y=0;
    x=0;
}

//Crea l'array d'immoble en entrar en una zona
function guarda_immobles(id, cont){
    result[cont] = id;
    y = cont;
   
}

//Guarda la url del resum d'immobles per a poder usar el boto de tornar llistat
function guarda_resum(url){
    window.top.document.getElementById("url_resum").value = url;
}

/*function borra_url_detall(){
    window.top.document.getElementById("url_detall").value = "";
}*/

function borra_urls(){
    window.top.document.getElementById("url_resum").value = "";
    window.top.document.getElementById("url_detall").value = "";
}

//Retorna un string passat amb la primera lletra majuscula
function primeraMayus(string){
    var arrayWords;
    var returnString = "";
    var len;
    arrayWords = string.split(" ");
    len = arrayWords.length;
    for(i=0;i < len ;i++){
        if(i != (len-1)){
            returnString = returnString+ucFirst(arrayWords[i])+" ";
        }
        else{
            returnString = returnString+ucFirst(arrayWords[i]);
        }
    }
    return returnString;
}

//Complementa primeraMayus
function ucFirst(string){
    return string.substr(0,1).toUpperCase()+string.substr(1,string.length).toLowerCase();
}

//Activa la imatge de seleccionat del id passat
function clicka_boto(id){
    ant = "/imagenes/" + id + "_selec.jpg";
    document.getElementById(id).src="/imagenes/" + id + "_selec.jpg";     
}

//Desactiva la imatge de seleccionat del id passat
function desclicka_boto(id){
    document.getElementById(id).src="/imagenes/"+id+".jpg"; 
}

//Canvia la classe en clickar un boto de la home (Home, Quienes Somos, Contacto)
function cambia_classe(id, clase, clase2){
    if (id != pest_activa){
        if (pest_activa == ""){
            pest_activa = id;
            class_activa = clase;
        }
        document.getElementById(id).className = clase;
        document.getElementById(pest_activa).className = class_activa;
    }
    pest_activa = id;
    class_activa = clase2;
}

//Canvia la classe en fer mouseover en un boto de la home (Home, Quienes Somos, Contacto)
function classe_over(id, clase){
    if (id != pest_activa){
        document.getElementById(id).className = clase;
    }
}

//Canvia la classe en fer mouseout en un boto de la home (Home, Quienes Somos, Contacto)
function classe_out(id, clase){
    if (id != pest_activa){
        document.getElementById(id).className = clase;
    }
}

//Amaga els botons de anterior, seguent i tornar llistat
function esborra_botons(){
    document.getElementById("pis_anterior").style.display="none";
    document.getElementById("pis_seguent").style.display="none";
    document.getElementById("torna_menu").style.display="none";
}

//Amaga el desplegable de ordenar per preu
function amaga_preu(){
    if(document.getElementById("desplegable_preu")){
        document.getElementById("desplegable_preu").style.display="none";   
    }
}

//Mostra el desplegable de ordenar per preu
function ensenya_preu(){
    document.getElementById("desplegable_preu").style.display="";
}

//Crea una nova finestra
function nova_finestra(url){
    window.open(url,"ventana_loc");
}

//Inicialitza les classes dels botons de la home en clickar una zona
function imatges_ini(){
    document.getElementById("pestanya_home").className = "pestanya pestanya_home";
    document.getElementById("pestanya_quienes").className = "pestanya pestanya_quienes";
    document.getElementById("pestanya_contacto").className = "pestanya pestanya_contacto";
    pest_activa = "";
}


function comprova_caracteristicas(szId, szIdContainer){
    
    var trobat = false;
    
    arr = $("." + szId)
    //alert(arr.length);
    for(var i = 0; i < arr.length; i++){
        
        if(arr[i].innerHTML != ""){
            trobat = true;
        }
    }
    
    if(!trobat){
        document.getElementById(szIdContainer).style.display = "none";
    }
}

function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}

function carrega_no_disponible(image_id, src_image, src_image_no_disponible){
    image = document.getElementById(image_id);
   
    if(image){
        if(src_image != "" && src_image != " " ){
            if(image.src != src_image) image.src = src_image;   
        }
        else{
            if(image.src != src_image_no_disponible) image.src = src_image_no_disponible;        
        }
        
    }
    
}

function crea_imagenes(){
    
    var tope = 3;
    
    if(isArray(ImageSrc) && document.getElementById("tabla_imagenes")){
        table = document.getElementById("tabla_imagenes");
        for(var i = 0; i < ImageSrc.length; i++ ){
            if(ImageSrc[i] != ""){
                if(i%3==0){
                   tr = table.insertRow(table.rows.length); 
                }
                td = tr.insertCell(tr.cells.length);
                szId = i + "pis";
                td.id = szId;
                td.className = "cursor caixaPis";
                if (i==0){td.style.backgroundColor = "#ffe899";}
                td.innerHTML = "<div onclick=\"carga_imatge('" + ImageSrc[i] + "'); resaltar('"+ szId + "');\" ><img src=/enterprise/web" + ImageSrc[i] + "  height=\"100px\" width=\"100px\" /></div>";            
            }    
        }   
    }
}
      
function formata(szText,szId){

    var preu = formatNumber(szText); 
    document.getElementById(szId).innerHTML= preu;          
}

function formatNumber(num){

var splitStr = num.split(',');
var splitLeft = splitStr[0];
var splitRight = splitStr.length > 1 ? '.' + splitStr[1] : '';
var regx = /(\d+)(\d{3})/;
while (regx.test(splitLeft)) {
splitLeft = splitLeft.replace(regx, '$1' + '.' + '$2');
}
return splitLeft + splitRight;
}


function set_value(szId, szValor){
    
    switch(szValor){
        case "c_compra":
            szCadena = "COMPRA";
            break;
        case "c_lloguer":
            szCadena = "LLOGUER";
            break;
        default:
            szCadena = "";
            break;
    }
    
    document.getElementById(szId).innerHTML = szCadena;
}

function set_preu(szId, szPreu, szValor){
  
     switch(szValor){
        case "c_compra":
            szCadena = " &euro;";
            break;
        case "c_lloguer":
            szCadena = " &euro;/mes";
            break;
        default:
            szCadena = "";
            break;
    }  
    
    document.getElementById(szId).innerHTML = szPreu + szCadena;
}
