//fred 2010
// mmc = mosy map catalog
// mmi = mosy map indicators


var clusterLayer;
var layercount = 1;
var layerPropertiesBar = null;
$('#rampcolorselect').hide();
$('#mmi_morefilters').hide();



$(".rampcolor").spectrum({
showPaletteOnly: true,
    togglePaletteOnly: false,
    hideAfterPaletteSelect:true,
    palette: [
        ["#000","#444","#666","#999","#ccc","#eee","#f3f3f3","#fff"],
        ["#f00","#f90","#ff0","#0f0","#0ff","#00f","#90f","#f0f"],
        ["#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#cfe2f3","#d9d2e9","#ead1dc"],
        ["#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#9fc5e8","#b4a7d6","#d5a6bd"],
        ["#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6fa8dc","#8e7cc3","#c27ba0"],
        ["#c00","#e69138","#f1c232","#6aa84f","#45818e","#3d85c6","#674ea7","#a64d79"],
        ["#900","#b45f06","#bf9000","#38761d","#134f5c","#0b5394","#351c75","#741b47"],
        ["#600","#783f04","#7f6000","#274e13","#0c343d","#073763","#20124d","#4c1130"]
    ]
});


$('#mmc_serviceGroup').change(function() {
    update_servicesList($("#mmc_serviceGroup option:selected").val());
});


$('#mmc_cbx_services').change(function() {
    var val = $("#mmc_cbx_services option:selected").attr("ws_url");

    if (val !== undefined) {
        $("#mmc_wmsUrl").val(val);
    } else {
        $("#mmc_wmsUrl").val("");
    }
});


$("#mmc_btnGetCatalogLayers").click(function(e) {
    //$(this).addClass('fa-spin');
    //$(this).append('<span class="fa fa-spinner fa-spin"></span> ');
    
    var type = $('#mmc_serviceType').val();
    var version = $('#mmc_serviceVersion').val();
    var url = $("#mmc_wmsUrl").val();
    
    $(".modal-body", "#recordMetadata").empty();
	$("#mmc_btnGetMetadata").data("action", null);
    $('#div-wms-results-glass').toggle();

    if (type == "wfs") {
        getWFSCapabilities(version,url);
    } else if (type == "wmts") {
        getWMTSCapabilities(version,url);
    } else {
        getWMSCapabilities(version,url);
    }

});
    
$("#mmc_btnGetMetadata").click(function(e) {
    if ($(this).data("action")) {
		var url = OpenLayers.ProxyHost + encodeURIComponent($(this).data("action"));

		$.get(url, null,
			function(data){
				new Transformation().setXml(data)
					.setXslt(xsltMetadata).setCallback(function (d) {
						$(".modal-body", "#recordMetadata").empty().prepend($(d));						
						$("#recordMetadata").modal("show");
					}
				).getTransformed();							
			},
			'text'
		);				       
    }
});



$('#mmi_color_scheme').change(function() {
    var colors = $('#mmi_color_scheme').val();
    if (colors == "discrete") {
        $('#rampcolorselect').fadeOut('slow');
    } else {
        $('#rampcolorselect').fadeIn('slow');
    }

});


//  years
var dateexploitfrom = $('#mmi_registdatefrom').val();
if (dateexploitfrom !== '') filters += ";dateexploitfrom:" + dateexploitfrom;
var dateexploitto = $('#mmi_registdateto').val();
if (dateexploitto !== '') filters += ";dateexploitto:" + dateexploitto;
var daterecruitfrom = $('#mmi_recruitdatefrom').val();
if (daterecruitfrom !== '') filters += ";daterecruitfrom:" + daterecruitfrom;
var daterecruitto = $('#mmi_recruitdateto').val();
if (daterecruitto !== '') filters += ";daterecruitto:" + daterecruitto;

// clusters

$("#mmi_btnGetCluster").click(function(e) {
    $.ajax({
        url: 'websig',
        type: 'POST',
        dataType: 'json',
        data: {'action': 'get_json',
            'context': $('#mmi_geo_context').val(),
            'type': $('#mmi_type').val(),
            'gender': $('#mmi_gender').val(),
            'agegroup': $('#mmi_agegroup').val(),
            'status': $('#mmi_status').val(),
            'citizenship': $('#mmi_citizenship').val(),
            'formfexplotation': $('#mmi_formfexplotation').val(),
            'placeof_exploit': $('#mmi_placeof_exploit').val(),
            'placeof_recruit':$('#mmi_placeof_recruit').val(),
            'placeof_waypoint':$('#mmi_placeof_waypoint').val(),
            'dateexploitfrom': $('#mmi_registdatefrom').val(),
            'dateexploitto': $('#mmi_registdateto').val(),
            'daterecruitfrom': $('#mmi_recruitdatefrom').val(),
            'daterecruitto': $('#mmi_recruitdateto').val()
        },
        success: function(data, status) {

            if (osmaps.hasLayer(clusterLayer)) {
                osmaps.removeLayer(clusterLayer);
                layerControl.removeLayer(clusterLayer);
            }
            ;

            if (data.features === null) {
                console.log("MoSY: Cluster query with no result");
                return;
            };

            clusterLayer = L.markerClusterGroup({
                singleMarkerMode: true,
                iconCreateFunction: function(cluster) {
                    var marks = cluster.getAllChildMarkers();
                    var n = 0;
                    var childCount = cluster.getChildCount();
                    var c = ' marker-cluster-';
                    if (childCount < 2) {
                        c += 'small';
                    } else if (childCount < 5) {
                        c += 'medium';
                    } else {
                        c += 'large';
                    }
                    for (var i = 0; i < marks.length; i++) {
                        n += marks[i].feature.properties.nb_pts;
                    }

                    return new L.DivIcon({html: '<div><span>' + n + '</span></div>',
                        className: 'marker-cluster' + c,
                        iconSize: new L.Point(40, 40)

                    });
                }
            });
            var geoJsonLayer = L.geoJson(data, {
                onEachFeature: function(feature, layer) {
                    layer.bindPopup(feature.properties.nb_pts.toString());
                }
            });


            clusterLayer.addLayer(geoJsonLayer);
            clusterLayer.ExtendedLayerControl = {
                removable: true,
                layerTypeName: "MoSy Cluster",
                layerTypeId: 0,
                haveProperties: true
            }
            osmaps.addLayer(clusterLayer);
            layerControl.addOverlay(clusterLayer, "Cluster", {groupName: "Cluster Map", expanded: true, removable: true});


        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });



});

// choropleth
$("#mmi_btnGetIndicatorsRec").click(function(e) {
    $.ajax({
        url: 'websig',
        type: 'POST',
        dataType: 'json',
        data: {'action': 'get_indicFiltersIds', 
            'type': $('#mmi_type').val(),
            'gender': $('#mmi_gender').val(),
            'agegroup': $('#mmi_agegroup').val(),
            'status': $('#mmi_status').val(),
            'citizenship': $('#mmi_citizenship').val(),
            'formfexplotation': $('#mmi_formfexplotation').val(),
        },
        success: function(data, status) {

            var context = $('#mmi_geo_context').val();
            var mtype = $('#mmi_type').val();
            var layername = $('#mmi_layer_name').val();
            if (layername == "") {
                layername = " Map Layer " + layercount;
                layercount++;
            }
            var nb_class = $('#mmi_nb_classes').val(); 
            var percent_transp = $('#mmi_percent_transp').val() / 100;
            var colors = $('#mmi_color_scheme').val();
            var style;
            
            var filters = "viewparams=context:" + context + ";nbc:" + nb_class + ";mtype:" + mtype;
            
            if (typeof data["genderid"] !== 'undefined') filters += ";gender:" + data["genderid"];
            if (typeof data["agegroupid"] !== 'undefined') filters += ";agegroup:" + data["agegroupid"];
            if (typeof data["citizenshipid"] !== 'undefined') filters += ";citiz:" + data["citizenshipid"];
            if (typeof data["formfexplotation"] !== 'undefined') filters += ";formofexploit:" + data["formfexplotation"];
            if (typeof data["status"] !== 'undefined') filters += ";status:" + data["status"];
            //  direct codes
            var placeofexploit = $('#mmi_placeof_exploit').val();
            if (placeofexploit !== '') filters += ";exploitcntr:" + placeofexploit;
            var placeofrecruit = $('#mmi_placeof_recruit').val();
            if (placeofrecruit !== '') filters += ";recruitcntr:" + placeofrecruit;
            var placeofwaypoint = $('#mmi_placeof_waypoint').val();
            if (placeofwaypoint !== '') filters += ";waypointcntr:" + placeofwaypoint;
            //  years
            var dateexploitfrom = $('#mmi_registdatefrom').val();
            if (dateexploitfrom !== '') filters += ";dateexploitfrom:" + dateexploitfrom;
            var dateexploitto = $('#mmi_registdateto').val();
            if (dateexploitto !== '') filters += ";dateexploitto:" + dateexploitto;
            var daterecruitfrom = $('#mmi_recruitdatefrom').val();
            if (daterecruitfrom !== '') filters += ";daterecruitfrom:" + daterecruitfrom;
            var daterecruitto = $('#mmi_recruitdateto').val();
            if (daterecruitto !== '') filters += ";daterecruitto:" + daterecruitto;
            
            var wms_url = geoserver_url + "/moSy/wms?" + filters + "&env=valtrans:" + percent_transp;  
            
            if (colors === "discrete") {
                //style = "mosy_discrete";
                style = "mosy_coro1";
            } else {
                style = "mosy_color_ramp";
                var c1 = $("#ramp_color1").spectrum("get").toHex();
                var c2 = $("#ramp_color2").spectrum("get").toHex();
                wms_url += ";fromcol:%23" + c1 + ";tocol:%23" + c2;
            }


            wms_url += "&";

            var wms = addWMSLayer(wms_url, osmaps, "moSy:geostats", 'image/png', true, "MoSy Indicators", "EPSG:3857", false, "1.1.1", style);
            wms.ExtendedLayerControl = {
                removable: true,
                layerTypeName: "MoSy Choropleth",
                layerTypeId: 2,
                haveProperties: true,
                activeIdentify: false
            }
            if (colors !== "discrete") {
                wms.ExtendedLayerControl.fromColor = c1;
                wms.ExtendedLayerControl.toColor = c2;
            }
            layerControl.addOverlay(wms, layername, {groupName: "Choropleth", expanded: true, removable: true});


        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });




});
    
    
    
// Graph
$("#mmi_btnGetGraph").click(function(e) {
    $.ajax({
        url: 'websig',
        type: 'POST',
        dataType: 'json',
        data: {'action': 'get_indicFiltersIds', 
            'type': $('#mmi_type').val(),
            'gender': $('#mmi_gender').val(),
            'agegroup': $('#mmi_agegroup').val(),
            'status': $('#mmi_status').val(),
            'citizenship': $('#mmi_citizenship').val(),
            'formfexplotation': $('#mmi_formfexplotation').val(),
        },
        success: function(data, status) {

            var context = $('#mmi_geo_context').val();
            var mtype = $('#mmi_type').val();
            var layername = $('#mmi_layer_name').val();
            if (layername == "") {
                layername = " Map Layer " + layercount;
                layercount++;
            }
            var nb_class = $('#mmi_nb_classes').val(); 
            var percent_transp = $('#mmi_percent_transp').val() / 100;
            var colors = $('#mmi_color_scheme').val();
             
            var filters = "viewparams=context:" + context + ";nbc:" + nb_class + ";mtype:" + mtype;
            
            if (typeof data["genderid"] !== 'undefined') filters += ";gender:" + data["genderid"];
            if (typeof data["agegroupid"] !== 'undefined') filters += ";agegroup:" + data["agegroupid"];
            if (typeof data["citizenshipid"] !== 'undefined') filters += ";citiz:" + data["citizenshipid"];
            
            // ---------------------------------------- direct codes
            var placeofexploit = $('#mmi_placeof_exploit').val();
            if (placeofexploit !== '') filters += ";exploitcntr:" + placeofexploit;
            var placeofrecruit = $('#mmi_placeof_recruit').val();
            if (placeofrecruit !== '') filters += ";recruitcntr:" + placeofrecruit;
            var placeofwaypoint = $('#mmi_placeof_waypoint').val();
            if (placeofwaypoint !== '') filters += ";waypointcntr:" + placeofwaypoint;
            // ---------------------------------------- 
            //  years
            var dateexploitfrom = $('#mmi_registdatefrom').val();
            if (dateexploitfrom !== '') filters += ";dateexploitfrom:" + dateexploitfrom;
            var dateexploitto = $('#mmi_registdateto').val();
            if (dateexploitto !== '') filters += ";dateexploitto:" + dateexploitto;
            var daterecruitfrom = $('#mmi_recruitdatefrom').val();
            if (daterecruitfrom !== '') filters += ";daterecruitfrom:" + daterecruitfrom;
            var daterecruitto = $('#mmi_recruitdateto').val();
            if (daterecruitto !== '') filters += ";daterecruitto:" + daterecruitto;

            var wms_url = geoserver_url + "/moSy/wms?" + filters + "&env=valtrans:" + percent_transp;  
            
            wms_url += "&";

            var fly_route = $('#mmi_fly_view').val();  
            var layer;
            if (fly_route == "true") {
                layer = "moSy:geostat_graph_fly";
            } else {
                layer = "moSy:geostat_graph";
            }
            
            var wms_graph = addWMSLayer(wms_url, osmaps, layer, 'image/png', true, "MoSy Indicators", "EPSG:3857", false, "1.1.1", "mosy_lines");
            wms_graph.ExtendedLayerControl = {
                removable: true,
                layerTypeName: "MoSy Graph",
                layerTypeId: 3,
                haveProperties: true,
                activeIdentify: false
            }
            layerControl.addOverlay(wms_graph, layername + " (graph)", {groupName: "Routing", expanded: true});
            
            
            var wms_node = addWMSLayer(wms_url, osmaps, "moSy:geostat_graph_pts", 'image/png', true, "MoSy Indicators", "EPSG:3857", false, "1.1.1", "mosy_pts");
            wms_node.ExtendedLayerControl = {
                removable: true,
                layerTypeName: "MoSy Graph Nodes",
                layerTypeId: 4,
                haveProperties: true,
                activeIdentify: false
            }
            layerControl.addOverlay(wms_node, layername + " (nodes)", {groupName: "Routing", expanded: true});





        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });




});
    

function update_servicesList(group_name) {
    $("#mmc_cbx_services").empty();
    $("#mmc_wmsUrl").val("");
    $('#mmc_cbx_services').append(new Option());
    $.ajax({
        url: 'websig',
        type: 'POST',
        dataType: 'json',
        data: {'action': 'get_serviceslist', 'groupName': group_name},
        success: function(data, status) {

            for (i = 0; i < data.length; i++) {
                var newOpt = new Option(data[i].service_name);
                newOpt.setAttribute('ws_url', data[i].service_url);
                if ((data[i].service_name) !== undefined) {
                    $('#mmc_cbx_services').append(newOpt)
                };
            };
        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });
};

//------------------------------------------------------------------------------------------
var controlMeasure = null;
var controlMeasureArea = null;
var osmaps = null;
var layerContol = null;

$(document).ready(function()
{
    osmaps = OSGeoInitialize();

    // Highlight search box text on click 
    $("#searchbox").click(function() {
        $(this).select();
    });
    $("#loading").hide();
});

function isvalidCoord(val) {
    if (!isNaN(parseFloat(val)) && (val > -180 && val < 180)) {
        return true;
    } else {
        return false;
    }
};

function getColor(d) {
    return d > 7 ? '#8c510a' :
            d > 6 ? '#d8b365' :
            d > 5 ? '#f6e8c3' :
            d > 4 ? '#f5f5f5' :
            d > 3 ? '#c7eae5' :
            d > 2 ? '#5ab4ac' :
            d > 1 ? '#01665e' :
            '#FFFFFF';
}

function style(feature) {
    return {
        fillColor: getColor(feature.properties.popup),
        weight: 2,
        opacity: 1,
        color: 'white',
        dashArray: '3',
        fillOpacity: 0.7
    };
}

// Map + geonames
function OSGeoInitialize(question, latLng) {

    var blanck_base = L.geoJson();
   



















    var mosy_cntr_wms = L.tileLayer.wms(geoserver_url + "/moSy/wms", {
        layers: 'moSy:cntr_2010_60m',
        format: 'image/png',
        transparent: true
    });
	
	var OpenStreetMap_Mapnik = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
		maxZoom: 19,
		attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
	});
	
	var Esri_WorldStreetMap = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', {
		attribution: 'Tiles &copy; Esri &mdash; Source: Esri, DeLorme, NAVTEQ, USGS, Intermap, iPC, NRCAN, Esri Japan, METI, Esri China (Hong Kong), Esri (Thailand), TomTom, 2012'
	});
	
	var Esri_WorldImagery = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
		attribution: 'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
	});
       
    var baseMaps = [
        {
            groupName: "Base Maps",
            expanded: true,
            layers: {
                "None": blanck_base,
				//"Mosy Countries": mosy_cntr_wms,
				"Open Street Map": OpenStreetMap_Mapnik,
				"ESRI World Street Map": Esri_WorldStreetMap,
				"ESRI World Imagery": Esri_WorldImagery



            }

        }
    ];
    
    var overlays = [
    ];
    
    var options = {
        container_width: "242px",
        container_maxHeight: "350px",
        group_maxHeight: "1500px",
        exclusive: false
    };

    var map = L.map("map", {
        zoom: 2,
        minZoom: 2,
        center: [15, 15],
        maxBounds: ([[-90, -180], [90, 180]])
                //layers: [blanck_base]
    });

    map.on('click', function(e) {
        mapCLick(e);
    });

    layerControl = L.Control.extendedLayerControl(baseMaps, overlays, options);
    map.addControl(layerControl);
    map.addLayer(Esri_WorldStreetMap);

    controlMeasure = L.control.measure().addTo(map);
    controlMeasureArea = L.control.measureArea().addTo(map);
    scaleCtrl = L.control.scale().addTo(map);
    L.easyPrint().addTo(map)

    // side panel about
    var sidebar = L.control.sidebar("sidebar", {
        closeButton: true,
        position: "left"
    }).addTo(map);

    $('#aboutPanel').on('click', function() {
        if (statbar.isVisible()) {
            statbar.hide();
        }
        sidebar.toggle();
    });

    // stat panel
    var statbar = L.control.sidebar("statbar", {
        closeButton: true,
        position: "left"
    }).addTo(map);

    $('#statisticPanel').on('click', function() {
        if (sidebar.isVisible()) {
            sidebar.hide();
        }
        statbar.toggle();
    });

    // layerProperties panel
    layerPropertiesBar = L.control.sidebar("layerProperties", {
        closeButton: true,
        position: "right"
    }).addTo(map);

    function zoomExtent() { // todo: restrict to rect ?
        map.setView([15, 15], 2);
    }

    $('#zoomExtent').on('click', function() {
        zoomExtent()
    })


    function isNumber(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }

    /* Typeahead search functionality */
    var geonamesBH = new Bloodhound({
        name: "GeoNames",
        datumTokenizer: function(d) {
            return Bloodhound.tokenizers.whitespace(d.name);
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: "http://api.geonames.org/searchJSON?username=limesurvey&featureClass=P&maxRows=5&name_startsWith=%QUERY",
            filter: function(data) {
                return $.map(data.geonames, function(result) {
                    return {
                        name: result.name + ", " + result.countryName,
                        lat: result.lat,
                        lng: result.lng,
                        source: "GeoNames"
                    };
                });
            },
            ajax: {
                beforeSend: function(jqXhr, settings) {

                    if ($("#restrictToExtent").prop('checked')) {
                        settings.url += "&east=" + osmaps['' + question].getBounds().getEast() + "&west=" + osmaps['' + question].getBounds().getWest() + "&north=" + osmaps['' + question].getBounds().getNorth() + "&south=" + osmaps['' + question].getBounds().getSouth();
                    }
                    $("#searchicon").removeClass("fa-search").addClass("fa-refresh fa-spin");
                },
                complete: function(jqXHR, status) {
                    geonamesBH.clearRemoteCache(); //clear cache
                    $('#searchicon').removeClass("fa-refresh fa-spin").addClass("fa-search");
                }
            }
        },
        limit: 10
    });

    geonamesBH.initialize();

    /* instantiate the typeahead UI */
    $("#searchbox").typeahead({
        minLength: 3,
        highlight: true,
        hint: false
    }, {
        name: "GeoNames",
        displayKey: "name",
        source: geonamesBH.ttAdapter(),
        templates: {
            header: "<h4 class='typeahead-header'><img src='theme/mosy/resources/websig/img/globe.png' width='25' height='25'>&nbsp;GeoNames</h4>"
        }
    }).on("typeahead:selected", function(obj, datum) {
        if (datum.source === "GeoNames") {
            osmaps.setView([datum.lat, datum.lng], 13);
        }

        if ($(".navbar-collapse").height() > 50) {
            $(".navbar-collapse").collapse("hide");
        }
    }).on("typeahead:opened", function() {
        $(".navbar-collapse.in").css("max-height", $(document).height() - $(".navbar-header").height());
        $(".navbar-collapse.in").css("height", $(document).height() - $(".navbar-header").height());
    }).on("typeahead:closed", function() {
        $(".navbar-collapse.in").css("max-height", "");
        $(".navbar-collapse.in").css("height", "");
    });
    $(".twitter-typeahead").css("position", "static");
    $(".twitter-typeahead").css("display", "block");

    return map;

}

/* Placeholder hack for IE */
if (navigator.appName == "Microsoft Internet Explorer") {
    $("input").each(function() {
        if ($(this).val() === "" && $(this).attr("placeholder") !== "") {
            $(this).val($(this).attr("placeholder"));
            $(this).focus(function() {
                if ($(this).val() === $(this).attr("placeholder"))
                    $(this).val("");
            });
            $(this).blur(function() {
                if ($(this).val() === "")
                    $(this).val($(this).attr("placeholder"));
            });
        }
    });
}

function mapZoom(zoom) {
    osmaps.setZoom(zoom, true);
};

function mapLatLong(lat,lng,zoom) { //default: zoom=8 
    var latlng = L.latLng(lat, lng);
    osmaps.setView(latlng,zoom || 8,true);
};

function pinMarker(lat,lng) { 
    marker = new L.marker([lat,lng], {title:'URL Location !',id:1,draggable:'false'});
    osmaps.addLayer(marker);
};

// Color Func
function rgbToHex(R,G,B) { return toHex(R)+toHex(G)+toHex(B); }
function toHex(n) {
 n = parseInt(n,10);
 if (isNaN(n)) return "00";
 n = Math.max(0,Math.min(n,255));
 return "0123456789ABCDEF".charAt((n-n%16)/16)
      + "0123456789ABCDEF".charAt(n%16);
}


function mapCLick(e) {
    $('#map').css('cursor', '-moz-grab');

    var onBut = $(".butgetcntr[value='on']").attr('id')
    if (typeof onBut === 'undefined') {
        layerControl.getFeatureInfoEvent(e);
        return;
    } else {
        layerControl.resetIdentify();
        $('#' + onBut).val('load');
    }

    $.ajax({
        url: 'websig',
        type: 'POST',
        dataType: 'json',
        data: {'action': 'get_cntr',
            'lat': e.latlng.lat,
            'lng': e.latlng.lng
        },
        success: function(data, status) {
            if (typeof data["cntr_code"] !== 'undefined')
                $('#' + onBut.slice(0, -4)).val(data["cntr_code"]);

            $('#' + onBut).val('off');

        },
        error: function(xhr, desc, err) {
            $('#' + onBut).val('off');
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });
}

$(".butgetcntr").click(function(e) {
    if ($(this).val() === 'on') {
        $(this).val('off');
        return;
    }
    $(".butgetcntr[value='on']").val('off');
    $(this).val('on');
    $('#map').css('cursor', 'crosshair');
});


function ShowLoading(element, cancel, xhr) {
    var msg = '<div class="loading-indicator"><div class="progress progress-striped active"><div class="progress-bar progress-bar-info" style="width: 100%"></div></div></div>';

    var options = {
        message: msg,
        overlayCSS: {
            backgroundColor: '#000',
            opacity: 0.1,
            cursor: 'wait'
        },
        css: {
            border: '0px solid #aaa',
            width: '50%',
            backgroundColor: '',
        },
        onOverlayClick: $.unblockUI
    };

    if (element) {
        if (cancel) {
            options.onOverlayClick = function(e) {
                if (xhr) {
                    xhr.abort();
                }
                $(element).unblock();
            }
        }

        $(element).block(options);
    } else {
        if (cancel) {
            options.onOverlayClick = function(e) {
                if (xhr) {
                    xhr.abort();
                }
                $.unblockUI()
            }
        }

        options.message = '<div class="loading-indicator"><div class="progress progress-striped active"><div class="progress-bar progress-bar-info" style="width: 100%"></div></div></div>';
        options.css.width = '10%';
        options.css["margin-left"] = '100px';

        $.blockUI(options);
    }
};

function HideLoading(element) {
    if (element) {
        $(element).unblock();
    } else {
        $.unblockUI();
    }
};