﻿var geo;
var map;
var reasons;
var noUpdate = false;
var icon;
var currentMarker;
var showLocation;
var currentClickedMarker;
var clickEventListener = null;
var overlays = [];
var clubIcon, eventIcon, spotIcon, locationIcon;
var safeMapBounds;



function SetIcon(type) {
    icon = type;
}

function InitMapAdd() {
  
    clubIcon = "/images/gfx/icon/pointeur_club.png";
    eventIcon = "/images/gfx/icon/pointeur_event.png";
    spotIcon = "/images/gfx/icon/pointeur_spot.png";

    locationIcon = "/images/gfx/icon/mini_site.png";

    // for step 2
    if (document.getElementById("addressMap") == null)
        return;

    var mapOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP  };

    if ((latitude != null) && (document.getElementById(latitude).value != "")) { // case 

        var lat = parseFloat(document.getElementById(latitude).value);
        var lng = parseFloat(document.getElementById(longitude).value);
        mapOptions.center = new google.maps.LatLng(lat, lng);
        mapOptions.zoom = 7;
        map = new google.maps.Map(document.getElementById("addressMap"), mapOptions);

       InitMarkerPosition(mapOptions.center,true);

    }
    else if ((centerLatitude != null) && (document.getElementById(centerLatitude).value != "")) {
        var centerLat = parseFloat(document.getElementById(centerLatitude).value);
        var centerLng = parseFloat(document.getElementById(centerLongitude).value);
        var zoom = parseInt(document.getElementById(centerZoom).value) - 1;
        mapOptions.center = new google.maps.LatLng(centerLat, centerLng);
        mapOptions.zoom = zoom;
        map = new google.maps.Map(document.getElementById("addressMap"), mapOptions);

        google.maps.event.addListener(map, 'click', function (event) {
            InitMarkerPosition(event.latLng);
          });
    }
    else {
        mapOptions.center = new google.maps.LatLng(0, 0);
        mapOptions.zoom = 15;

        map = new google.maps.Map(document.getElementById("addressMap"), mapOptions);

        google.maps.event.addListener(map, 'click', function (event) {
            InitMarkerPosition(event.latLng);
        }); 
    }


    geo = new google.maps.Geocoder();

//    google.maps.event.addListener(map, 'zoom_changed', function (overlay, point) {       
//        UpdateMarkers();
//    });

//    google.maps.event.addListener(map, 'bounds_changed', function () {
//        UpdateMarkers();
//    });

   
    $("#" + divExistingSites).html("");
    $("#" + divExistingSites).hide();  
    
}

function CreateMarker(point, html, address, locationID) {
//    var marker;
//    marker = new GMarker(point, { icon: locationIcon });

//    GEvent.addListener(marker, "click", function() {

//        // update list site
//        if (divExistingSites != null) {
//            currentClickedMarker = marker;
//            var updateLoc = "<div><img src='/images/gfx/other/fleche_droite.gif'/><a onclick=\"UpdateLocation(" + locationID + ");return false;\" href=\"#\" >" + ResourceManager.GetString("add_UseEntry") + "</a> </div>";
//            document.getElementById(divExistingSites).innerHTML = html + address + updateLoc;
//            $("#" + divExistingSites).html(html + address + updateLoc);
//            $("#" + divExistingSites).STshow("slow");   
//        }
//    });
//    return marker;
}


function UpdateLatLong(point) {
    document.getElementById(latitude).value = point.lat();
    document.getElementById(longitude).value = point.lng();
}


function Geocodeaddr() {
    if (noUpdate)
        return;

    var i = document.getElementById(dlCountry).selectedIndex;
    var textCountry = document.getElementById(dlCountry).options[i].text;

    var emptyAddress = false;
    if ((document.getElementById(tbAddress1).value == '') &&
        (document.getElementById(tbAddress2).value == '') &&
        (document.getElementById(tbPostCode).value == '') &&
        (document.getElementById(tbCity).value == ''))
        emptyAddress = true;
     
     
    // Perform the Geocoding
    var addr = document.getElementById(tbAddress1).value + ',' +
	           document.getElementById(tbAddress2).value + ',' +
	           document.getElementById(tbPostCode).value + ',' +
	           document.getElementById(tbCity).value + ',' +
	           textCountry;

    geo.geocode({ address: addr }, function (result, status) {

        if (status == google.maps.GeocoderStatus.OK && result[0]) {
                    
            InitMarkerPosition(result[0].geometry.location);

            if (emptyAddress) {
                map.setCenter(result[0].geometry.location);
                map.setZoom(6);
            }
            else {
                map.setCenter(result[0].geometry.location);
                map.setZoom(14);
            }

            //            document.getElementById('cbShowLocation').checked = true;
            //            ShowLocation(true);            
        }
        else {

            $('#errorAddress').jqmShow();
        }
    });
}

// handy method to fill in the lat and lng fields by clicking on the map.
function InitMarkerPosition(point,draggable) {

    clearOverlays();
    safeMapBounds = null;

    var image;

    if (icon == "club")
        image = clubIcon;
    else if (icon == "event")
        image = eventIcon; 
    else if (icon == "spot")
        image = spotIcon; 
    
    var marker = new google.maps.Marker({
        position: point,
        map: map,
        icon: image,
        draggable: true
    });

    overlays.push(marker);
    currentMarker = marker;

    UpdateLatLong(point);

    google.maps.event.addListener(currentMarker, 'dragend', function () {
        UpdateLatLong(currentMarker.position);        
    }); 

//    GEvent.addListener(currentMarker, "dragend", function() {
//        var pointDrag = currentMarker.getPoint();
//        UpdateLatLong(pointDrag);
//    });
//    
//    GEvent.addListener(currentMarker, "click", function() {
//        $("#" + divExistingSites).html("");
//        $("#" + divExistingSites).hide();   
//    });
    

//    var cbShowLoc = document.getElementById('cbShowLocation');
//    if (cbShowLoc != null)
//        ShowLocation(cbShowLoc.checked);
}

function ChangeTypeCurrentMarker() {
    
    if (currentMarker == null)
        return;
    
    var currentPoint = currentMarker.position;

    InitMarkerPosition(currentPoint);
    
    //document.getElementById('cbShowLocation').checked = false;
}


function clearOverlays() {

    for (var n = 0, overlay; overlay = overlays[n]; n++) {
        overlay.setMap(null);
    }
    // Clear overlays from collection
    overlays = [];
}




//function ObjectLocation(lat, lng, locationID, addressLine1, addressLine2, postcode, town, country,countryID) {
//    this.lat = lat;
//    this.lng = lng;
//    this.locationID = locationID;

//    this.addressLine1 = addressLine1;
//    this.addressLine2 = addressLine2;
//    this.postcode = postcode;
//    this.town = town;
//    this.country = country;
//    this.countryID = countryID;
//}

//function UpdateLocation(locationID) {
//    for (var i = 0; i < existingLocations.length; i++) {
//        if (existingLocations[i].locationID == locationID) {
//            document.getElementById(latitude).value = existingLocations[i].lat;
//            document.getElementById(longitude).value = existingLocations[i].lng;
//            document.getElementById(tbAddress1).value = existingLocations[i].addressLine1;
//            document.getElementById(tbAddress2).value = existingLocations[i].addressLine2;
//            document.getElementById(tbPostCode).value = existingLocations[i].postcode;
//            document.getElementById(tbCity).value = existingLocations[i].town;
//            document.getElementById(dlCountry).value = existingLocations[i].countryID;           
//            
//            //document.getElementById('cbShowLocation').checked = false;
//            InitMarkerPosition(new google.map.LatLng(existingLocations[i].lat, existingLocations[i].lng));
//            
//            return;
//        }
//    }
//}


//function ShowLocation(show) {
//    showLocation = show;
//    document.getElementById('tooManyLoc').style.display = "none";
//    // don't show location
//    if (!showLocation) {
//        clearOverlays();
//        safeMapBounds = null;
//        // add marker currentMarker
//        if (currentMarker != null)
//            map.addOverlay(currentMarker);
//        // hide existing site
//        $("#" + divExistingSites).html("");
//        $("#" + divExistingSites).hide();   
//    }
//    else {
//        UpdateMarkers();
//    }

//}

//function UpdateMarkers() {

//    if (!showLocation)
//        return;

//    //create the boundry for the data to provide
//    //initial filtering
//    var mapBounds = map.getBounds();
//    var southWest = mapBounds.getSouthWest();
//    var northEast = mapBounds.getNorthEast();

//    if (safeMapBounds != null) {
//        if (safeMapBounds.contains(southWest) && safeMapBounds.contains(northEast))
//            return;
//    }

//    var param = '{"neLat":"' + mapBounds.getNorthEast().lat() +
//                '","neLong":"' + mapBounds.getNorthEast().lng() +
//                '","swLat":"' + mapBounds.getSouthWest().lat() +
//                '","swLong":"' + mapBounds.getSouthWest().lng() +
//                '"}';

//    $.ajax({
//        type: "POST",
//        url: "/WebServices/SportTribeWebService.asmx/GetAllLocations",
//        contentType: "application/json; charset=utf-8",
//        dataType: "json",
//        data: param,
//        //processData: false,
//        error: function (xhr, message) { }, //alert(xhr.responseText); ,
//        success: function (resXml) { populateMap(resXml); }
//    }); 

//}

//function populateMap(resXml) {
//    
//        var xmlDoc = GXml.parse(request.responseText); //request.responseXML;

//        var existingLocations = [];

//        // obtain the array of markers and loop through it
//        if (xmlDoc.documentElement == null)
//            return;

//        var listMarkers = xmlDoc.documentElement.getElementsByTagName("marker");

//        if (xmlDoc.documentElement.getElementsByTagName("tooManyLocation").length != 0) {
//            document.getElementById("tooManyLoc").style.display = "block";

//            clearOverlays();
//            safeMapBounds = null;
//            // add marker currentMarker
//            if (currentMarker != null)
//                currentMarker.setMap(map);
//            return;
//        }
//        document.getElementById('tooManyLoc').style.display = "none";
//        safeMapBounds = map.getBounds();

//        var lat, lng, point, siteList, address, locationID;

//        for (var i = 0; i < listMarkers.length; i++) {
//            // obtain the attribues of each marker
//            lat = parseFloat(listMarkers[i].getAttribute("latitude"));
//            lng = parseFloat(listMarkers[i].getAttribute("longitude"));
//            locationID = parseInt(listMarkers[i].getAttribute("locationID"));

//            // if we are at the same location of the new site then dont add a spot there
//            if ((latitude != null) && (document.getElementById(latitude).value != "")) {
//                var latSite = parseFloat(document.getElementById(latitude).value);
//                var lngSite = parseFloat(document.getElementById(longitude).value);

//                if ((lat == latSite) && (lng == lngSite))
//                    continue;
//            }

//            var objLocation = new ObjectLocation(lat, lng, locationID, listMarkers[i].getAttribute("addressLine1"),
//                                listMarkers[i].getAttribute("addressLine2"),
//                                listMarkers[i].getAttribute("postCode"),
//                                listMarkers[i].getAttribute("town"),
//                                listMarkers[i].getAttribute("country"),
//                                listMarkers[i].getAttribute("countryID"));

//            address = "<div class='miniMarginTop'>";
//            address += objLocation.addressLine1 + " ";
//            address += objLocation.addressLine2 + " ";
//            address += objLocation.postcode + " ";
//            address += objLocation.town + " ";
//            address += objLocation.country;
//            address += "</div>";

//            point = new google.map.LatLng(lat, lng);

//            if (listMarkers[i].firstChild != null) {
//                siteList = listMarkers[i].firstChild.nodeValue;

//                map.addOverlay(CreateMarker(point, siteList, address, locationID));

//                existingLocations.push(objLocation);
//            }

//        }
//}