﻿/// <reference path="Map.debug.js" />
/// <reference name="MicrosoftAjax.js" />
/// <reference path="../Services/DataService.asmx" />


/***************************************************************************\
*                               VARIABLES                                   *
\***************************************************************************/
var _addressMarker = null;
var _currentModal = null;
var _geocodeCallback = null;
var _geocoder = null;
var _loadingAjax = false;
var _loadingMessages = new Array();
var _map = new GenericMap();

/***************************************************************************\
*                               LOADING                                     *
\***************************************************************************/
function CompleteForgotPassword_Click() {
    DataService.ForgotPassword($("#ForgotEmail").val(),
        function(isCreated) {
            if (isCreated)
                alert("Your password has been sent to your email.");
            else
                alert("No such email was found.");
            HideModal();
        },
        function(error) {
            alert("There was a problem sending the email.");
        }
    );
}

function CompleteRegistration() {
    /// <summary>
    /// Completes the registration of the new user.
    /// </summary>

    try {
        var _user = new WebApp.Contact();

        if ($("#NewPassword").val() != $("#NewPassword2").val()) {
            alert("Passwords do not match.");
            return;
        }

        if ($("#NewContactName").val() == "" || $("#NewCompany").val() == "" ||
            $("#NewAddress").val() == "" || $("#NewCity").val() == "" ||
            $("#NewState").val() == "" || $("#NewZIP").val() == "" ||
            $("#NewPhone").val() == "" || $("#NewEmail").val() == "") {
            alert("Not all of the information is completed.");
            return;
        }

        _user.Name = $("#NewContactName").val();
        _user.Company = $("#NewCompany").val();
        _user.Address1 = $("#NewAddress").val();
        _user.Address2 = $("#NewAddressContinued").val();
        _user.City = $("#NewCity").val();
        _user.State = $("#NewState").val();
        _user.ZIP = $("#NewZIP").val();
        _user.Phone = $("#NewPhone").val();
        _user.Email = $("#NewEmail").val();

        DataService.CreateNewUser($("#NewUsername").val(), $("#NewPassword").val(), _user,
            function(error) {
                if (error) {
                    alert(error);
                    return;
                }

                alert("The registration process is complete.  You will be sent an email that you must confirm before logging in.");
                HideModal();
            },
            function() {
                alert("Unable to create a new user.");
            }
        );
    } catch (e) {
        //alert("Unable to complete the registration.");
        alert(e.get_message());
    }
}

function ForgotPassword() {
    ShowModal("ForgotPassword");
}

function HideModal() {
    _currentModal.css("display", "none");
    $("#ModalBackground").fadeTo("normal", 0, function() { $(this).css("display", "none") });
}

function RegisterUser() {
    ShowModal("Registration");
}

function ResizeApplication() {
    /// <summary>
    /// Resizes the application to make everything take up the right amount of space.
    /// </summary>

    var _height = $(window).height();
    var _top = $(".leftNavigation").offset().top;
    var _mapArea = $("#map");
    var _subMap = $("#gMap");
    var _leftNavigation = $(".leftNavigation");

    _height -= _top;
    
    if($("#MapTools").length > 0) {
        var _newHeight = _height;

        _leftNavigation.height(_newHeight);
        $("#LeftNavContent").height(_height + _top - $("#LeftNavContent").offset().top - 10);
    } else {
        _leftNavigation.height(_height);
    }
    
    _mapArea.height(_height - (_mapArea.outerHeight(true) - _mapArea.height()));
    
    if(_map && _map.googleMap)
        _map.googleMap.checkResize();

    // If we are using a custom template, resize accordingly.
    if (_subMap.length > 0) {
        var _offsetTop = _subMap.offset().top - $(_subMap.parent().children()[0]).offset().top;

        if ($("#BottomZipDiv").length == 0 || $("#BottomZipDiv").css("display") == "none")
            _subMap.height(_mapArea.height() - _offsetTop);
        else
            _subMap.height(_mapArea.height() - _offsetTop - ($("#BottomZipDiv").height() + 4));
    }
}

function ShowModal(ModalID) {
    _currentModal = $("#" + ModalID);

    $("#ModalBackground").css("background-color", "#ccc").css("display", "").fadeTo("normal", 0.7,
        function() {
            _currentModal.css({ "display": "block",
                "position": "absolute",
                "z-index": 202
            });
            _currentModal.css("left", ($(window).width() / 2) - (_currentModal.width() / 2));
            _currentModal.css("top", ($(window).height() / 2) - (_currentModal.height() / 2));
        }
    );
}

function SwitchModal(ModalID) {
    _currentModal.css("display", "none");

    _currentModal = $("#" + ModalID);
    _currentModal.css({ "display": "block",
        "position": "absolute",
        "z-index": 202
    });
    _currentModal.css("left", ($(window).width() / 2) - (_currentModal.width() / 2));
    _currentModal.css("top", ($(window).height() / 2) - (_currentModal.height() / 2));
}

/***************************************************************************\
*                               FUNCTIONS                                   *
\***************************************************************************/


function GeocodeException(message, address) {
    /// <summary>
    /// Raised when there is an exception in geocoding.
    /// </summary>
    /// <field name="message" type="String">Provides the error message.</field>
    this.message = message;
    this.address = address;
}

function GeocodeLocation(latlng, description, accuracy, addressdetails) {
    /// <summary>
    /// Provides information about a location returned from the geocoder.
    /// </summary>
    /// <field name="latlng" type="MapPoint">Provides the latitude/longitude of the current point.</field>
    /// <field name="description" type="String">Provides the description for the point.</field>
    this.latlng = latlng;
    this.description = description;
    this.accuracy = accuracy;
    this.addressdetails = addressdetails;
}

Geocoder = function() {
    /// <summary>
    /// Represents a geocoder for the current map.
    /// </summary>

    /// <field name="googleGeocoder" type="GClientGeocoder">The google representation of the geocoder.</field>
}

Geocoder.prototype = {
    googleGeocoder: new GClientGeocoder(),
    i: Math.random(),

    findAddress: function(address, callback) {
        /// <summary>
        /// Finds the specified address and calls the call back function when finished.
        /// </summary>
        /// <param name="address" type="string">The address to be found</param>
        /// <param name="callback" type="Function">The function to be called when the geocoding finishes.</param>
        
        var _geocoder = this.googleGeocoder;
        
        DataService.GetLocation(address,
            function(response) {
                if(!response) {
                    //  Try using google, if we can't find something locally
                    GoogleGeocodeFindAddress(address, callback, _geocoder);
                } else {
                    var _places = new Array();
                    
                    for(var i = 0; i < response.length; i++) {
                        var _place = response[i];
                        _places.push(new GeocodeLocation( new MapPoint(_place.Latitude, _place.Longitude), _place.Name, _place.Accuracy, null));
                    }
                    
                    callback(_places);
                }
            }
        );
    }
}

function GoogleGeocodeFindAddress(address, callback, _googleGeoCoder) {
    _googleGeoCoder.getLocations(address,
        function(response) {
            if (!response || (response.Status.code != 200 && response.Status.code != 620)) {
                callback(new GeocodeException("Unable to find the specified location.", address));
            } else if (response.Status.code == 620) {
                setTimeout(function() {GoogleGeocodeFindAddress(address, callback, _googleGeoCoder);}, 3000);
            
            } else {
                var _places = new Array();

                for (var i = 0; i < response.Placemark.length; i++) {
                    var _place = response.Placemark[i];
                    _places.push(new GeocodeLocation(new MapPoint(_place.Point.coordinates[1], _place.Point.coordinates[0]), _place.address, _place.AddressDetails.Accuracy, _place.AddressDetails));
                }

                callback(_places);
            }
        }
    );
}

/***************************************************************************\
*                               AJAX EVENTS                                 *
\***************************************************************************/
function FinishedAjax(sender, eventArgs)
{
    _loadingAjax = false;
        
    HideLoading();
}

function GetWebRequestFunction(eventArgs)
{
    /// <summary>
    /// Gets the function called by the web request.
    /// </summary>
    
    var _request = eventArgs.get_webRequest();
    var _url = _request.get_url();
    
    return _url.substring(_url.lastIndexOf('/') + 1);
}

function PerformingAjax(sender, eventArgs)
{
    _loadingAjax = true;
        
    var _function = GetWebRequestFunction(eventArgs);
    
    if(_function == "AddLocation" || _function == "AddCustomLocation")
        DisplayLoading("Please wait while your map is created...");
    else
        DisplayLoading("Loading.  Please wait...");
}

/***************************************************************************\
*                               LOADING                                     *
\***************************************************************************/
$(document).ready(function() {
    ResizeApplication();
    _geocoder = new Geocoder();

    // Wrap up the mapping environment.
    if ($("#gMap").length > 0)
        _map.wrapElement("gMap");
    else if ($("#map").length > 0)
        _map.wrapElement("map");

    $("#ModalBackground").fadeTo(1, 0).css("display", "none").css("z-index", 201);
    $("#CloseRegistrationModal").click(function() { HideModal(); });
    $("#CompleteRegistration").click(function() { CompleteRegistration() });
    $("#ClosePasswordModal").click(function() { HideModal(); });
    $("#CompleteForgotPassword").click(CompleteForgotPassword_Click);
    
    // Keep the session alive.
    if(DataService != null && DataService.KeepAlive != null)
        setInterval(function() { DataService.KeepAlive(); }, 60000);

    if (location.href.indexOf('#Register') != -1)
        RegisterUser();
        
    //  this is required to show scroll bars in some speedy javascript browsers(chrome)
    setTimeout(ResizeApplication, 1000);
    
    // Begin watching for ASP.NET Ajax calls.
    try
    {
        if(DisplayLoading)
        {
            Sys.Net.WebRequestManager.add_invokingRequest(PerformingAjax);
            Sys.Net.WebRequestManager.add_completedRequest(FinishedAjax);
        }
    } catch(e) { }
});

$(window).resize(function() {
    ResizeApplication();
});