/*
  quicksearch script (adaption of the Plone livesearch script) for cities 
  inside the region-navi on the SGP portal
  
*/
var liveCitySearchReq   = false;
var t                   = null;
var liveCitySearchLast  = "";
var cityQueryTarget     = "livecitysearch_reply?q=";
var citySearchInput     = null;
var filterString        = '';

var isIE                = false;

var _cityCache          = new Object();
var _search_delay       = 750;
var timerDIV            = null;
var searchTimer         = null;

function getCityElementDimensions(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 (!isIE)
        width = citySearchInput.offsetWidth-widthOffset*2;
    else
        width = citySearchInput.offsetWidth;
    return { left: offsetLeft,
             top: offsetTop,
             width: width,
             height: base.offsetHeight,
             bottom: offsetTop + base.offsetHeight,
             right: offsetLeft + width};
}
//***************************


function liveCitySearchInit(filter) {
    filterString    = filter;
    citySearchInput = document.getElementById('citySearch');
    cityResultDIV   = document.getElementById('cityResults');
    if (citySearchInput == null || citySearchInput == undefined) {
        return;
    }
    // Only keypress catches repeats in moz/FF but keydown is needed for
    // khtml based browsers.
    if (navigator.userAgent.indexOf("KHTML") > 0) {
        citySearchInput.addEventListener("keydown", liveCitySearchKeyPress, false);
        citySearchInput.addEventListener("focus", liveSearchDoSearch, false);
        citySearchInput.addEventListener("keydown", liveCitySearchStart, false);
        citySearchInput.addEventListener("blur", liveCitySearchHideDelayed, false);
    } else if (citySearchInput.addEventListener) {
        citySearchInput.addEventListener("keypress", liveCitySearchKeyPress, false);
        citySearchInput.addEventListener("keypress", liveCitySearchStart, false);
        citySearchInput.addEventListener("blur", liveCitySearchHideDelayed, false);
        //cityShadowDIV.addEventListener("mouseout",initClose,false);
    } else {
        citySearchInput.attachEvent("onkeydown", liveCitySearchKeyPress);
        citySearchInput.attachEvent("onkeydown", liveCitySearchStart);
        citySearchInput.attachEvent("onblur", liveCitySearchHideDelayed);
        //cityShadowDIV.attachEvent("onmouseout",initClose,false);
        isIE = true;
    }

    // Why doesn't this work in konq, setting it inline does.
    citySearchInput.setAttribute("autocomplete", "off");
    var pos = getCityElementDimensions('citySearch');
    if ((typeof cityResultDIV.offsetParent != 'undefined') && (cityResultDIV.offsetParent != null)) {
        pos.left = pos.left - cityResultDIV.offsetParent.offsetLeft + pos.width;
    } else {
        pos.left = pos.left + pos.width;
    }
    cityResultDIV.style.display = 'none';
    }
//***************************


function getCityFirstHighlight() {
    var set = getCityHits();
    return set[0];
}
//---------------------------


function getCityLastHighlight() {
    var set = getCityHits();
    return set[set.length-1];
}
//---------------------------


function getCityHits() {
    var res = document.getElementById("cityShadow");
    var set = res.getElementsByTagName('li');
    return set;
}
//---------------------------

function findChildCity(object, specifier) {
    var cur = object.firstChild;
    try {
        while (cur != undefined) {
            cur = cur.nextSibling;
            if (specifier(cur) == true) {
                return cur;
            }
        }
    } catch(e) {};
    return null;
}
//---------------------------


function findPrevCity(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 findNextCity(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 liveCitySearchKeyPress(event) {
    var highlight = document.getElementById("cityHighlight");
    if (event.keyCode == 40 )
    //KEY DOWN
    {
        if (!highlight) {
            highlight = getCityFirstHighlight();
        } else {
            highlight.removeAttribute("id");
            highlight = findNextCity(highlight, function (o) {return o.className =="cityRow";});
        }
        if (highlight) {
            highlight.setAttribute("id","cityHighlight");
        }
        if (!isIE) {
            event.preventDefault();
        }
    }
    //KEY UP
    else if (event.keyCode == 38 ) {
        if (!highlight) {
            highlight = getCityLastHighlight();
        }
        else {
            highlight.removeAttribute("id");
            highlight = findPrevCity(highlight, function (o) {return o.className=='cityRow';});
        }
        if (highlight) {
            highlight.setAttribute("id","cityHighlight");
        }
        if (!isIE) {
            event.preventDefault();
        }
    }
    // ENTER
    else if (event.keyCode == 13) {
        if (highlight) {
            var links = highlight.getElementsByTagName("A");
            window.location.href = links[0].href;
        }
    }
    //ESC
    else if (event.keyCode == 27) {
        if (highlight) {
            highlight.removeAttribute("id");
        }
        document.getElementById("cityResults").style.display = "none";
    }
}
//---------------------------


function liveCitySearchStart(event) {
    if (searchTimer) {
        window.clearTimeout(searchTimer);
    }
    var code = event.keyCode;
    if (code!=40 && code!=38 && code!=27 && code!=37 && code!=39) {
        searchTimer = window.setTimeout("liveCitySearchDoSearch()", _search_delay);
    }
}
//---------------------------


function liveCitySearchDoSearch() {
    if (typeof liveCitySearchRoot == "undefined") {
        if (typeof portal_url == "undefined") {
            liveCitySearchRoot = "";
        } else {
            if (portal_url[portal_url.length-1] == '/') {
                liveCitySearchRoot = portal_url;
            } else {
                liveCitySearchRoot = portal_url + '/';
            }
        }
    }
    // dirty trick to fix the www - XMLHTTPREQUEST problem
    if (document.location.href.indexOf('http://www.') == 0)
        if (liveCitySearchRoot.indexOf('http://www') != 0) {
            liveCitySearchRoot = 'http://www.' + liveCitySearchRoot.slice(7)
        }

    if (typeof liveCitySearchRootSubDir == "undefined") {
        liveCitySearchRootSubDir = "";
    }
    if (liveCitySearchLast != citySearchInput.value) {
        if (liveCitySearchReq && liveCitySearchReq.readyState < 4) {
            liveCitySearchReq.abort();
        }
        if ( citySearchInput.value == "") {
            liveCitySearchHide();
            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 ( citySearchInput.value.length < 2) {
            liveCitySearchHide();
            return false;
        }
        // Do we have cached results
        var result = _cityCache[citySearchInput.value];
        if (result) {
            showCityResult(result);
            return;
        }
        liveCitySearchReq = new XMLHttpRequest();
        liveCitySearchReq.onreadystatechange = liveCitySearchProcessReqChange;
        // Need to use encodeURIComponent instead of encodeURI, to escape +
        liveCitySearchReq.open("GET", liveCitySearchRoot + cityQueryTarget + encodeURIComponent(citySearchInput.value));
        liveCitySearchLast = citySearchInput.value;
        liveCitySearchReq.send(null);
    }
}
//---------------------------


function liveCitySearchProcessReqChange() {
    if (liveCitySearchReq.readyState == 4) {
        try {
            if (liveCitySearchReq.status > 299 || liveCitySearchReq.status < 200) {
                return;
            }
        } catch(e) {
            return;
        }
        showCityResult(liveCitySearchReq.responseText);
        _cityCache[liveCitySearchLast] = liveCitySearchReq.responseText;
    }
}
//---------------------------


function showCityResult(result) {
    if (result) {
        var cRes = document.getElementById("cityResults");
        cRes.style.display = "block";
        var cSh = document.getElementById("cityShadow");
        
        // processing response text
        var token = result.split('#');
        var base  = liveCitySearchRoot + 'region';
        var html = '<ul id="resultList">';
        if (typeof filterString == "undefined") {
            filterString = "";
        }
        for (var idx in token) { 
            var city = token[idx].split('|');
            html += '<li class="cityRow"><a href="' + base + city[1] + filterString + '">' + city[0] + '</a></li>';
        }    
        cSh.innerHTML = html;
        var dummyEvent = new Object();
        dummyEvent.keyCode = 40;
        liveCitySearchKeyPress(dummyEvent);
    }
}
//---------------------------


function liveCitySearchHide() {
    document.getElementById("cityResults").style.display = "none";
    var highlight = document.getElementById("cityHighlight");
    if (highlight) {
        highlight.removeAttribute("id");
    }
}
//---------------------------


function liveCitySearchHideDelayed() {
    window.setTimeout("liveCitySearchHide()", 400);
}
//---------------------------


function initClose(event) {
    var ref   = event.target;
    if (ref.id == 'cityShadow') {
        ref.style.background = 'yellow';
    }
}
//---------------------------


function clearCitySearch(event) {
    /* clear the html of the ref node
    */
    var ref   = event.target; //.getElementById("cityShadow");
    var div   = document.getElementById("cityShadow");
    var input = document.getElementById("citySearch");
    if (ref.id == 'cityResults') {
        div.innerHTML = '';
        ref.style.display = 'none';
        input.value = 'Ihre Stadt finden';
    }    
}
//---------------------------


function liveCitySearch(ref) {
    /* search cities thats contain the ref.value -> *{ref.value}*
    */
    var searchStr = ref.value.toLowerCase()
    if (searchStr.length > 2) {
        alert('search for: ' + searchStr);
    }
}
//---------------------------

registerPloneFunction(liveCitySearchInit);

