﻿var geoURL = "http://demo.maptoweb.dk/mapToWebJson/getLocationWithInfo.aspx";
var map = null;
var geocoder = null;
var mapLoaded = false;
var baseIcon = null;
var markerArray = new Array();
var FoliaBox = null;

//input stuff
var mapDefaultHeight = 346;
var onMapMoveText = "kortudsnit";
var defaultWhereText = "Hvor";
var defaultPostalCodeText = "By, postnr";
var JsonResidenceResult;
var residenceDialogContentOnlyURL = "/map/ResidenceDialogContentOnly.aspx?aid=";
var selectedSearchText = null;

var selectedClusterItem = null
var mapViewAllButton = null;
//references
var whereField;
var postalCodeField;
var validPostFieldText = "";
var hiddelPostalCodeField;
var addressDropdownField;
var addressDropdownDataField;
var xmaxField;
var xminField;
var ymaxField;
var yminField;
var mapTypeField;
var mapField;
var clatField;
var clngField;
var zoomField;

//Icons
//var rentedhousingIcon = "/gfx/boligikon26-leje-ledig.png";
//var youthRentedhousingIcon = "/gfx/boligikon26-leje-ledig.png";
//var clusterIcon = "/gfx/boligikon26-generel-blaa.png";

var rentedhousingIcon = "/gfx/boligikon.png";
var youthRentedhousingIcon = "/gfx/boligikon.png";
var clusterIcon = "/gfx/boligikon-cluster.png";

//---------------------------------
// Setup Google map for SearchAgent
//---------------------------------
function initializeGoogleMapSearchAgent() {
    if (GBrowserIsCompatible()) {
        mapLoaded = true;
        mapField = document.getElementById("map_canvas");
        map = new GMap2(mapField);
        
        //------------------------------------------------------
        //set normal street map
        //------------------------------------------------------
        map.setMapType(G_NORMAL_MAP);
        map.enableScrollWheelZoom();

        //------------------------------------------------------
        //show and zoom to denmark
        //------------------------------------------------------
        map.setCenter(new GLatLng(56, 10.6), 6);
        geocoder = new GClientGeocoder();

        //------------------------------------------------------
        //Adding google controls
        //------------------------------------------------------
        map.addControl(new GLargeMapControl3D());
    }
}



//-------------------------------
// Setup Google map
//-------------------------------
function initializeGoogleMap() {
    
    if (GBrowserIsCompatible()) {                
        mapLoaded = true;
        mapField = document.getElementById("map_canvas");
        map = new GMap2(mapField);
        map.enableContinuousZoom();

        baseIcon = new GIcon();

        baseIcon.shadow = "/gfx/boligikon-skygge.png";
        baseIcon.shadowSize = new GSize(48, 44);
        baseIcon.infoShadowAnchor = new GPoint(1, 1);

        baseIcon.iconSize = new GSize(35, 44);
        baseIcon.iconAnchor = new GPoint(17, 38);
        baseIcon.infoWindowAnchor = new GPoint(10, -8);
        
        //------------------------------------------------------
        //set normal street map
        //------------------------------------------------------
        map.setMapType(G_NORMAL_MAP);        
        map.enableScrollWheelZoom();

        //------------------------------------------------------
        //show and zoom to denmark
        //------------------------------------------------------
        map.setCenter(new GLatLng(56, 10.6), 6);
        geocoder = new GClientGeocoder();

        //------------------------------------------------------
        //Adding google controls
        //------------------------------------------------------
        map.addControl(new GLargeMapControl3D());                                  
    }
}


//------------------------------------------------------
//Changeing the map type of the google map
//------------------------------------------------------
function changeMapType(googleMapType) {
    map.setMapType(googleMapType);    
}

//----------------------------------------------
// Request the server based on the search query
//----------------------------------------------
function updateMap() {    
       
    updateHiddenXYFromMapBounds();

    if (map.getZoom() < 5) 
    {
            clearMarkers();
            return;
    }
    zoomField.value = map.getZoom();   
    
    var SearchAgentJson = $.toJSON(SearchCriteriasObject.SearchAgent);

    $.ajax({
        //-------- DEFAULT AJAX POST -----------
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataFilter: function(data) {
            var msg;
            if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function')
                msg = JSON.parse(data);
            else
                msg = eval('(' + data + ')');

            if (msg.hasOwnProperty('d'))
                return msg.d;
            else
                return msg;
        },
        //-------- DEFAULT AJAX POST -----------        
        url: "/Services/MapServices.asmx/GetMarkers",
        data: "{\"searchAgentJson\": " + SearchAgentJson + "}",
        success: function(msg) {
            JsonResidenceResult = $.evalJSON(msg);
            initMarkers();            
        },
        error: function(msg) {
            alert('Failed' + msg.responseText);            
        }
    });
}

//---------------------------------------------------
// Clear markers will remove all markers from the map
//---------------------------------------------------
function clearMarkers() {
    for (var j = 0; j < markerArray.length; j++)
        map.removeOverlay(markerArray[j]);

    markerArray = new Array();    
}


//-------------------------------------------------------
// JsonResidenceResult contains the reulst on markers to 
// be displayed. We will now render the markers on screen
//-------------------------------------------------------
function initMarkers() {
                
    // Create a base icon for all of our markers that specifies the
    // shadow, icon dimensions, etc. (CLUSTER javscript icon is defined in the Clusterer2.js file)
    clearMarkers();        
                
    if (JsonResidenceResult != null && JsonResidenceResult.clusters != null) {
        for (i = 0; i < JsonResidenceResult.clusters.length; i++) {
            var clusterItem = JsonResidenceResult.clusters[i];
            var point = new GLatLng(clusterItem.lat, clusterItem.lon);
            var newMarker;
            if (clusterItem.ids.length > 1) {
                //item is a cluster
                newMarker = createMarker(point, -1, clusterItem);
            }
            else {
                //single item
                newMarker = createMarker(point, 1, clusterItem);
            }
            
            markerArray[i] = newMarker                        
        }
    }
}
//-------------------------------------------------------
// Create a maker to be displayed on map
//-------------------------------------------------------
function createMarker(point, residenceType, clusterItem) {            
    var letteredIcon = new GIcon(baseIcon);
    if (residenceType == 1) //ledige boliger
        letteredIcon.image = rentedhousingIcon;
    else if (residenceType == 2)//ungdomsboliger
        letteredIcon.image = youthRentedhousingIcon;
    else if (residenceType == -1)//contains many items and will be defined as cluster
        letteredIcon.image = clusterIcon;

    markerOptions = { icon: letteredIcon };
    var marker = new GMarker(point, markerOptions);

    GEvent.addListener(marker, "click", function() {

        if (clusterItem.ids.length > 1) {
            selectedClusterItem = clusterItem;            
        }
        else {
            selectedClusterItem = null;
        }

        var URL = residenceDialogContentOnlyURL + clusterItem.ids[0] + "&lan=" + currentLang;

        marker.openExtInfoWindow
        (
            map,
            "mapDialogBoxContainer",
            "<div id=\"mapDialogBoxLoader\"><img src=\"/img/loader.gif\"></div>",
            { beakOffset: 3 }
        );

        if (clusterItem.ids.length > 1) {
            RenderMapdialogCluster(URL, clusterItem.ids.length, marker);
        } else {
            RenderMapdialogSingle(URL, marker);
        }
    });
    
    map.addOverlay(marker);
    return marker;
}


//-------------------------------------------
// Render map dialog for a a singel residence 
//-------------------------------------------
function RenderMapdialogSingle(url, marker) {
    $.get(url, function(data) {
        marker.openExtInfoWindow(
            map,
            "mapDialogBoxContainer",

            "<div id='mapDialogBox'>" +
	            "<a href='#' onclick='map.closeExtInfoWindow();' class='close'><img src='/gfx/clear.gif' width='13' height='13' border='0' alt='Luk' /></a>" +
                "<div id='mapDialogBoxContent'>" + data + "</div>" +
            "</div>"
            ,
            { beakOffset: 3 });        
    });
}

//---------------------------------------------------
// Render map dialog for a multi/clustered residence
// "previousResidence, nextResidence, of is located
// MapTranslationElements.ascx"
//---------------------------------------------------
function RenderMapdialogCluster(url, pageing, marker) {
    $.get(url, function(data) {
        marker.openExtInfoWindow(
            map,
            "mapDialogBoxContainer",

            "<div id='mapDialogBox'>"+
	            "<p class='mapDialogBoxPaging'>"+
		            "<a href='#' onclick='map.closeExtInfoWindow();' class='close'><img src='/gfx/clear.gif' width='13' height='13' border='0' alt='Luk' /></a>"+
		            "<a href='#' onclick='residenceDialogPrevious(document.getElementById(\"currentNum\"))'> < " + previousResidence + " </a> <span id='currentNum'>1</span> " + of + " <span id='totalNum'> " + pageing + " </span> <a href='#' onclick='residenceDialogNext(document.getElementById(\"currentNum\"), document.getElementById(\"totalNum\"))'> " + nextResidence + " > </a>" +
	            "</p>"+
	            "<div></div>"+            		            
                "<div id='mapDialogBoxContent'>"+data+"</div>"+
            "</div>"
            ,
            { beakOffset: 3 });
    });
}



//-------------------------------------------------------
// Create a maker to be displayed on map
//-------------------------------------------------------
function createMarkerSimple(point, residenceType) {
    var letteredIcon = new GIcon(baseIcon);
    if (residenceType == 1) //ledige boliger
        letteredIcon.image = rentedhousingIcon;
    else if (residenceType == 2)//ungdomsboliger
        letteredIcon.image = youthRentedhousingIcon;
    else if (residenceType == -1)//contains many items and will be defined as cluster
        letteredIcon.image = clusterIcon;

    markerOptions = { icon: letteredIcon };
    var marker = new GMarker(point, markerOptions);
    
    map.addOverlay(marker);
}

//------------------------------------------
// Function used when map zooming has ended
//------------------------------------------
function mapZoomEnded(newZoomLevel) {    
    updateMap();           
}


//------------------------------------------------------------------------------------
// When loading the page we will try and set the map type according to the search agent
//------------------------------------------------------------------------------------
function setMapTypeOnLoad() {
    var loadedMapType = mapTypeField.value;
    var maptypes = map.getMapTypes()
    for (i = 0; i < maptypes.length; i++) {
        if (loadedMapType == maptypes[i].getName()) {            
            map.setMapType(maptypes[i]);              
        }
    }
}


//-------------------------------
// Setup Google without map
//-------------------------------
function initializeGoogleGeo() {
    if (GBrowserIsCompatible()) {        
        geocoder = new GClientGeocoder();
    }
}

//====================================
// ********  PostalCodes  ********  
//====================================

//-----------------------------------------------------------
// Setup postal code text field in order to handle key events
//-----------------------------------------------------------
function setupSearchCriteriasEventsOnPostalCode() {

    $(postalCodeField).keyup(function(e) {
        if (e.which == 40) {
            IsArrayDown = true;
        }
        else {
            IsArrayDown = false;
        }
        timerCall(function() {//Will wait 100 millsec before calling the search
            if (e.which != 32 || //space                    
                    e.which == 40 ||  //enter                
                    e.which == 190 || //æ
                    e.which == 222 || //ø
                    e.which == 221 || //å
                    (65 <= e.which && e.which <= 65 + 25) ||
                    (97 <= e.which && e.which <= 97 + 25)) {
                if (e.which == 13) { //enter button                   
                    var listItem = GetFirstDropDownListItem(addressDropdownDataField);
                    if (listItem != null) {

                        if (mapLoaded)
                        { map.closeExtInfoWindow(); }
                        
                        ZoomToSelectedListItem(listItem);
                        postalCodeField.blur();
                        postalCodeField.focus();
                        if (!mapLoaded) {
                            doSearch();
                        }
                    }
                    else {
                        //alert("nothing selected");
                    }
                }
                else {
                    DoPostalCodeSearch(e);
                }
            }

        }, 150);
    });

    //Disable Enter button on input field
    $(postalCodeField).keydown(function(e) {
        return !(e.which == 13);
    });

    $(postalCodeField).focus(function(e) {
        clearField(this, defaultPostalCodeText, true); doFocus(this);
    });

    $(postalCodeField).blur(function(e) {
        closeDropdown();
        if (whereField.value != selectedSearchText) {
            whereField.value = selectedSearchText;
            whereField.style.color = "rgb(150,150,150)";
        }        
    });

    if (postalCodeField.value.length <= 0)
        postalCodeField.value = defaultPostalCodeText;


    //============================
    //      dropdown field
    //============================
    $(addressDropdownDataField).keyup(function(e) {
        if (e.which == 13) { //Enter
            if (mapLoaded)
            { map.closeExtInfoWindow(); }            
            listItem = GetSelectedDropDownListItem(addressDropdownDataField);
            ZoomToSelectedListItem(listItem);
            postalCodeField.focus();
            if (!mapLoaded) {
                doSearch();
            }
        }
    });

    $(addressDropdownDataField).blur(function(e) {
        closeDropdown();
    });

    $(addressDropdownDataField).click(function(e) {
        setTimeout(function() {
            listItem = GetSelectedDropDownListItem(addressDropdownDataField);
            ZoomToSelectedListItem(listItem);
            postalCodeField.focus();
            doSearch();
        }, 0);
    });

    $(addressDropdownDataField).focus(function(e) {
        keepDropdownOpen();
    });

}

//------------------------------------------------------------------------
// Do Postal code search based on the value from the postalCode text field
//------------------------------------------------------------------------
function DoPostalCodeSearch(evt) {
    if (evt.which == 13) { //enter button
        //Do nothing // "ENTER BUTTON"
    } else if (evt.which == 40) { // arrowdown button
        if (addressDropdownField.style.display != 'none' && addressDropdownDataField.options.length > 0) {
            addressDropdownDataField.focus();
            addressDropdownDataField.options[0].selected = true;
        }
    } else {
        removeAllOptions(addressDropdownDataField, function() {            
            if (postalCodeField.value.length > 0 && postalCodeField.value != "") 
            {
                getPostalCodes(postalCodeField.value);
            } 
            else 
            {
                $(addressDropdownField).hide('fast');
            }
        });        
    }
}

//-----------------------------------------------------------------
// Get list of postal codes based on search query (database search)
//-----------------------------------------------------------------
function getPostalCodes(searchString) {
    $.ajax({
        //-------- DEFAULT AJAX POST -----------
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataFilter: function(data) {
            var msg;
            if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function')
                msg = JSON.parse(data);
            else
                msg = eval('(' + data + ')');

            if (msg.hasOwnProperty('d'))
                return msg.d;
            else
                return msg;
        },
        //-------- DEFAULT AJAX POST -----------
        url: "/Services/MapServices.asmx/GetPostalCodes",
        data: "{searchString:'" + searchString + "'}",
        success: function(msg) {
            AddPostalCodesToDropDown($.evalJSON(msg));            
        },
        error: function(msg) {
            alert('Failed' + msg.responseText);
        }
    });        
}


//---------------------------------------------------------------
// Add the results from the PostalCode  search to the dropdown box
//---------------------------------------------------------------
function AddPostalCodesToDropDown(postalCodeList) {

    var countedElements = 0;
    for (var i = 0; i < postalCodeList.length; i++) {
        postal = postalCodeList[i];
        
        IsCustomArea = postal.IsCustomArea;
        PostalCode = postal.PostalCodeID;
        Xmin = postal.Xmin;
        Xmax = postal.Xmax;
        Ymin = postal.Ymin;
        Ymax = postal.Ymax;

        if (IsCustomArea == true) {
            text = postal.City;
        } else {
            text = postal.City + ", " + postal.PostalCodeText;                                           
        }
        value = IsCustomArea + "|"; // array 0
        value += PostalCode + "|"; // array 1
        value += Xmin + "|"; // array 2
        value += Xmax + "|"; // array 3
        value += Ymin + "|"; // array 4
        value += Ymax; // array 5
        
        addOption(addressDropdownDataField, text , value);
        countedElements++;

    } 
       
    if (countedElements > 0) {
        $(addressDropdownField).show('fast');                
    } else {
        $(addressDropdownField).hide('fast');
    }
}

//----------------------------------------------
// Resutns the first element from the select box
// Returns null if nothing found
//----------------------------------------------
function GetFirstDropDownListItem(select) {    
    if (select.children.length > 0 && select.selectedIndex < 0 && select.options.length > 0) {
        return select.options[0];        
    }
    return null;
}

//-----------------------------------------------
// map zooms based on the selected dropdown value
//-----------------------------------------------
function GetSelectedDropDownListItem(select) {
    if (select.selectedIndex > -1) {
        return select.options[select.selectedIndex];
    }
    return null;
}

//-----------------------------------------------------
// Zoom to map area based on the value in the list item
//-----------------------------------------------------
function ZoomToSelectedListItem(listItem) {    
        if (listItem != null) {

            selectedListItemArray = listItem.value.split('|');

            if (selectedListItemArray[0] == "true") {
                //update Xmax, Xmin, Ymax, Ymin with the result from the selected dropdown element
                xminField.value = selectedListItemArray[2];
                xmaxField.value = selectedListItemArray[3];
                yminField.value = selectedListItemArray[4];
                ymaxField.value = selectedListItemArray[5];

                //Set the text to be shown on screen
                postalCodeField.value = listItem.text;
                validPostFieldText = postalCodeField.value;
                //Set the postal ID in the hidden field. to be use with query string
                hiddelPostalCodeField.value = selectedListItemArray[1];
                
                gotoArea(xmaxField.value, xminField.value, ymaxField.value, yminField.value, "");
            }
            else {                
                //Set the text to be shown on screen
                postalCodeField.value = listItem.text;
                validPostFieldText = postalCodeField.value;
                //Set the postal ID in the hidden field. to be use with query string
                hiddelPostalCodeField.value = selectedListItemArray[1];

                //Call Folia in order to get coordinates and then update Xmax, Xmin, Ymax, Ymin
                CallFoliaAndSetXYPos(selectedListItemArray[1]);
            }                        
        }

        closeDropdown();    
}

//-------------------------------------------------------------------
// Call Folia and get the area coordinates related to the postalcode
//-------------------------------------------------------------------
function CallFoliaAndSetXYPos(postalcode) {
    $.getJSON(geoURL +
        "?AddressPostalID=" + selectedListItemArray[1] +
        "&response=?",
    function(data) {
        if (data[0] != null) {
            xminField.value = data[0].ExtentXmin;
            xmaxField.value = data[0].ExtentYmax;
            yminField.value = data[0].ExtentYmin;
            ymaxField.value = data[0].ExtentXmax;            
            gotoArea(xmaxField.value, xminField.value, ymaxField.value, yminField.value, "");
        }
    });
}


//====================================


//-------------------------------------------------------------
// Do geo google search based on the value from the where field
//-------------------------------------------------------------
function GeoSearchGoogle(evt) {
    if (evt.which == 13) { //enter button
        //Do nothing // "ENTER BUTTON"
    } else if (evt.which == 40) { // arrowdown button
        if (addressDropdownField.style.display != 'none' && addressDropdownDataField.options.length > 0) {
            addressDropdownDataField.focus();
            addressDropdownDataField.options[0].selected = true;
        }    
    } else {
    
        removeAllOptions(addressDropdownDataField);            
        //select.parentNode.style.display = 'none';
        geocoder.getLocations(whereField.value, listGoogleGeoResults);
    }    
}
//---------------------------------------------------------------
// Add the results from the google geo search to the dropdown box
//---------------------------------------------------------------
function listGoogleGeoResults(response) {   
    if (response && response.Status.code == 200) {
        //addressDropdownDataField.innerHTML = "";
        var countedElements = 0;
                                
        for (var i = 0; i < response.Placemark.length; i++) {
            place = response.Placemark[i];
            if (place != null && place.AddressDetails.Country != null && place.AddressDetails.Country.CountryNameCode == "DK")// Only list DK
            {
                addOption(addressDropdownDataField, place.address, getSouth(place) + "|" + getWest(place) + "|" + getNorth(place) + "|" + getEast(place));                
                countedElements++;
            }
        }

        if (countedElements > 0) {
            $(addressDropdownField).show('fast');
    //        var colLeftPos = $("#colLeft").offset().left-0+10;
    //        $(addressDropdownField).css('left', colLeftPos + 'px');       
        } else {
            $(addressDropdownField).hide('fast');        
        }                
    }
}

//---------------------------------------------------------------
// Remove all options from dropdown
//---------------------------------------------------------------
function removeAllOptions(selectbox, fnCallback) {    
    if (selectbox.options) {
        var i;
        for (i = selectbox.options.length - 1; i >= 0; i--) {
            selectbox.remove(i);
        }
    }    
    
    fnCallback();
}

//---------------------------------------------------------------
// Add options to dropdown
//---------------------------------------------------------------
function addOption(selectbox, text, value) {
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}


//----------------------------------------------------
// Zoom to area on map and set values on hidden fields
// coordinates and clicked field
// obj = cliked dropdown element
//----------------------------------------------------
function gotoArea(ExtentXmax,ExtentXmin,ExtentYmax,ExtentYmin,addressText) 
{        
    if (ExtentXmax != "" && ExtentXmin != "" && ExtentYmax != "" && ExtentYmin != "" && ExtentXmax != 0 && ExtentXmin != 0 && ExtentYmax != 0 && ExtentYmin != 0) {        
            updateHiddenLATLNG(ExtentXmax, ExtentXmin, ExtentYmax, ExtentYmin);
            if(addressText != null)
                whereField.value = addressText;        

        if (mapLoaded) {

            zoomedByUser = false;
            // Define the two corners of the bounding box
            var sw = new GLatLng(ExtentXmax, ExtentXmin);
            var ne = new GLatLng(ExtentYmax, ExtentYmin);

            // Create a bounding box   
            var bounds = new GLatLngBounds(sw, ne);

            // Center map in the center of the bounding box   
            // and calculate the appropriate zoom level    
            var viewport = new GLatLngBounds;

            viewport.extend(new GLatLng(ExtentXmax, ExtentXmin));
            viewport.extend(new GLatLng(ExtentYmax, ExtentYmin));

            map.setCenter(viewport.getCenter(), map.getBoundsZoomLevel(viewport));

            var expandMapLink = document.getElementById("expandMapLink");
            if(expandMapLink != null)
            {
                expandMapLink.style.color = "rgb(0,0,0)";
            }                        
                     
            /*
            //CAP show test point
            var marker1 = new GMarker(sw);
            var marker2 = new GMarker(ne);
            map.addOverlay(marker1);
            map.addOverlay(marker2);

            debug(ExtentXmax + ", " + ExtentXmin + ", " + ExtentYmax + ", " + ExtentYmin);       
            */
        }
    }
}
//--------------------------------
// udate the hidden coordiantes 
//----------------------------------
function updateHiddenLATLNG(ExtentXmax, ExtentXmin, ExtentYmax, ExtentYmin) {
    xmaxField.value = ExtentXmax;
    xminField.value = ExtentXmin;
    ymaxField.value = ExtentYmax;
    yminField.value = ExtentYmin;
}
//-----------------------------------------------------
// Get Goolge coordiantes and update the hidden fields
//-----------------------------------------------------
function updateHiddenXYFromMapBounds() {
    if (mapLoaded) {
        var bounds = map.getBounds();
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();
        xmaxField.value = southWest.y;
        xminField.value = southWest.x;
        ymaxField.value = northEast.y;
        yminField.value = northEast.x;
        mapTypeField.value = map.getCurrentMapType().getName(true);

        clatField.value = map.getCenter().lat();
        clngField.value = map.getCenter().lng();
        zoomField.value = map.getZoom();

        SearchCriteriasObject.SearchAgent.xmax = southWest.y;
        SearchCriteriasObject.SearchAgent.xmin = southWest.x;
        SearchCriteriasObject.SearchAgent.ymax = northEast.y;
        SearchCriteriasObject.SearchAgent.ymin = northEast.x;
        SearchCriteriasObject.SearchAgent.maptype = map.getCurrentMapType().getName(true);

        SearchCriteriasObject.SearchAgent.clat = map.getCenter().lat();
        SearchCriteriasObject.SearchAgent.clng = map.getCenter().lng();
        SearchCriteriasObject.SearchAgent.z = map.getZoom();
    }
    else {
        clatField.value = "";
        clngField.value = "";
        zoomField.value = "";
    }
}

//--------------------------------------------------
//Add Folia Points Of Interests to Google map
//--------------------------------------------------
function AddPointsOfInterests() {
    FoliaBox = new Folia.UI.FoliaBox();
    Folia.Controls.PointsOfInterest.ImageURL = "/gfx/foliatema/"

    var POIs = new Folia.Controls.PointsOfInterest();

    POIs.Layout = {
        Category1: { title: ChildrenAndEducation, Layers: [
            POIs.PoiLayers.Layer81,  //Skole
            POIs.PoiLayers.Layer82,  //Mellemlang uddannelse
            POIs.PoiLayers.Layer83,  //Lang uddannelse
            POIs.PoiLayers.Layer84  //Børnepasning
        ]
        },
        Category2: { title: SportsAndRecreationText, Layers: [
            POIs.PoiLayers.Layer90,  //Sportshal
            POIs.PoiLayers.Layer91,  //Svømmehal
            POIs.PoiLayers.Layer110, //Stadion
            POIs.PoiLayers.Layer95,  //Biograf
            POIs.PoiLayers.Layer96,  //Bibliotek
            POIs.PoiLayers.Layer97  //Teater
        ]
        },
        Category3: { title: PublicServiceText, Layers: [
            POIs.PoiLayers.Layer87,  //Hospital
            POIs.PoiLayers.Layer88,  //Politi                        
            POIs.PoiLayers.Layer111, //Posthus
            //POIs.PoiLayers.Layer112, //Postbutik
            POIs.PoiLayers.Layer113 //Bank
            //POIs.PoiLayers.Layer116  //Genbrugsplads                        
        ]
        },
        Category4: { title: StoreText, Layers: [
            POIs.PoiLayers.Layer85  //Indkøb
            //POIs.PoiLayers.Layer109 //Storcentre
        ]}
        };    
    
    FoliaBox.addControl(POIs);
    map.addControl(FoliaBox);            
}
//--------------------------------------------------
// Add adfound address to the result dropdown box
//--------------------------------------------------
function CreateAddressDropDownItem(item) {
    var ExtentXmax = item.ExtentXmax;
    var ExtentXmin = item.ExtentXmin;
    var ExtentYmax = item.ExtentYmax;
    var ExtentYmin = item.ExtentYmin;
    
    if (ExtentXmax < 0 || ExtentXmin < 0 || ExtentYmax < 0 || ExtentYmin < 0)//Coordinates not right. Do not show!
        return;
    
    var address = "";
    if (item.AddressStreetName.length > 0) {
        address += item.AddressStreetName + "<br />";
    }
    address += item.AddressPostalID + " ";
    address += item.AddressPostalDistrictName + ", ";
    address += item.AreaMunicipalityName;
    var htmlStr = "<div class='addressDropdownItem' onclick='gotoArea(" + ExtentXmax + "," + ExtentXmin + "," + ExtentYmax + "," + ExtentYmin + ");'>" + address + "</div>";
    $(addressDropdownField).append(htmlStr);
}

//------------------------------
// Get east from LatLng
//------------------------------
function getEast(googlePlace) {
    return place.ExtendedData.LatLonBox.east;
}
//------------------------------
// Get north from LatLng
//------------------------------
function getNorth(googlePlace) {
    return place.ExtendedData.LatLonBox.north;
}
//------------------------------
// Get south from LatLng
//------------------------------
function getSouth(googlePlace) {
    return place.ExtendedData.LatLonBox.south;
}
//------------------------------
// Get west from LatLng
//------------------------------
function getWest(googlePlace) {
    return place.ExtendedData.LatLonBox.west;
}

//-------------------------------
// Set default or max height of map
//-------------------------------

function SetMapSize(adjust) {
    if (mapLoaded) {
        var newMapHeight = 0;

        var winHeight = $(window).height();
        
        var mainformHeight = $("#mainform").height() + 1;
        
        var containerBoxHeight = $("#colLeft").height();


        
        if (containerBoxHeight > mapDefaultHeight) {
            mapDefaultHeight = containerBoxHeight;
            newMapHeight = containerBoxHeight;
        }
        else {
            newMapHeight = mapDefaultHeight;
        } 
        
        
        if (winHeight > mainformHeight) {
            newMapHeight = (winHeight - mainformHeight) + mapDefaultHeight;
        }

        if(adjust != null)
            mapField.style.height = (newMapHeight + adjust) + "px";
        else
            mapField.style.height = (newMapHeight) + "px";
        map.checkResize();        
    }
}

function SetToFullHeight(obj) {
    if (mapLoaded) {
        var newHeight = 0;

        var winHeight = $(window).height();
        var objHeight = $(obj).height();
        var mainformHeight = $("#mainform").height() + 1;

        newHeight = (winHeight - mainformHeight) + objHeight;
        if (newHeight < mapDefaultHeight) {
            //set height to default since we are below the default height
            obj.style.height = mapDefaultHeight + "px";
        } else {
            obj.style.height = newHeight + "px";
        }
    }
}

function keepDropdownOpen() {
    cancelTimeCall();
}

function openDropdown() {
    cancelTimeCall();
}

function closeDropdown() {
    timerCall(function() {//Will wait 200 millsec before calling
        $(addressDropdownField).hide('fast');
    }, 200);
}

function setupSearchCriteriasEvents() {

    //============================
    //      where field
    //============================
    //GEO Search event when typing
    $(whereField).keyup(function(e) {
        if (e.which == 40) {
            IsArrayDown = true;
        }
        else {
            IsArrayDown = false;
        }
        timerCall(function() {//Will wait 100 millsec before calling the search                                
            if (e.which != 32 || //space
                    e.which == 40 ||  //enter                
                    e.which == 190 || //æ
                    e.which == 222 || //ø
                    e.which == 221 || //å
                    (65 <= e.which && e.which <= 65 + 25) ||
                    (97 <= e.which && e.which <= 97 + 25)) {
                GeoSearchGoogle(e);
            }

        }, 150);
    });

    //Disable Enter button on input field
    $(whereField).keydown(function(e) {
        return !(e.which == 13);
    });

    $(whereField).focus(function(e) {
        clearAndResetField(this, defaultWhereText);
        doFocus(this);
    });

    $(whereField).blur(function(e) {
        closeDropdown();
        if (whereField.value != selectedSearchText) {
            whereField.value = selectedSearchText;
            whereField.style.color = "rgb(150,150,150)";
        }
        //clearField(this, defaultWhereText, false);
    });

    if(whereField.value.length <= 0)
        whereField.value = defaultWhereText;

    //============================
    //      dropdown field
    //============================
    $(addressDropdownDataField).keyup(function(e) {
        if (e.which == 13) { //Enter
            selectDropDownValue();
        }
    });

    $(addressDropdownDataField).blur(function(e) {
        closeDropdown();
    });

    $(addressDropdownDataField).click(function(e) {
        selectDropDownValue();
    });

    $(addressDropdownDataField).focus(function(e) {
        keepDropdownOpen();
    });



}

//-----------------------------------------------
// map zooms based on the selected dropdown value
//-----------------------------------------------
function selectDropDownValue() {
    if (addressDropdownDataField.selectedIndex > -1) {
        minMaxArray = addressDropdownDataField.options[addressDropdownDataField.selectedIndex].value.split('|');
        selectedSearchText = addressDropdownDataField.options[addressDropdownDataField.selectedIndex].text;
        gotoArea(minMaxArray[0], minMaxArray[1], minMaxArray[2], minMaxArray[3], selectedSearchText);
        whereField.focus();
        closeDropdown();
    }
}

//-----------------------------------------------
// Updates a google control element with some new text
//-----------------------------------------------
function updateGoogleControlText(control, text) {
    if (control != null) {
        control.title = text;
        control.firstChild.innerHTML = text;
    }
}


//-----------------------------------------------
// Related to ResidenceDialog.aspx when showing a
// clustered element
//-----------------------------------------------
function residenceDialogPrevious(currentNum) {
    var minNum = currentNum.innerHTML * 1;
    
    if (minNum > 1) {
        if (selectedClusterItem != null) 
        {
            minNum = minNum - 1;
            var URL = residenceDialogContentOnlyURL + selectedClusterItem.ids[minNum-1];
            $.get(URL, function(data) {
                $("#mapDialogBoxContent").html(data);
                $("#currentNum").html(minNum + "");
            });
        }
    }
}

//-----------------------------------------------
// Related to ResidenceDialog.aspx when showing a
// clustered element
//-----------------------------------------------
function residenceDialogNext(currentNum, totalNum) {
    var minNum = currentNum.innerHTML * 1;
    var maxNum = totalNum.innerHTML * 1;

    if (minNum < maxNum) {                                
        if(selectedClusterItem != null) {
            minNum = minNum + 1;
            var URL = residenceDialogContentOnlyURL + selectedClusterItem.ids[minNum - 1] + "&lan=" + currentLang;
            $.get(URL, function(data) {
                $("#mapDialogBoxContent").html(data);
                $("#currentNum").html(minNum + "");
            });
        }
    }
}

//-----------------------------------------------
// Related to ResidenceDialog.aspx when loading
// an item
//-----------------------------------------------
function getResidenceDialog(residenceID) {
    var URL = residenceDialogContentOnlyURL + residenceID + "&lan=" + currentLang;
    $.get(URL, function(data){
        $("#mapDialogBoxContent").html(data);                
    });
}

//------------------------------------------------
// List the residences related to your search
//------------------------------------------------
function doSearch() {
    validPostFieldText = postalCodeField.value;
    if (!mapLoaded) {
        setTimeout(doSearchOnList, 300);
    }
    else {                
        doSearchOnMap();
    }
}

function doSearchOnList(){    
    if (!mapLoaded) {        
        updateHiddenXYFromMapBounds();
        SearchCriteriasObject.Search();
        SearchCriteriasObject.Redirect("");
    }
    else {
        SearchCriteriasObject.GetFormParams();
        updateHiddenXYFromMapBounds();
        SearchCriteriasObject.Remove("pageindex");
        SearchCriteriasObject.Remove("pagesize");
        SearchCriteriasObject.Remove("sortexp");
        SearchCriteriasObject.Remove("sortdir");
        SearchCriteriasObject.UpdateXYAndResidrect("/searchlist.aspx");
    }
}

function doSearchOnMap() {
    if (!mapLoaded) {
        SearchCriteriasObject.GetFormParams();
        SearchCriteriasObject.Remove("pageindex");
        SearchCriteriasObject.Remove("pagesize");
        SearchCriteriasObject.Remove("sortexp");
        SearchCriteriasObject.Remove("sortdir");
        SearchCriteriasObject.Redirect("/searchmap.aspx");
    }
    else {        
        updateHiddenXYFromMapBounds();
        SearchCriteriasObject.GetFormParams();                
        updateMap();        
    }
}