define([
    'jquery',
    'Magento_Ui/js/modal/modal',
    'underscore',
    'FiloBlu_Storelocator/js/model/selected-store-data',
    'mage/translate',
    'markercluster',
], function ($, modal, _, selectedStoreData) {

    window.FiloBlu = (!window.FiloBlu) ? {} : window.FiloBlu;

    // hook return to store as pickup in store
    window.return_to_store = 0;

    if($('#return-to-store-wrapper').length > 0) {
        window.return_to_store = 1;
    }

    window.FiloBlu.StoreLocator = {
        gMap: null,
        settings: null,
        infowindow: null,
        markerclick: false,
        directionsDisplay: null,
        initGMap: function (params) {
            var self = this;

            var defaults = {
                //gmap params
                center: {
                    lat: 41.068179,
                    lng: 14.331737
                },
                zoom: 4,
                minZoom: 3,
                maxZoom: 20,
                mapContainerId: 'map',
                mapTypeId: 'roadmap',
                zoomControl: true,
                mapTypeControl: true,
                streetViewControl: true,
                rotateControl: true,
                scaleControl: false,
                fullscreenControl: false,
                // custom params
                gmapApiUrl: 'https://maps.googleapis.com/maps/api/js',
                gmapGeolocationApiUrl: 'https://www.googleapis.com/geolocation/v1/geolocate',
                gmapApiKey: '',
                gmapLanguage: 'en',
                gmapMarkers: {},
                gmapMarkersArray: [],
                // geolocation
                gmapGeoLocation: false,
                gmapGeoLocationZoom: 15,
                gmapGeoLocationDistance: false,
                gmapGeoLocationDuration: false,
                gmapGeoLocationTravelMode: 'DRIVING',
                gmapGeoLocationUnitSystem: google.maps.UnitSystem.METRIC,
                gmapGeoLocationGetDirections: false,
                gmapGeoLocationGetDirectionsPanelId: 'gmapGetDirectionsPanel',
                // cluster
                gmapMarkerClusterMarkerEntity: null,
                gmapMarkersClusterMarker: false,
                gmapMarkersClusterMarkerGridSize: 60,
                gmapMarkersClusterMarkerMaxZoom: null,
                gmapMarkersClusterMarkerZoomOnClick: true,
                gmapMarkersClusterMarkerAverageCenter: false,
                gmapMarkersClusterMarkerMinimumClusterSize: 2,
                gmapMarkersClusterMarkerImage: '',
                gmapMarkersClusterMarkerImageWidth: 28,
                gmapMarkersClusterMarkerImageHeight: 43,
                gmapMarkersClusterMarkerTextColor: 'black',
                gmapMarkersClusterMarkerTextSize: 11,
                gmapMarkersClusterMarkerTextOffsetWidth: 0,
                gmapMarkersClusterMarkerTextOffsetHeight: 0,
                // search
                gmapSearchAutocomplete: true,
                gmapSearchAutocompleteId: 'gmapSearch',
                gmapSearchAutocompleteZoom: 17,
                gmapSearchCountryId: 'gmapCountry',
                gmapSearchRegionId: 'gmapRegion',
                gmapSearchCityId: 'gmapCity',
                gmapSearchCountry: true,
                gmapSearchRegion: false,
                gmapSearchCity: true,
                gmapSearchTags: false,
                gmapSearchTagsContainerClass: 'tag-info',
                // stores list
                gmapStoresListId: 'gmapStoresList',
                gmapActiveTagArray: [],
                // working times
                gmapWorkingTimes: true,
                pickup_in_store: window.return_to_store,
                tag_filters_params : window.tagFilterCategories,
                // functions
                handleZoomChanged: function (map, settings) {
                    self.getStoresByCurrentZoom(map);
                },
                handleCountryChanged: function (country, settings, map) {
                    if(!country){
                        $('#' + settings.gmapSearchRegionId).prop('disabled',true);
                        $('#' + settings.gmapSearchCityId).prop('disabled',true);
                        if(self.settings.gmapGeoLocation){
                            map.setCenter(self.settings.gmapGeolocationCurrent);
                            map.setZoom(self.settings.gmapGeoLocationZoom);
                        } else{
                            map.setCenter(self.settings.center);
                            map.setZoom(self.settings.zoom);
                        }
                        self.getStoresByCurrentZoom(map);
                        return false;
                    }

                    if (settings.gmapSearchRegion) {

                        var param = 'ajax=1&&country=' + country;

                        if ($('input[name="pickupatstorechooser"]').size()) {
                            param += '&pickup_in_store=' + settings.pickup_in_store ;
                        }

                        if ($('input[name="rma_returntostore_active"]').size()) {
                            param += '&return_in_store=1'
                        }

                        $.ajax({
                            showLoader: true,
                            url: self.settings.baseUrl + "storelocator/index/regionbycountry",
                            data: param,
                            type: "GET",
                            cache: true,
                            dataType: 'json'
                        }).done(function (data) {


                            if (data && data !== false) {

                                if (GetIEVersion() > 0 && GetIEVersion() == 11 ) {

                                    setTimeout(function(){
                                        $('#' + settings.gmapSearchRegionId).html(data);
                                        $('#' + settings.gmapSearchRegionId).prop('disabled', false);

                                        $('#' + settings.gmapSearchRegionId).on('change', function () {
                                            if (self.infowindow) {
                                                self.infowindow.close();
                                                self.markerClick = false;
                                            }
                                            settings.handleRegionChanged($(this).val(), settings, map);
                                        });
                                    }, 500);
                                } else{

                                    $('#' + settings.gmapSearchRegionId).html(data);
                                    $('#' + settings.gmapSearchRegionId).prop('disabled', false);

                                    $('#' + settings.gmapSearchRegionId).on('change', function () {
                                        if (self.infowindow) {
                                            self.infowindow.close();
                                            self.markerClick = false;
                                        }
                                        settings.handleRegionChanged($(this).val(), settings, map);
                                    });
                                }
                            } else {
                                $('#' + settings.gmapSearchRegionId).html('');
                                $('#' + settings.gmapSearchRegionId).prop('disabled', true);
                                var param = 'ajax=1&country=' + country;

                                if ($('input[name="pickupatstorechooser"]').size()) {
                                    param += '&pickup_in_store=' + settings.pickup_in_store;
                                }

                                if ($('input[name="rma_returntostore_active"]').size()) {
                                    param += '&return_in_store=1'
                                }

                                $.ajax({
                                    showLoader: true,
                                    url: self.settings.baseUrl + "storelocator/index/citiesbycountry",
                                    data: param,
                                    type: "GET",
                                    cache: true,
                                    dataType: 'json'
                                }).done(function (data) {
                                    if (data) {
                                        if (GetIEVersion() > 0 && GetIEVersion() == 11 ) {
                                            setTimeout(function(){
                                                $('#' + settings.gmapSearchCityId).html(data);
                                                $('#' + settings.gmapSearchCityId).prop('disabled', false);

                                                $('#' + settings.gmapSearchCityId).on('change', function () {
                                                    if (self.infowindow) {
                                                        self.infowindow.close();
                                                        self.markerClick = false;
                                                    }
                                                    settings.handleCityChanged($(this).val(), settings, map);
                                                });
                                            }, 500);
                                        } else{
                                            $('#' + settings.gmapSearchCityId).html(data);
                                            $('#' + settings.gmapSearchCityId).prop('disabled', false);

                                            $('#' + settings.gmapSearchCityId).on('change', function () {
                                                if (self.infowindow) {
                                                    self.infowindow.close();
                                                    self.markerClick = false;
                                                }
                                                settings.handleCityChanged($(this).val(), settings, map);
                                            });
                                        }
                                    }
                                })
                            }
                        })
                        ;
                    } else {
                        var param = 'ajax=1&country=' + country;

                        if ($('input[name="pickupatstorechooser"]').size()) {
                            param += '&pickup_in_store=' + settings.pickup_in_store;
                        }

                        if ($('input[name="rma_returntostore_active"]').size()) {
                            param += '&return_in_store=1'
                        }

                        $.ajax({
                            showLoader: true,
                            url: self.settings.baseUrl + "storelocator/index/citiesbycountry",
                            data: param,
                            type: "GET",
                            cache: true,
                            dataType: 'json'
                        }).done(function (data) {
                            if (data) {
                                if (GetIEVersion() > 0 && GetIEVersion() == 11 ) {
                                    setTimeout(function(){
                                        $('#' + settings.gmapSearchCityId).html(data);
                                        $('#' + settings.gmapSearchCityId).prop('disabled', false);

                                        $('#' + settings.gmapSearchCityId).on('change', function () {
                                            if (self.infowindow) {
                                                self.infowindow.close();
                                                self.markerClick = false;
                                            }
                                            settings.handleCityChanged($(this).val(), settings, map);
                                        });
                                    }, 500);
                                } else{
                                    $('#' + settings.gmapSearchCityId).html(data);
                                    $('#' + settings.gmapSearchCityId).prop('disabled', false);

                                    $('#' + settings.gmapSearchCityId).on('change', function () {
                                        if (self.infowindow) {
                                            self.infowindow.close();
                                            self.markerClick = false;
                                        }
                                        settings.handleCityChanged($(this).val(), settings, map);
                                    });
                                }
                            }
                        })
                    }

                    var param = 'ajax=1&country=' + country;

                    if ($('input[name="pickupatstorechooser"]').size()) {
                        param += 'pickup_in_store=' + settings.pickup_in_store;
                    }

                    if ($('input[name="rma_returntostore_active"]').size()) {
                        param += '&return_in_store=1'
                    }

                    $.ajax({
                        showLoader: true,
                        url: self.settings.baseUrl + "storelocator/index/latlngbycountry",
                        data: param,
                        type: "GET",
                        cache: true,
                        dataType: 'json'
                    }).done(function (data) {
                        var bounds = new google.maps.LatLngBounds();
                        var found = false;

                        if(data){
                            $.each(data.items, function (key, value) {
                                found = true;
                                var latLng = new google.maps.LatLng(value.latitude, value.longitude);
                                bounds.extend(latLng);
                            });
                        }

                        if (found) {
                            map.fitBounds(bounds);
                        }

                    });

                },

                handleRegionChanged: function (region,settings,map) {
                    var param = 'ajax=1&region=' + region;

                    if ($('input[name="pickupatstorechooser"]').size()) {
                        param += '&pickup_in_store=' + settings.pickup_in_store;
                    }

                    if ($('input[name="rma_returntostore_active"]').size()) {
                        param += '&return_in_store=1'
                    }

                    $.ajax({
                        showLoader: true,
                        url: settings.baseUrl + "storelocator/index/citiesbyregion",
                        data: param,
                        type: "GET",
                        cache: true,
                        dataType: 'json'
                    }).done(function (data) {
                        if (data) {
                            if (GetIEVersion() > 0 && GetIEVersion() == 11 ) {
                                setTimeout(function(){
                                    $('#' + settings.gmapSearchCityId).html(data);
                                    $('#' + settings.gmapSearchCityId).prop('disabled', false);

                                    $('#' + settings.gmapSearchCityId).on('change', function () {
                                        if (self.infowindow) {
                                            self.infowindow.close();
                                            self.markerClick = false;
                                        }
                                        settings.handleCityChanged($(this).val(), settings, map);
                                    });
                                }, 500);
                            } else{
                                $('#' + settings.gmapSearchCityId).html(data);
                                $('#' + settings.gmapSearchCityId).prop('disabled', false);

                                $('#' + settings.gmapSearchCityId).on('change', function () {
                                    if (self.infowindow) {
                                        self.infowindow.close();
                                        self.markerClick = false;
                                    }
                                    settings.handleCityChanged($(this).val(), settings, map);
                                });
                            }
                        }
                    })
                },

                handleCityChanged: function (city, settings, map) {
                    if (self.settings.gmapSearchCountry) {
                        var country = $('#' + self.settings.gmapSearchCountryId).val();

                        if(!city){
                            self.settings.handleCountryChanged(country,settings,map);
                            return false;
                        }
                    } else {
                        var country = "";
                    }

                    var param = 'ajax=1&city=' + city + '&country=' + country;

                    if ($('input[name="pickupatstorechooser"]').size()) {
                        param += '&pickup_in_store=' + settings.pickup_in_store;

                    }

                    if ($('input[name="rma_returntostore_active"]').size()) {
                        param += '&return_in_store=1'
                    }

                    $.ajax({
                        showLoader: true,
                        url: self.settings.baseUrl + "storelocator/index/latlngbycity",
                        data: param,
                        type: "GET",
                        cache: true,
                        dataType: 'json'
                    }).done(function (data) {
                        var bounds = new google.maps.LatLngBounds();
                        var found = false;

                        if(data){
                            $.each(data.items, function (key, value) {
                                found = true;
                                var latLng = new google.maps.LatLng(value.latitude, value.longitude);
                                bounds.extend(latLng);
                            });
                        }

                        if (found) {
                            map.fitBounds(bounds);
                        }
                    });

                },
                handleMarkerClick: function (item, settings) {

                    $("#" + settings.gmapStoresListId + " ul li").removeClass("active");
                    $('#store-info-' + item.store_id).addClass("active");

                    $("#" + settings.gmapStoresListId + " ul").animate({
                        scrollTop: $("#" + settings.gmapStoresListId + " ul").scrollTop() - $("#" + settings.gmapStoresListId + " ul").offset().top + $('#store-info-' + item.store_id).offset().top
                    }, 1000);

                    var tel1 = item.phone_1;
                    var tel2 = item.phone_2;
                    var fax = item.fax;
                    var email = item.email;
                    var website_url = item.website_url;
                    var additional_text = item.additional_text;
                    var additional_text_2 = item.additional_text_2;

                    var get_directions_link = '';

                    if (self.settings.gmapGeoLocationGetDirections && self.settings.gmapGeolocationCurrent) {
                        get_directions_link = '<p><a class="gmap-getdirection" href="#" data-latitude="' + item.latitude + '" data-longitude="' + item.longitude + '"><span class="icon-direction"></span>' + $.mage.__("Get Directions") + '</a></p>';
                    }

                    if (tel1) {

                        tel1 = '<p class="gmaps-tel1">Tel: ' + tel1 + '</p>';
                    } else {
                        tel1 = '';
                    }

                    if (tel2) {
                        tel2 = '<p class="gmaps-tel2">Tel: ' + tel2 + '</p>';
                    } else {
                        tel2 = '';
                    }

                    if (fax) {
                        fax = '<p class="gmaps-fax">Fax: ' + fax + '</p>';
                    } else {
                        fax = '';
                    }

                    if (email) {
                        email = '<p class="gmaps-email">Email: ' + email + '</p>';
                    } else {
                        email = '';
                    }

                    var region = '';

                    if (item.region) {
                        region = ', ' + item.region;
                    }

                    var contentString = '<div id="content" class="gmaps-details">' +
                        '<div id="siteNotice">' +
                        '</div>' +
                        '<h1 id="firstHeading" class="firstHeading">' + item.title + '</h1>' +
                        '<div id="bodyContent">' +
                        '<p class="gmaps-street">' + item.street + ' ' + item.postcode + '</p>' +
                        '<p class="gmaps-city_country">' + item.city +  region + ' (' + item.country + ')</p>' +
                        tel1 +
                        tel2 +
                        email +
                        get_directions_link +
                        '</div>' +
                        '</div>';

                    return contentString;
                },
                handleAutocompletePlaceChanged: function (map, settings, place) {
                    if (!place.geometry) {
                        window.alert($.mage.__("Autocomplete's returned place contains no geometry"));
                        return;
                    }

                    // If the place has a geometry, then present it on a map.
                    if (place.geometry.viewport) {
                        map.fitBounds(place.geometry.viewport);
                    } else {
                        map.setCenter(place.geometry.location);
                        map.setZoom(settings.gmapSearchAutocompleteZoom);
                    }

                },
                handleDistanceMatrixResponse: function (response, status, settings, markerArrayElement) {
                    if (status !== 'OK') {
                        console.log('Error was: ' + status);
                    } else {
                        for (i = 0; i < response.rows[0].elements.length; i++) {
                            if (response.rows[0].elements[i].status == "OK") {
                                if (settings.gmapGeoLocationDistance) {
                                    var txtDistance = response.rows[0].elements[i].distance.text;
                                    var valueDistance = response.rows[0].elements[i].distance.value;
                                    var elementToUpdateDistance = $('#store-info-distance-' + markerArrayElement[i].store_id);
                                    elementToUpdateDistance.html($.mage.__("Distance") + ': ' + txtDistance);
                                    $('#store-info-' + markerArrayElement[i].store_id).attr("data-distance", valueDistance);
                                }
                                if (settings.gmapGeoLocationDuration) {
                                    var txtDuration = response.rows[0].elements[i].duration.text;
                                    var valueDuration = response.rows[0].elements[i].duration.value;
                                    var elementToUpdateDuration = $('#store-info-duration-' + markerArrayElement[i].store_id);
                                    elementToUpdateDuration.html($.mage.__("Duration") + ': ' + txtDuration);
                                    $('#store-info-' + markerArrayElement[i].store_id).attr("data-duration", valueDuration);
                                }
                            }
                        }

                        //reorder by distance
                        var storeLocationListDom = $("#" + settings.gmapStoresListId + " > ul");
                        var storeLocationList = _.sortBy(storeLocationListDom.children(), function (storeLocation) {
                            return !_.isNaN(parseInt(storeLocation.dataset.distance)) ? parseInt(storeLocation.dataset.distance) : undefined;
                        });

                        storeLocationListDom.html('');
                        _.each(storeLocationList, function (storeLocation) {
                            storeLocationListDom.append(storeLocation);
                        });
                    }

                },
                handleStoresList: function (map, settings) {
                    // remove all stores
                    $("#" + settings.gmapStoresListId + " ul li.no-store").remove();
                    $("#" + settings.gmapStoresListId + " ul li").removeClass("visible").attr("data-order-country", 2);
                    var atLeastOnStoreVisible = false;
                    if (self.settings.gmapSearchTags) {
                        settings.handleTagInStore(map, settings);
                    }

                    var htmlElement = [];

                    for (var i = settings.gmapMarkersArray.length, bounds = map.getBounds(); i--; ) {
                        if (bounds && bounds.contains(settings.gmapMarkersArray[i].marker.getPosition())) {

                            var data = settings.gmapMarkersArray[i].data;

                            if (self.settings.gmapSearchTags && !data.in_tags) {
                                continue;
                            }

                            if(self.settings.tag_filters_params && self.settings.tag_filters_params.enabled == '1' && window.return_to_store == '1'){
                                // tag filter enabled and only return to store section
                                var filterValues = self.settings.tag_filters_params.value;
                                var tags_settings = JSON.parse(filterValues);
                                var tags_array = [];
                                var store_consider = [];

                                $.each(tags_settings, function( index, value ){
                                    tags_array.push(value);
                                });

                                $.each(data.tags_id, function( i, val ){
                                    if($.inArray(val, tags_array) >= 0){
                                        store_consider[i] = data.store_id;
                                    }
                                });

                                if(store_consider.length <= 0){
                                    continue;
                                }
                            }

                            atLeastOnStoreVisible = true;

                            var storeCountryOrder = 2;

                            if (data.country && self.settings.gmapSearchCountry && data.country == $('#' + self.settings.gmapSearchCountryId).val()) {
                                storeCountryOrder = 1;
                            }

                            if ($('#store-info-' + data.store_id).length > 0) {
                                $('#store-info-' + data.store_id).addClass("visible");
                                $('#store-info-' + data.store_id).attr("data-order-country", storeCountryOrder);
                            } else {

                                var tel1 = data.phone_1;
                                var tel2 = data.phone_2;
                                var shopViewLink = data.shop_view_url;
                                var shopViewHtml = '';
                                var fax = data.fax;
                                var email = data.email;
                                var website_url = data.website_url;
                                var additional_text = data.additional_text;
                                var additional_text_2 = data.additional_text_2;
                                var get_directions_link = '';
                                var tags = '';
                                var image = data.image_url;
                                var distanceContainer = '';
                                var distanceElement = '';
                                var durationElement = '';
                                var workingTimes = '';
                                var workingTimesData = '';
                                var galleryLink = '';
                                var pickupInStoreSelection = '';

                                if (window.currentProduct) {
                                    shopViewLink = data.shop_view_url + '/product/' + window.currentProduct;
                                }

                                if (settings.pickup_in_store) {
                                    pickupInStoreSelection = '<p><a class="pickup-in-store-selection action primary inverse" data-store-id="' + data.store_id + '" href="#">' + $.mage.__("Select this store for pick up") + '</a></p>';
                                }

                                if(window.return_to_store == 1)
                                {
                                    pickupInStoreSelection = '<p><a class="return-to-store-selection action primary inverse" data-store-id="' + data.store_id + '" href="#">' + $.mage.__("Select this store for return") + '</a></p>';
                                }

                                if (data.image_gallery.length) {

                                    galleryLink = '<p><a class="view-gallery" href="#" onclick="jQuery(\'#popup-modal-' + data.store_id + '\').modal(\'openModal\'); return false;" ><span class="icon-gallery"></span>' + $.mage.__("View gallery images") + '</a></p>';

                                    var galleryHTML = '';
                                    var galleryImages = [];

                                    for (cImage = 0; cImage < data.image_gallery.length; cImage++) {
                                        galleryImages.push({
                                            img: data.image_gallery[cImage].imageUrl,
                                            caption: data.image_gallery[cImage].title,
                                            position: cImage + 1,
                                            isMain: (cImage == 0)
                                        });
                                    }

                                    galleryHTML = '<div id="popup-modal-' + data.store_id + '"><div class="gallery-placeholder _block-content-loading" data-gallery-role="gallery-placeholder-' + data.store_id + '"></div></div>';

                                    galleryHTML += '<script type="text/x-magento-init">' +
                                        '{' +
                                        '"[data-gallery-role=gallery-placeholder-' + data.store_id + ']": {' +
                                        '"mage/gallery/gallery": {' +
                                        '"data": ' + JSON.stringify(galleryImages) + ',' +
                                        '"options": {' +
                                        '"nav": "dots",' +
                                        '"loop": false,' +
                                        '"keyboard": true,' +
                                        '"arrows": true,' +
                                        '"allowfullscreen": false,' +
                                        '"showCaption": true,' +
                                        '"transitionduration": 500,' +
                                        '"transition": "slide",' +
                                        '"navarrows": true,' +
                                        '"navtype": "slides",' +
                                        '"navdir": "horizontal"' +
                                        '},' +
                                        '"fullscreen": {' +
                                        '"nav": false,' +
                                        '"loop": false,' +
                                        '"navdir": "horizontal",' +
                                        '"arrows": false,' +
                                        '"showCaption": false,' +
                                        '"transitionduration": 500,' +
                                        '"transition": "slide"' +
                                        '}' +
                                        '}' +
                                        '}' +
                                        '}' +
                                        '</script>';

                                    $(galleryHTML).insertAfter("#" + settings.gmapStoresListId);

                                    var optionsPopup = {
                                        type: 'popup',
                                        responsive: true,
                                        innerScroll: true,
                                        title: data.title,
                                        modalClass: 'storelocator-gallery-popup'
                                    };

                                    var popup = modal(optionsPopup, $('#popup-modal-' + data.store_id));

                                    $('body').trigger('contentUpdated');
                                }

                                if (self.settings.gmapGeoLocationGetDirections && self.settings.gmapGeolocationCurrent) {
                                    get_directions_link = '<p class="store-info-direction"><a class="gmap-getdirection" href="#" data-latitude="' + data.latitude + '" data-longitude="' + data.longitude + '"><span class="icon-direction"></span>' + $.mage.__("Get Directions") + '</a></p>';
                                }

                                if (tel1) {

                                    tel1 = '<span class="icon-tel"></span> Tel: ' + tel1 + ' ';
                                } else {
                                    tel1 = '';
                                }

                                if (tel2) {
                                    tel2 = 'Tel: ' + tel2 + ' ';
                                } else {
                                    tel2 = '';
                                }

                                if (fax) {
                                    fax = '<span class="icon-fax"></span> Fax: ' + fax + '';
                                } else {
                                    fax = '';
                                }

                                if (email) {
                                    email = '<p>Email: <a href="mailto:' + email + '">' + email + '</a></p>';
                                } else {
                                    email = '';
                                }

                                if (website_url) {
                                    website_url = '<p>Website: <a href="' + website_url + '" target="_blank">' + website_url + '</a></p>';
                                } else {
                                    website_url = '';
                                }

                                if (additional_text) {
                                    additional_text = '<div class="additional-text">' + additional_text + '</div>';
                                } else {
                                    additional_text = '';
                                }


                                if (additional_text_2) {
                                    additional_text_2 = '<div class="additional-text">' + additional_text_2 + '</div>';
                                } else {
                                    additional_text_2 = '';
                                }

                                if (settings.gmapGeoLocationDistance) {
                                    distanceElement = '<p class="store-distance" id="store-info-distance-' + data.store_id + '"></p>';
                                }

                                if (settings.gmapGeoLocationDuration) {
                                    durationElement = '<p class="store-duration" id="store-info-duration-' + data.store_id + '"></p>';
                                }

                                if (distanceElement && !durationElement) {
                                    distanceContainer = "<div class='distance-container'>" + distanceElement + "</div>";
                                }

                                if (!distanceElement && durationElement) {
                                    distanceContainer = "<div class='distance-container'>" + durationElement + "</div>";
                                }

                                if (distanceElement && durationElement) {
                                    distanceContainer = "<div class='distance-container'>" + distanceElement + durationElement + "</div>";
                                }

                                if (data.tags_name.length) {
                                    tags += '<div class="tags-container">';
                                    for (jj = 0; jj < data.tags_name.length; jj++) {
                                        tags += '<span>' + data.tags_name[jj] + '</span>';
                                    }
                                    tags += '</div>';
                                }

                                if (image) {
                                    image = '<div class="store-image-preview-container" style="background-image:url(' + image + ')"></div>';
                                } else {
                                    image = '';
                                }

                                if (self.settings.gmapWorkingTimes && data.has_working_times) {

                                    for (wk = 0; wk < data.working_times.length; wk += 2) {
                                        var dayName = '';

                                        switch (data.working_times[wk].day) {
                                            case "1":
                                                dayName = $.mage.__('Monday');
                                                break;
                                            case "2":
                                                dayName = $.mage.__('Tuesday');
                                                break;
                                            case "3":
                                                dayName = $.mage.__('Wednesday');
                                                break;
                                            case "4":
                                                dayName = $.mage.__('Thursday');
                                                break;
                                            case "5":
                                                dayName = $.mage.__('Friday');
                                                break;
                                            case "6":
                                                dayName = $.mage.__('Saturday');
                                                break;
                                            case "7":
                                                dayName = $.mage.__('Sunday');
                                                break;

                                            default:
                                                dayName = '';
                                        }

                                        var morningStr = '<span class="working-times-closed">' + $.mage.__('Closed') + '</span>';
                                        var afternoonStr = '<span class="working-times-closed">' + $.mage.__('Closed') + '</span>';
                                        var continuedTimetable = false;

                                        if (!data.working_times[wk].closed && !(data.working_times[wk].from == '00:00' && data.working_times[wk].to == '00:00')) {
                                            morningStr = data.working_times[wk].from + ' - ' + data.working_times[wk].to;

                                            if (data.working_times[wk].to == data.working_times[wk + 1].from) {
                                                continuedTimetable = true;
                                                morningStr = data.working_times[wk].from + ' - ' + data.working_times[wk + 1].to;
                                            }
                                        }

                                        if (!continuedTimetable && !data.working_times[wk + 1].closed && !(data.working_times[wk + 1].from == '00:00' && data.working_times[wk + 1].to == '00:00')) {
                                            afternoonStr = data.working_times[wk + 1].from + ' - ' + data.working_times[wk + 1].to;
                                        }

                                        if (continuedTimetable) {
                                            workingTimesData +=
                                                '<tr>' +
                                                '<td>' + dayName + '</td>' +
                                                '<td colspan="2">' + morningStr + '</td>' +
                                                '</tr>';
                                        } else {
                                            workingTimesData +=
                                                '<tr>' +
                                                '<td>' + dayName + '</td>' +
                                                '<td>' + morningStr + '</td>' +
                                                '<td>' + afternoonStr + '</td>' +
                                                '</tr>';
                                        }


                                    }

                                    workingTimes = '<table class="hours-table" cellspacing="0" cellpadding="0" border="0">' +
                                        '<tr>' +
                                        '<td class="hours-table-title" colspan="3"><span class="icon-hours"></span> ' + $.mage.__('Working Times') + '</td>' +
                                        '</tr>' +
                                        '<tr>' +
                                        '<td>&nbsp;</td>' + '<td>' + $.mage.__('Morning') + '</td>' + '<td>' + $.mage.__('Afternoon') + '</td>' +
                                        '</tr>' +
                                        workingTimesData +
                                        '</table>';
                                }
                                if (self.settings.listShopDetails) {
                                    shopViewHtml = '<p><a href="' + shopViewLink +'" class="shop-view-link">' + $.mage.__('Shop details') + '</a></p>';
                                }

                                var region = '';

                                if (data.region) {
                                    region = ', ' + data.region;
                                }

                                var contentString =
                                    image +
                                    '<div class="store-details-container"><p><strong>' + data.title + '</strong></p>' +
                                    '<p><a href="#" class="reveal-on-map" data-store-id="' + data.store_id + '"><span class="icon-location"></span>' + $.mage.__('Reveal on map') + '</a></p>' +
                                    '<p>' + data.street + ' ' + data.postcode + ' ' + data.city + region + ' (' + data.country + ')</p>' +
                                    '<p>' + tel1 +
                                    tel2 +
                                    fax + '</p>' +
                                    email +
                                    website_url +
                                    shopViewHtml +
                                    pickupInStoreSelection +
                                    additional_text +
                                    additional_text_2 +
                                    get_directions_link +
                                    distanceContainer +
                                    galleryLink +
                                    tags +
                                    workingTimes +
                                    '</div>';

                                htmlElement.push("<li id='store-info-" + data.store_id + "' data-store-id='" + data.store_id + "' data-tags='" + data.tags_id + "' data-order-country='" + storeCountryOrder + "' class='visible'>" + contentString + "</li>");
                                $(document).on('click', '.store-image-preview-container', function () {});
                            }
                        }
                    }

                    if (GetIEVersion() > 0 && GetIEVersion() == 11) {
                        setTimeout(function () {
                            $("#" + settings.gmapStoresListId + " ul").append(htmlElement);
                        }, 500);
                    } else {
                        $("#" + settings.gmapStoresListId + " ul").append(htmlElement);
                    }

                    //add alert no store in the DOM
                    if (!atLeastOnStoreVisible) {
                        if (GetIEVersion() > 0 && GetIEVersion() == 11 ) {
                            setTimeout(function(){
                                $("#" + settings.gmapStoresListId + " ul").append('<li class="visible no-store">' + $.mage.__('No stores in this location.') + '<li>');
                            }, 500);
                        } else {
                            $("#" + settings.gmapStoresListId + " ul").append('<li class="visible no-store">' + $.mage.__('No stores in this location.') + '<li>');
                        }
                    }

                    //reorder by selected country
                    var storeLocationListDom = $("#" + settings.gmapStoresListId + " > ul");
                    var storeLocationList = _.sortBy(storeLocationListDom.children(), function (storeLocation) {
                        return !_.isNaN(parseInt(storeLocation.dataset.orderCountry)) ? parseInt(storeLocation.dataset.orderCountry) : undefined;
                    });

                    storeLocationListDom.html('');
                    _.each(storeLocationList, function (storeLocation) {
                        storeLocationListDom.append(storeLocation);
                    });

                    self.getDistanceFromStoreByCurrentPosition(settings.gmapMarkersArray);

                    if ($("#" + settings.gmapStoresListId + " ul li.active").length > 0) {
                        $("#" + settings.gmapStoresListId + " ul").animate({
                            scrollTop: $("#" + settings.gmapStoresListId + " ul").scrollTop() - $("#" + settings.gmapStoresListId + " ul").offset().top + $("#" + settings.gmapStoresListId + " ul li.active").offset().top
                        }, 1000);
                    }
                },
                handleGetDirections: function (map, settings, self) {
                    $(document).on('click', '.gmap-getdirection', function (e) {
                        e.preventDefault();

                        if (self.directionsDisplay) {
                            self.directionsDisplay.setMap(null);
                            self.directionsDisplay.setPanel(null);
                        }

                        var directionsService = new google.maps.DirectionsService();
                        self.directionsDisplay = new google.maps.DirectionsRenderer();

                        self.directionsDisplay.setMap(map);
                        self.directionsDisplay.setPanel(document.getElementById(settings.gmapGeoLocationGetDirectionsPanelId));

                        var latLng = new google.maps.LatLng($(this).attr("data-latitude"), $(this).attr("data-longitude"));

                        directionsService.route({
                            origin: self.settings.gmapGeolocationCurrent,
                            destination: latLng,
                            travelMode: self.settings.gmapGeoLocationTravelMode
                        }, function (response, status) {
                            if (status === 'OK') {
                                self.directionsDisplay.setDirections(response);
                                $('#gmapGetDirectionsRemove').addClass('active');
                            } else {
                                window.alert('Directions request failed due to ' + status);
                            }
                        });
                    });

                    $(document).on('click', '#gmapGetDirectionsRemove', function (e) {
                        e.preventDefault();
                        if (self.directionsDisplay) {
                            self.directionsDisplay.setMap(null);
                            self.directionsDisplay.setPanel(null);
                        }

                        $(this).removeClass('active');

                    });

                },
                handleTagClick: function (tagElement, settings, map, self) {
                    tagElement.toggleClass('active');
                    if (tagElement.hasClass("active")) {

                        settings.gmapActiveTagArray.push(tagElement.attr("data-tag-id"));
                    } else {
                        var index = settings.gmapActiveTagArray.indexOf(tagElement.attr("data-tag-id"));
                        if (index > -1) {
                            settings.gmapActiveTagArray.splice(index, 1);
                        }
                    }

                    //settings.handleTagInStore(map, settings);

                    settings.handleStoresList(map, settings);

                },
                handleTagInStore: function (map, settings) {

                    if (self.settings.gmapMarkerClusterMarkerEntity) {
                        self.settings.gmapMarkerClusterMarkerEntity.clearMarkers();
                    }

                    for (i = 0; i < settings.gmapMarkersArray.length; i++) {

                        if (settings.gmapActiveTagArray.length == 0) {
                            settings.gmapMarkersArray[i].data.in_tags = true;
                            if (self.settings.gmapMarkersClusterMarker) {
                                self.settings.gmapMarkerClusterMarkerEntity.addMarker(settings.gmapMarkersArray[i].marker, false);
                            }
                        } else {
                            settings.gmapMarkersArray[i].data.in_tags = false;
                        }

                        if (settings.gmapActiveTagArray.length == 0 && !self.settings.gmapMarkersClusterMarker) {
                            settings.gmapMarkersArray[i].marker.setMap(map);
                        } else {
                            if (!self.settings.gmapMarkersClusterMarker) {
                                settings.gmapMarkersArray[i].marker.setMap(null);
                            }

                        }

                        for (j = 0; j < settings.gmapActiveTagArray.length; j++) {
                            var index = settings.gmapMarkersArray[i].data.tags_id.indexOf(settings.gmapActiveTagArray[j]);
                            if (index > -1) {
                                settings.gmapMarkersArray[i].data.in_tags = true;

                                if (self.settings.gmapMarkersClusterMarker) {
                                    self.settings.gmapMarkerClusterMarkerEntity.addMarker(settings.gmapMarkersArray[i].marker, false);
                                } else {
                                    settings.gmapMarkersArray[i].marker.setMap(map);
                                }

                            }
                        }
                    }
                },
                handleAfterInit: function (map, settings) {

                },
            };

            self.settings = $.extend(defaults, params);
            self.gMap = new google.maps.Map(document.getElementById(self.settings.mapContainerId), self.settings)

            if (self.settings.gmapGeoLocation) {
                // use google API location instead HTML5
                self.geoLocationGoogleAPI(self.gMap.getCenter(), self.gMap);
            } else {
                self.initElementsAfterGeolocation();
            }

            // Search Autocomplete
            if (self.settings.gmapSearchAutocomplete) {
                var input = document.getElementById(self.settings.gmapSearchAutocompleteId);
                var autocomplete = new google.maps.places.SearchBox(input);

                if (self.settings.gmapSearchAutocompleteType) {
                    autocomplete.setTypes([self.settings.gmapSearchAutocompleteType]);
                }

                autocomplete.bindTo('bounds', self.gMap);

                google.maps.event.addListener(autocomplete, 'places_changed', function() {

                    self.settings.handleAutocompletePlaceChanged(self.gMap, self.settings, autocomplete.getPlaces()[0]);
                });


            }

            if (self.settings.gmapSearchCountry) {
                // Search by Country/City
                var param = 'ajax=1';

                if ($('input[name="pickupatstorechooser"]').size()) {
                    param += '&pickup_in_store=' + self.settings.pickup_in_store;
                }

                if ($('input[name="rma_returntostore_active"]').size()) {
                    param += '&return_in_store=1'
                }

                $.ajax({
                    showLoader: true,
                    url: self.settings.baseUrl + "storelocator/index/countriesbyavailablestores",
                    data: param,
                    type: "GET",
                    cache: true,
                    dataType: 'json'
                }).done(function (data) {
                    if (data) {
                        $('#' + self.settings.gmapSearchCountryId).html(data);
                        $('#' + self.settings.gmapSearchCountryId).on('change', function () {
                            if (self.infowindow) {
                                self.infowindow.close();
                                self.markerClick = false;
                            }
                            self.settings.handleCountryChanged($(this).val(), self.settings, self.gMap);
                        });

                    }

                    $(window).trigger('countriesLoaded');

                });
            }

            if (self.settings.gmapSearchTags) {
                $('.' + self.settings.gmapSearchTagsContainerClass).on('click', function () {
                    self.settings.handleTagClick($(this), self.settings, self.gMap, self);
                });
            }

            self.settings.handleAfterInit(self.gMap, self.settings);

        },
        geoLocationGoogleAPI: function (pos, map) {
            var self = this;

            jQuery.post(this.settings.gmapGeolocationApiUrl + '?key=' + this.settings.gmapApiKey, function (success) {

                pos = {
                    lat: success.location.lat,
                    lng: success.location.lng
                };

                if (self.settings.gmapGeoLocationMarker) {
                    //infoWindow.setPosition(pos);
                    //infoWindow.setContent($.mage.__('Your Position.'))

                    var markerAnimation = null;

                    if (self.settings.gmapGeoLocationMarkerAnimation) {
                        markerAnimation = google.maps.Animation.DROP;
                    }

                    var marker = new google.maps.Marker({
                        position: pos,
                        map: map,
                        animation: markerAnimation,
                        title: $.mage.__('Your Geolocalized Position.'),
                        icon: self.settings.gmapGeoLocationMarkerImage,
                    });
                }

                self.settings.gmapGeolocationCurrent = pos;
                map.setZoom(self.settings.gmapGeoLocationZoom);
                map.setCenter(pos);

                self.initElementsAfterGeolocation();

                //self.getStoresByCurrentZoom(map);
            })
                .fail(function (err) {
                    self.initElementsAfterGeolocation();
                    //infoWindow.setPosition(pos);
                    //infoWindow.setContent('Geolocation with Google API service failed');
                });
        },
        getStoresByCurrentZoom: function (map) {
            var self = this;
            var southWestBounds = map.getBounds().getSouthWest();
            var northEastBounds = map.getBounds().getNorthEast();
            var loadedMarkers = "&loadedMarkers=";
            var mcOptions = {
                gridSize: self.settings.gmapMarkersClusterMarkerGridSize,
                maxZoom: self.settings.gmapMarkersClusterMarkerMaxZoom,
                //imagePath: 'images/m',
                zoomOnClick: self.settings.gmapMarkersClusterMarkerZoomOnClick,
                averageCenter: self.settings.gmapMarkersClusterMarkerAverageCenter,
                minimumClusterSize: self.settings.gmapMarkersClusterMarkerMinimumClusterSize,
                styles: [
                    {
                        url: self.settings.gmapMarkersClusterMarkerImage,
                        height: self.settings.gmapMarkersClusterMarkerImageHeight,
                        width: self.settings.gmapMarkersClusterMarkerImageWidth,
                        textColor: self.settings.gmapMarkersClusterMarkerTextColor,
                        textSize: self.settings.gmapMarkersClusterMarkerTextSize,
                        offsetWidth: self.settings.gmapMarkersClusterMarkerTextOffsetWidth,
                        offsetHeight: self.settings.gmapMarkersClusterMarkerTextOffsetHeight,
                        //anchor: [10 ,0],
                    }
                ],
            };

            // all loaded markers
            $.each(self.settings.gmapMarkers, function (key) {
                loadedMarkers += key + '_';
            });

            var param = 'ajax=1&lat1=' + southWestBounds.lat() + '&lng1=' + southWestBounds.lng() + '&lat2=' + northEastBounds.lat() + '&lng2=' + northEastBounds.lng() + loadedMarkers;

            if ($('input[name="pickupatstorechooser"]').size()) {
                param += '&pickup_in_store=' + self.settings.pickup_in_store;
            }

            if ($('input[name="rma_returntostore_active"]').size()) {
                param += '&return_in_store=1'
            }

            $.ajax({
                showLoader: true,
                url: self.settings.baseUrl + "storelocator/index/storesbycurrentzoom",
                data: param,
                type: "GET",
                cache: false,
                dataType: 'json'
            }).done(function (data) {

                $.each(data.items, function (key, value) {

                    var data = value;

                    if(self.settings.tag_filters_params && self.settings.tag_filters_params.enabled == '1' && window.return_to_store == '1'){
                        // tag filter enabled and only return to store section
                        var filterValues = self.settings.tag_filters_params.value;
                        var tags_settings = JSON.parse(filterValues);
                        var tags_array = [];
                        var marker_store_consider = [];

                        $.each(tags_settings, function( index, value ){
                            tags_array.push(value);
                        });

                        $.each(data.tags_id, function( i, val ){
                            if($.inArray(val, tags_array) >= 0){
                                marker_store_consider[i] = data.store_id;
                            }
                        });

                        if(marker_store_consider.length <= 0){
                            return;
                        }
                    }

                    if (!self.settings.gmapMarkers[value.store_id]) {

                        var pos = {
                            lat: parseFloat(value.latitude),
                            lng: parseFloat(value.longitude)
                        };

                        var markerMap = map;

                        if (self.settings.gmapMarkersClusterMarker || (self.settings.gmapSearchTags && self.settings.gmapActiveTagArray.length > 0)) {
                            markerMap = null;
                        }

                        var markerImage = self.settings.gmapMarkersMarkerImage;

                        if (value.marker_image) {
                            markerImage = self.settings.gmapStoresImageDir + value.marker_image;
                        }

                        var marker = new google.maps.Marker({
                            position: pos,
                            map: markerMap,
                            title: value.title,
                            icon: markerImage,
                        });

                        marker.addListener('click', function () {
                            self.markerclick = true;
                            if (self.infowindow) {
                                self.infowindow.close();
                            }

                            self.infowindow = new google.maps.InfoWindow({
                                content: self.settings.handleMarkerClick(value, self.settings)
                            });

                            self.infowindow.open(map, marker);
                            self.markerclick = false;
                        });

                        self.settings.gmapMarkers[value.store_id] = marker;
                        self.settings.gmapMarkersArray.push(
                            {
                                marker: marker,
                                data: value,
                            }
                        );

                        if (self.settings.gmapMarkersClusterMarker) {

                            if (!self.settings.gmapMarkerClusterMarkerEntity) {
                                self.settings.gmapMarkerClusterMarkerEntity = new MarkerClusterer(map, [], mcOptions);
                            }

                            self.settings.gmapMarkerClusterMarkerEntity.addMarker(marker, false);
                        }
                    }
                });
                self.settings.handleStoresList(self.gMap, self.settings);
            });
        },
        getDistanceFromStoreByCurrentPosition: function (markerArray) {

            var self = this;
            if (self.settings.gmapGeolocationCurrent && (self.settings.gmapGeoLocationDistance || self.settings.gmapGeoLocationDuration)) {

                var markerArrayDestination = [];
                var markerArrayElement = [];

                for (i = 0; i < markerArray.length; i++) {
                    if (!markerArray[i].data.getting_distance) {
                        markerArray[i].data.getting_distance = true;

                        markerArrayDestination.push(markerArray[i].marker.getPosition());
                        markerArrayElement.push(markerArray[i].data);
                    }
                }

                if (markerArrayDestination.length > 0) {

                    var service = new google.maps.DistanceMatrixService();
                    service.getDistanceMatrix({
                        origins: [self.settings.gmapGeolocationCurrent],
                        destinations: markerArrayDestination,
                        travelMode: self.settings.gmapGeoLocationTravelMode,
                        unitSystem: self.settings.gmapGeoLocationUnitSystem,
                        avoidHighways: false,
                        avoidTolls: false
                    }, function (response, status) {

                        self.settings.handleDistanceMatrixResponse(response, status, self.settings, markerArrayElement);

                    });
                }

            }
        },
        initElementsAfterGeolocation: function () {
            var self = this;

            self.gMap.addListener('idle', function () {
                if (!self.markerclick) {
                    self.settings.handleZoomChanged(self.gMap, self.settings);
                } else {
                    self.markerclick = false;
                }

            });

            if (self.settings.gmapGeoLocationGetDirections && self.settings.gmapGeolocationCurrent) {
                self.settings.handleGetDirections(self.gMap, self.settings, self);
            }

            self.handleRevealOnMap();
            self.handlePickUpInStoreSelection();
        },
        handleRevealOnMap: function () {

            var self = this;

            $(document).on('click', '.reveal-on-map', function (e) {

                e.preventDefault();
                var currentMarker = self.settings.gmapMarkers[$(this).attr("data-store-id")];
                new google.maps.event.trigger(currentMarker, 'click');

            });

        },
        handlePickUpInStoreSelection: function () {

            var self = this;

            $(document).on('click', '.pickup-in-store-selection', function (e) {
                e.preventDefault();
                var currentStoreId = $(this).attr("data-store-id");
                self.setStoreForPickup(currentStoreId);

            });

            $(document).on('click', '.return-to-store-selection', function (e) {
                e.preventDefault();
                var currentStoreId = $(this).attr("data-store-id");
                self.setStoreForReturn(currentStoreId);

            });

        },

        setStoreForReturn: function(storeId){
            var self = this;
            var param = 'ajax=1&store_id=' + storeId;

            if ($('input[name="rma_returntostore_active"]').size()) {
                param += '&return_in_store=1'
            }

            $.ajax({
                showLoader: true,
                url: self.settings.baseUrl + "storelocator/index/storedetailsbyid",
                data: param,
                type: "GET",
                cache: true,
                dataType: 'json'
            }).done(function (data) {
                if (data) {
                    var region = '';
                    if (data.region) {
                        region = ', ' + data.region;
                    }
                    window.currentSelectedStoreData = {
                        store_id: data.store_id,
                        title: data.title,
                        email: data.email,
                        street: data.street,
                        postcode: data.postcode,
                        city: data.city,
                        region: data.region,
                        region_id: data.region_id,
                        country_id: data.country,
                        phone: data.phone_1,
                        address: '</br>' + data.street + '</br>' + data.postcode + ' ' + data.city + region + ' (' + data.country + ')'
                    };

                    var containerData = $('#return-to-store-data');
                    var containerSummary = $('#return-to-store-summary');
                    var containerSummaryTitle = $('#return-to-store-summary').data('title');
                    var data = '';
                    var summary = '';

                    var addressTitle = window.currentSelectedStoreData.title;
                    var addressSummary = window.currentSelectedStoreData.address;
                    var addressTelephone = window.currentSelectedStoreData.phone;

                    if(containerData.length > 0){
                        $.each(window.currentSelectedStoreData, function( index, value ) {
                            data+= '<input name="rma_returntostore_'+index+'" type="hidden" id="selected-store-'+index+'" value="'+value+'" />';
                        });
                    }

                    summary+='<p><strong>'+addressTitle+'</strong></p>';
                    summary+='<p>'+addressSummary+' </p>';
                    summary+='<p>'+addressTelephone+'</p>';

                    containerData.html(data);
                    containerSummary.html(summary);
                    containerSummary.prepend( '<p id="return-to-store-summary-title"><strong>'+containerSummaryTitle+'</strong></p>');
                    $('.filoblu-storelocator-container').modal('closeModal');
                }
            });
        },

        setStoreForPickup: function (storeId) {
            var self = this;
            var param = 'ajax=1&store_id=' + storeId;

            if ($('input[name="rma_returntostore_active"]').size()) {
                param += '&return_in_store=1'
            }

            $.ajax({
                showLoader: true,
                url: self.settings.baseUrl + "storelocator/index/storedetailsbyid",
                data: param,
                type: "GET",
                cache: true,
                dataType: 'json'
            }).done(function (data) {
                if (data) {
                    var region = '';
                    if (data.region) {
                        region = ', ' + data.region;
                    }
                    var currentSelectedStoreData = {
                        store_id: data.store_id,
                        title: data.title,
                        email: data.email,
                        street: data.street,
                        postcode: data.postcode,
                        city: data.city,
                        region: data.region,
                        region_id: data.region_id,
                        country_id: data.country,
                        phone: data.phone_1,
                        address: '</br>' + data.street + '</br>' + data.postcode + ' ' + data.city + region + ' (' + data.country + ')'
                    };
                    selectedStoreData(currentSelectedStoreData);
                    $('.filoblu-storelocator-container').modal('closeModal');
                }
            });

        },
    }
    ;

    return window.FiloBlu.StoreLocator;
})
;
//});

function GetIEVersion() {
    var sAgent = window.navigator.userAgent;
    var Idx = sAgent.indexOf("MSIE");

    // If IE, return version number.
    if (Idx > 0)
        return parseInt(sAgent.substring(Idx+ 5, sAgent.indexOf(".", Idx)));

    // If IE 11 then look for Updated user agent string.
    else if (!!navigator.userAgent.match(/Trident\/7\./))
        return 11;

    else
        return 0; //It is not IE
}