/**
 * @author b.gabella
 */


function centerPoint(latlon,connId,layerId,info){

    var map = eGV.getMap();
    if (!map) return false;

    //center the point
    var newCenter = OpenLayers.LonLat.fromString(latlon);
    map.moveTo(newCenter);
	map.zoomToScale(2500,true);

    if (connId && layerId) {
        //show layer
        var conn = map.getConnection(connId);
        var lay = conn.getLayer(layerId);
        if (lay){
            lay.changeDisplayed(true);
        }
        
    }

    //make info
    if (info == true) {
        var infoControl = map.getControl("infoControl");
        var coords = latlon.split(",")
        infoControl.getInfoFromCoordinates(coords[0],coords[1]);
    }
}

function centerExtent(extent,connId,layerId) {
    var map = eGV.getMap();
    if (!map) return false;

    if (connId && layerId) {
        //show layer
        var conn = map.getConnection(connId);
        var lay = conn.getLayer(layerId);
        lay.changeDisplayed(true);
    }

 	map.zoomToExtent(new OpenLayers.Bounds(extent[0],extent[1],extent[2],extent[3]),true);


}

function cultureLoad()
{
	 var culture_combo = $("#cultureType");

    $.getJSON("php/ajax.php?op=get_culture_types", function(data){
        culture_combo.attr("options").length = 0;
        culture_combo.createAppend("option",{value:"0"},locStrings["_menu_select_option"]);
        $.each(data, function(i){
            var extent = [
                this.minx,
                this.miny,
                this.maxx,
                this.maxy
            ];
            culture_combo.createAppend("option",{value:extent,id:this.id},this.name)
        })
        culture_combo.trigger("load");
    });
}

function cultureType()
{
	var culture_combo = $("#cultureType");
    var culture_combo_eleme = $("#cultureElem");

    var options = culture_combo.attr("options");
    var opt = options[culture_combo.attr("selectedIndex")];

    //get the data via AJAX of the selected "cami"
    $.getJSON("php/ajax.php?op=get_culture_elem&id="+opt.id, function(data){
        culture_combo_eleme.attr("options").length = 0;
        culture_combo_eleme.createAppend("option",{value:"0"},locStrings["_menu_select_option"]);
        $.each(data, function(i){
            culture_combo_eleme.createAppend("option",{value:this.geom,id:this.id},this.name)
        })
    });
}

function cultureCenter() {
    var culture_combo = $("#cultureElem");

    var options = culture_combo.attr("options");
    var opt = options[culture_combo.attr("selectedIndex")];

    var culture_type = $("#cultureType");
    var options_type = culture_type.attr("options");
    var opt_type = options_type[culture_type.attr("selectedIndex")];

    var layerId = null;
    if (opt_type.id == 1) layerId = "castell";
    if (opt_type.id == 2) layerId = "cova";
    if (opt_type.id == 3) layerId = "despoblat";
    if (opt_type.id == 5) layerId = "esglesia";
    if (opt_type.id == 8) layerId = "altres";

    var connId = "patrimoni";

    //center the elem
    var center = culture_combo.attr("value");
    centerPoint(center,connId,layerId,true);


}


function caminsLoad()
{
	 var camins_type_combo = $("#caminsType");

    $.getJSON("php/ajax.php?op=get_camins_types", function(data){
        camins_type_combo.attr("options").length = 0;
        camins_type_combo.createAppend("option",{value:"0"},locStrings["_menu_select_option"]);
        $.each(data, function(i){
            camins_type_combo.createAppend("option",{id:this.id},this.name)
        })
        camins_type_combo.trigger("load");
    });
}

function caminsType()
{
	 var camins_combo = $("#camins");

     var camins_type_combo = $("#caminsType");

     var options = camins_type_combo.attr("options");
    var opt = options[camins_type_combo.attr("selectedIndex")];

    if (opt.id) {

        $.getJSON("php/ajax.php?op=get_camins&id="+opt.id, function(data){
            camins_combo.attr("options").length = 0;
            camins_combo.createAppend("option",{value:"0"},locStrings["_menu_select_option"]);
            $.each(data, function(i){
                var extent = [
                    this.minx,
                    this.miny,
                    this.maxx,
                    this.maxy
                ];
                camins_combo.createAppend("option",{value:extent,id:this.id},this.name)
            })
            camins_combo.trigger("load");
        });
    } else {
        camins_combo.attr("options").length = 0;
        camins_combo.createAppend("option",{value:"0"},locStrings["_menu_select_option"]);
    }
}

function caminsCenter() {
    var camins_combo = $("#camins");

    var options = camins_combo.attr("options");
    var opt = options[camins_combo.attr("selectedIndex")];

    //get the data via AJAX of the selected "cami"
    $.getJSON("php/ajax.php?op=get_cami&id="+opt.id, function(data){
        //create the html to fill in the floating div.
        var html = "<h3>"+data[0].name+"</h3>";
        //add the profile image to the floating div
        var i = 0;
        var points = new Array();
        for (i = 0; i < data[0].points.length; i++) {
            points.push(data[0].points[i][0]);
            points.push(data[0].points[i][1]);
            
        }
        //html = "<img src='"+serverUrl+"/geoz/geoz.php?REQUEST=getimage&POINTS="+points.join(",")+"&STEP=100&WIDTH=590&HEIGHT=125&BOTTOMCOLOR=white&TOPCOLOR=maroon&LOCALIZERS=0&FLOOR=1' alt='Perfil'>"
        html = "<div class='divProfilesClass'>\n\
                    <div class='profileLeft'>\n\
                        <img src='"+serverUrl+"/geoz/geoz.php?REQUEST=getimage&amp;POINTS="+points.join(",")+"&amp;STEP=100&amp;WIDTH=590&amp;HEIGHT=125&amp;BOTTOMCOLOR=green&amp;TOPCOLOR=maroon&amp;LOCALIZERS=0&amp;FLOOR=1'/>\n\
                    </div>\n\
                    <div class='profileRight'>\n\
                        Exportació<br/><br/>\n\
                        <img src='img/fileTree/page_white_picture.png'/>\n\
                        <a href='"+serverUrl+"/geoz/geoz.php?REQUEST=getimage&amp;POINTS="+points.join(",")+"&amp;STEP=100&amp;WIDTH=1024&amp;HEIGHT=480&amp;BOTTOMCOLOR=green&amp;TOPCOLOR=maroon&amp;LOCALIZERS=0&amp;FLOOR=1' target='_blank'>\n\
                            Imatge\n\
                        </a>\n\
                        <br/>\n\
                        <img src='img/fileTree/page_white_excel.png'/>\n\
                        <a href='"+serverUrl+"/tremp/php/profile.php?POINTS="+points.join(",")+">Excel</a>\n\
                    </div>\n\
                </div>";

        //fill the floating div width data about the "cami"
        effects.fillFloatingDiv("divProfile",html);


        //show the floating window
        effects.showFloatingDiv("divProfile",true);

        //highlight the path
        var map = eGV.getMap();
        var highlightConn = map.getConnection("highlight");

        //change the SLD param
        var sldUrl = serverUrl+"/tremp/php/sld.php?layer=xv_senders&field=xv_senders_fid&value="+data[0].id;
        highlightConn.olLayer.params.SLD = sldUrl;

        //make the layer visible
        var highlightLayer = highlightConn.getLayer("highlight");
        highlightLayer.changeDisplayed(true);

        //make the button to clear the SLD visible
        var button = $("#hideSLD");
        button.css("display","inline");


        //center the path
        var extent = camins_combo.attr("value").split(",");
        centerExtent(extent,"senders","xv_senders");
   });
}

function townsLoad()
{
	 var towns_combo = $("#towns");

    $.getJSON("php/ajax.php?op=get_towns", function(data){
        towns_combo.attr("options").length = 0;
        towns_combo.createAppend("option",{value:"0"},locStrings["_menu_select_option"]);
        $.each(data, function(i){
            towns_combo.createAppend("option",{value:this.geom,id:this.id},this.name)

        })
        towns_combo.trigger("load");
    });
}


function townsCenter()
{
	var towns_combo = $("#towns");

    var layerId = "ptpapa_assentament";
    var connId = "proteccions";

    //center the elem
    var center = towns_combo.attr("value");
    centerPoint(center,connId,layerId,false);
}


function topoLoad()
{
     var input_topo = $("#input_topo");
     if (!input_topo) return false;

     var value = input_topo.attr("value");

     var results_topo = $("#results_topo");

	 if (value.length > 2) {

        value = value.toLowerCase();

        value = value
            .replace(/à/g,'a')
            .replace(/á/g,'a')
            .replace(/è/g,'e')
            .replace(/é/g,'e')
            .replace(/í/g,'i')
            .replace(/ò/g,'o')
            .replace(/ó/g,'o')
            .replace(/ü/g,'u')
            .replace(/ú/g,'u')



	 	$.getJSON(serverUrl+"/localizer/localizer.php?municipi=252347&output=json&search=" + value, function(data){

            //street_suggest.attr("options").length = 0;
            results_topo.empty();
            var i = 0;

            if (data == false) {
                results_topo.createAppend("span",{},locStrings["_menu_search_topo_no_value"]);

                return true;
            }

	 		$.each(data, function(){

                if ((i % 2) == 0) {resultTopoCN = "topoResultsOdd";}
                else {resultTopoCN = "topoResultsEven";}

                results_topo.createAppend("div",{className:resultTopoCN,id:"result"+i},highlightText(this.nom,value));

                var resDiv = $("#result"+i);
                resDiv.attr("value",this.minx+","+this.maxy+","+this.maxx+","+this.miny);
                resDiv.hover(
                    function () {
                        $(this).addClass("topoResultsHover");
                    },
                    function () {
                        $(this).removeClass("topoResultsHover");
                    }
                );
                resDiv.click( function() {
                    centerExtent($(this).attr("value").split(","));
                });

                i++;


	 		})
	 	});

	 }
}

function cadastre()
{
	var referencia = $("#ref");
	if(!referencia) return false;
	var value = referencia.attr("value");
	$.getJSON("php/ajax.php?op=cadastre&code=" + value, function(data){
	 		$.each(data, function(i){
				var X = this.coords[0];
				var Y = this.coords[1];
                centerPoint(X+","+Y,false,false,true);
	 		})
	 	});


}






