var URL = "http://api.nestoria.es/api?action=search_listings&encoding=json&pretty=1";
var parametros = "";
var objetosEncontrados
var objetoEspacio = new Array();
var objetoEspacioNes = new Array();
var objetoPrecio = new Array();
var arrayVacio = new Array();
var i = 0;
var a = 0;
var b = 0;
var c = 1;
var textoSaltos = "";
var posicionArray = 0;
var actualPage = 0;
var totalPages = 0;
var html = "";
var html2 = "";
var promedio = 0;
var sumaPreciosMetros2 = 0;
var rangoMinPreciosMetros2 = 0;
var rangoMaxPreciosMetros2 = 0;
var desviacionSumatorioTem = 0;
var desviacionSumatorio = 0;
var desviacion = 0;
var precioMetro2 = 0;
var precioEspacio = 0;
var indiceRangoPrecioEspacio = 0;
var rangoMinprecioEspacio = 0;
var rangoMaxprecioEspacio = 0;
var ejecutaProcesos = 1;

function Newton(dato){
   var X = 1;
   var FX = X*X - dato;
   for (var i = 0; i < 10; i++) {
      X = X - FX/(2*X);
      FX = X*X - dato;
   }
   dato = X;
   return dato;
}


function calculaPrecioVenta(objetoPrecio){
    promedio = 0;
    desviacionSumatorioTem = 0;
    desviacionSumatorio = 0;
    desviacion = 0;
    sumaPreciosMetros2 = 0;
    precioMetro2 = 0;

    for (b=0; b <= objetoPrecio.length-1 ; b++){
        sumaPreciosMetros2 = sumaPreciosMetros2 + parseInt(objetoPrecio[b]);
    }
    promedio = sumaPreciosMetros2/b;

    for (b=0; b <= objetoPrecio.length-1 ; b++){
        desviacionSumatorioTem = ( parseInt(objetoPrecio[b]) - parseInt(promedio));
        desviacionSumatorioTem = desviacionSumatorioTem * desviacionSumatorioTem;
        desviacionSumatorio = desviacionSumatorio + desviacionSumatorioTem
    }
    //promedio
    desviacion = desviacionSumatorio * ( 1 / (b - 1) );
    desviacion = parseInt(Newton(desviacion));

    rangoMinPreciosMetros2 = promedio - desviacion;
    rangoMaxPreciosMetros2 = promedio + desviacion;

    var cuantosEstanDentro = 0;

    document.getElementById("flancoEstad").innerHTML = 'entre <b>' + fmtMoney( rangoMinPreciosMetros2, 0, '.', '.' ) + '</b> y <b>' + fmtMoney( rangoMaxPreciosMetros2, 0, '.', '.' ) + '</b>&nbsp;&euro;/mē' ;

    for (b=0; b <= objetoPrecio.length-1 ; b++){
        if (objetoPrecio[b] >= rangoMinPreciosMetros2 && objetoPrecio[b] <= rangoMaxPreciosMetros2){
            cuantosEstanDentro++;
            precioMetro2 = precioMetro2 + parseInt(objetoPrecio[b]);
            if (cuantosEstanDentro<=20){
                html2 += '<tr><td class="tablaPreciosHtml">' + objetoEspacio[b][7] + '</td><td class="tablaPreciosHtmlCenter">' + objetoEspacio[b][4] + '</td><td class="tablaPreciosHtmlCenter">' + objetoEspacio[b][5] + '</td><td class="tablaPreciosHtmlRight">' + objetoEspacio[b][3] + ' m<sup>2</sup></td><td class="tablaPreciosHtmlRight">' + fmtMoney( objetoEspacio[b][6], 0) + ' &euro;</td><td class="tablaPreciosHtmlRight2">' + fmtMoney( (parseInt(objetoEspacio[b][6]) / parseInt(objetoEspacio[b][3])), 0 ) + ' &euro;</td></tr>';
            }
            c++;
        }
    }

    $('#informePrecios').append($(html2));

    if (tipoVivBus == 1){
        if (cuantosEstanDentro < 5){
            ejecutaProcesos = 0;
        }else{
            ejecutaProcesos = 1;
        }
    }else if (tipoVivBus == 2){
        if (cuantosEstanDentro < 6){
            ejecutaProcesos = 0;
        }else{
            ejecutaProcesos = 1;
        }
    }else if (tipoVivBus == 3){
        if (cuantosEstanDentro < 8){
            ejecutaProcesos = 0;
        }else{
            ejecutaProcesos = 1;
        }
    }else if (tipoVivBus == 4){
            ejecutaProcesos = 1;
    }


    if (ejecutaProcesos == 1){
        precioMetro2 =  precioMetro2 / cuantosEstanDentro;
        precioEspacio = precioMetro2 * parseInt(metrosVivienda);

        indiceRangoPrecioEspacio =  (precioEspacio * 3) / 100;
        rangoMinprecioEspacio =  precioEspacio - indiceRangoPrecioEspacio;
        rangoMaxprecioEspacio =  precioEspacio + indiceRangoPrecioEspacio;

        var precioTotal = (rangoMinprecioEspacio + rangoMaxprecioEspacio ) / 2;
        if (pecioAltamiraVenta_ok >= precioTotal){
             $('#fichaInmueble').hide();
             $('#mensaje').fadeIn("slow");
        }else{
            $('#fichaInmueble').hide();
            $('#preciosFichaButton').toggle();
            $('.mapSelected').fadeOut("fast");
            $('.mapSelected').removeClass('mapSelected');
            $('.tab').removeClass('selected');
            $('#preciosFichaButton').addClass('selected');
            $('#precios').addClass('mapSelected');
            $('#precios').fadeIn("slow");
            document.getElementById("pecioAltamira").innerHTML = "<b>" +  fmtMoney( pecioAltamiraVenta_ok, 0, '.', '.' ) + "</b> &euro;";
            var descuento = ((pecioAltamiraVenta_ok * 100) / precioTotal);
            descuento = fmtMoney( descuento, 0, '.', '.' );
            descuento = descuento - 100;
            document.getElementById("flancoEstad").innerHTML = descuento + ' %' ;
            document.getElementById("pecioEstimadoPrecio").innerHTML = "<b>" +  fmtMoney( precioTotal, 0, '.', '.' ) + "</b> &euro;";
            document.getElementById("pecioM2AplicadoPrecio").innerHTML = fmtMoney( precioMetro2, 0, '.', '.' ) + " &euro;/mē";
            completaInfoPlusVenta(cuantosEstanDentro);
        }
        //llama a la carga de alquiler-------
        llamadaPerfectaAlquiler("1");
    }else{
        objetoEspacio = [];
        objetoPrecio = [];
        i = 0;
        html = "";
        html2 = "";
        tipoVivBus = tipoVivBus +  1;
        textoSaltos  = "Elemento control especial tipo de busqueda salto  " + tipoVivBus + " <br><br>";

        cambiavivienda(tipoVivBus)
    }
}


function pintaDatosVenta(){
    $('#informePrecios').empty();

    for (a=0; a <= objetoEspacio.length-1 ; a++){
        objetoPrecio[a]=parseInt(objetoEspacio[a][6]) / parseInt(objetoEspacio[a][3]);
    }
    calculaPrecioVenta(objetoPrecio);
}


function creaObjetoNewNesVenta(response){
        if (""+response['response']['listings']!="undefined" && ""+response['response']['listings']!=""){
            var numeroElementos = eval(response['response']['listings'].length);
            paginaActual = response['response']['page'];
            paginasTotales = response['response']['total_pages'];
                var html = '';
                objetosEncontrados = response['response']['total_results'];
                actualPage = response['response']['page'];
                totalPages = response['response']['total_pages'];
                html += '<h3> Total: ' + response['response']['total_results'] + ' _ actualPage: ' + response['response']['page'] + ' _ totalPages: ' + response['response']['total_pages'] + '</h3>';

                 for(indiceArrayNes=0;indiceArrayNes < numeroElementos;indiceArrayNes++){
                    var dato =  response['response']['listings'][indiceArrayNes];
                    objetoEspacio[i] = new Array(9);
                    objetoEspacio[i][0] = dato['guid'];
                    objetoEspacio[i][1] = dato['property_type'];
                    objetoEspacio[i][2] = dato['datasource_name'];
                    objetoEspacio[i][3] = dato['size'];
                    if (dato['bedroom_number']!=""){
                        objetoEspacio[i][4] = dato['bedroom_number'];
                    }else{
                        objetoEspacio[i][4] = dato['room_number'];
                    }
                    objetoEspacio[i][5] = dato['bathroom_number'];
                    objetoEspacio[i][6] = dato['price'];
                    objetoEspacio[i][7] = dato['title'];
                    objetoEspacio[i][8] = dato['lister_url'];

                    i++;
                  };
                if (totalPages > 0 && actualPage != totalPages){
                    if (actualPage==2){
                         pintaDatosVenta();
                    }else{
                        llamadaPerfectaVenta(parseInt(actualPage)+1);
                    }
                }else{
                    if (objetosEncontrados==0){
                        objetoEspacio = [];
                        objetoPrecio = [];
                        i = 0;
                        html = "";
                        html2 = "";
                        tipoVivBus = tipoVivBus +  1;
                        textoSaltos  = "Elemento control especial tipo de busqueda salto  " + tipoVivBus + " <br><br>";

                        cambiavivienda(tipoVivBus)
                    }else{
                        pintaDatosVenta();
                    }
                }
        }else{
            $('#fichaInmueble').hide();
             $('#mensaje').fadeIn("slow");
        }
}



function recuperaObjetosVenta(lon,lat,rad,min,max,tipoOpe,tipoInm,index){
    radiusVenta = parseInt(rad) / 1000;
    if (tipoInm=="P"){
        var property_type = "flat";
    } else if(tipoInm=="C"){
        var property_type = "house";
    }

    var listing_type = "buy";
    if(index > 0){
        parametros = "&centre_point=" + lon + "," + lat + "," + radiusVenta + "km&number_of_results=50&sort=newest&property_type=" + property_type + "&listing_type=" + listing_type + "&size_max=" + max + "&size_min=" + min + "&page=" + index + "&callback=creaObjetoNewNesVenta"
        indicePaginaActual = index;
        latitud = lat;
        longitud = lon;
        radioBusqueda = radio;
        tipoBusqueda = tipoOpe;
        realizarConsultaNewNesVenta();
	}
}

function realizarConsultaNewNesVenta(){
	if(parametros != ""){
		var jstagVenta=document.createElement("script");
		jstagVenta.setAttribute("type", "text/javascript");
		jstagVenta.setAttribute("src", URL + parametros);
		document.getElementsByTagName("head")[0].appendChild(jstagVenta);
	}
}

