﻿/// <reference path="~/Scripts/jquery-1.3.2-vsdoc2.js"/>

var cachedStoreData = null;
var map = null;
var zipChanged = false;
var stateZoom = true;

//page ready function
$(function() {
    initializeBehaviors();

    var zipData = $('.zipcodesearchdata').val();
    if (zipData != '') {
        cachedStoreData = eval('(' + zipData + ')');
        refreshMap();
    }
});

//function that initializes the client side behaviors for all of the controls on the delivery page.
function initializeBehaviors() {
    $('.searchbutton').removeAttr('onclick');
    $('.searchbutton').click(function() {
        performZipSearch();
        return false;
    });

    //wire up the state search links
    $('.stateoptioncontainer a').click(function () {
        var container = $(this).parent();
        var stateName = $('input[type=hidden]', container).val();
        performStateSearch(stateName);
        return false;
    });

    //wire up the zipcode input behaviors
    if ($('.zipcode').val() == '') {
        $('.zipcode').val('ex. 21703');
    }
    $('.zipcode').focus(function () {
        if ($(this).val() == 'ex. 21703')
            $(this).val('');

        $(this).css('backgroundColor', '#ffffff');
    });
    $('.zipcode').blur(function () {
        if ($(this).val() == '')
            $(this).val('ex. 21703');

        $(this).css('backgroundColor', '#f8f8f8');
    });
    $('.zipcode').change(function () { zipChanged = true; });

    $('select.radius').change(function() {
        cachedStoreData = null;
    });

    //wire up the wait modals
    $(document).ajaxStart(blockUI).ajaxStop($.unblockUI);
}

//controls the blocking of the UI during an ajax call.
function blockUI() {
    $.blockUI({ message: '<div style="height: 65px; line-height: 65px;"><h3><img src="/rentals/images/loading.gif" style="vertical-align: middle;"/>  Searching, Please Wait...</h3></div>' });
}

//function that validates the delivery form.
function validateForm() {
    var isSearchValid = true;

    var zipValue = $('.zipcode').val();
    var zipRegExp = /^\d{5}$/;
    if (!zipRegExp.test(zipValue) || zipValue == '00000') {
        isSearchValid = false;
        $('.zipcode').addClass('error');
        $('.zipcode').val('');
        $('.zipcode').css("backgroundColor", "#ffcdcd");

        $('.ziplabel').css("color", "#ff0000");
    }
    else {
        $('.zipcode').removeClass('error');
        $('.ziplabel').css("color", "#646464");
    }

    if (!isSearchValid) {
        $('.rentals_errorMessage').show();
    }
    else {
        $('.rentals_errorMessage').hide();
    }

    return isSearchValid;
}

///function that calls out to find store locations by zipcode/radius.
function performZipSearch() {

    if (!validateForm(false))
        return false;

    stateZoom = false;
    var zipCode = $('.zipcode').val();
    var radius = $('select.radius option:selected').val();
    var requiredPickupLocation = '-2';

    var locationFinderType = $('.locationfindertype').val();
    if(locationFinderType != ''){
        requiredPickupLocation = locationFinderType;
    }

    //if we have cached data let's use it rather than making another call to the service.
    if (!zipChanged && cachedStoreData != null) {
        searchCompleted(cachedStoreData, "Success");
    }
    else {
        cachedStoreData = null;
        //make the service call
        var myUrl = '/Rentals/ClientServices/Rentals.svc/getStores/' + zipCode + '/' + requiredPickupLocation + '/' + radius + '/';
        $.ajax({
            url: myUrl,
            success: searchCompleted
        });
    }
}

function performStateSearch(stateVal) {

    var requiredPickupLocation = '-2';
    stateZoom = true;

    var locationFinderType = $('.locationfindertype').val();
    if (locationFinderType != '') {
        requiredPickupLocation = locationFinderType;
    }

    //make the service call
    cachedStoreData = null;
    var myUrl = '/Rentals/ClientServices/Rentals.svc/getStoresByState/' + stateVal + '/' + requiredPickupLocation + '/';
    $.ajax({
        url: myUrl,
        success: searchCompleted
    });
}

//callback function for when the store search has completed successfully.
function searchCompleted(data, successText) {

    if (cachedStoreData == null) {
        cachedStoreData = data;
    }
    
    //process the template
    $('#storeSearchResultsContainer').setTemplateURL('/Rentals/Templates/LocationSearchResults.htm');
    $('#storeSearchResultsContainer').processTemplate(data);

    $('.rentals_errorMessage2').hide();

    refreshMap();
}

//refreshes the map interface
function refreshMap() {

    var zip = "00000";
    if (!stateZoom) {
        zip = $('.zipcode').val();
    }
    else if (cachedStoreData) {
            zip = cachedStoreData.ZipCode;
    }    
    
    if (map == null) {
        map = new VEMap('map_canvas');
        map.SetDashboardSize(VEDashboardSize.Small);
        map.LoadMap(null, 9, 'r', false, VEMapMode.Mode2D, false);
        map.Find(null, zip, null, null, 0, 1, false, false, false, true, setMapConditions);
    }
    else {
        map.DeleteAllShapes();
        map.DeleteAllShapeLayers();

        map.Find(null, zip, null, null, 0, 1, false, false, false, true, setMapConditions);
    }
}

function setMapConditions() {

    var radius = $('select.radius option:selected').val();

    //load the map shapes
    if (cachedStoreData) {
        var layer = new VEShapeLayer();
        for (var i = 0; i < cachedStoreData.Records.length; i++) {
            var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(cachedStoreData.Records[i].Latitude, cachedStoreData.Records[i].Longitude));
            shape.SetTitle('<b>' + cachedStoreData.Records[i].LocationName + '</b>');
            shape.SetDescription(cachedStoreData.Records[i].Address3 + '<br/>' + cachedStoreData.Records[i].Address4);
            layer.AddShape(shape);
        }

        layer.SetClusteringConfiguration(VEClusteringType.Grid);
        map.AddShapeLayer(layer);
    }

    //set the zoom appropriately depending on the searchdistance.
    var zoomLevel = 9;
    if (!stateZoom) {
        if (radius > 40)
            zoomLevel = 7;
        else if (radius > 20)
            zoomLevel = 8;
    }
    else {
        zoomLevel = 7;
    }

    map.SetZoomLevel(zoomLevel);
}

