﻿(function($) {

    var nearestForPaging = [];
    var listPage = 0;

    $.fn.jsGMap = function(options) {
        if (!GBrowserIsCompatible()) {
            return;
        }
        settings = jQuery.extend({
            width: 800,
            height: 600
        }, options);

        var $this = $(this), WayPoints = [], attachedMarkers = [];
        var _clickedMarker = null, _visibleMarkerOverlay = null;
        $this.width(settings.width);
        $this.height(settings.height);


        var selectedMarkerIcon = new GIcon(G_DEFAULT_ICON);
        selectedMarkerIcon.iconSize = new GSize(45, 51);
        selectedMarkerIcon.image = "/gfx/hjertestarter.dk/googlemap/markers/defibrillatorSelectedMarker.png";
        selectedMarkerIcon.iconAnchor = new GPoint(22, 51);
        selectedMarkerIcon.shadow = selectedMarkerIcon.printShadow = null;
        $this.selectedMarker = new GMarker(new GLatLng(0, 0), { icon: selectedMarkerIcon, draggable: false })

        var positionIcon = new GIcon(G_DEFAULT_ICON);
        positionIcon.iconSize = new GSize(38, 41);
        positionIcon.image = "/gfx/hjertestarter.dk/googlemap/markers/markerCurrentPosition.png";
        positionIcon.iconAnchor = new GPoint(19, 41);
        positionIcon.shadow = positionIcon.printShadow = null;
        $this.positionMarker = new GMarker(new GLatLng(0, 0), {
    //    icon: positionIcon,
          draggable: false })

        $this.positionMarker.hide();
        $this.selectedMarker.hide()
        $this.gmap = new GMap2(document.getElementById($this.attr('id')));
        $this.gmap.addOverlay($this.selectedMarker);
        $this.gmap.addOverlay($this.positionMarker);
        $this.geocoder = new GClientGeocoder();

        var minMapScale = 7;
        var maxMapScale = 19;
        var mapTypes = $this.gmap.getMapTypes();
        for (var i = 0; i < mapTypes.length; i++) {
            mapTypes[i].getMinimumResolution = function() { return minMapScale; }
            mapTypes[i].getMaximumResolution = function() { return maxMapScale; }
        }

        $this.gmap.setCenter(new GLatLng(56.3, 11), 7);
        var customUI = $this.gmap.getDefaultUI();
        customUI.controls.scalecontrol = false;
        customUI.controls.largemapcontrol3d = false;
        $this.gmap.setUI(customUI);
        $this.gmap.addControl(new GScaleControl(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10, 20)));
        $this.gmap.addControl(new GLargeMapControl3D(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(5, 130)));
        $("#activityMap").append($("#searchtemplate").html());
        $("#activityMap .txtSearchQueryAddress").focus();
        $("#activityMap .txtSearchQueryAddress").keydown(function(e) {
            if (e.keyCode == 13) {
                $("#activityMap .btnSearch").trigger("click");
            }
        });
        $("#activityMap").append($("#defibrillatorNetworktemplate").html());
        $("#activityMap").append($("#resultAsListtemplate").html());


        $("#activityMap .resultAsList .button").click(function() {

            var btn = $(this)
            var height = $("#activityMap .resultAsList .resultAsListResult .resultAsListResultItem").size() * 30;
            var top = 477 - height + 1;

            if ($("#activityMap .resultAsList").css("top") == "539px") {
                $this.infoOverlay.hideInfo()
                btn.height(28);
                $("#activityMap .resultAsList").animate({ top: top, height: top }, 300);
            } else {
                $("#activityMap .resultAsList").animate({ top: 539, height: 29 }, 300, function() { btn.height(29); });
            }

        });


        var markerCluster;
        $.fn.loadWayPoints = function(url) {
            $.ajax({
                url: url,
                cache: false,
                dataType: "json",
                success: function(jsonWayPoints) {
                    $this.addWayPoints(jsonWayPoints);
                },
                error: function(req, status, error) {
                    alert("err");
                }
            });
        }

        $.fn.addWayPoints = function(jsonWayPoints) {
            WayPoints = jsonWayPoints;
            $("#activityMap .defibrillatorNetwork strong").text(WayPoints.length);
            var icon = new GIcon(G_DEFAULT_ICON);
            icon.iconSize = new GSize(19, 22);
            icon.image = "/gfx/hjertestarter.dk/googlemap/markers/marker.png";
            icon.iconAnchor = new GPoint(8, 22);
            icon.shadow = icon.printShadow = null;
            icon.imageMap = [0, 0, 20, 0, 20, 20, 0, 20];

            for (var i = 0; i < WayPoints.length; i++) {
                var wp = WayPoints[i];
                wp.latlng = new GLatLng(wp.Latitude, wp.Longitude);
                wp.currentMarker = wp.marker = new GMarker(wp.latlng, { icon: icon, draggable: false });
                wp.marker.ID = wp.ID;
                wp.marker.index = i;
                wp.marker.FirmaID = wp.FirmaID;
                GEvent.addListener(wp.marker, 'click', $.fn.GMarkerClick);

                attachedMarkers.push(wp.marker);
            }
            markerCluster = new MarkerClusterer($this.gmap, attachedMarkers, { maxZoom: 15, gridSize: 80 });
        }

        $.fn.GMarkerClick = function() {
            //$("#activityMap .resultAsList").animate({ top: 539, height: 29 }, 300, function() { $("#activityMap .resultAsList .button").height(29); });
            if (_visibleMarkerOverlay == this)
                return;

            if (_clickedMarker != this) {
                $this.infoOverlay.update(this);
            }

            this.hide();

            //$this.gmap.removeOverlay(this)
            $this.selectedMarker.setLatLng(this.getLatLng())
            $this.selectedMarker.show();

            if ($("#activityMap .resultAsList").height() > '29') {
                $("#activityMap .resultAsList").animate({ top: 539, height: 29 }, 300, function() { });
            }
            
            var latlng = this.getLatLng();
            var bounds = $this.gmap.getBounds();
            var southWest = bounds.getSouthWest();
            var northEast = bounds.getNorthEast();


            var pixel = $this.gmap.fromContainerPixelToLatLng(new GPoint(1, 1))

            var newLat = (latlng.lat() + (northEast.lat() - southWest.lat()) / 2)
            //newLat = newLat + ((northEast.lat() - pixel.lat()) * -17);
            newLat = newLat + ((northEast.lat() - pixel.lat()) * -77);

            var newLng = (latlng.lng() + (northEast.lng() - southWest.lng()) / 2)
            //newLng = newLng + ((pixel.lng() - southWest.lng()) * -73);
            newLng = newLng + ((pixel.lng() - southWest.lng()) * -290);
            var newCenter = new GLatLng(newLat, newLng)

            var panto = newCenter//new GLatLng((latlng.lat() + ((northEast.lat() - southWest.lat()) / 20) * 7.0001), (latlng.lng() + ((northEast.lng() - southWest.lng()) / 20) * 7.8))
            var p1 = $this.gmap.fromLatLngToDivPixel($this.gmap.getCenter());
            var p2 = $this.gmap.fromLatLngToDivPixel(panto);


            var marker = this

            var moveEnd = GEvent.addListener($this.gmap, "moveend", function() {
                $this.gmap.addOverlay($this.infoOverlay);

                _clickedMarker = marker;
                _clickedMarker.hide();
                GEvent.removeListener(moveEnd);
            });


            if (p1.x == p2.x && p1.y == p2.y) {
                $this.gmap.addOverlay($this.infoOverlay);
                _clickedMarker = marker;
            } else {

                markerCluster.setDoCount();
                $this.gmap.setCenter(panto);

                markerCluster.getMarkersInViewport_();
            }
        }

        $.fn.searchGeocoder = function(address, successFunction) {
            if ($this.geocoder) {
                var searchAddress = address;

                return $this.geocoder.getLocations(searchAddress, successFunction);
            } else {
                return null;
            }
        }


        $.fn.showNearest = function(placemark) {
            if (placemark.Point) {
                placemark.Easting = placemark.Point.coordinates[0];
                placemark.Northing = placemark.Point.coordinates[1];
            }

            var nearest = [];
            for (var i = 0; i < WayPoints.length; i++) {
                nearest.push({ "distance": new GLatLng(placemark.Northing, placemark.Easting).distanceFrom(WayPoints[i].latlng), "arrPos": i })
            }


            nearest.sort(sort);

            $this.positionMarker.setLatLng(new GLatLng(placemark.Northing, placemark.Easting));


            for (var j = 0; j < 5; j++) {
                var latlngbounds = new GLatLngBounds();

                latlngbounds.extend(new GLatLng(placemark.Northing, placemark.Easting));

                for (var u = 0; u < (5 - j); u++) {
                    latlngbounds.extend(WayPoints[nearest[u].arrPos].latlng);
                }
                var sw = latlngbounds.getSouthWest();
                var ne = latlngbounds.getNorthEast();
                var swLAT = sw.lat() - (0.01348662805392 / settings.width * 100);
                var swLNG = sw.lng() - (0.04085540771484 / settings.height * 100);
                var neLAT = ne.lat() + (0.01348662805392 / settings.width * 100);
                var neLNG = ne.lng() + (0.04085540771484 / settings.height * 100);

                latlngbounds.extend(new GLatLng(swLAT, swLNG));
                latlngbounds.extend(new GLatLng(neLAT, neLNG));

                if ($this.gmap.getBoundsZoomLevel(latlngbounds) >= 14) {
                    $this.gmap.setCenter(latlngbounds.getCenter(), 13);
                    break;
                } else if (j == 4) {
                    $this.gmap.setCenter(latlngbounds.getCenter(), $this.gmap.getBoundsZoomLevel(latlngbounds) - 1);
                    break;
                }
            }

            nearestForPaging = [];

            var mapBounds = $this.gmap.getBounds();
            var northEast = mapBounds.getNorthEast();
            var southWest = mapBounds.getSouthWest();

            for (var i = 0; i < nearest.length; i++) {
                var item = nearest[i];
                var distance = WayPoints[item.arrPos].latlng;
                if (distance.lat() < northEast.lat() && distance.lng() < northEast.lng() && distance.lat() > southWest.lat() && distance.lng() > southWest.lng()) {
                    nearestForPaging.push(item);
                }

            }

            $.fn.loadResultList(nearestForPaging, nearestForPaging.length - j, 0);

            function sort(a, b) {
                return Number(a.distance) - Number(b.distance);
            }
        }

        var currentResultList, resultListCurrentPage, totalPages;
        var resultListPageSize = 5;

        $('#listNextPage').click(function() {
            if ((resultListCurrentPage + 1) <= totalPages) {
                populateResultList(resultListCurrentPage + 1);
                fixResultListHeight();
            }
        });

        $('#listPrevPage').click(function() {
            if (resultListCurrentPage > 1) {
                populateResultList(resultListCurrentPage - 1);
                fixResultListHeight();
            }
        });

        function fixResultListHeight() {
            var height = $("#activityMap .resultAsList .resultAsListResult .resultAsListResultItem").size() * 30;
            var top = 477 - height + 1;
            $("#activityMap .resultAsList").animate({ top: top, height: top }, 0);
        }

        function populateResultList(page) {
            resultListCurrentPage = page;
            var startIndex = (page - 1) * resultListPageSize;
            var endIndex = (startIndex + resultListPageSize);

            if (endIndex > currentResultList.length) {
                endIndex = currentResultList.length;
            }

            $('#listPages').children().removeClass('listPageDisabled');
            $('#listPages').children().eq(page - 1).addClass('listPageDisabled');

            $('#listNextPage').removeClass('listNextPageDisabled');
            $('#listPrevPage').removeClass('listPrevPageDisabled');

            if (endIndex == currentResultList.length) {
                $('#listNextPage').addClass('listNextPageDisabled');
            }
            if (page == 1) {
                $('#listPrevPage').addClass('listPrevPageDisabled');
            }

            var elm = $("#activityMap .resultAsList .resultAsListResult");
            elm.empty();

            for (var i = startIndex; i < endIndex; i++) {
                var name = currentResultList[i].Name;
                var address = currentResultList[i].Address;
                var count = currentResultList[i].Count;
                var appendHTML = '<div class="resultAsListResultItem"><div class="cell1"><a href="#" class="' + i + '">' + name + '</a></div><div class="cell2">' + address + '</div><div class="cell3">' + count + '</div><div class="clear"></div></div>';

                elm.append(appendHTML);
                hookupClickEvent(i);
            }
            function hookupClickEvent(index) {
                $("#activityMap .resultAsList .resultAsListResult ." + index).bind("click", function(e) {
                    GEvent.trigger(WayPoints[nearestForPaging[index].arrPos].marker, "click");

                    $("#activityMap .resultAsList").animate({ top: 539, height: 29 }, 300, function() { });
                });
            }
        }

        $.fn.loadResultList = function(items) {
            var ids = "";
            for (var y = 0; y < items.length; y++) {
                ids += "&id=" + WayPoints[items[y].arrPos].FirmaID
            }
            $.ajax({
                url: "/layouts/hjertestarter.dk/jsGoogleMap/mapdata.aspx",
                cache: false,
                data: "fName=getWaypointDataResultList" + ids,
                type: "GET",
                dataType: "json",
                success: function(data) {
                    $("#activityMap .resultAsList").css({ display: "block", opacity: 0 }).animate({ opacity: 1 }, 300);
                    $("#activityMap .resultAsList .resultAsListResultItem:not(.header)").remove();

                    if (data.length > 0)
                        totalPages = Math.ceil(data.length / resultListPageSize);

                    var allPagesElem = $('#listPages');
                    allPagesElem.empty();

                    var cssClass = 'listPage';
                    for (var i = 1; i <= totalPages; i++) {

                        allPagesElem.append(
              $('<span>').addClass(cssClass).append(
                $('<a>').css('cursor', 'pointer').text(i)
                  .click(function() {
                      populateResultList($(this).text());
                      fixResultListHeight();
                  })

              ));
                    }

                    allPagesElem.children().eq(0).addClass('listPageDisabled');

                    currentResultList = data;
                    populateResultList(1);
                },
                error: function(req, status, error) {
                    //alert("err");
                }
            });
        }

        $.fn.info = function() {
            this.latlng = null;
            this.div_ = document.createElement("div");
            this.div_.style.display = "none";
            var div = $(this.div_);

            div.html($("#infoBoxtemplate").html());
            $("#activityMap").append(this.div_);
        }

        $.fn.info.prototype = new GOverlay();
        var added = false;
        $.fn.info.prototype.hideInfo = function() {
            if (added) {
                $this.selectedMarker.hide();
                _clickedMarker.show();
                _visibleMarkerOverlay = null;
                var div = this.div_;
                $("#activityMap .infoBox, #activityMap .infoBox .infoHeaderMenu li div").animate({ opacity: 0 }, 300, function() {
                    $("#activityMap .infoBox, #activityMap .infoBox .infoHeaderMenu li div").css({ opacity: 0 });
                    try {
                        // $this.gmap.getPane(G_MAP_FLOAT_PANE).removeChild(div);

                        $(div).hide();
                    } catch (e) { }
                });
                added = false;
            }
        }
        $.fn.info.prototype.showInfo = function() {
            added = true;
            //$this.gmap.getPane(G_MAP_FLOAT_PANE).appendChild(this.div_);
            $(this.div_).show();
            $("#activityMap .infoBox, #activityMap .infoBox .infoHeaderMenu li div").css({ opacity: 0 });
            $("#activityMap .infoBox, #activityMap .infoBox .infoHeaderMenu li div").animate({ opacity: 1 }, 300);
        }
        $.fn.info.prototype.update = function(marker) {
            this.marker = marker;
            this.latlng = marker.getLatLng()
            //    alert("/layouts/hjertestarter.dk/jsGoogleMap/mapdata.aspx?FirmaID=" + marker.FirmaID + "&ID=" + marker.ID + "&fName=getWaypointData");

            $.ajax({
                url: "/layouts/hjertestarter.dk/jsGoogleMap/mapdata.aspx?FirmaID=" + marker.FirmaID + "&ID=" + marker.ID + "&fName=getWaypointData",
                cache: false,
                dataType: "json",
                dataFilter: function(data, type) {
                    return data.replace(/"\\\/(Date\([0-9-+]+\))\\\/"/gi, 'new $1');
                },
                success: function(response) {

                    var infoBox = $("#activityMap .infoBox")

                    $("#activityMap .infoBox .infoBoxCenter .infoHeader .infoHeaderLeft").text(response.FirmaNavn)
                    $("#activityMap .infoBox .infoBoxCenter .address").html(response.Vejnavn + " " + response.Vejnummer + response.Vejbogstav + " " + response.Etage + " " + response.Doer + "<br />" + response.Postnummer + " " + response.District)
                    $("#activityMap .infoBox .infoBoxCenter .placement").text(response.Lokalisering);

                    if (response.Bemaerkning) {
                        $("#activityMap .infoBox .infoBoxCenter .bemark").css("display", "inline");
                        $("#activityMap .infoBox .infoBoxCenter .bemark p").html(nl2br(response.Bemaerkning));
                    } else {
                        $("#activityMap .infoBox .infoBoxCenter .bemark").hide()
                    }
                    $("#activityMap #infoContentBillederThumbs .thumb").hide();
                    if (response.Images.length == 0) {
                        $(".infoHeaderMenu a[href*='infoContentBilleder']").parents("li").hide();
                    } else {
                        $(".infoHeaderMenu a[href*='infoContentBilleder']").parents("li").show();
                        $("#activityMap #infoContentBillederThumbs .thumb .overlay").unbind("click");
                        $("#activityMap #infoContentBillederThumbs .overlay").removeClass("active")
                        $("#activityMap #infoContentBillederThumbs .thumb:eq(0) .overlay").addClass("active");
                        $("#activityMap #infoContentBillederImage .text strong:eq(0)").text(response.Images[0].Billedenavn);
                        $("#activityMap #infoContentBillederImage .bigImage img").attr("src", "/Handlers/hjertestarter.dk/GoogleMapImageHandler.ashx?id=" + response.Images[0].Id + "&size=normal")
                        $("#activityMap #infoContentBillederImage .text p:eq(0)").text(response.Images[0].Note);
                    }

                    infoBox.find(".infoContentAabningstiderRight .AabenNytaarsaftensdag").css("display", !response.Holidays.AabenNytaarsaftensdag ? "none" : "block");
                    infoBox.find(".infoContentAabningstiderRight .AabenNytaarssdag").css("display", !response.Holidays.AabenNytaarssdag ? "none" : "block");
                    infoBox.find(".infoContentAabningstiderRight .Aaben1Maj").css("display", !response.Holidays.Aaben1Maj ? "none" : "block");
                    infoBox.find(".infoContentAabningstiderRight .AabenGrundlovsdag").css("display", !response.Holidays.AabenGrundlovsdag ? "none" : "block");
                    infoBox.find(".infoContentAabningstiderRight .AabenSkaertorsdag").css("display", !response.Holidays.AabenSkaertorsdag ? "none" : "block");
                    infoBox.find(".infoContentAabningstiderRight .AabenLangfredag").css("display", !response.Holidays.AabenLangfredag ? "none" : "block");
                    infoBox.find(".infoContentAabningstiderRight .Aaben1Paaskedag").css("display", !response.Holidays.Aaben1Paaskedag ? "none" : "block");
                    infoBox.find(".infoContentAabningstiderRight .Aaben2Paaskedag").css("display", !response.Holidays.Aaben2Paaskedag ? "none" : "block");
                    infoBox.find(".infoContentAabningstiderRight .AabenStBededag").css("display", !response.Holidays.AabenStBededag ? "none" : "block");
                    infoBox.find(".infoContentAabningstiderRight .AabenKrHimmelfartsdag").css("display", !response.Holidays.AabenKrHimmelfartsdag ? "none" : "block");
                    infoBox.find(".infoContentAabningstiderRight .Aaben1Pinsedag").css("display", !response.Holidays.Aaben1Pinsedag ? "none" : "block");
                    infoBox.find(".infoContentAabningstiderRight .Aaben2Pinsedag").css("display", !response.Holidays.Aaben2Pinsedag ? "none" : "block");
                    infoBox.find(".infoContentAabningstiderRight .AabenJuleaftensdag").css("display", !response.Holidays.AabenJuleaftensdag ? "none" : "block");
                    infoBox.find(".infoContentAabningstiderRight .Aaben1Juledag").css("display", !response.Holidays.Aaben1Juledag ? "none" : "block");
                    infoBox.find(".infoContentAabningstiderRight .Aaben2Juledag").css("display", !response.Holidays.Aaben2Juledag ? "none" : "block");
                    infoBox.find("#infoContentAabningstider .ugedage").html("");
                    for (var g = 0; g < response.OpeningHours.length; g++) {
                        var html = "";

                        var html = "";
                        if (response.OpeningHours[g].OpeningHours != null) {
                            for (var t = 0; t < response.OpeningHours[g].OpeningHours.length; t++) {
                                var hours = response.OpeningHours[g].OpeningHours[t];
                                html += "<div>" + checkTime(hours.Open.getHours()) + ":" + checkTime(hours.Open.getMinutes()) + " - " + checkTime(hours.Close.getHours()) + ":" + checkTime(hours.Close.getMinutes()) + "</div>";
                            }
                        } else {
                            html = "<div>Lukket</div>";
                        }

                        html = '<div class="day"><div class="weekday">' + response.OpeningHours[g].WeekDay + '</div><div class="openingHours">' + html + '</div><div class="clear"></div></div>';
                        infoBox.find("#infoContentAabningstider .ugedage").append(html);
                    }

                    $('.weekLink').click(function() {
                        $('.infoContentAabningstiderLeft').show();
                        $('.infoContentAabningstiderRight').hide();
                        $('.closeLinkDiv').removeAttr('style');
                        $('.closeLinkDiv a').removeAttr('style');
                        $('.weekLinkDiv').attr('style', 'background-image: url("/gfx/hjertestarter.dk/googlemap/bg.gif"); font-weight: bold; color: #000;');
                        $('.weekLinkDiv a').attr('style', 'color: #000;');
                    });

                    $('.closeLink').click(function() {
                        $('.infoContentAabningstiderLeft').hide();
                        $('.infoContentAabningstiderRight').show();
                        $('.weekLinkDiv').removeAttr('style');
                        $('.weekLinkDiv a').removeAttr('style');
                        $('.closeLinkDiv').attr('style', 'background-image: url("/gfx/hjertestarter.dk/googlemap/bg.gif"); font-weight: bold; color: #000;');
                        $('.closeLinkDiv a').attr('style', 'color: #000;');
                    });

                    $('.nextImage').show();
                    $('.prevImage').hide();

                    if (response.Images.length == 0) {
                        $('.nextImage').hide();
                        $('.prevImage').hide();
                    }

                    var infoContentBillederThumbs = $('#infoContentBillederThumbs');
                    infoContentBillederThumbs.empty();

                    $.each(response.Images, function(i, e) {
                        $.preloadImages("/Handlers/hjertestarter.dk/GoogleMapImageHandler.ashx?id=" + e.Id + "&size=thumb", "/Handlers/hjertestarter.dk/GoogleMapImageHandler.ashx?id=" + e.Id + "&size=normal");

                        infoContentBillederThumbs.append(
              $('<div>').attr('display', 'none').append(
                $('<img>')
                .attr('src', '/Handlers/hjertestarter.dk/GoogleMapImageHandler.ashx?size=thumb&id=' + e.Id)
                .attr('ref', '/Handlers/hjertestarter.dk/GoogleMapImageHandler.ashx?size=normal&id=' + e.Id))
              .append($('<strong>').text(e.Billedenavn))
              .append($('<p>').text(e.Note)));

                        //            var thumb = $("#activityMap #infoContentBillederThumbs .thumb:eq(" + image + ")").show();
                        //            thumb.css({ "background-image": "url(\"/Handlers/hjertestarter.dk/GoogleMapImageHandler.ashx?id=" + response.Images[image].Id + "&size=thumb\")" });

                        //            $("#activityMap #infoContentBillederThumbs .thumb:eq(" + image + ") .overlay").bind("click", { index: image, id: response.Images[image].Id }, function(e, data) {
                        //              $("#activityMap #infoContentBillederThumbs .overlay").removeClass("active")
                        //              $(this).addClass("active")
                        //              $("#activityMap #infoContentBillederImage .text strong:eq(0)").text(response.Images[e.data.index].Billedenavn);
                        //              $("#activityMap #infoContentBillederImage .text p:eq(0)").text(response.Images[e.data.index].Note);
                        //              $("#activityMap #infoContentBillederImage .bigImage img").attr("src", "/Handlers/hjertestarter.dk/GoogleMapImageHandler.ashx?id=" + e.data.id + "&size=normal")
                        //            });
                    });

                    var images = infoContentBillederThumbs.find('img');

                    var firstImage = images.filter(':first');
                    var lastImage = images.filter(':last');
                    var currentImage = firstImage;

                    $('.nextImage').click(function() {
                        currentImage = currentImage.parent().next().children('img');
                        showImage();
                    });
                    $('.prevImage').click(function() {
                        currentImage = currentImage.parent().prev().children('img');
                        showImage();
                    });

                    function showImage() {
                        $("#activityMap #infoContentBillederImage .text strong:eq(0)").text(currentImage.siblings('strong').text());
                        $("#activityMap #infoContentBillederImage .text p:eq(0)").text(currentImage.siblings('p').text());
                        $("#activityMap #infoContentBillederImage .bigImage img").attr("src", currentImage.attr('ref'));
                        showHidePrevNext();
                    }

                    function showHidePrevNext() {
                        var next = currentImage.parent().next().children('img');
                        var prev = currentImage.parent().prev().children('img');

                        if (next.length == 0) {
                            $('.nextImage').hide();
                        } else {
                            $('.nextImage').show();
                        }
                        if (prev.length == 0) {
                            $('.prevImage').hide();
                        } else {
                            $('.prevImage').show();
                        }
                    }

                },
                error: function(req, status, error) {
                    alert("error loading info" + error);
                }
            });
        }


        $.fn.info.prototype.onClick_ = function(e) {
            if (navigator.userAgent.toLowerCase().indexOf('msie') != -1 && document.all) {
                window.event.cancelBubble = true;
                window.event.returnValue = false;
            } else {
                //e.preventDefault();
                e.stopPropagation();
            }
        };


        $.fn.info.prototype.initialize = function(map) {
            var elm = this;
            var moveStart = GEvent.addListener($this.gmap, "movestart", function() { elm.hideInfo(); GEvent.removeListener(moveStart); });
            var zoomend = GEvent.addListener($this.gmap, "zoomend", function() { elm.hideInfo(); GEvent.removeListener(zoomend); });

            _visibleMarkerOverlay = this.marker;

            GEvent.bindDom(this.div_, 'mousedown', this, $.fn.info.prototype.onClick_);
            GEvent.bindDom(this.div_, 'dblclick', this, $.fn.info.prototype.onClick_);
            GEvent.bindDom(this.div_, 'DOMMouseScroll', this, $.fn.info.prototype.onClick_);

            $(this.div_).css({ position: 'absolute', "z-index": 100000 });

            this.showInfo();

            this.map_ = map;

            $("#activityMap .infoHeaderMenu a").each(function() {
                if ($(this).innerWidth() > 0)
                    $(this).css("width", $(this).innerWidth() - 20).css("display", "block");
            });
            $("#activityMap .infoHeaderMenu a:first").each(function() {
                document.getElementById($(this).attr("href").substring($(this).attr("href").lastIndexOf("#") + 1)).style.display = "block";
                $("#activityMap .infoBox .infoHeaderMenu li").removeClass("active");
                $("#activityMap .infoBox .infoHeaderMenu li div").hide()
                $(this).siblings("div").css({ width: $(this).parents("li").width() }).show();
                $(this).parents("li").addClass("active");
            });
            $("#activityMap .infoHeaderRight").click(function() {
                $this.infoOverlay.hideInfo();
            });
            $("#activityMap .infoHeaderMenu a").click(function() {
                $("#activityMap .infoContent .infoContentContent").hide();
                $("#activityMap .infoContent " + $(this).attr("href").substring($(this).attr("href").lastIndexOf("#"))).show();
                $("#activityMap .infoBox .infoHeaderMenu li").removeClass("active");
                $("#activityMap .infoBox .infoHeaderMenu li div").hide()
                $(this).siblings("div").css({ width: $(this).parents("li").width() }).show();
                $(this).parents("li").addClass("active");

                return false;
            });

            $("#activityMap .infoHeaderMenu a").mouseover(function() {
                $(this).parents("li").addClass("hover");
            });
            $("#activityMap .infoContentContent").hide();
            $("#activityMap .infoContentContent:eq(0)").show();
        };



        $.fn.info.prototype.remove = function() {

        };
        $.fn.info.prototype.add = function() {

        };
        $.fn.info.prototype.copy = function() {

        };
        $.fn.info.prototype.redraw = function(force) {
            if (!force) return;
            var divPixel = this.map_.fromLatLngToDivPixel(this.latlng);
            $(this.div_).css({ left: 261, top: 68, height: 400, width: 364 });
        };

        $this.infoOverlay = new $this.info();
        return this;
    }
})(jQuery);
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length >>> 0;

        var from = Number(arguments[1]) || 0;
        from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
        if (from < 0)
            from += len;

        for (; from < len; from++) {
            if (from in this &&
          this[from] === elt)
                return from;
        }
        return -1;
    };
}


function nl2br(text) {
    textescape = escape(text);
    var re_nlchar = "";
    if (textescape.indexOf('%0D%0A') > -1) {
        re_nlchar = /%0D%0A/g;
    } else if (textescape.indexOf('%0A') > -1) {
        re_nlchar = /%0A/g;
    } else if (textescape.indexOf('%0D') > -1) {
        re_nlchar = /%0D/g;
    }
    if (re_nlchar != "")
        return unescape(textescape.replace(re_nlchar, '<br />'));
    else
        return text;
}
jQuery.preloadImages = function() {
    for (var i = 0; i < arguments.length; i++) {
        jQuery("body").append(jQuery("<img>").attr("src", arguments[i]).hide());
    }
}

function checkTime(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}
