﻿///
/// <reference path="../Edentity.Global.js" />
/// <reference path="../External/jquery-1.4.1-vsdoc.js" />
/// <reference path="../Shoppers.Cookie.js" />

Edentity.RegisterNamespace("Shoppers.Controls.StoreLocatorHeader");

// TODO: Redo scrolltrack image
// TODO: Reinitialize scrollpane when details and close buttons are clicked

(function(SLB, $) {

    var opts = {
        MapId: 'map',
        IconPath: '',
        ResultsListID: 'div.List',
        SelectButtonImageURL: "",
        CloseButtonImageURL: "",
        DetailsLabel: "",
        ResultsPerSearch: 10,
        MyStoreLabel: ""
    };

    var StoreLocatorArea = null;
    var map;
    var geocoder;
    var activeMarkers = new Array();
    var resultsList = null;
    var MapCenter = null;

    SLB.OnInit = function(p) {

        opts = $.extend({}, opts, p || {});
        StoreLocatorArea = $("div.StoreLocatorHeader");
        InitControls();
    };

    SLB.OnSearch = function(sender) {

        var postalcodeStr = $(sender).prev().val().replace(/^\s+|\s+$/g, "");
        var rePostalCode = /^[a-ceghj-npr-tvxy]\d[a-ceghj-npr-tv-z]\s*\d[a-ceghj-npr-tv-z]\d$/i;

        if (rePostalCode.test(postalcodeStr)) {
            Shoppers.Controls.StoreLocatorHeader.Search(postalcodeStr, null);
        }
    };

    SLB.Search = function(postalCode, storeHours) {

        if (storeHours != null) {
            //Request is comming from store locator bar
            ResetSortBy();
            SetStoreHours(storeHours);
        }

        var pc = postalCode.replace(/\s/g, "").toUpperCase();

        var params = "{'PostalCode':'" + pc + "'}";

        $.ajax({
            type: 'POST',
            url: Edentity.ResolveUrl('~/WebServices/AjaxService.asmx/SearchByPostalCode'),
            data: "{'PostalCode':'" + pc + "'}",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(res) {
                if (res != null && res.d != null) {
                    InitGObjects();
                    MapCenter = res.d;
                    map.setCenter(new GLatLng(res.d.Latitude, res.d.Longitude), 10);
                    $("input.PostalCode", StoreLocatorArea).val(pc);
                    var as = $("a.AdvancedSearchLink", StoreLocatorArea);
                    as.attr("href", as.attr("link") + "?pc=" + pc);


                    //store cookie here

                    StorePostalCode(pc)

                    //Search for the stores
                    GetNearestStores();
                }
            },
            complete: function(XMLHttpRequest, textStatus) {
                //alert(XMLHttpRequest.status + ' ' + textStatus);
                //alert(XMLHttpRequest.responseText);
            }
        });
    };


    function StorePostalCode(code) {
        Shoppers.Cookie.Set("eFlyerPostalCode", code, 3600);
    }


    function GetFilters() {
        var filters = [];
        $("input[type=checkbox]", StoreLocatorArea).each(function(idx) {
            if ($(this).is(":checked")) {
                filters[filters.length] = idx;
            }
        });
        return filters.join(",");
    };

    function SetStoreHours(storeHours) {

        var h = parseInt(storeHours);
        if (!isNaN(h)) {
            var cbs = $("div.SortOptions div[id^=cbSortBy]", StoreLocatorArea);
            if (h == 12) {
                cbs.eq(1).click();
            }
            else if (h == 24) {
                cbs.eq(0).click();
            }
        }
    };

    function InitControls() {

        resultsList = $(opts.ResultsListID);

        // Custom-styled checkboxes
        $('div.Checkbox input', StoreLocatorArea).each(function() {
            $(this).styledcheckbox();
        });
    };

    function ResetSortBy() {
        $("div.SortOptions div[id^=cbSortBy]", StoreLocatorArea).each(function() {
            var cb = $(this);
            if (cb.is(".StyledSelectedCheckbox")) {
                cb.click();
            }
        });
    };

    function InitGObjects() {
        try {
            if (GBrowserIsCompatible()) {
                map = new GMap2(document.getElementById(opts.MapId));
                map.setUIToDefault();
                geocoder = new GClientGeocoder();
            }
        }
        catch (er) {
        }
    };

    function GetNearestStores() {

        if (MapCenter == null) return;

		var latLngBounds = map.getBounds();

        var params =
            "{'Latitude':" + MapCenter.Latitude +
            ",'Longitude':" + MapCenter.Longitude +
            ",'MinX':" + latLngBounds.getSouthWest().lng() +
            ",'MinY':" + latLngBounds.getSouthWest().lat() +
            ",'MaxX':" + latLngBounds.getNorthEast().lng() +
            ",'MaxY':" + latLngBounds.getNorthEast().lat() +
            ",'Count':" + opts.ResultsPerSearch +
            ",'Filters':'" + GetFilters() + "'}";

        $.ajax({
            type: 'POST',
            url: Edentity.ResolveUrl('~/WebServices/AjaxService.asmx/GetNearestStores'),
            data: params,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(res) {
                if (res != null && res.d != undefined && res.d != null) {
                    LoadStores(res.d);
                }
                else {
                    //alert(res.Message);
                }
            },
            complete: function(XMLHttpRequest, textStatus) {
                //alert(XMLHttpRequest.status + ' ' + textStatus);
                //alert(XMLHttpRequest.responseText);
            }
        });
    };

    function LoadStores(stores) {
        LoadList(stores);
        LoadMarkers(stores);
    };

    // TODO: Only show photo icon if there is one available
    function LoadList(stores) {

        if (typeof stores != 'undefined' && stores != null && stores.length > 0) {

            resultsList.empty();

            var myStore = parseInt(Shoppers.Cookie.GetPreferredStore());

            for (var i = 0; i < stores.length; i++) {
                var item = $("<div class='Item' storeid='" + stores[i].StoreID + "'></div>");
                var body = $("<div class='Body'></div>");

                var left = $("<div class='Other'></div>").append("<b>" + stores[i].Distance + " k</b><br/><br/>");
                left.append($("<a class='Select' href='javascript:;'><img src='" + opts.SelectButtonImageURL + "'/></a>").click(function(e) {
                    var a = $(this);
                    var storeID = a.parent().parent().parent().attr("storeid");
                    Shoppers.Cookie.SetPreferredStore(storeID);
                    //Remove any previously selected
                    $("span.MyStore", a.parent().parent().parent().parent()).remove();
                    $("a.Select", a.parent().parent().parent().parent()).show();
                    a.hide();
                    //Select the current one
                    a.after("<span class='MyStore'>" + opts.MyStoreLabel + "</span>");
                }));

                if (!isNaN(myStore) && myStore == stores[i].StoreID) {
                    left.append("<span class='MyStore'>" + opts.MyStoreLabel + "</span>");
                    $("a", left).hide();
                }

                var middle = GetGeneralStoreInfo(stores[i]);

                body.append(left);
                body.append(middle);
                body.append($('<div class="Clear"></div>'));

                //Extra info
                body.append(GetExtraStoreInfo(stores[i]));
                body.append($('<div class="Clear"></div>'));

                item.append($('<div class="Top"></div>'));
                item.append(body);
                item.append($('<div class="Bottom"></div>'));

                resultsList.append(item);
            }

            RefreshList();
        }
    }

    function RefreshList() {
        resultsList.jScrollPane({
            animateTo: true,
            dragMaxHeight: 58,
            scrollbarMargin: 15
        });
    };

    var openMarker = null;

    SLB.OnCloseMarker = function() {
        if (openMarker != null) {
            openMarker.closeInfoWindow();
        }
    };

    var currTimeout = null;

    function LoadMarkers(stores) {

        if (typeof stores != 'undefined' && stores != null && stores.length > 0) {

            var bounds = new GLatLngBounds;

            for (var i = 0; i < stores.length; i++) {
                var LatLong = new GLatLng(stores[i].Latitude, stores[i].Longitude);
                if (LatLong != null) {
                    var marker = new GMarker(LatLong, CreateIcon());
                    marker.num = i;
                    map.addOverlay(marker);
                    bounds.extend(marker.getPoint());

                    GEvent.addListener(marker, "mouseover", function() {
                        this.openInfoWindowHtml(GetSmallStoreInfo(stores[this.num]));
                        openMarker = this;
                        if (currTimeout != null) clearTimeout(currTimeout);
                    });
                    GEvent.addListener(marker, "mouseout", function() {
                        currTimeout = setTimeout("Shoppers.Controls.StoreLocatorHeader.OnCloseMarker();", 4000);
                    });
                    GEvent.addListener(marker, "click", function() {
                        var sel = "div.Item[storeid=" + stores[this.num].StoreID + "]";
                        var details = $(sel + " a.Details");
                        resultsList[0].scrollTo("div.Item[storeid=" + stores[this.num].StoreID + "]");
                        if (details.parent().is(":visible")) {
                            details.click();
                        }
                    });
                }
            }
            //Set new zoom level to hold all the points
            bounds.extend(map.getCenter());
            map.setZoom(map.getBoundsZoomLevel(bounds));
        }
    };

    ///
    // Returns custom icon settings
    ///
    function CreateIcon() {
        var iconPath = opts.IconPath;
        var icon = new GIcon();
        icon.image = iconPath + 'image.png';
        icon.shadow = iconPath + 'shadow.png';
        icon.iconSize = new GSize(22, 28);
        icon.shadowSize = new GSize(36, 28);
        icon.iconAnchor = new GPoint(11, 28);
        icon.infoWindowAnchor = new GPoint(11, 0);
        icon.printImage = iconPath + 'printImage.gif';
        icon.mozPrintImage = iconPath + 'mozPrintImage.gif';
        icon.printShadow = iconPath + 'printShadow.gif';
        icon.transparent = iconPath + 'transparent.png';
        icon.imageMap = [13, 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 20, 6, 21, 7, 21, 8, 21, 9, 21, 10, 21, 11, 21, 12, 21, 13, 21, 14, 20, 15, 20, 16, 19, 17, 19, 18, 18, 19, 17, 20, 17, 21, 16, 22, 15, 23, 14, 24, 13, 25, 12, 26, 11, 27, 10, 27, 9, 26, 8, 25, 7, 24, 6, 23, 6, 22, 5, 21, 4, 20, 3, 19, 3, 18, 2, 17, 1, 16, 1, 15, 1, 14, 0, 13, 0, 12, 0, 11, 0, 10, 0, 9, 0, 8, 0, 7, 1, 6, 1, 5, 2, 4, 3, 3, 4, 2, 6, 1, 8, 0];
        return icon;
    };

    function GetGeneralStoreInfo(store) {

        var container = $('<div class="Info"></div>');
        var basic = $('<div class="Basic"></div>')
            .append($('<div />').text('Store #' + store.StoreID))
            .append($('<div />').text(store.Address))
            .append($('<div />').text(store.City));
        var details = $('<div class="Details"></div>')
            .append($('<img />').attr('src', Edentity.ResolveUrl('~/Images/ListDot.png'))).append('&nbsp;')
            .append($('<a href="javascript:;"></a>').addClass('Details').text(opts.DetailsLabel)
                .bind('click', function() {
                    $(this).parent().hide().parent().next().next().show();
                    RefreshList();
                }));

        container.append(basic);
        container.append(details);
        return container;
    };

    function GetExtraStoreInfo(store) {
        var html = $("<div class='Extra' style='display:none'></div>");
        var other = $("<div class='Other'><br/></div>")
            .append($("<a class='Close' href='javascript:;'><img src='" + opts.CloseButtonImageURL + "'/></a>").bind('click', function(e) {
                var p = $(this).parent().parent().hide();
                $("div.Details", p.prev().prev()).show();
                RefreshList();
            }));

        html.append(other);
        html.append("<div class='Info'>" + "<br/>Ph: " + store.PhoneNumber + "<br/><br/>" + store.StoreHours + "</div>");

        return html;
    };

    function GetSmallStoreInfo(store) {
        return "<b>" + store.Name + "</b><br/>"
            + store.Address + "<br/>" + store.City;
    };

})(Shoppers.Controls.StoreLocatorHeader, jQuery);


