﻿    var gElmTargetContainer;
//    var gElmContentTargetFast;
    var gElmSelSearchResult;
    var gElmLoader;
    var giLastTimerId;
    var g_sImageMarkerPath;
    var gAutoPath;

// Function that shows selected item in map.
function showOnMap(x, y, adress) {
    searchValueToPrint = adress;
    for (var i = 0; i < map.layers.length; i++) {
        if (map.layers[i].CLASS_NAME == "OpenLayers.Layer.Markers") {
            var markerLayer = map.layers[i];
        }
    }
    markerLayer.clearMarkers();
    var size = new OpenLayers.Size(30,40);
    //31,43
    var calculateOffset = function(size) {
            return new OpenLayers.Pixel(-(size.w/2), -size.h); 
    };
    var icon = new OpenLayers.Icon(g_sImageMarkerPath,
        size, null, calculateOffset);
    var tempMarker = new OpenLayers.Marker(new OpenLayers.LonLat(x, y), icon);
    markerLayer.addMarker(tempMarker);
    map.setCenter(new OpenLayers.LonLat(x,y), 9);
}



// Close the result list and popup on click anywhere.
function checkSearchVisibility(e) {
    if (gElmTargetContainer) {
        var searchButton = document.getElementById("searchBtn");     
        var target = (e && e.target) || (event && event.srcElement);
        var bIsChild = isSameOrChild(target, gElmTargetContainer, searchButton);
        if ((!bIsChild)) {
            gElmTargetContainer.style.display = 'none';
        } 
    }
    if(map.popups){
        if(map.popups.length != 0) {
            map.popups[0].hide();
        }
    }
}

// Checks weather a selected element is the same as onther element or a child to the same. 
// For example you don´t want to close result list when clicked, but you want it closed when click elsewhere.
function isSameOrChild(elmChildTarget, elmParent, elmParentTwo) {
    while (elmChildTarget.parentNode) {
        if (elmChildTarget == elmParent) {
            return true
        }
        else if (elmChildTarget == elmParentTwo) {
            return true
        }
        elmChildTarget = elmChildTarget.parentNode
    }
    return false
} 

//Starts the WebService function when value in search field exced three characters, with timer functionality. 
function checkAutoSearch(elmToCheck, iSeconds) {
    var elm = elmToCheck; 
    var val = elm.value;
    // Cancel previous scheduled search
    if (giLastTimerId) {
        clearTimeout(giLastTimerId);
    }
    if (!gElmTargetContainer) {
        gElmTargetContainer = document.getElementById('searchTargetContainer');
    }
    if (!gElmLoader) {
        gElmLoader = document.getElementById('searchLoader');
    }
    if (!gElmSelSearchResult) {
//        gElmContentTargetFast = document.getElementById('searchContentFast');
        gElmSelSearchResult = document.getElementById('lstSearchContent');
    }
    if (val.length <= 3) {
        gElmTargetContainer.style.display = 'none';
    }
    else {
        gElmTargetContainer.style.display = 'block';
//        gElmContentTargetFast.style.display = 'block'; //ändrat från none
        gElmLoader.style.display = 'block';
        // Schedule search
        var iMilliseconds = (iSeconds * 1000);
        var sFunctionCall = 'startSearch(\'' + val + '\')';
        giLastTimerId = setTimeout(sFunctionCall, iMilliseconds);
    }
}

//Calls the WebService and returns result to checkAutoSearchSuccess
function startSearch(sSearchCriteria) {

    autoComplete._staticInstance._path = gAutoPath;
    // Perform ajax-Search
    autoComplete.GetAdresses(sSearchCriteria, checkAutoSearchSuccess);
}

// Function that handles the results from the WebService call. Puts the items in result list.
function checkAutoSearchSuccess(result) {
//    gElmContentTargetFast.style.display = 'block';
    gElmLoader.style.display = 'none';
    gElmSelSearchResult.options.length = 0;
    //alert(result.length);
    if (result.length == 0) {
            var optNew = new Option('Sökningen gav ingen träff');
            gElmSelSearchResult.options[0] = optNew;
    }
    else if (result.length == 1) {
        showOnMap(result[0].x, result[0].y, result[0].data); 
        gElmTargetContainer.style.display = 'none'; 
    }
    else {
        for (var i = 0; i < result.length; i++) {
            var dataPoint = result[i];
            var optNew = new Option(dataPoint.data, dataPoint.x + ',' + dataPoint.y);
            gElmSelSearchResult.options[i] = optNew;
        }
    }
}

// Calls the function that shows the selected item on map
function showSelectedOnMap() {
    var indx = gElmSelSearchResult.selectedIndex;
    var sAddress = gElmSelSearchResult[indx].text;
    var aCoords = gElmSelSearchResult[indx].value.split(',');
    var x = aCoords[0];
    var y = aCoords[1];
    var sFunctionCall = 'showOnMap(' + x+ ', ' + y +', \'' + sAddress + '\')';
    setTimeout(sFunctionCall, 10); // just to get it asynchronous
}

// Function to clear the searchfield, but only when its in the default state
function searchClick(sDefaultVal) {
    var elm = document.getElementById("txtSearch");
    if (elm.value == sDefaultVal) {
        elm.value = '';
    }
}

// Registers function to call on document.onlick.
// Several functions can be added.
function addDocumentClickEvent(func) {   
    var oldonload = window.onload;   
    if (typeof document.onclick != 'function') {   
        document.onclick = func;   
    } 
    else {   
        document.onclick = function() {   
            if (oldonload) {   
                oldonload();   
            }   
            func();   
        }   
    }   
}

function initSearch(sImageMarkerPath, autoPath) {
    var elmSearchPath = document.getElementById(autoPath);
    gAutoPath = elmSearchPath.href;
    g_sImageMarkerPath = sImageMarkerPath;
    addDocumentClickEvent(checkSearchVisibility);
}

// Function to select the first item in result list when arrow down key is fired. Also to prevent the result list to reload when other arrow keys fires. 
// And then of course fire the search function.
function keyCheck(event, elm ,iSeconds) {
    var KeyID = event.keyCode;
    if(KeyID == 40){
        if(gElmSelSearchResult){
            if(gElmTargetContainer.style.display == 'block'){
                if(gElmSelSearchResult.options.length != 0){
                    gElmSelSearchResult.focus();
                    gElmSelSearchResult[0].selected = true;
                }
            }
        }
    }
    else if(KeyID == 39){
    }
    else if(KeyID == 38){
    }
    else if(KeyID == 37){
    }
    else if(KeyID == 13){
        twoLetterSearch();
    }
    else{
        checkAutoSearch(elm, iSeconds); 
        return false;
    }
}

// Function to handle the "enter" key event in the result list.   
function enterKey(event){
    var KeyID = event.keyCode;
    if(KeyID == 13){
        var indx = gElmSelSearchResult.selectedIndex;
        var sAddress = gElmSelSearchResult[indx].text;
        var elm = document.getElementById("txtSearch");
        gElmTargetContainer.style.display = 'none';
        elm.value = sAddress;
    }
}

//Functionality for searchbutton
function twoLetterSearch() {
    var elm = document.getElementById("txtSearch");
    var val = elm.value;
    if (val.length >= 2) {
        if (!gElmTargetContainer) {
            gElmTargetContainer = document.getElementById('searchTargetContainer');
        }
        if (!gElmLoader) {
            gElmLoader = document.getElementById('searchLoader');
        }
        if (!gElmSelSearchResult) {
//            gElmContentTargetFast = document.getElementById('searchContentFast');
            gElmSelSearchResult = document.getElementById('lstSearchContent');
        }
        else {
            gElmTargetContainer.style.display = 'block';
//            gElmContentTargetFast.style.display = 'block'; //ändrat från none
            gElmLoader.style.display = 'block';
            startSearch(val);
        }
    }
}
function removeMarker() {
    var markerLayer = map.getLayersByClass("OpenLayers.Layer.Markers");
    markerLayer[0].clearMarkers();
}