﻿var Cowi = Cowi || {};

Cowi.Dn = {

    custkey: "DN",
    srcProj: "EPSG:32632",   // Native tab SRID 
    destProj: "EPSG:3857",   // SRID 900913: Connect 2.0 = EPSG:3785, Connect 2.1 = EPSG:3857
    isEmbedded: false,      // is embedded in an iframe
    preservationLayer: "fredede_omr",
    preservationColumnId: "id",
    municipalityLayer: "NyKomg2006",
    municipalityColumnId: "Komnr",

    /* 
    *   "Origin http://xxx.xxx.xxx.xxx is not allowed by Access-Control-Allow-Origin"
    *   Client request to the server MUST have the precise ip in AJAX URL, this much match the current host.
    */

    /* 
    * Keep id of current preservation 
    * Yahoo JavaScript Module Pattern allowing private and public properties
    */
    currentPreservation: function () {
        var id = 0; // private
        return {
            getId: function () {
                return id;
            },
            setId: function (newId) {
                id = parseInt(newId);
            }
        };
    } (),

    /* 
    * Keep id of current municipality
    * Yahoo JavaScript Module Pattern allowing private and public properties
    */
    currentMunicipality: function () {
        var id = -1; // private, default -1 = all municipalities
        return {
            getId: function () {
                return id;
            },
            setId: function (newId) {
                id = parseInt(newId);
            }
        };
    } (),

    /*
    * Run start up rutinees
    */
    init: function () {

        // Internet Explore 6,7 and 8 does not support JSON.stringify
        if (typeof JSON === "undefined") {
            Cowi.Dn.Utils.loadScripts(["/Scripts/json2.js"]);
        }

        // Is site embedded in an iframe
        if (top === self) {
            Cowi.Dn.embedded = false;
            jQuery("#dn-logo-div").css({ visibility: 'visible' });
        } else {
            Cowi.Dn.embedded = true;
        }

        Cowi.Dn.adjustMapToWindowHeight();
        jQuery(window).resize(Cowi.Dn.adjustMapToWindowHeight);

        Cowi.Dn.currentPreservation.setId(-1);

        Cowi.Dn.initMunicipalicyControl();
        Cowi.Dn.initPresevationAutocomplete(-1);  // -1 as municipalityId equals to all municipalities
        Cowi.Dn.initPreservationDialog();
        Cowi.Dn.initMap();

        Cowi.Dn.handleDeeplink();
        Cowi.Dn.handleMunicipalityDeeplink();
    },

    handleMunicipalityDeeplink: function () {

        var sid = Cowi.Dn.Utils.getParameterFromUrl('komnr');

        var id = parseInt(sid);

        if (isNaN(id)) {
            return;
        }

        if (id === "") {
            return;
        }

        var municipalityId = id;

        Cowi.Dn.currentMunicipality.setId(municipalityId);

        // Clear preservation when new municipality is selected
        jQuery("#preservationAutocomplete").val("");
        Cowi.Dn.initPresevationAutocomplete(municipalityId);

        if (municipalityId === -1) {
            // Zoom to DK
            Cowi.Dn.map.setCenter(new OpenLayers.LonLat(1100000, 7600000), 6);
        }
        else {
            // Clause used to get bound
            var sqlClause = 'select * from "/stratus/' + Cowi.Dn.municipalityLayer + '" where ' + Cowi.Dn.municipalityColumnId + ' = ' + municipalityId;

            Cowi.Dn.zoomToBound(Cowi.Dn.custkey, Cowi.Dn.municipalityLayer, sqlClause, 1);
        }

    },

    /*
    * If the user uses a deeplink to a preservation show like it was clicked or searched in a standard way
    */
    handleDeeplink: function () {

        var sid = Cowi.Dn.Utils.getParameterFromUrl('id');

        var id = parseInt(sid);

        if (isNaN(id)) {
            return;
        }

        if (id === "") {
            return;
        }

        Cowi.Dn.currentPreservation.setId(id);
        Cowi.Dn.showPreservation(id, true, true);
    },

    /*
    * Load municipalities to select combo
    */
    initMunicipalicyControl: function () {

        jQuery.ajax({
            url: "/Dn/GetMunicipalities",
            type: "Get",
            dataType: "json",
            contentType: "application/json",
            success: function (data) {

                var municipalities = jQuery("#municipalities");

                // Reset the combobox
                municipalities.html("<option value=\"-1\">Vælg en kommune</option>");

                // Append data to combobox
                jQuery.each(data, function (i, item) {
                    jQuery("<option/>", { value: item.Id, text: item.Name }).appendTo(municipalities);
                });
            },
            error: function (xhr) {
                /*
                if (xhr.responseText) {
                var err = xhr.responseText;
                if (err)
                alert("ERROR\n\n" + err);
                else
                alert("Unknown server error.");
                }
                return;
                */
            }
        });
    },

    /**
    * Fired when a municipality is selected. Centers and zooms to the municipality.
    */
    municipalitySelected: function () {

        jQuery("#preservationAutocomplete").autocomplete('close');

        var municipalityId = parseInt(jQuery("#municipalities").val());
        var municipalityName = jQuery("#municipalities option:selected").text();

        Cowi.Dn.currentMunicipality.setId(municipalityId);

        // Clear preservation when new municipality is selected
        jQuery("#preservationAutocomplete").val("");
        Cowi.Dn.initPresevationAutocomplete(municipalityId);

        if (municipalityId === -1) {
            // Zoom to DK
            Cowi.Dn.map.setCenter(new OpenLayers.LonLat(1100000, 7600000), 6);
        }
        else {
            // Clause used to get bound
            var sqlClause = 'select * from "/stratus/' + Cowi.Dn.municipalityLayer + '" where ' + Cowi.Dn.municipalityColumnId + ' = ' + municipalityId;

            Cowi.Dn.zoomToBound(Cowi.Dn.custkey, Cowi.Dn.municipalityLayer, sqlClause, 1);
        }
    },

    /*
    * Combobox functionality for a preservation select
    */
    preservationButtonClick: function () {

        var id = Cowi.Dn.currentMunicipality.getId();

        if (id === -1 || id === 'NaN') {
            alert("Vælg først en kommune");
        }
        else {
            jQuery('#preservationAutocomplete').autocomplete('search', '');
        }
    },

    /**
    * Load data to autocomplete
    * @municipalityId: Id to load. -1 is all municipalities. 
    */
    initPresevationAutocomplete: function (municipalityId) {

        var minLengthAutoComplete = 0;  // the min length of character input for autocomplete to come with search suggestions
        if (municipalityId === -1) {
            if (navigator.appName === "Microsoft Internet Explorer") {
                minLengthAutoComplete = 4; // IE cannot handle ?1000+ items, if search starts at 0 characters
            }
            else {
                minLengthAutoComplete = 2;  // Let other browsers start search after 2 characters
            }
        }
        else {
            // Since a municipality is selected we allow combobox popup
            minLengthAutoComplete = 0;  // 0 characters needed for the combobox functionality seach popup            
        }

        municipalityId = parseInt(municipalityId);  // Avoid any arbitrary string conversion

        var urlRest;

        if (municipalityId === -1) {
            urlRest = "/Dn/GetPreservations";
        }
        else {
            urlRest = "/Dn/GetPreservationsByMunicipalityId?municipalityId=" + municipalityId;
        }

        jQuery.ajax({
            url: urlRest,
            type: "GET",
            dataType: "json",
            contentType: "application/json",
            success: function (data) {

                var preservation = jQuery.map(data, function (item) {
                    return {
                        label: item.Name,
                        //label: item.Name + " (" + municipalityId + ")",
                        value: item.Id
                    };
                });

                jQuery("#preservationAutocomplete").autocomplete({
                    minLength: minLengthAutoComplete,
                    source: preservation,
                    focus: function (event, ui) {
                        jQuery(this).val(ui.item.label);
                        return false;
                    },
                    select: function (event, ui) {
                        jQuery(this).val(ui.item.label);

                        ui.item ?
							Cowi.Dn.showPreservation(ui.item.value, true, true) : //Cowi.Dn.loadPreservationDialog(ui.item.value) :
							alert("Ingen data fundet");

                        return false;
                    }
                });
            },
            error: function (xhr) {
                if (xhr.responseText) {
                    var err = xhr.responseText;
                    if (err)
                        var debug1 = err;
                    else
                        var debug2 = "Unknow server error";
                }
                return;
            }
        });
    },

    /*
    * Init preservation details dialog
    */
    initPreservationDialog: function () {

        var dialog = jQuery('<div/>', { id: "preservationContainer", title: "Fredning" })
			.append('<div id="preservationTabs"></div>');

        jQuery("#all").after(dialog);

        jQuery("#preservationContainer").dialog({
            autoOpen: false,
            close: function (event, ui) { },
            open: function (event, ui) { },
            //            dragStart: function (event, ui) {
            //                dialog.css({ opacity: '0.4', filter: 'alpha(opacity=40)' });
            //            },
            //            dragStop: function (event, ui) {
            //                dialog.css({ opacity: '1.0', filter: 'alpha(opacity=100)' });
            //            },
            position: ["right", "bottom"]
        });

        jQuery("#preservationContainer").dialog("option", "width", 420);
        jQuery("#preservationContainer").dialog("option", "height", 500);
        jQuery("#preservationContainer").dialog("option", "maxHeight", 800);
    },

    /*
    * Show preservation popup and zoom to bound of preservation
    */
    showPreservation: function (id, showPopup, zoomMap) {

        if ((id === 0) || (id === "0")) {
            alert("Fredningsbeskrivelse ikke udarbejdet på valgte fredning!");
            return;
        }

        if (showPopup) {
            Cowi.Dn.loadPreservationDialog(id);
        }

        if (zoomMap) {
            var sqlClause = 'SELECT * FROM "/stratus/' + Cowi.Dn.preservationLayer + '" WHERE ' + Cowi.Dn.preservationColumnId + ' = ' + id
            Cowi.Dn.zoomToBound(Cowi.Dn.custkey, Cowi.Dn.preservationLayer, sqlClause, 2);
        }
    },

    /*
    * @example: http://localhost:3423/dn/GetBound?custkey=demo&layer=frede_omr&sqlClause=select * from fredede_omr where id = 2044&srcProj=epsg:32632&destProj=3857
    * @param <string> custkey: Stratus instance name
    * @param <string> layer: MapInfo tab layer to query bound in
    * @param <string> sqlClause: retrieve feature to get bound of
    * @param <int> factor: Factorize the bound. Muse be in interval [1-8]. 2 = double bound etc..
    */
    zoomToBound: function (custkey, layer, sqlClause, factor) {

        if (factor < 1 || factor > 8) {
            alert("Factor in bound must be in interval [1;8]");
            return;
        }
        var param = "?custkey=" + custkey +
					"&layer=" + layer +
					"&sqlClause=" + sqlClause +
					"&srcProj=" + Cowi.Dn.srcProj +
					"&destProj=" + Cowi.Dn.destProj;

        var sUrl = "/Dn/GetBound" + param;

        jQuery.ajax({
            url: sUrl,
            type: "GET",
            dataType: "json",
            contentType: "application/json",
            success: function (data) {

                if (data !== null) {
                    // Enforce the factor
                    var factorArray = [0, 0, 0.5, 1, 2, 4, 8, 16]; //double width on one factor increment
                    var additivValue = (data.x2 - data.x1) * factorArray[factor];

                    var left = data.x1 - additivValue;
                    var bottom = data.y1 - additivValue;
                    var right = data.x2 + additivValue;
                    var top = data.y2 + additivValue;

                    var bounds = new OpenLayers.Bounds(left, bottom, right, top);

                    Cowi.Dn.map.zoomToExtent(bounds, true);
                }
                else {
                    // Debug alert. Should never be hit in production.
                    alert("Du har linket til en fredning eller kommune som ikke findes!");
                    return;
                }

            }
        });
    },

    /*
    * Load preservation details dialog when new id arrives from autocomplete or map click
    */
    loadPreservationDialog: function (id) {

        Cowi.Dn.currentPreservation.setId(id)

        var sUrl = "/Dn/GetPreservationsItem?preservationId=" + id;

        jQuery.ajax({
            url: sUrl,
            type: "GET",
            dataType: "json",
            contentType: "application/json",
            success: function (data) {

                jQuery("#preservationContainer").dialog('close');
                jQuery("#preservationContainer").dialog("option", "title", data.Name);

                var accordion = jQuery("#preservationTabs");

                if (jQuery("#preservationItemList").length === 0) {
                    accordion.append('<ul id="preservationItemList"><li><a href="#tabs-1">Fredning</a></li> <li><a href="#tabs-2">Turforslag m.m.</a></li> <li><a href="#tabs-3">Vejbeskrivelse</a></li> </ul>');

                    accordion.append('<div id="tabs-1"></div>');
                    accordion.append('<div id="tabs-2"></div>');
                    accordion.append('<div id="tabs-3"></div>');
                }

                var divPreservation = jQuery("#tabs-1");
                var divTrip = jQuery("#tabs-2");
                var divRoad = jQuery("#tabs-3");

                divPreservation.empty();
                divTrip.empty();
                divRoad.empty();

                // Tab 1 Preservation
                jQuery('<img/>', { 'class': "print-icon", alt: "Print", title: "Åbn fredning i nyt vindue i udskrifts venligt format", src: "/content/images/print-icon.gif" })
					.click(Cowi.Dn.openPrintableWindow)
					.appendTo(divPreservation);

                // Deeplink
                var urlWithNoParam = location.protocol + "//" + location.host + location.pathname;
                var deeplinkpath = urlWithNoParam + "?id=" + id;
                var deeplinkTextbox = jQuery('<input>', { type: "text", value: deeplinkpath }).css({ width: '350px' });
                divPreservation.append(jQuery('<h3 style="margin: 8px 0px 1px 0px;">Link til fredning</h3>'));
                divPreservation.append(deeplinkTextbox);

                Cowi.Dn.appendPreservationItemDetails(divPreservation, "Indledning", data.Description);
                Cowi.Dn.appendPreservationItemDetails(divPreservation, "Landskabet", data.Landscape);
                Cowi.Dn.appendPreservationItemDetails(divPreservation, "Plantelivet", data.Flora);
                Cowi.Dn.appendPreservationItemDetails(divPreservation, "Dyrelivet", data.Fauna);
                Cowi.Dn.appendPreservationItemDetails(divPreservation, "Kulturhistorie", data.CulturalHistory);
                Cowi.Dn.appendPreservationItemDetails(divPreservation, "Fredningen og dens pleje", data.Care);

                // Tab 2 - Trips
                Cowi.Dn.appendPreservationItemDetails(divTrip, "Ture og seværdigheder", data.Trips);
                Cowi.Dn.appendLocalOffices(divTrip, "Adresser, folder, m.m.", data.DnLocalOffices);
                Cowi.Dn.appendPreservationItemDetails(divTrip, "", data.AdditionalInfo);

                Cowi.Dn.appendPreservationItemDetails(divTrip, "Kommentar / forslag", "<p>Du er meget velkommen til at kontakte os med kommentarer eller forslag til rettelser til denne fredning. Du kan skrive din kommentar / forslag herunder.</p>");
                divTrip.append('<p style="margin-bottom:4px">Fredningens navn:</p>');
                divTrip.append('<input id= "inputPreservationName" type="text" value="123" readonly="true" style="width:350px; background-color:#EBEBE4;"></input>');
                jQuery("#inputPreservationName").val(data.Name);

                divTrip.append('<p style="margin-bottom:4px">Skriv din kommentar / forslag her:</p>');
                divTrip.append('<textarea id="inputComment" rows="5" cols="47"></textarea>');

                divTrip.append('<p style="margin-bottom:4px">Navn:</p>');
                divTrip.append('<input id= "inputName" type="text" style="width:350px"></input>');

                divTrip.append('<p style="margin-bottom:4px">Email:</p>');
                divTrip.append('<input id= "inputEmail" type="text" style="width:350px"></input>');

                divTrip.append('</br><input id="inputButton" type="Button" value="Send besked" onclick="Cowi.Dn.SendMessage()"></input>');

                // Tab 3 - Road
                Cowi.Dn.appendPreservationItemDetails(divRoad, "GPS-koordinater", '<p>X: ' + data.Xcoord + ', Y:' + data.Ycoord + '</p>');
                Cowi.Dn.appendPreservationItemDetails(divRoad, "Vejbeskrivelse", data.Road);

                // Do not create the tab before the dynamic generated DOM has loaded in above js.
                jQuery("#preservationTabs").tabs();
                jQuery("#preservationTabs").tabs('select', 0);

                jQuery("#preservationContainer").dialog('open');
            }
        });
    },

    /*
    * Save comment from user
    */
    SendMessage: function () {
        var input = {
            preservationId: Cowi.Dn.currentPreservation.getId(),
            comment: jQuery("#inputPreservationName").val() + ': ' + jQuery("#inputComment").val(),
            name: jQuery("#inputName").val(),
            email: jQuery("#inputEmail").val()
        };

        var sUrl = "/Dn/SavePreservationComment";

        jQuery.ajax({
            type: "POST",
            url: sUrl,
            data: JSON.stringify(input),
            datatype: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                // zero the user input controls
                jQuery("#inputComment").val("");
                jQuery("#inputName").val("");
                jQuery("#inputEmail").val("");

                alert(data);
            }
        });
    },

    /*
    * Append the preservation item to div
    */
    appendPreservationItemDetails: function (div, heading, text) {
        if (text !== null) {
            jQuery('<h3 style="margin: 8px 0px 1px 0px;">' + heading + '</h3>').appendTo(div);
            jQuery(text).appendTo(div);
        }
    },

    /*
    * append the one or several local offices attached to a preservation
    */
    appendLocalOffices: function (div, heading, localoffices) {
        if (localoffices !== null) {

            jQuery('<h3 style="margin: 8px 0px 1px 0px;">' + heading + '</h3>').appendTo(div);

            jQuery.each(localoffices, function (key, value) {
                jQuery('<p>Om Danmarks Naturfredningsforening lokalt:</p>').appendTo(div);

                div.append(value.DnName);
                div.append('</br>');
                div.append(value.Name);
                div.append('</br>');
                div.append(value.Road);
                div.append('</br>');
                div.append(value.Postalcode + ' ' + localoffices[0].Postaldistrict);
                div.append('</br></br>');

                div.append("Tlf.: " + value.Phone);
                div.append('</br>');
                div.append("Email: " + value.Email);
                div.append('</br>');
                div.append("Web: " + value.Web);
                div.append('</br></br>');
            });
        }
    },

    /*
    * Print preservation details
    */
    openPrintableWindow: function () {
        url = '/home/print?preservationId=' + Cowi.Dn.currentPreservation.getId();
        window.open(url, 'Udskriv', 'width=820, height=600, scrollbars=yes, resizeable=yes');
    },

    /*
    * Init map
    */
    initMap: function () {

        OpenLayers.ProxyHost = "/proxy?url=";

        var options =
		{
		    projection: new OpenLayers.Projection("EPSG:900913"),
		    maxExtent: new OpenLayers.Bounds(856774, 7244677, 1726562, 7969318),
		    restrictedExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34), // "restrictedExtent" should prevent WMS layer not aligned with BING maps see: http://trac.osgeo.org/openlayers/ticket/2541
		    units: "m",
		    numZoomLevels: 18,
		    controls:
			[
				new OpenLayers.Control.Navigation(),
				new OpenLayers.Control.PanZoomBar(),
		    //new OpenLayers.Control.Scale(),
				new OpenLayers.Control.Attribution(),
				new OpenLayers.Control.LayerSwitcher()
		    //new OpenLayers.Control.MousePosition()
			]
		};

        Cowi.Dn.map = new OpenLayers.Map('map', options);

        var shaded = new OpenLayers.Layer.VirtualEarth("Shaded", {
            type: VEMapStyle.Shaded, sphericalMercator: true
        });
        var hybrid = new OpenLayers.Layer.VirtualEarth("Hybrid", {
            type: VEMapStyle.Hybrid, sphericalMercator: true
        });
        var aerial = new OpenLayers.Layer.VirtualEarth("Aerial", {
            type: VEMapStyle.Aerial, sphericalMercator: true
        });

        var url = "http://stratus.gis-hotel.dk/wms?custkey=" + Cowi.Dn.custkey;
        if (window.location.host.indexOf("localhost") > -1) {
            url = "http://localhost:2818/wms?custkey=" + Cowi.Dn.custkey;
        }

        var komg = new OpenLayers.Layer.WMS(
			"Kommunegrænser",
			url,
			{
			    layers: "komg",
			    format: "image/png"
			},
			{
			    visibility: true,
			    isBaseLayer: false
			}
		);

        var fred = new OpenLayers.Layer.WMS(
			"Fredninger",
			url,
			{
			    layers: "fred",
			    format: "image/png"
			},
			{
			    visibility: true,
			    isBaseLayer: false
			}
		);

        var fredinfo = new OpenLayers.Control.WMSGetFeatureInfo({
            title: 'Identify features by clicking',
            layers: [fred],
            maxFeatures: 1,
            queryVisible: true, // Hidden layers won't be queried.
            infoFormat: 'application/vnd.ogc.gml',
            eventListeners: {
                getfeatureinfo: Cowi.Dn.getFeatureInfo
            }
        });

        Cowi.Dn.map.addControl(fredinfo);

        fredinfo.activate();

        Cowi.Dn.map.addLayers([shaded, hybrid, aerial, komg, fred]);

        Cowi.Dn.map.setCenter(new OpenLayers.LonLat(1100000, 7600000), 6);
    },

    /*
    * WMS GetFeatureInfo
    */
    getFeatureInfo: function showInfo(event) {
        if (event.features.length > 0) {
            var firstFeature = event.features[0];
            if (firstFeature.attributes.hasOwnProperty("Id")) {
                var id = firstFeature.attributes.Id;

                // Update autocomplete when user picks a preservation from map
                if (firstFeature.attributes.hasOwnProperty("Text")) {
                    jQuery("#preservationAutocomplete").val(firstFeature.attributes.Text)
                }

                Cowi.Dn.showPreservation(id, true, false);
            }
        }
    },

    /**
    * Adjusts the map height to match the window height
    */
    adjustMapToWindowHeight: function () {
        var windowHeight = jQuery(window).height();
        jQuery("#map").height(windowHeight);
    }
};

/*
* hidePix and showPix is not included in Cowi.Dn due to backwards compability to fredninger.dk
*/
function hidePix() {
    jQuery("#divPixLayer").css({ display: 'none' });
}

/*
* hidePix and showPix is not included in Cowi.Dn due to backwards compability to html written in db
* Called from client html like:
* <a onmouseover="showPix(event,'http://www.fredninger.dk/dnressources/Engelsød_Biopix_JCS.jpg')" 
*    onmouseout="hidePix()" href="javascript:void(0)">almindelig engelsød</a>
*/
function showPix(event, pixUrl) {
    var pixdiv = jQuery("#divPixLayer").css({ display: 'none' });

    //alert("navigator.appName: " + navigator.appName);

    var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;

    if (isChrome) {
        pixdiv.css({ left: event.clientX + document.body.scrollLeft + 'px' });
        pixdiv.css({ top: event.y + 20 + document.body.scrollTop + 'px' });
    }
    else if (navigator.appName === "Microsoft Internet Explorer") {
        if (Cowi.Dn.embedded) {
            pixdiv.css({ left: event.clientX });
            pixdiv.css({ top: event.clientY });
        }
        else {
            if (window.location.pathname.toLowerCase().indexOf('/home/print') > -1) {
                pixdiv.css({ left: event.offsetX + document.documentElement.scrollLeft + 'px' });
                pixdiv.css({ top: event.offsetY + document.documentElement.scrollTop + 20 + 'px' });
            }
            else {
                pixdiv.css({ left: event.offsetX });
                pixdiv.css({ top: event.offsetY });
            }
        }
    }
    else if (navigator.appName === "Netscape") {
        if (window.location.pathname.toLowerCase().indexOf('/home/print') > -1) {
            pixdiv.css({ left: event.pageX + 'px' });
            pixdiv.css({ top: event.pageY + 20 + 'px' });
        }
        else {
            pixdiv.css({ left: event.clientX });
            pixdiv.css({ top: event.clientY });
        }
    }
    else {
        pixdiv.css({ left: event.clientX + document.body.scrollLeft + 'px' });
        pixdiv.css({ top: event.y + 20 + document.body.scrollTop + 'px' });
    }

    pixdiv.css({ display: 'inline' });
    jQuery("#imgPopup").attr('src', pixUrl);
}

