﻿/// <reference path="jquery-1.2.6-vsdoc.js" />
/// <reference path="jquery.eventCalendar.js" />
/// <reference path="csState.js" />

// Kalender funktioner
calendarViewChanged = function (year, month) {
    var startDato = new Date(year, month, 1);
    var slutDato = startDato.addMonth(1);

    $.getJSON("/Kalender/" + DgiLokalt.State.tilbudId + "/" + startDato.format("yyyy-MM-dd") + "/" + slutDato.format("yyyy-MM-dd"), {}, function (data) {
        var triplets = [];
        $.each(data, function (entryIndex, entry) {
            var date = eval('new' + entry.date.replace(/\//g, ' '));
            $calendar.addDate(date, entry.count);
        });
        $calendar.refresh();
    });
};

onDateClick = function (ticks) {
    var date = new Date(parseInt(ticks));
    var dayName = date.getDayName().capitalize();

    var ddtxt = "{0} den {1:d. MMM yyyy}".format(dayName, date);
    $("p#ddtxt").text("" + ddtxt);

    DgiLokalt.Actions.hentBegivenheder(date);
};
// Kalender slut

$(function () {
    $state.hookup("#inpHvad");
    $state.hookup("#inpHvor");
    $state.onChange = DgiLokalt.Actions.ExecuteQuery;

    $("#alternativeAdresser").hide();
    $("#searchBox").show();
    $("#knapQuery").bind("click", DgiLokalt.Utility.clickSearch);
    $("#menubarOmBtn").bind("click", DgiLokalt.Utility.showAbout);
    $("#menubarOpretBtn").bind("click", DgiLokalt.Utility.showCreate);
    $("div.mapEnlargeBtn").click(DgiLokalt.Utility.fullScreen);
    $("#alternativeAdresser .tilbageknap A").click(DgiLokalt.Utility.hideAltAddress);
    $("#menubarSogBtn").bind("click", DgiLokalt.Utility.fanebladSog);
    $("#getMap").bind("click", DgiLokalt.Utility.showGetMap);

    DgiLokalt.Utility.fanebladSog();
    DgiLokalt.Google.Initialize();
    DgiLokalt.Actions.ExecuteQuery();
    // Initialicering af kalender kontrol
    var element = document.getElementById("kalender");
    window.$calendar = createCalendar(element, calendarViewChanged, onDateClick);
});

var DgiLokalt = {
    Constants: {
        Debug: true,
        TilbudInfoPaddingTop: 100,
        TilbudInfoWidth: 700,
        MaximumNumberOfMarkers: 200
    },
    State: new stateObject(),
    Actions: new actions(),
    Google: new googleObject(),
    Utility: new utility()
};

function stateObject() {
    return {
        getHvad: function () { return $state.get("inpHvad", ""); },
        getHvor: function () { return $state.get("inpHvor", ""); },
        setHvor: function (value) {
            $("#inpHvor").val(value);
            if (!value) // jQuery bug? Hvis der skiftes til tom streng, rejses change ikke!!!
                $("#inpHvor").triggerHandler("change");
        },
        setHvad: function (value) {
            $("#inpHvad").val(value);
            if (!value) // jQuery bug? Hvis der skiftes til tom streng, rejses change ikke!!!
                $("#inpHvad").triggerHandler("change");
        },
        Caller: null,
        tilbudId: null,
        getUrl: function () {
            return location.href;
        },
        persistGoogleState: function () {
            $state.setRange([
            ["lat", DgiLokalt.Google.Map.getCenter().lat()],
            ["lng", DgiLokalt.Google.Map.getCenter().lng()],
            ["zoom", DgiLokalt.Google.Map.getZoom()],
            ["inpHvor", ""] // Hvis der bliver trukket/zoomet i kortet, skal hvor sættes ""
            ]);
        },
        getLatLng: function (defLat, defLng) {
            return new GLatLng($state.get("lat", defLat), $state.get("lng", defLng));
        },
        getZoom: function (defaultZoom) {
            return parseInt($state.get("zoom", defaultZoom), 10);
        }
    }
}

// Google
function googleObject() {
    this.Map = null;
    this.Bounds = function () {
        if (this.Map == null)
            return null;
        var bounds = this.Map.getBounds();
        var sw = bounds.getSouthWest();
        var ne = bounds.getNorthEast();
        return { n: ne.lat(), s: sw.lat(), e: ne.lng(), w: sw.lng() };
    };
    this.Icons = [];
}

googleObject.prototype.Initialize = function () {
    if (GBrowserIsCompatible()) {
        this.Map = new GMap2(document.getElementById("map_canvas"));
        this.Map.addControl(new GSmallMapControl());
        this.Map.setCenter(GetClientLocation(), DgiLokalt.State.getZoom(12));
        this.Map.enableScrollWheelZoom();

        var dgiIcon = new GIcon();
        dgiIcon.image = "/Content/Images/aktivitet.png";
        dgiIcon.size = new GSize(54, 35); // w, h
        dgiIcon.shadow = "/Content/Images/aktivitetskygge.png";
        dgiIcon.shadowSize = new GSize(54, 35);
        dgiIcon.iconAnchor = new GPoint(27, 35);
        dgiIcon.infoWindowAnchor = new GPoint(1, 1);
        this.Icons.push(dgiIcon);

        GEvent.addListener(this.Map, "dragend", function () {
            if (DgiLokalt.Google.Map.getInfoWindow().isHidden()) {
                DgiLokalt.State.persistGoogleState();
            }
        });
        GEvent.addListener(this.Map, "zoomend", function () {
            DgiLokalt.State.persistGoogleState();
            DgiLokalt.Actions.ExecuteQuery();
        });
    }
};

googleObject.prototype.Dispose = function () {
    GUnload();
};

googleObject.prototype.Resize = function () {
    this.Map.checkResize();
    this.MarkerManager.refresh();
};

googleObject.prototype.PanTo = function (lat, lng) {
    this.Map.panTo(new GLatLng(lat, lng));
}

// Actions
function actions() { }

actions.prototype.GetTilbudInfo = function (id) {
    $.getJSON("/Sted/Tilbud/" + id, {}, DgiLokalt.Utility.RenderTilbudInfo);
    DgiLokalt.State.tilbudId = id;
};

actions.prototype.GetPoints = function (calback) {
    var bounds = DgiLokalt.Google.Bounds();
    var url = "/Sted/Punkter/" + bounds.n + "-" + bounds.s + "-" + bounds.e + "-" + bounds.w;

    if (DgiLokalt.Constants.Debug) window.status = ("n:" + bounds.n + " s:" + bounds.s + " e:" + bounds.e + " w:" + bounds.w);
    $.getJSON(url, {}, calback);
};

actions.prototype.GetMarkerInfo = function (id, callback) {
    $.getJSON("/Sted/Punkt/" + id + (DgiLokalt.State.getHvad() ? ("/" + DgiLokalt.State.getHvad()) : ""), {}, callback);
};

actions.prototype.GetStedInfo = function (id, callback) {
    $.getJSON("/Sted/Info/" + id, {}, callback);
};

actions.prototype.GetMarkersInView = function () {
    DgiLokalt.Actions.GetPoints(DgiLokalt.Utility.RenderMarkers);
};

actions.prototype.QueryWithBounds = function (hvad) {
    var bounds = DgiLokalt.Google.Bounds();
    $.getJSON(
    "/Query/WithBounds",
            { north: bounds.n, south: bounds.s, east: bounds.e, west: bounds.w, what: hvad },
            DgiLokalt.Utility.RenderMarkers
            );
};

actions.prototype.QueryWhere = function (where, callback) {
    var client = new GClientGeocoder();
    var query = new gQuery(where);
    client.setBaseCountryCode("DK");
    client.getLocations(query.getQuery(), DgiLokalt.Utility.ShowWhereResult);
    if (typeof callback == 'function')
        callback();
};

actions.prototype.ExecuteQuery = function () {
    DgiLokalt.Utility.HideWarning();
    DgiLokalt.State.Caller = (this.id == "knapQuery") ? "Knap" : "Map";
    if (DgiLokalt.State.getHvor() && DgiLokalt.State.getHvad()) {
        DgiLokalt.Actions.QueryWhere(DgiLokalt.State.getHvor(), function () {
            DgiLokalt.Actions.QueryWithBounds(DgiLokalt.State.getHvad());
        });
    }
    if (DgiLokalt.State.getHvor()) {
        DgiLokalt.Actions.QueryWhere(DgiLokalt.State.getHvor());
    }
    if (DgiLokalt.State.getHvad() && !DgiLokalt.State.getHvor()) {
        DgiLokalt.Actions.QueryWithBounds(DgiLokalt.State.getHvad());
    }
    if (!DgiLokalt.State.getHvor() && !DgiLokalt.State.getHvad()) {
        DgiLokalt.Actions.GetMarkersInView();
    }

}

// Parameter day: [year, month, day]
actions.prototype.hentBegivenheder = function (date) {
    $.getJSON("/Kalender/" + DgiLokalt.State.tilbudId + "/" + date.format("yyyy-MM-dd"), {}, function (data) {

        $("div.begivenhedsOversigt").empty();

        $.each(data, function (entryIndex, entry) {
            var from = entry.from;
            var to = entry.to;
            var description = entry.description;
            var begivenhedData = "<p>{0} {1}</p><br />".format(
                (from != to ? "<b>{0} - {1}</b>: ".format(from.slice(0, 5), to.slice(0, 5)) : ""),
                 description.replace(/\n/g, "<br />")
                 );
            $("div.begivenhedsOversigt").append($(begivenhedData));
        });

        if ($("div.begivenhedsOversigt")[0].childNodes.length == 0) {
            $("div.begivenhedsOversigt").append("<p>Klik på en dato med begivenheder for at vise tilbud</p><br />");
        }
    });
}

// Utility
function utility() { this.Timer; }

utility.prototype.ShowWarning = function (text) {
    $("#maxmarkerwarning > p").html(text);
    doBlink($("#maxmarkerwarning"), 1, 2);
    window.clearTimeout(this.Timer);
    this.Timer = window.setTimeout(this.HideWarning, 8000);
};

utility.prototype.HideWarning = function () {
    $("#maxmarkerwarning").hide();
}

utility.prototype.ShowWhereResult = function (data) {
    if (data.Status.code != 200)
        return;
    var count = typeof (data.Placemarkdata) != "undefined" ? 0 : data.Placemark.length;

    if (count > 0) {
        var clnt = new gPointResult(data.Placemark[0]);
        if (clnt.isDenmark()) {
            var point = data.Placemark[0].Point.coordinates;
            DgiLokalt.Utility.SetLocation(point[1], point[0], clnt.getName(), DgiLokalt.State.Caller == "Knap");

            if (DgiLokalt.State.getHvad())
                DgiLokalt.Actions.QueryWithBounds(DgiLokalt.State.getHvad());
            else
                DgiLokalt.Actions.GetMarkersInView();

            if (count > 1)
                DgiLokalt.Utility.RenderAlternativeLokationer(data.Placemark.slice(1));
        } else DgiLokalt.Utility.ShowWarning("'Hvor'-søgningen gav ingen resultater");
    } else DgiLokalt.Utility.ShowWarning("'Hvor'-søgningen gav ingen resultater.");

};

utility.prototype.RenderAlternativeLokationer = function (data) {
    if (typeof (data) != "object")
        return;

    liTags = "";

    $(data).each(function (id, item) {
        var point = new gPointResult(item);
        liTags += "<li><a onclick=\"javascript:DgiLokalt.Utility.SetLocation(" + item.Point.coordinates[1] + "," + item.Point.coordinates[0] + ",'" + point.getName() + "', true);\">" + point.getName() + "</a></li>";
    });

    $("#ulboks > ul").html(liTags);

    $("#alternativeAdresser").show();
    $("#searchBox").hide();

}

utility.prototype.SetLocation = function (lat, lng, where, withZoom) {
    DgiLokalt.State.setHvor(where);
    DgiLokalt.Google.PanTo(lat, lng);
    if (withZoom)
        DgiLokalt.Google.Map.setZoom(12);
};

utility.prototype.RenderTilbudInfo = function (data) {
    var tilbudData = eval("(" + data + ")");
    $("div.ui-dialog").remove();

    var obj = $("#renderedTilbudInfo");
    obj.find("#TITekst").html(tilbudData.Tekst);
    obj.find("#TIHeaderForeningsnavn").html(' - ' + tilbudData.Foreningsnavn);
    obj.find("#TIInstruktoerNavn").html('Instruktør: ' + tilbudData.InstruktoerNavn);
    obj.find("#TIStedNavn").html(tilbudData.Hvor);
    obj.find("#TIKontaktNavn").html(tilbudData.KontaktNavn);
    obj.find("#TIKontaktTlf").html('Tlf: ' + tilbudData.KontaktTlf);
    obj.find("#TIKontaktEmail").html('E-mail: <a href="mailto:' + tilbudData.KontaktEmail + '">' + tilbudData.KontaktEmail + '</a>');
    obj.find("#TIKontaktUrl").html(tilbudData.KontaktUrl);
    obj.find("#TIKontaktUrl").attr("href", tilbudData.KontaktUrl);
    if (tilbudData.OnlineTilmeldUrl == "") {
        obj.find("#TIOnlinetilmeldUrl").hide();
    }
    else {
        obj.find("#TIOnlinetilmeldUrl").attr("href", tilbudData.OnlineTilmeldUrl);
        obj.find("#TIOnlinetilmeldUrl").button().show();

    }
    obj.show();

    if (tilbudData.HarKalenderInfo) {
        $calendar.clearSelected();
        $calendar.setMonth(new Date().getMonth());
        $("#renderedTilbudKalenderParent").show();
    }
    else {
        $("#renderedTilbudKalenderParent").hide();
    }
    var renderedTilbudInfoContainerHeight = $(".renderedTilbudInfoContainer").height();
    obj.dialog({
        modal: true,
        draggable: false,
        resizable: false,
        width: DgiLokalt.Constants.TilbudInfoWidth,
        height: renderedTilbudInfoContainerHeight + 100,
        title: tilbudData.Titel,
        border: "none",
        top: 136,
        overlay: {
            opacity: 0.5,
            background: "black"
        }
    });

    StyleDialogue();
}

utility.prototype.RenderMarkerInfo = function (arr) {
    if (arr == null)
        return;
    var html = "";
    $.each(arr, function (id, data) {
        html += "<h3>" + data.Navn + "</h3>";
        html += "<ul>";
        $.each(data.Tilbud, function (id, item) {
            html += "<li><a onclick=\"javascript:DgiLokalt.Actions.GetTilbudInfo(" + item.ID + ");\">" + item.Navn + "</a></li>";
        });
        html += "</ul>";
    });
    return "<div class='container'>" + html + "</div>";
};

utility.prototype.RenderStedInfo = function (data) {
    if (data == null)
        return "Ingen steddata!";
    var html = "";
    $.each(data, function (idx, item) {
        var $template = $("#stedinfolayout div:first-child").clone();
        $template.find(".lblNavn").html(item.Navn);
        $template.find(".lblAdresse").html(item.Adresse);
        $template.find(".lblPostBy").html(item.PostBy);
        $template.find(".lblTilgaengelighed").html(item.Tilgaengelighed);
        $template.find(".lblTelefon").html(item.Telefon);
        var lnk = $template.find(".lnkHjemmeside");
        if (item.Hjemmeside) {
            lnk.attr("href", item.Hjemmeside);
            lnk.html(item.Hjemmeside);
        } else {
            lnk.html("Ikke angivet");
            lnk.removeAttr("href");
        }
        var eml = $template.find(".lnkEmail");
        if (item.Hjemmeside) {
            eml.attr("href", "mailto:" + item.Email);
            eml.html(item.Email);
        } else {
            eml.html("Ikke angivet");
            eml.removeAttr("href");
        }
        html += $template.html();
    });
    return "<div class='container'>" + html + "</div>";
};

utility.prototype.RenderMarkers = function (y, status) {
    var result = eval(y);

    if (typeof (result.result) == 'undefined')
        return;

    if (result.result == 0 && result.data.length > DgiLokalt.Constants.MaximumNumberOfMarkers) {
        DgiLokalt.Utility.ShowWarning("Søgningen gav for mange resultater.<br>Prøv at zoome ind.");
        return;
    }

    if (result.result == 1)
        DgiLokalt.Utility.ShowWarning("Ingen resultater i det valgte område.");

    if (result.result == 2) {
        DgiLokalt.Utility.ShowWarning("Søgningen er ikke valid");
        return;
    }

    markerOptions = { icon: DgiLokalt.Google.Icons[0] };

    DgiLokalt.Google.Map.clearOverlays();
    var infoconfig = { maxHeight: 300 };

    if (result.result == 0) {
        for (var i = 0; i < result.data.length; i++) {
            var point = new GLatLng(result.data[i][0], result.data[i][1]);
            var marker = new GMarker(point, markerOptions);
            marker["tag"] = result.data[i][2];
            GEvent.addListener(marker, "click", function () {
                var lm = this;
                var infoTabs = [null, null];
                DgiLokalt.Actions.GetMarkerInfo(this.tag, function (result) {
                    var info = eval("(" + result + ")");
                    infoTabs[0] = new GInfoWindowTab("Tilbud", DgiLokalt.Utility.RenderMarkerInfo(info));
                    if (infoTabs[1]) lm.openInfoWindowTabsHtml(infoTabs, infoconfig);
                });
                DgiLokalt.Actions.GetStedInfo(this.tag, function (result) {
                    var steddata = eval("(" + result + ")");
                    infoTabs[1] = new GInfoWindowTab("Sted", DgiLokalt.Utility.RenderStedInfo(steddata))
                    if (infoTabs[0]) lm.openInfoWindowTabsHtml(infoTabs, infoconfig);
                });
            });
            GEvent.addListener(marker, "infowindowclose", DgiLokalt.Actions.ExecuteQuery);
            DgiLokalt.Google.Map.addOverlay(marker);
        }
    }
};

utility.prototype.fanebladSog = function () {
    $("#OTInfoBox").hide();
    $("#faneblade").css("background", "transparent url(/content/images/faneblade.png) no-repeat scroll 0 0");
    $("#SogTilbud").attr("src", "/Content/Images/TxtSogValgt.png");
    $("#OpretTilbud").attr("src", "/Content/Images/TxtOpretTilbud.png");
    $("#OpretTilbudBtn").css("top", "-27px");
    $("#SogTilbudBtn").css("top", "5px");
    fjernFocus();
};

utility.prototype.showAbout = function () {
    $("#dialogOm")
    .dialog({
        modal: true,
        draggable: false,
        width: 550,
        height: 400,
        border: "none",
        top: 136,
        overlay: {
            opacity: 0.8,
            background: "black"
        }

    }).dialog("open");
    StyleDialogue();
};

utility.prototype.showCreate = function () {
    $("#OTInfoBox").show();
    $("#faneblade").css("background", "transparent url(/content/images/fanebladeOprettilbud.png) no-repeat scroll 0 0");
    $("#SogTilbud").attr("src", "/Content/Images/TxtSogTilbud.png");
    $("#OpretTilbud").attr("src", "/Content/Images/TxtOpretValgt.png");
    $("#SogTilbudBtn").css("top", "11px");
    $("#OpretTilbudBtn").css("top", "-33px");
    fjernFocus();
};

utility.prototype.fullScreen = function () {
    location.href = "/Home/Fullscreen" + location.hash;
};

utility.prototype.hideAltAddress = function () {
    $("#alternativeAdresser").hide();
    $("#searchBox").show();
};

utility.prototype.clickSearch = function () {
    DgiLokalt.Actions.ExecuteQuery();
    $("#OTInfoBox").hide();
    DgiLokalt.Utility.fanebladSog();
    return false;
};

DgiLokalt.Utility.showGetMap = function () {
    $("#dialogKortWidget").show();
    $("#dialogKortWidget").dialog({
        modal: true,
        draggable: false,
        width: 650,
        height: 400,
        border: "none",
        overlay: {
            opacity: 0.8,
            background: "black"
        }

    }).dialog("open");
    StyleDialogue();
};

// Statiske objekter
window.GetClientLocation = function () {
    if (google.loader.ClientLocation) {
        return DgiLokalt.State.getLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
    }
    return DgiLokalt.State.getLatLng(55.816, 9.588);
};

window.doBlink = function (obj, start, finish) {
    obj.fadeOut(100).fadeIn(100);
    if (start != finish) {
        start = start + 1;
        doBlink(obj, start, finish);
    }
};

window.StyleDialogue = function () {
    //Fjern resize-rammer
    $(".ui-resizable-handle").remove();

    //Fjern focus-ramme
    $(".ui-dialog-titlebar-close").blur();
};
window.fjernFocus = function () {
    $("#SogTilbudBtn a").blur();
    $("#OpretTilbudBtn a").blur();
};

// Hjælpe klasser
function gPointResult(data) {
    this.data = data;
    this.name = data.address.indexOf(",") > -1 ? data.address.substring(0, data.address.indexOf(",")) : this.data.address;

    this.getName = function () {
        if (typeof(this.data.AddressDetails.Country) != "undefined")
        {
            if (typeof (this.data.AddressDetails.Country.Locality) != "undefined")
                return this.name + ", " + this.data.AddressDetails.Country.Locality.LocalityName;
            if (typeof (this.data.AddressDetails.Country.AdministrativeArea) != "undefined") {
                if (typeof (this.data.AddressDetails.Country.AdministrativeArea.Locality) != "undefined" && this.data.AddressDetails.Country.AdministrativeArea.Locality.LocalityName != this.name)
                    return this.name + ", " + this.data.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
                else
                    return this.name + ", " + this.data.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
            }
        }
        return this.data.address;
    };
    this.isDenmark = function () {
        if (typeof(this.data.AddressDetails.Country) != "undefined")
            return this.data.AddressDetails.Country.CountryNameCode == "DK";
        return this.data.address.indexOf("Denmark") > -1;
    };
}

function gQuery(originalQuery) {
    this.query = originalQuery;
    this.getQuery = function () {
        if (!isNaN(this.query))
            return this.query + ", danmark";
        return this.query;
    }
}

