﻿var locationString = "";
var distance;
var InfoBox;
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,
    geocoder: '',
    location1: '',
    location2: '',
    SearchRange: 0,
    ResultInMiles: true,
    filterByRange: false,
    currentDistributer: 0,
    resultOk: false,
    map: null,
    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);
        });
    },
    calculateDistance: function(compareTo) {
        try {
            var glatlng1 = new GLatLng(locationString.lat, locationString.lon);
            var glatlng2 = new GLatLng(compareTo.lat, compareTo.lon);
            var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
            var kmdistance = (miledistance * 1.609344).toFixed(1);
            if (this.ResultInMiles == true)
                return miledistance;
            else
                return kmdistance;
        }
        catch (error) {
            alert(error);
        }
    },


    initializeMapParams: function() {
        this.SearchRange = "50000"; //$$(".ddlRange")[0].value;
        this.filterByRange = $$(".ddlScale")[0].value;
    },
    initializeMap: function() {
        Distributers.geocoder = new GClientGeocoder();
    },

    showMap: function(lat, lon, title, address, display) {
        this.DealerMap = new lightbox($("lightboxAll"), $("mapHolder"), false);
        var elem = document.getElementById("mapHolder");
        elem.style.display = "block";
        var vlightbox = document.getElementById("lightbox-back");
        vlightbox.style.width = "537px";
        vlightbox.style.height = "560px";

        var disp = $(display);
        displayContent = disp.childElements()[1].childElements()[0].childElements()[4].innerHTML;


        $$(".map-header .title")[0].update(title);
        var myLatLng = new google.maps.LatLng(lat, lon);

        if (GBrowserIsCompatible()) {
            this.map = new GMap2(document.getElementById("map_canvas"));
            this.map.setCenter(new GLatLng(lat, lon), 13);
            this.map.setUIToDefault();


            var baseIcon = new GIcon(G_DEFAULT_ICON);
            baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
            baseIcon.iconSize = new GSize(20, 34);
            baseIcon.shadowSize = new GSize(37, 34);
            baseIcon.iconAnchor = new GPoint(9, 34);
            baseIcon.infoWindowAnchor = new GPoint(9, 2);
            //console.log(baseIcon);

            var bounds = this.map.getBounds();
            var southWest = bounds.getSouthWest();
            var northEast = bounds.getNorthEast();
            var lngSpan = northEast.lng() - southWest.lng();
            var latSpan = northEast.lat() - southWest.lat();
            var point = new GLatLng(lat, lon);


            var letteredIcon = new GIcon(baseIcon);
            letteredIcon.image = "http://www.google.com/mapfiles/markerD.png";
            markerOptions = { icon: letteredIcon };
            var marker = new GMarker(point, markerOptions);
            var htmlMsg = "<div style='color:#000000;float:left;direction:ltr;font-family:arial;font-size:12px;'>" + address + "</div>";
            htmlMsg += "<div style='float:left;clear:both;color:#000000;font-family:arial;font-size:12px;width:200px;text-align:left;'>" + displayContent + "</div>";

            GEvent.addListener(marker, "click", function() {
                marker.openInfoWindowHtml(htmlMsg);
            });


            this.map.addOverlay(marker);



            //map.addOverlay(baseIcon);

        }
        var distributerEmail = document.getElementById("distributers-email-form");
        distributerEmail.style.display = "none";

    },



    closeMap: function(e) {
        this.DealerMap.deactivate(); eight = "";
        var elem = document.getElementById("mapHolder");
        elem.style.display = "none";


    },

    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 = $$(".zipCode")[0]; //$(Distributers.txtPostal);
        //console.log(o.value.replace(/^\s+|\s+$/g, ''));
        txtPostal = o.value.replace(/^\s+|\s+$/g, '');

        //        if (txtPostal != "") {
        //            //$(Distributers.ddlCitiesId).selectedIndex = 0;
        //            Distributers.ShowDistributers(null, null, txtPostal);
        //        }
        //        else {
        //            Distributers.linkClearClicked();
        //        }
        Distributers.linkClearClicked();
    },

    overServiceDetails: function(e) {
        var ServiceElem = e.childNodes[1];
        ServiceElem.style.display = 'block';
    },

    outServiceDetails: function(e) {
        var ServiceElem = e.childNodes[1];
        ServiceElem.style.display = 'none';
    },

    linkClearClicked: function(e) {
        //var o = $(Distributers.txtPostal);
        // o.value = '';
        $(Distributers.ddlCitiesId).selectedIndex = 0;
        locationString = $$(".zipCode")[0].value;
        if (locationString != "") {
            this.initializeMapParams();
            setLocationString();
        }
        else
            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);
        }
        $("DealerDetails").addClassName('hidden');
    },

    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;
        $("DealerDetails").removeClassName('hidden');
        var obj1 = {};
        obj1.titleElem = $("DealerTitle");
        obj1.titleVal = country.SubHeader;
        obj1.addressElem = $("DealerAddress");
        obj1.addressVal = country.Address;
        obj1.urlElem = $("DealerUrl");
        obj1.urlVal = country.Url;
        obj1.emailElem = $("DealerEmail");
        obj1.emailVal = country.ContactEmail;
        Distributers.SetDistributerWindowByObj(obj1, country);

        var obj2 = {};
        obj2.titleElem = $("DealerTitle2");
        obj2.titleVal = country.DistributerName2;
        obj2.addressElem = $("DealerAddress2");
        obj2.addressVal = country.Address2;
        obj2.urlElem = $("DealerUrl2");
        obj2.urlVal = country.Url2;
        obj2.emailElem = $("DealerEmail2");
        obj2.emailVal = country.ContactEmail2;
        Distributers.SetDistributerWindowByObj(obj2, country);
    },
    SetDistributerWindowByObj: function(obj, country) {
        obj.titleElem.innerHTML = obj.titleVal;
        obj.addressElem.innerHTML = obj.addressVal.gsub(/\n/, '<br/>');

        if (obj.urlVal != '') {
            obj.urlElem.innerHTML = obj.urlVal;
            obj.urlElem.href = (obj.urlVal.toLowerCase().indexOf('http://') == -1 ? 'http://' : '') + obj.urlVal;

            obj.urlElem.onclick = function() { pageTracker._trackPageview('/distributor/site/' + country.Header); };

            obj.urlElem.show();
        } else {
            obj.urlElem.hide();
        }

        if (obj.emailVal != '') {

            obj.emailElem.onclick = function() { Distributers.showForm(country.LogHeader, obj.emailVal); };
            obj.emailElem.show();
        } else {
            obj.emailElem.hide();
        }
    },
    showForm: function(country, address) {

        this.DealerEmailFormLightbox = new lightbox($("lightboxAll"), $("distributers-email-form"), false);
        var distributerEmail = document.getElementById("distributers-email-form");
        distributerEmail.style.display = "block";
        var idInput = $("ToAddress");
        if (idInput) {
            idInput.value = address;
        }
        idInput = $("LogHeader");
        if (idInput) {
            idInput.value = country;
        }
    },
    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();
        }
    },
    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="left">\
							<div class="distributerHeader" style=""><h4>{0}</h4>\
							 <div class="distributerServices">{4}</div></div>\
							</div>\
							<div class="right">\
							<div class="distributerBody">\
							 <div class="title">Address</div>\
							<div class="address">\
							{1}</div>\
							<div class="title"></div>\
							<div class="{2} orange">' + withCountertopUiText + '</div>\
							{3}\
							</div>\
							</div>\
						<div class="distTinySep"></div></div>';
        var templateMap = '<div class="distributer" id=\'{10}\'>\
                            <div class="left">\
							<div class="distributerHeader" style=""><h4>{0}</h4>\
							 <div class="distributerServices">{4}</div></div>\
							</div>\
							<div class="right" >\
							<div class="distributerBody" >\
							 <div class="title" style="margin-top:30px;">' + addressTxt + '</div>\
							<div class="address">\
							{1}</div>\
							<div class="view-map" style="margin-bottom:10px;float:left;clear:both;"><div style="color:#6b6251;float:left;clear:both;border-bottom:solid 1px #6b6251;cursor:pointer;" onclick="Distributers.showMap({5},{6},\'{7}\',\'{1}\',\'{10}\');">View map</div></div>\
							<div class="title">' + txtDisplay + '</div>\
							<div class="display" style="float:left;font-family:arial;font-size:11px;color:#000000;clear:both;">{9}</div>\
							<div class="{2} orange" style="margin-top:10px;">' + withCountertopUiText + '</div>\
							{3}\
							</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="distEmails"{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;


        //checking if need to consider the range params,
        //if no location entered sorting distributer in the regular way other wise 
        //we keep just the disributer in the relevant range



        for (var i = 0, len = distributers.length; i < len; i++) {
            this.currentDistributer = i;
            //the top if is with search for postal 
            //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].CountryId == countryId || distributers[i].CityId == cityId) {
                if (distributers[i].DistributerType != null || UseGmap==false && distributers[i].Latitude != null && distributers[i].Latitude != "" ) {//must have type
                    if (locationString != "") {
                        distributers[i].location2 = { lat: distributers[i].Latitude, lon: distributers[i].Longitude };
                        distance = this.calculateDistance(distributers[i].location2);
                        distributers[i].distance = distance;
                    }
                    if (parseFloat(distributers[i].distance) <= parseFloat(this.SearchRange) || locationString == "") {
                        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) {
                            if (typeof distributers[i].distance == 'undefined' || locationString == "") {
                                itemsList.push(String.format(template,
							distributers[i].Header,
							distributers[i].Address,
							Distributers.getOnOrOffClassByBoolean(distributers[i].IsDemoCountertop),
							Distributers.getEmailDivs(distributers[i].ContactEmail, distributers[i].ContactEmail2, distributers[i].ContactEmail3, distributers[i].Website),
							Distributers.getDistributerServices(distributers[i].DistributerService)
							)
						);
                            }
                            else {
                                itemsList.push(String.format(templateMap,
							    distributers[i].Header,
							    distributers[i].Address,
							    Distributers.getOnOrOffClassByBoolean(distributers[i].IsDemoCountertop),
							    Distributers.getEmailDivs(distributers[i].ContactEmail, distributers[i].ContactEmail2, distributers[i].ContactEmail3, distributers[i].Website),
							    Distributers.getDistributerServices(distributers[i].DistributerService),
							    distributers[i].Latitude,
							    distributers[i].Longitude,
							    distributers[i].Header,
							    distributers[i].Address,
							    distributers[i].Display,
							    distributers[i].DistributerId
							)
						);
                            }

                        }

                        //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(); }
                            }

                            if (typeof distributers[i].distance == 'undefined' || locationString == "") {
                                itemsList = []; //make new list
                                itemsList.push(String.format(template,
							distributers[i].Header,
							distributers[i].Address,
							Distributers.getOnOrOffClassByBoolean(distributers[i].IsDemoCountertop),
							Distributers.getEmailDivs(distributers[i].ContactEmail, distributers[i].ContactEmail2, distributers[i].ContactEmail3, distributers[i].Website),
							Distributers.getDistributerServices(distributers[i].DistributerService)
							)
						);
                            }
                            else {
                                itemsList = []; //make new list
                                itemsList.push(String.format(templateMap,
							distributers[i].Header,
							distributers[i].Address,
							Distributers.getOnOrOffClassByBoolean(distributers[i].IsDemoCountertop),
							Distributers.getEmailDivs(distributers[i].ContactEmail, distributers[i].ContactEmail2, distributers[i].ContactEmail3, distributers[i].Website),
							Distributers.getDistributerServices(distributers[i].DistributerService),
							distributers[i].Latitude,
							distributers[i].Longitude,
							distributers[i].Header,
							distributers[i].Address,
							distributers[i].Display,
							distributers[i].DistributerId
							)
						);
                            }
                            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.rel.length > 0) {
                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 "";
    },

    getDistributerServices: function(services) {
        var serviceTemplateOpener = '<div class="service-wrapper">';
        var serviceItemTemplate = '<div class="service" style="background-color:Gray;width:33px;float:left;margin-left:8px;cursor:pointer;position:relative;height:28px;" onMouseOver="Distributers.overServiceDetails(this);" onMouseOut="Distributers.outServiceDetails(this);">{0}\
        <div class="desc" style="background-image:url(\'Images/service-desc-bg.png\');background-repeat:no-repeat;width:229px;height:101px;position:relative;top:-117px;right:95px;display:none;">\
        <div style="float:left;color:#ef7d0b;font-family:Arial;font-size:11px;text-transform:uppercase;margin-left:15px;margin-top:10px;width:193px;">{1}</div><div style="margin-left:15px;margin-top:5px;float:left;color:#b6b3b3;font-family:Arial;font-size:11px;width:193px;overflow:hidden;height:50px;">{2}</div>\
        </div>\
        </div>';
        //console.log(services[0]);
        var itemWrapper = "";
        var serviceTemplateCloser = '</div>';
        if (services.length > 0) {
            for (var i = 0; i < services.length; i++) {
                itemWrapper += String.format(serviceItemTemplate, services[i].Title, services[i].Title, services[i].Tip);
            }
            var finalTemplate = serviceTemplateOpener + itemWrapper + serviceTemplateCloser;
            return finalTemplate;
        }
        return "";

    },

    getEmailDivs: function(Email, Email2, Email3, website) {
        var emailTemplate = '<div class="distEmail"><a href="#" rel="{0}">{1}</a></div>';
        var ret = '';
        if (Email != '')
            ret += String.format(emailTemplate, Email, SEND_TO_UI_LABEL + ' ' + SALES_UI_LABEL);
        if (Email2 != '')
            ret += String.format(emailTemplate, Email2, SEND_TO_UI_LABEL + ' ' + MARKETING_UI_LABEL);
        if (Email3 != '')
            ret += String.format(emailTemplate, Email3, SEND_TO_UI_LABEL + ' ' + TECHNICAL_UI_LABEL);
        if (website)
            ret += String.format(emailTemplate, website, website);
        return ret;
    }
}

//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);
}

function SetGeo() {
    Distributers.geocoder = new GClientGeocoder();
}

function setLocationString() {
    locationString = $$(".zipCode")[0].value;

    Distributers.geocoder.getLocations(locationString, function(response) {
        if (!response || response.Status.code != 200) {
            alert("Sorry, we were unable to geocode the first address");
        }
        else {
            locationString = { lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address };
            Distributers.ShowDistributers(null, "0", "");
            // Distributers[i].location2 = { lat: Distributers[i].Latitude, lon: Distributers[i].Longitude };
            //Distributers.calculateDistance();
        }
    });
    
}

