var popupEl = null;
var acEl = null;
var acSelected = -1;
var prevValue = null;
var acInput = null;
var acHoover = false;
var lastAc = 0;

document.onkeydown = function(event){handleKeyDown(event);};
document.onclick = function(event){handleClick(event);}

function handleClick(e) {
    if(e) {
        var target = null;
        if(e.target) target= e.target;
        else if(e.srcElement) target = e.srcElement;
        if(target != null && target && acEl != null && acEl.innerHTML !="") {
             if(target && target.id != "search" && target.className != "acItem" && target.className != "acItem_s" && target.className != "acList")
                clearAC(acEl);
        }
    } 
}
function geIEVersion(){
    var version = -1;
    if(navigator.appName == "Microsoft Internet Explorer"){
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if(re.exec(ua)!=null){
            version = parseFloat(RegExp.$1)
        }
    }
    return version;
}
function handleKeyDown(e) {
  if(acEl != null && acEl.innerHTML != "") {
    if(!e) e = window.event;
    var code = getKeyCode(e); var node; var scroll; var pozy; var pozy1;
    if(code == 37 || code == 38) { // up
        node = acEl.childNodes[0];
        if(node.childNodes.length > 0) {
            if(acSelected != -1 && node.childNodes[acSelected]) node.childNodes[acSelected].className = "acItem";
            acSelected--;
            if(acSelected < 0) acSelected = node.childNodes.length-1;
            node.childNodes[acSelected].className = "acItem_s";
            pozy = node.childNodes[acSelected].offsetTop;
            pozy1 = pozy + node.childNodes[acSelected].offsetHeight;
            scroll = node.scrollTop;
            if(pozy < node.scrollTop) {
               scroll -= node.scrollTop-pozy;
            } else if(pozy1 > (node.offsetHeight+node.scrollTop)) {
               scroll += (pozy1-(node.offsetHeight+node.scrollTop));
            }
            if(scroll < 0) scroll = 0;
            if(scroll != node.scrollTop) node.scrollTop = scroll;
            acHoover = false;
        }
    } else if(code == 39 || code == 40) { // down
        node = acEl.childNodes[0];
        if(node.childNodes.length > 0) {
            if(acSelected != -1 && node.childNodes[acSelected]) node.childNodes[acSelected].className = "acItem";
            acSelected++;
            if(acSelected >= node.childNodes.length) acSelected = 0;
            node.childNodes[acSelected].className = "acItem_s";
             pozy = node.childNodes[acSelected].offsetTop;
             pozy1 = pozy + node.childNodes[acSelected].offsetHeight;
             scroll = node.scrollTop;
            if(pozy < node.scrollTop) {
               scroll -= node.scrollTop-pozy;
            } else if(pozy1 > (node.offsetHeight+node.scrollTop)) {
               scroll += (pozy1-(node.offsetHeight+node.scrollTop));
            }
            if(scroll < 0) scroll = 0;
            if(scroll != node.scrollTop) node.scrollTop = scroll;
            acHoover = false;
        }
    } else if(code == 13) { // enter
       if(acSelected != -1) {
           acInput.value = rhtmlspecialchars(strip_tags(acEl.childNodes[0].childNodes[acSelected].innerHTML));
       }
       clearAC(acEl);
       acInput.form.submit();
   } else if(code == 27) {
        clearAC(acEl);
    }
  }
}
function handleItemClick(index) {
    if(acEl != null && acEl.innerHTML != "" && acInput != null) {
        var node = acEl.childNodes[0];
        if(node.childNodes[index]) {
            acInput.value = rhtmlspecialchars(strip_tags(node.childNodes[index].innerHTML));
            clearAC(acEl);
            acInput.form.submit();
        }
    }
}
function handleUnHoover() {
    if(acEl != null && acEl.innerHTML != "" && acHoover) {
        if(acEl.childNodes[0].childNodes[acSelected]) {
            acHoover = false;
            acEl.childNodes[0].childNodes[acSelected].className = "acItem";
        }

    }
}
function handleHoover(index) {
    if(acEl != null && acEl.innerHTML != "") {
        var node = acEl.childNodes[0];
        if(acSelected != -1 &&  index != acSelected &&  node.childNodes[acSelected]) node.childNodes[acSelected].className = "acItem";
        acSelected = index;
        acHoover = true;
        if(node.childNodes[acSelected]) {
            node.childNodes[acSelected].className = "acItem_s";
        } 
    } 
}

function getKeyCode(e) {
    var code = -1;
    if(e) {
        if(e.keyCode) code = e.keyCode;
        else if(e.which) code = e.which;
    }
    return code;
} 

var SMDEBUG = 0;
/** Async functions **/
function getStatus(client)
{
    if (client.readyState == 4)
    {
        if (client.status == 200)
        {
            var string = client.responseText;
            return string;
        } else
        {
            throw('There was a problem with the request. ' + client.status);
        }
    }else throw('1000');
    return null;
}

function handleError(e)
{
    if(SMDEBUG == 1)
        alert(e);
}

function initClient()
{
    var client = null;
    try
    {
        client = new XMLHttpRequest();
    }catch(e)
    {
        try
        {
            client = new ActiveXObject("Microsoft.XMLHttp");
        }catch(e)
        {
            alert("Fatal error creating XMLHttpRequest object, please upgrade your browser.");
            throw(e);
        }
    }
    return client;
}

function asyncSend(url, message, type, obj, id)
{

    var client = this.initClient();
    var response = null;
    client.onreadystatechange = function()
    {
        try
        {
            response = getStatus(client);
                try
                {
                   handleActions(response, type, obj, id);
                }catch(e)
                {
                    handleError(e);
                }

        }catch(e)
        {
            if(e != 1000)
            {
                handleError(e);
            }
        }
        return null;
    }
    try
    {
        client.open("POST", unescape(url), true);
        client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 //                   client.setRequestHeader("Connection", "close");
        client.send(message);

    }catch(e)
    {
        handleError(e);
    }
    return null;
}

function handleActions(response, type, obj, id)
{
    var data = trim(response);
    if(data != "") {
       if(type == 0) {
           if(obj != null && obj) {
               if(id == lastAc) {
                obj.innerHTML = response;
               }
           }
        } else if(type == 1) {
           if(obj != null && obj) {
                obj.innerHTML = response;
           }
        }
    } else if(type == 0) {
        if(obj != null && obj) {

          clearAC(obj);
        }
    }
}
function ac_data(input,containerId,extraContainer,extraData) {
    var container = document.getElementById(containerId);
    if(extraContainer != "")
        var exContainer = document.getElementById(extraContainer);
    if(input && container) {
         var value = trim(input.value).replace("&","%26");
         if(prevValue != null && prevValue == value) return; // no change in text
         prevValue = value;
         var now = new Date().getTime();
         lastAc = now;
         if(value == "") {
             clearAC(container);
         } else {
            acEl = container;
            acInput = input;
            var send = "&value="+value;
            if(exContainer && exContainer.value) send += "&extra="+exContainer.value;
            if(extraData != "")send += extraData;
            asyncSend("?action=autocomplete", send, 0, container, now);
         }
    } else if(input == null ) {
        clearAC(acEl);
    }
}
function stopEvent(e) {
    if(!e)
        if(window.event) e=window.event;
        else return;
    if(e.cancelBubble != null) e.cancelBubble=true;
    if(e.stopPropagation)e.stopPropagation();
    if(e.preventDefault)e.preventDefault();
    if(window.event) e.returnValue = false;
    if(e.cancel != null) e.cancel = true;
}
function clearAC(el) {
    if(el && el != null) {
        el.innerHTML = "";
        acSelected=-1;
        prevValue = null;
    }
}
function resetForm(formId)
{
    var form = document.getElementById(formId);
    if(form)
    {
        var objs = form.getElementsByTagName("input");
        if(objs.length > 0)
        {
            for(i = 0; i < objs.length; i++)
            {
                if(objs[i].type == "text")
                {
                    objs[i].value = "";
                }
            }
        }
    }
}
function rotateSpotlight(id,rotate) {
    var obj = document.getElementById(id);
    if(obj && rotate > 0) {
        var func = function() {
           asyncSend("?action=spotlight", "", 1, obj, null);
        }
        setInterval(func,rotate);
    }
}
function followLink(obj) {
    if(obj) {
        var objs = obj.getElementsByTagName("a");
        var len = objs.length;
        if(len > 0 && objs[0].href) {
            window.location = objs[0].href;
        }
    }
}
function showObject(tmp) {
    var obj = document.getElementById(tmp);
    if(obj) {
        if(obj.style) obj.style.display = "block";
    }
    return obj;
}
function hideObject(tmp) {
    var obj = document.getElementById(tmp);
    if(obj) {
        if(obj.style) obj.style.display = "none";
    }
    return obj;
}
function popup(target,el,visible) {
    if(!visible) hideObject(el);
    else {
        var obj = showObject(el);
        if(obj && target){
            obj.style.top = getElementOffset(target)-obj.offsetHeight+"px";
        }
    }
}
function getElementOffset(el) {
    var y = 0;
    if(el) {
        while (el && !isNaN(el.offsetTop)){
            y += el.offsetTop-el.scrollTop;
            el = el.offsetParent;
        }
    }
    return y;
}
function rhtmlspecialchars(str) {
    if(typeof(str)=="string"){
        str = str.replace(/&gt;/ig,">");
        str = str.replace(/&lt;/ig,"<");
        str = str.replace(/&#039;/ig,"'");
        str = str.replace(/&quot;/ig,'"');
        str = str.replace(/&amp;/ig,"&");
    }
    return str;
}
function htmlspecialchars(str) {
    if(typeof(str)=="string"){
        str = str.replace(/&/g,"&amp;");
        str = str.replace(/"/g,"&quot;");
        str = str.replace(/'/g,"&#039;");
        str = str.replace(/</g,"&lt;");
        str = str.replace(/>/g,"&gt;");
    }
    return str;
}
function trim(string) {
    return string.replace(/^\s+|\s+$/g,"");
}
function strip_tags(string) {
    return string.replace(/<([^>]+)>/ig,"");
}
