﻿var Distributers = {
    distributersCache: $H(),
    regionsCache: $H(),
    countriesCache: $H(),
    citiesCache: $H(),
    citiesHasDistributers: $H(),
    ddlCountriesId: '',
    ddlRegionsId: '',
    ddlCitiesId: '',
    distributerTypesCount: 0,
    showroomCount: 0,
    demoCountertopCount: 0,
    stoneSamplesCount: 0,
    dealerCount: 0,
    AddRegionsToCache: function(list) {
        list.each(function(region) {
            Distributers.regionsCache.set("Region" + region.RegionId, region);
        });
    },
    AddDistributersToCache: function(list) {
        list.each(function(distributer) {
            Distributers.distributersCache.set("Distributer" + distributer.DistributerId, distributer);
            Distributers.citiesHasDistributers.set(distributer.CityId, true);
        });
    },
    AddCountriesToCache: function(list) {
        list.each(function(country) {
            Distributers.countriesCache.set("Country" + country.CountryId, country);
        });
    },
    AddCitiesToCache: function(list) {
        list.each(function(city) {
            Distributers.citiesCache.set("City" + city.CityId, city);
        });
    },
    RegisterEvents: function(rId, cId, ctId, tp) {
        Distributers.ddlRegionsId = rId;
        Distributers.ddlCountriesId = cId;
        Distributers.ddlCitiesId = ctId;
        Distributers.txtPostal = tp;

        $(rId).observe("change", function(e) { Distributers.RegionChanged(null, true) });
        $(cId).observe("change", function(e) { Distributers.CountryChanged(null, true) });
        if ($(Distributers.ddlCountriesId).getStyle("display") == "none")
            $(ctId).observe("change", function(e) { Distributers.CountryChanged($(ctId).value, true) });
        else
            $(ctId).observe("change", Distributers.CityChanged);

        $('DistributersListWrap').hide();
    },

    btnPostalClicked: function(e) {
        var o = $(Distributers.txtPostal);
        txtPostal = o.value;

        if (txtPostal != "") {
            //$(Distributers.ddlCitiesId).selectedIndex = 0;
            Distributers.ShowDistributers(null, null, txtPostal);
        }
        else {
            Distributers.linkClearClicked();
        }
    },

    linkClearClicked: function(e) {
        var o = $(Distributers.txtPostal);
        o.value = '';
        $(Distributers.ddlCitiesId).selectedIndex = 0;
        Distributers.ShowDistributers(null, "0", "");
    },
    GetRegionId: function(queryName) {
        var id = 0;
        var regions = Distributers.regionsCache.values();
        for (var i = 0, len = regions.length; i < len; i++) {
            if (regions[i].QueryName == queryName) {
                id = regions[i].RegionId;
                break;
            }
        }
        return id;
    },

    GetCountryId: function(codeName) {
        var id = 0;
        var countries = Distributers.countriesCache.values();
        for (var i = 0, len = countries.length; i < len; i++) {
            if (countries[i].CodeName == codeName) {
                id = countries[i].CountryId;
                break;
            }
        }
        return id;
    },

    RegionChanged: function(regionId, notifyFlash) {
        var o = $(Distributers.ddlRegionsId);

        if (regionId) {
            o.value = regionId;
        } else {
            regionId = o.value;
        }
        if (regionId != 0) {
            if (notifyFlash) $waitUntil(function() { return $("MapWrap").gotoRegion != null; }, function() { $("MapWrap").gotoRegion(Distributers.regionsCache.get("Region" + $(Distributers.ddlRegionsId).value).QueryName); });
            Distributers.FilterCountries(regionId);

            if ($(Distributers.ddlCountriesId).getStyle("display") == "none") {
                Distributers.ShowDistributers(null, 0);
            }
        }
        else {
            Distributers.FilterCountries(0);
        }
    },

    CountryChanged: function(countryId, notifyFlash) {
        var o = $(Distributers.ddlCountriesId);

        if (countryId) {
            o.value = countryId;
        } else {
            countryId = o.value;
        }

        Distributers.SetDistributerWindow(countryId);
        Distributers.FilterCities(countryId);
        if ($(Distributers.ddlCountriesId).getStyle("display") == "none")
            Distributers.ShowDistributers(null, countryId);
        else
            Distributers.ShowDistributers(countryId);
    },

    SetDistributerWindow: function(countryId) {
        var country = Distributers.countriesCache.get("Country" + countryId);

        if (country == null) return;
        $("DealerTitle").innerHTML = country.SubHeader;
        $("DealerAddress").innerHTML = country.Address.gsub(/\n/, '<br/>');

        if (country.Url != '') {
            $("DealerUrl").innerHTML = country.Url;
            $("DealerUrl").href = (country.Url.toLowerCase().indexOf('http://') == -1 ? 'http://' : '') + country.Url;

            //if(country.Url.indexOf("caesarstoneus.com")>-1){
            //	$("DealerUrl").onclick=function(){pageTracker._trackPageview('/outgoing/caesarstoneus.com');};
            //}
            //else{
            //	$("DealerUrl").onclick="";
            //}
            //alert(country.Url.indexOf("caesarstoneus.com")+"_____"+$("DealerUrl").onclick);
            $("DealerUrl").onclick = function() { pageTracker._trackPageview('/distributor/site/' + country.Header); };

            $("DealerUrl").show();
        } else {
            $("DealerUrl").hide();
        }

        if (country.ContactEmail != '') {
            //$("DealerEmail").innerHTML = country.ContactEmail;
            //$("DealerEmail").href = "mailto:" + country.ContactEmail;
            //$("DealerEmail").href = "#";

            $("DealerEmail").onclick = function() { Distributers.showForm(country.LogHeader, country.ContactEmail); };
            $("DealerEmail").show();
        } else {
            $("DealerEmail").hide();
        }
    },
    showForm: function(country, address) {

        this.DealerEmailFormLightbox = new lightbox($("lightboxAll"), $("distributers-email-form"), false);

        var idInput = $("ToAddress");
        if (idInput) {
            idInput.value = address;
        }
        idInput = $("LogHeader");
        if (idInput) {
            idInput.value = country;
        }

        //		if (pageTracker){
        //			pageTracker._trackPageview('/distributor/mail/'+ country.Header);
        //		}
    },
    closeForm: function() {
        this.DealerEmailFormLightbox.deactivate();
    },
    CityChanged: function(e, cityId) {
        countryId = null;
        var o = $(Distributers.ddlCitiesId);
        if (cityId) {
            o.value = cityId;
        } else {
            cityId = o.value;
        }

        if (cityId != "0") {
            var city = Distributers.citiesCache.get("City" + cityId);
            if (city == null) return;
        }
        Distributers.ShowDistributers(countryId, cityId);
    },
    FilterCountries: function(regionId) {
        var o = null;
        if ($(Distributers.ddlCountriesId).getStyle("display") == "none")
            o = $(Distributers.ddlCitiesId);
        else
            o = $(Distributers.ddlCountriesId);
        var iterations = 0;
        var option;

        o.length = 1;

        countries = Distributers.countriesCache.values();

        if (regionId > 0) {
            for (var i = 0, len = countries.length; i < len; i++) {
                if (countries[i].Region != null && countries[i].Region.RegionId == regionId) {
                    option = document.createElement("option");
                    option.text = countries[i].Header;
                    option.value = countries[i].CountryId;
                    if (is_ie) {
                        o.add(option);
                    } else {
                        o.add(option, null);
                    }
                }
            }
        }
        else {
            for (var i = 0, len = countries.length; i < len; i++) {
                option = document.createElement("option");
                option.text = countries[i].Header;
                option.value = countries[i].CountryId;
                if (is_ie) {
                    o.add(option);
                } else {
                    o.add(option, null);
                }
            }
        }
    },
    FilterCities: function(countryId) {
        if (countryId == null) return;
        if ($(Distributers.ddlCountriesId).getStyle("display") == "none") {
            $(Distributers.ddlCitiesId).value = countryId;
            return;
        }

        var o = $(Distributers.ddlCitiesId);
        var iterations = 0;
        var option;

        while (o.length > 1 && iterations++ < 200) {
            o.remove(1);
        }

        cities = Distributers.citiesCache.values();
        for (var i = 0; i < cities.length; i++) {
            if (cities[i].Country != null) {
                if (cities[i].Country.CountryId == countryId) {
                    if (Distributers.citiesHasDistributers.get(cities[i].CityId)) {
                        option = document.createElement("option");
                        option.text = cities[i].Header;
                        option.value = cities[i].CityId;
                        if (is_ie) {
                            o.add(option);
                        } else {
                            o.add(option, null);
                        }
                    }
                }
            }
        }
    },
    setTypesCount: function(distrCount) {
        Distributers.distributerTypesCount = distrCount;
    },
    hideAllDistributerTypes: function(distrCount) {
        var typesContainers = document.getElementsByClassName("distributer-type");
        for (var i = 0; i < typesContainers.length; i++) {

            typesContainers[i].hide();
        }

        //		var currItemsContainer;
        //		for (var i=1;i<=distrCount;i++){
        //			currItemsContainer = $("distributer-type-"+i);
        //			if(currItemsContainer){currItemsContainer.hide();}
        //		}
    },
    ShowDistributers: function(countryId, cityId, postalCode) {
        //we do this for refresh distributers for all cities
        if (cityId == "0") countryId = ($(Distributers.ddlCountriesId).value != "0") ? $(Distributers.ddlCountriesId).value : null;

        var list = [];
        var showroomlist = [];
        distributers = Distributers.distributersCache.values();

        var withCountertopUiText = $('withCountertopUiText').value;
        var template = '<div class="distributer">\
							<div class="distributerHeader"><h4>{0}</h4></div>\
							<div class="distributerBody">\
							<div>{1}</div>\
							<div class="{4} orange">' + withCountertopUiText + '</div>\
							<div class="distEmail"{3}><a href="#" >{2}</a></div>\
							</div>\
						<div class="distTinySep"></div></div>';
        var templateLast = '<div class="distributer">\
							<div class="distributerHeader"><h4>{0}</h4></div>\
							<div class="distributerBody">\
							<div>{1}</div>\
							<div class="distEmail"{3}><a href="#" >{2}</a></div>\
							</div>\
						</div>';

        var style = "";

        //---------------------------------------------
        var itemsList = [];
        var currItemsContainer, currType, distribType
        if ((distributers.length > 0) && (distributers[0].DistributerType != null)) {
            currType = distributers[0].DistributerType.DistributerTypeId;
        }
        else {
            currType = 0;
        }

        Distributers.hideAllDistributerTypes(Distributers.distributerTypesCount);

        if (countryId != null) {

            var totalDistributersInCurrentCountry = 0;

            for (var i = 0; i < distributers.length; i++) {
                if (distributers[i].CountryId == countryId) {
                    totalDistributersInCurrentCountry++;
                }
            }
            if (totalDistributersInCurrentCountry == 0) {
                $('DistributersListWrap').hide();
                $('contentpage-body').show();
            }
            else {
                $('DistributersListWrap').show();
                $('contentpage-body').hide();
            }
        }
        else {
            $('DistributersListWrap').show();
            $('contentpage-body').hide();
        }

        Distributers.dealerCount = 0;
        Distributers.showroomCount = 0;
        Distributers.demoCountertopCount = 0;
        Distributers.stoneSamplesCount = 0;
        for (var i = 0, len = distributers.length; i < len; i++) {
            if (distributers[i].CountryId == countryId || distributers[i].CityId == cityId || postalCode != '' && (eval("distributers[i].PostalCode.search(/" + postalCode + "/i)") > -1 || eval("distributers[i].Header.search(/" + postalCode + "/i)") > -1 || eval("distributers[i].Address.search(/" + postalCode + "/i)") > -1)) {
                if (distributers[i].ContactEmail == '') style = ' style="display: none"'; else style = '';
                if (distributers[i].DistributerType != null) {//must have type

                    distribType = distributers[i].DistributerType.DistributerTypeId;

                    // get count by distr type
                    if (distribType == 1) {
                        Distributers.dealerCount++;
                    }

                    if (distribType == 2) {
                        Distributers.showroomCount++;
                        if (distributers[i].IsDemoCountertop)
                            Distributers.demoCountertopCount++;
                        if (distributers[i].IsStoneSamples)
                            Distributers.stoneSamplesCount++;
                    }

                    //add this item to current list of items
                    if (currType == distribType) {
                        itemsList.push(String.format(template,
							distributers[i].Header,
							distributers[i].Address,
							distributers[i].ContactEmail,
							style,
							Distributers.getOnOrOffClassByBoolean(distributers[i].IsDemoCountertop)
							)
						);
                    }

                    //make new list
                    else {
                        //inser the current list

                        if (itemsList.length > 0) {
                            currItemsContainer = $("distributer-type-items-" + currType);
                            currItemsContainer.innerHTML = itemsList.join("");
                            if ($("distributer-type-" + currType)) { $("distributer-type-" + currType).show(); }
                        }
                        else {
                            if ($("distributer-type-" + currType)) { $("distributer-type-" + currType).hide(); }
                        }

                        itemsList = []; //make new list
                        itemsList.push(String.format(template,
							distributers[i].Header,
							distributers[i].Address,
							distributers[i].ContactEmail,
							style,
							Distributers.getOnOrOffClassByBoolean(distributers[i].IsDemoCountertop)
							)
						);
                        currType = distribType;
                    }
                }
            }
        }
        if (itemsList.length > 0) {
            currItemsContainer = $("distributer-type-items-" + currType);
            if ($("distributer-type-" + currType)) { $("distributer-type-" + currType).show(); }
            currItemsContainer.innerHTML = itemsList.join("");
            itemsList = [];
        }

        if ($(Distributers.ddlRegionsId).selectedIndex > 0) $("HeaderRegion").innerHTML = $(Distributers.ddlRegionsId)[$(Distributers.ddlRegionsId).selectedIndex].text;
        if ($(Distributers.ddlCountriesId).selectedIndex > 0) $("HeaderCountry").innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + $(Distributers.ddlCountriesId)[$(Distributers.ddlCountriesId).selectedIndex].text;

        var links = $("DistributersListWrap").getElementsByClassName("distEmail");
        var country = Distributers.countriesCache.get("Country" + countryId);

        for (var i = 0; i < links.length; i++) {
            var item = links[i].childElements()[0];
            if (item.innerHTML.length > 0) {
                var address = item.innerHTML;
                item.innerHTML = SEND_TO_UI_LABEL;
                item.rel = address;
                item.onclick = function(el) {
                    Distributers.showForm(country.LogHeader, this.rel);
                };
            }
        }

        // populate the DistributersFilteringResult div
        if (Distributers.showroomCount == 0) {
            $("idShowroomCount").hide();
            $("idDemoCountertopCount").hide();
            $("idStoneSamplesCount").hide();
        }
        else {
            $("idShowroomCount").show();
            $("DistributersShowroomCount").innerHTML = Distributers.showroomCount;

            if (Distributers.demoCountertopCount == 0) {
                $("idDemoCountertopCount").hide();
            }
            else {
                $("idDemoCountertopCount").show();
                $("DistributersDemoCountertopCount").innerHTML = Distributers.demoCountertopCount;
            }

            if (Distributers.stoneSamplesCount == 0) {
                $("idStoneSamplesCount").hide();
            }
            else {
                $("idStoneSamplesCount").show();
                $("DistributersStoneSamplesCount").innerHTML = Distributers.stoneSamplesCount;
            }
        }
        if (cityId == null || cityId == "0") {
            var o = $(Distributers.ddlCitiesId);
            if (o.value == 0) {
                $("cityMapUrl").hide();
                $("chooseCityToSeeMap").show();
            }
        }
        else {
            $("chooseCityToSeeMap").hide();
            _cities = Distributers.citiesCache.values();
            for (var i = 0; i < _cities.length; i++) {
                if (cityId == _cities[i].CityId) {
                    if (_cities[i].Url != "" && _cities[i].Url != null && _cities[i].Url != 'undefined') {
                        $("cityMapUrl").href = _cities[i].Url;
                        $("cityMapUrl").show();
                    }
                    else
                        $("cityMapUrl").hide();
                }
            }
        }
    },

    getOnOrOffClassByBoolean: function(bool) {
        if (!bool)
            return "off";
        else
            return "";
    }
}

//called from the flash map
function setRegion( regionCodeName ){
	Distributers.RegionChanged(Distributers.GetRegionId(regionCodeName), false);
}

//called from the flash map
function selectCountry ( countryCodeName){
	Distributers.CountryChanged(Distributers.GetCountryId(countryCodeName), false);
}
