﻿var aTimer;
var LocationList = null;
var geoUrl = baseurl + "addons/xparo/storesearch/desktop/geowebservice.aspx";
var googleMap = null;
var googleEventLockTimestamp = 0;
var googleEventLockDuration = 400;

function getUnixTimeStamp() {
    var now = new Date();
    var year = now.getUTCFullYear();
    var month = now.getUTCMonth();
    var day = now.getUTCDate();
    var hour = now.getUTCHours();
    var minute = now.getUTCMinutes();
    var second = now.getUTCSeconds(); 
    var milliseconds = now.getUTCMilliseconds();
    return parseInt(Date.UTC(year, month, day, hour, minute, second, milliseconds));
}

function googleEventLock() {
    var currentTimestamp = getUnixTimeStamp();
    if (currentTimestamp - googleEventLockDuration > googleEventLockTimestamp) {
        return true;
    }
    return false;
}


function loadCities(country, region, preselect) {
    var itemcount = 0;
    jQuery.ajax({ type: "POST",
        contentType: "application/json; charset=utf-8",
        url: baseurl + 'addons/xparo/storesearch/desktop/storesearch.asmx/GetCityCount',
        data: "{'countryCode':'" + country + "','region':'" + region + "'}",
        dataType: "json",
        success: function(msg) {
            jQuery("#CityList").append(jQuery('<option></option>').val("").html(""));
            getCityItems(country, region, msg.d, 250, 0, preselect);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            jQuery('#Results').html(genericerror);
        },
        async: false
    });
}

function getCityItems(country, region, itemcount, packagesize, offset, preselect) {
    jQuery.ajax({ type: "POST",
        contentType: "application/json; charset=utf-8",
        url: baseurl + 'addons/xparo/storesearch/desktop/storesearch.asmx/GetCities',
        data: "{'countryCode':'" + country + "','region':'" + region + "','offset':'" + offset + "','count':'" + packagesize + "'}",
        dataType: "json",
        success: function(msg) {
            jQuery("#CityList").fillSelect(msg.d);
            offset = offset + packagesize;
            if (offset < itemcount) {
                getCityItems(country, region, itemcount, 250, offset);
            }
            jQuery('#CityList').val(preselect);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            jQuery('#Results').html(genericerror);
        }
    });
}

function loadRegions(country, preselect) {
    var itemcount = 0;
    jQuery.ajax({ type: "POST",
        contentType: "application/json; charset=utf-8",
        url: baseurl + 'addons/xparo/storesearch/desktop/storesearch.asmx/GetRegions',
        data: "{'countryCode':'" + country + "'}",
        dataType: "json",
        success: function(msg) {
            jQuery("#RegionList").append(jQuery('<option></option>').val("").html(""));
            jQuery("#RegionList").fillSelect(msg.d);
            jQuery('#RegionList').val(preselect);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            jQuery('#Results').html(genericerror);
        },
        async: false
    });
}


function GetCheckboxValue(element) {
    var enabledAppendix = "_on";
    var imagePath = jQuery(element).attr("src");
    if (imagePath.indexOf(enabledAppendix) != -1) {
        return true;
    } else {
        return false;
    }
}

function SetCheckboxValue(element, on) {
    if (on) {
        jQuery(element).attr("src", "portaldata/1/resources/icons/selected_on.gif");
    } else {
        jQuery(element).attr("src", "portaldata/1/resources/icons/selected_off.gif");
    }
}

function SetFieldValid(element, valid) {
    if (valid) {
        element.css("border-color", "#808080");
    } else {
        element.css("border-color", "#CC0000");
    }
}

function GetResults(pageNumber, presetCity, presetRegion, newStores) {
    jQuery('#message').html('');
    var country = jQuery('#' + IdOfCountryList + ' option:selected').val();
    var zipcode = jQuery('#zipcode').val();

    if (country == "DE" && zipcode != "") {
        //validate zipcode
        var patt1 = new RegExp(/^\d{5}$/);

        if (!patt1.test(zipcode)) {
            SetFieldValid(jQuery('#zipcode'), false);
            jQuery('#message').html(errormessage);
            return;
        } else {
            SetFieldValid(jQuery('#zipcode'), true);
        }
    }
    var city;
    if (presetCity != "") {
        city = presetCity;
    } else {
        city = jQuery('#CityList option:selected').val();
    }

    var region;
    if (presetRegion != "") {
        region = presetRegion;
    } else {
        region = jQuery('#RegionList option:selected').val();
    }

    var stores = GetCheckboxValue(jQuery('#searchStores'));
    var dealers = GetCheckboxValue(jQuery('#searchDealers'));


    if (redirect != '0') {
        window.location = baseurl + "desktopdefault.aspx/tabid-" + redirect
										  + "/cntry-" + country
										  + "/region-" + region
										  + (zipcode != "" ? "/zip-" + zipcode : "")
										  + (city != "" ? "/city-" + encodeURI(city) : "")
										  + "/stores-" + (stores ? "1" : "0")
										  + "/dealer-" + (dealers ? "1" : "0")
										  + "/new-" + (newStores ? "1" : "0")
										  + "/";
    }

    jQuery.ajax({ type: "POST",
        contentType: "application/json; charset=utf-8",
        url: baseurl + 'addons/xparo/storesearch/desktop/storesearch.asmx/GetResults',
        data: "{'country':'" + country
	 				+ "','region':'" + region
					+ "','zipcode':'" + zipcode
					+ "','city':'" + city
					+ "','searchStores':'" + stores
					+ "','searchDealers':'" + dealers
					+ "', 'pageNumber':'" + pageNumber
					+ "', 'pageSize':'" + pageSize
					+ "','moduleId':'" + moduleId
					+ "'," + (newStores ? "'newStores':'true'" : "'newStores':'false'")
					+ "}",
        dataType: "json",
        success: function(msg) {
            /* jQuery("#show_search_area").show(); */
            /* jQuery("#search_stores_form").hide(); */
            LocationList = msg.d.ResultList;
            showResult(msg.d);
            window.location.hash = "googleMapsAnchor";
            showMap();
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            jQuery('#Results').html(genericerror);
        }
    });
}

function showResult(result) {
    jQuery('#Results').html(result.Content);

    jQuery("a[rel^='prettyPhoto']").prettyPhoto({
        animationSpeed: 'normal',
        padding: 40,
        opacity: 0.35,
        showTitle: true,
        allowresize: false,
        counter_separator_label: '/',
        theme: 'light_square',
        callback: function() { }
    });
}


/* ********************************************************************* */

function getCountryCode() {
    switch (languageId) {
        case '5': return 'CN'; break;
        case '9': return 'FR'; break;
        case '16': return 'RU'; break;
        case '25': return 'KR'; break;
        case '14': return 'PL'; break;
        case '22': return 'FI'; break;
        case '24': return 'JP'; break;
    }
    return 'DE'; //Default
}


jQuery(document).ready(function() {
    var country = 'DE';
    var preset;
    jQuery('#zipcodePanel').hide();

    if (redirected != "") {
        preset = redirected.split("|");
        if (preset.length == 7) {
            country = preset[0];
        }
        jQuery('#zipcode').val(preset[1]);

        SetCheckboxValue(jQuery('#searchStores'), (preset[3] == "1"));
        SetCheckboxValue(jQuery('#searchDealers'), (preset[4] == "1"));
    }
    else {
        //preselect country and load cities	 	 
        country = getCountryCode();
    }

    if (enabledCountries.indexOf(country) > -1) jQuery('#zipcodePanel').show();

    jQuery('#' + IdOfCountryList).val(country);
    var selectedCountry = jQuery('#' + IdOfCountryList + ' option:selected').val();

    jQuery("#CityList").clearSelect();
    jQuery("#RegionList").clearSelect();

    if (redirected != "") {
        loadRegions(selectedCountry, preset[6]);
        loadCities(selectedCountry, preset[6], preset[2]);

        GetResults(1, preset[2], preset[6], preset[5] == '1');
    }
    else {
        loadRegions(selectedCountry, "", "");
        loadCities(selectedCountry, "");
    }

    if (jQuery('#RegionList option').length > 1) {
        jQuery('#regionPanel').show();
    }
    else {
        jQuery('#regionPanel').hide();
    }



    //------------------------------------------------
    jQuery('#seachStores').click(function() {
        SearchStores();
    });
    //------------------------------------------------

    jQuery('#SearchNewStoresLink').click(function() {
        GetResults(1, "", "", true);
        return false;
    });

    //------------------------------------------------
    jQuery('#' + IdOfCountryList).change(function() {
        changeCountryList()
        var encodedPlace = encodeURI(jQuery('#' + IdOfCountryList + ' option:selected').val());
        var geoResult = null;
        geoResult = getGeoInformation(encodedPlace);
        if (DisallowedOverviewMaps[encodedPlace] != null && DisallowedOverviewMaps[encodedPlace] == true) {
            jQuery("#googlemaps").hide();
        }
        else {
            jQuery("#googlemaps").show();
        }
        if (geoInformationOk(geoResult) && googleMap != null && typeof (GBrowserIsCompatible) != "undefined " && GBrowserIsCompatible()) {
            var x = geoResult.Placemark[0].Point.coordinates[1];
            var y = geoResult.Placemark[0].Point.coordinates[0];

            googleMap.panTo(new GLatLng(x, y), 4);
        }
    });
    //------------------------------------------------

    jQuery('#RegionList').change(function() {
        jQuery("#CityList").clearSelect();
        var selectedCountry = jQuery('#' + IdOfCountryList + ' option:selected').val();
        var selectedRegion = jQuery('#RegionList option:selected').val();
        loadCities(selectedCountry, selectedRegion, "");
        jQuery('#Results').html('');
    });

    //------------------------------------------------

    jQuery('#CityList').change(function() {
        jQuery('#Results').html('');
    });

    showMap();
});

function SearchStores() {
    GetResults(1, "", "", false);
    //jQuery('#googlemaps').empty();
    return false;
}

function changeCountryList() {
    jQuery('#Results').html('');
    //jQuery('#loadingDiv').show();

    var selectedCountry = jQuery('#' + IdOfCountryList + ' option:selected').val();

    if (enabledCountries.indexOf(selectedCountry) > -1) {
        jQuery('#zipcodePanel').show();
    } else {
        jQuery('#zipcodePanel').hide();
    }

    jQuery("#RegionList").clearSelect();
    loadRegions(selectedCountry, "");

    jQuery("#CityList").clearSelect();
    loadCities(selectedCountry, "", "");

    if (jQuery('#RegionList option').length > 1) {
        jQuery('#regionPanel').show();
    }
    else {
        jQuery('#regionPanel').hide();
    }

    //jQuery('#loadingDiv').hide();
}


//////////////////////////////////////MAPS////////////////////////////////////////////////
function encodeHTML(input) {
    var div = document.createElement('div');
    var text = document.createTextNode(input);
    div.appendChild(text);
    return div.innerHTML;
}

function getGeoInformation(query) {
    var result = null;

    if (query == "DE")
        query = "Germany";
    
    var geoParams = "q=" + query + "&hl=en&sensor=false&output=json&key=" + googleMapsKey;
    var geoResult = null;
    jQuery.ajax({
        type: "GET",
        url: geoUrl + "?" + geoParams,
        dataType: "json",
        success: function(data) {
            result = data;
        },
        async: false
    });
    return result;
}

function geoInformationOk(geoInformationObject) {
    if (geoInformationObject != null && geoInformationObject.Status.code == 200) {
        return true;
    }
    return false;
}



function initialize() {
    if (typeof (GBrowserIsCompatible) != "undefined" && GBrowserIsCompatible()) {

        if (googleMap == null) {
            googleMap = new GMap2(document.getElementById("googlemaps"))
        }
        var map = googleMap;

        //Fill up missing geo informations
        if (LocationList != null && LocationList.length > 0) {
            jQuery.each(LocationList, function() {
                if (this.CoordinateX == 0 && this.CoordinateX == 0) {
                    var encodedPlace = encodeURI(this.Street + ", " + this.ZipCode + " " + this.City + ", " + this.Country);
                    var geoResult = null;
                    geoResult = getGeoInformation(encodedPlace);
                    if (geoInformationOk(geoResult)) {
                        this.CoordinateX = parseFloat(geoResult.Placemark[0].Point.coordinates[1]);
                        this.CoordinateY = parseFloat(geoResult.Placemark[0].Point.coordinates[0]);
                    }
                }
            });
        }

        //Calculate center point
        var centerX = 0;
        var centerY = 0;
        var centerCounter = 0;
        if (LocationList != null && LocationList.length > 0) {
            jQuery.each(LocationList, function() {
                if (this.CoordinateX != 0 || this.CoordinateX != 0) {
                    centerCounter++;
                    centerX += this.CoordinateX;
                    centerY += this.CoordinateY;
                }
            });
            centerX = centerX / centerCounter;
            centerY = centerY / centerCounter;
            map.setCenter(new GLatLng(centerX, centerY), 15);
        }
        else {
            var countryX = 0;
            var countryY = 0;
            var geoResult = null;
            geoResult = getGeoInformation(getCountryCode());

            if (geoInformationOk(geoResult)) {
                countryX = parseFloat(geoResult.Placemark[0].Point.coordinates[1]);
                countryY = parseFloat(geoResult.Placemark[0].Point.coordinates[0]);
            }
            else { //Position of Germany if everthing else fails
                countryX = 51.165691;
                countryY = 10.451526;
            }
            map.setCenter(new GLatLng(countryX, countryY), 5);
        }
        map.setUIToDefault();


        //Calculate and set the correct zoom factor
        var exitZoomLoop = false;
        var watchDogCounter = 0;
        if (LocationList != null && LocationList.length > 0) {
            do {
                exitZoomLoop = true;
                jQuery.each(LocationList, function() {
                    var mapBounds = map.getBounds();
                    if (this.CoordinateX != 0 || this.CoordinateX != 0) {
                        if (!mapBounds.containsLatLng(new GLatLng(this.CoordinateX, this.CoordinateY))) {
                            exitZoomLoop = false;
                            map.zoomOut();
                        }
                    }
                });
                watchDogCounter++;
            } while (!exitZoomLoop || watchDogCounter < 15);
        }

        //Remove not used map types
        map.removeMapType(G_SATELLITE_MAP);
        map.removeMapType(G_HYBRID_MAP);
        map.removeMapType(G_PHYSICAL_MAP);

        var baseIcon = new GIcon(G_DEFAULT_ICON);
        baseIcon.iconSize = new GSize(20, 34);
        baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(9, 34);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);


        function createMarker(point, isStore, text) {
            var pinIcon = new GIcon(baseIcon);
            if (isStore) {
                pinIcon.image = baseurl + "addons/xparo/storesearch/images/marker_kreis.png";
            }
            else {
                pinIcon.image = baseurl + "addons/xparo/storesearch/images/dealers.png";
            }
            markerOptions = { icon: pinIcon };
            var marker = new GMarker(point, markerOptions);
            GEvent.addListener(marker, "mouseover", function() {
                marker.openInfoWindowHtml(text);
            });
            return marker;
        }


        //Set shop marker
        centerCounter = 0;
        map.clearOverlays();
        if (LocationList != null && LocationList.length > 0) {
            jQuery.each(LocationList, function() {
                if (this.CoordinateX != 0 || this.CoordinateX != 0) {
                    var markerPosition = new GLatLng(this.CoordinateX, this.CoordinateY);
                    var phoneText = "";
                    var emailText = "";
                    if (this.Phone != "") {
                        phoneText = "<br /><br />" + phoneTranslation + " " + encodeHTML(this.Phone);
                    }
                    if (this.Email != "") {
                        emailText = "<br /><a href='mailto:" + encodeHTML(this.Email) + "'>" + encodeHTML(this.Email) + "</a>";
                    }
                    var infoText = "<b>" + encodeHTML(this.Company) + "</b><br />" + encodeHTML(this.Street) + "<br />" + encodeHTML(this.ZipCode) + " " + encodeHTML(this.City) + phoneText + emailText;
                    map.addOverlay(createMarker(markerPosition, this.IsStore, infoText));
                    centerCounter++;
                }
            });
        }

        GEvent.addListener(map, "click", function(overlay, latlng) {
            if (latlng && googleEventLock()) {
                var geoResult = null;
                var geoStateName = '';
                var geoCountryName = '';
                geoResult = getGeoInformation(latlng.toUrlValue(6));
                if (geoInformationOk(geoResult)) {
                    try {
                        geoStateName = geoResult.Placemark[0].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
                        geoCountryName = geoResult.Placemark[0].AddressDetails.Country.CountryNameCode;
                        var systemRegionName = null;
                        jQuery.ajax({
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            url: baseurl + "addons/xparo/storesearch/desktop/storesearch.asmx/RegionByGoogleName",
                            data: "{\"googleRegionName\":\"" + geoStateName + "\"}",
                            dataType: "json",
                            async: false,
                            success: function(msg) {
                                systemRegionName = msg.d;
                            }
                        });

                        jQuery("#" + IdOfCountryList).val(geoCountryName);
                        changeCountryList();
                        if (systemRegionName != null && systemRegionName != "") {
                            jQuery("#RegionList").val(systemRegionName);
                            SearchStores();
                        }
                        googleEventLockTimestamp = getUnixTimeStamp();
                    }
                    catch (ex) {
                       
                    }
                }
            }
        });
    }
}

function showMap() {
        //jQuery('#googlemaps').empty();
        initialize();
}


