window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.searchSystem = window.eviivo.searchSystem ? window.eviivo.searchSystem : {};
window.eviivo.searchSystem.largeMapView = window.eviivo.searchSystem.mapView ? window.eviivo.searchSystem.largeMapView : {};

window.eviivo.searchSystem.largeMapView = function (jQuery) {
    var defaultOptions = {
        resources: {
            fullScreen: "Full screen",
            thirtyPercent: "Exit full screen",
            loadingText: "Loading property information please wait.",
            mapNoResultsText: "No results found, please refine your search using the search criteria and filters on the left"
        },
        disableAllPropertiesDisplay: true
    };

    var options,
        infoBubble,
        infoBubble2,
        map,
        markers = [],
        markersBubbleInfo = {},
        mapBounds,
        MAP_CANVAS_ID = "map-canvas",
        MAP_MARKER_TOKEN = "mapMarker",
        mapLocations,
        bubbleTemplate1,
        bubbleTemplate2,
        ieMarkerDefault,
        msIe;

    ///<summary>Main init method of the eviivo.searchSystem.mapView object</summary>
    ///<param name="settings">external settings</param>
    function init(settings) {
        options = jQuery.extend(defaultOptions, settings);
        markers = [];

        detectIeUserAgent();

        //in case view type is map we initialize the map from the start
        if (eviivo.searchSystem.views.getViewType() == 3) {
            var mapLocationsValues = jQuery('#results-map-locations').val();
            if (mapLocationsValues != "" && mapLocationsValues != null) {
                mapLocations = JSON.parse(mapLocationsValues);
                mapLocations = mapLocations.results;
            }

            loadMapScript();
        }
    }

    function generatedoTTemplate() {
        if (jQuery("#property-info-bubble-template1").length > 0 && jQuery("#property-info-bubble-template2").length > 0) {
            bubbleTemplate1 = doT.template(jQuery("#property-info-bubble-template1").html());
            bubbleTemplate2 = doT.template(jQuery("#property-info-bubble-template2").html());
        }
    }

    function detectIeUserAgent() {
        msIe = false;
        var ua = window.navigator.userAgent;
        var oldIe = ua.indexOf('MSIE ');
        var newIe = ua.indexOf('Trident/');

        if ((oldIe > -1) || (newIe > -1)) {
            msIe = true;
        }
    }

    ///<summary>Loading the google maps script</summary>
    function loadMapScript(data) {
        if (data != null) {
            mapLocations = data;
        }
        if ((typeof (google) == "undefined" || typeof (google.maps) == "undefined") && options.googleMapsApiUrl != "" && options.googleMapsApiUrl != null) {
            //use script tag appender (much safer and much simpler)
            jQuery(document.body).append(jQuery("<script src=\"/Scripts/infobubble.js\" type=\"text/javascript\" />"));
            jQuery(document.body).append(jQuery("<script src=\"" + options.googleMapsApiUrl + "window.eviivo.searchSystem.largeMapView.loadMap\" type=\"text/javascript\" />"));
        } else {
            //in case the map is already exposed we only refresh the data
            clearMarkers();
            jQuery(".mod-map-view-wrap").removeClass("hidden");
            jQuery(".mod-map-no-results").remove();
            //This is to diplay the map legend
            displayMapLegend();
            if (mapLocations != null && mapLocations.length > 0) {
                loadProperties();
            }
            else {
                if (jQuery(".mod-map-no-results").length == 0) {
                    jQuery(".mod-map-view-wrap").append("<div class='mod-map-no-results'>" + options.resources.mapNoResultsText + "</div>");
                }
            }

        }
        return true;
    }

    function setCenter() {
        var lat = jQuery("#results-centerpoint-lat").val();
        var lng = jQuery("#results-centerpoint-lng").val();
        var radius = jQuery("#results-centerpoint-rad").val();
        var center = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
        new google.maps.Circle({
            strokeColor: '#000000',
            strokeOpacity: 0.8,
            strokeWeight: 1,
            fillColor: '#ffffff',
            fillOpacity: 0.25,
            radius: radius * 1609.0,
            center: center,
            map: map
        });
        map.setCenter(center);
        map.setZoom(Math.round(15 - Math.log(radius) / Math.LN2));
    }

    ///<summary>Setup map and loop round JSON results to render property markers</summary>
    function loadMap() {
        var mapCanvas = document.getElementById(MAP_CANVAS_ID);
        if (mapCanvas == null) {
            return;
        }
        //Generates the dot templates that will be used to fill the available properties markers
        generatedoTTemplate();
        //This is to diplay the map legend
        displayMapLegend();

        //once the google maps are loaded expand the cutom marker type
        prototypecustomMarker();

        jQuery(".mod-map-view-wrap").removeClass("hidden");
        jQuery(".mod-map-no-results").remove();
        map = new google.maps.Map(document.getElementById(MAP_CANVAS_ID), {
            streetViewControl: false,
            panControl: false,
            zoomControl: true,
            mapTypeControl: false,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        ieMarkerDefault = new google.maps.MarkerImage(options.pinSource + "/images/marker-default.png");

        mapBounds = new google.maps.LatLngBounds();

        if (mapLocations != null && mapLocations.length > 0) {
            loadProperties();
        } else {
            setCenter();
            if (jQuery(".mod-map-no-results").length == 0) {
                jQuery(".mod-map-view-wrap").append("<div class='mod-map-no-results'>" + options.resources.mapNoResultsText + "</div>");
            }
       
        }

        if (options.disableAllPropertiesDisplay == false) {
            loadAllProperties();
        }

        //info bubble for large view
        infoBubble = new InfoBubble({
            maxWidth: 300,
            minWidth: 300,
            minHeight: 352,
            maxHeight: 352,
            boxStyle: {
                width: "300px",
                height: "350px",
                border: "0px solid transparent"
            },
            map: map,
            disableAutoPan: false,
            hideCloseButton: false,
            arrowPosition: 50,
            padding: 0,
            closeSrc: "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOC4xLjEsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiDQoJIHdpZHRoPSIzMXB4IiBoZWlnaHQ9IjMycHgiIHZpZXdCb3g9IjAgMCAzMSAzMiIgZW5hYmxlLWJhY2tncm91bmQ9Im5ldyAwIDAgMzEgMzIiIHhtbDpzcGFjZT0icHJlc2VydmUiPg0KPGc+DQoJPHJlY3QgeD0iOS41IiB5PSIxMC41IiBmaWxsPSIjRkZGRkZGIiB3aWR0aD0iMTMiIGhlaWdodD0iMTMiLz4NCgk8cGF0aCBmaWxsPSIjQjJCMkIyIiBkPSJNMjIsMTF2MTJIMTBWMTFIMjIgTTIzLDEwSDl2MTRoMTRWMTBMMjMsMTB6Ii8+DQo8L2c+DQo8cG9seWdvbiBmaWxsPSIjQjJCMkIyIiBwb2ludHM9IjE5LjIsMTUuMiAxNy44LDEzLjggMTYsMTUuNiAxNC4yLDEzLjggMTIuOCwxNS4yIDE0LjYsMTcgMTIuOCwxOC44IDE0LjIsMjAuMiAxNiwxOC40IDE3LjgsMjAuMiANCgkxOS4yLDE4LjggMTcuNCwxNyAiLz4NCjwvc3ZnPg0K"
        });

        //info bubble for small view (mouse hover)
        infoBubble2 = new InfoBubble({
            maxWidth: 190,
            maxHeight: 100,
            boxStyle: {
                width: "",
                height: "100px",
                border: "0px solid transparent"
            },
            map: map,
            disableAutoPan: true,
            hideCloseButton: true,
            arrowPosition: 50,
            padding: 0,
            closeSrc: "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOC4xLjEsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiDQoJIHdpZHRoPSIzMXB4IiBoZWlnaHQ9IjMycHgiIHZpZXdCb3g9IjAgMCAzMSAzMiIgZW5hYmxlLWJhY2tncm91bmQ9Im5ldyAwIDAgMzEgMzIiIHhtbDpzcGFjZT0icHJlc2VydmUiPg0KPGc+DQoJPHJlY3QgeD0iOS41IiB5PSIxMC41IiBmaWxsPSIjRkZGRkZGIiB3aWR0aD0iMTMiIGhlaWdodD0iMTMiLz4NCgk8cGF0aCBmaWxsPSIjQjJCMkIyIiBkPSJNMjIsMTF2MTJIMTBWMTFIMjIgTTIzLDEwSDl2MTRoMTRWMTBMMjMsMTB6Ii8+DQo8L2c+DQo8cG9seWdvbiBmaWxsPSIjQjJCMkIyIiBwb2ludHM9IjE5LjIsMTUuMiAxNy44LDEzLjggMTYsMTUuNiAxNC4yLDEzLjggMTIuOCwxNS4yIDE0LjYsMTcgMTIuOCwxOC44IDE0LjIsMjAuMiAxNiwxOC40IDE3LjgsMjAuMiANCgkxOS4yLDE4LjggMTcuNCwxNyAiLz4NCjwvc3ZnPg0K"
        });
    }

    //Refresh map view
    function refreshMapOnResize() {
        google.maps.event.trigger(map, 'resize');
    }

    function loadAllProperties() {
        map.data.setStyle({
            icon: "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOC4xLjEsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiDQoJIHdpZHRoPSI3cHgiIGhlaWdodD0iN3B4IiB2aWV3Qm94PSIwIDAgNyA3IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCA3IDciIHhtbDpzcGFjZT0icHJlc2VydmUiPg0KPHBhdGggZmlsbD0iIzM4M0EzRCIgZD0iTTMuNSwwQzEuNiwwLDAsMS42LDAsMy41UzEuNiw3LDMuNSw3UzcsNS40LDcsMy41UzUuNCwwLDMuNSwweiIvPg0KPC9zdmc+DQo="//options.pinSource + "/images/marker-highlight.png"
        });

        map.data.loadGeoJson(options.ajaxBaseUrl + '?channelShortName=toprooms&batchIndex=0&format=json');
        map.data.loadGeoJson(options.ajaxBaseUrl + '?channelShortName=toprooms&batchIndex=1&format=json');
        map.data.loadGeoJson(options.ajaxBaseUrl + '?channelShortName=toprooms&batchIndex=2&format=json');

        // Set mouseover event for each feature.
        map.data.addListener('click', smallMarkerMouseOverHandler);
    }

    function smallMarkerMouseOverHandler(e) {
        showSmallBubble(e.feature["A"]);
    }

    function loadProperties() {
        mapBounds = new google.maps.LatLngBounds();
        if (mapLocations != null && mapLocations.length > 0) {
            jQuery.each(mapLocations, function (k, v) {
                addMarker(parseFloat(v.lat), parseFloat(v.lng), v.snm, v.prc);
                markersBubbleInfo[v.snm] = v;
            });

            map.fitBounds(mapBounds);
        }
        else {
            if (jQuery(".mod-map-no-results").length == 0) {
                jQuery(".mod-map-view-wrap").append("<div class='mod-map-no-results'>" + options.resources.mapNoResultsText + "</div>");
            }
        }
    }

    function clearMarkers() {
        jQuery.each(markers, function (i, v) {
            v.setMap(null);
        });
        markers = [];
    }

    // Add a marker to the map and push to the array.
    function addMarker(latitude, longitude, shortName, priceText) {
        if (latitude != 0 && longitude != 0) {
            var location = new google.maps.LatLng(latitude, longitude);

            var markerId = MAP_MARKER_TOKEN + shortName;
            var marker;
            if (priceText != "") {
                marker = new customMarker({
                    position: location,
                    map: map,
                    content: priceText,
                    className: "eviivo-price-pin",
                    id: markerId
                });
            } else {
 
                // Adds markers to the map.
                // Marker sizes are expressed as a Size of X,Y where the origin of the image
                // (0,0) is located in the top left of the image.
                // Origins, anchor positions and coordinates of the marker increase in the X
                // direction to the right and in the Y direction down.
                const markerImage = {
                    url: "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjIiIGhlaWdodD0iMzYiIHZpZXdCb3g9IjAgMCAyMiAzNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGcgY2xpcC1wYX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x0ZXIgaWQ9ImZpbHRlcjBfZCIgeD0iMS4xNzk5MyIgeT0iMC4xOTk5NTEiIHdpZHRoPSIyMS42Nzk4IiBoZWlnaHQ9IjM1LjYxIiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiI+CjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+CjxmZUNvbG9yTWF0cml4IGluPSJTb3VyY2VBbHBoYSIgdHlwZT0ibWF0cml4IiB2YWx1ZXM9IjAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDEyNyAwIiByZXN1bHQ9ImhhcmRBbHBoYSIvPgo8ZmVPZmZzZXQgZHg9IjEiLz4KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iMSIvPgo8ZmVDb2xvck1hdHJpeCB0eXBlPSJtYXRyaXgiIHZhbHVlcz0iMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMC4xNSAwIi8+CjxmZUJsZW5kIG1vZGU9Im5vcm1hbCIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIHJlc3VsdD0iZWZmZWN0MV9kcm9wU2hhZG93Ii8+CjxmZUJsZW5kIG1vZGU9Im5vcm1hbCIgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iZWZmZWN0MV9kcm9wU2hhZG93IiByZXN1bHQ9InNoYXBlIi8+CjwvZmlsdGVyPgo8Y2xpcFBhdGggaWQ9ImNsaXAwIj4KPHJlY3Qgd2lkdGg9IjIyIiBoZWlnaHQ9IjM2IiBmaWxsPSJ3aGl0ZSIvPgo8L2NsaXBQYXRoPgo8L2RlZnM+Cjwvc3ZnPgo=",
                    // This marker is 20 pixels wide by 32 pixels high.
                    size: new google.maps.Size(22, 36),
                    // The origin for this image is (0, 0).
                    origin: new google.maps.Point(0, 0),
                    // The anchor for this image is the base of the mappin at (11, 32). Half the width of the 22px
                    anchor: new google.maps.Point(11, 36),
                };

                marker = new google.maps.Marker({
                    name: shortName,
                    position: location,
                    map: map,
                    id: markerId,
                    zIndex: 9999,
                    icon: markerImage
                });


            }

            google.maps.event.addListener(marker, 'click', markerMouseClickHandler);

            mapBounds.extend(location);
            markers.push(marker);
        }
    }

    function markerMouseClickHandler() {
        var info = markersBubbleInfo[this.id.replace(MAP_MARKER_TOKEN, "")];

        if (info.ism == false) {
            infoBubble.setMaxHeight(305);
            infoBubble.setMinHeight(305);
            infoBubble.boxStyle.height = 300;
        }
        else {
            infoBubble.setMaxHeight(352);
            infoBubble.setMinHeight(352);
            infoBubble.boxStyle.height = 350;
        }

        if (infoBubble.isOpen()) {
            infoBubble.close(map, this);
        }
        if (infoBubble2.isOpen()) {
            infoBubble2.close(map);
        }

        var resultText = bubbleTemplate1(info);
        infoBubble.setContent(resultText);
        infoBubble.open(map, this);

        google.maps.event.addListener(infoBubble, 'domready', function() {
            $(".cp-tip").tooltip({
                position: {
                    my: "center bottom-15",
                    at: "center top",
                    using: function (position, feedback) {
                        $(this).css(position);
                        $("<div>")
                            .addClass("arrow")
                            .addClass(feedback.vertical)
                            .addClass(feedback.horizontal)
                            .appendTo(this);
                    }
                },
                content: function () {
                    return $(this).prop('title');
                }
            }); 
        });
    }

    function showSmallBubble(obj) {
        if (infoBubble.isOpen()) {
            infoBubble.close(map);
        }
        if (!infoBubble2.isOpen()) {
            infoBubble2.open(map);
        }

        var content = bubbleTemplate2(obj);
        infoBubble2.refreshBubble({ content: content, position: new google.maps.LatLng(obj.lat, obj.lng) });
    }

    function customMarker(settings) {
        this.latlng_ = settings.position;
        this.content = settings.content;
        this.className = settings.className;
        this.id = settings.id;

        // Once the LatLng and text are set, add the overlay to the map.  This will
        // trigger a call to panes_changed which should in turn call draw.
        this.setMap(settings.map);
    }

    function prototypecustomMarker() {
        customMarker.prototype = new google.maps.OverlayView();

        customMarker.prototype.draw = function () {
            var me = this;

            // Check if the div has been created.
            var div = this.div_;
            if (!div) {
                // Create a overlay text DIV
                div = this.div_ = document.createElement('DIV');

                div.className = me.className;
                div.innerHTML = me.content;
                // Create the DIV representing our customMarker
                div.style.border = "none";
                div.style.position = "absolute";

                google.maps.event.addDomListener(div, "click", function () {
                    google.maps.event.trigger(me, "click");
                });

                google.maps.event.addDomListener(div, "mouseover", function () {
                    google.maps.event.trigger(me, "mouseover");
                });

                google.maps.event.addDomListener(div, "mouseout", function () {
                    google.maps.event.trigger(me, "mouseout");
                });

                // Then add the overlay to the DOM
                var panes = this.getPanes();
                panes.overlayImage.appendChild(div);
            }

            // Position the overlay 
            var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
            if (point) {
                div.style.left = point.x + 'px';
                div.style.top = point.y + 'px';
            }
        };

        customMarker.prototype.remove = function () {
            // Check if the overlay was on the map and needs to be removed.
            if (this.div_) {
                this.div_.parentNode.removeChild(this.div_);
                this.div_ = null;
            }
        };

        customMarker.prototype.getPosition = function () {
            return this.latlng_;
        };
    }
    
    function displayMapLegend() {
        var $mapControl = $(".map-controls");
        var classToToggle = "visualy-hidden";
        if (eviivo.utils.queryStringHelper.isSearchMode() && mapLocations != null && mapLocations.length > 0) {
            $mapControl.removeClass(classToToggle);
        } else {
            $mapControl.addClass(classToToggle);
        }
    }

    return {
        init: init,
        loadMap: loadMap,
        loadMapScript: loadMapScript,
        refreshMapOnResize: refreshMapOnResize
    };
}(jQuery);
