﻿
//Initialize component
$().ready(function() {
    BranchLocator.init();
});

//BranchSearchCriteria object
function BranchSearchCriteria(division, country, province, city, zipcode, distance) {
    this.AdeccoDivision = (division ? division : "");
    this.Address = {
        Address1: "",
        Address2: "",
        PostalOrZipCode: (zipcode ? zipcode : ""),
        City: (city ? city : ""),
        ProvinceOrState: (province ? province : ""),
        Country: (country ? country : ""),
        Telephone: "",
        Fax: "",
        Email: "",
        Location: {
            Latitude: 0.0,
            Longitude: 0.0
        }
    };
    this.Radius = (distance ? parseFloat(distance) : BranchLocatorConfiguration.Properties.DefaultDistance);
    this.DistanceType = BranchLocatorConfiguration.Properties.UseMilesOrKMs;
    this.MinResults = BranchLocatorConfiguration.Properties.NumberOfItems;
    this.SiteCollectionUrl = BranchLocatorConfiguration.Properties.SiteCollectionUrl;
    this.getPermalink = function() {
        var array = [];
        //Calculate parameters
        if (this.AdeccoDivision) array.push("division=" + escape(this.AdeccoDivision));
        if (this.Address.Country) array.push("country=" + escape(this.Address.Country));
        if (this.Address.ProvinceOrState) array.push("province=" + escape(this.Address.ProvinceOrState));
        if (this.Address.City) array.push("city=" + escape(this.Address.City));
        if (this.Address.PostalOrZipCode) array.push("zipcode=" + escape(this.Address.PostalOrZipCode));
        if (this.Radius != BranchLocatorConfiguration.Properties.DefaultDistance) array.push("distance=" + escape(this.Radius));
        //TO DO: what if no filters?
        //Contruct the permalink
        var permalink = location.protocol + "//" + location.host;
        permalink += location.pathname + "?" + array.join("&");
        return permalink;
    };
    if (!this.Address.City && !this.Address.PostalOrZipCode)
        this.Radius = 0;
}

//BranchLocator class
BranchLocator = {

    searchCriteria: null, //search criteria
    address: "", //searched address
    branches: [], //Array to store branches client cache
    markers: [], //Array to store branches markers
    resultBranchesList: null, //Branches for last search
    position: null, //searched location
    map: null, //GoogleMap canvas
    geocoder: null, //Client Geocoder object to get latitude and longitude for an address
    markerManager: null, //Client object to manage all branches markers
    branchIcon: null, //Icon for Adecco map marker
    provinceIcon: null, //Icon for province group
    countryIcon: null, //Icon for country group
    searchIcon: null, //Icon for search location
    clipboard: null, clipboard2: null, //ZeroClipboard objects
    typePanel: { None: 0, Loading: 1, Search: 2, Results: 3, Detail: 4 },
    template: "", //Store template html for branch results
    templateInfo: "", //Store template html for branch info window
    templateBranchesInfo: "", //Store template html for branches with the same address //VLF
    templateProvince: "", //Store template html for province info window
    templateCountry: "", //Store template html for country info window
    templateContact: "", //Store template html for contacts

    //initialize the component
    init: function() {

        if (typeof GBrowserIsCompatible == "undefined") {
            BranchLocator.showPanel(BranchLocator.typePanel.None, BranchLocatorConfiguration.Messages.MessageGoogleMapsScriptNotLoaded);
        } else if (GBrowserIsCompatible()) {
            //Read templates
            BranchLocator.template = $("#pnlBLBranchTemplate").html();
            BranchLocator.templateInfo = $("#pnlBLInfoWindowTemplate").html();
            BranchLocator.templateBranchesInfo = $("#pnlBLInfoBranchesWindowTemplate").html(); //VLF
            BranchLocator.templateProvince = $("#pnlBLProvinceInfoWindowTemplate").html();
            BranchLocator.templateCountry = $("#pnlBLCountryInfoWindowTemplate").html();
            BranchLocator.templateContact = $("#pnlBLContactTemplate").html();

            //Initialize maps
            BranchLocator.map = new GMap2(document.getElementById("pnlBLMap"), { size: new GSize(540, 450) });
            //BranchLocator.map.addControl(new GSmallMapControl());
            BranchLocator.map.addControl(new GLargeMapControl());
            BranchLocator.map.addControl(new GMapTypeControl(true));
            BranchLocator.map.setCenter(new GLatLng(0, 0), 15);

            BranchLocator.geocoder = new GClientGeocoder();
            BranchLocator.branchIcon = BranchLocator.getIcon(BranchLocatorConfiguration.Properties.BranchMarkerImage);
            BranchLocator.provinceIcon = BranchLocator.getIcon(BranchLocatorConfiguration.Properties.ProvinceMarkerImage);
            BranchLocator.countryIcon = BranchLocator.getIcon(BranchLocatorConfiguration.Properties.CountryMarkerImage);
            BranchLocator.searchIcon = BranchLocator.getIcon(BranchLocatorConfiguration.Properties.SearchMarkerImage);
            BranchLocator.markerManager = new MarkerManager(BranchLocator.map);
            setTimeout("BranchLocator.loadMarkers();", 50);

            //Fill combos
            BranchLocator.fillCombos();
            //$("#txtBLDistance").val(BranchLocatorConfiguration.Properties.DefaultDistance);
            //BranchLocator.updateControlsEnabled(); //Disable text controls

            //If Permalink is allowed
            if (BranchLocatorConfiguration.Properties.EnablePermalink == "True") {
                $("#lnkBLPermalink").show();
                $("#lnkBLPermalink2").show();
                //Init clipboard
                ZeroClipboard.setMoviePath("/_controltemplates/BranchLocator/js/ZeroClipboard.swf");
            } else {
                $("#lnkBLPermalink").hide();
                $("#lnkBLPermalink2").hide();
            }

            //Init BlockUI
            $.blockUI.defaults.css = { position: 'absolute', width: 'auto', top: 'auto', left: '40%',
                color: '#000', border: '1px', backgroundColor: 'transparent'
            };
            $.blockUI.defaults.overlayCSS = { backgroundColor: '#000', opacity: '0.3' };
            $.blockUI.defaults.message = "";

            //Initialize event handlers
            BranchLocator.setEventHandlers();

            //Check params and show right panel
            BranchLocator.readParameters();
            if (BranchLocator.searchCriteria != null) {
                BranchLocator.searchBranches();
            } else {
                BranchLocator.showPanel(BranchLocator.typePanel.Search);
            }
        } else {
            BranchLocator.showPanel(BranchLocator.typePanel.None, BranchLocatorConfiguration.Messages.MessageBrowserNotCompatibleGoogleMaps);
        }
    },

    getIcon: function(iconPath) {
        var result = "none";
        if (iconPath != "none")
            result = new GIcon(G_DEFAULT_ICON, iconPath);
        return result;
    },

    getPosition: function(latitude, longitude) {
        latitude = latitude.toString().replace(/,/g, '.');
        longitude = longitude.toString().replace(/,/g, '.');
        return new GLatLng(latitude, longitude); //Latitude and longitude
    },

    loadMarkers: function() {
        var res = Adecco.SharePoint.Branches.WebServices.WSBranches.GetBranchMarkers(
                        BranchLocatorConfiguration.Properties.SiteCollectionUrl,
                        BranchLocatorConfiguration.Properties.BranchesListName,
                        BranchLocatorConfiguration.Properties.ProvincesListName,
                        BranchLocatorConfiguration.Properties.CountriesListName);
        if (res && !res.error && res.value) {
            //Add markers for branches
            var markers = [];
            if (BranchLocator.branchIcon != "none") {
                for (var i = 0; i < res.value.Branches.length; i++)
                    markers.push(BranchLocator.createBranchMarker(res.value.Branches[i]));
                BranchLocator.markerManager.addMarkers(markers, 5);
            }
            //Add markers for provinces
            if (BranchLocator.provinceIcon != "none") {
                markers = [];
                for (var i = 0; i < res.value.Provinces.length; i++)
                    markers.push(BranchLocator.createGroupMarker(BranchLocator.provinceIcon, res.value.Provinces[i], BranchLocator.templateProvince));
                BranchLocator.markerManager.addMarkers(markers, 3, 4); //MinZoom=1, maxZoom=6
            }
            //Add markers for countries
            if (BranchLocator.countryIcon != "none") {
                markers = [];
                for (var i = 0; i < res.value.Countries.length; i++)
                    markers.push(BranchLocator.createGroupMarker(BranchLocator.countryIcon, res.value.Countries[i], BranchLocator.templateCountry));
                BranchLocator.markerManager.addMarkers(markers, 0, 2); //MinZoom=1, maxZoom=6
            }
        }
    },

    createBranchMarker: function(branchData) {
        var pos = BranchLocator.getPosition(branchData[1], branchData[2]); //Latitude and longitude
        var marker = new GMarker(pos, BranchLocator.branchIcon);
        marker.branchId = branchData[0];
        BranchLocator.markers[marker.branchId] = marker;
        GEvent.addListener(marker, "click", function() {
            BranchLocator.openBranchInfoWindow(marker.branchId, marker);
        });
        return marker;
    },

    createGroupMarker: function(icon, data, template) {
        var pos = BranchLocator.getPosition(data[1], data[2]); //Latitude and longitude
        var marker = new GMarker(pos, icon);
        marker.htmlInfo = template.replace(/{Name}/g, data[0]).replace(/{Count}/g, data[3]);
        GEvent.addListener(marker, "mouseover", function() {
            BranchLocator.openGroupInfoWindow(marker);
        });
        GEvent.addListener(marker, "mouseout", function() {
            BranchLocator.map.closeInfoWindow();
        });
        return marker;
    },

    openBranchInfoWindow: function(branchId, marker) {
        var branch = BranchLocator.branches[branchId];
        if (!marker) marker = BranchLocator.markers[branchId];
        if (!branch) {
            var res = Adecco.SharePoint.Branches.WebServices.WSBranches.GetBranchesById(BranchLocatorConfiguration.Properties.SiteCollectionUrl, BranchLocatorConfiguration.Properties.BranchesListName, branchId);
            if (res && !res.error && res.value) {
                if (res.value.length > 0) {
                    branch = BranchLocator.fillBranchInfo(res.value[0]);
                }
            }
        }

        if (branch && branch.htmlBranchesInfo && marker)
            marker.openInfoWindowHtml(branch.htmlBranchesInfo);
        else if (branch && branch.htmlInfo && marker)
            marker.openInfoWindowHtml(branch.htmlInfo);
    },

    openGroupInfoWindow: function(marker) {
        if (marker.htmlInfo)
            marker.openInfoWindowHtml(marker.htmlInfo);
    },

    fillCombos: function() {

        //Fill combo Divisions
        var selectDivision = $('#selBLAdeccoDivision');
        var allDivision = $('<option value="">' + BranchLocatorConfiguration.Labels.AllComboDivision + '</option>');
        selectDivision.append(allDivision); //Add first option
        var res = Adecco.SharePoint.Branches.WebServices.WSBranches.GetDivisions(BranchLocatorConfiguration.Properties.SiteCollectionUrl, BranchLocatorConfiguration.Properties.DivisionsListName);
        if (res && !res.error && res.value) {
            $.each(res.value, function(key, value) {
                selectDivision.append($("<option></option>").attr("value", value.Name).text(value.Name));
            });
        }

        //Select default Adecco Division
        $('#selBLAdeccoDivision').val(BranchLocatorConfiguration.Labels.AllComboDivision);
        //selectDivision.val(selectDivision.children(":eq(1)").val()); //Select first option after All

        //Fill combo Country
        var allCountry = $('<option value="">' + BranchLocatorConfiguration.Labels.AllComboCountry + '</option>');
        $('#selBLCountry').append(allCountry); //Add first option
        var res = Adecco.SharePoint.Branches.WebServices.WSBranches.GetCountries(BranchLocatorConfiguration.Properties.SiteCollectionUrl, BranchLocatorConfiguration.Properties.CountriesListName);
        if (res && !res.error && res.value) {
            $.each(res.value, function(key, value)
            { $('#selBLCountry').append($("<option></option>").attr("value", value.Name).text(value.Name)); });
        }

        //Select default country
        $('#selBLCountry').val(BranchLocatorConfiguration.Labels.DefaultCountry);

        //Fill combo Province
        BranchLocator.fillStateProvince(BranchLocatorConfiguration.Labels.DefaultCountry);
    },


    fillStateProvince: function(country) {
        $('#selBLStateProvince').empty();

        var allProvince = $('<option value="">' + BranchLocatorConfiguration.Labels.AllComboProvince + '</option>');
        $('#selBLStateProvince').append(allProvince); //Add first option

        //Fill combo State/Province
        if (country == BranchLocatorConfiguration.Labels.AllComboCountry)
            country = "";
        var res = Adecco.SharePoint.Branches.WebServices.WSBranches.GetProvinceListForCountry(country, BranchLocatorConfiguration.Properties.SiteCollectionUrl, BranchLocatorConfiguration.Properties.ProvincesListName);
        if (res && !res.error && res.value) {
            $.each(res.value, function(key, value)
            { $('#selBLStateProvince').append($("<option></option>").attr("value", value.Name).text(value.Name)); });
        }

        //Select default province
        $('#selBLStateProvince').val(BranchLocatorConfiguration.Labels.AllComboProvince);
    },

    setEventHandlers: function() {
        $("#btnBLClearSearch").unbind().click(BranchLocator.onClickCancel);
        $("#btnBLSearch").unbind().click(BranchLocator.onClickSearch);
        $("#selBLAdeccoDivision").unbind().keydown(BranchLocator.onKeyDown);
        $("#selBLCountry").unbind().keydown(BranchLocator.onKeyDown);
        $("#selBLStateProvince").unbind().keydown(BranchLocator.onKeyDown);
        $("#txtBLCity").unbind().keydown(BranchLocator.onKeyDown);
        $("#txtBLZipCode").unbind().keydown(BranchLocator.onKeyDown);
        $("#txtBLDistance").unbind().keydown(BranchLocator.onKeyDown);
        $("#lnkBLNewSearch").unbind().click(BranchLocator.onClickNewSearch);
        $("#lnkBLNewSearch2").unbind().click(BranchLocator.onClickNewSearch);
        //$("#lnkBLPermalink").unbind().click(BranchLocator.onClickPermalink);
        //$("#lnkBLPermalink2").unbind().click(BranchLocator.onClickPermalink);
        $("#selBLCountry").unbind().change(BranchLocator.onChangeCountry);
        $("#selBLStateProvince").unbind().change(BranchLocator.onChangeProvince);
        $("#lnkBranchPicture").unbind().click(BranchLocator.onClickBranchPicture);
        $("#btnBLClose").unbind().click(BranchLocator.onClickClose);
        $(window).unload(GUnload); //Unload handler: this reduces memory leaks in IE
        $(window).unload(BranchLocator.onUnload); //Unload handler for BranchLocator
    },

    showPanel: function(type, message) {
        //Show / hide loading panel
        if (type == BranchLocator.typePanel.Loading) // 1
            $("#msgBLLoading").show();
        else
            $("#msgBLLoading").hide();
        //Show / hide search panel
        if (type == BranchLocator.typePanel.Search) {// 2
            $("#pnlBLSearchBox").show();
            $("#txtBLCity").focus();
        } else
            $("#pnlBLSearchBox").hide();
        //Show / hide results panel
        if (type == BranchLocator.typePanel.Results) {//3
            $("#pnlBLResults").show();
            //Show flash movies for ZeroClipboard
            if (BranchLocator.clipboard) {
                BranchLocator.clipboard.show();
                BranchLocator.clipboard2.show();
            }
        } else {
            $("#pnlBLResults").hide();
            //Hide flash movies for ZeroClipboard
            if (BranchLocator.clipboard) {
                BranchLocator.clipboard.hide();
                BranchLocator.clipboard2.hide();
            }
        }
        //Show message if it exists
        if (message) {
            $("#msgBLError").html(message);
            $("#msgBLError").show();
        } else
            $("#msgBLError").hide();
    },

    onUnload: function() {
        //Clear handlers
        $("#btnBLClearSearch").unbind();
        $("#btnBLSearch").unbind();
        $("#selBLAdeccoDivision").unbind();
        $("#selBLCountry").unbind();
        $("#selBLStateProvince").unbind();
        $("#txtBLCity").unbind();
        $("#txtBLZipCode").unbind();
        $("#txtBLDistance").unbind();
        $("#lnkBLNewSearch").unbind();
        $("#lnkBLNewSearch2").unbind();
        $("#lnkBLPermalink").unbind();
        $("#lnkBLPermalink2").unbind();
        $("#lnkBranchPicture").unbind();
        $("#btnBLClose").unbind();
        //Clear properties
        BranchLocator.position = null;
        BranchLocator.address = null;
        BranchLocator.searchCriteria = null;
        BranchLocator.map = null;
        BranchLocator.geocoder = null;
        BranchLocator.icon = null;
        BranchLocator.template = null;
        BranchLocator.templateInfo = null;
        BranchLocator.templateBranchesInfo = null; //VLF
        BranchLocator.templateContact = null;
        //Destroy clipboard objects (flash objects)
        if (BranchLocator.clipboard) {
            BranchLocator.clipboard.destroy();
            BranchLocator.clipboard2.destroy();
        }
    },

    onKeyDown: function(e) {
        if (e.which == 13) {//If enter key is pressed
            $("#btnBLSearch").click();
            return false;
        }
    },

    onClickCancel: function() {
        $("#selBLAdeccoDivision").val(BranchLocatorConfiguration.Properties.DefaultAdeccoDivision);
        $("#selBLCountry").val(BranchLocatorConfiguration.Properties.DefaultCountry);
        $("#selBLStateProvince").val(BranchLocatorConfiguration.Properties.DefaultProvince);
        $("#txtBLCity").val("");
        $("#txtBLZipCode").val("");
        $("#txtBLDistance").val("");
        //BranchLocator.updateControlsEnabled();
        return false;
    },

    onClickSearch: function() {
        var valid = BranchLocator.validateFilters();

        $("#msgBLError").html("");
        $("#msgBLError").hide();

        if (valid) {
            var country = "";
            if ($("#selBLCountry").val() != "") country = $("#selBLCountry").val();
            else country = BranchLocatorConfiguration.Labels.DefaultCountry;

            BranchLocator.searchCriteria = new BranchSearchCriteria($("#selBLAdeccoDivision").val(),
                country, $("#selBLStateProvince").val(), $("#txtBLCity").val(),
                $("#txtBLZipCode").val(), $("#txtBLDistance").val());
            BranchLocator.searchBranches();
        }
        else {
            var message = BranchLocatorConfiguration.Messages.MessageSearchValidation;
            var text = BranchLocatorConfiguration.Labels.AdeccoDivision;
            text = text.split(":")[0];
            message = message.replace("{Division}", text);
            $("#msgBLError").html(message);
            $("#msgBLError").show();
        }
        return false;
    },

    validateFilters: function() {
        var valid = true;

        if (($("#selBLAdeccoDivision").val() == "") && ($("#selBLCountry").val() == "") && ($("#selBLStateProvince").val() == "") && ($("#txtBLCity").val() == "") && ($("#txtBLZipCode").val() == "")) {
            valid = false;
        }
        else {
            valid = true;
        }
        return valid;
    },

    onClickNewSearch: function() {
        $("#selBLAdeccoDivision").val(BranchLocatorConfiguration.Labels.AllComboDivision);
        $("#selBLCountry").val(BranchLocatorConfiguration.Labels.DefaultCountry);
        BranchLocator.fillStateProvince(BranchLocatorConfiguration.Labels.DefaultCountry);
        $("#txtBLCity").val("");
        $("#txtBLZipCode").val("");
        $("#txtBLDistance").val("");
        BranchLocator.initSearch();
        BranchLocator.showPanel(BranchLocator.typePanel.Search);
        return false;
    },

    onChangeCountry: function() {
        BranchLocator.fillStateProvince(this.value);
        return false;
    },

    initSearch: function() {
        //Init map
        BranchLocator.map.clearOverlays();
        BranchLocator.map.closeInfoWindow();
        BranchLocator.map.setCenter(new GLatLng(0, 0), 15); //Vlf
        BranchLocator.position = null;
        BranchLocator.address = "";
        BranchLocator.branches = []; //Clear branch cache
    },

    searchBranches: function() {
        //Show loading...
        BranchLocator.showPanel(BranchLocator.typePanel.Loading);

        //Get address
        BranchLocator.address = BranchLocator.getAddress(BranchLocator.searchCriteria);

        if (BranchLocator.address) {
            //Get Latitude and Longitude using Geocoder
            //TO IMPROVE: Use getLocations (http://econym.org.uk/gmap/example_geo.htm)
            //This is an async call
            BranchLocator.geocoder.getLatLng(BranchLocator.address, function(point) {
                BranchLocator.showBranchesList(point);
            });
        } else {
            //Distance can't be taken into account in the search
            BranchLocator.showBranchesList(null);
        }
        return false;
    },

    getAddress: function(filters) {
        var address = "";

        if (filters.Address.Country != "") {
            if (address != "") address += ", ";
            address += filters.Address.Country;
        }

        if (filters.Address.ProvinceOrState != "") {
            if (address != "") address += ", ";
            address += filters.Address.ProvinceOrState;
        }
        if (filters.Address.City != "") {
            if (address != "") address += ", ";
            address += filters.Address.City;
        }
        if (filters.Address.PostalOrZipCode != "") {
            if (address != "") address += ", ";
            address += filters.Address.PostalOrZipCode;
        }
        return address;
    },

    getAddressWCountry: function(filters) {
        var address = "";

        if (filters.Address.ProvinceOrState != "") {
            if (address != "") address += ", ";
            address += filters.Address.ProvinceOrState;
        }
        if (filters.Address.City != "") {
            if (address != "") address += ", ";
            address += filters.Address.City;
        }
        if (filters.Address.PostalOrZipCode != "") {
            if (address != "") address += ", ";
            address += filters.Address.PostalOrZipCode;
        }
        return address;
    },

    showBranchesList: function(point) {
        if (point) {
            //We have location: do search
            //Save location
            BranchLocator.position = point;

            //Get branches from server
            BranchLocator.searchCriteria.Address.Location.Latitude = point.y;
            BranchLocator.searchCriteria.Address.Location.Longitude = point.x;
        }

        //Retrieve Branches List from server
        var result = Adecco.SharePoint.Branches.WebServices.WSBranches.SearchBranches(BranchLocator.searchCriteria, BranchLocatorConfiguration.Properties.BranchesListName, BranchLocatorConfiguration.Properties.SiteCollectionUrl, BranchLocatorConfiguration.Properties.ContactsListName);

        //Write results
        if (result && !result.error && result.value) {
            var branches = result.value.Results;

            //complete branch info
            var sActual;
            var sAnterior = "";
            var sSiguiente = "";
            for (var i = 0; i < branches.length; i++) {
                branches[i] = BranchLocator.fillBranchInfo(branches[i]);
                sActual = branches[i].Address.Address2;
                if (i > 0) {
                    sAnterior = branches[i - 1].Address.Address2;
                }
                if (i + 1 < branches.length) {
                    sSiguiente = branches[i + 1].Address.Address2;
                }
                if (sAnterior == sActual && sActual != "") //Copio el Template
                {
                    branches[i].htmlBranchesInfo = branches[i - 1].htmlBranchesInfo;
                }
                else { //Verify if Actual = Siguiente create the new template
                    if (sActual == sSiguiente) {
                        var j = i;
                        var texto = "";
                        while (sActual == sSiguiente && j < branches.length) {

                            texto = BranchLocator.fillBranchesInfo(branches[j], texto);
                            j++;
                            if (j < branches.length)
                                sSiguiente = branches[j].Address.Address2;
                        }
                        branches[i].htmlBranchesInfo = BranchLocator.replaceTemplateBranchesTags(texto, BranchLocator.templateBranchesInfo,branches[i]);
                        BranchLocator.branches[branches[i].Id] = branches[i];
                    }
                }
            }

            //Add location marker if Reference Point is set to Visible
            //in WebPart Properties
            if (BranchLocatorConfiguration.Properties.IsReferenceVisible == "True") {
                if (BranchLocator.position && BranchLocator.searchIcon != "none") {
                    var marker = new GMarker(BranchLocator.position, BranchLocator.searchIcon);
                    BranchLocator.map.addOverlay(marker);
                }
            }
            if (BranchLocatorConfiguration.Properties.RadiusEnabled == "True" && BranchLocator.searchCriteria.Radius > 0 && BranchLocator.position) {
                var circle = BranchLocator.createCircle(BranchLocator.position, BranchLocator.searchCriteria.Radius);
                BranchLocator.map.addOverlay(circle);
            }

            //Write branch results
            var result = "";
            for (var i = 0; i < branches.length; i++) {
                result += branches[i].html; //Add html to results panel
            }
            $("#pnlBLBranches").html(result); //Write results

            //Write number of branches
            BranchLocator.showNumberOfBranchesMessage(branches.length);

            //Set map center and zoom level        
            BranchLocator.resultBranchesList = branches;
            setTimeout("BranchLocator.setZoom(BranchLocator.resultBranchesList);", 50);

            //Set clipboard text
            if (BranchLocatorConfiguration.Properties.EnablePermalink == "True") {
                window.setTimeout("BranchLocator.setClipboardText();", 100);
            }

            //Show results panel with map
            BranchLocator.showPanel(BranchLocator.typePanel.Results);
        } else {
            //Error: show search box again (and message)
            BranchLocator.showPanel(BranchLocator.typePanel.Search, BranchLocatorConfiguration.Messages.MessageErrorGettingBranches);
        }
    },

    fillBranchesInfo: function(branch, texto) {
        texto = texto + "<p class=\"item\">" + branch.Name + " - " + branch.Address.Address2 + "</p>";
        return texto;
    },

    replaceTemplateBranchesTags: function(texto, template, branch) {
        var html = unescape(template);
        var sURL = window.location.href;
        var sCriteria;
        var getDirectionsAddress = "";
        if (sURL.toUpperCase().search("/DIS") != -1) {
            sCriteria = "DIS AG";
        }
        else {
            sCriteria = "EE AG";
        }

        html = html.replace(/{SiteName}/g, sCriteria);

        var sCriteriaAddress;
        var array = [];
        if (BranchLocator.searchCriteria.AdeccoDivision)
            array.push(BranchLocator.searchCriteria.AdeccoDivision);
        if (BranchLocator.searchCriteria.Address.ProvinceOrState != "" || BranchLocator.searchCriteria.Address.City != "" || BranchLocator.searchCriteria.Address.PostalOrZipCode != "") {
            var sAddress = BranchLocator.getAddressWCountry(BranchLocator.searchCriteria);
            array.push(sAddress);
        }
        if (BranchLocator.searchCriteria.Radius > 0)
            array.push(BranchLocator.searchCriteria.Radius + " " + BranchLocatorConfiguration.Labels.DistanceTypeName);
        sCriteriaAddress = array.join(" / ");
        sCriteriaAddress = sCriteriaAddress.replace(/,/g, " / ");

        html = html.replace(/{Criteria}/g, sCriteriaAddress);
        html = html.replace(/{Branches}/g, texto);

        getDirectionsAddress = "<div class='WebLink GetDirections'><a href='http://maps.google.com?daddr=" + branch.Address.Address2 + ", " + branch.Address.PostalOrZipCode + " " + branch.Address.City + ", " + branch.Address.ProvinceOrState + ", " + branch.Address.Country + "' class='linkClear' target='_blank'>" + BranchLocatorConfiguration.Labels.GetDirection + "</a></div>"
        html = html.replace(/{GetDirections}/g, getDirectionsAddress);

        html = html.replace(/{GetDirections}/g, "GetDirections");

        html = html.replace("<p></p>", ""); //Remove empty paragraphs from template
        html = html.replace("<div></div>", ""); //Remove empty paragraphs from template

        return html;
    },

    setZoom: function(branches) {
        var bounds = new GLatLngBounds();
        var iCount = 0;
        //Add search location
        if (BranchLocatorConfiguration.Properties.IsReferenceVisible == "True") {
            if (BranchLocator.position)
                bounds.extend(BranchLocator.position);
        }

        //Add branches location
        for (var i = 0; i < branches.length; i++) {
            var branch = branches[i];
            bounds.extend(branch.position);
            iCount++;
        }
        //Set center and zoom level
        var zoom = BranchLocator.map.getBoundsZoomLevel(bounds);
        if (zoom > 15) zoom = 15; //Maximum zoom by default is 15 (user can manually increase zoom)
        if (iCount == 1)
            BranchLocator.map.setCenter(branches[0].position, zoom);
        else
            BranchLocator.map.setCenter(bounds.getCenter(), zoom);
    },

    readParameters: function() {
        var params = BranchLocator.getParams();
        if (params["division"] || params["country"] || params["province"] || params["city"] || params["zipcode"] || params["distance"]) {
            if (params["country"] == "" || params["country"] == undefined) params["country"] = BranchLocatorConfiguration.Labels.DefaultCountry;
            BranchLocator.searchCriteria = new BranchSearchCriteria(params["division"], params["country"],
                params["province"], params["city"], params["zipcode"], params["distance"]);

            $("#selBLAdeccoDivision").val(params["division"]);
            $("#selBLCountry").val(params["country"]);
            $("#selBLStateProvince").val(params["province"]);
            $("#txtBLCity").val(params["city"]);
            $("#txtBLZipCode").val(params["zipcode"]);
            $("#txtBLDistance").val(params["distance"]);
        }
    },

    getParams: function() {
        var query = window.location.search.substring(1).toLowerCase();
        var vars = query.split("&");
        var params = [];
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            params[pair[0]] = unescape(pair[1]);
        }
        return params;
    },

    fillBranchInfo: function(branch) {
        if (!BranchLocator.branches[branch.Id]) {
            //replace tags in template by values            
            branch.html = BranchLocator.replaceTemplateTags(branch, BranchLocator.template);
            branch.htmlInfo = BranchLocator.replaceTemplateTags(branch, BranchLocator.templateInfo);
            //Save the branch position
            branch.position = BranchLocator.getPosition(branch.Address.Location.Latitude, branch.Address.Location.Longitude);
            //Save branch to cache            
            BranchLocator.branches[branch.Id] = branch;
        } else { //Branch already in cache, return it
            branch = BranchLocator.branches[branch.Id];
        }
        return branch;
    },

    setClipboardText: function() {
        //Remove previous flash objects
        if (BranchLocator.clipboard) BranchLocator.clipboard.destroy();
        if (BranchLocator.clipboard2) BranchLocator.clipboard2.destroy();

        //Get text to copy
        var text = BranchLocator.searchCriteria.getPermalink();

        //First clipboard object
        var clip = new ZeroClipboard.Client();
        clip.setHandCursor(true);
        clip.glue('lnkBLPermalink', 'permalinkContainer');
        //clip.addEventListener('load', function() { alert("Loaded."); });
        //clip.addEventListener('complete', function() { alert("Copied."); });
        clip.setText(text);
        BranchLocator.clipboard = clip;

        clip = new ZeroClipboard.Client();
        clip.setHandCursor(true);
        clip.glue('lnkBLPermalink2', 'permalinkContainer2');
        //clip.addEventListener('load', function() { alert("Loaded."); });
        //clip.addEventListener('complete', function() { alert("Copied."); });
        clip.setText(text);
        BranchLocator.clipboard2 = clip;
    },

    showNumberOfBranchesMessage: function(count) {
        var message = "";
        var message2 = "";
        var array = [];

        if (count > 0) {
            message = BranchLocatorConfiguration.Messages.MessageBranchesFound.replace("{Count}", count);
            $("#lnkBLNewSearch").show();
            if (BranchLocatorConfiguration.Properties.EnablePermalink == "True")
                $("#lnkBLPermalink").show();
        } else {
            message = BranchLocatorConfiguration.Messages.MessageNoResults;
            $("#lnkBLNewSearch").hide();
            if (BranchLocatorConfiguration.Properties.EnablePermalink == "True")
                $("#lnkBLPermalink").hide();
        }
        $("#msgBLResult").html(message);

        if (BranchLocator.searchCriteria.AdeccoDivision)
            array.push(BranchLocator.searchCriteria.AdeccoDivision);
        if (BranchLocator.address)
            array.push(BranchLocator.address);
        if (BranchLocator.searchCriteria.Radius > 0)
            array.push(BranchLocator.searchCriteria.Radius + " " + BranchLocatorConfiguration.Labels.DistanceTypeName);

        message2 = BranchLocatorConfiguration.Messages.YourSearchCriteria.replace("{Address}", array.join(" / "));
        message2 = message2.replace(/,/g, " / ");
        $("#msgSearchCriteria").html(message2);
    },

    replaceTemplateTags: function(branch, template) {
        var html = unescape(template);
        var picture = "";
        var phone = "";
        var getDirectionsAddress = "";
        var webAddress = "";
 		var job = "";

        html = html.replace(/{BranchName}/g, branch.Name + " ");
        html = html.replace(/{Division}/g, branch.Division);
        html = html.replace(/{Address1}/g, branch.Address.Address1);
        html = html.replace(/{Address2}/g, branch.Address.Address2);
        html = html.replace(/{City}/g, branch.Address.City);
        html = html.replace(/{PostCode}/g, branch.Address.PostalOrZipCode);
        html = html.replace(/{ProvinceOrState}/g, branch.Address.ProvinceOrState);
        html = html.replace(/{Country}/g, branch.Address.Country);
        html = html.replace(/{BranchId}/g, branch.Id);
        html = html.replace(/{ExternalId}/g, branch.ExternalId);

        getDirectionsAddress = "<div class='WebLink GetDirections'><a href='http://maps.google.com?daddr=" + branch.Address.Address2 + ", " + branch.Address.PostalOrZipCode + " " + branch.Address.City + ", " + branch.Address.ProvinceOrState + ", " + branch.Address.Country + "' class='linkClear' target='_blank'>" + BranchLocatorConfiguration.Labels.GetDirection + "</a></div>"
        html = html.replace(/{GetDirections}/g, getDirectionsAddress);

        html = html.replace(/{GetDirections}/g, "GetDirections");

        if (branch.Address.Telephone) {
            phone = BranchLocatorConfiguration.Labels.PhoneName + " <a href='skype:" + branch.Address.Telephone + "?call' onclick='return skypeCheck();' title='Call with Skype'>" + branch.Address.Telephone + "</a>";
            html = html.replace(/{Phone}/g, phone);
        } else {
            html = html.replace(/{Phone}/g, "");
        }

        if (branch.Address.Fax) {
            html = html.replace(/{FaxName}/g, BranchLocatorConfiguration.Labels.FaxName);
            html = html.replace(/{Fax}/g, branch.Address.Fax);
        } else {
            html = html.replace(/{FaxName}/g, "");
            html = html.replace(/{Fax}/g, "");
        }

        if (branch.Distance > 0) {
            html = html.replace(/{Distance}/g, "(" + branch.Distance.toFixed(2));
            html = html.replace(/{DistanceType}/g, BranchLocatorConfiguration.Labels.DistanceTypeName + ")");
        }
        else {
            html = html.replace(/{Distance}/g, "");
            html = html.replace(/{DistanceType}/g, "");
        }

        if (branch.WebAddress) {
            webAddress = "<div class='WebLink WebAddress'><a href='" + branch.WebAddress + "' class='linkClear' target='_blank'>" + branch.WebAddress + "</a></div>";
            if (branch.WebAddress.split("http").length > 1)
                html = html.replace(/{WebAddress}/g, webAddress);
            else
                html = html.replace(/{WebAddress}/g, "http://" + webAddress);
        }
        else {
            html = html.replace(/{WebAddress}/g, "");
        }
        
        if (branch.Job) {

            job = "<div class='WebLink Job'><a href='" + branch.Job + "' >" + BranchLocatorConfiguration.Labels.Job + "</a></div>";
            if (branch.Job.split("http").length > 1)
                html = html.replace(/{Job}/g, job);
            else
                html = html.replace(/{Job}/g, "http://" + job);
        }
        else {
            html = html.replace(/{Job}/g, "");
        }
        html = html.replace("<p></p>", ""); //Remove empty paragraphs from template
        html = html.replace("<div></div>", ""); //Remove empty paragraphs from template

        //Display or remove links
        var item = $(html).parent();
        var pictureNode = item.find('.PictureLink');
        //var webNode = item.find('.WebAddress');
        var mailNode = item.find('.EmailBranch');
        var contactsNode = item.find('.divContacts');
        
        if (branch.Picture) {
            if (pictureNode.length > 0) {
                pictureNode.html(pictureNode.html().replace(/{Picture}/g, branch.Picture));
            }
            else {
                pictureNode = item.find('.BLInfoRight');
                if (pictureNode.length > 0) {
                    picture = "<img src='" + branch.Picture + "'/>";
                    pictureNode.html(pictureNode.html().replace(/{Picture}/g, picture));
                }
                else  //Remove node
                {
                    pictureNode.remove();
                    item.find('.BLInfoLeft').removeClass('BLInfoLeft').addClass('BLInfoFull');
                }
            }
        } else {
            if (pictureNode.length > 0) {
                pictureNode.remove();
            } else {
                item.find('.BLInfoRight').remove();
                item.find('.BLInfoLeft').removeClass('BLInfoLeft').addClass('BLInfoFull');
            }
        }

        /*if (branch.WebAddress) {
        if (webNode.length > 0) {
        webNode.html(webNode.html().replace(/{WebAddress}/g, webAddress));
        }
        } else { //Remove node
        $(item).find('.WebAddress').remove();
        }*/

        if (mailNode.length > 0) {
            if (branch.Address.Email) {
                var email;
                email = "<p class='item'>" + BranchLocatorConfiguration.Labels.EmailName + "<a href='MailTo:" + branch.Address.Email + "'>" + branch.Address.Email + "</a></p>";
                mailNode.html(mailNode.html().replace(/{Email}/g, email));
            }
            else {
                mailNode.remove();
            }
        }

        if (contactsNode.length > 0) {
            if (branch.HasContacts) {
                contactsNode.html(contactsNode.html().replace(/{ShowHideContacts}/g, BranchLocatorConfiguration.Labels.ShowHideContacts));
            } else {
                contactsNode.remove();
            }
        }

        return item.html();
    },

    replaceContactsTemplateTags: function(contact, contact2, template) {
        var html = unescape(template);
        var picture = "";
        var email = "";
        var phone = "";

        html = html.replace(/{Name}/g, contact.Name);
        html = html.replace(/{Category}/g, contact.Category);
        if (contact.Phone) {
            phone = BranchLocatorConfiguration.Labels.PhoneName + "<a href='skype:" + contact.Phone + "?call' onclick='return skypeCheck();' title='Call with Skype'>" + contact.Phone + "</a>";
            html = html.replace(/{Telephone}/g, phone);
        }
        else {
            html = html.replace(/{Telephone}/g, "");
        }

        if (contact.Fax) {
            html = html.replace(/{FaxName}/g, BranchLocatorConfiguration.Labels.FaxName);
            html = html.replace(/{Fax}/g, contact.Fax);
        }
        else {
            html = html.replace(/{FaxName}/g, "");
            html = html.replace(/{Fax}/g, "");
        }

        if (contact2 != null) {

            html = html.replace(/{Category2}/g, contact2.Category);
            html = html.replace(/{Name2}/g, contact2.Name);

            if (contact2.Phone) {
                phone = BranchLocatorConfiguration.Labels.PhoneName + "<a href='skype:" + contact2.Phone + "?call' onclick='return skypeCheck();' title='Call with Skype'>" + contact2.Phone + "</a>";
                html = html.replace(/{Telephone2}/g, phone);
            }
            else {
                html = html.replace(/{Telephone2}/g, "");
            }

            if (contact2.Fax) {
                html = html.replace(/{FaxName2}/g, BranchLocatorConfiguration.Labels.FaxName);
                html = html.replace(/{Fax2}/g, contact2.Fax);
            }
            else {
                html = html.replace(/{FaxName2}/g, "");
                html = html.replace(/{Fax2}/g, "");
            }

        }

        html = html.replace("<p></p>", ""); //Remove empty paragraphs from template
        html = html.replace("<div></div>", ""); //Remove empty paragraphs from template

        //Display or remove links
        var item = $(html).parent();
        var pictureNode = item.find('.Picture');
        var mailNode = item.find('.Email');

        if (contact.Picture) {
            picture = '<img src="' + contact.Picture + '" alt="Contact image" />';
            pictureNode.html(pictureNode.html().replace(/{Picture}/g, picture));
        }
        else
            pictureNode.remove();

        if (contact.Email) {
            email = BranchLocatorConfiguration.Labels.EmailName + "<a href='MailTo:" + contact.Email + "'>" + contact.Email + "</a>";
            mailNode.html(mailNode.html().replace(/{Email}/g, email));
        }
        else {
            mailNode.remove();
        }

        if (contact2 == null) {
            $(item).find('.BLColumnContact2Data').remove();
        }
        else {

            //Display or remove links
            var mailNode = item.find('.Email2');

            if (contact2.Email) {
                email = BranchLocatorConfiguration.Labels.EmailName + "<a href='MailTo:" + contact2.Email + "'>" + contact2.Email + "</a>";
                mailNode.html(mailNode.html().replace(/{Email2}/g, email));
            }
            else {
                mailNode.remove();
            }
        }

        return item.html();
    },

    showContacts: function(branchId) {
        var panelContacts = $("#pnlContacts" + branchId);
        if (panelContacts.is(":visible")) {
            panelContacts.hide();
        } else {
            if (panelContacts.html() == "") {
                var result = Adecco.SharePoint.Branches.WebServices.WSBranches.GetContactFromBranch("" + branchId, BranchLocatorConfiguration.Properties.SiteCollectionUrl, BranchLocatorConfiguration.Properties.ContactsListName);
                if (result && !result.error && result.value) {
                    var html = "";
                    var contacts = result.value;
                    for (i = 0; i < contacts.length; i++) {
                        if (contacts[i].Picture)
                            html += BranchLocator.replaceContactsTemplateTags(contacts[i], null, BranchLocator.templateContact);
                        else {
                            if (BranchLocatorConfiguration.Properties.DefaultContactPicture) {
                                contacts[i].Picture = BranchLocatorConfiguration.Properties.DefaultContactPicture;
                                html += BranchLocator.replaceContactsTemplateTags(contacts[i], null, BranchLocator.templateContact);
                            }
                            else {
                                var contact1;
                                var contact2;

                                i++;
                                if (i < contacts.length) {
                                    contact1 = contacts[i - 1];
                                    contact2 = contacts[i];
                                    html += BranchLocator.replaceContactsTemplateTags(contact1, contact2, BranchLocator.templateContact);
                                } else {
                                    contact1 = contacts[i - 1];
                                    html += BranchLocator.replaceContactsTemplateTags(contact1, null, BranchLocator.templateContact);
                                }
                            }
                        }
                    }
                    panelContacts.html(html);
                }
            }
            panelContacts.show();
        }
    },

    onClickBranchPicture: function(branchPictureURL) {
        $("#imgBranchPicture").attr("src", branchPictureURL);
        $.blockUI({ message: $("#divBranchPicture") });
        return false;
    },

    onClickClose: function() {
        $.unblockUI();
        return false;
    },

    numbersOnly: function(e) {
        var unicode = e.charCode ? e.charCode : e.keyCode;
        if (unicode != 8) { //if the key isn't the backspace key (which we should allow)
            if (unicode < 48 || unicode > 57) //if not a number
                return false; //disable key press
        }
    },

    createCircle: function(pointLng, circleRadius, use_miles) {

        var strokeColor = BranchLocatorConfiguration.Properties.StrokeColor;
        var strokeWidth = BranchLocatorConfiguration.Properties.StrokeWidth;
        var strokeOpacity = BranchLocatorConfiguration.Properties.StrokeOpacity;
        var fillColor = BranchLocatorConfiguration.Properties.FillColor;
        var fillOpacity = BranchLocatorConfiguration.Properties.FillOpacity;

        var lat = pointLng.lat();
        var lng = pointLng.lng();
        var d2r = Math.PI / 180;   // degrees to radians
        var r2d = 180 / Math.PI;   // radians to degrees
        if (use_miles == null || use_miles == "undefined") use_miles = false;
        var earthsradius = use_miles ? 3963 : 6371;   //3963 for miles; 
        var points = 256;
        var radius = circleRadius; // radius in km

        // find the raidus in lat/lon
        var rlat = (radius / earthsradius) * r2d;
        var rlng = rlat / Math.cos(lat * d2r);
        var circlePoints = new Array();
        for (var i = 0; i < (points + 1); i++) {
            var theta = Math.PI * (i / (points / 2));
            ex = lng + (rlng * Math.cos(theta)); // center a + radius x * cos(theta)
            ey = lat + (rlat * Math.sin(theta)); // center b + radius y * sin(theta)
            circlePoints.push(new GPoint(ex, ey));
        }

        return (new GPolygon(circlePoints,
				strokeColor,
				strokeWidth,
				strokeOpacity,
				fillColor,
				fillOpacity));
    }

};


