﻿
var map;
var geocoder;
var markersArray = []; // holds references to current markers
var markerClusterer = null;
var infoWindow;
var infoBox;
var initialLocation;
var browserSupportFlag = new Boolean();
var isLoggedIn = new Boolean();

var LATITUDE_MANILA = 14.6010326;
var LONGITUDE_MANILA = 120.9761599;
var LATITUDE_DEFAULT = 21.05006570022086;
var LONGITUDE_DEFAULT = -365.443517834375;

// called upon loading

function prepHome() {
    try {

        enableFilter(false);
        geocoder = new google.maps.Geocoder();
        var zoom = 6;
//        v3.1
//        not working because browser doesn't wait for user response
        //        var latlng = detectCurrentLocation();
        var latlng;
        if (latlng == null) {
            latlng = new google.maps.LatLng(LATITUDE_DEFAULT, LONGITUDE_DEFAULT);
            zoom = 2;
        }

        var myOptions = {
            zoom: zoom,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map($get("map_canvas"), myOptions);
        google.maps.event.addListener(map, "dragstart", function () { 
            if (infoBox)
                infoBox.close();
        });

        checkIsLogin();

        var currentPage_ = $get("mylocation_");
        if (currentPage_) {
            if (isLoggedIn === true) {
                GetAlumni();
            } else {
                handleNotLoginUser();
            }
            return;
        }

        currentPage_ = $get("home_");
        if (currentPage_) {
            GetAllAlumni();

            //                    google.maps.event.addListener(map, "drag", function () {
            //                        showMessage('center: ' + map.getCenter() + ' zoom: ' + map.getZoom());
            //                    });
        }
    }
    catch (ex) {
        showMessage("prepHome() failed. Error: " + ex);
    }
}
  
function checkIsLogin() {
    $.ajax({
        type: "POST",
        url: "MyLocation.aspx/CheckIsLogin",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function (data, status, xhr) {
            isLoggedIn = data.d;
        },
        error: function (xhr, status, error) {
            showMessage('checkIsLogin() failed. Error:' + error);
        }
    });
}

function showNotLoginMessage() {
    showMessage("Please login <a href=\"http://www.asmsi.org.ph\" target=\"_self\">here</a> to update your map location.");
}

function handleNotLoginUser() {
    showNotLoginMessage();
    enableFilter(false);

//    v3.1
//    var latlng = detectCurrentLocation();
//    if (latlng) {
//        map.panTo(latlng);
//    }
}

// gets user's location as stored in the DB
function GetAlumni() {
    showMessage('retrieving your location from the database...please wait.');

    $.ajax({
        type: "POST",
        url: "MyLocation.aspx/GetAlumni",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function (data, status, xhr) {
            if (data && data.d) {
                if (data.d.IsLogin === true) {
                    updateTextbox(data.d.Latitude, data.d.Longitude);
                    var latlng = new google.maps.LatLng(data.d.Latitude, data.d.Longitude);
                    map.panTo(latlng);
                    clearOverlays();
                    var marker = setMarkerLocation(latlng);
                    clearMessage();
                } else {
                    isLoggedIn = false;
                    handleNotLoginUser();
                }
            } else {
                showMessage('Null was returned from the service call.');
            }
        },
        error: function (xhr, status, error) {
            showMessage('There was an error while retrieving your location. Error:' + error);
        }
    });
}

function GetAllAlumni() {
    showMessage('retrieving all locations from the database...please wait.');
    enableFilter(false);
    clearOverlays();
    $.ajax({
        type: "POST",
        url: "Default.aspx/GetAllAlumni",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        success: OnGetAllAlumniSuccess,
        error: function (xhr, status, error) {
            showMessage('There was an error while retrieving all locations. Error:' + error);
        }
    });
}

function SearchAlumni(batch) {
    showMessage('retrieving locations for batch:"' + batch + '"...please wait.');
    enableFilter(false);

    clearOverlays();
    var params = '{ "batch":"' + batch + '"}';
    $.ajax({
        type: "POST",
        url: "Default.aspx/Search",
        data: params,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        success: OnSearchAlumniSuccess,
        error: function (xhr, status, error) {
            showMessage('There was an error while retrieving the locations. Error:' + error);
        }
    });
}

// GetAllAlumniComplete callback
function OnGetAllAlumniSuccess(data, status, xhr) {
    clearMessage();

    if (data && data.d) {
        clearOverlays();

        for (var alum in data.d) {
            if (data.d[alum].Latitude && data.d[alum].Longitude) {
                var latlng = new google.maps.LatLng(data.d[alum].Latitude, data.d[alum].Longitude);
                var marker = createMarkerNonDraggable(latlng);

                if (data.d[alum].InfoWindow && data.d[alum].InfoWindow.length > 0) {
                    marker = attachMessageOnClick(marker, data.d[alum].InfoWindow);
                    marker.setTitle(data.d[alum].Batch);
                }
                markersArray.push(marker);
            }
        }
        
        showCount(markersArray.length);

        // add markers to clusterer
        var mcOptions = { 'maxZoom': 15 };
        markerClusterer = new MarkerClusterer(map, markersArray, mcOptions);

        if (isLoggedIn == true)
            showMessage("You can click the markers to see more information.");
        else
            showMessage("Please login <a href=\"http://www.asmsi.org.ph\" target=\"_self\">here</a> to see more information on each marker.");
    }

    enableFilter(true);
}

function OnSearchAlumniSuccess(data, status, xhr) {
    clearMessage();

    if (data && data.d) {
        for (var alum in data.d) {
            if (data.d[alum].Latitude && data.d[alum].Longitude) {
                var latlng = new google.maps.LatLng(data.d[alum].Latitude, data.d[alum].Longitude);
                var marker = createMarkerNonDraggable(latlng);

                if (data.d[alum].InfoWindow && data.d[alum].InfoWindow.length > 0) {
                    marker = attachMessageOnClick(marker, data.d[alum].InfoWindow);
                    marker.setTitle(data.d[alum].Batch);
                }

                markersArray.push(marker);
            }
        }

        showCount(markersArray.length);

        // add markers to clusterer
        var mcOptions = { maxZoom: 15 };
        markerClusterer = new MarkerClusterer(map, markersArray, mcOptions);

        if (isLoggedIn == true)
            showMessage("You can click the markers to see more information.");
        else
            showMessage("Please login <a href=\"http://www.asmsi.org.ph\" target=\"_self\">here</a> to see more information on each marker.");
    }
    enableFilter(true);
}

// detect the user's browser's location  
// and put a marker on it 
function detectCurrentLocation() {
    // Try W3C Geolocation (Preferred)
    if (navigator.geolocation) {
        browserSupportFlag = true;
        navigator.geolocation.getCurrentPosition(function (position) {
            initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            return initialLocation;
        }, function () {
            handleNoGeolocation(browserSupportFlag);
        });
        // Try Google Gears Geolocation
    } else if (google.gears) {
        browserSupportFlag = true;
        var geo = google.gears.factory.create('beta.geolocation');
        geo.getCurrentPosition(function (position) {
            initialLocation = new google.maps.LatLng(position.latitude, position.longitude);
            return initialLocation;
        }, function () {
            handleNoGeoLocation(browserSupportFlag);
        });
        // Browser doesn't support Geolocation
    } else {
        browserSupportFlag = false;
        handleNoGeolocation(browserSupportFlag);
        return initialLocation;
    }

    function handleNoGeolocation(errorFlag) {
        // do nothing for now
    }
}

// findLocation() 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 findLocation() {
    if (geocoder) {
        var address = $get("w_q");
        if (address && (address.value.length > 0)) {
            showMessage("searching location...please wait.");
            geocoder.geocode({ 'address': address.value }, findLocationCallback);
        }
    }
}

// findLocationCallback() 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 findLocationCallback(results, status) {
    clearMessage();

    if (status == google.maps.GeocoderStatus.OK) {
        clearOverlays();
        var latlng = results[0].geometry.location;
        var marker = setMarkerLocation(latlng);
    } else {
        showMessage("Geocode was not successful for the following reason: " + status);
    }
}

function setMarkerLocation(latlng) {
    map.setCenter(latlng);
    map.setZoom(14)

    var marker = createMarker(latlng);
    marker.setMap(map); // show marker 
    marker = addEventsToMarker(marker);
    markersArray.push(marker); // add to list of references
    map.panTo(latlng);
    updateTextbox(latlng.lat(), latlng.lng());

    return marker;
}

//clearOverlays() removes all markers from the map
function clearOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(null);
        }
        //markersArray.length = 0;
        markersArray = [];
        if (markerClusterer) {
            markerClusterer.clearMarkers();
        }
    }

    showCount(0);
}

// creates a draggable marker
function createMarker(location) {
    var marker = new google.maps.Marker({
        map: map,
        position: location,
        draggable: true
    });

    return marker;
}

// creates a non-draggable marker
function createMarkerNonDraggable(location) {
    var marker = new google.maps.Marker({
        map: map,
        position: location,
        draggable: false
    });

    return marker;
}

// given the LAT, LON this method creates a marker
function createMarkerFromLatLng(lat, lon) {
    var latlng = new google.maps.LatLng(lat, lon);
    return createMarker(latlng);
}

// add dragstart and dragend events to marker 
function addEventsToMarker(marker) {
//    v3.1
//    if (infoWindow == null) {
//        infoWindow = new google.maps.InfoWindow();
//    }

    // add 'dragstart'
    google.maps.event.addListener(marker, "dragstart", function () {
        //        v3.1
        //        infoWindow.close();
        if (infoBox)
            infoBox.close();

        clearMessage();
    });

    // add 'dragend'
    google.maps.event.addListener(marker, "dragend", function () {
        var latlng = marker.getPosition();
        updateTextbox(latlng.lat(), latlng.lng());
    });

    return marker;
}

function attachMessageOnClick(marker, msg) {
//    if (infoWindow == null) {
//        infoWindow = new google.maps.InfoWindow();
//    }

    google.maps.event.addListener(marker, 'click', function () {
        //infoWindow.close();
       
        if (infoBox)
            infoBox.close();

        infoBox = new InfoBox({ boxClass: "infoBox", alignBottom: true, closeBoxMargin: "10px" });
        //infoWindow.setContent(msg);
        //infoWindow.open(map, marker);
        infoBox.setContent(msg);
         infoBox.open(map, marker);
    });
   
    return marker;
}

// updates the LAT/LNG holder for future posting to db 
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 showMessage(message) {
    var msg = $get("dispMessage");
    if (msg) {
        msg.innerHTML = message;
    }
}

function clearMessage() {
    var msg = $get("dispMessage");
    if (msg) {
        msg.innerHTML = '';
    }
}

function enableFilter(enable) {
    if (enable && enable == true && isLoggedIn == true) {
        $("#ddlFilter").removeAttr('disabled');
    } else {
        $("#ddlFilter").attr('disabled', 'disabled');
    }
}

function showCount(count) {
    $("#spCount").text('found: ' + count);
}

$(document).ready(function () {
    // Add the page method call as an onclick handler for the button.
    $("#btnUpdate").click(function () {
        var lblLat = $get("lblLat");
        var lblLon = $get("lblLon");
        if (lblLat && lblLon) {
            showMessage('updating your location...please wait.');
            var params = '{ "lat":"' + lblLat.value + '", "lng":"' + lblLon.value + '"}';
            $.ajax({
                type: "POST",
                url: "MyLocation.aspx/UpdateDB",
                data: params,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: function (data, status, xhr) {
                    showMessage('Your location has been updated successfully.');
                },
                error: function (xhr, status, error) {
                    showMessage('There was an error while updating your location to the database. Error:' + error);
                }
            });

        } else {
            showMessage("Error occured: Location is undefined.");
        }

    });

    $("#ddlFilter").change(function () {
        var batch = $(this).val();
        if (batch) {
            if (batch === 'All') {
                GetAllAlumni();
            } else {
                SearchAlumni(batch);
            }
        }
    });   
});
 
