var map;
var markerManager;
var largeMapControl = null;
var infoPopupListener;
var parameterMap;
var _maxZoomLevel = 15;

var markerImages = {std: G_DEFAULT_ICON.image,
    small: '/static/images/8_storelocator/marker_small_red.png',
    medium: '/static/images/8_storelocator/marker_medium.png',
    mediumOn: '/static/images/8_storelocator/marker_medium_on.png',
    big: function(markerNr) {
        return '/static/images/8_storelocator/markers/marker_' + markerNr + '.png'
    },
    bigOn: function(markerNr) {
        return '/static/images/8_storelocator/markers/marker_on_' + markerNr + '.png'
    }};

var markers;
var filter;
var searchType;
var isInitializing = false;

function initStoreLocator() {
    var start = new Date().getTime();
    isInitializing = true;

    $("storeLocatorContainer").show();
    $('searchResult').hide();
    $('filterContainer').hide();
    $('noStoresInCountryMsg').hide();

    filter = new Filter();

    var country = querystring.getParameter("country");
    if (country != null) {
        setSelectedCountry(country);
    }

    if (querystring.hasParameter("s") ||
            querystring.hasParameter("filter") ||
            querystring.hasParameter("csc")) {
        executeSearch();
    } else {
        executeDefault();
    }

    $("freeText").checked = true;

    changeSearchType($("freeText"));
    loadListSearchView();
    $("filterHeadline").hide();

    new AutoComplete('ajaxInput', 'suggestionXML.ahtml',
    {
        delay: 0.25,
        resultFormat: AutoComplete.Options.RESULT_FORMAT_XML,
        threshold: 1,
        requestMethod: 'POST',
        command: 'command=suggest',
        onSelect: function(input, selection, event) {
            if (selection) {
                input.value = selection.replace(/ \(\d*\)/, "");
            }
            searchText($('ajaxInput').value, $('countrySelect').options[$('countrySelect').selectedIndex].value);
        },
        locale: function() {
            return $('countrySelect').options[$('countrySelect').selectedIndex].value;
        }
    });

    //pngfix();

    var end = new Date().getTime();
    //alert("javascript loaded in " + (end - start) + " ms");
}

function executeDefault() {
    var defaultCallback = function(location) {
        clearMarkerData();
        initMap(location);
        getAllStoresInCountry(getSelectedCountry());
    }

    goToCountryMap(getSelectedCountryInEnglish(), defaultCallback);
}

function executeSearch() {
    var searchString = querystring.getParameter("s");
    if (searchString == null) {
        searchString = "";
    }
    if (searchString.include('+')) {
        searchString = searchString.replace('+', '%20');
    }
    searchText(searchString, querystring.getParameter("country"));
}

function destroyStoreLocator() {
    GUnload();
    markers = null;
    filter = null;
}

function clearMarkerData() {
    if (markerManager) {
        markerManager.clearMarkers();
    }
    //clear all event handlers
    var locationsWithGeoData = $$('span[class="location"][name="geoData"]');
    for (var index = 0; index < locationsWithGeoData.length; index++) {
        var location = locationsWithGeoData[index];
        GEvent.clearInstanceListeners(location.parentNode);
        if (location.marker) {
            GEvent.clearInstanceListeners(location.marker);
            //untie circular references
            location.marker.storeInfoElement.marker = null;
            location.marker.storeInfoElement = null;
            location.marker = null;
        }
    }
}

function searchText(input, locale) {
    $("freeTextSearchButton").className = "buttonSmallInactive";
    clearMarkerData();

    //fetch new store information
    var pars = 'command=search&s=' + input + (locale ? '&locale=' + locale : '');
    new Ajax.Updater('searchResult', 'storelocatorV2.ahtml', {
        method: 'post',
        evalJS: 'false',
        parameters: pars,
        onComplete: function(transport) {
            handleSearchResult(transport);
            $("freeTextSearchButton").className = "buttonSmall";
        }
    });
}

function searchList() {
    if (isLinkEnabled()) {
        clearMarkerData();

        var pars = 'command=searchList&country=' + getSelectedCountry() + '&region=' + getSelectedRegion() + '&city=' + getSelectedCity();
        new Ajax.Updater('searchResult', 'storelocatorV2.ahtml', {
            method: 'post',
            evalJS: 'force',
            parameters: pars,
            onComplete: function(transport) {
                handleSearchResult(transport);
            }
        });
    }
}

function searchZip(zip, radius) {
    var geocoder = new GClientGeocoder();
    var searchString = zip + "," + getSelectedCountry();
    if (geocoder) {
        clearMarkerData();

        geocoder.getLatLng(
                searchString,
                function(latlng) {
                    var zipLocation = "";
                    if (latlng) {
                        zipLocation = latlng.lat() + ',' + latlng.lng();
                    }
                    var r = radius.split(" ");
                    radiusInMeters = null;
                    if (r[1] == "km") {
                        radiusInMeters = r[0] * 1000;
                    } else {
                        radiusInMeters = r[0] * 1609.344;
                    }
                    var pars = 'command=zipSearch&s=' + '' + '&locale=' + getSelectedCountry() + '&zipLocation=' + zipLocation + '&radius=' + radiusInMeters;
                    new Ajax.Updater('searchResult', 'storelocatorV2.ahtml', {
                        method: 'post',
                        evalJS: 'force',
                        parameters: pars,
                        onComplete: function(transport) {
                            handleSearchResult(transport);
                        }
                    });

                }
                );
    }
}

function generateTransportLoggingString(searchString, transport) {
    var str = "SL: ";
    if (transport && transport.request && transport.request.parameters) {
        if (transport.request.parameters.command) {
            str += transport.request.parameters.command;
        }
        if (transport.request.parameters.locale) {
            str += " | " + transport.request.parameters.locale;
        }
        if (transport.request.parameters.country) {
            str += " | " + transport.request.parameters.country;
        }
        if (transport.request.parameters.radius) {
            str += " | Radius:" + transport.request.parameters.radius + "m";
        }
        if (transport.request.parameters.zipLocation) {
            str += " | Zip:" + $("slZip").value;
        }
        if (transport.request.parameters.city) {
            str += " | " + $$('#cities option[value=' + transport.request.parameters.city + ']')[0].text
        }


    }
    if (searchString != null && searchString.length > 0) {
        str += " | " + searchString;
    }
    return str;
}

function handleSearchResult(transport) {
    //Collect search params for logging
    var searchString = transport.request.parameters.s;


    searchString = generateTransportLoggingString(searchString, transport);
    trackFlashPageView("StoreLocatorSearch", "static:storelocatorjs", searchString, null);

    //logPageView("SL_SearchResult");
    //logClick("SL_SearchType_" + searchType);

    $('searchResult').show();
    $('noStoresInCountryMsg').hide();
    if ($('noHits')) {
        $('map_canvas').className = "map";
        goToCountryMap(getSelectedCountryInEnglish(), initMap);
    } else {
        var locations = $$('span[class="location"]');
        var locationsWithGeoData = $$('span[class="location"][name="geoData"]');
        if (locationsWithGeoData.length == 0) {
            $('errorMsg').show();
            $('map_canvas').className = "map";
            $('mapContainer').className = "mapContainer results";
            $('filterContainer').show();
            filter.resizeFilterBg();
            map.checkResize();
        } else {
            $('errorMsg').hide();
            updateMap(locationsWithGeoData);
            $('filterContainer').show();

            filter.applyFilters();

            if (isInitializing) {
                //apply filters given in the url
                if (querystring.hasParameter("filter")) {
                    filter.loadFilters(querystring.getParameterValues("filter"));
                }

                //show store details popup if csc is in the url
                if (querystring.hasParameter("csc")) {
                    showStoreDetails(querystring.getParameter("csc"));
                }
                isInitializing = false;
            }


        }
    }
}

function getAllStoresInCountry(locale) {
    var pars = 'command=storesInCountry&country=' + locale;
    new Ajax.Request('storelocatorV2.ahtml', {
        method: 'post',
        evalJS: 'false',
        parameters: pars,
        onComplete: function(transport) {
            var locations = transport.responseText.evalJSON();
            if (locations.length > 0) {
                markers = new Hash();
                var markers2 = [];
                var storesWithGeodata = 0;
                for (var index = 0; index < locations.length; index++) {
                    var storeInfo = locations[index];
                    if (storeInfo.lat && storeInfo.lat != "") {
                        var marker = createStaticMarker(storeInfo, null, false);
                        markers.set(storeInfo.ccc, marker);
                        markers2.push(marker);
                        storesWithGeodata++;
                    }
                    storeInfo = null;
                }
                if (storesWithGeodata > 0) {
                    markerManager.addMarkers(markers2, 0, 17);
                    markerManager.refresh();
                } else {
                    $('errorMsg').show();
                }
            } else {
                $('noStoresInCountryMsg').show();
            }
        }
    });
}

var initMap = function initializeMap(location) {
    if (GBrowserIsCompatible()) {
        if ($('searchResult').visible()) {
            $('mapContainer').className = "mapContainer results";
        } else {
            $('mapContainer').className = "mapContainer start";
        }
        if (!map) {
            map = new GMap2(document.getElementById("map_canvas"));
        }
        var center = location;
        var zoomLevel = new Number(getZoomLevelForCountry());
        map.setCenter(center, zoomLevel.abs());
        map.disableDragging();
        map.disableDoubleClickZoom();
        map.enableContinuousZoom();
        if (!markerManager) {
            markerManager = new MarkerManager(map);
        }
        map.checkResize();
    }
}

function updateMap(locations) {
    //$('result').show();
    //$('searchResultNoSearch').hide();

    if (!map) {
        map = new GMap2(document.getElementById("map_canvas"));
    }

    $('filterContainer').show();
    $('mapContainer').className = "mapContainer results";

    filter.resizeFilterBg();

    var bounds = new GLatLngBounds();
    if (locations.length > 0) {
        markers = [];
        for (var index = 0; index < locations.length; index++) {

            var location = locations[index];
            var storeInfo = location.innerHTML.evalJSON();

            if (storeInfo.lat != "" || storeInfo.lat == null) {
                var marker = createMarker(storeInfo, locations.length, index);
                bounds.extend(marker.getLatLng());
                location.marker = marker;
                if (location.parentNode.hidden == true) {
                    marker.hidden = true;
                }
                markers[markers.length] = marker;
            }
        }
        $('map_canvas').className = "map";
        if (!largeMapControl) {
            largeMapControl = new GLargeMapControl();
            map.addControl(largeMapControl);
        }
        map.enableDragging();
        map.enableDoubleClickZoom();
        map.enableScrollWheelZoom();
        newzoom = Math.min(map.getBoundsZoomLevel(bounds), _maxZoomLevel);
        newcenter = bounds.getCenter();
        map.setCenter(newcenter, newzoom);

        if (!markerManager) {
            markerManager = new MarkerManager(map);
        }

        markerManager.addMarkers(markers, 0, 17);
        markerManager.refresh();
        map.checkResize();
    }
}

function showStaticMap(location, mapDiv) {
    var staticMap = new GMap2(document.getElementById(mapDiv));
    var latlng = new GLatLng(location.lat, location.lng);
    var marker = createStaticMarker(location, 1, false, 1);
    staticMap.setCenter(latlng, 13);
    //staticMap.disableDragging();
    //staticMap.disableDoubleClickZoom();
    staticMap.enableScrollWheelZoom();
    staticMap.enableContinuousZoom();
    staticMap.addControl(new GLargeMapControl());
    staticMap.addOverlay(marker);
}

function resetMap() {
    $('searchResult').hide();
    $('filterContainer').hide();
    $('noStoresInCountryMsg').hide();
    executeDefault();
}

function goToCountryMap(country, callback) {
    var location = country;// + ", country";
    $('errorMsg').hide();
    var geocoder = new GClientGeocoder();
    if (geocoder) {
        geocoder.getLatLng(
                location,
                function(latlng) {
                    if (!latlng) {
                        alert(location + " not found");
                    } else {
                        if (callback) {
                            callback(latlng);
                        }
                    }
                }
                );
    }
}

function createStaticMarker(storeInfo, nrOfStores, clickable, markerNr) {
    var latlng = new GLatLng(storeInfo.lat, storeInfo.lng);
    var img = null;
    var marker = null;
    var icon = new GIcon();

    if (markerNr && markerNr > 99) {
        img = markerImages.big(markerNr);
        icon.iconSize = new GSize(43, 37);
        icon.iconAnchor = new GPoint(19, 24);
        icon.infoWindowAnchor = new GPoint(19, 24);
        icon.isBig = true;
    } else if (markerNr) {
        img = markerImages.big(markerNr);
        icon.iconSize = new GSize(31, 37);
        icon.iconAnchor = new GPoint(16, 28);
        icon.infoWindowAnchor = new GPoint(16, 1);
        icon.isBig = true;
    } else {
        img = markerImages.small;
        icon.iconSize = new GSize(20, 21);
        icon.iconAnchor = new GPoint(9, 15);
        icon.infoWindowAnchor = new GPoint(9, 0);
    }

    icon.image = img;
    marker = new GMarker(latlng, {icon: icon, clickable: clickable});
    return marker;
}

function createMarker(storeInfo, nrOfStores, markerNr) {
    markerNr = markerNr + 1;
    var storeInfoElement = $('store' + storeInfo.csc);
    var marker = createStaticMarker(storeInfo, nrOfStores, true, markerNr);
    marker.markerNr = markerNr;
    marker.csc = storeInfo.csc;
    marker.storeInfoElement = storeInfoElement;
    storeInfoElement.marker = marker;

    GEvent.addListener(marker, "click", function() {
        logClick("SL_Popup: " + this.csc);
        var info = $("storeMouseOverInfo" + this.csc).innerHTML;
        // Before showing popup, move the marker to a fixed
        // position where there is room for the balloon bubble
        var icon = marker.getIcon();
        var iconAnchor = icon.iconAnchor;
        var point = map.fromLatLngToContainerPixel(marker.getLatLng());
        var newX = 175;
        var newY = 350;
        var moveX = newX - point.x;
        var moveY = newY - point.y;
        map.panBy(new GSize(moveX, moveY));
        infoPopupListener = GEvent.addListener(map, "moveend", function() {
            marker.openInfoWindowHtml(info);
            GEvent.removeListener(infoPopupListener);
        });

    });
    GEvent.addListener(marker, "mouseover", function() {
        this.storeInfoElement.className = "mouseOverStore";
        if (this.getIcon().isBig) {
            this.setImage(markerImages.bigOn(this.markerNr));
        } else {
            this.setImage(markerImages.mediumOn);
        }
    });
    GEvent.addListener(marker, "mouseout", function() {
        this.storeInfoElement.className = "";
        if (this.getIcon().isBig) {
            this.setImage(markerImages.big(this.markerNr));
        } else {
            this.setImage(markerImages.medium);
        }
    });
    GEvent.addDomListener(storeInfoElement, 'mouseover', function(event) {
        this.className = "mouseOverStore";
        if (this.marker.getIcon().isBig) {
            this.marker.setImage(markerImages.bigOn(this.marker.markerNr));
        } else {
            this.marker.setImage(markerImages.mediumOn);
        }
    });
    GEvent.addDomListener(storeInfoElement, 'mouseout', function(event) {
        this.className = "";
        if (this.marker.getIcon().isBig) {
            this.marker.setImage(markerImages.big(this.marker.markerNr));
        } else {
            this.marker.setImage(markerImages.medium);
        }
    });
    return marker;
}

function getSelectedCountry() {
    return $('countrySelect').options[$('countrySelect').selectedIndex].value.toLowerCase();
}

function getSelectedCountryInEnglish() {
    return $('countrySelect').options[$('countrySelect').selectedIndex].id;
}

function setSelectedCountry(country) {
    if (country == null) return;

    var e = $(country.toLowerCase());
    if (e != null) {
        e.selected = true;
    }
}

function getSelectedRegion() {
    if ($('regions')) {
        return $('regions').options[$('regions').selectedIndex].value;
    }
    return null;
}

function getSelectedCity() {
    if ($('cities')) {
        return $('cities').options[$('cities').selectedIndex].value;
    }
    return null;
}

function isLinkEnabled() {
    if ($('regions') && getSelectedRegion() == "NO_REGION") {
        return false;
    } else if (getSelectedCity() == "NO_CITY") {
        return false;
    }
    return true;
}

function getSelectedCity() {
    return $('cities').options[$('cities').selectedIndex].value;
}

function getSelectedCountryName() {
    return $('countrySelect').options[$('countrySelect').selectedIndex].innerHTML;
}

function changeSearchType(type) {
    logClick("searchType: " + type.value);
    clearSearchFields();
    searchType = type.value;
    if (type.value == "free") {
        $('freeTextSearch').show();
        $('cityRegionSearch').hide();
        $('zipSearch').hide();
        $('freeTextLabel').className = "checked";
        $('postalLabel').className = "";
        $('cityLabel').className = "";
        $('freeDiv').className = "radio radioChecked";
        $('postalDiv').className = "radio";
        $('cityDiv').className = "radio";
    } else if (type.value == "city") {
        $('freeTextSearch').hide();
        $('cityRegionSearch').show();
        $('zipSearch').hide();
        $('freeTextLabel').className = "";
        $('postalLabel').className = "";
        $('cityLabel').className = "checked";
        $('freeDiv').className = "radio";
        $('postalDiv').className = "radio";
        $('cityDiv').className = "radio radioChecked";
    } else if (type.value == "zip") {
        $('freeTextSearch').hide();
        $('cityRegionSearch').hide();
        $('zipSearch').show();
        $('freeTextLabel').className = "";
        $('postalLabel').className = "checked";
        $('cityLabel').className = "";
        $('freeDiv').className = "radio";
        $('postalDiv').className = "radio radioChecked";
        $('cityDiv').className = "radio";
    }
}

function getZoomLevelForCountry() {
    var zoomLevelsString = $('customZoomLevels').innerHTML.split(",");
    for (var index = 0; index < zoomLevelsString.length; index++) {
        var countryLevel = zoomLevelsString[index].split(":");
        if (countryLevel[0] == getSelectedCountry()) {
            return countryLevel[1];
        }
    }
    return $('defaultZoomLevel').innerHTML;
}

function loadListSearchView() {
    var pars = 'command=listSearchView&locale=' + getSelectedCountry();
    new Ajax.Updater('cityRegionSearch', 'storelocatorV2.ahtml', {
        method: 'post',
        evalJS: 'force',
        parameters: pars,
        onComplete: function(transport) {
            if (getSelectedRegion()) {
                filterCities();
            } else {
                $("listSearchLink").disabled = false;
                $("cities").disabled = false;
            }
        }
    });
}

function regionSelected() {
    if (getSelectedRegion() == "NO_REGION") {
        $("listSearchLink").className = "buttonSmallInactive";
        $("cities").disabled = true;
    } else {
        $("listSearchLink").className = "buttonSmall";
        $("cities").disabled = false;
        filterCities();
    }
}

function citySelected() {
    if (getSelectedCity() == "NO_CITY") {
        $("listSearchLink").className = "buttonSmallInactive";
    } else {
        $("listSearchLink").className = "buttonSmall";
    }
}

function filterCities() {
    var selectedRegion = getSelectedRegion();
    if (selectedRegion) {
        var selLen = $("cities").options.length;
        for (var index = 0; index < selLen; index++) {
            $("cities").options[0] = null;
        }
        var allCitiesTxt = $("allCitiesText").innerHTML;
        $("cities").options[0] = new Option(allCitiesTxt, "ALL_CITIES");
        var opts = $('citiesHolder').select('option[class="' + selectedRegion + '"]');
        opts.each(function(element) {
            $("cities").options[$("cities").options.length] = new Option(element.innerHTML, element.value);
        });
    }
}

function showStoreDetails(csc) {
    var pars = 'command=details' + '&csc=' + csc;
    new Ajax.Updater('storeDetails', 'storelocatorV2.ahtml', {
        method: 'post',
        evalJS: 'force',
        parameters: pars,
        onComplete: function(transport) {
            if ($("selectedStoreNotFound")) {
                //no store with the given csc was found
                return;
            }
            //Track details
            var storeName = $$("#store" + csc + " a")[0].innerHTML.trim()
            trackElementEvent("SL: " + storeName, "Corp: Store Locator");
            $("storeDetails").show();

            var location = $("detailsLocation").innerHTML.evalJSON();
            if (location.lat != null && location.lat != "") {
                showStaticMap(location, "detailsMap");
            }
            switchDetailsTab("details");
        }
    });
}

function closeDetails() {
    $('storeDetails').hide();
    if ($("cities")) {
        $("cities").show();
    }
    if ($("regions")) {
        $("regions").show();
    }
    if ($("slRadius")) {
        $("slRadius").show();
    }
}

function getCurrentElementID() {
    var ret = "";
    if ($("freeText").checked) {
        ret = $("countrySelect").value + " | " + $("ajaxInput").value;
    } else if ($("postal").checked) {
        ret = $("countrySelect").value + " | " + $("slZip").value + " | " + $("slRadius").value;
    } else if ($("city").checked) {
        ret = $("countrySelect").value + " | " + $$('#cities option[value=' + $("cities").value + ']')[0].text;
    }

    return ret;
}

function getFilterElementParams() {
    var bxs = $$('input[class="checkbox selectedConcept"]', 'input[class="selectedFilter"]');
    var str = new Array();
    for (var a in bxs) {
        if (bxs[a].checked) {
            var id = bxs[a].id;
            var name = $(bxs[a].parentNode.nextSiblings())[0].innerHTML.stripTags().trim();
            //Check if we have a parent
            var parent = $(bxs[a].parentNode).up("ul");
            if (parent) {
                var parentName = $("label" + parent.id).innerHTML.stripTags().trim();
                name = parentName + " | " + name;
            }


            str[str.length] = name;
        }
    }
    return str.join("-_-");
}

var Filter = Class.create();
Filter.prototype = {
    filterOut: true,
    filterOn: false,

    initialize: function() {
        var filters = $$('input.unselectedFilter');
        for (var index = 0; index < filters.length; index++) {
            if (filters[index].checked == true) {
                filters[index].className = "selectedFilter"
            }
        }
        filters = null;
        var concepts = $$('input.checkbox unselectedConcept');
        for (var index = 0; index < concepts.length; index++) {
            if (concepts[index].checked == true) {
                concepts[index].className = "checkbox selectedConcept"
            }
        }
        concepts = null;
        //this.resizeFilterBg();
    },

    loadFilters: function(filterArray) {
        var isFilterExpanded = false;
        filterArray.each(
            //toggle each filter
                function(filterName) {
                    if (this.isConceptFilter(filterName)) {
                        var e = this.getChildFilterById(filterName);
                        e.checked = true;
                        var dep = e.value;
                        this.toggleConcept(filterName, dep);

                        //expand _one_ department filter only once
                        if (!isFilterExpanded) {
                            this.expandFilter(this.getIndexForFilter(dep));
                            isFilterExpanded = true;
                        }
                    } else if (this.isDepartmentFilter(filterName)) {
                        $('parent_' + filterName).checked = true;
                        this.toggleFilter(filterName);
                    }
                },
                filter //each() context obj
                );
        this.applyFilters();
    },

    isDepartmentFilter: function(filterName) {
        return $$("fieldset > div#parent_" + filterName + "_Div").length != 0;
    },

    isConceptFilter: function(filterName) {
        return this.getChildFilterById(filterName) != null;
    },

    getChildFilterById: function(filterName) {
        var childFilters = $$("div#filters li input");

        var e = null;

        childFilters.each(
                function(childFilter) {
                    var childFilterId = this.getConceptFilterIdFromElementId(childFilter.id);
                    if (filterName == childFilterId) {
                        e = childFilter;
                    }
                }, filter);

        return e;
    },

    getDepartmentForConcept: function(conceptName) {
        return $(conceptName).value;
    },

    getIndexForFilter: function(department) {
        return $("filter" + department).next("ul").id;
    },

    getDepartmentFilterIdFromElementId: function(elementId) {
        var beginIndex = elementId.search(/parent_/) + 7;
        return elementId.substr(beginIndex);
    },

    getConceptFilterIdFromElementId: function(elementId) {
        var beginIndex = elementId.search(/child_/) + 6;
        return elementId.substr(beginIndex);
    },

    on: function() {
        this.filterOn = true;
        this.applyFilters();
        $("filterOnLink").className = "marked";
        $("filterOffLink").className = "unmarked";
        logClick("SL_Filter: On");
    },

    off: function() {
        this.filterOn = false;
        this.applyFilters();
        $("filterOnLink").className = "unmarked";
        $("filterOffLink").className = "marked";
        logClick("SL_Filter: Off");
    },

    clear: function() {
        var selectedFilters = $$('input[class="checkbox selectedConcept"]', 'input[class="selectedFilter"]');
        for (var index = 0; index < selectedFilters.length; index++) {
            if (selectedFilters[index].parentNode) {
                selectedFilters[index].parentNode.className = "checkbox";
            }
            selectedFilters[index].checked = false;
            var clazz = selectedFilters[index].className.replace("selected", "unselected");
            selectedFilters[index].className = clazz;
        }
        filter.applyFilters();
        logClick("SL_Filter: Reset");
    },

    expandFilter: function(filterId) {
        var filterNodes = $$('ul.selected');
        var filterExpanded = $(filterId).className == "selected";
        if (filterNodes.length > 0) {
            for (var index = 0; index < filterNodes.length; index++) {
                filterNodes[index].hide();
                filterNodes[index].className = "filter";
                $("label" + filterNodes[index].id).className = "";
            }
        }
        if (filterExpanded) {
            $(filterId).className = "filter";
            $(filterId).hide();
            $("label" + filterId).className = "";
        } else {
            $(filterId).show();
            $(filterId).className = "selected";
            $("label" + filterId).className = "selected";
        }
        this.resizeFilterBg();
    },

    toggleFilter: function (filterId) {
        var filterInputElement = $('parent_' + filterId);
        var filterContainerElement = $('parent_' + filterId + '_Div');

        var filterName = $(filterContainerElement.nextSiblings())[0].innerHTML.stripTags().trim();

        if (filterInputElement.checked == true) {
            filterInputElement.className = "selectedFilter";
            if (this.filterOn == false) {
                this.filterOn = true;
            }

            filterContainerElement.className = "checkbox checkboxChecked";
            logClick(getCurrentElementID() + ": " + filterName + ": On", getFilterElementParams());
        } else {
            filterInputElement.className = "unselectedFilter";
            filterContainerElement.className = "checkbox";
            var selectedConcepts = $$('input[class="checkbox selectedConcept"][value=\"' + filterId + '\"]');
            if (selectedConcepts && selectedConcepts.length > 0) {
                for (var index = 0; index < selectedConcepts.length; index++) {
                    selectedConcepts[index].checked = false;
                    selectedConcepts[index].className = "checkbox unselectedConcept";
                    $($(selectedConcepts[index]).id + "_Div").className = "checkbox";
                }
            }
            logClick(getCurrentElementID() + ": " + filterName + ": Off", getFilterElementParams());

        }
    },

    toggleConcept: function(conceptId, filterId) {
        var filterInputElement = $('parent_' + filterId);
        var conceptInputElement = $('parent_' + filterId + '_child_' + conceptId);
        var conceptContainerElement = $('parent_' + filterId + '_child_' + conceptId + '_Div');

        if (conceptInputElement.checked == true) {
            if (!filterInputElement.checked) {
                filterInputElement.checked = true;
                this.toggleFilter(filterId);
            }

            conceptInputElement.className = "checkbox selectedConcept";
            conceptContainerElement.className = "checkbox checkboxChecked";
            logClick(getCurrentElementID() + ": " + conceptId + ": On", getFilterElementParams());
        } else {
            conceptInputElement.className = "checkbox unselectedConcept";
            conceptContainerElement.className = "checkbox";
            logClick(getCurrentElementID() + ": " + conceptId + ": Off", getFilterElementParams());
        }
    },

    applyFilters: function() {
        var filters = $$('input.selectedFilter');
        var stores = $$('span.location');
        $('noResult').hide();
        var storesShown = 0;
        if (stores.length > 0) {
            for (var index = 0; index < stores.length; index++) {
                var store = stores[index];
                var storeInfo = getJSON(store);
                var departmentIds = storeInfo.departmentIds;
                if (filters.length > 0 && this.filterOn) {
                    var hits = 0;
                    for (var index2 = 0; index2 < departmentIds.length; index2++) {
                        for (var index3 = 0; index3 < filters.length; index3++) {
                            var filterId = this.getDepartmentFilterIdFromElementId(filters[index3].id);
                            if (departmentIds[index2] == filterId) {
                                if (this.checkConceptFilter(storeInfo.conceptIds, filterId)) {
                                    hits++;
                                }
                            }
                        }
                    }
                    if (hits == filters.length) {
                        storesShown++;
                        if (store.marker) {
                            store.marker.show();
                            store.marker.pleaseHideLater = false;
                        }
                        store.parentNode.hidden = false;
                        $(store.parentNode).show();
                    } else {
                        if (store.marker) {
                            store.marker.hide();
                            store.marker.pleaseHideLater = true;
                        }
                        store.parentNode.hidden = true;
                        $(store.parentNode).hide();
                    }
                } else {
                    storesShown++;
                    if (store.marker) {
                        store.marker.show();
                        store.marker.pleaseHideLater = false;
                    }
                    store.parentNode.hidden = false;
                    $(store.parentNode).show();
                }
            }
            if (storesShown == 0) {
                $('noResult').show();
            }
        }
        if ($('noOfStores')) {
            $('noOfStores').innerHTML = storesShown;
        }
    },

    checkConceptFilter: function(conceptIds, filterId) {
        var selectedConcepts = $$('input[class="checkbox selectedConcept"][value=\"' + filterId + '\"]');
        if (selectedConcepts && selectedConcepts.length > 0) {
            var hits = 0;
            for (var index = 0; index < conceptIds.length; index++) {
                for (var index2 = 0; index2 < selectedConcepts.length; index2++) {
                    var conceptId = this.getConceptFilterIdFromElementId(selectedConcepts[index2].id);
                    if (conceptId == conceptIds[index]) {
                        hits++;
                    }
                }
            }
            return hits == selectedConcepts.length;
        } else {
            return true;
        }
    },

    resizeFilterBg: function() {
        if (this.filterOut) {
            $('filterBg').style.height = $('filters').offsetHeight + "px";
        } else {
            $('filterBg').style.height = $('filterInfo').offsetHeight + "px";
        }
    },

    toggleFilterView: function() {
        $('filterOn').toggle();
        if (this.filterOut) {
            this.filterOut = false;
            $("filterHeadline").show();
            $("resetFilterLink").hide();
            $("filterButton").src = "/static/images/8_storelocator/buttonUnfold.gif";
            //$("filterOnLink").className = "unmarked";
            //$("filterOnLink").className = "marked";
            $('filterBg').style.width = "80px";
            $('filters').style.width = "60px";
        } else {
            this.filterOut = true;
            $("filterHeadline").hide();
            $("resetFilterLink").show();
            $("filterButton").src = "/static/images/8_storelocator/buttonFold.gif";
            //$("filterOnLink").className = "marked";
            //$("filterOnLink").className = "unmarked";
            $('filterBg').style.width = "163px";
            $('filters').style.width = "145px";
        }
        this.resizeFilterBg();
    }
}

function switchDetailsTab(tab) {
    if (tab == "details") {
        logPageView("SL_DetailsInfo");
        $("storeDetailsTab").className = "detailsContent";
        $("storeMapTab").className = "detailsContent tabSelected";
        $("detailsLi").className = "current";
        $("mapLi").className = "";
    } else if (tab == "map") {
        logPageView("SL_DetailsMap");
        $("storeDetailsTab").className = "detailsContent tabSelected";
        $("storeMapTab").className = "detailsContent";
        $("detailsLi").className = "";
        $("mapLi").className = "current";
    }
}

var clear = "/static/images/8_storelocator/clear.gif";
var pngfix = function() {
    var els = document.getElementsByTagName('*');
    var ip = /\.png/i;
    var i = els.length;
    while (i-- > 0) {
        var el = els[i];
        var es = el.style;
        if (el.src && el.src.match(ip) && !es.filter) {
            es.height = el.height;
            es.width = el.width;
            es.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + el.src + "',sizingMethod='crop')";
            el.src = clear;
        } else {
            var currentStyle = el.currentStyle;
            var elb;
            if (currentStyle) {
                elb = currentStyle.backgroundImage;
            }
            if (elb && elb.match(ip)) {
                var path = elb.split('"');
                var rep = (el.currentStyle.backgroundRepeat == 'no-repeat') ? 'crop' : 'scale';
                es.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + path[1] + "',sizingMethod='" + rep + "')";
                es.height = el.clientHeight + 'px';
                es.backgroundImage = 'none';
                var elkids = el.getElementsByTagName('*');
                if (elkids) {
                    var j = elkids.length;
                    if (el.currentStyle.position != "absolute")
                        es.position = 'static';
                    while (j-- > 0)
                        if (!elkids[j].style.position)elkids[j].style.position = "relative";
                }
            }
        }
    }
}

function openConcept(id) {
    var current = $("detailDepartments").select('li[class="current"]');
    for (var index = 0; index < current.length; index++) {
        current[index].className = "";
        if ($("sub" + current[index].id)) {
            $("sub" + current[index].id).hide();
        }
    }
    $(id).className = "current";
    if ($("sub" + id)) {
        $("sub" + id).show();
    }
}

function closeConcept() {
    var current = $("detailDepartments").select('li[class="current"]');
    for (var index = 0; index < current.length; index++) {
        current[index].className = "";
        if ($("sub" + current[index].id)) {
            $("sub" + current[index].id).hide();
        }
    }
}

function printDetails() {
    $("searchResult").hide();
    $("mapContainer").hide();
    window.print();
    $("searchResult").show();
    $("mapContainer").show();

}

var freeClearState = true;
function clearFreeInitialText(force) {
    if (freeClearState && force) {
        $("ajaxInput").value = "";
        freeClearState = false;
    } else if (!freeClearState && !force) {
        $("ajaxInput").value = "";
        freeClearState = false;
    }
}

var postalClearState = true;
function clearPostalInitialText(force) {
    if (postalClearState && force) {
        $("slZip").value = "";
        postalClearState = false;
    } else if (!postalClearState && !force) {
        $("slZip").value = "";
        postalClearState = false;
    }
}

function clearSearchFields() {
    clearFreeInitialText(false);
    clearPostalInitialText(false);
}

function checkEnableSearch(input) {
    if (input.value == "") {
        $("zipSearchButton").className = "buttonSmallInactive";
    } else {
        $("zipSearchButton").className = "buttonSmall";
    }
}

/*
 logPageView logs a pageview of the specified pagename in Omniture SiteCatalyst

 Requires the omniture js
 */
function logPageView(pageName) {
    var pageName = "" + pageName;
    trackFlashPageView(pageName, "static:storelocatorjs", null, null, null);
}

/*
 logClick logs a click at a named counter in Omniture SiteCatalyst

 Requires the omniture js
 */
function logClick(counter, params) {
    if (counter.indexOf("CRP") !== 0) {
        counter = "" + counter;
    }
    trackElementEvent(counter, "Store Locator Map", params);

}

function searchTextResult(isEnter) {
    if (isEnter) {
        var suggestSelector = document.getElementById('suggest_selector');
        if (suggestSelector != null && suggestSelector.selectedIndex == -1) {
            clearFreeInitialText(true);
            searchText($('ajaxInput').value, $('countrySelect').options[$('countrySelect').selectedIndex].value);
        }
    }
}

function searchZipResult(isEnter) {
    if (isEnter) {
        clearPostalInitialText(true);
        searchZip($('slZip').value, $('slRadius').options[$('slRadius').selectedIndex].value);
    }
}

function checkEnter(e) {
    var characterCode;

    if (e && e.which) { //Netscape/Firefox/Opera
        e = e
        characterCode = e.which
    }
    else {
        e = event
        characterCode = e.keyCode //IE
    }

    if (characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
        return true
    }
    else {
        return false
    }

}

/*
 JSON method that tries not introduce HTML escaping in the JSON data
 (as opposed to using innerHTML.evalJSON() with Prototype)
 */
function getJSON(element) {
    if (element.textContent) {
        return eval('(' + element.textContent + ')');
    } else if (element.innerText) {
        return eval('(' + element.innerText + ')');
    } else {
        //last effort  
        return element.innerHTML.evalJSON();
    }
}



