/*
// +----------------------------------------------------------------------+
// | Copyright (c) 2004 Bitflux GmbH                                      |
// +----------------------------------------------------------------------+
// | Licensed under the Apache License, Version 2.0 (the "License");      |
// | you may not use this file except in compliance with the License.     |
// | You may obtain a copy of the License at                              |
// | http://www.apache.org/licenses/LICENSE-2.0                           |
// | Unless required by applicable law or agreed to in writing, software  |
// | distributed under the License is distributed on an "AS IS" BASIS,    |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or      |
// | implied. See the License for the specific language governing         |
// | permissions and limitations under the License.                       |
// +----------------------------------------------------------------------+
// | Author: Bitflux GmbH <devel@bitflux.ch>                              |
// +----------------------------------------------------------------------+
*/

var kw_liveSearchReq = false;
var kw_t = null;
var kw_liveSearchLast = "";
var kw_queryTarget = "raw_tag_list";

var kw_searchForm = null;
var kw_searchInput = null;

var kw_isIE = false;

var kw_cache = null;

var kw_widthOffset = 1;

function kw_calculateWidth() {
}

function kw_getElementDimensions(elemID) {
    var base = document.getElementById(elemID);
    var offsetTrail = base;
    var offsetLeft = 0;
    var offsetTop = 0;
    var width = 0;

    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 &&
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    if (!kw_isIE)
        width = kw_searchInput.offsetWidth-kw_widthOffset*2;
    else
        width = kw_searchInput.offsetWidth;
    return { left: offsetLeft,
             top: offsetTop,
             width: width,
             height: base.offsetHeight,
             bottom: offsetTop + base.offsetHeight,
             right: offsetLeft + width};
}

function kw_liveSearchInit() {
    kw_searchInput = document.getElementById('add_tag_input');
    if (kw_searchInput == null || kw_searchInput == undefined)
        return
    // Only keypress catches repeats in moz/FF but keydown is needed for
    // khtml based browsers.
    if (navigator.userAgent.indexOf("KHTML") > 0) {
        kw_searchInput.addEventListener("keydown",kw_liveSearchKeyPress,false);
        kw_searchInput.addEventListener("focus",kw_liveSearchDoSearch,false);
        kw_searchInput.addEventListener("keydown",kw_liveSearchStart, false);
        kw_searchInput.addEventListener("blur",kw_liveSearchHideDelayed,false);
    } else if (kw_searchInput.addEventListener) {
        kw_searchInput.addEventListener("keypress",kw_liveSearchKeyPress,false);
        kw_searchInput.addEventListener("blur",kw_liveSearchHideDelayed,false);
        kw_searchInput.addEventListener("keypress",kw_liveSearchStart, false);
    } else {
        kw_searchInput.attachEvent("onkeydown",kw_liveSearchKeyPress);
        kw_searchInput.attachEvent("onkeydown",kw_liveSearchStart);
        kw_searchInput.attachEvent("onblur",kw_liveSearchHideDelayed);
        kw_isIE = true;
    }

    // Why doesn't this work in konq, setting it inline does.
    kw_searchInput.setAttribute("autocomplete", "off");
    var pos = kw_getElementDimensions('add_tag_input');
    result = document.getElementById('KWResult');
    if ((typeof result.offsetParent != 'undefined') && (result.offsetParent != null)) {
        pos.left = pos.left - result.offsetParent.offsetLeft + pos.width;
    } else {
        pos.left = pos.left + pos.width;
    }
    result.style.display = 'none';
}


function kw_liveSearchHideDelayed() {
    window.setTimeout("kw_liveSearchHide()", 400);
}

function kw_liveSearchHide() {
    document.getElementById("KWResult").style.display = "none";
    var highlight = document.getElementById("KWHighlight");
    if (highlight)
        highlight.removeAttribute("id");
}

function kw_getFirstHighlight() {
    var set = kw_getHits();
    return set[0];
}

function kw_getLastHighlight() {
    var set = kw_getHits();
    return set[set.length-1];
}

function kw_getHits() {
    var res = document.getElementById("KWShadow");
    var set = res.getElementsByTagName('li');
    return set;
}

function kw_findChild(object, specifier) {
    var cur = object.firstChild;
    try {
        while (cur != undefined) {
            cur = cur.nextSibling;
            if (specifier(cur) == true)
                return cur;
        }
    } catch(e) {};
    return null;
}

function kw_findNext(object, specifier) {
    var cur = object;
    try {
        while (cur != undefined) {
            cur = cur.nextSibling;
            if (cur.nodeType==3)
                cur=cur.nextSibling;
            if (cur != undefined) {
                if (specifier(cur) == true)
                    return cur;
            } else { break; }
        }
    } catch(e) {};
    return null;
}

function kw_findPrev(object, specifier) {
    var cur = object;
    try {
        cur = cur.previousSibling;
        if (cur.nodeType == 3)
            cur = cur.previousSibling;
        if (cur != undefined) {
            if (specifier(cur) == true)
                return cur;
        }
    } catch(e) {};
    return null;
}

function kw_liveSearchKeyPress(event) {
    var highlight = document.getElementById("LSHighlight");
    if (event.keyCode == 40 )
    //KEY DOWN
    {
        if (!highlight) {
            highlight = kw_getFirstHighlight();
        } else {
            highlight.removeAttribute("id");
            highlight = kw_findNext(highlight, function (o) {return o.className =="KWRow";});
        }
        if (highlight)
            highlight.setAttribute("id","LSHighlight");
        if (!kw_isIE)
            event.preventDefault();
    }
    //KEY UP
    else if (event.keyCode == 38 ) {
        if (!highlight) {
            highlight = kw_getLastHighlight();
        }
        else {
            highlight.removeAttribute("id");
            highlight = kw_findPrev(highlight, function (o) {return o.className=='KWRow';});
        }
        if (highlight)
            highlight.setAttribute("id","LSHighlight");
        if (!kw_isIE)
            event.preventDefault();
    }
    //ESC
    else if (event.keyCode == 27) {
        if (highlight)
            highlight.removeAttribute("id");
        document.getElementById("KWResult").style.display = "none";
    }
    // ENTER
    else if(event.keyCode == 13) {
       if(highlight) kw_addTag(highlight.innerHTML);
       kw_liveSearchHideDelayed();
       if(kw_isIE) {
	       event.cancelBubble = true;
	       event.returnValue = false;
       }
       else {
         event.preventDefault(true);
         event.stopPropagation(true);
       }
    }
}

function kw_liveSearchStart(event) {
    if (kw_t) {
        window.clearTimeout(kw_t);
    }
    var code = event.keyCode;
    if (code!=40 && code!=38 && code!=27 && code!=37 && code!=39) {
        kw_t = window.setTimeout("kw_liveSearchDoSearch()", 200);
    }
}

function kw_liveSearchDoSearch() {
    if (kw_liveSearchLast != kw_searchInput.value) {
        if (kw_liveSearchReq && kw_liveSearchReq.readyState < 4) {
            kw_liveSearchReq.abort();
        }
        if (kw_getLastTagInBox() == "") {
            kw_liveSearchHide();
            return false;
        }
        // Do nothing as long as we have less then two characters -
        // the search results makes no sense, and it's harder on the server.
        if (kw_getLastTagInBox().length < 2) {
            kw_liveSearchHide();
            return false;
        }
        // Do we have cached results
        if (kw_cache) {
            kw_showResult(kw_cache);
            return;
        }
        
        kw_liveSearchReq = new XMLHttpRequest();
        kw_liveSearchReq.onreadystatechange = kw_liveSearchProcessReqChange;
        // Need to use encodeURIComponent instead of encodeURI, to escape +
        kw_liveSearchReq.open("GET", kw_queryTarget);
        kw_liveSearchLast = kw_searchInput.value;
        kw_liveSearchReq.send(null);
    }
}

function kw_showResult(result) {
        //do the search
        var tagList = kw_searchTags(result);
            
        //format the results
        var formattedTags = kw_formatResults(tagList);
        
	    var res = document.getElementById("KWResult");
	    res.style.display = "block";
	    var sh = document.getElementById("KWShadow");
	    sh.innerHTML = formattedTags;
}

function kw_liveSearchProcessReqChange() {
    if (kw_liveSearchReq.readyState == 4) {
        try {
            if (kw_liveSearchReq.status > 299 || kw_liveSearchReq.status < 200) {
                kw_liveSearchHide();
                return;
            }
        } catch(e) {
            return;
        }
        
        kw_cache = kw_liveSearchReq.responseText.split(',');
        kw_showResult(kw_cache);
    }
}

function kw_getLastTagInBox() {
    var boxtext = kw_searchInput.value
    var commapos = boxtext.lastIndexOf(',');
    return boxtext.substring(commapos+1).replace(' ', '');
}

function kw_addTag(tag) {
    var boxtext = kw_searchInput.value
    var commapos = boxtext.lastIndexOf(',');
    if(commapos < 0) commapos = 0;
    var all_other_tags = boxtext.substring(0, commapos);

    if(all_other_tags) all_other_tags += ", ";
	kw_searchInput.value = all_other_tags + tag;
}

function kw_searchTags(tagList) {
    var newtaglist = Array();
    var lastTag = kw_getLastTagInBox()
    
    for(i=0;i<tagList.length; i++) {
        if(tagList[i].search(lastTag.toLowerCase()) != -1) {
            newtaglist.push(tagList[i]);
        } 
    }
    return newtaglist;
}

function kw_formatResults(tagList) {
    if(!tagList.length) return "";
    
    var result = '<fieldset class="keywordsearchContainer">';
    result += '<legend id="livesearchLegend">Existing tags...</legend>';
    result += '<div class="LSIEFix">';
    result += '<ul class="LSTable">';
    for(i=0; i<tagList.length; i++) {
        var full_title = tagList[i];
        full_title = full_title.replace('&', '&amp;')
        full_title = full_title.replace('"', '&quot;')
        var display_title = full_title
        result += '<li class="KWRow" onclick="kw_addTag(\'' + display_title  + '\'); return false">';
        result += display_title
        result += '</li>'
        full_title = ''
        display_title = ''
    }

    result += '</ul>';
    result += '</div>';
    result += '</fieldset>';
    
    return result;
}


if (window.addEventListener)
    window.addEventListener("load", kw_liveSearchInit, false);
else if (window.attachEvent)
    window.attachEvent("onload", kw_liveSearchInit);
