﻿var browserSupportsGeo = false;

function getZipCode(returnFunction) {

    var zipCode = $.cookie("ZipCode");
    if (!jQuery.isEmptyObject(zipCode) && zipCode != null && zipCode != undefined && zipCode != "")
        returnFunction(zipCode);
    else {
        // Try W3C Geolocation method (Preferred)
        try {
            if ((Modernizr && Modernizr.geolocation) || navigator.geolocation ) {
                navigator.geolocation.getCurrentPosition(function (position) {
                    handleGeolocation({ Lat: position.coords.latitude, Lon: position.coords.longitude });
                }, error);
            } else {
                // Browser doesn't support Geolocation
                error();
                // TODO: Handle Geolocation without the help of the browser.
            }
        } catch(e) {
            // ignore IE9 modernizer bug
        } 

    }

    function error(msg) {
        browserSupportsGeo = false;
    }
    
    function handleGeolocation(location) {
        var data = { location: location.Lat + "," + location.Lon };

        $.ajax({
            data: $.toJSON(data),
            url: "/static/services/shared/service.asmx/GetZipCode",
            success: function (msg) {
                $.cookie("ZipCode", msg.d);
                returnFunction(msg.d);
            }
        });
    }
}


function setLocation(user) {

    getZipCode(handleSetLocation);
    
    function handleSetLocation(zipCode) {

        var data = {userKey:user.UserKey, zipCode: zipCode };

        $.ajax({
            data: $.toJSON(data),
            url: "/static/services/shared/service.asmx/SetLocation"
        });

    }
}



