/**
 * E框架V1.0
 * 
 */

var Easy = {
    Object: {
        /**
        * 解析Easy标记
        * 
        * @param {}
        *            JSONList
        * @param {}
        *            options
        */
        parserTag: function(JSONobj, key, objectId) {

            if ($(objectId) != null) {

                if ($(objectId).tagName.toLowerCase() == 'input') {
                    if ($(objectId).type == '') {
                    } else {
                        $(objectId).value = Easy.Grid.replaceTag(JSONobj[key],
								JSONobj);
                    }
                } else if ($(objectId).tagName.toLowerCase() == 'textarea') {
                    $(objectId).value = Easy.Grid.replaceTag(JSONobj[key],
							JSONobj);
                } else if ($(objectId).tagName.toLowerCase() == 'select') {

                    $(objectId).value = Easy.Grid.replaceTag(JSONobj[key],
							JSONobj);
                } else {

                    if ($(objectId).tagName.toLowerCase() == 'span'
							&& $(objectId).readAttribute('type') != null
							&& $(objectId).readAttribute('type') == 'radio') {
                        // 单选框赋值
                        var radios = $(objectId).immediateDescendants();
                        for (var i = 0; i < radios.length; i++) {
                            if (radios[i].tagName.toLowerCase() == 'input'
									&& radios[i].type == 'radio') {
                                if (radios[i].value == JSONobj[key]) {
                                    radios[i].checked = true;
                                }
                            }
                        }

                    } else if ($(objectId).tagName.toLowerCase() == 'span'
							&& $(objectId).readAttribute('type') != null
							&& $(objectId).readAttribute('type') == 'checkbox') {
                        // 复选框赋值
                        var values = JSONobj[key].split(',');
                        var checkboxs = $(objectId).immediateDescendants();
                        for (var i = 0; i < checkboxs.length; i++) {
                            if (checkboxs[i].tagName.toLowerCase() == 'input'
									&& checkboxs[i].type == 'checkbox') {
                                for (var k = 0; k < values.length; k++) {

                                    if (checkboxs[i].value == values[k]) {
                                        checkboxs[i].checked = true;
                                        break;
                                    }
                                }
                            }
                        }

                    } else {
                        // 其他类型,span div等
                        $(objectId).innerHTML = Easy.Grid.replaceTag(
								JSONobj[key], JSONobj);
                    }

                }

            }

        },
        /**
        * 发送Ajax请求
        * 
        * @param {}
        *            url
        * @param {}
        *            options
        */
        request: function(url, options) {

            var parameters = {};
            if (options.parameters != null) {
                parameters = options.parameters;
            }
            new Ajax.Request(url, {
                method: 'post',
                parameters: parameters,
                onSuccess: function(response) {

                    var result = response.responseText.evalJSON();
                    var JSONobj = result.data;

                    if (result.success != null && result.success) {
                        for (var key in JSONobj) {
                            var objectId = key.toString();

                            if (options.prefix != null && options.prefix != '') {
                                objectId = options.prefix + "." + objectId;
                            }
                            Easy.Object.parserTag(JSONobj, key, objectId);
                        }

                        // 反射回调函数
                        if (options.callBack != null) {
                            eval(options.callBack);
                        }
                        if (options.isMask == null || options.isMask) {
                            Easy.MessageBox.unmask();
                        }
                    } else {
                        if (options.isMask == null || options.isMask) {
                            Easy.MessageBox.unmask();
                        }
                        alert(result.error);
                    }

                },
                onFailure: function(transport) {
                    if (options.isMask == null || options.isMask) {
                        Easy.MessageBox.unmask();
                    }
                    alert('服务器出现错误请稍后再试！');
                }
            });
        },
        load: function(url, options) {
         
            if (options.isMask == null || options.isMask) {
                var msg = "下载中...";
                if (options.msg != null) {
                    msg = options.msg;
                }
                Easy.MessageBox.wait(msg);
            }
            this.request(url, options);
        }
    },

    Grid: {
        /**
        * 正在请求队列
        */
        loadingArray: new Array(),
        /**
        * 是否另一请求在加载中，如果已经有请求取消，没有，存入请求队列中，返回TRUE
        * 
        * @param {}
        *            gridId
        * @return {Boolean}
        */
        isLoading: function(gridId) {
            for (var i = 0; i < this.loadingArray.length; i++) {
                if (gridId == this.loadingArray[i]) {
                    return true;
                }
            }
            this.loadingArray.push(gridId);
            return false;
        },
        /**
        * 加载完，从下载队列中移除,反射回调函数
        * 
        * @param {}
        *            gridId
        */
        loaded: function(options) {
            if (options.isMask == null || options.isMask) {
                Easy.MessageBox.unmask();
            }
            if (options.gridId != null) {

                for (var i = 0; i < this.loadingArray.length; i++) {
                    if (options.gridId == this.loadingArray[i]) {
                        this.loadingArray.splice(i, 1);
                        return;
                    }
                }
            }
        },
        /**
        * @param {}
        *            parameters 参数
        * @param {}
        *            url 请求URL地址
        * @param {}
        *            gridId 表格元素ID
        * @param {}
        *            pageId 分页ID
        * @param {}
        *            callBack 强回调函数
        */
        load: function(url, options) {
            if (this.isLoading(options.gridId)) {// 已经下载中，本次被取消
                return;
            }
            if (options.isMask == null || options.isMask) {
                var msg = "下载中...";
                if (options.msg != null) {
                    msg = options.msg;
                }
                Easy.MessageBox.wait(msg);
            }

            if (options.gridId != null && options.gridId != '') {
                $(options.gridId).hide();
            }
            this.request(url, options);
        },
        /**
        * 解析Easy标记
        * 
        * @param {}
        *            JSONList
        * @param {}
        *            options
        */
        parserTag: function(JSONList, options) {
        
            for (var i = 0; i < JSONList.length; i++) {
                var JSONobj = JSONList[i];
              
                this.parserCell(options.gridId, JSONobj, i,
						options.parameters.start);

            }
        },
        /**
        * 替换标记为对应值
        * 
        * @param {}
        *            gridId
        * @param {}
        *            JSONobj
        * @param {}
        *            index
        * @param {}
        *            start
        */
        parserCell: function(gridId, JSONobj, index, start) {

            var html = $(gridId).outerHTML;
            html = html.replace(gridId, gridId + "_" + index);
            var seqIndex = start;
            if (seqIndex < 0) {
                seqIndex = 0;
            }

            html = html.replace(/\[v:g@#index#@]/g, parseInt(seqIndex)
							+ parseInt(index) + 1);
            html = html.replace(/\[v:g@#record#@]/g, Object.toJSON(JSONobj));
            html = this.replaceTag(html, JSONobj);

            new Insertion.Before(gridId, html)
            $(gridId + "_" + index).show();


        },
        removeALLCell: function(gridId, limit) {

            var total = limit;
            if (limit == -1) {
                total = 10000;
            }

            for (var i = 0; i < total; i++) {
                if ($(gridId + "_" + i) != null) {
                    $(gridId + "_" + i).remove();
                } else {
                    break;
                }
            }
        },
        /**
        * 分解标签
        * 
        * @param {}
        *            data
        * @param {}
        *            JSONobj
        * @return {}
        */
        replaceTag: function(html, JSONobj) {

            var lastData = html.toString() + "";
            var reCat = /\[v:.*?\]/gi;
            html += "";
            var arrMactches = html.match(reCat);
            if (arrMactches != null) {
                for (var i = 0; i < arrMactches.length; i++) {
                    var match = arrMactches[i];

                    var attribute = this.tagHTML(JSONobj, match);
                    lastData = lastData.replace(match, attribute);
                }
            }

            return lastData;
        },

        tagHTML: function(JSONobj, arg0) {
            var sIndex = arg0.indexOf("@");
            strParam = arg0.substring(sIndex + 1, arg0.length - 2);
            var params = strParam.split(",");
            for (var i = 0; i < params.length; i++) {
                var param = params[i];
                if (params[i].indexOf("$") == 0) {
                    param = param.substring(1, param.length);
                    if (JSONobj[param] != null) {
                        param = JSONobj[param];
                    } else {
                        param = "";
                    }
                    param = param.toString();
                    param = param.replace(/<br>/g, "\n");
                    param = param.replace(/\'/g, "&#39;");
                    param = param.replace(/\"/g, "&quot;");
                }

                params[i] = "'" + param + "'";

            }
            var str = "{" + arg0.substring(1, sIndex) + "(" + params.toString()
					+ ")}";
            var htmlFilterStr = "<br>";
            str = str.replace(/\r\n/g, htmlFilterStr);
            str = str.replace(/\n/g, htmlFilterStr);
            str = str.replace(/\r\t/g, htmlFilterStr);
            var JSON = str.evalJSON();
            var result = JSON.v;
            return result;
        },
        /**
        * 发送Ajax请求
        * 
        * @param {}
        *            url
        * @param {}
        *            options
        */
        request: function(url, options) {
          
            var parameters = {};
            if (options.parameters != null) {
                parameters = options.parameters;
            }

            new Ajax.Request(url, {
                method: 'post',
                parameters: parameters,
                onSuccess: function(response) {
               
                    var result = response.responseText.evalJSON();
                    var JSONList = result.root;
                    var total = result.total;
                    // alert(JSONList[1].Title);
                    if (options.gridId != null && options.gridId != '') {
                        Easy.Grid.removeALLCell(options.gridId,
										options.parameters.limit);

                        Easy.Grid.parserTag(JSONList, options);
                      
                        // 增加对行的颜色变化侦听
                        if ($("tbColor") != null) {
                            addTableListener($("tbColor"), 0, 0);
                        }
                        Easy.Grid.printPageInfo(url, options, total);

                    }
                    // 反射回调函数
                    if (options.callBack != null) {
                        eval(options.callBack);
                    }
                    Easy.Grid.loaded(options);
                },
                onFailure: function(transport) {
                    Easy.Grid.loaded(options);
                    alert('服务器出现错误请稍后再试！');
                }
            });
        },
        // 从前面iHead行开始变色，直到倒数iEnd行结束
        addTableListener: function(o, iHead, iEnd) {
            o.style.cursor = "normal";
            iHead = iHead > o.rows.length ? 0 : iHead;
            iEnd = iEnd > o.rows.length ? 0 : iEnd;
            for (var i = iHead; i < o.rows.length - iEnd; i++) {
                o.rows[i].onmouseover = function() {
                    setTrBgColor(this, true)
                }
                o.rows[i].onmouseout = function() {
                    setTrBgColor(this, false)
                }
            }
        },
        setTrBgColor: function(oTr, b) {
            // 分别是奇数行默认颜色,偶数行颜色,鼠标放上时奇偶行颜色
            var aBgColor = ["#FFFFFF", "#f5fce9", "#d1eea7", "#d1eea7"];
            oTr.rowIndex % 2 != 0 ? oTr.style.backgroundColor = b
					? aBgColor[3]
					: aBgColor[1] : oTr.style.backgroundColor = b
					? aBgColor[2]
					: aBgColor[0];
        },
        /**
        * 打印页码信息
        * 
        * @param {}
        *            url
        * @param {}
        *            options
        */
        printPageInfo: function(url, options, total) {

            if (options.pageId != null && options.pageId != '') {

                var pageIds = options.pageId.split(',');
                for (var i = 0; i < pageIds.length; i++) {
                    if (pageIds != "") {

                        this.printPageInfoHTML(url, options, total, pageIds[i]);

                    }
                }

            }
        },
        /**
        * 计算并打印页码HTML
        * 
        * @param {}
        *            total
        * @param {}
        *            parameters
        * @param {}
        *            url
        * @param {}
        *            listId
        * @param {}
        *            pageIds
        * @param {}
        *            pageId
        */
        printPageInfoHTML: function(url, options, total, pageId) {
            var pageIds = options.pageId;
            var currentPageNo = 1;
            var rand = 0;
            var limit = options.parameters["limit"];
            var start = options.parameters["start"];
            if (limit == -1) {
                return;
            }
            var totalPage = 1;
            if (total > 0) {
                totalPage = parseInt(total / limit);
                if ((total % limit) > 0) {
                    totalPage += 1;
                }
            }
            if (totalPage < 0) {
                totalPage = 1;
            }
            if (start > 0) {
                currentPageNo = parseInt(start / limit) + 1;
            }
            if (currentPageNo < 0) {
                currentPageNo = 1;
            }

            rand++;

            var queryStringId = "queryString_" + rand;
            var tb = '<table width="100%" height="38" cellpadding="0" cellspacing="0" border="0" align="center">'
            tb += '<tr>';

            tb += '<td width="50%" ><span style="font-weight:bold;">共'
					+ total
					+ '条信息</span>&nbsp;&nbsp;每页'
					+ limit
					+ '条&nbsp;&nbsp;第<input type="text" id="pageNo_'
					+ rand
					+ '" name="page" style="width:20px"  value="'
					+ currentPageNo
					+ '"/>页<input type="button" value="跳&nbsp;转" class="click"  onclick="Easy.Grid.gotoPage(\''
					+ queryStringId + '\',\'pageNo_' + rand + '\',\'' + url
					+ '\',\'' + options.gridId + '\',\'' + pageId + '\',\''
					+ pageIds + '\',' + totalPage + ')"/>/共' + totalPage
					+ '页</td>';
            tb += '<td  align="right">';

            if (start >= limit) {
                var nextIndex = 0;
                tb += '<button class="mid_Btn" onclick="Easy.Grid.locationPage(\''
						+ queryStringId
						+ '\','
						+ nextIndex
						+ ',\''
						+ url
						+ '\',\''
						+ options.gridId
						+ '\',\''
						+ pageId
						+ '\',\''
						+ pageIds + '\')">首&nbsp;&nbsp;页</button>&nbsp;';
            }

            if (start - limit >= 0) {
                var nextIndex = start - limit;
                tb += '<button class="mid_Btn" onclick="Easy.Grid.locationPage(\''
						+ queryStringId
						+ '\','
						+ nextIndex
						+ ',\''
						+ url
						+ '\',\''
						+ options.gridId
						+ '\',\''
						+ pageId
						+ '\',\''
						+ pageIds + '\')">上一页</button>&nbsp;';
            }
            if (start + limit < total) {
                var nextIndex = start + limit;
                tb += '<button class="mid_Btn" onclick="Easy.Grid.locationPage(\''
						+ queryStringId
						+ '\','
						+ nextIndex
						+ ',\''
						+ url
						+ '\',\''
						+ options.gridId
						+ '\',\''
						+ pageId
						+ '\',\''
						+ pageIds + '\')">下一页</button>&nbsp;';
            }

            if (start + limit < total) {
                var nextIndex = limit * (totalPage - 1);
                tb += '<button class="mid_Btn" onclick="Easy.Grid.locationPage(\''
						+ queryStringId
						+ '\','
						+ nextIndex
						+ ',\''
						+ url
						+ '\',\''
						+ options.gridId
						+ '\',\''
						+ pageId
						+ '\',\''
						+ pageIds + '\')">末&nbsp;页</button>';
            }
            tb += '</td>';
            tb += '</tr>';
            tb += '</table>';

            tb += '<span id="' + queryStringId + '" style="display:none">'
					+ Object.toJSON(options) + '</span>';

            if ($(pageId) != null) {
                $(pageId).update(tb);
            }

        },
        locationPage: function(queryStringId, start, url, gridId, pageId,
				pageIds) {

            var options = $(queryStringId).innerHTML.evalJSON();
            options.parameters["start"] = start;
            options.parameters["gridId"] = gridId;
            options.parameters["pageId"] = pageIds;

            this.load(url, options);

        },
        gotoPage: function(queryStringId, pageNo, url, gridId, pageId,
				pageIds, totalPage) {

            if (!isNaN($F(pageNo)) && $F(pageNo) <= totalPage) {
                var options = $(queryStringId).innerHTML.evalJSON();
                options.parameters["start"] = options.parameters["limit"]
						* ($F(pageNo) - 1);
                if (parseInt(options.parameters["start"]) < 0) {
                    return;
                }
                options.parameters["gridId"] = gridId;
                options.parameters["pageId"] = pageIds;
                this.load(url, options);
            }

        }
    },
    MessageBox: {
        maskId: 'topFill',
        loadingId: 'loadingMsgId',
        /**
        * 取消遮罩
        */
        unmask: function() {
            $(this.maskId).style.display = 'none';
        },
        /**
        * 弹出遮罩，处于下载状态
        * 
        * @param {}
        *            msg
        */
        wait: function(msg) {

            if ($(this.maskId) == null) {
                var messageBoxElement = document.createElement('div');
                document.body.appendChild(messageBoxElement); // 
                messageBoxElement.id = this.maskId;
                messageBoxElement.style.width = '100%';
                messageBoxElement.style.display = 'none';
                messageBoxElement.innerHTML = "<div id='loadingMsgId' class='loading-in'><div class='loadingImage'></div>"
						+ msg + "</div></div>";

            }
            var obj = $(this.maskId);
            var loadingObj = $(this.loadingId);
            if (obj) {
                var iWidth = document.body.clientWidth;
                var iHeight = document.body.clientHeight;
                obj.style.width = Math.max(document.body.clientWidth, iWidth)
						+ "px";
                obj.style.height = Math
						.max(document.body.clientHeight, iHeight)
						+ "px";
                /*
                * if (loadingObj) { loadingObj.style.margin =
                * (document.documentElement.offsetHeight - obj.offsetHeight)/2; }
                */
                obj.style.display = 'block';
                var changeAlpha = function() {
                    var obj_w;
                    var e_add = 0;
                    var obj_a = 0;
                    if (Prototype.Browser.Gecko) {
                        obj_a = parseInt(obj.style.opacity);
                    } else {

                        obj_a = parseInt(obj.filters.alpha.opacity);
                    }
                    e_add += 20;
                    if (obj_a < 80) {
                        if (Prototype.Browser.Gecko) {
                            obj.style.opacity = (obj_a + e_add);
                        } else {
                            obj.filters.alpha.opacity = (obj_a + e_add);
                        }
                    } else {

                        clearInterval(bw);
                    }
                }
                var bw = window.setInterval(changeAlpha, 1);
            }

        }
    }
};
