﻿
var county = '';
var addressID = '';
var latitudeID = '';
var longitudeID = '';
var imageMapID = '';
var delayMilis = 1000;
function onChangeShowLinkMap(showMapID, ddCountyID) {
    //alert($("#" + ddCountyID).val());

    if ($("#" + ddCountyID).val() != null && $("#" + ddCountyID).val() != '' && $("#" + ddCountyID).val() != 'undefined') {

        disableImageMap(showMapID, false);

        county = jQuery.trim($("#" + ddCountyID + " option:selected").text());
    }
    else {
        disableImageMap(showMapID, true);
        county = '';
    }
}

function onClickShowMap(divID, addID, imgID, latID, longID) {
    //alert("addID: "+ addID);

    addressID = addID;
    imageMapID = imgID;
    latitudeID = latID;
    longitudeID = longID;

    $("#" + divID).dialog('open');
}

function formatAddressSelected(latId, longId,addID, ddDistrictID, ddCountyID) {

    var lat = $("#" + latId).val();
    var lng = $("#" + longId).val();
    var add = $("#" + addID).val();
    var c = $("#" + ddCountyID + " option:selected").text();
    var d = $("#" + ddDistrictID + " option:selected").text();

    return formatAddress(lat, lng, add, c, d);
}

function formatAddress(lat, lng, add, c, d) {
    
    // se tiver latitude e longitude é o que envio, cc mando o endereço formatado
    if (lat.length > 0 && lng.length > 0) {
        return (lat + ", " + lng);
    }

    var fAdd = '';
    if (add.length > 0) {
        fAdd += add + ", ";
    }
    fAdd += c + ", " + d + ", portugal";
    return fAdd;
}


// realiza uma chamada em AJAX para buscar todas as situações reportadas para o munícipio escolhido
function getAllSituations(ddDistrictID, ddCountyID, fnCallback) {

    var dd = $("#" + ddDistrictID + " option:selected").text();
    var d = $("#" + ddDistrictID).val();
    var cc = $("#" + ddCountyID + " option:selected").text();
    var c = $("#" + ddCountyID).val();
    var add = $("#" + addressID).val();

    $.ajax({
        type: "POST",
        url: "getAllSituations.aspx",
        data: "d=" + d + "&dd=" + dd + "&c=" + c + "&cc=" + cc + "&add=" + add,
        async: false,
        processData: false,
        dataType: "text/plain",
        success: function(data) {        
            if (fnCallback != null) {
                fnCallback(data);
            }
        },
        error:function(x,e){
			if(x.status==0){
			alert('Erro ao carregar as ocorrências para o município escolhido!\n\nYou are offline!!\n Please Check Your Network.');
			}else if(x.status==404){
			alert('Erro ao carregar as ocorrências para o município escolhido!\n\nRequested URL not found.');
			}else if(x.status==500){
			alert('Erro ao carregar as ocorrências para o município escolhido!\n\nInternel Server Error.');
			}else if(e=='parsererror'){
			alert('Erro ao carregar as ocorrências para o município escolhido!\n\nError.\nParsing JSON Request failed.');
			}else if(e=='timeout'){
			alert('Erro ao carregar as ocorrências para o município escolhido!\n\nRequest Time out.');
			}else {
			alert('Erro ao carregar as ocorrências para o município escolhido!\n\nUnknow Error.\n'+x.responseText);
			}
		}
    });

}
/*
function loadDataToDOM(xmlData) {

    try {
        //alert(xmlData);
        var markers = $(xmlData).find("marker");

        $(markers).each(function() {
            var marker = $(this);
            var LatLong = '';
            if (marker.attr("latitude").length > 0 && marker.attr("longitude").length > 0) {
                LatLong = marker.attr("latitude") + " , " + marker.attr("longitude");
            }
            //alert("LatLong:" + LatLong);
            setMarkers(marker.attr("address") + "[|]" + marker.attr("markertitle") + "[|]" + marker.attr("content") + "[|]" + LatLong + "[|]" + marker.attr("marker"));
        });

    } catch (e) {
        alert("Error:" + e);
    }
}
*/
function disableImageMap(objId, disable) {
    var obj = document.getElementById(objId);
    if (obj != null) {
        if (disable) {
            var onclick = obj.getAttribute("onclick");
            var title = obj.getAttribute("title");
                        
            if (onclick != null) {
                obj.setAttribute('onclick_back', onclick);
                obj.setAttribute('onclick', "void(0);");
            }
            
            if (title != null) {
                obj.setAttribute('title_back', title);
                obj.setAttribute('title', "");
            }

            var src = obj.getAttribute("src");
            var src_off = obj.getAttribute("src_off");
            if (src != null && src_off != null) {                
                obj.setAttribute('src', src_off);
            }

            obj.removeAttribute('onclick');
            obj.removeAttribute('title');

            obj.style.cursor = "default";

        }
        else {
            var onclickBack = obj.getAttribute("onclick_back");
            var titleBack = obj.getAttribute("title_back");
            if (onclickBack != null) {
                obj.setAttribute('onclick', onclickBack);
                obj.removeAttribute('onclick_back');
            }
            
            if (titleBack != null) {
                obj.setAttribute('title', titleBack);
                obj.removeAttribute('title_back');
            }

            var src = obj.getAttribute("src");
            var src_on = obj.getAttribute("src_on");
            if (src != null && src_on != null) {
                obj.setAttribute('src', src_on);
            }
            
            obj.style.cursor = "pointer";
        }
    }
}

/**
* Delay for a number of milliseconds
*/
function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

/*
* Função que permite criar um mapa só com um ponto
*/
fnSimpleMap = function() {
    // Lisboa
    var initLat = "38.70716";
    var initLong = "-9.13552";
    var initZoom = 15;

    var geocoder;
    var place;
    var map;
    var markers = [];

    var markerTitle = '';
    var markerContent = '';

    this.initialize = function(divMapID) {
        if (GBrowserIsCompatible()) {
            map = new GMap2(document.getElementById(divMapID));
            map.setUIToDefault();

            map.setCenter(new GLatLng(initLat, initLong), initZoom);
            map.addControl(new GOverviewMapControl());

            geocoder = new GClientGeocoder();
            geocoder.setBaseCountryCode('PT');
        }
        else {
            alert("Este browser não é suportado pelo google maps!");
        }
    };

    /// show address in map
    this.showAddress = function(response) {
        if (!response || response.Status.code != 200) {
            if (response.Status.code == 620) {
                sleep(delayMilis);
            }
            else {
                alert("Erro ao obter informação do google maps.\n\n[Information code:" + response.Status.code + "]");
            }
        } else {
            place = response.Placemark[0];
            point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);

            if (place != null) {
                var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
                var marker = new GMarker(point, { title: markerTitle });
                GEvent.addListener(marker, "click", function() {
                    marker.openInfoWindowHtml(markerContent);
                }
                    );

                if (marker != null) {
                    map.addOverlay(marker);
                }

                map.setCenter(point, initZoom);
            }
        }
    };

    ///get address by local
    this.getAddressByLocal = function(local) {
        if (geocoder) {
            geocoder.getLocations(local, this.showAddress);
        }
    };

    this.onClickShowMap = function(divID, address, markertitle, content, latitude, longitude) {
        $("#" + divID).dialog('open');
        markerTitle = markertitle;
        markerContent = content;
        fAdd = formatAddress(latitude, longitude, address)
        this.getAddressByLocal(fAdd);
    };
}