﻿if (typeof Leapfrog === "undefined") {
    Leapfrog = {}
}
Leapfrog.GoogleMap = function() {
    var mapConstruct = this;
    this._map = false;
    this.selectedLocation = false;
    this.globalMarkers = new Array();
    this.globalLocations = new Array();
    this.resultsList = $j('#results-list');
    this.overlayMarker = false;
    this.mapPoint = null;
    this.searchBounds = "";
    this.defaultFacilityImagePath = "/widgets/locator/images/default-facility.gif";

    this.getResults = function(searchText) {
        var searchType = $j('#hidDV1').val();
        var searchId = $j('#hidDV2').val();

        var filterCheckboxes = $j(".search-area input[type=checkbox]");
        var types = "";

        var facilityTypeCheckboxes = $j(".search-area input[type=checkbox]");
        facilityTypeCheckboxes.each(function() {
            if (this.value != "")
                types += this.value + "-";
        });

        types = types.substring(0, types.length - 1);

        if (filterCheckboxes) {
            types = "";
            filterCheckboxes.each(function() {
                if (this.checked && this.value != "")
                    types += (this.value + '-');
            });

            if (types.length != 0)
                types = types.substring(0, types.length - 1);
        }

        $j.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/global/webservices/FetchFacilityLocatorResults.aspx/FetchFacilities",
            data: "{'search': '" + searchText.replace("'", "\\'") + "','searchType': '" + searchType + "','searchId': '" + searchId + "','facilityTypeFilter': '" + types + "'}",
            dataType: "json",
            success: function(data, msg) {
                var results = eval('(' + data.d + ')');
                $j('#results-list').attr('scrollTop', 0);
                mapConstruct.showResults(results, searchText);
            },
            error: function() { alert("fail") }
        });
    }

    this.hideResults = function(results) {
        $j(".scroll-down").hide(300);
        $j(".scroll-up").hide(300);
        mapConstruct.resultsList.slideUp(500, function() { mapConstruct.showResults(results); });
        mapConstruct.resultsList.get(0).innerHTML = "";
    }

    this.showNoResults = function() {
        var jLi = $j('#no-result-template');
        var newLi = $j(jLi.get(0).cloneNode(true));
        newLi.attr("id", "no-result");
        mapConstruct.resultsList.get(0).appendChild(newLi.get(0));
        mapConstruct.resultsList.slideDown("slow");

        this._map.setCenter(new GLatLng(37.926868, -97.294922));
        this._map.setZoom(3);

        while (mapConstruct._map.getPane(G_MAP_MARKER_PANE).hasChildNodes())
            mapConstruct._map.getPane(G_MAP_MARKER_PANE).removeChild(mapConstruct._map.getPane(G_MAP_MARKER_PANE).lastChild);
    }

    this.showResults = function(results, searchText) {
        while (mapConstruct._map.getPane(G_MAP_MARKER_PANE).hasChildNodes())
            mapConstruct._map.getPane(G_MAP_MARKER_PANE).removeChild(mapConstruct._map.getPane(G_MAP_MARKER_PANE).lastChild);

        var jResultsList = $j('#results-list');
        var resultsList = jResultsList.get(0);

        if (jResultsList.is(":visible")) {
            mapConstruct.hideResults(results);
            return;
        }

        if (!results.length || results.length == 0) {
            mapConstruct.showNoResults();
            return;
        }

        resultsList.innerHTML = "";

        var bounds = new GLatLngBounds;

        for (var i = 0; i < results.length; i++) {
            var facility = results[i];
            var letter = String.fromCharCode(i%26 + 97);
            var number = (i > 25) ? '1' : '';
            var iconSrc = "/widgets/locator/images/labeled-pins/" + facility.KindredFacilityType.Color + "-" + letter + number + ".gif"

            var jLi = $j('#result-template');
            var newLi = $j(jLi.get(0).cloneNode(true));
            newLi.get(0).internalId = i;

            newLi.attr('id', "location_" + facility.Id);

            // Get src of correct pin
            newLi.find(".result-icon:first").attr("src", iconSrc);
            newLi.find("h2:first").text(facility.FacilityName);

            //build address
            var address = "";
            address += facility.Address + " ";
            if (facility.Address2 != "")
                address += facility.Address2 + " ";
            address += facility.City + ", ";
            address += facility.State + " ";
            address += facility.PostalCode;

            newLi.find(".addr").text(address);
            
            if (facility.Phone != "")
				newLi.find(".phone-number").text(facility.Phone);

            newLi.find(".dir-input-area").attr("id", "dir-input-area" + i);
            newLi.find("input.dir-input").attr("id", "dir-input" + i);
            newLi.find("input.dir-input").keypress(function(e) {
                if (e.keyCode == 13) {
                    mapConstruct.submitDirections($j(this));
                    return false;
                }
                //e.stopImmediatePropagation();
                //e.preventDefault();
            });
            newLi.find(".dir").attr("id", "dir" + i);
            newLi.find(".dir a").attr("id", "dir-link" + i);
            newLi.find(".dir a").click(function() { mapConstruct.expandDirections($j(this)); return false; });
            newLi.find(".dir-input-area .btn-get-directions").click(function() { mapConstruct.submitDirections($j(this)); return false; });

            var url = facility.WebsiteUrl;
            if (url.indexOf("http://") == -1)
                url = "http://" + url;
            newLi.find(".site").attr("href", url);
            newLi.find(".site").text(facility.WebsiteUrl);
            //newLi.find(".site").click(function() { });


            resultsList.appendChild(newLi.get(0));
            if (i == 0)
                newLi.find(".dir a").click();
            mapConstruct.globalLocations[i] = newLi;

            var latLng = new GLatLng(parseFloat(facility.Latitude), parseFloat(facility.Longitude));
            bounds.extend(latLng);

            var marker = mapConstruct.getMarker(latLng, facility, iconSrc, i);
            this._map.addOverlay(marker);
        }

        //        $j.ajax({
        //              type: "POST",
        //              contentType: "application/json; charset=utf-8",
        //              url: "/global/webservices/FetchFacilityLocatorResults.aspx/FetchLatitudeLongitueForSearchTerm",
        //              data: "{'search': '" + searchText.replace("'","\\'") + "'}",
        //              dataType: "text",
        //              success: function(data, msg) {
        //                mapConstruct.searchBounds = eval('(' + data + ')').d;
        //              },
        //              async: false
        //            });

        var searchLat = "";
        var searchLong = "";
        if (mapConstruct.searchBounds != "") {
            searchLat = mapConstruct.searchBounds.split(',')[0];
            searchLong = mapConstruct.searchBounds.split(',')[1];
            var latLong = new GLatLng(parseFloat(searchLat), parseFloat(searchLong));
            bounds.extend(latLong);
        }

        this._map.setCenter(new GLatLng((bounds.getSouthWest().lat() + bounds.getNorthEast().lat()) / 2, (bounds.getSouthWest().lng() + bounds.getNorthEast().lng()) / 2));

        // 16 is the closest we want to zoom in
        var zoomLevel = 16;
        if (parseInt(this._map.getBoundsZoomLevel(bounds)) < 16)
            zoomLevel = this._map.getBoundsZoomLevel(bounds);
        this._map.setZoom(zoomLevel);

        mapConstruct.highlightLocations();
        inputDefaultSwitch();

        jResultsList.slideDown("slow");
        $j(".scroll-down").show("slow");
        $j(".scroll-up").show("slow");

        if ($j.browser.msie && parseInt($j.browser.version) < 7) {
            DD_belatedPNG.fix('.blpng');
        }
    }

    this.submitDirections = function(input) {
        var input = input.parent().find("input.dir-input");
        var address = input.closest("li").find(".addr").text();
        var directionsQuery = "from: " + input.val();
        directionsQuery += " to: " + address;
        window.open("http://maps.google.com/maps?q=" + directionsQuery);
        return false;
    }

    this.expandDirections = function(inputArea) {
        var me = inputArea;

        // 'degrade' show/hide effect in IE7 to slideUp/slideDown becaue the rounded textboxes dont work.
        if ($j.browser.msie && parseInt($j.browser.version) == 7) {
            mapConstruct.resultsList.children().each(function() {
                if (me.closest("li").get(0) != $j(this).get(0))
                    $j(this).find(".dir-input-area").slideUp("slow");
            });
            me.parent().siblings(".dir-input-area").slideToggle("slow");
        }
        else {
            mapConstruct.resultsList.children().each(function() {
                if (me.closest("li").get(0) != $j(this).get(0))
                    $j(this).find(".dir-input-area").hide("slow");
            });
            me.parent().siblings(".dir-input-area").toggle("slow");
        }
        return false;
    }

    this.getMarker = function(latLng, facilityEntity, iconSrc, internalId) {
        var icon = new GIcon(G_DEFAULT_ICON);
        icon.image = iconSrc;
        icon.shadow = "/global/images/transparent.gif";
        icon.iconSize = new GSize(27, 33);
        icon.iconAnchor = new GPoint(6, 21);
        icon.infoWindowAnchor = new GPoint(0, 0);
        icon.imageMap = [13, 28, 18, 22, 22, 15, 21, 7, 14, 3, 10, 1, 3, 6, 0, 14, 3, 21, 9, 28];

        var marker = new GMarker(latLng, icon);
        marker.markerContent = mapConstruct.getMarkerContent(facilityEntity);

        GEvent.addListener(marker, "click_action", function() {
            mapConstruct.showMarkerInfo(marker);
        });
        GEvent.addListener(marker, "click", function() {
            mapConstruct.activateMarker(mapConstruct.globalLocations[internalId]);
        });

        mapConstruct.globalMarkers[internalId] = marker;
        return marker;
    }

    this.showMarkerInfo = function(marker) {
        mapConstruct.mapPoint = mapConstruct._map.fromLatLngToDivPixel(marker.getPoint());
        var markerInfo = mapConstruct.getMapMarkerInfo(marker);
        mapConstruct._map.getPane(G_MAP_MARKER_PANE).appendChild(markerInfo);
        markerInfo.style.display = "block";
        this.positionWindow(markerInfo, markerInfo.marker);
    }

    this.getMapMarkerInfo = function(marker) {
        var overlay;
        if (!mapConstruct.overlayMarker) {
            overlay = $j('<div id="mapoverlay" style="display: none;"/>').html($j('#overlay-template').get(0).innerHTML);
            $j('body').append(overlay);
        } else {
			overlay = $j(mapConstruct.overlayMarker);
        }

        var imagePath = mapConstruct.defaultFacilityImagePath;
        if (marker.markerContent.ImagePath && marker.markerContent.ImagePath != "")
            imagePath = marker.markerContent.ImagePath;
        overlay.find(".facility-image").css("background-image", "url('" + imagePath + "')");
        overlay.find(".facility-image").css("background-repeat", "no-repeat");
        overlay.find("h3").text(marker.markerContent.facilityname);
        overlay.find(".facility-type").text(marker.markerContent.facilitytype.replace("Hospitals", "Hospital").replace("Nursing Centers", "Nursing Center"));
        overlay.find(".street-address").text(marker.markerContent.streetaddress);
        overlay.find(".locality").text(marker.markerContent.locality);
        overlay.find(".region").text(marker.markerContent.region);
        overlay.find(".postal-code").text(marker.markerContent.postalcode);

		if (marker.markerContent.phone != null)
			overlay.find(".phone").text(marker.markerContent.phone);

        if (marker.markerContent.url != null)
            overlay.find(".website").html("<a href='http://" + marker.markerContent.url + "' target='_blank'>" + marker.markerContent.url + "</a>");
        else
            overlay.find(".website").hide();

        mapConstruct.overlayMarker = overlay.get(0);
        overlay.find(".close").click(function() { mapConstruct.closeMarker(); return false; });
        overlay.get(0).marker = marker;

        return overlay.get(0);
    }

    this.positionWindow = function(markerInfo, marker) {
        var yPos = parseInt(mapConstruct.mapPoint.y) - markerInfo.offsetHeight - 40;
        var xPos = parseInt(mapConstruct.mapPoint.x) - 46;
        var e = null;
        markerInfo.style.top = yPos + "px";
        markerInfo.style.left = xPos + "px";
        e = new GLatLng(marker.getPoint().lat(), marker.getPoint().lng());
        mapConstruct._map.panTo(e);
    }

    this.getMarkerContent = function(facilityEntity) {
        var content = new Object();

        content.imagepath = "";
        if (facilityEntity.ImagePath != "")
            content.imagepath = facilityEntity.ImagePath;

		if (facilityEntity.Phone != "")
			content.phone = facilityEntity.Phone;

        content.url = "";
        if (facilityEntity.WebsiteUrl != "") {
            content.url = facilityEntity.WebsiteUrl;
        }
        content.facilityname = facilityEntity.FacilityName;
        content.facilitytype = facilityEntity.KindredFacilityType.Type;

        var address = "";
        address += facilityEntity.Address + " ";
        if (facilityEntity.Address2)
            address += facilityEntity.Address2 + " ";

        content.streetaddress = address;
        content.locality = facilityEntity.City;
        content.region = facilityEntity.State;
        content.postalcode = facilityEntity.PostalCode;

        return content;
    }

    this.highlightLocations = function() {
        mapConstruct.resultsList.children().each(function() {
            $j(this).mouseover(function() { $j(this).addClass("hover"); });
            $j(this).mouseout(function() { $j(this).removeClass("hover"); });
            $j(this).click(function(e) {
                if (e.target.tagName.toLowerCase() != "a")
                    mapConstruct.activateMarker($j(this));
            });
        });
    }

    this.activateMarker = function(a) {
        if (mapConstruct.selectedLocation instanceof $j) {
            if (mapConstruct.selectedLocation.get(0) == a.get(0))
                return false;
        }
        a.addClass("selected");
        GEvent.trigger(mapConstruct.globalMarkers[a.get(0).internalId], "click_action");
        if (mapConstruct.selectedLocation) {
            mapConstruct.selectedLocation.removeClass("selected");
        }
        mapConstruct.selectedLocation = a;
    }

    this.deactivateMarker = function(a) {
        a.removeClass("selected");
        mapConstruct.selectedLocation = false;
    }

    this.closeMarker = function() {
        $j(mapConstruct.overlayMarker).hide();
        mapConstruct.deactivateMarker($j("#location_" + mapConstruct.overlayMarker.marker.internalId));
        return false;
    }

    this.setAutoCompleter = function(textboxId, filterCheckboxes) {
        var types = "";

        var facilityTypeCheckboxes = $j(".search-area input[type=checkbox]:checked");
        facilityTypeCheckboxes.each(function() {
            if (this.value != "")
                types += this.value + "-";
        });

        types = types.substring(0, types.length - 1);

        if (filterCheckboxes) {
            types = "";
            filterCheckboxes.each(function() {
                if (this.checked && this.value != "")
                    types += (this.value + '-');
            });

            if (types.length != 0)
                types = types.substring(0, types.length - 1);
        }

        var tb = $j('#' + textboxId).autocomplete({
            serviceUrl: '/global/webservices/FacilityLocatorAutocomplete.ashx',
            minChars: 2,
            delimiter: /(;)\s*/, // regex or character
            maxHeight: 400,
            width: 300,
            deferRequestBy: 500, //miliseconds
            params: { 'facilityTypes': types }, //aditional parameters
            onSelect: function(value, data) { mapConstruct.getResults(value); }
        });
        $j('#' + textboxId).keypress(function(e) {
            var code;
            if (!e) var e = window.event;
            if (e.keyCode)
                code = e.keyCode;
            else if (e.which)
                code = e.which;
            if (code == 13) {
                return false;
            }
        });
        $j('#' + textboxId).click(function(e) { this.value = ''; });
    }

    this.draw = function() {
        if (!this._map) {
            this._map = new GMap2($j('#map').get(0));
            this._map.addControl(new GLargeMapControl3D());
            this._map.addControl(new GScaleControl());
            this._map.setCenter(new GLatLng(37.926868, -97.294922));
            this._map.setZoom(3);
            if (Leapfrog.Detector.isiPhone()) {
                this._map.disablePinchToZoom()
            }
            return true
        }

        if (this._queryString === "") {
            this._map.setCenter(new GLatLng(37.926868, -97.294922))
        }
    }
};