﻿//*************************
// author: m. salazar
// email: mastereuo [at] yahoo dot com
//*************************

var isLoggedIn = false;
var map = {};
var geocoder = {};

function initialize() {
    if (GBrowserIsCompatible()) {

        var map = new GMap2($get('map'));
        map.setCenter(new GLatLng(0, 0), 0, G_NORMAL_MAP);
        map.addControl(new GLargeMapControl());

        var marker, markersArray = [];
        for (var i = 0; i < 10; i++) {
            marker = newMarker(new GLatLng(i, i * 1.5), i);
            markersArray.push(marker);
        }

        var cluster = new ClusterMarker(map, { markers: markersArray });
        cluster.fitMapToMarkers();
    }
}

function newMarker(markerLocation, markerId) {

    var html = "<input  type=\"button\" value=\"PostToDb\" onclick=\"return PostToDb(" + markerLocation.y + "," + markerLocation.x + ")\" />";
    var marker = new GMarker(markerLocation, { title: 'Marker[' + markerId + ']' });
    GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml('<p>Marker[' + markerId + '] clicked.</p><br/>' + html + '<br/>');
    });
    return marker;
}

function PostLatLong(lat, lon) {
    UpdateDB(lat,lon);
    return;
    
    var a = lat + '|' + lon;
    var g = new WS.WService();
    g.PostLatLong(a, OnPostLatLongComplete, OnError);
}

function OnPostLatLongComplete(result) {
    $get("dispMessage").innerHTML = result;
}

function OnError(result) {
    var msg = "Error occured: " + result.get_message();
    alert(msg);
    $get("dispMessage").innerText = msg;
}

function GetAllAlumni() {
    PageMethods.GetAllAlumni(OnGetAllAlumniComplete, OnError);
}

function OnGetAllAlumniComplete(result) {
    var LATITUDE_MANILA = 14.6010326;
    var LONGITUDE_MANILA = 120.9761599;
    map.setCenter(new GLatLng(LATITUDE_MANILA, LONGITUDE_MANILA), 5, G_NORMAL_MAP);

    // set here the markers 
    var markers = [];
    for (var alum in result) {
        if (result[alum].Latitude && result[alum].Longitude) {
            var latlng = new GLatLng(result[alum].Latitude, result[alum].Longitude)
            var marker = new GMarker(latlng);

            if (isLoggedIn) {

                var ht = "<div class=\"box\">";
                ht = ht + "<img src=\"";
                ht = ht + result[alum].Avatar;
                ht = ht + "\" alt=\"alt\" \/>";
                ht = ht + "<label class=\"txt\">";
                ht = ht + result[alum].FirstName + ' ' + result[alum].LastName + "<\/label>";
                ht = ht + "<label class=\"txt\">";
                ht = ht + result[alum].Batch + ", " + result[alum].Branch + "</label>";
                ht = ht + "<a href=\"http:\/\/www.asmsi.org.ph\/profile.php\?id=";
                ht = ht + result[alum].UserId;
                ht = ht + ">view profile";
                ht = ht + "<\/a>";
                ht = ht + "<\/div>";

                marker = createMarkerWithEvent(marker, ht);
            }
            markers.push(marker);
        }
    }
    var mcOptions = { maxZoom: 13 };
    var markerCluster1 = new MarkerClusterer(map, markers, mcOptions);
    // add 'dragstart' 
    GEvent.addListener(map, "dragstart", function() {
        map.closeInfoWindow();
    });

    addMapControls();
}

function createMarkerWithEvent(m, h) {
    // add 'click' 
    GEvent.addListener(m, 'click', function() {
        m.openInfoWindowHtml(h);
    });
    return m;
}

function OnGetMoreAlumniComplete(result) {
    $get("dispMessage").innerHTML = result;
}

function prepHome() {
    try {
        map = new GMap2($get('map_canvas'));
        geocoder = new GClientGeocoder();

        var currentPage_ = $get("mylocation_");
        if (currentPage_) {
            GetAlumni();
            return;
        }

        currentPage_ = $get("home_");
        if (currentPage_ != null) {
            map.setCenter(new GLatLng(0, 0), 2);
            checkIsLogin();
            return;
        }
    }
    catch (ex) {
        $get("dispMessage").innerText = ex;
    }
}

function checkIsLogin() {
    PageMethods.CheckIsLogin(OnCheckIsLoginComplete, OnError);
}

function OnCheckIsLoginComplete(result) {
    var msg = $get("dispMessage");
    if (result === 0) {
        msg.innerHTML = "Please login <a href=\"http://www.asmsi.org.ph\" target=\"_self\">here</a> to update your map location.";
        isLoggedIn = false;
    } else {
        isLoggedIn = true;
    }
    GetAllAlumni();
}

function addMapControls() {
    map.addControl(new GLargeMapControl());
    map.enableContinuousZoom();
    map.setUIToDefault();
}

function GetAlumni() {
    PageMethods.GetAlumni(OnGetAlumniComplete, OnError);
}

function OnGetAlumniComplete(result) {
    var msg = $get("dispMessage");
    if (null == result) {
        msg.innerHTML = "Please login <a href=\"http://www.asmsi.org.ph\" target=\"_self\">here</a> to update your map location.";
        isLoggedIn = false;
        map.setCenter(new GLatLng(0, 0), 1, G_NORMAL_MAP);
        return;
    }
    //process user's location
    isLoggedIn = true;
    updateTextbox(result.Latitude, result.Longitude);
    map.setCenter(new GLatLng(result.Latitude, result.Longitude), 15, G_NORMAL_MAP);
    map.clearOverlays();

    var m = createMarkerFromLatLng(result.Latitude, result.Longitude);
    map.addOverlay(m);
    addMapControls();
}

// findLocation() is used to enter the sample addresses into the form.
function findLocation(address) {
    $get('w_q').value = address;
     showLocation();
}

// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation() {
    var address = document.getElementById('w_q');

    if (address && (address.value.length > 0)) {
        showProgress("searching location...");
        geocoder.getLocations(address.value, addAddressToMap);
    }
}
    
// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(response) {
    map.clearOverlays();
    clearMessage();
    if (!response || response.Status.code != 200) {
        var msg = "Unable to locate that address.";
        alert(msg);
        $get("dispMessage").innerText = msg;
        //disable UPDATE button
        return;
    } else {
        place = response.Placemark[0];
        var m = createMarkerFromAddress(place);
        map.addOverlay(m);
        map.panTo(new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]));
        updateTextbox(place.Point.coordinates[1], place.Point.coordinates[0]);
    }
}

function createMarkerFromAddress(place) {
    var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
    var marker = new GMarker(point, { draggable: true });
    marker = addEventsToMarker(marker);
    return marker;
}

function createMarkerFromLatLng(lat, lon) {
    var point = new GLatLng(lat, lon);
    var marker = new GMarker(point, { draggable: true });
    marker = addEventsToMarker(marker);
    return marker;
}

function addEventsToMarker(marker) {
    // add 'dragstart' 
    GEvent.addListener(marker, "dragstart", function() {
        map.closeInfoWindow();

        clearMessage();
    });

    // add 'dragend'
    GEvent.addListener(marker, "dragend", function() {
        var point = marker.getPoint();
        updateTextbox(point.y, point.x);
    });

    return marker;
}

function updateTextbox(lat, lon) {
    // textbox is used to hold location for updating
    var lblLat = $get("lblLat");
    var lblLon = $get("lblLon");

    if (lblLat && lblLon) {
        lblLat.value = lat;
        lblLon.value = lon;
    }
}

function showProgress(msg) {
    var d = document.getElementById("dispMessage");
    if (d) {
        d.innerText = msg + "please wait";
    }
}
