/*
   --------html表单处理程序(submit需要jquery)-----------
    2014-11-17
    控件有多值时使用分号(,)进行隔开;加上nosubmit标记则不提交到服务器;
    自定义的控件使用html的table包裹,相关参数加在table的属性上;
  */
var form = {
    base: {//base对象下不建议对象外部直接调用
        multivaluedSeparator: ",",
        check: function (vallist, param) {
            var test = function (r, v) { return new RegExp(r).test(v); };
            form.tips.removeAll();
            if (typeof param == "object") {
                var getval = eval('(' + "{\"" + vallist.replace(/^__VIEWSTATE=\S[^&]+=&/, "").replace(/&/g, "\",\"").replace(/=/g, "\":\"") + "\"}" + ')');
                for (var i = 0, j = param.length != null ? param.length : 1; i < j; i++) {
                    var obj = param.length != null ? param[i] : param;
                    if (getval[obj.Name] != null) {
                        if (obj.Null != null && (obj.Null == false || obj.Null == 0 || obj.Null == "0")) {
                            if (getval[obj.Name] == "") { if (obj.Error != null) { form.tips.error(obj.Name, obj.Error); } return obj.Name; }
                        } else if (getval[obj.Name] == "") { continue; }
                        if (obj.Rule != null && !test(obj.Rule, getval[obj.Name])) {
                            if (obj.Error != null) { form.tips.error(obj.Name, obj.Error); } return obj.Name;
                        }
                    }
                }
            }
            return "";
        },
        get: function (getParam) {
            var context = form; var formval = ""; var inputlist = document.getElementsByTagName("input"); var ckbNameStr = "", rdoNameStr = "";
            for (var i = 0; i < inputlist.length; i++) {
                var obj = inputlist[i];
                if (obj.attributes["nosubmit"] != null) { continue; }
                if (obj.type == "text" || obj.type == "password" || obj.type == "hidden") {
                    if (typeof obj.name == "string" && obj.name != "" && obj.name != "__VIEWSTATE") { formval += (obj.name + "=" + encodeURIComponent(obj.value) + "&"); }
                    else if (typeof obj.id == "string" && obj.id != "" && obj.id != "__VIEWSTATE") { formval += (obj.id + "=" + encodeURIComponent(obj.value) + "&"); }
                }
                else if (obj.type == "checkbox" && ckbNameStr.indexOf(obj.name) == -1) {
                    if (typeof obj.name == "string" && obj.name != "") { ckbNameStr += ("_" + obj.name); }
                }
                else if (obj.type == "radio" && rdoNameStr.indexOf(obj.name) == -1) {
                    if (typeof obj.name == "string" && obj.name != "") { rdoNameStr += ("_" + obj.name); }
                }
            }
            if (ckbNameStr != "") {
                var ckbNameList = ckbNameStr.substring(1).split('_');
                for (var i = 0; i < ckbNameList.length; i++) {
                    if (ckbNameList[i] != "") { formval += (ckbNameList[i] + "=" + context.checkbox.get(ckbNameList[i]) + "&"); }
                }
            }
            if (rdoNameStr != "") {
                var rdoNameList = rdoNameStr.substring(1).split('_');
                for (var i = 0; i < rdoNameList.length; i++) {
                    if (rdoNameList[i] != "") { formval += (rdoNameList[i] + "=" + context.radio.get(rdoNameList[i]) + "&"); }
                }
            }
            var selectList = document.getElementsByTagName("select");
            for (var i = 0; i < selectList.length; i++) {
                var select = selectList[i]; var nameorid = "";
                if (select.attributes["nosubmit"] != null) { continue; }
                if (select.name != null && select.name != "") {
                    nameorid = select.name;
                } else if (select.id != null && select.id != "") {
                    nameorid = select.id;
                } else { break; }
                formval += (nameorid + "=" + context.select.get(nameorid) + "&");
            }
            var textareaList = document.getElementsByTagName("textarea");
            for (var i = 0; i < textareaList.length; i++) {
                var textarea = textareaList[i];
                if (textarea.attributes["nosubmit"] != null) { continue; }
                if (textarea.name != null && textarea.name != "") {
                    formval += (textarea.name + "=" + encodeURIComponent(textarea.value) + "&");
                } else if (textarea.id != null && textarea.id != "") {
                    formval += (textarea.id + "=" + encodeURIComponent(textarea.value) + "&");
                }
            }
            if (this.__params != null)
            for (var i = 0, j = this.__params.length; i < j; i++)//处理部分特殊类型
            {
                var p = this.__params[i];
                if (p.Type == null) { continue; }
                if (p.Type == "javascript" && p.Call != null) {
                    try { if (formval.indexOf("&" + p.Name + "=") == -1) { formval += (p.Name + "=" + encodeURIComponent(eval(p.Call)) + "&"); } } catch (e) { console.log(e.message); }

                } else if (p.Type == "userControl") {
                    var tbobj = this.id(p.Name);
                    if (tbobj.attributes["control"] != null && tbobj.attributes["getvalue"] != null) {
                        if (tbobj.id != null && tbobj.id != "") { try { if (formval.indexOf("&" + tbobj.id + "=") == -1) { var v = eval(tbobj.attributes["getvalue"].value); formval += (tbobj.id + "=" + encodeURIComponent(v == "[]" ? "" : v) + "&"); } } catch (e) { console.log(e.message); } }
                    }
                } else if (p.Type == "attribute" && p.AttributeName != null) {
                    var domObj = this.id(p.Name);
                    if (domObj != null && domObj.attributes[p.AttributeName] != null) { formval += (p.Name + "=" + encodeURIComponent(domObj.attributes[p.AttributeName].value) + "&"); }
                } else if (p.Type == "attributes") {
                    var attr = ""; var domObj = this.id(p.Name);
                    if (domObj != null) { for (var akey in domObj.attributes) { attr += (akey + ":" + domObj.attributes[akey].value + ";"); } }
                    formval += (p.Name + "=" + encodeURIComponent(attr.substring(0, attr.length - 1)) + "&");
                }
            }
            return (formval.substr(0, formval.length - 1));
        },
        __params: null,//用来存放初始化表单的相关参数
        _addEvent: function (_obj, _type, _fn) { if (_obj.attachEvent) { _obj.attachEvent("on" + _type, _fn); } else { _obj.addEventListener(_type, _fn, false); } },
        id: function (_idstr) { return document.getElementById(_idstr); }

    },
    init: function (_params) {//初始化表单项(暂时只有获取时才需要此函数)
        if (_params == null || typeof _params != "object") { return; }
        var _base = this.base; _base.__params = _params; var context = this;
        for (var i = 0, j = _base.__params.length; i < j; i++) {
            var pobj = _base.__params[i];
            {
                if (pobj.Name != null) {
                    var dom = _base.id(pobj.Name);
                    if (dom != null) {
                        if (pobj.Focus != null) {//焦点提示
                            dom.setAttribute("focusTips", pobj.Focus);
                            _base._addEvent(dom, "mouseup", function (o) { context.tips.focus(this.id, this.attributes["focusTips"].value); });
                        }
                        _base._addEvent(dom, "blur", function (o) { context.tips.remove(this.id); });//有可能有别的提示存在
                    }
                }
            }
        }
    },
    check: function () {//在内部是先获取值，然后再验证
        var vallist = this.base.get();
        if (this.base.__params != null) { return this.base.check(vallist, this.base.__params); } else { return ""; }
    },
    checkAndGet: function () {//验证并获取(验证失败，将获取不到值)
        if (this.check() == "") { return this.base.get(); } else { return ""; }
    },
    get: function () {
        return this.base.get();
    },
    getJson: function () {//json对象
        var jsonstr = this.getJsonStr();
        try { return eval("[" + jsonstr + "]")[0]; } catch (e) { console.log(e.message); return {}; }
    },
    getJsonStr: function () {//获取的是json字符串
        var getval = this.get().replace(/%22/gi, "%5c%22");
        if (getval != "") {
            return '{"' + getval.replace(/^__VIEWSTATE=\S[^&]+=&/, "").replace(/&/g, "\",\"").replace(/=/g, "\":\"") + '"}';
        } else { return ""; }
    },
    set: function (param) {
        for (var key in param) {
            var inputlist = document.getElementsByName(key);
            if (inputlist.length > 0) {
                for (var x = 0; x < inputlist.length; x++) {
                    var d = inputlist[x], v = decodeURI(param[key]); var tag = d.tagName.toLowerCase();
                    if (tag == "input") {
                        if (d.type == "checkbox") { this.checkbox.set(key, v); }
                        else if (d.type == "radio") { this.radio.set(key, v); }
                        else { d.value = v; }
                    }
                    else if (tag == "select") { this.select.set(d.id, v); }
                    else if (tag == "textarea") { document.getElementsByName(d.name)[0].value = v; }
                }
            }
            else if (document.getElementById(key) != null && document.getElementById(key).tagName.toLowerCase() == "table") {
                var tbobj = document.getElementById(key);
                if (tbobj.attributes["control"] != null && tbobj.attributes["setvalue"] != null) {
                    try { eval(tbobj.attributes["setvalue"].value); } catch (e) { console.log(e.message); }
                }
            }
            else {//尝试使用js对象调用赋值
                try { eval(key + ".set('" + decodeURI(param[key]) + "')"); } catch (e) { console.log(e.message); }
            }
        }
    },
    radio: {
        get: function (domName) {
            var rdolist = document.getElementsByName(domName);
            for (var i = 0, j = rdolist != null ? rdolist.length : 0; i < j; i++) {
                if (rdolist[i].checked) { return rdolist[i].value; break; }
            }
        },
        set: function (domName, vstr) {
            var rdolist = document.getElementsByName(domName);
            for (var i = 0, j = rdolist != null ? rdolist.length : 0; i < j; i++) {
                if (rdolist[i].value == vstr) { rdolist[i].checked = "checked"; } else { rdolist[i].checked = false; }
            }
        }
    },
    checkbox: {
        get: function (domName) {
            var context = form; var ckblist = document.getElementsByName(domName); var tempval = "";
            for (var x = 0; x < ckblist.length; x++) { if (ckblist[x].checked) { tempval += ckblist[x].value + context.base.multivaluedSeparator; } }
            return tempval.substr(0, tempval.length - 1);
        },
        set: function (domName, vstr) {
            var context = form; var ckblist = document.getElementsByName(domName); var vlist = vstr.split(context.base.multivaluedSeparator);
            for (var x = 0; x < ckblist.length; x++) {
                for (var y = 0; y < vlist.length; y++) { if (ckblist[x].value == vlist[y]) { ckblist[x].checked = true; } }
            }
        }
    },
    select: {
        getDom: function (domId) { return document.getElementById(domId) != null ? document.getElementById(domId) : (document.getElementsByName(domId).length > 0 ? document.getElementsByName(domId)[0] : null); },
        get: function (domId) {
            var d = this.getDom(domId);
            if (d != null) {
                if (d.multiple) {
                    var selectVal = "";
                    for (var i = 0, j = d.options.length; i < j; i++) {
                        var option = d.options[i];
                        if (option.selected == true) { selectVal += (option.value + form.base.multivaluedSeparator); }
                    }
                    return selectVal.substring(0, selectVal.length - 1);
                } else {
                    return d.options[d.selectedIndex].value;
                }
            }
        },
        set: function (domId, value) {
            var d = this.getDom(domId);
            if (d != null && value != null) {
                var options = d.options;
                for (var i = 0; i < options.length; i++) {
                    options[i].selected = false;
                    if (d.multiple) {
                        var valueList = value.split(form.base.multivaluedSeparator);
                        for (var x = 0, y = valueList.length; x < y; x++) {
                            if (options[i].value == valueList[x]) { options[i].selected = true; break; }
                        }
                    } else {
                        if (options[i].value == value) { options[i].selected = true; }
                    }
                }
            }
        }
    },
    tips: {//表单提示
        _errorList: new Array(),
        _create: function (_inputId, _msg, _cssName) {//创建(紧跟指定id的后面)
            this.remove(_inputId);
            var control = document.getElementById(_inputId), pcontrol = control.parentNode;
            var tipsControl = document.createElement("span"); tipsControl.id = _inputId + "_formtips"; tipsControl.className = "formtips";
            var tipsObj = document.createElement("span"); tipsObj.id = _inputId + "_formtips-action"; tipsObj.className = "formtips-action formtips-" + _cssName;
            var txtObj = document.createElement("span"); txtObj.id = _inputId + "_formtips-content"; txtObj.className = "formtips-content"; txtObj.innerHTML = _msg;
            tipsObj.appendChild(txtObj);
            var bottonObj = document.createElement("span"); bottonObj.id = _inputId + "formtips-action-border"; bottonObj.className = "formtips-action-border formtips-border-" + _cssName;
            tipsObj.appendChild(bottonObj);

            tipsControl.appendChild(tipsObj);
            pcontrol.appendChild(tipsControl);
            return tipsObj;
        },
        remove: function (_inputId) {//移除，对象外也可以直接调用
            var tipsObj = document.getElementById(_inputId + "_formtips");
            if (tipsObj != null) { tipsObj.parentNode.removeChild(tipsObj); }
        },
        removeAll: function () {//移除所有(主要是错误的提示)
            if (this._errorList != null) {
                for (var i = 0, j = this._errorList.length; i < j; i++) { this.remove(this._errorList[i]); }
                this._errorList = new Array();
            }
        },
        error: function (_inputId, _msg) {//错误消息(id是指input控件的id,存在则使用,不存在则创建)
            this._errorList.push(_inputId);
            this._create(_inputId, _msg, "error");
        },
        focus: function (_inputId, _msg) {//得到焦点时显示的消息，其它同上
            this._create(_inputId, _msg, "focus");
        }
    },
    submit: function (getParam, checkParam) {
        var getval = this.getJson(getParam, checkParam);
        if (getval != null && getval != "") {
            try {
                $.post(document.location.href, { "form": getval }, function (data) {
                    if (data.status == "success") {
                        alert("提交成功");
                        location.href = location.href;
                    } else {
                        alert(data.message);
                    }
                }, "json");
            } catch (e) {
                alert("操作失败,请重试!");
            }
        }
    }
};


/*table支持
2013-11-22
*/
var Table = function () {
    var tb = null, tdList = new Array(), cellLength = 0;
    this.initial = function (tbid) {
        tb = document.getElementById(tbid);
        cellLength = tb.rows[0].cells.length;
        return tb;
    },
    this.saveColumn = function (index, isClear) {
        if (tb != null) {
            if (typeof index != "number") { index = 0; }
            var trlist = tb.getElementsByTagName("tr");
            if (trlist[index] != null) {
                var tdlist = trlist[index].getElementsByTagName("td");
                for (var i = 0; i < tdlist.length; i++) {
                    tdList.push(tdlist[i].innerHTML);
                }
                if (typeof isClear == "boolean" && isClear == true) { trlist[index].parentNode.removeChild(trlist[index]); }
            }
        }
    },
    this.saveBodyColumn = function (index, isClear) {
        if (typeof index != "number") { index = 0; }
        var tbody = tb.getElementsByTagName("tbody");
        if (tbody.length > 0) {
            var bodytrlist = tbody[0].getElementsByTagName("tr");
            if (bodytrlist.length > 0) {
                this.saveColumn(bodytrlist[0].rowIndex + index, isClear);
                return;
            }
        }
        this.saveColumn(index, isClear);
    },
    this.insertRow = function (index) {
        if (typeof index != "number") { index = -1; }
        if (tdList.length > 0) {
            var tr = tb.insertRow(index);
            addColumn(tr);
            return tr;
        }
        return null;
    },
    this.insertBodyRow = function (index) {
        if (typeof index != "number") { index = -1; }
        var tbody = tb.getElementsByTagName("tbody");
        if (tbody.length > 0) {
            var tr = tbody[0].insertRow(index);
            addColumn(tr);
            return tr;
        }
        return null;
    },
    this.clearBodyRow = function () {
        var tbody = tb.getElementsByTagName("tbody");
        if (tbody.length > 0) {
            while (true) {
                var trlist = tbody[0].getElementsByTagName("tr");
                if (trlist.length > 0) {
                    trlist[0].parentNode.removeChild(trlist[0])
                } else {
                    break;
                }
            }
        }
    },
    this.get = function () {
        if (tb != null) {
            alert(tdList.length)
        }
    }
    var addColumn = function (tr) {
        if (tdList.length > 0) {
            for (var i = 0, j = tdList.length; i < j; i++) {
                var td = tr.insertCell(-1);
                td.innerHTML = tdList[i];
            }
        } else {
            for (var i = 0; i < cellLength; i++) {
                var td = tr.insertCell(-1);
                td.innerHTML = "&nbsp;";
            }
        }

        return tr;
    }
}
/*--Table模板--2013-11-25--
传入数据格式{data:数据源,total:总行数}
需要引用:Pagination.js和handlebars.js
*/
var TableTemplate = function () {
    var table = null, tbobj = null;
    this.initial = function (tableid) {
        tbobj = new Table(); table = tbobj.initial(tableid);
        tbobj.saveBodyColumn(0, true); this.showMessage("数据加载中...");
        var tfoot = table.getElementsByTagName("tfoot"); if (tfoot.length > 0) { tfoot[0].style.display = "none"; }
    },
    this.showMessage = function (msg) {
        tbobj.clearBodyRow(); var tr = tbobj.insertBodyRow();
        for (var x = 0, y = tr.cells.length; x < y; x++) {
            var cell = tr.cells[x];
            if (x == 0) {
                cell.setAttribute("colSpan", y); cell.setAttribute("colspan", y); cell.innerHTML = "<div class='nodata' style='text-align:center;'>" + msg + "</div>";//兼容ie6-7
            } else { tr.deleteCell(-1); }
        }
    },
    this.template = {
        script: function (str) {
            if (str.indexOf("<\/script>") != -1) {
                var scriptList = str.match(new RegExp(/<script type="text\/javascript">[\s\S]+<\/script>/g));
                try {
                    if (scriptList.length > 0) {
                        var jsIframe = document.createElement("iframe");
                        jsIframe.style.display = "none";
                        document.body.appendChild(jsIframe);
                        with (window.frames[window.frames.length - 1]) {
                            document.open();
                            document.write(scriptList[0]); //执行JS代码  
                            document.close();
                        }
                        var _result = jsIframe.contentDocument.body.innerHTML;
                        document.body.removeChild(jsIframe);//执行后删除iframe对象
                        return _result;
                    }
                } catch (e) {
                    return "";
                }
            }
            else {
                return str;
            }
        }
    },
    this.row = {
        ckbName: "ckbRecord",
        rowSelected: function (isSelected) {//获取所有选中/取消选项
            var ckblist = document.getElementsByName(this.ckbName); var valuelist = "";
            if (isSelected == null) { isSelected = true; }
            for (var i = 0, j = ckblist.length; i < j; i++) { if (ckblist[i].checked == isSelected && ckblist[i].value != "") { valuelist += ckblist[i].value + "|"; } }
            valuelist = (valuelist.lastIndexOf("|") == valuelist.length - 1) ? valuelist.substring(0, valuelist.length - 1) : valuelist;
            return valuelist;
        },
        rowSelection: function (obj, t, ckbName) {//触发选中状态,参数:ckb对象,t:1根据ckb对象的状态选择,2反选
            if (typeof ckbName == "string") { this.ckbName = ckbName; };//选项name
            var checkBox = document.getElementsByName(this.ckbName); t = t == null ? 1 : t;
            for (var i = 0; i < checkBox.length; i++) {
                if (t == 1) { checkBox[i].checked = obj.checked; }
                else if (t == 2) { checkBox[i].checked = !checkBox[i].checked; }
            }
        },
        cancelSelection: function () {//全部取消
            var checkBox = document.getElementsByName(this.ckbName);
            for (var i = 0; i < checkBox.length; i++) { checkBox[i].checked = false; }
        },
        allRowSelection: function () {//全部选中
            var checkBox = document.getElementsByName(this.ckbName);
            for (var i = 0; i < checkBox.length; i++) { checkBox[i].checked = true; }
        }
    },
    this.bind = function (data) {
        tbobj.clearBodyRow();
        if (data != null && data.length > 0) {
            for (var i = 0, j = data.length; i < j; i++) {
                var tr = tbobj.insertBodyRow();
                for (var x = 0, y = tr.cells.length; x < y; x++) {
                    var cell = tr.cells[x];
                    var html = cell.innerHTML.replace(/type="text\/javascript"/gi, "type=\"text\/template\"");
                    var template = Handlebars.compile(html);//使用第三方模板引擎解析
                    html = template(data[i]); html = this.template.script(html.replace(/type="text\/template"/gi, "type=\"text\/javascript\""));
                    cell.innerHTML = html;
                }
            }
        } else { this.showMessage("暂无数据!"); }
    },
    this.pagination = function (link, page, totalRows, maximumRows) {
        var _p = new Pagination(); _p.IsShowTotal = true; var htmlstr = _p.list(link, page, totalRows, maximumRows);
        if (table != null) {
            var tfoot = table.getElementsByTagName("tfoot");
            if (tfoot.length > 0) {
                tfoot[0].style.display = ""; var tr = tfoot[0].getElementsByTagName("tr");
                for (var r = 0; r < tr.length; r++)
                { var cells = tr[r].getElementsByTagName("td"); for (var c = 0; c < cells.length; c++) { cells[c].innerHTML = cells[c].innerHTML.replace(/{{page}}/gi, htmlstr); } }
            }
        }
    }
}

//自定义控件部分
var citycontrolid;
function ClickOpenCityList(evt, obj) {
    citycontrolid = obj.id;
    var citylsit = '<iframe style="background-color:white;border:1px #ccc solid;" id="SelectWindowIframe" callback="CategorySelectCallback" scrolling="no" name="SelectWindowIframe" frameborder="0" width="400" height="200" src="/plugin/_CityList.html"></iframe>';
    follow.show(evt, -10, 30, obj, citylsit);
}
function CitySelectCallback(params) {
    try {
        var cityobj = document.getElementById(citycontrolid);
        cityobj.value = params.namePath;
        cityobj.setAttribute("namepath", params.namePath);
        cityobj.setAttribute("idpath", params.idPath);
        cityobj.setAttribute("cityname", params.cityName);
        cityobj.setAttribute("cityid", params.cityId);
        follow.close();
    } catch (e) { }
}