
var searchfield_noview = document.getElementById("searchfield");
var searchfield = document.getElementById("searchfield_view");
var sugbox = document.getElementById("searchsuggestions");
var sugbox_details = document.getElementById("searchsuggestions_details");
var queries = new Array();
var suggestions = new Array();
var searchValue;
var hoveredSuggestion = -1;
var maxreturn = 200;
var maxtoshow = 20;
var readmoreLink = "";
var fok = "";
var activeload = false;
var autocomplete_timeout = "";
var autocomplete_showbox = "";
var autocomplete_hidebox = "";
var autocomplete_keypress = "";
var autocomplete_givesuggestions = "";
function mediaTypeMAP(id, name) {
   this.id = id;
   this.name = name;
   return this;
}
var arrMediaTypes = new Array();
function getMediaTypeName(id) {
	// Find the IDMS club in the array
    for (var i = 0; i < arrMediaTypes.length; i++) {
        var mediamapping = arrMediaTypes[i];
		// if it exists
        if (mediamapping.id == id) {
			// return the corresponding dmpclub
            return mediamapping.name;
		}
	}
	// If reached here it did not find a dmpclub mapping,
	// so return the IDMSclub coming in as parameter
	return id;

}



function realOffset(B, A) {
    var C = 0;
    while (B) {
        C += B[A];
        B = B.offsetParent;
    }
    return C;
}

function SearchSuggest(formid) {

    searchfield.setAttribute("autocomplete", "off");

    searchfield.onkeydown = function (F) {
        clearTimeout(autocomplete_keypress);
        clearTimeout(autocomplete_timeout); autocomplete_timeout = null;
        clearTimeout(autocomplete_givesuggestions); autocomplete_givesuggestions = null;

        try {
            if (event.keyCode == 13 && hoveredSuggestion != -1) {
                a_href = sugbox.getElementsByTagName("a")[hoveredSuggestion].href;
                if (a_href != "") {
                    window.location = a_href;
                    return false;
                }
            }
            autocomplete_keypress = setTimeout("searchKeyDown(" + event.keyCode + "," + formid + ")", 10);
        }
        catch (G) {
            if (F.keyCode == 13 && hoveredSuggestion != -1) {
                a_href = sugbox.getElementsByTagName("a")[hoveredSuggestion].href;
                if (a_href != "") {
                    window.location = a_href;
                    return false;
                }
            }
            autocomplete_keypress = setTimeout("searchKeyDown(" + F.keyCode + "," + formid + ")", 10);
        }
    };

    searchfield.onkeyup = function (F) {
        if (searchfield != null && searchfield_noview != null)
            searchfield_noview.value = searchfield.value;

        var timeout = 100;
        if (searchfield.value.length > 0) {

            if (searchfield.value.length < 2)
                timeout = 1000;
            else if (searchfield.value.length < 3)
                timeout = 1000;
            else if (searchfield.value.length < 4)
                timeout = 500;

            try {
                autocomplete_timeout = setTimeout("searchKeyUp(" + event.keyCode + "," + formid + ")", timeout);
            } catch (G) {
                autocomplete_timeout = setTimeout("searchKeyUp(" + F.keyCode + "," + formid + ")", timeout);
            }

        } else {
            
            clearTimeout(autocomplete_timeout);
            clearTimeout(autocomplete_givesuggestions);
            clearTimeout(autocomplete_showbox);
            queries = new Array()
            autocomplete_hidebox = setTimeout(hideSugbox, 1);
        }

    };
    searchfield.onblur = function() {
        clearTimeout(autocomplete_showbox);
        autocomplete_hidebox = setTimeout(hideSugbox, 250);
    } 
}
function hoverSuggestion(A) {
    for (var B = 0; B < suggestions.length; B++) {
        sugbox.getElementsByTagName("a")[B].className = "";
    }
    if (A != -1) {
        sugbox.getElementsByTagName("a")[A].className = "hovered";
        hoveredSuggestion = A;
        showSugbox_detail(A);


    }

}

function searchKeyDown(A) {
    if (sugbox.style.display == "block") {
        if (A != 38 && A != 40) {
            hoveredSuggestion = -1;
         }
        if (A == 38 && hoveredSuggestion != -1) {
            hoveredSuggestion--;
            hoverSuggestion(hoveredSuggestion);
			if (hoveredSuggestion != -1)
				searchfield.value = String(suggestions[hoveredSuggestion].split('|')[0]);
			else
				searchfield.value = searchValue;
        }
        if (A == 40 && hoveredSuggestion < suggestions.length - 1) {
            hoveredSuggestion++;
            hoverSuggestion(hoveredSuggestion);
            searchfield.value = String(suggestions[hoveredSuggestion].split('|')[0]);
        }
    } 
}

function searchKeyUp(A, formid) {
    if (A != 38 && A != 40) { searchValue = searchfield.value }
    if (searchfield.value != "" && A != 13 && A != 27 && A != 38 && A != 40) {
        loadSearch(formid, maxreturn);
//        autocomplete_givesuggestions = setTimeout(giveSuggestions, 50);
    }
    if ((searchfield.value == "" || A == 27) && sugbox.style.display == "block") {
        hideSugbox();
        searchfield.setAttribute("autocomplete", "off");
    }
}



function loadSearch(f, maxreturn) {
    
    try {
        //var objectForm = eval('document.' + f + '');
        var objectForm = document.getElementById(f);
        var URLtouse = getFormValues(objectForm, '/cds/search.asp') + "&maxreturn=" + maxreturn;    // Finns i functions.js

        //var xmlhttp = xmlhttp = new XMLHttpRequest();
        //alert(URLtouse);
        //if (!xmlhttp && typeof xmlhttprequest != 'undefined') {
        //xmlhttp = new xmlhttprequest(); //If we were able to get a working active x object, start an xmlhttprequest 
        //}

        var xmlhttp = false; //Clear our fetching variable

        if (window.ActiveXObject) {
            if ((navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) || (navigator.userAgent.toLowerCase().indexOf('msie 7') != -1))
                xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
            else
                xmlhttp = new XMLHttpRequest();

        } else {
            xmlhttp = new XMLHttpRequest();
            //alert('Firefox ok!!');
        }

        xmlhttp.open("GET", URLtouse, true); //Open the file through GET
        xmlhttp.setRequestHeader("Cache-Control", "no-cache");
        xmlhttp.setRequestHeader('If-Modified-Since', 'Wed, 15 Nov 1995 00:00:00 GMT');
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4) {
                var content = xmlhttp.responseXML;
                queries = new Array();
                var oorder_by = content.getElementsByTagName("order_by");
                var oorder_number = content.getElementsByTagName("order_number");
                var otype = content.getElementsByTagName("type");
                if (oorder_by.length > 0) {
                    for (var i = 0; i < oorder_by.length; i++) {
                        var order_by = String(oorder_by[i].firstChild.data);
                        var order_number = String(oorder_number[i].firstChild.data);
                        var type = String(otype[i].firstChild.data);
                        queries.push(order_by + '|' + order_number + '|' + type);
                    }
                }
                if (autocomplete_timeout)
                autocomplete_givesuggestions = setTimeout(giveSuggestions, 10);    
            }

        }

        xmlhttp.send(); //Nullify the xmlhttprequest

        //The content data which has been retrieved ***
        


    } catch (e) {
        //                alert('ERROR:' + e);
        //                alert('ERROR:' + e.description);
        //var resultArray = new Array();
    }
    //return resultArray;

}




function giveSuggestions() {

    suggestions = new Array();

    for (var A = 0; A < queries.length && suggestions.length < maxtoshow; A++) {
        if (String(queries[A]).indexOf(String(searchfield.value)) == 0) {
            suggestions.push(queries[A]);
            queries[A] = '';
        }
    }
    
    for (var A = 0; A < queries.length && suggestions.length < maxtoshow; A++) {
        if (String(queries[A]).toLowerCase().indexOf(searchfield.value.toLowerCase()) == 0) {
            suggestions.push(queries[A]);
            queries[A] = '';
        }
    }    
    


    for (var A = 0; A < queries.length && suggestions.length < maxtoshow; A++) {
        if (String(queries[A]).toLowerCase().indexOf(searchfield.value) > 0) {
            suggestions.push(queries[A]);
            queries[A] = '';
        }
    }


    for (var A = 0; A < queries.length && suggestions.length < maxtoshow; A++) {
    if (queries[A] != '')
    suggestions.push(queries[A]);
    }

    
    if (suggestions.length == 0) {
        clearTimeout(autocomplete_showbox);
        autocomplete_hidebox = setTimeout(hideSugbox, 10);
    }
    else {
        clearTimeout(autocomplete_showbox);
        clearTimeout(autocomplete_hidebox);
        autocomplete_showbox = setTimeout(showSugbox, 10);
    }

    var contentINBox = "";

    for (var A = 0; A < suggestions.length; A++) {
        var order_by = String(String(suggestions[A]).split('|')[0]);
        var order_number = String(String(suggestions[A]).split('|')[1]);
        var type = String(String(suggestions[A]).split('|')[2]);
		if (parseInt(type, 10) < 0)
		    contentINBox += '<div class="left" style="width:' + (searchfield.offsetWidth - 3) + 'px;" onmouseover="hoverSuggestion(' + A + ')"  title="' + order_by + ' (' + getMediaTypeName(type) + ')' + '"><a id="' + order_number + '" href="/cds/showpage.asp?nodeid=' + order_number + '">' + order_by + '</a></div><div class="right">(' + getMediaTypeName(type) + ')</div>';
		else
		{
			if (readmoreLink == '')
			    contentINBox += '<div class="left" style="width:' + (searchfield.offsetWidth - 2) + 'px;" onmouseover="hoverSuggestion(' + A + ')"  title="' + order_by + ' (' + getMediaTypeName(type) + ' ' + order_number + ')' + '"><a id="' + order_number + '" onClick="searchfield.value = \'' + order_by + '\';" title="' + order_by + ' (' + getMediaTypeName(type) + ' ' + order_number + ')' + '">' + order_by + '</a></div><div class="right">(' + getMediaTypeName(type) + ' ' + order_number + ')</div>';
			else
			    contentINBox += '<div class="left" style="width:' + (searchfield.offsetWidth - 3) + 'px;" onmouseover="hoverSuggestion(' + A + ')" title="' + order_by + ' (' + getMediaTypeName(type) + ' ' + order_number + ')' + '"><a id="' + order_number + '" href="' + readmoreLink.replace('##catnr##', 'a' + order_number).replace('##title##', order_by.replace(/[^a-zA-Z0-9åäöÅÄÖøØ\s]/g, " ").replace(/\s+$/, '').replace(/[\s]+/g, "-").toLowerCase()) + '">' + order_by + '</a></div><div class="right">(' + getMediaTypeName(type) + ' ' + order_number + ')</div>';
		}
}

sugbox.innerHTML = contentINBox;
}
function showSugbox() {
    searchfield.setAttribute("autocomplete", "off");
    sugbox.style.top = (realOffset(searchfield, "offsetTop") + searchfield.offsetHeight - 1) + "px"; 
    sugbox.style.left = realOffset(searchfield, "offsetLeft") + 3 + "px";
    sugbox.style.width = (searchfield.offsetWidth + 124) + "px";
    sugbox.style.display = "block";
}

function showSugbox_detail(A) {
    try {
        var type = String(String(suggestions[A]).split('|')[2]);
        if (type > 0) {
            var catnr = sugbox.getElementsByTagName("a")[A].id;
            var link = sugbox.getElementsByTagName("a")[A].href;
            var URLtouse = '/image.asp?info=true&productid=' + catnr + '&width=125&fok=' + fok + '';
            var xmlhttp = false; //Clear our fetching variable

            if (window.ActiveXObject) {
                if ((navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) || (navigator.userAgent.toLowerCase().indexOf('msie 7') != -1))
                    xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
                else
                    xmlhttp = new XMLHttpRequest();

            } else {
                xmlhttp = new XMLHttpRequest();
            }
            xmlhttp.open("GET", URLtouse, true); //Open the file through GET
            xmlhttp.setRequestHeader("Cache-Control", "no-cache");
            xmlhttp.setRequestHeader('If-Modified-Since', 'Wed, 15 Nov 1995 00:00:00 GMT');

            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4) {
                    sugbox_details.style.top = (realOffset(searchfield, "offsetTop") + searchfield.offsetHeight - 1) + "px";
                    sugbox_details.style.left = realOffset(searchfield, "offsetLeft") - 131 + "px";
                    sugbox_details.style.width = '125px';
                    sugbox_details.style.display = 'block';


                    //sugbox_details.innerHTML = '<img src="http://www.homeenter.com/image.asp?productid=' + catnr + '&width=125&fok='+fok+'">';
                    sugbox_details.innerHTML = '<a href="' + link + '">' + xmlhttp.responseText + '</a>';
                }
            }

            xmlhttp.send(); //Nullify the xmlhttprequest
        } else {sugbox_details.style.display = "none";}

    } catch (e) {
    //alert(e + ' : ' + e.description);
    }


}



function hideSugbox() {
    sugbox.style.display = "none";
    sugbox_details.style.display = "none";
}
      
