/**
 *
 * @param {Object} objId 生成文本框(input) 的 id 和 name
 * @param {Object} data 原始数据，json 对象，3个属性 text,simpleSpell,spell, 和 value,value是要放到输入框中的值，text是提示框中显示的值,simpleSpell是拼音简写，spell是中文的拼音
 * @param {Object} defaultValue 默认值
 * @param {Object} recommend 用户没有输入时列表中显示的
 * @param {Object} title 显示在提示框最上方的文字
 */

function Suggest(objId, data, defaultValue, recommend, inputclass, title,getValue){
	
    //输入框
    var obj;
    
    //提示框
    var div;
    
    var divBottom;
    
    var divTop;
    
    var t = "请输入/拼音/三字码，用↑↓← →选择"
    
    // div中的table(提示的内容都在此table中)
    var table;
	
    var orgData = data;
    
    var page;
    
    var isFF = navigator.userAgent.indexOf("Firefox") > -1;
    
    var rowIndex = -1;
	
	// 找不到用户输入的数据
	var noSuchData_ = false;
    
    function includeCSS(){
        if ($$('suggestCss')) {
            return;
        }
        var oHead = document.getElementsByTagName('HEAD').item(0);
        var oCss = document.createElement('link');
        oCss.id = "suggestCss";
        oCss.href = '/js/suggest/suggest.css';
        oCss.rel = 'stylesheet';
        oCss.type = 'text/css';
        oCss.charset = 'utf-8';
        oHead.appendChild(oCss);
    }
    
    /**
     * 初始化
     */
    var init = function(){
    	
        t = title && title != "" ? title : t;
        includeCSS();
        document.write('<span class=""><input type="text" name="' + objId + '" class="'+inputclass+'" id="' + objId + '" value="' + defaultValue + '" />');
        obj = $$(objId);
        
        document.write('<div id="suggest_top' + objId + '" class="suggest_top" style="display:none;" ></div>');
        divTop = $$("suggest_top" + objId);
        
        document.write('<div id="suggest' + objId + '" class="suggest_div" style="display:none;"></div>');
        div = $$("suggest" + objId);
        
        document.write('<div id="suggest_bottom' + objId + '" class="suggest_bottom" style="display:none;" ></div>');
        divBottom = $$("suggest_bottom" + objId);
        
        /**
         * 重写输入框的 onkeyup事件
         * @param {Object} evt
         */
        obj.onkeyup = function(evt){
            evt = isFF ? evt : window.event;
            var keyCode = isFF ? evt.which : evt.keyCode;
            
            switch (keyCode) {
                case 13:
                    enter();
                    break;
                case 40:
                    down();
                    break;
                case 38:
                    up();
                    break;
                case 39:
                    nextPage();
                    break;
                case 37:
                    prePage();
                    break;
                default:
                    suggest();
            };
        };
        
        /**
         * 重写输入框的 onclick事件
         * @param {Object} evt
         */
        obj.onclick = function(evt){
        	this.select();
        	
        };
        
        /**
         *  重写输入框的 onblur
         * @param {Object} e
         */
        obj.onblur = function(e){
            var target = isFF ? e.explicitOriginalTarget : document.activeElement;
            if (page && page.data && page.data[rowIndex]) {
                var currentRow = rowIndex == -1 ? null : table.rows[rowIndex];
                if (currentRow) {
                    choose(objId, contentDiv(currentRow).value);
                }
            	
                //obj.value = page.data[rowIndex].value;
            } else if (recommend && recommend[rowIndex]) {
                obj.value = recommend[rowIndex].value;
            }
            if (!target || !target.id) {
                hide();
            } else if (target.id.indexOf("suggest_top") == 0) {
                obj.focus();
            } else if (target.id.indexOf("suggest_bottom") == 0) {
                obj.focus();
            } else if (target.id.indexOf("suggest_div") != 0) {
                hide();
            } 
            
            //如果用户未输入，重置文本框
            if($.trim($(obj).val()) == "") {
            	$(obj).val(defaultValue);
            }
        };
        
        /**
         * 重写输入框的 onfocus
         */
        obj.onfocus = function(){
        	//去除默认值
        	if($(obj).val() == defaultValue) {
        		$(obj).val("");
        	}
            suggest();
        };
    };
    
    init();
    
    /**
     * 构造提示信息 并显示
     */
    var suggest = function(){
        buildData();
        
        buildTable();
        
        position(obj);
                
        resetBottom(page.pageInfo());
    };
    
    /**
     * 在输入框中输入内容后，从orgData中选择合适的值显示在提示框中
     */
    var buildData = function(){
        var input = obj.value.toUpperCase();
        page = new Page();
        
        if (input.trim() == "") {
            hide();
            return;
        }
        var temp = new Array();
        var j = 0;
        for (var i = 0; i < orgData.length; i++) {
            if (orgData[i].text.indexOf(input) >= 0 || orgData[i].simpleSpell.indexOf(input) == 0 || orgData[i].spell.indexOf(input) == 0) {
                temp.push(orgData[i]);
                j++;
            }
            if (j == 10 || (temp.length > 0 && i == orgData.length - 1)) {
                page.push(temp);
                temp = new Array();
                j = 0;
            }
        }
		
		noSuchData_ = page.pageCount == 0;
    };
	
	this.noSuchData = function() {
		return noSuchData_;
	};
	
    /**
     * 上面文字
     * @param {Object} s
     */
    var resetTop = function(s){
        divTop.innerHTML = s;
    };
    
    /**
     * 下面文字
     * @param {Object} s
     */
    var resetBottom = function(s){
        if (s == "") {
            divBottom.style.display = "none";
        } else {
            divBottom.innerHTML = s;
            divBottom.style.display = "block";
        }
        
    }
    
    var buildTable = function(){
        if (!table) {
            table = document.createElement("table");
            table.id = "suggestTable" + obj.id;
            table.width = "100%";
            div.appendChild(table);
        }
        
        // 清除上次显示的结果
        var all = table.childNodes;
        for (var i = 0; i < all.length; i++) {
            table.removeChild(all[i]);
        }
        
        // 一定要加tbody
        var tBody;
        tBody = document.createElement("tbody");
        table.appendChild(tBody);
        
        var d;
        
        if (obj.value == "" && recommend) {
            d = recommend;
        } else if (!page || !page.data) {
            resetTop("对不起，找不到:" + obj.value);
            resetBottom("");
            //obj.value = "";
            return;
        } else {
            d = page.data;
        }
        // 把当前行设为初始值 -1
        rowIndex = -1;
        
        
        for (var i = 0; i < d.length; i++) {
            var tr = document.createElement("tr");
            tr.id = "suggest_tr" + obj.id + "_" + i;
            
            var td = document.createElement("td");
            
            var s_div = document.createElement("div");
            
            s_div.id = "suggest_div" + obj.id + "_" + i;
            s_div.className = "suggest_out";
            s_div.onmouseover = function(){
                over(this);
            };
            s_div.onmouseout = function(){
                out(this);
            };
            
            // 保存value , 以便于choose(obj.id, this.value);
            s_div.value = d[i].value;
            if(getValue) {
            	s_div.value=getValue(d[i]);
            }
            
            if (isFF) {
                s_div.addEventListener("click", function(e){
                    choose(obj.id, this.value);
                }, false);
            } else {
                s_div.onclick = function(){
                    choose(obj.id, this.value);
                };
                
            }
            var a = d[i].text.split("_");
            s_div.innerHTML = '<p class="p_left">' + a[1] + '</p><p class="p_right">' + a[0] + '</p>';
            
            td.appendChild(s_div);
            tr.appendChild(td);
            tBody.appendChild(tr);
            
            
        }
        
        resetTop(t);
        resetBottom(page.pageInfo());
    };
    
    /**
     * 提示框处于隐藏状态 ? true : false
     */
    var alreadyHide = function(){
        return div.style.display == "";
    };
    
    /**
     * 隐藏提示框
     */
    var hide = function(){
        div.style.display = "none";
        divTop.style.display = "none";
        divBottom.style.display = "none";
    };
    
    /**
     * 根据行取到div
     * @param {Object} row
     */
    var contentDiv = function(row){
        return $$(row.id.replace("suggest_tr", "suggest_div"));
    };
    
    /**
     * 回车
     */
    var enter = function(){
        if (alreadyHide()) {
            return suggest();
        }
        if (!table || table.rows.length < 0) {
            return;
        }
        
        var currentRow = rowIndex == -1 ? null : table.rows[rowIndex];
        if (currentRow) {
            choose(objId, contentDiv(currentRow).value);
        }
    };
    
    /**
     * 下箭头
     */
    var down = function(){
        if (alreadyHide()) {
            return suggest();
        }
        if (!table || table.rows.length < 0) {
            return;
        }
        
        var currentRow = rowIndex == -1 ? null : table.rows[rowIndex];
        var nextRow = rowIndex == table.rows.length ? null : table.rows[++rowIndex];
        if (nextRow) {
            if (currentRow) {
                out(contentDiv(currentRow));
            }
            over(contentDiv(nextRow));
        } else if (page.hasNext()) {
            nextPage();
        } else if (currentRow) {
            firstPage();
        }
    };
    
    /**
     * 上箭头
     */
    var up = function(){
        if (alreadyHide()) {
            return suggest();
        }
        
        if (!table || table.rows.length < 0) {
            return;
        }
        
        if (rowIndex == -1) {
            rowIndex = table.rows.length;
        }
        var currentRow = rowIndex == -1 ? null : table.rows[rowIndex];
        var nextRow = rowIndex == 0 ? null : table.rows[--rowIndex];
        if (nextRow) {
            if (currentRow) {
                out(contentDiv(currentRow));
            }
            over(contentDiv(nextRow));
        } else if (page.hasPre()) {
            prePage();
        } else if (currentRow) {
            lastPage();
        }
    };
    
    /**
     * 下一页
     */
    var nextPage = function(){
        if (alreadyHide()) {
            return suggest();
        }
        if (page.hasNext()) {
            page.next();
            buildTable();
        } else if (page.hasPre()) {
            firstPage();
        }
    };
    
    /**
     * 前一页
     */
    var prePage = function(){
        if (alreadyHide()) {
            return suggest();
        }
        if (page.hasPre()) {
            page.pre();
            buildTable();
        } else if (page.hasNext()) {
            lastPage();
        }
    };
    
    /**
     * 第一页
     */
    var firstPage = function(){
        page.first();
        buildTable();
    };
    
    /**
     * 最后页
     */
    var lastPage = function(){
        page.last();
        buildTable();
    };
    
    
    /**
     * 定位提示框
     */
    var position = function(o){
    
        var top = o.offsetTop;
        var height = o.clientHeight;
        var left = o.offsetLeft;
        while (o = o.offsetParent) {
        	if(o.style.position =='relative'){
        		break;
        	}
            top += o.offsetTop;
            left += o.offsetLeft;
            
        }
        //alert("top="+top);
        //alert("left="+left);
        divTop.style.top = (top + height + 2) + 'px';
        divTop.style.left = left + 'px';
        divTop.style.display = "block";
        divTop.style.zIndex = "999";
        
       div.style.top = (divTop.offsetTop + divTop.clientHeight) + 'px';
        div.style.left = left + 'px';
        div.style.display = "block";
        div.style.zIndex = "999";
        //alert(divTop.offsetTop)
        divBottom.style.top = (div.offsetTop + div.clientHeight - 1) + 'px';
        divBottom.style.left = left + 'px';
        divBottom.style.display = "block";
        divBottom.style.zIndex = "999";
    };
    
    /**
     * 分页类
     */
    function Page(){
        // 所有页的数据
        var list = new Array();
        
        var c_index = 0;
        
        this.pageCount = 0;
        
        //当前页数据
        this.data;
        
        this.push = function(onePage){
            if (this.pageCount == 0) {
                this.data = onePage;
            }
            list.push(onePage);
            this.pageCount++;
        };
        this.get = function(i){
            return list[i];
        };
        this.pre = function(){
            if (c_index > 0) {
                this.data = list[--c_index];
            }
        };
        this.next = function(){
            if (c_index < list.length - 1) {
                this.data = list[++c_index];
            }
        };
        
        this.hasNext = function(){
            return c_index < list.length - 1;
        };
        
        this.hasPre = function(){
            return c_index > 0;
        };
        
        this.first = function(){
            if (list.length > 0) {
                c_index = 0;
                this.data = list[c_index];
            }
        };
        this.last = function(){
            if (list.length > 0) {
                c_index = list.length - 1;
                this.data = list[c_index];
            }
        };
        // 当前页数 从 1 开始
        this.pageInfo = function(){
            return this.pageCount > 1 ? c_index + 1 + "/" + this.pageCount : "";
        };
    }
}


/**
 * 通过鼠标选择提示框中的内容
 * @param {Object} objId
 * @param {Object} value
 */
function choose(objId, value){
	 //richAlert(value);
    $$(objId).value = value;
    $$("suggest" + objId).style.display = "none";
    $$("suggest_top" + objId).style.display = "none";
    $$("suggest_bottom" + objId).style.display = "none";
}

/**
 * 修改样式为"选中"
 * @param {Object} o
 */
function over(o){
    o.className = "suggest_over";
}

/**
 * 修改样式为"未选中"
 * @param {Object} o
 */
function out(o){
    o.className = "suggest_out";
}




String.prototype.trim = function()
{
    return this.replace(/(^[\\s]*)|([\\s]*$)/g, "");
}

