﻿// build the "namespaces" if they don't exist previously
if (!Consumer)
{
    var Consumer = {};
}

// Execute when DOM is ready
$(function ()
{
    if (!Utils.IsCufonAvailable())
        $('#searchblock h3').addClass('noCufon');

    Consumer.StoreMap.loadAPI(function ()
    {
        $.getScript('/scripts/consumer/infobox.js', function ()
        {
            new Consumer.StoreLocator();
        });
    });
});


Consumer.StoreLocator = function ()
{
    var NO_CUFON = new Array("el-gr", "uk-­ua", "pl-pl");

    var states = {};

    var siteLanguage;

    var cufonAvailable;

    var _storeLocatorSettings;

    var storeMap;

    var storeList;

    var topStoreList;

    var storeDirections;

    var storesSearchResults;

    var storeDatabase;

    var match = location.href.match(/country=(.+?)(?:$|&|#)/im);

    var initialCountry = match == null ? null : match[1];

    var lastDisplayedCountry = null;

    var isMetricSystem;

    var storeToShowInfoWindow;

    var days = new Array(Dictionary.Mo, Dictionary.Tu, Dictionary.We, Dictionary.Th, Dictionary.Fr, Dictionary.Sa, Dictionary.Su);

    // Initializes map after Google API is loaded
    var initPage = function ()
    {
        Consumer.StoreMap.autocomplete($("#storeAddress"), function (e, data)
        {
            if (data.type == "cornerCase")
                displayCornerCase(data.value);
            else
                if (data.type == "geo")
                    searchStores();
                else
                {
                    var store = data.value;

                    storeMap.setSearchAnchor(new google.maps.LatLng(store.GeoInfo.Latitude, store.GeoInfo.Longitude));

                    storeList.setStartPoint(store.GeoInfo.Latitude, store.GeoInfo.Longitude);
                    storeList.setShowDistances(true);

                    if (topStoreList)
                    {
                        topStoreList.setStartPoint(store.GeoInfo.Latitude, store.GeoInfo.Longitude);
                        topStoreList.setShowDistances(true);
                    }

                    showStores(new Array(store));
                    storeToShowInfoWindow = store;
                }
        });

        $("#btGetStoresNearby").click(function () { searchStores(); return false; });
        $("#storeAddress").keypress(function (e) { if (Utils.isEnterKey(e)) { searchStores(); return false; } });
        var initMap = function ()
        {
            storeMap = new Consumer.StoreMap($("#map_canvas"));
            // ignore map events until data is loaded
            //storeMap.ignoreEvents();

            storeMap.subscribe("storeIconClicked", function (storeInfo)
            {
                storeMap.onceOnIdle(function ()
                {
                    storeList.onceOnIdle(function ()
                    {
                        storeList.selectStore(storeInfo);
                    });
                });
            });

            storeMap.subscribe("allIconsArePlaced", function ()
            {
                storeMap.raiseChangedEvent();
            });

            storeMap.subscribe("onStreetViewVisibleChanged", onMapsStreetViewChanged);
            storeMap.subscribe("onChanged", onChanged);

            storeMap.setStoreInfoCreateFunction(createStoreInfoWindowContent);

            storeDirections = new Consumer.StoreDirections($(".stores-directions"), storeMap);
            storeDirections.hide();
            storeDirections.subscribe("onGoBackLinkClicked", onDirectionsGoBackLinkClicked);

            if (storeMap.showCountry(initialCountry))
            {
                Consumer.StoreLocator.COUNTRY = initialCountry.toLowerCase();
                storeDatabase.initStoresForCountry(Consumer.StoreLocator.COUNTRY);
                states["initialCountry"] = "yep";
            }

            states["initMap"] = "yep";
            setDistanceCalculators();

            setFooter();
        };
        MyStoresClass.GetMyGeoInfo(function (response)
        {
            if (!response)
                return;

            initMap();

            if (!states["initialCountry"])
            {

                initialCountry = response.CountryCode.toLowerCase();

                if (!storeMap.showCountry(initialCountry))
                {
                    initialCountry = Consumer.StoreMap.getCurrentCoutryCode().toLowerCase();
                    storeMap.showCountry(initialCountry);
                }

                Consumer.StoreLocator.COUNTRY = initialCountry;
                storeDatabase.initStoresForCountry(Consumer.StoreLocator.COUNTRY);
                states["initialCountry"] = "yep";
            }

            showStoresCount();

            var address = "";
            if (response.City && response.City.length > 0)
                address = response.City;
            if (response.Country && response.Country.length > 0)
            {
                if (address != "") address += ", ";
                address += response.Country;
            }
            if (response.PostalCode && response.PostalCode.length > 0)
            {
                if (address != "") address += ", " + response.PostalCode;
            }

            if (address != "")
            {
                var searchblock = $("#searchblock");

                var p = $("<p class='stores-near'/>").html("<span class='bullet'>&nbsp;</span>" + htmlDecode(Dictionary.FindNear)).append(":<br/>");

                searchblock.append(p);

                $("#linkNearestStores").text(address);

                var link = $('<a href="#">' + address + '</a>');

                $(link).click(function ()
                {
                    $("#storeAddress")[0].value = address;
                    searchStores();
                    setFooter();
                    return false;
                });

                p.append(link);
            }
        });
    };

    var displayCornerCase = function (cornerCase)
    {
        storeMap.panTo(cornerCase.CenterLatitude, cornerCase.CenterLongitude);
        storeMap.setZoom(cornerCase.Zoom);
    }

    var searchStores = function ()
    {
        //$(".ac_results").css('display', 'none');

        showSearchStatus();

        var address = $("#storeAddress")[0].value;

        var displayLocation = function (location, zoom)
        {
            storeMap.setSearchAnchor(location);

            storeMap.panTo(location.lat(), location.lng());

            if (zoom != null)
            {
                if (zoom instanceof google.maps.LatLngBounds)
                {
                    storeMap.onceOnIdle(function () { storeMap.getMap().fitBounds(zoom) });
                }
                else
                {
                    storeMap.onceOnIdle(function() { storeMap.setZoom(zoom); });
                }
            }
        };

        Consumer.StoreMap.searchLocationByAddress(address, function (locations)
        {
            if (locations.length == 0)
            {
                storeList.showStatus
                (
                    $('<p class="header"/>')
                        .text(htmlDecode(Dictionary.SearchReturn)
                        .replace('{0}', '0'))
                        .add($('<p/>').text(htmlDecode(Dictionary.CheckYourSpelling)))
                );
            }
            else
            {
                if (!$.Enumerable.From(locations).Any('$.raw.address_components'))
                {
                    if (locations.length == 1)
                    {
                        displayLocation(locations[0].location, locations[0].raw.Zoom);
                    } else
                    {
                        storeList.chooseYourArea(locations, displayLocation);
                    }
                    return;
                }

                Consumer.StoreLocator.COUNTRY = $.Enumerable.From(locations)
                    .SelectMany('$.raw.address_components')
                    .Where(function (t) { return $.inArray('country', t.types) >= 0; })
                    .Select('$.short_name')
                    .FirstOrDefault().toLowerCase();

                storeDatabase.initStoresForCountry(Consumer.StoreLocator.COUNTRY);

                if (locations.length == 1)
                {
                    // check if we found the whole country
                    var isCountry = locations[0].raw.address_components.length == 1 && $.inArray('country', locations[0].raw.address_components[0].types) >= 0;

                    if (isCountry)
                    {
                        storeMap.showCountry(Consumer.StoreLocator.COUNTRY);
                        storeMap.setSearchAnchor(locations[0].location);
                    }
                    else
                        displayLocation(locations[0].location, locations[0].raw.geometry.bounds);

                    var closestStore = storeDatabase.getClosestStore(locations[0].location, Consumer.StoreLocator.COUNTRY);

                    if (closestStore != null)
                    {
                        var actionExecuted = false;
                        var timeoutCounter = 0;

                        var action = function (byMap)
                        {
                            if (actionExecuted)
                            {
                                return;
                            }

                            if (!byMap && timeoutCounter < 3)
                            {
                                timeoutCounter++;
                                setTimeout(function () { action(false); }, 500);
                                return;
                            }

                            actionExecuted = true;

                            if (!storeMap.isStoreVisible(closestStore))
                            {
                                storeMap.displayAll([locations[0].location, new google.maps.LatLng(closestStore.GeoInfo.Latitude, closestStore.GeoInfo.Longitude)]);
                            }
                            else
                            {
                                storeMap.raiseChangedEvent();
                            }
                        };
                        storeMap.onceOnIdle(function () { action(true); });
                        setTimeout(function () { action(false); }, 500);
                    }
                } else
                {
                    storeList.chooseYourArea(locations, displayLocation);
                }
            }
        });

        return false;
    };
    var showSearchStatus = function ()
    {
        storeList.loading();
    }; // Displays search results
    var showStores = function (stores)
    {
        //$("#storeAddress").css('background', 'none');

        storeMap.hideStreetView();

        storesSearchResults = stores;

        storeMap.fitBoundsForStores(storesSearchResults);
        onChanged();
    };
    var onMapsStreetViewChanged = function ()
    {
        if (!storeMap.isStreetViewVisible())
        {
            onChanged();
        }
    };
    var onChanged = function ()
    {
        var center = storeMap.getMap().getCenter();

        // get country that lies under map center
        var geocoder = new google.maps.Geocoder();

        geocoder.geocode({ latLng: center }, function (results, status)
        {
            if (status == google.maps.GeocoderStatus.OK)
            {
                var country = $.Enumerable.From(results)
                                .SelectMany('$.address_components')
                                .Where(function (t) { return $.inArray('country', t.types) >= 0; })
                                .Select('$.short_name')
                                .FirstOrDefault();

                if (!country)
                {
                    Utils.ShowErrorMessage("Unable to detect underlying country");
                    return;
                }

                Consumer.StoreLocator.COUNTRY = country.toLowerCase();

                storeList.loading();

                storeDatabase.getStoresForCountry(country, function (storesForCountry)
                {
                    storesSearchResults = storesForCountry;

                    storeList.setStartPoint(center.lat(), center.lng());
                    storeList.setShowDistances(true);

                    if (topStoreList)
                    {
                        topStoreList.setStartPoint(center.lat(), center.lng());
                        topStoreList.setShowDistances(true);
                    }

                    updateStoreViews(lastDisplayedCountry != country);

                    lastDisplayedCountry = country;
                });
            }
            else
            {
                //Utils.ShowErrorMessage("Geocode was not successful for the following reason: " + status);
                return;
            }
        });
    };
    var onStoreCaptionClick = function (storeInfo)
    {
        if (storeList.getCurrentView() == Consumer.StoreListView.MAP_VIEW)
        {
            storeMap.panTo(storeInfo.GeoInfo.Latitude, storeInfo.GeoInfo.Longitude);
            storeMap.openStoreInfoWindow(storeInfo);
            storeMap.onceOnIdle(function ()
            {
                storeList.onceOnIdle(function ()
                {
                    storeList.selectStore(storeInfo);
                });
            });
        } else
        {
            goToStorePage(storeInfo);
        }
    };
    var updateStoreViews = function (updateMap)
    {
        if (updateMap)
        {
            //console.log('displaying stores (HEAVY OPERATION)');

            storeMap.removeMarkers();
            storeMap.createStoreMarkers(storesSearchResults, true);
        }

        storeMap.startLettersFromBeginning();
        storeList.showStores(storesSearchResults, storeMap.assignLetter);

        if (topStoreList)
        {
            topStoreList.showStores(storesSearchResults);
            topStoreList.show();
            resize();
        }

        if (storeToShowInfoWindow)
        {
            storeMap.openStoreInfoWindow(storeToShowInfoWindow);
            storeToShowInfoWindow = null; ;
        }
    };
    var createStoreInfoWindowContent = function (storeInfo, closeFunction)
    {
        var dynBox = $("<div id='infoWindow' class='dynBox'/>").attr('storeID', storeInfo.ID);

        dynBox
            .append($('<div class="dynBoxTop" />')
                .append($('<div class="dynBoxTopLeft">').html('&nbsp;'))
                .append($('<div class="dynBoxTopBg" />').html('&nbsp;'))
                .append($('<div class="dynBoxTopRight" />').html('&nbsp;')))
            .append($('<div class="dynBoxMain" />')
                .append($('<div class="dynBoxLeft" />').html('&nbsp;'))
                .append($('<div class="dynBoxContent" />'))
                .append($('<div class="dynBoxRight" />').html('&nbsp;')))
            .append($('<div class="dynBoxBottom" />')
                .append($('<div class="dynBoxBottomLeft" />').html('&nbsp;'))
                .append($('<div class="dynBoxBottomBg" />').html('<div class="dynBoxBottomBgArrow">&nbsp;</div>'))
                .append($('<div class="dynBoxBottomRight" />').html('&nbsp;')));

        var dynBoxContent = $('.dynBoxContent', dynBox);

        var closeLink = $('<a id="close-link" class="close" href="#" />').text(htmlDecode(Dictionary.Close));

        if (closeFunction)
        {
            closeLink.click(function () { closeFunction(); return false; });
        }

        dynBox.append(closeLink);

        var textInfo = $('<div class="text" />');
        if (storeInfo.SecondName != null && $.trim(storeInfo.SecondName) != '')
        {
            textInfo.append($('<p />').text(htmlDecode(storeInfo.SecondName)));
        }

        var addressLines = Utils.formatAddressLines(storeInfo);
        for (var i = 0; i < addressLines.length; ++i)
        {
            textInfo.append($('<p />').html(addressLines[i]));
        }

        textInfo.append('<p>&nbsp;</p>').append((storeInfo.Type) ? $('<p class="storetype"/>').html(storeInfo.Type) : '');

        dynBoxContent
            .append($('<h4/>').html(htmlDecode(storeInfo.Caption).toUpperCase()))
        // Add address info
            .append(textInfo);
        // Added Opening hours
        if (storeInfo.Schedule.length)
        {
            dynBoxContent.append(createOpeningHoursBlock(storeInfo));
        }

        // Add bottom links
        dynBoxContent
            .append(
                $('<div class="bottom" />')
        // MoreInfo button
                .append(
                    $('<a class="small light" />')
                    .attr('href', Utils.formatStoreLink(storeInfo))
                    .append('<span class="l">&nbsp;</span>')
                    .append($('<span class="c"/>').text(htmlDecode(Dictionary.MoreInfo)).prepend('<img height="12" width="12" alt="Bullet" src="http://static.pandora.net/consumer/images/btn-bullet-gray.png"/>'))
                    .append('<span class="r">&nbsp;</span>')
                    .click(function () { goToStorePage(storeInfo); return false; })
                )
        // Send button
                .append(
                    $('<a class="small simple" href="#" style="display: none"/>')
                    .text(htmlDecode(Dictionary.Send))
                    .click(function () { onSendLinkClick(storeInfo); })
                )
            );

        return dynBox.get(0);
    };
    var createOpeningHoursBlock = function (storeInfo)
    {
        var hours = $("<div class='openinghours'></div>");

        if (storeInfo.Schedule.length)
        {
            $(hours).append('<p>' + htmlDecode(Dictionary.OpeningHours) + ':</p>');

            var left = $("<div class='left'></div>");
            for (var i = 0; i < storeInfo.Schedule.length; i++)
            {
                if (storeInfo.Schedule[i].AfterSiesta)
                {
                    $(left).append('<p>&nbsp;</p>');
                } else if (storeInfo.Schedule[i].FirstDay == storeInfo.Schedule[i].LastDay)
                {
                    $(left).append('<p>' + days[storeInfo.Schedule[i].FirstDay] + '</p>');
                } else
                {
                    $(left).append('<p>' + days[storeInfo.Schedule[i].FirstDay] + ' - ' + days[storeInfo.Schedule[i].LastDay] + '</p>');
                }
            }
            $(hours).append(left);

            var right = $("<div></div>");

            for (var i = 0; i < storeInfo.Schedule.length; i++)
            {
                $(right).append("<p>" + storeInfo.Schedule[i].OpensAt + ' - ' + storeInfo.Schedule[i].ClosesAt + "</p>");
            }
            $(hours).append(right);
        }

        return hours;
    };
    var onViewChanging = function (newView)
    {
        var mapView = newView == Consumer.StoreListView.MAP_VIEW;

        if (mapView)
        {
            storeMap.startLettersFromBeginning();
            storeMap.show();
        }
        else
        {
            storeList.setHeight('auto');
            $('.storemain').height('auto');
            storeMap.hide();
        }

        if (topStoreList)
        {
            topStoreList.setShowAddresses(!mapView);
            topStoreList.update();
        }
    };
    var onViewChanged = function (newView)
    {
        if (newView == Consumer.StoreListView.MAP_VIEW)
        {
            resize();
        } else
        {
            storeList.setHeight('auto');
            $('.storemain').height('auto');
        }
        $('#footer').removeClass('footerAbsolute');
    };
    var onDirectionsLinkClick = function (storeInfo)
    {
        storeMap.closeStoreInfoWindows();

        storeList.hide();

        storeDirections.reset();
        storeDirections.toStore(storeInfo);
        storeDirections.show();
    };
    var onSendLinkClick = function (storeInfo)
    {
        // creates dialog UI
        var createDialog = function ()
        {
            //decode all texts
            var sendTo = htmlDecode(Dictionary.SendStoreTo);
            var recipientEmail = htmlDecode(Dictionary.SendStoreRecipientEmail);
            var name = htmlDecode(Dictionary.SendStoreSenderName);
            var message = htmlDecode(Dictionary.SendStoreMessage);

            //create and init dialog UI
            var shareForm = $('<form id="share-form"></form>');
            var storeLocatorDiv = $('<div class="dynBoxNew storelocator">');
            var top = $('<div class="dynBoxNewTop">');
            var topContent = $('<div class="dynBoxNewTopLeft">&nbsp;</div><div class="dynBoxNewTopBg">&nbsp;</div> <div class="dynBoxNewTopRight">&nbsp;</div>');
            top.append(topContent);
            storeLocatorDiv.append(top);
            var main = $('<div class="dynBoxNewMain">');
            main.append('<div class="dynBoxNewLeft">&nbsp;</div>');
            var mainContent = $('<div class="dynBoxNewContent">');
            mainContent.height(400);
            var dialog = $("<div class='right send'></div>");
            //dialog.css('z-index', '2000');
            var header = $("<h5>" + sendTo + "</h5>");
            dialog.append(header);

            var emailDiv = $("<div/>");

            var emailArea = $("<span class='required'><label for='tbEmail'>*</label></span><input type='text' class='text required notInputHint email'  id='tbEmail' name='tbEmail'/>");
            emailArea.val(recipientEmail);
            emailArea.attr("title", recipientEmail);
            emailDiv.append(emailArea);
            dialog.append(emailDiv);

            var nameDiv = $("<div/>");
            var nameArea = $("<span class='required'><label for='tbName'>*</label></span><input type='text' class='text required notInputHint name' id='tbName' name='tbName'/>");
            nameArea.val(name);
            nameArea.attr("title", name);
            nameDiv.append(nameArea);
            dialog.append(nameDiv);

            var messageDiv = $("<div/>");
            var messageArea = $("<textarea class='textarea' id='tbMessage'/>");
            messageArea.val(message);
            messageArea.attr("title", message);
            messageDiv.append(messageArea);
            dialog.append(messageDiv);
            var sendButton = $("<a class='small dark sendStoreMail' id = 'btnShare' href='#'><span class='l'>&nbsp;</span><span class='c'><img src='http://static.pandora.net/consumer/images/btn-bullet-white.png' width='12' height='12' alt='Bullet' />" + htmlDecode(Dictionary.Send) + "</span><span class='r'>&nbsp;</span></a>");
            dialog.append(sendButton);
            mainContent.append(dialog);
            main.append(mainContent);
            main.append('<div class="dynBoxNewRight">&nbsp;</div>');
            storeLocatorDiv.append(main);
            var bottom = $('<div class="dynBoxNewBottom"></div>');
            bottom.append('<div class="dynBoxNewBottomLeft">&nbsp;</div> <div class="dynBoxNewBottomBg">&nbsp;</div> <div class="dynBoxNewBottomRight">&nbsp;</div>');
            storeLocatorDiv.append(bottom);
            shareForm.append(storeLocatorDiv);
            return shareForm;
        };
        $("#share-form").remove();
        var dialog = createDialog();
        dialog.fancyDialog
        (
            {
                show: null,
                open: function ()
                {
                    $('h5', dialog).cufon();
                    //coolinput for all input and textarea workaround
                    $("#share-form input").coolinput();
                    $("#share-form textarea").bind("focus", function ()
                    {
                        if ($.trim($(this).val()) == '' || $(this).val() == $(this).attr('title'))
                            $(this).val('');
                    });
                    $("#share-form textarea").bind("blur", function ()
                    {
                        if ($.trim($(this).val()) == '')
                            $(this).val($(this).attr('title'));
                    });

                    //validation
                    var errorPlacement = function (error, element)
                    {
                        $(error).insertAfter(element);
                    };
                    $.validator.addMethod("notInputHint", function (text, element)
                    {
                        return $(element).val() != $(element).attr("title");
                    }, htmlDecode(Dictionary.EmailCannotBeEmpty));

                    $.validator.addMethod("notInputHint", function (text, element)
                    {
                        return $(element).val() != $(element).attr("title");
                    }, htmlDecode(Dictionary.NameRequired));
                    $("#share-form").validate(
                    {
                        messages:
                            {
                                tbEmail:
                                {
                                    required: htmlDecode(Dictionary.EmailCannotBeEmpty),
                                    notInputHint: htmlDecode(Dictionary.EmailCannotBeEmpty),
                                    email: htmlDecode(Dictionary.InvalidEmailFormat)
                                },
                                tbName:
                                {
                                    required: htmlDecode(Dictionary.NameRequired),
                                    notInputHint: htmlDecode(Dictionary.NameRequired)
                                }
                            },
                        errorClass: 'fancyError',
                        errorPlacement: errorPlacement
                    });

                    //perform share            
                    $("#tbEmail, #tbName, #tbMessage").keypress(function (e) { if (Utils.isEnterKey(e)) { $("#btnShare").click(); return false; } });
                    $("a.sendStoreMail").click(function ()
                    {
                        if (!$("#share-form").valid())
                            return false;

                        MyStoresClass.ShareStore(storeInfo, $('#tbEmail').val(), $('#tbName').val(), $('#tbMessage').val());
                    });

                    $('#share-form').css({ 'height': '450px' });
                    $('.ui-widget-overlay').css({ 'width': 'auto', 'position': 'absolute', 'top': '0px', 'left': '0px', 'right': '0px' });
                    $('.ui-dialog').css({ 'position': 'absolute', 'height': '450px', 'width': '829px', 'top': '420px', 'left': '50%', 'margin-left': '-415px' });
                    // left 0px is not overwritten
                    // top 0px is not overwritten
                },
                useDefaultUI: false,
                draggable: false
            });
    };
    var onDirectionsGoBackLinkClicked = function ()
    {
        storeDirections.hide();
        storeList.show();
    };
    var goToStorePage = function (storeInfo)
    {
        //window.location = Utils.formatStoreLink(storeInfo);
        window.open(Utils.formatStoreLink(storeInfo), "_blank");
        return false;
    };
    var getFullCountryName = function (country, readyCallback)
    {
        if (!Utils.isDefined(readyCallback))
            return country;

        var action = function ()
        {
            if (_storeLocatorSettings == null)
            {
                setTimeout(action, 200);
                return;
            }

            country = country.toLowerCase();
            readyCallback(_storeLocatorSettings[country] != null ? _storeLocatorSettings[country] : country.toUpperCase());
        };
        action();
    };
    var showStoresCount = function ()
    {
        if (states["initialCountry"])
        {
            storeDatabase.getStoresCountForCountry(initialCountry, function (count)
            {
                getFullCountryName(initialCountry, function (fullCountryName)
                {
                    storeList.showStatus('<h4>' + htmlDecode(Dictionary.PandoraStoreLocator) + '</h4><p class="Optima">' + htmlDecode(Dictionary.CountryStoreCount).replace('{0}', count).replace('{1}', fullCountryName) + '</p>');

                    storeMap.considerEvents();
                });
            });
        }
    };
    var print = function ()
    {
        var main = $('<div class="storelocatorprint"/>');

        $('<div class="header"><img src="http://static.pandora.net/consumer/storelocator/logo-pandora.gif" alt="Pandora"/></div>').appendTo(main);

        if (topStoreList)
            main.append(topStoreList.getPrintMarkup());

        $('<h5/>').text(storeList.getStoresCount() + " " + Utils.GetEndingForNumber(storeList.getStoresCount(), htmlDecode(Dictionary.Stores).split(',')).toLowerCase()).appendTo(main);

        main.append(storeList.getPrintMarkup());

        $('<div class="footer"><p>&copy; 2011 Pandora. All rights reserved</p></div>').appendTo(main);

        if ($("body").hasClass("righttoleft"))
        {
            main.printElement({ leaveOpen: true, printMode: 'popup', printBodyOptions: { styleToAdd: 'background-color: #E9E9E9' }, overrideElementCSS: ['/design/consumer/css/sections/stores.css', '/design/consumer/css/general/pandora.css', '/design/consumer/css/general/print-righttoleft.css'] });
        } else
        {
            main.printElement({ leaveOpen: true, printMode: 'popup', printBodyOptions: { styleToAdd: 'background-color: #E9E9E9' }, overrideElementCSS: ['/design/consumer/css/sections/stores.css', '/design/consumer/css/general/pandora.css'] });
        }
    };
    var setDistanceCalculators = function ()
    {
        if (states["locatorSettings"] && states["initMap"])
        {
            storeList.setDistanceCalculator(storeMap.getDistance);
            if (topStoreList)
                topStoreList.setDistanceCalculator(storeMap.getDistance);
        }
    }; // constructor code

    siteLanguage = Utils.SiteLanguage();
    cufonAvailable = !$.Enumerable.From(NO_CUFON).Contains(siteLanguage);

    storeList = new Consumer.StoreList($("#list_canvas"));

    storeList.setFullCountryNameFunction(function (callback)
    {
        getFullCountryName(Consumer.StoreLocator.COUNTRY, callback);
    });

    storeList.loading();

    storeDatabase = new Consumer.StoreLocatorDatabase();
    Consumer.StoreLocator.STOREDATABASE = storeDatabase;

    storeList.subscribe("onStoreCaptionClick", onStoreCaptionClick);
    storeList.subscribe("onViewChanging", onViewChanging);
    storeList.subscribe("onViewChanged", onViewChanged);
    storeList.subscribe("onPrintButtonClick", print);

    MyStoresClass.GetStoreLocatorSettings(Utils.SiteLanguage(), function (response)
    {
        _storeLocatorSettings = response;

        $(_storeLocatorSettings.Countries).each(function ()
        {
            _storeLocatorSettings[this.key] = this.value;
        });

        if (response.ShowFeaturedStoresCarousel)
        {
            topStoreList = new Consumer.TopStoreList($("#toplist_canvas"));
            topStoreList.subscribe("onStoreCaptionClick", goToStorePage);
            topStoreList.hide();
        }

        states["locatorSettings"] = "got";
        setDistanceCalculators();

        MyStoresClass.IsMetricSystem(Utils.SiteLanguage(), function (response)
        {
            isMetricSystem = response;
            storeList.setIsMetricSystem(isMetricSystem);
            if (topStoreList)
            {
                topStoreList.setIsMetricSystem(isMetricSystem);
            }
        });
    });

    var resize = function ()
    {
        if (storeList && storeList.getCurrentView() == Consumer.StoreListView.LIST_VIEW)
            return;

        var newHeight = $(window).height() - 290;

        if (topStoreList && topStoreList.isVisible())
            newHeight -= 103;

        newHeight = Math.max(newHeight, 407);
        var storeMain = $('.storemain');
        var currentHeight = storeMain.height();
        if (newHeight != currentHeight)
        {
            storeMain.height(newHeight);
            if (storeMap)
                storeMap.setHeight(newHeight);
            else
                $('#map_canvas').height(newHeight);
            if (storeList)
                storeList.setHeight(newHeight - 20);
            else
                $('#list_canvas').height(newHeight);
        }
    };
    $(window).resize(resize);
    resize();

    initPage();
};
Consumer.StoreLocator.COUNTRY = "us";

Consumer.StoreLocator.STOREDATABASE = null;

