﻿
/* ---------------------------- Class KmwAutocp ------------------------- */

/*
 *  [Summary]
 *      自动完成
 */
function KmwAutocp(sId, sUrl, sType) {
    this.__txtid = sId;
    this.__atcid = sId + "_atc";
    this.__axaj = new KmwAxaj(sUrl, sType); // Axaj
    this.__cache = new Object();            // 缓存
    this.__currkey = "";                    // 当前检索用Key

    this.__search_timer = 0;                // 检索定时器
    this.__detect_timer = 0;                // 检测定时器
    this.__clear_timer = 0;                 // 清除定时器
    
    var me = this;                          // 闭包？

    this.onkeydown = function() {
        var textbox = document.getElementById(me.__txtid);
        switch (event.keyCode) {
            case 9: // tab key
                me.hide(true);
                break;
            case 13 : // enter key
            case 38 : // up arrow key
            case 40 : // down arrow key
                event.cancelBubble = true;
            default :
                if (me.__detect_timer == 0) {
                    me.__detect_timer = setInterval(function(){me.search();}, 589);
                }
                break;
        }
    }

    this.onkeyup = function() {
        me.search();
    }

    this.onblur = function() {
        if (me.__clear_timer == 0) {
            me.__clear_timer = setInterval(function(){me.hide(true);}, 973);
        }
    }

    this.search = function() {
        var sKey = me.__getCurrentKey();
        if (sKey == "") {
            me.hide();
            return;
        } else if (me.__currkey == sKey) {
            return;
        }
        me.__currkey = sKey;
        // 取消当前的处理
        if (me.__search_timer > 0) {
            clearTimeout(me.__search_timer);
            me.__search_timer = 0;
        }
        me.__axaj.abort();
        sKey = escape(sKey);
        if (typeof(me.__cache[sKey]) != "undefined") {
            // 缓存命中
            me.show(me.__cache[sKey]);
        } else {
            // 延时检索
            var oAxaj = me.__axaj;
            var sParams = "type=smsusr&key=" + sKey;
            var fCallback = me.show;
            me.__search_timer = setTimeout(function(){KmwAutocp.waitSearchResult(oAxaj,sParams,fCallback,sKey);}, 444);
        }
    }

    this.show = function(oXml, sKey){
        if (sKey) {
            me.__cache[sKey] = oXml;
        }
    	var oAtc = document.getElementById(me.__atcid);
    	var result = oXml.selectSingleNode("/result");
    	var count = result.childNodes.length;
    	if (count == 0) {
    		oAtc.style.visibility = "hidden";
    		return;
    	}
        oAtc.innerHTML = "";
    	for (var i = 0; i < count; i++) {
    		var node = result.childNodes[i];
    		var item = document.createElement("a");
    		item.setAttribute("href", "#");
    		item.innerText = (browser == "firefox") ? node.textContent : node.text;
    		item.attachEvent("onclick", me.select);
    		oAtc.appendChild(item);
    	}
    	var item = document.createElement("a");
    	item.setAttribute("href", "#");
    	item.className = "last";
		item.innerText = "关闭";
		item.attachEvent("onclick", me.hide);
		oAtc.appendChild(item);
        oAtc.style.top = me.top;
        oAtc.style.left = me.left
        oAtc.style.width = me.width;
        oAtc.style.visibility = "visible";
    }

    this.hide = function(bStop) {
        if (bStop) {
            if (me.__detect_timer > 0) {
                clearInterval(me.__detect_timer);
                me.__detect_timer = 0;
            }
            if (me.__search_timer > 0) {
                clearTimeout(me.__search_timer);
                me.__search_timer = 0;
            }
            me.__axaj.abort();
            me.__currkey = "";
        }
        var oAtc = document.getElementById(me.__atcid);
        oAtc.style.visibility = "hidden";
    }

    this.select = function() {
        me.__setCurrentKey(event.srcElement.innerText);
        event.cancelBubble = true; 
        me.hide(true);
    }
}


KmwAutocp.prototype.__getCurrentKey = function() {
    var textbox = document.getElementById(this.__txtid);
    // 检查关键字是否为空
    var content = textbox.value;
    if (content.replace(/ /g, "") == "") {
        return "";
    }
    // 从逗号分隔的关键字序列中，取出当前光标所在的关键字
	content = content.replace(/，/g, ",");
    var length = content.length;
    var pos = 0;
    textbox.focus();
    if (typeof(textbox.selectionStart) == "number") {
        pos = textbox.selectionStart;
    } else {
        var range = document.selection.createRange(); 
        range.setEndPoint("StartToStart", textbox.createTextRange());
        pos = range.text.length;
    }
    var start = 0;
    if (content.substr(pos, 1) == ",") {
        start = content.lastIndexOf(",", pos - 1);
    } else {
        start = content.lastIndexOf(",", pos);
    }
    start = (start < 0) ? 0 : (start + 1);
    var end = content.indexOf(",", pos);
    end = (end < 0) ? (length) : end;
    var sKey = content.substring(start, end).replace(/ /g, "");
    if (sKey == "") {
        return "";
    }
    return sKey;
}

KmwAutocp.prototype.__setCurrentKey = function(sKey) {
    var textbox = document.getElementById(this.__txtid);
    var content = textbox.value;
	content = content.replace(/，/g, ",");
    var length = content.length;
    var pos = 0;
    textbox.focus();
    if (typeof(textbox.selectionStart) == "number") {
        pos = textbox.selectionStart;
    } else {
        var range = document.selection.createRange(); 
        range.setEndPoint("StartToStart", textbox.createTextRange());
        pos = range.text.length;
    }
    var start = 0;
    if (content.substr(pos, 1) == ",") {
        start = content.lastIndexOf(",", pos - 1);
    } else {
        start = content.lastIndexOf(",", pos);
    }
    start = (start < 0) ? 0 : (start + 1);
    var end = content.indexOf(",", pos);
    end = (end < 0) ? (length) : end;
    if (start > 0) {
        content = content.substring(0, start) + " " + sKey + content.substring(end);
    } else {
        content = sKey + content.substring(end);
    }
    textbox.value = content;
}

    
/* ---------------------------- Static Members  --------------------------- */

KmwAutocp.attach = function($txtbox, $url, $left, $top, $width) {
    if ($txtbox.autocp == null) {
        var autocp = new KmwAutocp($txtbox.id, $url, "xml");
        autocp.left = $left;
        autocp.top = $top;
        autocp.width = $width;
        $txtbox.autocp = autocp;
    } else {
        var autocp = $txtbox.autocp;
    }
    if (autocp.__clear_timer > 0) {
        clearInterval(autocp.__clear_timer);
        autocp.__clear_timer = 0;
    }
    $txtbox.attachEvent("onkeydown", autocp.onkeydown);
    $txtbox.attachEvent("onkeyup", autocp.onkeyup);
    $txtbox.attachEvent("onblur", autocp.onblur);
}

KmwAutocp.waitSearchResult = function(oAxaj, sParams, fCallback, sKey) {
    oAxaj.post(sParams, fCallback, sKey);
}


/* ---------------------------- Functions  --------------------------- */

function get_top(e){
    var offset=e.offsetTop;
    if(e.offsetParent!=null) offset+=get_top(e.offsetParent);
    return offset;
}

function get_left(e){
    var offset=e.offsetLeft;
    if(e.offsetParent!=null) offset+=get_left(e.offsetParent);
    return offset;
}
