/**
 * 版权说明,你可以任意的拷贝,发布,修改本js代码.但对于修改后的代码修改 必须发一份到jspxnet@163.com
 * 这样方便我在后期升级考虑
 * jspxnet.js 1.2 for mootools 1.23
 * date:2009-5-13
 * chenYan
 * 简单的控件直接使用样式表
 * 日历样式 .calendar
 * 简单颜色选择 .colorBox
 * 链接方式窗口 a class="window"
 */
//保存当前选择的行
/*
 //表头Cation
 var hcaption = ["排序","开始HTML","结束HTML","目标字段","字段类型","不重复","常量-表达式","删除"];
 var varNames =[
 {name:"sortType",input:"input"},
 {name:"fieldStartTag",input:"text"},
 {name:"fieldEndTag",input:"text"},
 {name:"toField",input:"select",option:"one;two;three"},
 {name:"fieldType",input:"select",option:"string;int;float;double;date"},
 {name:"fieldCheck",input:"checkbox",option:"1"},
 {name:"fieldExpression",input:"text"}
 jtable = new TableBind({id:"表格ID",heads:hcaption});
 cbutton 将判断数据有无 出现
 */
//比较颜色 #ff000 形式和 rgb(255,0, 0) 比较
String.prototype.compareColor = function(color) {
    if (this == color) return true;
    if (this == null || color == null) return false;
    if (this.toLowerCase().replace(/ /g, '') == color.toLowerCase().replace(/ /g, '')) return true;
    var tempColor = false;
    if (this.toLowerCase().indexOf("rgb") == -1 && this.length > 1) {
        tempColor = this.hexToRgb();
        if (!tempColor) return false;
        tempColor = tempColor.toLowerCase().replace(/ /g, '');
        return (tempColor == color.toString().toLowerCase().replace(/ /g, ""));
    }
    if (color.toLowerCase().indexOf("rgb") == -1 && color.length > 1) {
        tempColor = color.hexToRgb();
        if (!tempColor) return false;
        tempColor = tempColor.toLowerCase().replace(/ /g, '');
        return (tempColor == this.toString().toLowerCase().replace(/ /g, ""));
    }
};
//交换表格的两列
function swapTableCell(mytable, startCell, endCell) {
    if (startCell == endCell) return;
    var oTBody = mytable.tBodies[0];
    for (var i = 0; i <= oTBody.rows.length; i++) {
        swapNode(mytable.rows.item(i).cells[startCell], mytable.rows.item(i).cells[endCell]);
    }
}
//firefox 交换节点,IE有
function swapNode(node1, node2) {
    var parent = node1.parentNode;//父节点
    var t1 = node1.nextSibling;//两节点的相对位置
    var t2 = node2.nextSibling;

    //如果是插入到最后就用appendChild
    if (t1) parent.insertBefore(node2, t1);
    else parent.appendChild(node2);
    if (t2) parent.insertBefore(node1, t2);
    else parent.appendChild(node1);
}
function createInputElement(vinput, svalue) {
    if (svalue == null||svalue == '&nbsp;') svalue = '';
    var myAnchor = false;
    if (!vinput.input) alert('type .input no definition,表格头部没有定义');
    if (vinput.input == "button" || vinput.input == "cbutton") {
        if (vinput.input == "cbutton" && (svalue == '' || svalue == '0')) myAnchor = new Element('div'); //如果无数据
        else if (vinput.blink) {
            //如果要新窗口使用函数方式
            myAnchor = new Element('a', {'class':'button','href':vinput.blink});
            if (vinput.caption && vinput.caption.indexOf('|') != -1)
                myAnchor.adopt(new Element('span', {'html':vinput.caption.substring(vinput.caption.indexOf('|') + 1, vinput.caption.length)}));
            else myAnchor.adopt(new Element('span', {'html':vinput.caption}));
        }
    }
    if ("textarea" == vinput.input) {
        myAnchor = new Element('textarea', {'rows':1,'name':vinput.name,'value': svalue});
    }
    if ("select" == vinput.input) {
        myAnchor = new Element('select', {'name':vinput.inputName?vinput.inputName:vinput.name});
        myAnchor.setOptions(vinput.option, svalue);
    }
    if ("urlDialog" == vinput.input) {
        myAnchor = new Element('input', {'type':'text','name':vinput.inputName?vinput.inputName:vinput.name,'class':'colorBox','value':svalue});
    }
    if ("selectbox" == vinput.input.toLocaleLowerCase()) {
        myAnchor = new Element('input', {'type':'checkbox','name':vinput.inputName?vinput.inputName:vinput.name,'value':svalue});
    }
    if ("checkbox" == vinput.input) {
        myAnchor = new Element('input', {'type':vinput.input,'name':vinput.inputName?vinput.inputName:vinput.name,'value':svalue});
        if (this.options) {
            var selectArray = vinput.options;
            if ($type(this.options) == 'string')
                selectArray = vinput.options.split(";");
            if ($type(selectArray) == 'array' && selectArray.contains(svalue))
                myAnchor.set('checked', 'checked');
        }
    }
    if ("color" == vinput.input) {
        myAnchor = new Element('input', {'type':'text','name':vinput.inputName?vinput.inputName:vinput.name,'class':'colorBox','value':svalue});
    }
    if ("date" == vinput.input) {
        myAnchor = new Element('input', {'type':'text','class':'calendar','name':vinput.inputName?vinput.inputName:vinput.name,'value':svalue});
    }
    if ("text" == vinput.input) {
        myAnchor = new Element('input', {'type':vinput.input,'name':vinput.inputName?vinput.inputName:vinput.name,'value': svalue});
    }
    if ("img" == vinput.input) {
        myAnchor = new Element('img', {'type':vinput.input,'name':vinput.inputName?vinput.inputName:vinput.name,'src': svalue});
    }
    return myAnchor;
}
function getTableCellValue(tableCell, fixed) {
	 var tempEl = tableCell.getElement("input");
     if (tempEl) return tempEl.get("value");
     
     var result = '';
	 tempEl = tableCell.getElement("textarea");
     if (tempEl) 
	 {
		result=tempEl.get("value"); 
		if (fixed && result)
               return result.replace(/\</g, "&lt;").replace(/\>/g, "&gt;");
		else return result;
	 }

	 tempEl = tableCell.getElement("select");
     if (tempEl) 
	 {
		return tempEl.get("value");
	 }

	 tempEl = tableCell.getElement("checkbox");
	 if (tempEl) return tempEl.get("value");
    return tableCell.get('html');
}
//判断单选或多选框是否选择
function getTableCellChecked(tableCell) {
    var fnp = tableCell.innerHTML;
    if (Browser.Engine.trident) {
        var tempEl = new Element('div', {'html': fnp});
        if (tempEl.getElement("input"))
            return tempEl.getElement("input").get("checked");
    } else {
        if (tableCell.getElement("input"))
            return tableCell.getElement("input").get("checked");
    }
    return false;
}

function convert(sValue, sDataType) {
    switch (sDataType) {
        case "number":
            if (sValue == null) return 0;
            return sValue.trim().toNumber() || 0;
        case "text":
            if (sValue == null) return 0;
            if (sValue.length > 40) return sValue.cut(40);
            return sValue.trim() || "";
        case "color":
            if (sValue == null) return 0;
            var tempColor = sValue;
            if (sValue.toLowerCase().indexOf("rgb") == -1 && sValue.length > 1)
                tempColor = color.hexToRgb();
            return tempColor.replace('rgb', '').replace(/ /g, '').replace(/, /g, '').trim().toInt() || 0;
        case "date":
            if (sValue == null) return 0;
            return sValue.toDate().getTime() || 0;
        default:
            if (sValue == null) return "";
            return sValue.trim() || "";
    }
}
//------------------------------------
var JsTable = new Class({
    Implements: Options,
    options: {
        parent:'', //主容器
        row:'', //一行模板
        url: false,
        format:false,
        turnPage:"turnPage",
        onLoadAfter:$empty()//载入数据后
    },
    initialize: function(options) {
        this.setOptions(options);
        var rowobj = false;
        if ($type(this.options.row) == 'string')
            rowobj = $(this.options.row);
        else rowobj = this.options.row;
        var tmpDiv = new Element('div');
        tmpDiv.adopt(rowobj);
        this.options.template = tmpDiv.get('html');
        if (Browser.Engines.gecko)   //firefox 请求会被转换
            this.options.template = this.options.template.replace(/%7B/g, "{").replace(/%7D/g, "}");
        if ($type(this.options.parent) == 'string')
            this.options.parent = $(this.options.parent);
        if ($type(this.options.turnPage) == 'string')
            this.options.turnPage = $(this.options.turnPage);
        this.loadURL();
    }
    ,
    loadURL: function(url) {
        if (!url) url = this.options.url;
        //接收url方式和数组方式
        new Request.JSON({
            url: url,
            method:'GET', //必须
            encoding:'UTF-8',
            result : "JSON",
            async:false,
            tableObject:this,
            onSuccess:  this.setData
        }).get();
    }
    ,
    setData: function(data, append) {
        if (!append) this.clearAll();
        var mytb = this;
        if (this.options.tableObject) {
            mytb = this.options.tableObject;
            mytb.clearAll();
        }
        if (!data) return;
        if (data.list) {
            var format = mytb.options.format;
            var html = '';
            data.list.each(function(line) {
                if (format)
                    for (var key in format) {
                        if (eval('line.' + key) != undefined) {
                            eval('line.' + key + '=line.' + key + format[key]);
                        }
                    }
                html = html + mytb.options.template.substitute(line);
            });
            mytb.options.parent.set('html', html);
            html = false;
            if (data.turnPage && mytb.options.turnPage) {
                mytb.options.turnPage.set('html', data.turnPage);
                var turnButtons = mytb.options.turnPage.getElements('a');
                turnButtons.each(function(button) {
                    var ahref = button.get('href');
                    button.removeProperty("href");
                    button.addEvent('click', function() {
                        if ((Browser.Engine.trident4 || Browser.Engine.trident5) && (ahref.startsWith("http") && mytb.options.url != '')) {
                            var x = ahref.indexOf('?');
                            if (x != -1)ahref = ahref.substring(x, ahref.length);
                        }
                        if (mytb.options.url.indexOf('?') != -1 && ahref.indexOf('?') == 0)
                            ahref = ahref.replace('?', '&');
                        mytb.loadURL(mytb.options.url + ahref);
                    });
                });
            }
            if (mytb.options.onLoadAfter) mytb.options.onLoadAfter();
        }
    }
    ,
    appendRow:function(line) {
        var html = this.options.parent.get('html') + this.options.template.substitute(line);
        this.options.parent.set('html', html);
    }
    ,
    clearAll:function() {
        this.options.parent.set('html', '');
    }
});

//-----------------------------颜色输入框
var ColorBox = new Class({
    Implements: Options,
    options: {
        ptag:'body',
        colorBoxCss:'.colorBox',
        option: 'default'
    },
    initialize: function(options) {
        this.setOptions(options);
        if (!this.ptag) this.ptag = "body";
    },
    cssInit:function() {
        var cr = this;
        var option = cr.options.option;
        if (!option || option == "default") option = "#000000;#B0B0B0;#F0F0F0;#FFFFFF;#F00000;#FFE0E0;#00cc00;#0FF0C0;#00ccFF;#bbF000;#0000BB;#B111B1;#BBBB00;#FFFF00;#FFBB00;#FF00FF";
        var colorBoxCss = cr.options.colorBoxCss;
        $$(cr.ptag.toLowerCase() + " " + colorBoxCss).each(function(cbox) {
            cbox.addEvent('mousedown', function(event) {
                var event = new Event(event);
                event.stopPropagation();
                var colorPaneId = cbox.id + '_colorPane';
                var colorPane = $(colorPaneId);
                if (colorPane) return false;
                this.set("colorBox", colorPaneId);
                colorPane = new Element('div', {id:colorPaneId,'class': 'colorPane'});
                colorPane.inject(cbox.getParent());
                colorPane.setStyle('left',cbox.getStyle('left').toInt());
                colorPane.adopt(new Element('span'));
                var colArray = option.split(";");
                for (var i = 0; i < colArray.length; i++) {
                    var col = colArray[i];
                    colorPane.adopt(new Element('div',
                    {
                        'styles':
                        {
                            'background-color':col
                        },
                        'events':
                        {
                            'mouseover': function(event) {
                                var event = new Event(event);
                                event.stopPropagation();
                                var selColor = this.getStyle("background-color");
                                colorPane.getElement("span").setStyle("background-color", selColor);
                            }
                            ,
                            'click': function(event) {
                                var event = new Event(event);
                                event.stopPropagation();
                                var selColor = colorPane.getElement("span").getStyle("background-color");
                                cbox.set("value", selColor);
                                cbox.setStyle("background-color", selColor);
                                colorPane.destroy();
                            }
                        }
                    }));
                }
			   
                colorPane.addEvent('mouseleave', function(event) {
                    var event = new Event(event);
                    event.stopPropagation();
					this.destroy();
                });

                //拖动
                if (colorPane.makeDraggable)
                    colorPane.makeDraggable({
                        container:window.document.body,
                        onStart:function() {
                            this.element.setOpacity(.5);
                        },
                        onComplete: function() {
                            this.element.setOpacity(1);
                        }
                  });

            });

        });
    }
});
//----------------------------------日历
/*
 * 2009.05.25 Delino ,2009-05-28 原作者:javaeye delino ,chenYuan修改支持一个页面多个日历
 * 语言 0: 中文, 1: 英语
 * 1.  new Calendar("id").show():
 实例元素中加入该日历, 该方法提供提示功能
 * 2.   new Calendar().cssInit();
 实例文本框点击弹出该日历
 需要调用该方法的input 加上class="calendar"
 */
var Calendar = function(language, ptag, calendarCss, startYear, endYear) {
    this.Date = new Date();
    this.Year = this.Date.getFullYear();
    this.Month = this.Date.getMonth();
    this.Week = this.Date.getDay();
    this.Today = this.Date.getDate();
    if (language == 'zh') language = 0;
    this.Language = language || 0;
    this.StartYear = startYear || this.Year - 30;
    this.EndYear = endYear || this.Year + 2;
    this.EndYear = endYear || this.Year + 2;
    this.ptag = ptag || "body";
    if (!this.ptag) this.ptag = "body";
    this.calendarCss = calendarCss || ".calendar";

    var times = $random(0, 10000);
    this.popContainer_id = 'popCalendarContainer' + times;

    // 存放信息的数组
    this.msgStore = [];
    this.caleContainer_id = 'calendarContainer' + times;
    this.caleTop = {
        today_view_id:        'calendarTodayView' + times,
        week_view_id:        'calendarWeekView' + times,
        lq_year_id:            'linkQuickYear' + times,
        lq_month_id:        'linkQuickMonth' + times,
        sq_year_id:            'selectQuickYear' + times,
        sq_month_id:        'selectQuickMonth' + times,
        close_id:            'calendarClose' + times,
        prev_month_id:        'toPrevMonth' + times,
        back_today_id:        'backToday' + times,
        next_month_id:        'toNextMonth' + times
    };

    this.daysContainer_id = 'calendarDaysContainer' + times;
    this.msgContainer_id = 'calendarTipsContainer' + times;

    this.curDayClass = 'calendarCurrentDay';
    this.tipDayClass = 'calendarTipDay';
    this.oldTipDayClass = 'calendarOldTipDay';
};

/* 日历语言包 */
Calendar.lang = {
    weeks:      [
        ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
        ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
    ],
    weeksMenu:[
        ["日","一","二","三","四","五","六"],
        ["SUN","MON","TUR","WED","THU","FRI","SAT"]
    ]
};
/* 创建日历元素 */
Calendar.prototype._getViewElement = function() {
    var caleElem = "";
    caleElem += '<div id=' + this.caleContainer_id + ' class="calendarContainer">';
    // <日历上部 - 显示日期部分>
    caleElem += '<div id="calendarTopContainer" class="calendarTopContainer"><table cellpadding="0" cellspacing="0"><tr>';
    // 上部 日期 部分
    caleElem += '<td id=' + this.caleTop.today_view_id + ' class="calendarTodayView"></td>';
    // 链接和select 控制部分
    caleElem += '<td>';
    caleElem += '<table id="calendarYearMonthContainer" class="calendarYearMonthContainer" cellpadding="0" cellspacing="0">';
    caleElem += '<tr>';
    caleElem += '<td>';
    caleElem += '<a id=' + this.caleTop.lq_year_id + ' class="linkQuickYear" href="javascript:void(0);"></a>';
    caleElem += '<select id=' + this.caleTop.sq_year_id + ' class="selectQuickYear"></select>';
    caleElem += '</td>';
    caleElem += '<td>.</td>';
    caleElem += '<td>';
    caleElem += '<a id=' + this.caleTop.lq_month_id + ' class="linkQuickMonth" href="javascript:void(0);"></a>';
    caleElem += '<select id=' + this.caleTop.sq_month_id + ' class="selectQuickMonth"></select>';
    caleElem += '</td>';
    caleElem += '</tr>';
    caleElem += '</table>';
    caleElem += '<div id=' + this.caleTop.week_view_id + ' class="calendarWeekView"></div>';
    caleElem += '</td>';


    // 快速切换到上下月或本月
    caleElem += '<td>';
    caleElem += '<div id="calendarCloseContainer" class="calendarCloseContainer">';
    caleElem += '<a id=' + this.caleTop.close_id + ' class="calendarClose" href="javascript:void(0);">x</a>';
    caleElem += '</div>';

    caleElem += '<div id="calendarQuickContainer" class="calendarQuickContainer">';
    caleElem += '<a id=' + this.caleTop.prev_month_id + ' class="toPrevMonth" href="javascript:void(0);">&laquo;</a>';
    caleElem += '<a id=' + this.caleTop.back_today_id + ' class="backToday" href="javascript:void(0);">&nbsp;</a>';
    caleElem += '<a id=' + this.caleTop.next_month_id + ' class="toNextMonth" href="javascript:void(0);">&raquo;</a>';
    caleElem += '</div>';
    caleElem += '</td>';

    caleElem += '</tr></table cellpadding="0" cellspacing="0"></div>';
    // <上部创建结束>

    // <日历视图主体部分>
    caleElem += '<div id="calendarMainContainer" class="calendarMainContainer">';
    // 周 菜单
    caleElem += '<div id="calendarWeeksContainer" class="calendarWeeksContainer">';
    for (var i = 0; i < 7; i ++) {
        caleElem += '<span>' + Calendar.lang["weeksMenu"][this.Language][i] + '</span>';
    }
    caleElem += '</div>';

    // 日期 视图
    caleElem += '<table id=' + this.daysContainer_id + ' class="calendarDaysContainer" cellpadding="0" cellspacing="0">';
    for (var tr = 0; tr < 6; tr ++) {
        caleElem += '<tr>';
        for (var td = 0; td < 7; td ++) {
            caleElem += '<td><span></span></td>';
        }
        caleElem += '</tr>';
    }
    caleElem += '</table>';

    caleElem += '</div>';
    // <日历主体部分创建结束>

    caleElem += '</div>';

    // <日历提示部分 - 提供给 show() 方法>
    caleElem += '<div id=' + this.msgContainer_id + ' class="calendarTipsContainer"></div>';
    // <日历提示部分创建结束>

    return caleElem;
};
/* 获取 月份 数据 */
Calendar.prototype._getMonthViewArray = function(year, month) {
    var monthArray = [],
        // 一周的开始
            beginDayOfWeek = new Date(year, month, 1).getDay(),
        // 该月总天数
            daysOfMonth = new Date(year, month + 1, 0).getDate();
    // 创建一个 7*6 的矩阵
    for (var i = 0; i < 42; i ++)
        monthArray[i] = "&nbsp;";
    for (var j = 0; j < daysOfMonth; j ++)
        monthArray[ j + beginDayOfWeek ] = j + 1;
    return monthArray;
};
/* 查找 某值 是在该select 中的索引值 */
Calendar.prototype._getOptionIndex = function(selectObject, value) {
    for (var j = 0; j < selectObject.options.length; j ++) {
        if (value == selectObject.options[j].value)
            return j;
    }
};
/* 绑定 年 数据 */
Calendar.prototype._bindYearIntoSelect = function() {
    var oYear = this.find(this.caleTop.sq_year_id);
    var oYearLen = 0;
    for (var i = this.StartYear; i <= this.EndYear; i ++,oYearLen ++)
        oYear.options[oYearLen] = new Option(i, i);
};
/* 绑定 月 数据 */
Calendar.prototype._bindMonthIntoSelect = function() {
    var oMonth = this.find(this.caleTop.sq_month_id);
    var oMonthLen = 0;
    for (var i = 0; i < 12; i ++,oMonthLen ++)
        oMonth.options[oMonthLen] = new Option(i + 1, i + 1);
};
/* 绑定所有数据 */
Calendar.prototype._bindAllData = function(curYear, curMonth) {
    this._bindYearIntoSelect();
    this._bindMonthIntoSelect();
    this.changeSelectValue(curYear, curMonth);

    // 绑定默认数据到日历面板上部分的 当天 和 周 部分中去
    this.find(this.caleTop.today_view_id).innerHTML = this.Today;
    this.find(this.caleTop.week_view_id).innerHTML = Calendar.lang['weeks'][this.Language][this.Week];
    // 获得日期并绑定到 日历主体 部分
    var daysOfMonthArray = this._getMonthViewArray(curYear, curMonth),
            spans = this.find(this.daysContainer_id, "span"),
            curYMD = this.Year + "" + ( this.Month + 1 ) + "" + this.Today,
            selectYear = $(this.caleTop.sq_year_id).value,
            selectMonth = $(this.caleTop.sq_month_id).value;
    for (var i = 0; i < spans.length; i ++) {
        spans[i].innerHTML = daysOfMonthArray[i];
        var selectYMD = selectYear + "" + selectMonth + "" + spans[i].innerHTML;
        if (curYMD == selectYMD)
            spans[i].className = this.curDayClass;
        else
            spans[i].className = "";
    }
    if (this.msgStore != "") this._initPopMsg(this.msgStore);
};
/* 绑定所有事件 */
Calendar.prototype._bindAllEvent = function() {
    var cr = this;
    // 上月, 下月, 返回当天, 上部分当日视图 事件
    $(this.caleTop.prev_month_id).onclick = function() {
        cr.goPrevOrNextMonth(this);
    };
    $(this.caleTop.next_month_id).onclick = function() {
        cr.goPrevOrNextMonth(this);
    };
    $(this.caleTop.back_today_id).onclick = function() {
        cr.backToday();
    };
    $(this.caleTop.today_view_id).onclick = function() {
        cr.backToday();
    };
    // 年月事件
    $(this.caleTop.sq_year_id).onchange = function() {
        cr.updateSelect();
    };
    $(this.caleTop.sq_month_id).onchange = function() {
        cr.updateSelect();
    };

    $(this.caleTop.lq_year_id).onclick = function() {
        cr.showOrHide(cr.caleTop.lq_year_id, "none");
        cr.showOrHide(cr.caleTop.sq_year_id, "block");
    };
    $(this.caleTop.lq_month_id).onclick = function() {
        cr.showOrHide(cr.caleTop.lq_month_id, "none");
        cr.showOrHide(cr.caleTop.sq_month_id, "block");
    };

    var spans = this.find(this.daysContainer_id, "span");
    for (var i = 0; i < spans.length; i ++) {
        spans[i].onmouseover = function() {
            if (this.innerHTML != "&nbsp;" && this.className == "")
                this.style.backgroundColor = "#f1f1f1";
        };
        spans[i].onmouseout = function() {
            if (spans[i].innerHTML != "&nbsp;")
                this.style.backgroundColor = "";
        };
    }
    // 移除超链接默认虚线
    var oLink = this.find(this.caleContainer_id, "a");
    for (i = 0; i < oLink.length; i ++) oLink[i].onfocus = function() {
        this.blur();
    }
};
Calendar.prototype._initCalendar = function() {
    this._bindAllEvent();
    this._bindAllData(this.Year, this.Month);
};
/* 改变快速选择年, 月的值 */
Calendar.prototype.changeSelectValue = function(year, month) {
    var ymArray = [], selectArray = [], linkArray = [];
    ymArray[0] = year;
    ymArray[1] = month + 1;
    selectArray[0] = this.caleTop.sq_year_id;
    selectArray[1] = this.caleTop.sq_month_id;
    linkArray[0] = this.caleTop.lq_year_id;
    linkArray[1] = this.caleTop.lq_month_id;
    for (var i = 0; i < selectArray.length; i ++) {
        var selectObject = $(selectArray[i]);
        var index = this._getOptionIndex(selectObject, ymArray[i]);
        // 重置年, 月下拉框的值
        selectObject.options[index].selected = "selected";
        // 重置年, 月超链接的值
        $(linkArray[i]).innerHTML = selectObject.value;
    }
    this.resetLinkSelect();
};
/* 初始化年, 月下拉框和对应超链接的值 */
Calendar.prototype.resetLinkSelect = function() {
    this.showOrHide(this.caleTop.sq_year_id, "none");
    this.showOrHide(this.caleTop.sq_month_id, "none");
    this.showOrHide(this.caleTop.lq_year_id, "block");
    this.showOrHide(this.caleTop.lq_month_id, "block");
};
/* 选择上下月 */
Calendar.prototype.goPrevOrNextMonth = function(obj) {
    var curMonthSelect = $(this.caleTop.sq_month_id);
    var curMonth = parseInt(curMonthSelect.value);
    var curYear = $(this.caleTop.sq_year_id).value;

    if (obj.id == this.caleTop.next_month_id)
        curMonthSelect.value = curMonth + 1;
    else
        curMonthSelect.value = curMonth - 1;

    var getNowMonth = curMonthSelect.value - 1;
    if (getNowMonth == -1 && curMonth == 1)     getNowMonth = 0;
    if (getNowMonth == -1 && curMonth == 12)     getNowMonth = 11;

    this._bindAllData(curYear, getNowMonth);
};
/* 选择下拉框后更新日历数据 */
Calendar.prototype.updateSelect = function() {
    var yearSelectValue = $(this.caleTop.sq_year_id).value;
    var monthSelectValue = $(this.caleTop.sq_month_id).value;
    this._bindAllData(yearSelectValue, monthSelectValue - 1);
};
/* 返回当天 */
Calendar.prototype.backToday = function() {
    this._bindAllData(this.Year, this.Month);
};
/* 根据ID 查找实例对象 */
Calendar.prototype.find = function(elemId, childTag) {
    if (!childTag)
        return $(elemId);
    else
        return  $(elemId).getElementsByTagName(childTag);
};
Calendar.prototype.css = function(obj, options) {
    if (options && typeof options == 'object') {
        for (var name in options) {
            var nameCase = name.replace(/\-(\w)/g, function($2, $1) {
                return $1.toUpperCase();
            });
            obj.style[nameCase] = options[name];
            if (Browser.Engine.trident && name == 'opacity')
                obj.style.filter = 'alpha(opacity=' + options["opacity"] * 100 + ')';
        }
    }
};
Calendar.prototype.showOrHide = function(objectId, dis) {
    return $(objectId).style.display = dis;
};

/* 方法一: 将日历插件加入实例元素中 */
Calendar.prototype.show = function(instanceId, msgData) {
    var obj = $(instanceId), cr = this;
    if (obj) {
        obj.innerHTML = this._getViewElement();
        this._initCalendar();
        // 方法一中没有关闭按钮
        this.showOrHide(this.caleTop.close_id, "none");
        if (typeof msgData == 'object') {
            this.msgStore = msgData;
            this._initPopMsg(this.msgStore);
            $(this.caleContainer_id).addEvent('mouseleave', function() {
                var hideMsgContainer = function () {
                    $(this).style.display = "none";
                };
                hideMsgContainer.delay(2000, cr.msgContainer_id);
            });
        }
    }
};

/* 初始化提示信息 */
Calendar.prototype._initPopMsg = function() {
    var cr = this;
    var selectYear = $(this.caleTop.sq_year_id).value;
    var selectm = $(this.caleTop.sq_month_id).value;
    var daysOfMonthArray = this._getMonthViewArray(selectYear, selectm);
    var spans = this.find(this.daysContainer_id, "span");
    for (var key in this.msgStore) {
        var keyMD = key.substring(4);
        var keyY = key.substring(0, 4);
        for (var i = 0; i < spans.length; i ++) {
            var d = spans[i].innerHTML;
            if (selectm.length < 2) selectm = "0" + selectm;
            if (d.length < 2) d = "0" + d;

            var getMD = selectm + "" + d;
            if (getMD == keyMD) {
                if (selectYear == keyY)
                    spans[i].className = this.tipDayClass + " " + keyY;
                else
                    spans[i].className = this.oldTipDayClass + " " + keyY;
                spans[i].onmouseover = function() {
                    var hoverDate = this.className.split(" ")[1] + "" + selectm + "" + this.innerHTML;
                    var y = this.className.split(" ")[1];
                    var d = this.innerHTML;
                    if (y) {
                        $(cr.msgContainer_id).innerHTML = cr._getMsgHtml(y, selectm, d);
                        cr.showOrHide(cr.msgContainer_id, "block");
                    }
                };
            }
        }
    }
};
/* 得到提示信息HTML 内容 */
Calendar.prototype._getMsgHtml = function(y, m, d) {
    if (m.length < 2) m = "0" + m;
    if (d.length < 2) d = "0" + d;
    var date = y + m + d;
    var showDate = y + "-" + m + "-" + d;
    return '<div>' + showDate + ':</div><div>' + this.msgStore[date] + '</div>';
};

/* 方法二: 弹出日历插件 */
Calendar.prototype.cssInit = function() {
    var cr = this;
    var sTitle = '双击显示日历';
    if (this.Language == 1) sTitle = 'double click show calendar';
    $$(cr.ptag.toLowerCase() + " " + cr.calendarCss).each(function(cbox) {

        cbox.set('title', sTitle);
        cbox.addEvent('dblclick', function(eve) {
            var event = new Event(eve);
            event.stopPropagation();
            if (!$(cr.popContainer_id)) {
                document.body.appendChild(new Element("div", {'id':cr.popContainer_id}));
            } else {
                cr.showOrHide(cr.popContainer_id, "block");
            }
            $(cr.popContainer_id).innerHTML = cr._getViewElement();
            cr._initCalendar();
            cr.popDaysClickEvent(this);
            var position = this.getPosition();
            var positionX = position.x;
            var pDiv = cbox.getParent('div');
            if (pDiv)
                positionX = position.x + pDiv.scrollLeft;

            cr.css($(cr.popContainer_id), {position: "absolute", left: positionX + "px", top: position.y + "px",'z-index':1000});
            this.focus();
            $(cr.caleTop.close_id).addEvent('click', function(eve) {
                var event = new Event(eve);
                event.stopPropagation();
                cr.showOrHide(cr.popContainer_id, "none");
                ///拖动
            });
            //拖动
            $(cr.popContainer_id).makeDraggable({
                onStart:function() {
                    this.element.setOpacity(.5);
                },
                onComplete: function() {
                    this.element.setOpacity(1);
                }
            });
        });
    });
};
/* 弹出日历插件的日期的点击事件 */
Calendar.prototype.popDaysClickEvent = function(obj) {
    var cr = this;
    var spans = cr.find(cr.daysContainer_id, "span");
    for (var i = 0; i < spans.length; i ++)
        spans[i].onclick = function(eve) {
            var event = new Event(eve);
            event.stopPropagation();
            if (this.innerHTML != "&nbsp;") {
                var getYear = cr.find(cr.caleTop.sq_year_id).value;
                var getMonth = cr.find(cr.caleTop.sq_month_id).value;
                obj.value = getYear + "-" + getMonth + "-" + this.innerHTML;
                cr.showOrHide(cr.popContainer_id, "none");
            }
        }
};
//-----------------------------------窗口
var JWindow = new Class({
    Implements: [Options, Events],
    options: {
        message: 'Message not specified.',
        url: false,
        ajaxErrorMessage: '<h3>Error 404</h3><p>The requested file could not be found.</p>',
        ajaxDelay: 800,
        top: 0,
        left: 0,
        width: 470,
        height: 'auto',
        title: 'title',
        modal:false,
        resize: true,
        move:true,
        minButton:true,
        zoomButton:true,
        maxButton:true,
        loadIcon: '/share/images/loading.gif',
        callback: null, //调用返回的函数
        windowCss: 'a.window', //调用返回的函数
        onComplete: $empty(), //当前要发送请求的时候
        onBeforeClose: $empty(),
        onBeforeHide: $empty(),
        onBeforeShow: $empty()
    },
    initialize: function(_opts) {

        this.setOptions(_opts);
        this.times = $random(0, 10000);
        var times = this.times;
        this.windowSideId = "windowSide_" + times;
        this.windowInsideId = "windowInside_" + times;
        this.windowTitlePaneId = "windowTitlePane_" + times;
        this.windowContextId = "windowContext_" + times;
        this.windowButtonPaneId = "windowButtonPaneID_" + times;
        this.winIconId = "winIconID_" + times;
        this.windowButtonPaneId = "windowButtonPane_" + times;
        this.minWindowId = "minWindow_" + times;
        this.maxWindowId = "maxWindow_" + times;
        this.zoomWindowId = "zoomWindow_" + times;
        this.closeWindowsId = "closeWindow_" + times;
		
        if (this.options.top <= 0 && this.options.left <= 0) {
			this.options.left=(screen.width-this.options.width)/2 - 10;
			this.options.top = screen.height/2-100-80; 
        }
    }
    ,
    beginLoading:function() {
        var loading = new Element("img", {'src':this.options.loadIcon,'class':'loading','border':'0'});
        $(this.windowContextId).empty();
        $(this.windowContextId).appendChild(loading);
    }
    ,
    hide:function() {
        this.fireEvent('beforeHide');
        $(this.windowSideId).setStyle('display', 'none');
    }
    ,
    show:function() {
        var win = this;
        var wincontHC = 32; //窗口 边和内容的高度差
        if ($(this.windowSideId)) {
            this.fireEvent('beforeShow');
            $(this.windowSideId).setStyle('display', '');
            return;
        }
        function saveXYWH() {
            //windowState状态  0:普通 1:最小化 2:最大化
            var windowState = windowSide.retrieve('windowState');
            if (!windowState) windowState = 0;
            if (windowState == 0) {
                windowSide.store('windowOldLeft', windowSide.getStyle('left'));
                windowSide.store('windowOldTop', windowSide.getStyle('top'));
                windowSide.store('windowOldWidth', windowSide.getStyle('width'));
                windowSide.store('windowOldHeight', windowSide.getStyle('height'));
                windowSide.setStyle('windowOldInsideHeight', windowInside.retrieve('height'));
                windowSide.store('windowOldContextHeight', windowContext.getStyle('height'));
                windowSide.store('windowOldContextWidth', windowContext.getStyle('width'));
            }
        }

        function getWindowHeight() {
            var height = windowSide.getStyle('height');
            if (height != 'auto' && height.indexOf('%') == -1)
                return height.toInt();
            var position = dragSizePane.getElement('span').getPosition();
            return (position.y - windowSide.getStyle('top').toInt() + 10);
        }

        function getMaxZindex() {
            if (!$$('.windowSide')) return 10;
            return $$('.windowSide').getStyle('z-index').max().toInt() + 1;
        }

        var windowContext = new Element('div', {'id':win.windowContextId,'class':'windowContext'});  //上下文内容
        var windowSide = new Element('div', {'id':win.windowSideId,'class':'windowSide','styles':{'z-index':10},
            'events':
            {
                'mousedown': function() {
                    this.setStyle('z-index', ( getMaxZindex() + 1));
                }
            }
        });  //最外部的层

        windowSide.setStyle("width", this.options.width);
        var windowInside = new Element('div', {'id':this.windowInsideId,'class':'windowInside'});  //最内部的层
        windowInside.setStyle("width", this.options.width - 10);
        if (this.options.height != 'auto') {
            windowInside.setStyle("height", this.options.height - 10);
            windowContext.setStyle("height", this.options.height - wincontHC);
            windowSide.setStyle("height", this.options.height);
        }

        var windowTitlePane = new Element('div', {'id':this.windowTitlePaneId,'class':'windowTitlePane'});  //标题头部
        if (this.options.zoomButton)
            windowTitlePane.ondblclick = function() {
                var windowState = windowSide.retrieve('windowState');
                if (!windowState) windowState = 0;
                //windowState状态  0:普通 1:最小化 2:最大化
                if (windowState == 2)
                    $(win.zoomWindowId).fireEvent('click');
                else
                    $(win.maxWindowId).fireEvent('click');
            };

        //按钮 begin
        //最小化窗口
        var windowButtonPane = new Element('div', {'id':this.windowButtonPaneId,'class':'windowButtonPane'});  //最内部的层
        if (this.options.minButton)
            windowButtonPane.adopt(new Element('span', {'id':this.minWindowId,'class':'minWindow',
                'events':
                {
                    'click': function() {
                        //windowState状态  0:普通 1:最小化 2:最大化
                        var windowState = windowSide.retrieve('windowState');
                        if (!windowState) windowState = 0;
                        saveXYWH();
                        windowContext.setStyle('display', 'none');
                        windowSide.setStyle('width', '120px');
                        windowSide.setStyle('height', 'auto');
                        windowInside.setStyle('width', '110px');
                        windowInside.setStyle('height', 'auto');
                        this.setStyle('display', 'none');
                        $(win.zoomWindowId).setStyle('display', '');
                        $(win.maxWindowId).setStyle('display', '');
                        windowSide.store('windowState', 1);
                    }
                }

            }), 'bottom');

        if (this.options.zoomButton)
            windowButtonPane.adopt(new Element('span', {'id':this.zoomWindowId,'class':'zoomWindow',
                'styles':{'display': 'none'},
                'events':
                {
                    'click': function() {

                        //windowState状态  0:普通 1:最小化 2:最大化
                        var windowState = windowSide.retrieve('windowState');
                        if (!windowState) windowState = 0;
                        windowSide.setStyle('left', windowSide.retrieve('windowOldLeft'));
                        windowSide.setStyle('top', windowSide.retrieve('windowOldTop'));

                        windowSide.setStyle('width', windowSide.retrieve('windowOldWidth'));
                        windowSide.setStyle('height', windowSide.retrieve('windowOldHeight'));

                        windowInside.setStyle('height', windowSide.retrieve('windowOldInsideHeight'));
                        windowInside.setStyle('width', 'auto');

                        windowContext.setStyle('height', windowSide.retrieve('windowOldContextHeight'));
                        windowContext.setStyle('width', windowSide.retrieve('windowOldContextWidth'));

                        windowContext.setStyle('display', '');
                        windowContext.setStyle('display', '');
                        this.setStyle('display', 'none');

                        windowSide.store('windowState', 0);
                        $(win.minWindowId).setStyle('display', '');
                        $(win.maxWindowId).setStyle('display', '');
                    }
                }

            }), 'bottom');  //缩放窗口

        //最大化窗口
        if (this.options.maxButton)
            windowButtonPane.adopt(new Element('span', {'id':this.maxWindowId,'class':'maxWindow',
                'events':
                {
                    'click': function() {
                        saveXYWH();
                        var page = window.document.getPosition();
                        windowSide.setStyle('width', page.x - 2 + 'px');
                        windowSide.setStyle('height', page.y - 2 + 'px');

                        windowInside.setStyle('width', 'auto');
                        windowInside.setStyle('height', (getWindowHeight() - 10));

                        windowContext.setStyle('height', (getWindowHeight() - wincontHC));
                        windowContext.setStyle('width', 'auto');

                        windowSide.setStyle('left', '0px');
                        windowSide.setStyle('top', '0px');
                        windowSide.store('windowState', 2);

                        this.setStyle('display', 'none');
                        windowContext.setStyle('display', '');
                        $(win.minWindowId).setStyle('display', '');
                        $(win.zoomWindowId).setStyle('display', '');
                    }
                }

            }), 'bottom');

        //关闭
        windowButtonPane.adopt(new Element('span', {'id':this.closeWindowsId,'class':'closeWindow',
            'events':
            {
                'click': function() {
                    win.fireEvent('beforeClose');
                    //关闭
                    windowSide.destroy();
                    if ($('blackgroundLock'))
                        $('blackgroundLock').destroy();
                }
            }

        }), 'bottom');  //关闭窗口
        //按钮 end

        windowTitlePane.adopt(windowButtonPane);
        windowTitlePane.adopt(new Element('span', {'id':this.winIconId,'class':'winIcon'}), 'bottom');  //图标
        windowTitlePane.appendText(this.options.title);
        windowInside.adopt(windowTitlePane, 'top');
        windowInside.adopt(windowContext, 'bottom');

        var dragSizePane = new Element('div', {'class':'dragSizePane'});
        var dragSizeOperate = new Element('span', {'class':'dragSizeOperate', 'events':
        {
            'mousedown': function(event) {

                //拖动影子    windowContext
                var dragDiv = new Element('div', {'id':'drag_' + this.windowContextId,'html':'&nbsp;','styles':
                {
                    'background-image':'url(/script/images/b.png)',
                    'left':windowSide.getStyle('left'),
                    'top':windowSide.getStyle('top'),
                    'width':windowSide.getStyle('width'),
                    'height':windowSide.getStyle('height'),
                    'z-index':100
                }});

                window.document.body.appendChild(dragDiv);
                var myDrag = dragDiv.makeDraggable({
                    onBeforeStart:function(element) {
                        element.setStyle('width', windowSide.getStyle('width'));
                        element.setStyle('height', getWindowHeight());
                    },
                    onStart:function() {
                        this.element.setOpacity(1);
                    },
                    onDrag : function(element) {
                        var h = element.getStyle('top').toInt() - windowSide.getStyle('top').toInt() + getWindowHeight() + 30;
                        var w = element.getStyle('left').toInt() - windowSide.getStyle('left').toInt() + windowSide.getStyle('width').toInt();
                        if (w < 120) w = 120;

                        element.setStyle('top', windowSide.getStyle('top'));
                        element.setStyle('left', windowSide.getStyle('left'));
                        element.setStyle('width', w);
                        if (h < 52) h = 52;
                        element.setStyle('height', (h - 30));


                    },
                    onComplete: function() {
                        this.element.setOpacity(0.5);
                        var w = this.element.getStyle('width').toInt();
                        var h = this.element.getStyle('height').toInt();
                        if (h < wincontHC) h = wincontHC;

                        windowSide.setStyle('width', w);
                        windowSide.setStyle('height', h);

                        windowInside.setStyle('width', w - 10);
                        windowInside.setStyle('height', h - 10);

                        windowContext.setStyle('width', w - 10);
                        windowContext.setStyle('height', h - wincontHC);
                        this.element.destroy();
                    }
                    ,
                    onCancel:function() {
                        this.element.destroy();
                    }
                });

                myDrag.start(event);
            }
        }});

        dragSizePane.adopt(dragSizeOperate, 'bottom');  //缩放窗口
        windowSide.adopt(windowInside);
        windowSide.adopt(dragSizePane, 'bottom');

        var zindex = (getMaxZindex() + 1);
        if (this.options.modal) {
            var blackgroundLock = new Element('div', {'id':'blackgroundLock','class':'blackgroundLock'});  //创建锁定背景层
            blackgroundLock.setStyle('z-index', zindex);
            window.document.body.appendChild(blackgroundLock);
            windowSide.setStyle('z-index', (zindex + 1));
            window.document.body.appendChild(windowSide);
        } else {
            window.document.body.appendChild(windowSide);
            windowSide.setStyle('z-index', zindex);
        }

        this.beginLoading();
        var iWin = $$('.windowSide').length;
        var scrollTop = document.body.scrollTop || document.documentElement.scrollTop || 0;
        windowSide.setStyle('top', (scrollTop + this.options.top + iWin * 24));
        windowSide.setStyle('left', (this.options.left + iWin * 24));
        //开启拖动
        if (this.options.move) {
            windowSide.makeDraggable({handle:windowTitlePane,
			    container:screen,
                onStart:function() {
					this.element.setOpacity(.5);
                    window.document.body.selectedIndex = 0;
                }
				,
				onComplete: function(){
					if (windowSide.getStyle('left').toInt()<0)
					{
						windowSide.setStyle('left',0);
					}
					if (windowSide.getStyle('left').toInt()+windowSide.getStyle('width').toInt()>screen.width)
					{
						windowSide.setStyle('left',screen.width-windowSide.getStyle('width').toInt()-1);
					}
					if (windowSide.getStyle('top').toInt()<0)
					{
						windowSide.setStyle('top',0);
					}

					this.element.setOpacity(1);
			    }
            });
        }
        if (!this.options.resize) {
            windowTitlePane.setStyle('cursor', 'auto');
            dragSizeOperate.setStyle('display', 'none');
            dragSizePane.setStyle('height', 5);
        }
        this.fireEvent('beforeShow');
        this.setMessage(this.options.url, this.options.message);
        new Calendar().cssInit();
    }
    ,
    setMessage:function(url, msg) {
        var win = this;
        var windowContext = $(this.windowContextId);
        if (url && (url.toLowerCase().indexOf(".png") == -1) &&
                (url.toLowerCase().indexOf(".jpg") == -1) &&
                (url.toLowerCase().indexOf(".gif") == -1)) {
            if (url.startsWith('file:')) alert('协议错误,你需要使用http协议,you need http');
            var ajax = new Request({
                url: url,
                method: 'GET',
                onComplete:this.options.onComplete,
                onSuccess: function(html) {
                    windowContext.empty();
                    windowContext.set('html', html);
                },
                onFailure: function(html) {
                    windowContext.empty();
                    windowContext.set('html', html);
                }
            });
            ajax.send();

        } else {
            windowContext.empty();
            if (msg && $type(msg) == 'element') {
                windowContext.adopt(msg);
            }
            else if (msg && $type(msg) == 'array') {
                msg.each(function(e) {
                    if ($type(e) == 'element')
                        windowContext.adopt(e);
                    else
                        windowContext.appendText(e);
                });
                if (Browser.Engine.trident) //IE 模型错位
                    windowContext.setStyle('height', windowContext.getStyle('height').toInt() + msg.length - 4);
            }
            else if (msg && (msg.toLowerCase().indexOf(".png") == -1) &&
                    (msg.toLowerCase().indexOf(".jpg") == -1) &&
                    (msg.toLowerCase().indexOf(".gif") == -1)) {
                windowContext.set('html', msg);
            } else {
                windowContext.adopt(new Element("img", {'src':msg,'border':'0'}));
            }
        }
    }
    ,
    close:function() {
        $(this.closeWindowsId).fireEvent('click');
    }
    ,
    isClose:function() {
        return !$(this.windowSideId);
    }
    ,
    cssInit:function() {
        if ($type(this.options.windowCss) == 'string')
            this.options.windowCss = $$(this.options.windowCss);
      		this.options.windowCss.each(function (e) {
            e.set('url', e.get('href'));
            e.set('href', 'javascript:void(0);');
            e.onclick = function() {
                var jwin = new JWindow({
                    title: 'URL连接页面对话框',
                    url:e.get('url')
                });
                jwin.show();
            };
        });
    }
});
//-------------------------------------------对话框
var JDialog = new Class({
    Extends: JWindow,
    options: {
        message: 'Message not specified.',
        url: false,
        ajaxErrorMessage: '<h3>Error 404</h3><p>The requested file could not be found.</p>',
        ajaxDelay: 800,
        top: 0,
        left: 0,
        width: 470,
        height: 'auto',
        title: 'title',
        modal:false,
        draggable: true,
        minButton:false,
        zoomButton:false,
        maxButton:false,
        loadIcon: '/share/images/loading.gif',

        onComplete: $empty(),
        onBeforeClose: $empty(),
        onBeforeHide: $empty(),
        onBeforeShow: $empty()

    },
    initialize: function(options) {
        this.parent(options);
    }
});
//--------------------------------------------yes no 对话框
JDialog.Confirm = new Class({
    Extends: JDialog,
    initialize: function(options) {
        options.resize = false;
        if (!options.okButtionCaption) options.okButtionCaption = '确定';
        if (!options.noButtionCaption) options.noButtionCaption = '取消';
        var win = this;
        var topPane = new Element('div', { 'class': 'jdialogButtonPane','html':'&nbsp;'});

        var buttonPane = new Element('div', { 'class': 'jdialogButtonPane'});
        buttonPane.adopt(new Element('button', { 'type':'button','html':options.okButtionCaption,'class': 'jdialog-ok-button',
            'events':
            {
                'click': function() {
                    win.options.callback(true);
                    win.close();
                }
            }
        }));

        buttonPane.adopt(new Element('button', { 'type':'button','html':options.noButtionCaption,'class': 'jdialog-no-button',
            'events':
            {
                'click': function() {
                    if (options.callback)
                        options.callback(false);
                    win.close();
                }
            }
        }));

        var infoDiv = new Element('div', {'class':'jdialogContentPane'});
        if ($type(options.message) == 'element')
            infoDiv.adopt(options.message);
        else
            infoDiv.set('html', options.message);

        var msgArray = new Array();
        msgArray.push(topPane);
        msgArray.push(infoDiv);
        msgArray.push(buttonPane);
        options.message = msgArray;
        this.parent(options);
    }
});
//-----------------------------------提示对话框返回一值  return dialog
JDialog.Prompt = new Class({
    Extends: JDialog,
    initialize: function(options) {
        if (!options.okButtionCaption) options.okButtionCaption = '确定';
        if (!options.noButtionCaption) options.noButtionCaption = '取消';
        var win = this;
        var topPane = new Element('div', { 'class': 'jdialogButtonPane','html':'&nbsp;'});
        var buttonPane = new Element('div', { 'class': 'jdialogButtonPane'});
        buttonPane.adopt(new Element('button', { 'type':'button','html':options.okButtionCaption,'class': 'jdialog-ok-button',
            'events':
            {
                'click': function() {
                    if (options.callback) {
                        options.callback($(win.windowContextId));
                    }
                    win.close();
                }
            }
        }));

        buttonPane.adopt(new Element('button', { 'type':'button','html':options.noButtionCaption,'class': 'jdialog-no-button',
            'events':
            {
                'click': function() {
                    win.close();
                }
            }
        }));

        var infoDiv = new Element('div', {'styles':{'width':'100%'}});
        if ($type(options.message) == 'element') {
            infoDiv.adopt(options.message.clone());
        }
        else {
            infoDiv.set('html', options.message);
        }
        if (!options.message) {
            infoDiv.adopt(new Element('input', {'type':'text'}));
        }
        var msgArray = new Array();
        msgArray.push(topPane);
        msgArray.push(infoDiv);
        msgArray.push(buttonPane);
        options.message = msgArray;
        this.parent(options);
    }
});
//-----------------------------------颜色话框 color dialog
JDialog.Color = new Class({
    Extends: JDialog,
    initialize: function(options) {
        options.resize = false;
        if (!options.title) options.title = '颜色对话框 Color Dialog';
        if (!options.okButtionCaption) options.okButtionCaption = '确定';
        if (!options.noButtionCaption) options.noButtionCaption = '取消';
        var win = this;
        var clr = new Array('00', '30', '60', '90', 'a0', 'c0', 'ff');
        var colorPane = new Element('div', {'class': 'jdialog_colorPane'});
        var bspan = new Element('span', {'html':'&nbsp;'});
        colorPane.adopt(bspan);

        for (var r = 0; r < 7; r++)
            for (var g = 0; g < 7; g++)
                for (var b = 0; b < 7; b++) {
                    var col = '#' + clr[6 - r] + clr[6 - g] + clr[6 - b];
                    colorPane.adopt(new Element('div',
                    {
                        'styles':
                        {
                            'background-color':col
                        },
                        'events':
                        {
                            'click': function() {
                                var cspan = colorPane.getElement("span");
                                var color = this.getStyle('background-color').toUpperCase();
                                cspan.setStyle("background-color", color);
                                cspan.set('html', color);
                                var white = new Color(color);
                                cspan.setStyle('color', white.invert());
                            }
                        }
                    }));
                }

        var buttonPane = new Element('div', { 'class': 'jdialogButtonPane'});
        buttonPane.adopt(new Element('button', { 'type':'button','html':options.okButtionCaption,'class': 'jdialog-ok-button',
            'events':
            {
                'click': function() {
                    var cspan = colorPane.getElement("span");
                    options.callback(cspan.getStyle('background-color'));
                    win.close();
                }
            }
        }));

        buttonPane.adopt(new Element('button', { 'type':'button','html':options.noButtionCaption,'class': 'jdialog-no-button',
            'events':
            {
                'click': function() {
                    win.close();
                }
            }
        }));

        var msgArray = new Array();
        msgArray.push(colorPane);
        msgArray.push(buttonPane);

        options.width = 430;
        options.message = msgArray;
        this.parent(options);
    }
});
//-----------------------------------提示对话框  alert dialog
JDialog.Alert = new Class({
    Extends: JDialog,
    initialize: function(options) {
        var win = this;
        options.resize = false;
        if (!options.title) options.title = '提示对话框 Alert Dialog';
        if (!options.okButtionCaption) options.okButtionCaption = '关闭';
        var topPane = new Element('div', { 'class': 'jdialogButtonPane','html':'&nbsp;'});
        var buttonPane = new Element('div', { 'class': 'jdialogButtonPane'});
        buttonPane.adopt(new Element('button', { 'type':'button','html':options.okButtionCaption,'class': 'jdialog-ok-button',
            'events':
            {
                'click': function() {
                    if (options.callback) options.callback(true);
                    win.close();
                }
            }
        }));

        var msgArray = new Array();
        msgArray.push(topPane);
        if (typeof(options.message) == 'string') {
            var fileName = options.message;
            var ext = fileName.toLocaleLowerCase();
            if (ext.endWith('jpg') || ext.endWith('gif') || ext.endWith('png') || ext.endWith('bmp')) {
                options.message = new Element('img', { 'src': fileName,border:0});
                var addFref = false;
                if (options.message.width > options.width) {
                    options.message.set('width', options.width - 10);
                    addFref = true;
                }
                if (options.message.height > 500) {
                    options.message.set('height', 480);
                    addFref = true;
                }
                if (addFref) {
                    var ael = new Element('a', { 'href':fileName,target:'_blank'});
                    ael.adopt(options.message);
                    options.message = ael;
                }
            }
        }
        if ($type(options.message) == 'element')
            msgArray.push(options.message);
        else
            msgArray.push(new Element('div', { 'class': 'jdialogContentPane','html':options.message}));
        msgArray.push(buttonPane);
        options.message = msgArray;
        this.parent(options);
    }
});
//-----------------------------------tab 选卡
var JTabs = new Class({
    Implements: Options,
    options: {
        buttons:false,
        buttonCss:'buttonCss',
        buttonCurrentCss:'buttonCurrentCss',
        contexts: false,
        clickAction:'mouseenter',
        highlight:'#FF9',
        current: 0
    },
    initialize: function(options) {
        this.setOptions(options);
        var tab = this;
        if ($type(this.options.buttons) == 'string')
            this.options.buttons = $$(this.options.buttons);
        if ($type(this.options.contexts) == 'string')
            this.options.contexts = $$(this.options.contexts);
        this.options.buttons.each(function(button, index) {
            button.store('tabIndex', index);
            //事件绑定
            button.addEvent(tab.options.clickAction, function() {
                tab.options.current = button.retrieve('tabIndex');
                tab.options.buttons.each(function(bt, actionIndex) {
                    if (tab.options.current == actionIndex) {
                        var cont = tab.options.contexts[actionIndex];
                        cont.highlight(tab.options.highlight);
                        cont.setStyle('display', '');
                        bt.set('class', tab.options.buttonCurrentCss);
                    } else {
                        tab.options.contexts[actionIndex].setStyle('display', 'none');
                        bt.set('class', tab.options.buttonCss);
                    }
                });
            });
        });
        this.setCurrent(tab.options.current);
    },
    setCurrent:function(current) {
        var button = this.options.buttons[current];
        if ($type(button) == 'element')
            button.fireEvent(this.options.clickAction);
    }
    ,
    getCurrent:function() {
        return this.options.current;
    }
});
//-----------------------------------树结构 tree
//var treeNode = {id:'节点ID',iocn:'图标',openIcon:'打开图标',inputType:'checkbox',inputCss:'treeInput',text:'节点描述',action:'动作',pid:'root'};

var JTree = new Class({
    Implements: [Options, Events],
    options: {
        url: false,
        paneId:'JTree',
        prefix:'JTree',
        rootId:'root', //更节点ID
        varName:'treeNode',
        multiselect:false, //是否多选
        loadJson:false,
        loadXml:false,
        edit:false, //默认模式
        editMode:false, //对于只显示不允许编辑的可以设置为false
        ajaxDelay: 800,
        inputType:false,
        useLimb:false, //输入框不使用枝节点
        buttonHide:true, //叶子节点隐藏展开按钮
        defaultOpenIcon:'images/tree/openfolder.png',  //打开节点图标
        defaultIcon:'images/tree/folder.png',  //打开节点图标
        nodeHideIcon:'images/elbow-plus.gif',  //隐藏图标
        nodeExpandIcon:'images/elbow-minus.gif',  //展开图标
        operateIcon:'images/dialog-operate.gif',
        operate2Icon:'images/dialog-operate2.gif',

        path:'',
        defaultInputCss:'treeNodeInput',
        treeNodeControlPaneCss:'treeNodeControlPane',
        treeNodeWrapButtonCss:'treeNodeWrapButton',

        addButtonCaption:'添加子分类',
        addButtonCss:'treeNodeAddButton',

        upButtonCaption:'',
        upButtonCss:'treeNodeUpButton',

        downButtonCaption:'',
        downButtonCss:'treeNodeDownButton',

        deleteButtonCaption:'',
        deleteButtonCss:'treeNodeDeleteButton',

        editButtonCaption:'编辑详细',
        editButtonCss:'treeNodeEidtButton',

        draggable: true, //是否运行拖动

        onDeleteBefore: $empty(),

        onDblclickNode: $empty(), //双击节点
        onClickNode: $empty(), //点击节点
        onSelectChange: $empty(), //勾选改变
        onClickEditButton: $empty(), //点击节点
        onNodeExpand: $empty(), //节点展开事件
        onNodeHide: $empty(), //节点收缩隐藏
        onShowAfter: $empty() //显示树之后
    },
    initialize: function(_opts) {
        this.setOptions(_opts);
        this.options.defaultOpenIcon = this.options.path + this.options.defaultOpenIcon;
        this.options.defaultIcon = this.options.path + this.options.defaultIcon;
        this.options.nodeHideIcon = this.options.path + this.options.nodeHideIcon;
        this.options.nodeExpandIcon = this.options.path + this.options.nodeExpandIcon;
        this.options.operateIcon = this.options.path + this.options.operateIcon;
        this.options.operate2Icon = this.options.path + this.options.operate2Icon;
        this.options.treeStatus = new Hash.Cookie('treeStatus' + this.options.paneId, {autoSave: true});

        if (this.options.loadJson) this.loadJson();
        else if (this.options.loadXml) this.loadXml();
        else if (this.options.url) this.loadURL(this.options.url);
    }
    ,
    show:function() {
        var domRoot = this.getDomRootNode();
        this.refreshButton(domRoot, true);
        this.upButtonEnable(domRoot, false);
        this.downButtonEnable(domRoot, false);
        this.deleteButtonEnable(domRoot, false);
        this.fireEvent('showAfter', domRoot);
        var tree = this;
        if (!this.options.edit) {
            this.viewMode();
            this.options.treeStatus.load();
            this.options.treeStatus.each(function(key, nodeId) {
                var node = $(nodeId);
                if (node) {
                    tree.expandOrCollapse(node.getElement('button'), key);
                }
            });
        }
    }
    ,
    deleteChildNodes:function(nodeId) {
        //删除节点
        var node = nodeId;
        if ($type(node) == 'string')
            node = $(node);
        if (node) {
            var child = node.getElement('ul');
            if (child)
                child.empty();
        }
    }
    ,
    getDomRootNode:function() {
        if ($type(this.options.rootId) == 'string')
            return  $(this.options.prefix + '_' + this.options.rootId);
        return this.options.rootId;
    }
    ,
    getRootNode:function() {
        var nodes = this.options.loadJson;
        for (var i = 0; i < nodes.length; i++)
            if (nodes[i].id == this.options.rootId) return nodes[i];
        return null;
    }
    ,
    showRoot:function() {
        var domRoot = this.getDomRootNode();
        if (domRoot)
            domRoot.getElement('.treeLiDiv').setStyle('display', '');
    }
    ,
    hideRoot:function() {
        var domRoot = this.getDomRootNode();
        if (domRoot) {
            domRoot.getElement('.treeLiDiv').setStyle('display', 'none');
            domRoot.getElement('ul').setStyle('padding', 0);
        }
    }
    ,
    editMode:function() {
        var tree = this;
        var domRoot = this.getDomRootNode();
        domRoot.getElements('div.' + this.options.treeNodeControlPaneCss).setStyle('display', '');
        var inputs = domRoot.getElements('span');
        inputs.each(function(inputbox) {
            new Element('input', {'type':'text','name':tree.options.varName,'class':'editCaption','value':inputbox.get("html")}).replaces(inputbox);
        });
        this.options.edit = true;
    }
    ,
    viewMode:function() {
        var tree = this;
        var domRoot = this.getDomRootNode();
        if (!domRoot) alert('不能得到 root 节点');
        domRoot.getElements('div.' + this.options.treeNodeControlPaneCss).setStyle('display', 'none');
        var inputs = domRoot.getElements('input.editCaption');
        inputs.each(function(inputbox) {
            var valueEl = new Element('span', {'html':  inputbox.get("value"),
                'events':
                {
                    'click':function() {
                        if (!tree.options.multiselect)
						{
                            domRoot.getElements('span').removeClass('seleced');
						}
                        tree.clickCaption(this);
                    }
                    ,
                    'dblclick':function() {
                        tree.fireEvent('dblclickNode', this.getParent('li').id);
                    }
                }
            });
            valueEl.replaces(inputbox);
        });
        this.options.edit = false;
    }
    ,
    getChildNodes:function(nodeId) {
        var result = new Array();
        var jsonData = this.options.loadJson;
        for (var i = 0; i < jsonData.length; i++) {
            if (jsonData[i].pid == nodeId)
                result.push(jsonData[i]);
        }
        if (result.length > 0)
            return result;
        return null;
    }
    ,
    loadJson:function() {
        if ($type(this.options.loadJson) !== 'array') alert('数据类型错误, error tree json data');
        var startNode = this.getRootNode();
        if (startNode) {   //数据里边存在根节点,
            //节点添加递归,只用一个开始节点
            this.appendNode(startNode);
        }
        else {
            //动态添加,不会添加子节点,非递归
            var nodes = this.options.loadJson;
            for (var i = 0; i < nodes.length; i++) {
                this.addNode(nodes[i].pid, this.createNode(nodes[i]));
            }
        }
        //if (!startNode) alert('没有找到起始节点, not found start node');
        this.show();
    }
    ,
    loadURL:function(url, varName) {
        var tree = this;
        if (!url) url = tree.options.url;
        //接收url方式和数组方式
        new Request.JSON({
            url: url,
            method:'GET', //必须
            secure:false,
            onComplete: function(nodes) {
                if (varName) {
                    if (typeof( nodes[varName]) == "string")
                        nodes = JSON.decode(nodes[varName]);
                }
                tree.options.loadJson = nodes;
                tree.loadJson();
            }
        }).send();
    }
    ,
    appendNode:function(node) {
        this.addNode(node.pid, this.createNode(node));
        var childs = this.getChildNodes(node.id);
        if (childs)
            for (var i = 0; i < childs.length; i++) {
                this.appendNode(childs[i]);
            }
    }
    ,
    loadXml:function(xmlDate) {
        var dom = loadXML(xmlDate);
        var result = new Array();
        var children = false;
        if ('tree' == dom.childNodes[0].nodeName)
            children = dom.childNodes[0].childNodes;
        else children = dom.childNodes;
        for (var i = 0; i < children.length; i++) {
            if ('node' == children[i].nodeName.toLowerCase()) {
                var node = new Object();
                node.id = children[i].getAttribute('id');
                node.text = children[i].getAttribute('text');
                node.iocn = children[i].getAttribute('iocn');
                node.openIcon = children[i].getAttribute('openIcon');
                node.pid = children[i].getAttribute('pid');
                node.action = children[i].getAttribute('action');
                node.checked = children[i].getAttribute('checked');
                node.value = children[i].getAttribute('value');
                result.push(node);
            }
        }
        this.options.loadJson = result;
        this.loadJson();
    }
    ,
    getSelected:function() {
        if (this.options.edit) {
            alert('不能在编辑模式下,not edit mode');
            return '';
        }
        var nodeSpan = this.getDomRootNode().getElement('span.seleced');
        if (nodeSpan) {
            nodeSpan = nodeSpan.getParent('li');
            if (nodeSpan) return nodeSpan.id;
        }
        return '';
    }
    ,
    clickCaption:function(nodeSpan) {
        if (nodeSpan) {
            if (nodeSpan.hasClass('seleced'))
                nodeSpan.removeClass('seleced');
            else
                nodeSpan.addClass('seleced');
            this.fireEvent('clickNode', nodeSpan.getParent('li').id);
        }
    }
    ,
    expandOrCollapse:function(tnode, status) {
        //展开
        if (!tnode) return false;
        var tree = this;
        var node = tnode.getParent('li');
        //展开，关闭
        var clickNode = tnode.getParent().getParent().getLast();
        var clickNodeStyle = clickNode.getStyle('display');
        if (clickNode.get('tag').toLowerCase() == 'ul')//如果最后一个元素是ul
        {
            var img = node.getElement('img');
            if ((!status || status == 0) && clickNodeStyle == 'block') {
                tnode.setStyle('background', 'url(' + tree.options.nodeHideIcon + ')');
                clickNode.setStyle('display', 'none');
                img.set('src', img.get('icon'));
                this.options.treeStatus.set(node.id, 0);
                tree.fireEvent('nodeHide', node.id);

            } else
            if (!status || status == 1) {
                tnode.setStyle('background', 'url(' + tree.options.nodeExpandIcon + ')');
                clickNode.setStyle('display', 'block');
                img.set('src', img.get('openIcon'));
                this.options.treeStatus.set(node.id, 1);
                tree.fireEvent('nodeExpand', node.id);
            }
        }
    }
    ,
    collapseAll:function() {
        //收缩节点
        var tree = this;
        var root = this.getDomRootNode();
        var uls = root.getElements('ul');
        var frootid = tree.options.prefix + '_' + tree.options.rootId;
        uls.each(function(ul) {
            var tnode = ul.getParent("li");
            if (frootid != tnode.get('id')) {
                var clickNode = tnode.getLast();
                var img = tnode.getElement('img');
                tnode.getElement('button').setStyle('background', 'url(' + tree.options.nodeHideIcon + ')');
                clickNode.setStyle('display', 'none');
                img.set('src', img.get('icon'));
                tree.options.treeStatus.set(tnode.id, 0);
            }
        });
    }
    ,
    expandAll:function() {
        //展开
        var tree = this;
        var root = this.getDomRootNode();
        var uls = root.getElements('ul');
        var frootid = tree.options.prefix + '_' + tree.options.rootId;
        uls.each(function(ul) {
            var tnode = ul.getParent("li");
            if (frootid != tnode.get('id')) {
                var clickNode = tnode.getLast();
                var img = tnode.getElement('img');
                tnode.getElement('button').setStyle('background', 'url(' + tree.options.nodeExpandIcon + ')');
                clickNode.setStyle('display', 'block');
                img.set('src', img.get('openIcon'));
                tree.options.treeStatus.set(tnode.id, 1);
            }
        });
    }
    ,
    isLimb:function(nodeId) {

        //判断是否为枝节点
        var nodes = this.options.loadJson;
        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].pid == nodeId) return true;
        }
        return false;
    }
    ,
    createNode:function(node) {
        if (!node.inputCss) node.inputCss = this.options.defaultInputCss;
        var tree = this;
        var treeLiNode = new Element('li', {'class':'treeLiNode','id':this.options.prefix + '_' + node.id});  //LI
        var treeLiDiv = new Element('div', {'class':'treeLiDiv'});
        treeLiNode.adopt(treeLiDiv);
        var cbutton = new Element('button', {'class': this.options.treeNodeWrapButtonCss,
            'events':
            {
                'click': function() {
                    tree.expandOrCollapse(this);
                    return false;
                }
            }
        });
        treeLiDiv.adopt(cbutton); //展开按钮
        if (node.value == undefined) node.value = "";
        //输入框
        var inputEl = null;
        if (this.options.inputType)
            inputEl = new Element('input', {'type':this.options.inputType,'class':this.options.defaultInputCss,'name':this.options.varName,'value':node.id});
        else
        if (node.inputType)
            inputEl = new Element('input', {'type':node.inputType,'class':node.inputCss,'name':this.options.varName,'value':node.id}); //输入框

        if (inputEl && node.checked) inputEl.set("checked", "checked");
        if (inputEl)
			if (inputEl.get("type") == "text")
				inputEl.set("value", node.value);
		    else
			{
				inputEl.addEvent('click', function() {
					 if (this.getProperty('checked'))
					 {
						tree.fireEvent('selectChange', node);	
					 }
				});
			}
	
        if (!this.options.useLimb) {
            if (!this.isLimb(node.id)) {
                if (this.options.buttonHide) {
                    cbutton.setStyle('display', 'none');
                }
                treeLiDiv.adopt(inputEl);
            }
        } else {
            treeLiDiv.adopt(inputEl);
        }

        if (node.iocn && node.openIcon)
            treeLiDiv.adopt(new Element('img', {'src':node.openIcon,'icon':node.icon,'openIcon':node.openIcon,'border':0})); //图标
        else
            treeLiDiv.adopt(new Element('img', {'src':this.options.defaultOpenIcon,'icon':this.options.defaultIcon,'openIcon':this.options.defaultOpenIcon,'border':0})); //图标

        if (!this.options.editMode) {
            treeLiDiv.adopt(new Element('span', {'html':node.text,
                'events':
                {
                    'click':function() {
                        if (!tree.options.multiselect)
                            tree.getDomRootNode().getElements('span').removeClass('seleced');
                        tree.clickCaption(this);
                        return false;
                    }
                    ,
                    'dblclick':function() {
                        tree.fireEvent('dblclickNode', this.getParent('li').id);
                        return false;
                    }
                }
            })); //caption
            //
        } else {
            treeLiDiv.adopt(new Element('input', {'type':'text','class':'editCaption','value':node.text})); // edit caption box
            var treeNodeControlPane = new Element('div', {'class':this.options.treeNodeControlPaneCss});
            //添加
            treeNodeControlPane.adopt(new Element('button', {'class':this.options.addButtonCss,'html':this.options.addButtonCaption,
                'events':
                {
                    'click':function() {
                        var allLi = tree.getDomRootNode().getElements("li");
                        var node = this.getParent('li');
                        //if (!node) return;
                        var nid = tree.options.prefix + (allLi.length + 1);
                        var newNode = {id:nid,iocn:'',openIcon:'',inputType:'',inputCss:'',text:'',action:'',pid:node.id};
                        tree.addNode(node.id, tree.createNode(newNode));
                    }
                }
            }));

            //li移动
            var treeNodemove = function() {
                //得到节点li--------------前面有这个变量了
                var thisNode = this.getParent('li');
                if (this.get('class') == tree.options.downButtonCss) {
                    var nextNode = thisNode.getNext();
                    if (nextNode) {
                        //向下
                        thisNode.inject(nextNode, 'after');
                    }
                }
                else {
                    var PreviousNode = thisNode.getPrevious(); //得到这个节点
                    if (PreviousNode) {
                        //向上
                        thisNode.inject(PreviousNode, 'before');
                    }
                }
                //-------------判断按钮
                var checkNode = thisNode.getParent('li');
                if (!checkNode)
                    checkNode = $(this.options.prefix + '_' + this.options.rootId);
                tree.refreshButton(checkNode, false);
            };
            treeNodeControlPane.adopt(new Element('button', {'class':this.options.upButtonCss,'html':this.options.upButtonCaption,
                'events':
                {
                    'click':treeNodemove
                }
            })); //上移
            treeNodeControlPane.adopt(new Element('button', {'class':this.options.downButtonCss,'html':this.options.downButtonCaption,
                'events':
                {
                    'click':treeNodemove
                }

            })); //下移

            treeNodeControlPane.adopt(new Element('button', {'class':this.options.deleteButtonCss,'html':this.options.deleteButtonCaption,
                'events':
                {
                    'click':function() {
                        //删除咨询
                        var node = this.getParent('li');
                        if (node) {
                            if (tree.options.deleteBefore) {
                                if (tree.options.deleteBefore(node.id)) {
                                    node.destroy();
                                }
                            } else  node.destroy();

                        }
                    }
                }
            })); //删除
            treeNodeControlPane.adopt(new Element('button', {'class':this.options.editButtonCss,'html':this.options.editButtonCaption,
                'events':
                {
                    'click':function() {
                        tree.fireEvent('clickEditButton', node.id);
                    }
                }
            })); //编辑详细

            treeLiDiv.adopt(treeNodeControlPane);
        }
        treeLiNode.adopt(new Element('ul', {'class':'treeNodes'})); //子节点位置
        return treeLiNode;
    }
    ,
    addNode:function(pId, nodeEL) {
        if (!pId || pId == '')
            $(this.options.paneId).adopt(nodeEL);
        else {
            var prefix = this.options.prefix;
            var liId = pId;
            if (!liId.startsWith(prefix + '_'))
                liId = prefix + '_' + pId;
            var pEL = $(liId);
            if (pEL) {
                pEL.getElement('ul').adopt(nodeEL);
            }
        }
    }
    ,
    deleteButtonEnable:function(liNode, disabled) {
        if (!liNode) return;
        var btnDel = liNode.getElement('button.treeNodeDeleteButton');
        if (!btnDel) return;
        if (disabled) {
            btnDel.setStyles({

                background:'url(' + this.options.operateIcon + ') 0 0px',
                cursor:'pointer'
            });
            btnDel.removeProperty('disabled');
        } else {
            //如果成立(即btnUp在第一行li中),设置这个btnUp样式为禁止
            btnDel.setStyles({
                background:'url(' + this.options.operate2Icon + ') 0 0px',
                cursor:'not-allowed'
            });
            btnDel.set('disabled', 'disabled');
        }
    }
    ,
    upButtonEnable:function(liNode, disabled) {
        if (!liNode) return;
        var btnUp = liNode.getElement('button.treeNodeUpButton');
        if (!btnUp) return;
        if (disabled) {
            //如果成立(即btnUp在第一行li中),设置这个btnUp样式为禁止
            btnUp.setStyles({
                background:'url(' + this.options.operateIcon + ') 0 -34px',
                cursor:'pointer'
            });
            btnUp.removeProperty('disabled');
        } else {
            //如果成立(即btnUp在第一行li中),设置这个btnUp样式为禁止
            btnUp.setStyles({
                background:'url(' + this.options.operate2Icon + ') 0 -34px',
                cursor:'not-allowed'
            });
            btnUp.set('disabled', 'disabled');
        }
    }
    ,
    downButtonEnable:function(liNode, disabled) {
        if (!liNode) return;
        var btnDown = liNode.getElement('button.treeNodeDownButton');
        if (!btnDown) return;
        if (disabled) {
            //如果成立(即btnUp在第一行li中),设置这个btnUp样式为禁止
            btnDown.setStyles({
                background:'url(' + this.options.operateIcon + ') 0 -17px',
                cursor:'pointer'
            });
            btnDown.removeProperty('disabled');
        } else {
            //如果成立(即btnUp在第一行li中),设置这个btnUp样式为禁止
            btnDown.setStyles({
                background:'url(' + this.options.operate2Icon + ') 0 -17px',
                cursor:'not-allowed'
            });
            btnDown.set('disabled', 'disabled');
        }
    }
    ,
    getDomChildren:function(liNode) {
        //得到 liNode 节点下的所有兄弟节点
        if (!liNode) return false;
        var ul = liNode.getElement('ul');
        return ul.childNodes;
    }
    ,
    getDomXml:function() {
        return '<tree>\r\n' + this.getNodesXml(this.getDomRootNode(), 1) + '</tree>';
    }
    ,
    getNodesXml:function(liNode, sort) {
        var result = '';
        var node = '<node id="' + liNode.id.substring(this.options.prefix.length + 1) + '" ';
        if (this.options.edit)
            node = node + 'text="' + liNode.getElement('input.editCaption').get('value').xmlEscape() + '" ';
        else
            node = node + 'text="' + liNode.getElement('span').get('html').xmlEscape() + '" ';

        node = node + 'icon="' + liNode.getElement('img').get('icon') + '" ';
        node = node + 'openIcon="' + liNode.getElement('img').get('openIcon') + '" ';
        node = node + 'sort="' + sort + '" ';

        if (liNode.getParent('li'))
            node = node + 'pid="' + liNode.getParent('li').id.substring(this.options.prefix.length + 1) + '" ';
        else node = node + 'pid="" ';
        node = node + "/>\r\n";
        result = result + node;

        var childs = this.getDomChildren(liNode);
        if (childs && childs.length > 0) {
            for (var i = 0; i < childs.length; i++)
                result = result + this.getNodesXml(childs[i], i + 1);
        }
        return result;
    }
    ,
    getDomJosn:function() {
        return JSON.encode(this.getNodesJosn(this.getDomRootNode()));
    }
    ,
    getNodesJosn:function(liNode) {
        var result = new Array();
        var node = new Object();
        node.id = liNode.id.substring(this.options.prefix.length + 1);
        if (this.options.edit)
            node.text = liNode.getElement('input.editCaption').get('value');
        else
            node.text = liNode.getElement('span').get('html');
        node.iocn = liNode.getElement('img').get('icon');
        node.openIcon = liNode.getElement('img').get('openIcon');
        if (liNode.getParent('li'))
            node.pid = liNode.getParent('li').id.substring(this.options.prefix.length + 1);
        else node.pid = '';
        result.push(node);
        var childs = this.getDomChildren(liNode);
        if (childs)
            for (var i = 0; i < childs.length; i++)
                result.push(this.getNodesJosn($(childs[i].id)));
        return result;
    }
    ,
    refreshButton: function(liNode, inChild) {
        //从liNode 节点开始向下遍历
        if (!liNode) return false;
        var startNode = liNode.getElement('ul');
        var children = startNode.childNodes;
        for (var i = 0; i < children.length; i++) {
            if (children[i].get('tag').toLowerCase() != 'li') break;
            //子节点begin
            if (inChild) {
                var childs = this.getDomChildren(children[i]);
                if (childs) {
                    this.refreshButton(children[i], inChild);
                }
            }
            //子节点end
            if (children.length == 1) {
                this.upButtonEnable(children[i], false);
                this.downButtonEnable(children[i], false);
                break;
            }
            if (i == 0) {
                this.upButtonEnable(children[i], false);
                if (children.length > 1)
                    this.downButtonEnable(children[i], true);
                else
                    this.downButtonEnable(children[i], false);
                continue;
            }
            if (children.length - 1 == i) {
                this.downButtonEnable(children[i], false);
                if (children.length > 1)
                    this.upButtonEnable(children[i], true);
                else
                    this.upButtonEnable(children[i], false);
                continue;
            }
            this.upButtonEnable(children[i], true);
            this.downButtonEnable(children[i], true);
        }
    }
});
//--------------------------进度条
var JProgressBar = new Class({
    Implements: [Events, Options],
    options: {
        container: $(document.body),
        width:0,
        startPercentage: 0,
        displayText: false,
        speed:10,
        step:1,
        allowMore: false
    },

    initialize: function(options) {
        this.times = $random(0, 10000);
        options.boxID = 'progressBarBg_' + this.times;
        options.percentageID = 'progressBarPoint_' + this.times;
        options.displayID = 'progressBarDisplay_' + this.times;

        this.setOptions(options);

        var box = new Element('div', {'id':this.options.boxID,'class':'progressBarBg'});
        if (this.options.width > 0)
            box.setStyle('width', this.options.width);
        else box.setStyle('width', this.options.container.getStyle('width'));

        var perc = new Element('div', {'id':this.options.percentageID,'class':'progressBarPoint'});
        perc.inject(box);
        box.inject(this.options.container);

        if (this.options.displayText) {
            var text = new Element('div', {'id':this.options.displayID,'class':'progressBarText'});
            perc.adopt(text);
        }
        this.set(this.options.startPercentage);
    },

    //计算得到百分比
    calculate: function(percentage) {
        return ($(this.options.boxID).getStyle('width').toInt() * (percentage / 100)).toInt();
    },

    //动画动作
    animate: function(go) {
        if (!this.options.allowMore && go > 100)     go = 100;
        this.to = go.toInt();
        $(this.options.percentageID).set('morph', {'duration': this.options.speed,'link':'cancel',onComplete: this.fireEvent(go == 100 ? 'complete' : 'change', [go], this.options.speed)
        }).morph({
                     width:this.calculate(go)
                 });
        if (this.options.displayText) {
            $(this.options.displayID).set('text', this.to + '%');
        }
    },
    //设置到指定位置
    set: function(to) {
        this.animate(to);
    },
    //按照步长增长
    step: function() {
        this.set(this.to + this.options.step);
    }
});
//--------------------------图片滚动显示
var JChangeIMG = new Class({
    Implements: [Events, Options],
    options: {
        container: $('changeIMGDiv'), //div容器
        data:[], //数据数组,格式 {title:'text',img:'*.jpg',link:'*.html'}
        target:'_blank',
        width: 0,
        height:0,
        sleep:1500,
        showTitle:true,
        onChange: $empty() //参数 是索引
    },

    initialize: function(options) {
        this.setOptions(options);
        if (this.options.width < 1) {
            this.options.width = this.options.container.getStyle('width').toInt();
        }
        if (this.options.height < 1) {
            this.options.height = this.options.container.getStyle('height').toInt();
        }
        var cimg = this;
        this.imgDiv = new Element('div', {'class':'changeImgs'});
        this.aImg = new Element('a', {'target':this.options.target});
        this.aImg.setStyle('width', this.options.width);
        this.aImg.setStyle('height', this.options.height);

        this.titleDiv = new Element('div', {'class':'changeImgTitle','html':'...'});
        this.titleDiv.setStyle('width', this.options.width);
        this.ImgPic = new Element('img', {'border':'0', 'src':this.options.data[0].img,
            'events':
            {
                'mouseover':function() {
                    cimg.stop = true;
                }
                ,
                'mouseout':function() {
                    cimg.stop = false;
                }
            }
        });
        this.ImgPic.setStyle('width', this.options.width);
        this.ImgPic.setStyle('height', this.options.height);

        if (this.options.showTitle) this.aImg.adopt(this.titleDiv);
        this.aImg.adopt(this.ImgPic);
        this.imgDiv.adopt(this.aImg);
        this.options.container.adopt(this.imgDiv);
        this.linksDiv = new Element('div', {'class':'changeImgButtons'});
        this.linksDiv.setStyle('width', this.options.width);

        this.options.data.each(function(da, index) {
            cimg.linksDiv.adopt(new Element('a', {'href':da.link, 'html':index + 1,
                'events':
                {
                    'mouseover':function() {
                        cimg.times = index;
                        cimg.changeImg();
                        cimg.stop = true;
                    }
                    ,
                    'mouseout':function() {
                        cimg.stop = false;
                    }
                }
            }));
        });
        this.options.container.adopt(this.linksDiv, 'bottom');
        this.times = 0;
        cimg.stop = false;
        this.isFade = false;
        this.changeImg.periodical(this.options.sleep, this);

    },
    //定时部分
    changeImg: function() {
        if (this.stop) return;
        if (!this.isFade) {
            this.ImgPic.fade(0.1);
            this.isFade = true;
        }
        var aArray = this.linksDiv.getElements('a');
        if (this.times >= aArray.length) this.times = 0;
		var t=this.times;
        aArray.each(function(e,i){
			if (e.hasClass('active')) e.removeClass('active');
			if (i==t) 
			{
				e.addClass('active');
				e.set('html',i+1);//兼容IE
			}
		});
        this.titleDiv.set('html', this.options.data[t].title);
        this.aImg.set('href', this.options.data[t].link);
        this.ImgPic.set('src', this.options.data[t].img);
        this.fireEvent('change', this.options.data[t]);
        this.fadeEnd.delay(300, this);
        this.times++;
    }
    ,
    fadeEnd:function() {
        this.ImgPic.fade(1);
        this.isFade = false;
    }
});
//--------------------------相册
var JPhotoAlbum = new Class({
    Implements: [Events, Options],
    options: {
        container: $('albumIMGDiv'), //div容器
        data:[], //数据数组,格式 {title:'text',img:'*.jpg'}
        target:'_blank',
        mousePause:true,
        autoPlay:true,
        startStep:0, //位置
        knobCss:'blueKnob',
        width: 0,
        height:0,
        thumbWidth:120,
        thumbHeight:60,
        sleep:2000,
        showTitle:true,
        link:'',
        onChange: $empty() //参数 是索�?
    },

    initialize: function(options) {
        this.setOptions(options);
        var cimg = this;
        this.imgDiv = new Element('div', {'class':'albumImgs'});
        this.aImg = new Element('a', {'target':this.options.target});

        this.titleDiv = new Element('div', {'class':'albumImgTitle','html':'loading...'});
        this.titleDiv.setStyle('display', 'none');

        this.ImgPic = new Element('img', {'border':'0', 'src':this.options.data[0].img});
        this.stop = this.options.autoPlay;
        this.tempstat = this.options.autoPlay;


        //标题显示
        this.ImgPic.addEvent('mouseover', function() {
            cimg.titleDiv.setStyle('display', '');
            if (cimg.options.mousePause) {
                cimg.tempstat = $chk(cimg.timeClock);
                cimg.pause();
            }
        });

        this.ImgPic.addEvent('mouseout', function() {
            cimg.titleDiv.setStyle('display', 'none');
            if (cimg.options.mousePause && cimg.tempstat)
                cimg.play();
        });

        //缩放大小
        this.ImgPic.addEvent('load', function() {
            var bl = 1;
            if (cimg.options.width > 0) {
                bl = cimg.options.width / this.width;
                this.width = this.width * bl;
                cimg.titleDiv.setStyle('width', this.width);
                if (cimg.options.height > 0)
                    this.height = this.height * bl;
            }
            else {
                this.width = cimg.options.width;
                cimg.titleDiv.width = this.width;
                this.height = cimg.options.height;
            }
        });

        if (this.options.showTitle)
            this.aImg.adopt(this.titleDiv, 'top');

        this.aImg.adopt(this.ImgPic);
        this.imgDiv.adopt(this.aImg);
        this.options.container.adopt(this.imgDiv);
        this.linksPane = new Element('div', {'class':'albumImgButtonPane'});
        this.linksPane.setStyle('height', this.options.thumbHeight + 20);

        var sliderPaneW = (this.options.thumbWidth + 4) * this.options.data.length;
        this.linksPane.setStyle('width', this.options.width);

        this.linksDiv = new Element('div', {'class':'albumImgButtons'});
        this.linksDiv.setStyle('width', sliderPaneW);

        this.options.data.each(function(da, index) {
            cimg.linksDiv.adopt(
                    new Element('img', {'src':da.img,'title':da.title,
                        'styles':
                        {
                            'width':cimg.options.thumbWidth,
                            'height':cimg.options.thumbHeight
                        }
                        ,
                        'events':
                        {
                            'click':function() {
                                cimg.Slider.set(index);
                            }
                        }
                    }));
        });

        this.linksPane.adopt(this.linksDiv);
        this.options.container.adopt(this.linksPane, 'bottom');
        //滚动条begin
        var sliderDiv = new Element('div', {'class':'dotSlider'});
        sliderDiv.setStyle('width', this.options.width);

        var knob = new Element('div', {'class':this.options.knobCss});
        sliderDiv.adopt(knob);
        this.linksPane.adopt(sliderDiv, 'bottom');
        //滚动条end
        var sliderW = this.linksPane.getStyle('width').toInt();
        this.fullw = cimg.ImgPic.getParent('div').getStyle('width').toInt() - 2;
        this.titleDiv.setStyle('width', this.fullw);
        this.Slider = new Slider(sliderDiv, knob, {
            sliderSteps:sliderPaneW,
            range:[0,cimg.options.data.length],
            steps: 1,
            wheel: true,
            onComplete: function(step) {
                cimg.set(step);
            }
            ,
            onTick: function(pos) {
                cimg.linksPane.scrollLeft = pos * (sliderPaneW / sliderW);
                sliderDiv.setStyle('left', cimg.linksPane.scrollLeft);
                this.knob.setStyle('left', pos);

                var step = (sliderPaneW / cimg.fullw) * pos;
                step = (step / 100).toInt();
                if (step < 0) step = 0;
                if (step > cimg.options.data.length) step = cimg.options.data.length;
            }

        }).set(this.options.startStep);

        //定时函数
        if (!this.timeClock)
            this.timeClock = this.timer.periodical(this.options.sleep, this);

    },
    timer:function () {
        this.Slider.step = this.Slider.step + 1;
        if (this.options.data.length == this.Slider.step + 1) this.Slider.step = 0;
        this.Slider.set(this.Slider.step);
        this.fireEvent('change', this.options.data[this.Slider.step]);
    }
    ,
    play:function() {
        if (!this.timeClock)
            this.timeClock = this.timer.periodical(this.options.sleep, this);
    },
    pause:function() {
        if (this.timeClock)
            $clear(this.timeClock);
        this.timeClock = false;
    }
    ,
    next:function() {
        this.Slider.step = this.Slider.step + 1;
        if (this.options.data.length == this.Slider.step) this.Slider.step = 0;
        this.Slider.set(this.Slider.step);
    }
    ,
    previous:function() {
        this.Slider.step = this.Slider.step - 1;
        if (this.Slider.step < 0) this.Slider.step = this.options.data.length - 1;
        this.Slider.set(this.Slider.step);
    }
    ,
    set:function(step) {
        var aArray = this.linksDiv.getElements('img');
        aArray.removeClass('active');
        if (aArray[step])
            aArray[step].addClass('active');
        if (this.options.data[step]) {
            this.titleDiv.set('html', this.options.data[step].title);
            if (this.options.link && this.options.link != '')
                this.aImg.set('href', this.options.link);
            else
            if (this.options.data[step].link)
                this.aImg.set('href', this.options.data[step].link);
            else this.aImg.set('href', 'javascript:void(0);');
            this.ImgPic.set('src', this.options.data[step].img);
        }
    }
});

/*-------------------tagsBox */
var TagboxList = new Class({
    Implements: [Options, Events],
    plugins: [],
    options: {/*
     onFocus: $empty,
     onBlur: $empty,
     onBitFocus: $empty,
     onBitBlur: $empty,
     onBitAdd: $empty,
     onBitRemove: $empty,
     onBitBoxFocus: $empty,
     onBitBoxBlur: $empty,
     onBitBoxAdd: $empty,
     onBitBoxRemove: $empty,
     onBitEditableFocus: $empty,
     onBitEditableBlue: $empty,
     onBitEditableAdd: $empty,
     onBitEditableRemove: $empty,*/
        prefix: 'tagboxList',
        split:' ',
        max: null,
        unique: false,
        uniqueInsensitive: true,
        endEditableBit: true,
        startEditableBit: true,
        hideEditableBits: true,
        inBetweenEditableBits: true,
        keys: {previous: Event.Keys.left, next: Event.Keys.right},
        bitsOptions: {editable: {}, box: {}},
        plugins: {},
        check: function(s) {
            return s.clean().replace(/this.options.split/g, '') != '';
        },
        encode: function(o) {
            return o.map(
                    function(v) {
                        v = ($chk(v[0]) ? v[0] : v[1]);
                        return $chk(v) ? v : null;
                    }).clean().join(this.options.split);
        },
        decode: function(o) {
            return o.split(this.options.split);
        }
    },

    initialize: function(element, options) {
        this.setOptions(options);
        this.original = $(element).setStyle('display', 'none').set('autocomplete', 'off').addEvent('focus', this.focusLast.bind(this));
        this.container = new Element('div', {'class': this.options.prefix}).inject(element, 'after');
        this.container.addEvent('click', function(e) {
            if ((e.target == this.list || e.target == this.container) &&
                    (!this.focused || $(this.current) != this.list.getLast())) this.focusLast();
        }.bind(this));
        this.list = new Element('ul', {'class': this.options.prefix + '-bits'}).inject(this.container);
        for (var name in this.options.plugins) this.enablePlugin(name, this.options.plugins[name]);
        ['check', 'encode', 'decode'].each(function(i) {
            this.options[i] = this.options[i].bind(this);
        }, this);
        this.afterInit();
    },

    enablePlugin: function(name, options) {
        this.plugins[name] = new TagboxList[name.camelCase().capitalize()](this, options);
    },

    afterInit: function() {
        if (this.options.unique) this.index = [];
        if (this.options.endEditableBit) this.create('editable', null, {tabIndex: this.original.tabIndex}).inject(this.list);
        var update = this.update.bind(this);
        this.addEvent('bitAdd', update, true).addEvent('bitRemove', update, true);
        document.addEvents({
            click: function(e) {
                if (!this.focused) return;
                if (e.target.className.contains(this.options.prefix)) {
                    if (e.target == this.container) return;
                    var parent = e.target.getParent('.' + this.options.prefix);
                    if (parent == this.container) return;
                }
                this.blur();
            }.bind(this),
            keydown: function(ev) {
                if (!this.focused || !this.current) return;
                var caret = this.current.is('editable') ? this.current.getCaret() : null;
                var value = this.current.getValue()[1];
                var special = ['shift', 'alt', 'meta', 'ctrl'].some(function(e) {
                    return ev[e];
                });
                var custom = special || (this.current.is('editable') && this.current.isSelected());
                switch (ev.code) {
                    case Event.Keys.backspace:
                        if (this.current.is('box')) {
                            ev.stop();
                            return this.current.remove();
                        }
                    case this.options.keys.previous:
                        if (this.current.is('box') || ((caret == 0 || !value.length) && !custom)) {
                            ev.stop();
                            this.focusRelative('previous');
                        }
                        break;
                    case Event.Keys['delete']:
                        if (this.current.is('box')) {
                            ev.stop();
                            return this.current.remove();
                        }
                    case this.options.keys.next:
                        if (this.current.is('box') || (caret == value.length && !custom)) {
                            ev.stop();
                            this.focusRelative('next');
                        }
                }
            }.bind(this)
        });
        this.setValues(this.options.decode(this.original.get('value')));
    },

    create: function(klass, value, options) {
        if (klass == 'box') {
            if ((!value[0] && !value[1]) || ($chk(value[1]) && !this.options.check(value[1]))) return false;
            if ($chk(this.options.max) && this.list.getChildren('.' + this.options.prefix + '-bit-box').length + 1 > this.options.max) return false;
            if (this.options.unique && this.index.contains(this.uniqueValue(value))) return false;
        }
        return new TagboxListBit[klass.capitalize()](value, this, $merge(this.options.bitsOptions[klass], options));
    },

    uniqueValue: function(value) {
        return $chk(value[0]) ? value[0] : (this.options.uniqueInsensitive ? value[1].toLowerCase() : value[1]);
    },

    onFocus: function(bit) {
        if (this.current) this.current.blur();
        $clear(this.blurtimer);
        this.current = bit;
        this.container.addClass(this.options.prefix + '-focus');
        if (!this.focused) {
            this.focused = true;
            this.fireEvent('focus', bit);
        }
    },

    onBlur: function(bit, all) {
        this.current = null;
        this.container.removeClass(this.options.prefix + '-focus');
        this.blurtimer = this.blur.delay(all ? 0 : 200, this);
    },

    onAdd: function(bit) {
        if (this.options.unique && bit.is('box')) this.index.push(this.uniqueValue(bit.value));
        if (bit.is('box')) {
            var prior = this.getBit($(bit).getPrevious());
            if ((prior && prior.is('box') && this.options.inBetweenEditableBits) ||
                    (!prior && this.options.startEditableBit)) {
                var b = this.create('editable').inject(prior || this.list, prior ? 'after' : 'top');
                if (this.options.hideEditableBits) b.hide();
            }
        }
    },

    onRemove: function(bit) {
        if (!this.focused) return;
        if (this.options.unique && bit.is('box')) this.index.erase(this.uniqueValue(bit.value));
        var prior = this.getBit($(bit).getPrevious());
        if (prior && prior.is('editable')) prior.remove();
        this.focusRelative('next', bit);
    },

    focusRelative: function(dir, to) {
        var b = this.getBit($($pick(to, this.current))['get' + dir.capitalize()]());
        if (b) b.focus();
        return this;
    },

    focusLast: function() {
        var lastElement = this.list.getLast();
        if (lastElement) this.getBit(lastElement).focus();
        return this;
    },

    blur: function() {
        if (! this.focused) return this;
        if (this.current) this.current.blur();
        this.focused = false;
        return this.fireEvent('blur');
    },

    add: function(plain, id, html, afterEl) {
        var b = this.create('box', [id, plain, html]);
        if (b) {
            if (!afterEl) afterEl = this.list.getLast('.' + this.options.prefix + '-bit-box');
            b.inject(afterEl || this.list, afterEl ? 'after' : 'top');
        }
        return this;
    },

    getBit: function(obj) {
        return ($type(obj) == 'element') ? obj.retrieve('tagboxList:bit') : obj;
    },

    getValues: function() {
        return this.list.getChildren().map(
                function(el) {
                    var bit = this.getBit(el);
                    if (bit.is('editable')) return null;
                    return bit.getValue();
                }, this).clean();
    },

    setValues: function(values) {
        if (!values) return;
        values.each(function(v) {
            if (v) this.add.apply(this, $type(v) == 'array' ? [v[1], v[0], v[2]] : [v]);
        }, this);
    },

    update: function() {
        this.original.set('value', this.options.encode(this.getValues()));
    }

});

var TagboxListBit = new Class({
    Implements: Options,
    initialize: function(value, tagboxList, options) {
        this.name = this.type.capitalize();
        this.value = value;
        this.tagboxList = tagboxList;
        this.setOptions(options);
        this.prefix = this.tagboxList.options.prefix + '-bit';
        this.typeprefix = this.prefix + '-' + this.type;
        this.bit = new Element('li').addClass(this.prefix).addClass(this.typeprefix).store('tagboxList:bit', this);
        this.bit.addEvents({
            mouseenter: function() {
                this.bit.addClass(this.prefix + '-hover').addClass(this.typeprefix + '-hover');
            }.bind(this),
            mouseleave: function() {
                this.bit.removeClass(this.prefix + '-hover').removeClass(this.typeprefix + '-hover');
            }.bind(this)
        });
    },

    inject: function(element, where) {
        this.bit.inject(element, where);
        this.tagboxList.onAdd(this);
        return this.fireBitEvent('add');
    },

    focus: function() {
        if (this.focused) return this;
        this.show();
        this.focused = true;
        this.tagboxList.onFocus(this);
        this.bit.addClass(this.prefix + '-focus').addClass(this.prefix + '-' + this.type + '-focus');
        return this.fireBitEvent('focus');
    },

    blur: function() {
        if (!this.focused) return this;
        this.focused = false;
        this.tagboxList.onBlur(this);
        this.bit.removeClass(this.prefix + '-focus').removeClass(this.prefix + '-' + this.type + '-focus');
        return this.fireBitEvent('blur');
    },

    remove: function() {
        this.blur();
        this.tagboxList.onRemove(this);
        this.bit.destroy();
        return this.fireBitEvent('remove');
    },

    show: function() {
        this.bit.setStyle('display', 'block');
        return this;
    },

    hide: function() {
        this.bit.setStyle('display', 'none');
        return this;
    },

    fireBitEvent: function(type) {
        type = type.capitalize();
        this.tagboxList.fireEvent('bit' + type, this).fireEvent('bit' + this.name + type, this);
        return this;
    },

    is: function(t) {
        return this.type == t;
    },

    setValue: function(v) {
        this.value = v;
        return this;
    },

    getValue: function() {
        return this.value;
    },

    toElement: function() {
        return this.bit;
    }

});

TagboxListBit.Editable = new Class({
    Extends: TagboxListBit,
    options: {
        tabIndex: null,
        growing: true,
        growingOptions: {},
        stopEnter: true,
        addOnBlur: false,
        addKeys: Event.Keys.enter
    },
    type: 'editable',
    initialize: function(value, tagboxList, options) {
        this.parent(value, tagboxList, options);
        this.element = new Element('input', {type: 'text', 'class': this.typeprefix + '-input', autocomplete: 'off', value: this.value ? this.value[1] : ''}).inject(this.bit);
        if ($chk(this.options.tabIndex)) this.element.tabIndex = this.options.tabIndex;
        if (this.options.growing) new GrowingInput(this.element, this.options.growingOptions);
        this.element.addEvents({
            focus: function() {
                this.focus(true);
            }.bind(this),
            blur: function() {
                this.blur(true);
                if (this.options.addOnBlur) this.toBox();
            }.bind(this)
        });
        if (this.options.addKeys || this.options.stopEnter) {
            this.element.addEvent('keydown', function(ev) {
                if (!this.focused) return;
                if (this.options.stopEnter && ev.code === Event.Keys.enter) ev.stop();
                if ($splat(this.options.addKeys).contains(ev.code)) {
                    ev.stop();
                    this.toBox();
                }
            }.bind(this));
        }
    },

    focus: function(noReal) {
        this.parent();
        if (!noReal) this.element.focus();
        return this;
    },

    blur: function(noReal) {
        this.parent();
        if (!noReal) this.element.blur();
        return this;
    },

    getCaret: function() {
        if (this.element.createTextRange) {
            var r = document.selection.createRange().duplicate();
            r.moveEnd('character', this.element.value.length);
            if (r.text == '') return this.element.value.length;
            return this.element.value.lastIndexOf(r.text);
        } else return this.element.selectionStart;
    },

    getCaretEnd: function() {
        if (this.element.createTextRange) {
            var r = document.selection.createRange().duplicate();
            r.moveStart('character', -this.element.value.length);
            return r.text.length;
        } else return this.element.selectionEnd;
    },

    isSelected: function() {
        return this.focused && (this.getCaret() !== this.getCaretEnd());
    },
    setValue: function(val) {
        this.element.value = $chk(val[0]) ? val[0] : val[1];
        if (this.options.growing) this.element.retrieve('growing').resize();
        return this;
    },
    getValue: function() {
        return [null, this.element.value, null];
    },
    toBox: function() {
        var value = this.getValue();
        var b = this.tagboxList.create('box', value);
        if (b){
            b.inject(this.bit, 'before');
            this.setValue([null, '', null]);
            return b;
        }
        return null;
    }

});

TagboxListBit.Box = new Class({
    Extends: TagboxListBit,
    options: {
        deleteButton: true
    },
    type: 'box',
    initialize: function(value, tagboxList, options) {
        this.parent(value, tagboxList, options);
        this.bit.set('html', $chk(this.value[2]) ? this.value[2] : this.value[1]);
        this.bit.addEvent('click', this.focus.bind(this));
        if (this.options.deleteButton) {
            this.bit.addClass(this.typeprefix + '-deletable');
            this.close = new Element('a', {href: '#', 'class': this.typeprefix + '-deletebutton', events: {click: this.remove.bind(this)}}).inject(this.bit);
        }
        this.bit.getChildren().addEvent('click', function(e) {
            e.stop();
        });
    }
});

(function() {
    GrowingInput = new Class({

        Implements: [Options, Events],

        options: {
            min: 0,
            max: null,
            startWidth: 2,
            correction: 15
        },
        initialize: function(element, options) {
            this.setOptions(options);
            this.element = $(element).store('growing', this).set('autocomplete', 'off');
            this.calc = new Element('span', {
                'styles': {
                    'float': 'left',
                    'display': 'inline-block',
                    'position': 'absolute',
                    'left': -1000
                }
            }).inject(this.element, 'after');
            ['font-size', 'font-family', 'padding-left', 'padding-top', 'padding-bottom',
                'padding-right', 'border-left', 'border-right', 'border-top', 'border-bottom',
                'word-spacing', 'letter-spacing', 'text-indent', 'text-transform'].each(function(p) {
                this.calc.setStyle(p, this.element.getStyle(p));
            }, this);
            this.resize();
            var resize = this.resize.bind(this);
            this.element.addEvents({blur: resize, keyup: resize, keydown: resize, keypress: resize});
        },

        calculate: function(chars) {
            this.calc.set('html', chars);
            var width = this.calc.getStyle('width').toInt();
            return (width ? width : this.options.startWidth) + this.options.correction;
        },

        resize: function() {
            this.lastvalue = this.value;
            this.value = this.element.value;
            var value = this.value;
            if ($chk(this.options.min) && this.value.length < this.options.min) {
                if ($chk(this.lastvalue) && (this.lastvalue.length <= this.options.min)) return;
                value = str_pad(this.value, this.options.min, '-');
            } else if ($chk(this.options.max) && this.value.length > this.options.max) {
                if ($chk(this.lastvalue) && (this.lastvalue.length >= this.options.max)) return;
                value = this.value.substr(0, this.options.max);
            }
            this.element.setStyle('width', this.calculate(value));
            return this;
        }

    });

    var str_repeat = function(str, times) {
        return new Array(times + 1).join(str);
    };
    var str_pad = function(self, length, str, dir) {
        if (self.length >= length) return this;
        str = str || ' ';
        var pad = str_repeat(str, length - self.length).substr(0, length - self.length);
        if (!dir || dir == 'right') return self + pad;
        if (dir == 'left') return pad + self;
        return pad.substr(0, (pad.length / 2).floor()) + self + pad.substr(0, (pad.length / 2).ceil());
    };
})();
//----------------只能输入数字
var NumberInput = new Class({
    Implements: Options,
    options: {
        inputCss:'input.number',
        defaultValue:"0",
        min:0,
        max:10000
    },
    initialize: function(options) {
        this.setOptions(options);
        if (!this.options.defaultValue.isNumber()) this.options.defaultValue = "0";
        var ni = this;
        $$(this.options.inputCss).addEvent('keyup', function() {
            if (!this.get('value').isNumber()) {
                var v = this.get('value');
                if (v == '') this.set('value', ni.options.defaultValue);
                else {
                    var showV = '';
                    for (var i = 0; i < v.length; i++) {
                        var sv = v.charAt(i) + "";
                        if (sv.isInteger())
                            showV = showV + sv;
                    }
                    if (showV == '') this.set('value', ni.options.defaultValue);
                    else  this.set('value', showV);
                }
            }
            var value = this.get('value');
            this.set('value', value.toInt().limit(ni.options.min, ni.options.max));
        });
    }
});
//-----------多选框
//全选
function selectAll(id, name) {
    if (typeof(id) == 'string')
        id = $(id);
    var inputs = id.getElements('input');
    inputs.each(function(e) {
        if (e.get('name') == name)
            e.set('checked', 'checked');
    });
}
//反选
function selectedConvert(id, name) {
    if (typeof(id) == 'string')
        id = $(id);
    var inputs = id.getElements('input');
    inputs.each(function(e) {
        if (e.get('name') == name) {
            if (e.get('checked') == 'checked' || e.get('checked') == '')
                e.set('checked', 'checked');
            else e.set('checked', '');
        }
    });
}
//得到选择的值,方便ajax提交
function selectedValues(elId) {
    var result = new Array();
    var inputs;
    if (typeof(id) == 'string')
        id = $$(elId);
    else inputs = elId;
    if (inputs)
        inputs.each(function(e) {
            if (e.get('checked'))
                result.push(e.get('value'));
        });
    return result;
}
// Author: Marko Šantić and chenYuan
// Web: http://www.omnisdata.com/omnigrid || http://www.jspx.net
// Email: marko@omnisdata.com
// 特殊类型
//selectbox : 选择框，tog:展开标记 ,button||cbutton 按钮 这几个只有编辑状态,其他标准空间不变
// ****************************************************************************
var JDataTable = new Class({
    Implements: [Events,Options],
    getOptions: function() {
        return {
            title: 'grid',
            alternaterows: true,
            showCaption:true,
            sortCaption:true,
            resizeColumns:true,
            selectable:true,
            serverSort:true,
            sortOn: null,
            sortBy: 'ASC',
            filterHide: true,
            filterHideCls: 'hide',
            filterSelectedCls: 'filter',
            multiselect:false,
            editMode:false,
            editondblclick:false,
            height:0,
            // accordion
            accordion:false,
            accordionRenderer:null,
            autoSectionToggle:true, //如果为 true 详细只打开一个，否则可以同时看多个
            showTog:false,
            openAccordionOnDblClick:false,
            // pagination
            url:null,
            pagination:false,
            currentPage:1,
            countOptions: [8, 12, 24, 50, 100],
            count:12,
            filterInput:false,
            // dataProvider
            dataProvider:null,
            language:'zh',
            onSelected: $empty(), //选择后
            onLoadAfter:$empty()//载入数据后
        };
    },
    initialize: function(options) {
        this.setOptions(this.getOptions(), options);
        this.container = $(this.options.table);
        if (!this.container) return;
        if (this.container.tagName.toLowerCase() != 'div') {
            alert('table 的容器为div');
            return;
        }
        //兼容老版本
        if (!this.options.buttons) {
            this.options.buttons = this.options.headButtons;
        }
        if (!this.options.columnModel) {
            this.options.columnModel = this.options.columnModels;
        }
        if (this.options.height <= 0) {
            var postion = window.document.getPosition();
            this.options.height = postion.y*3/5;
        }
        this.useSelectBox = false;
        for (var i = 0; i < this.options.columnModel.length; i++) {
            if (this.options.columnModel[i].input == 'selectbox') {
                this.useSelectBox = true;
                break;
            }
        }

        this.draw();
		this.refresh();
        this.calendar = new Calendar(this.options.language, this.container.tagName);
        this.colorBox = new ColorBox({ptag:this.container.tagName});
    },

    // API
    reset: function() {
        this.renderData();
        this.refreshDelayID = null;
        this.dragging = false;
        this.selected = new Array();

        if (this.options.accordion)
            this.elements = this.ulBody.getElements('li:nth-child(2n+1)');
        else
            this.elements = this.ulBody.getElements('li');

        this.filtered = false;
        this.lastsection = null;
        if (this.options.alternaterows) this.altRow();
        this.elements.each(function(el, i) {
            el.addEvent('click', this.onRowClick.bind(this));
            el.addEvent('dblclick', this.onRowDblClick.bind(this));
            el.addEvent('mouseover', this.onRowMouseOver.bind(this));
            el.addEvent('mouseout', this.onRowMouseOut.bind(this));
        }, this);

        // **************************** Setup Caption ************************
        this.container.getElements('div.th').each(function(el, i) {
            var type = el.retrieve('dataType');
            if (type) {
                el.getdate = function(str) {
                    return str.toDate();
                };
                el.findData = function(elem) {
                    var child = elem.getFirst();
                    if (child) {
                        return el.findData(child);
                    } else {
                        return elem.innerHTML();
                    }
                };
                el.compare = function(a, b) {
                    var var1 = a.getChildren()[i].innerHTML.trim();
                    var var2 = b.getChildren()[i].innerHTML.trim();
                    if (type == 'number' || type == 'int' || type == 'float') {
                        var1 = parseFloat(var1);
                        var2 = parseFloat(var2);
                        if (el.sortBy == 'ASC') {
                            return var1 - var2;
                        } else {
                            return var2 - var1;
                        }
                    } else if (type == 'string') {
                        var1 = var1.toUpperCase();
                        var2 = var2.toUpperCase();
                        if (var1 == var2) {
                            return 0
                        }
                        if (el.sortBy == 'ASC') {
                            if (var1 < var2) {
                                return -1
                            }
                        } else {
                            if (var1 > var2) {
                                return -1
                            }
                        }
                        return 1;
                    } else if (type == 'date') {
                        var1 = parseFloat(el.getdate(var1));
                        var2 = parseFloat(el.getdate(var2));

                        if (el.sortBy == 'ASC') {
                            return var1 - var2;
                        } else {
                            return var2 - var1;
                        }
                    } else if (type == 'currency') {
                        var1 = parseFloat(var1.substr(1).replace(',', ''));
                        var2 = parseFloat(var2.substr(1).replace(',', ''));
                        if (el.sortBy == 'ASC') {
                            return var1 - var2;
                        } else {
                            return var2 - var1;
                        }
                    }
                }
            }
        }, this);

    },

    //编辑模式
    editMode: function() {
        if (this.options.editMode) return;
        this.options.editMode = true;
        var grid = this;
        var lis = this.container.getElements("li");
        lis.each(function(li, i) {
            var rowData = grid.options.list[i];
            var tds = li.getElements("div.td");
            tds.each(function(e, j) {
                var th = grid.options.columnModel[j];
                var value = e.get('html');
                e.empty();
                if (!th.edit) return;
                if ($type(value) == 'string') {
                    value = value.replace(/\$\{/g, "$\\{").substitute({'index':i}).replace(/\$\\\{/g, "${");
                }
                if (th.input == "select")
                    e.setAttribute("keyValue", value);
                if (rowData && (th.input == "button" || th.input == "cbutton"))
                    th.blink = th.link.substitute(rowData);
                if (th.input == "checkbox" && value == "" && th.name == "select") //没有值就默认为id
                    value = e.getAttribute("keyValue");
				var input = createInputElement(th, value);
	 		    input.addClass('inline');
                e.adopt(input);
            });
        });
        this.reset();
    }
    ,
	//浏览模式
    viewMode: function() {
        if (!this.options.editMode) return;
        this.options.editMode = false;
        var lis = this.container.getElements("li");
        lis.each(function(li, i) {
            var tds = li.getElements("div.td");
            tds.each(function(e, j) {
                e.set('html', getTableCellValue(e, false));
            });
        });
       this.reset();
    }
    ,
    finishEditing: function() {
		var cmu = this.options.columnModel;
        if (!cmu) return;
		var editMode = this.options.editMode;
		var result = new Array();
        var elements = this.ulBody.getElements('li.tr');
        elements.each(function(el, i) {
			var obj = new Object();
            var columns = el.getElements('div.td');
			columns.each(function(td){
				var filed = td.getProperty('filed');
				if (filed)
				{
				   obj[filed] =  getTableCellValue(td, false);
				}
			});
            result.push(obj);
        });

		this.options.list = result;
    },
    addRow: function(data, row) {
	    this.finishEditing();
        if (this.options.list==null) this.options.list = new Array();
		if (!data)
		{
            var data = new Object();
			var cmu = this.options.columnModel;
            for (var i=0; i<cmu.length;i++) data[cmu[i].name] = "";
		}
		if (row)
		{
			this.options.list.splice(row,row,data);
		} else
	        this.options.list.push(data);

        this.reset();
    },
    deleteRow: function(row) {
        if (row >= 0 && row < this.options.list.length) {
            this.options.list.splice(row, 1);
            this.refresh();
        }
    },
    toggle: function(el) {
        if (el.getStyle('display') == 'block') {
            el.setStyle('display', 'none');
        } else {
            el.setStyle('display', 'block');
        }
    },
    getSection: function(row) {
        return this.ulBody.getElement('.section-' + row);
    },

    getLiParent: function (target) {
        target = $(target);
        while (target && !target.hasClass('td')) {
            target = target.getParent();
        }
        if (target)
            return target.getParent();
    },

    onRowMouseOver: function (evt) {
        var li = this.getLiParent(evt.target);
        if (!li) return;
        if (!this.dragging)
            li.addClass('over');
        this.fireEvent("mouseover", {target:this, row:li.retrieve('row'), element:li });
    },

    onRowMouseOut: function (evt) {
        var li = this.getLiParent(evt.target);
        if (!li) return;
        if (!this.dragging)
            li.removeClass('over');
        this.fireEvent("mouseout", {target:this, row:li.retrieve('row'), element:li });
    },
    onSelectBoxClick:function(evt) {
        if (evt.target.type.toLowerCase() != 'checkbox') return;
        var li = this.getLiParent(evt.target);
        var check = evt.target.getProperty('checked');
        if (check) {
            if (!li.hasClass('selected')) {
                li.addClass('selected');
                this.selected.push(Number(li.retrieve('row')));
            }
        } else {
            if (li.hasClass('selected')) {
                li.removeClass('selected');
                this.selected.erase(Number(li.retrieve('row')));
            }
        }
    }
    ,
    onRowClick: function (evt) {
        if ("div" != evt.target.tagName.toLowerCase()) return;
        var li = this.getLiParent(evt.target);
        if (!li) return;
        if (this.options.selectable && evt.target.get('class') != 'toggleicon') {
            var currentindex = li.retrieve('row');
            var selectedNum = this.selected.length;
            var dontselect = false;
            var useSelectBox = this.useSelectBox;

            if ((!evt.control && !evt.shift) || !this.options.multiselect) {
                this.elements.each(function(el, i) {
                    if (useSelectBox) {
                        var selectBox = el.getElement('.selectbox');
                        if (selectBox) selectBox.removeProperty('checked');
                    }
                    el.removeClass('selected')
                }, this);
                this.selected = new Array();
            }
            if (evt.control) {
                for (var i = 0; i < selectedNum; i++) {
                    if (currentindex == this.selected[i]) {
                        var el = this.elements[ currentindex ];
                        el.removeClass('selected');
                        if (useSelectBox) {
                            var selectBox = el.getElement('.selectbox');
                            if (selectBox) selectBox.removeProperty('checked');
                        }
                        this.selected.splice(i, 1);
                        dontselect = true;
                    }
                }
            }
            if (evt.shift && this.options.multiselect) {
                var si = 0;
                if (this.selected.length > 0)
                    si = this.selected[selectedNum - 1];

                var endindex = currentindex;
                startindex = Math.min(si, endindex);
                endindex = Math.max(si, endindex);

                for (var i = startindex; i <= endindex; i++) {
                    var el = this.elements[i];
                    if (useSelectBox) {
                        var selectBox = el.getElement('.selectbox');
                        if (selectBox) selectBox.setProperty('checked', 'checked');
                    }
					if (!el.hasClass('selected')) el.addClass('selected');
                    this.selected.push(Number(i));
                }
            }
            if (!dontselect) {
                if (useSelectBox) {
                    var selectBox = li.getElement('.selectbox');
                    if (selectBox) selectBox.setProperty('checked', 'checked');
                }
                li.addClass('selected');
                this.selected.push(Number(li.retrieve('row')));
            }
            this.unique(this.selected, true);
        }
        if (evt.target.get('class') == 'toggleicon' && this.options.accordion && !this.options.openAccordionOnDblClick) {
            this.accordianOpen(li);
        }

        this.fireEvent("click", {indices:this.selected, target:this, row:li.retrieve('row'), element:li });
        this.fireEvent("selected", {indices:this.selected, target:this, row:li.retrieve('row'), element:li });
    },

    toggleIconClick: function(evt) {
        var li = this.getLiParent(evt.target);
        this.accordianOpen(li);
    },

    accordianOpen: function(li) {
        var section = this.getSection(li.retrieve('row'));
        if (this.options.autoSectionToggle) {
            if (this.lastsection)
                if (this.lastsection != section) {
                    this.lastsection.setStyle('display', 'none');
                    var temp = this.lastsection.getPrevious();
                    if (temp) {
                        temp.getElement('.toggleicon').setStyle('background-position', '0 0');
                    }
                }
            if (!this.options.accordionRenderer) {
                section.setStyle('display', 'block');
            }
        }
        if (this.options.accordionRenderer)  this.toggle(section);
        if (this.options.showTog)  li.getElement('.toggleicon').setStyle('background-position', section.getStyle('display') == 'block' ? '-16px 0' : '0 0');
        this.lastsection = section;
    },
    onRowDblClick: function (evt) {
        if ("div" != evt.target.tagName.toLowerCase()) return;
        var li = this.getLiParent(evt.target);
        if (!li) return;
        var t = evt.target;
        if (this.options.editMode && this.options.editondblclick && t.hasClass('td')) {
            var childs = li.getChildren();
            for (var i = 0; i < childs.length; i++) {
                if (childs[i] == t) break;
            }
            var obj = this.edit({columnIndex:i});
            if (obj) obj.input.selectRange(0, obj.input.value.length);
        }
        if (this.options.accordion && this.options.openAccordionOnDblClick) {
            this.accordianOpen(li);
        }
        this.fireEvent("dblclick", {row:li.retrieve('row'), target:this, element:li});
    },
    onLoadData: function (data) {
        this.setData(data);
        this.fireEvent("loadData", {target:this, pkey:data.pkey});	// jedino pkey salje van jer se on nigdje ne sprema trenutno unutar OMG
        this.fireEvent("loadAfter", {target:this, pkey:data.pkey});
    },
    unique: function(a, asNumber) {
        function om_sort_number(a, b) {
            return a - b;
        }
        var sf = asNumber ? om_sort_number : function() {  };
        a.sort(sf);
        for (var i = 1; i < a.length; i++) {
            if (a[i - 1] == a[i]) {
                a.splice(i, 1);
                i--;
            }
        }
        return a;
    },
    // API
    loadData: function (url) {
        if (!this.options.url && !this.options.dataProvider) return;
        var param = {};

        // ************* pagination *************************
        if (this.options.pagination)
            param = {currentPage:this.options.currentPage, count:this.options.count};

        // ************* server sorting *********************
        if (this.options.serverSort) {
            if (this.options.sortOn)
                param.sort = this.options.sortOn + ':' + this.options.sortBy;
        }
        if (this.options.filterInput) {
            var cfilter = this.container.getElement('input.cfilter');
            if (cfilter) param.filter = cfilter.value;
        }
        this.showLoader();

        if (this.options.dataProvider) {
            this.options.dataProvider.loadData(param);
        } else {
            var toUrl = (url != null) ? url : this.options.url;
            var request = new Request.JSON({url:toUrl, data:param,async:false});
            request.addEvent("complete",this.onLoadData.bind(this));
            request.get();
        }

    },
    refresh: function() {
        this.loadData();
        if (this.options.editMode) {
            this.options.editMode = false;
            this.editMode();
        } else {
            this.options.editMode = true;
            this.viewMode();
        }
    },
    setData: function(data, cm) {
        if (!data) return;
        if ($type(data)=='array') this.options.list = data;
        if (data.list) this.options.list = data.list;
        if (data.turnPage) this.options.turnPage = data.turnPage;
        if (!this.options.columnModel) this.setAutoColumnModel();
        if (this.options.pagination) {
            if (data.totalCount && data.currentPage) {
                this.options.currentPage = data.currentPage;
                this.options.totalCount = data.totalCount;
                this.options.maxpage = Math.ceil(this.options.totalCount / this.options.count);
                this.container.getElement('div.pDiv input').value = data.currentPage;
                var to = (data.currentPage * this.options.count) > data.totalCount ? data.totalCount : (data.currentPage * this.options.count);

                this.container.getElement('div.pDiv span.pPageStat').set('html', ((data.currentPage - 1) * this.options.count + 1) + '..' + to + ' / ' + data.totalCount);
                this.container.getElement('div.pDiv .pcontrol span.maxPage').set('html', this.options.maxpage);

            } else if (data.turnPage) {
                this.options.turnPage = data.turnPage;
                var footerDiv = this.container.getElement('div.pDiv2');
                footerDiv.empty();
                turnPageDiv = new Element('div', {'class':'turnPagePane'});
                footerDiv.adopt(turnPageDiv);
                turnPageDiv.set('html', this.options.turnPage);
                var grid = this;
                var trunButtons = turnPageDiv.getElements('a');
                trunButtons.each(function(button) {
                    var ahref = button.get('href');
                    button.removeProperty("href");
                    button.addEvent('click', function(e) {
                        var event = new Event(e);
                        event.stopPropagation();
                        if ((Browser.Engine.trident4 || Browser.Engine.trident5) && (ahref.startsWith("http") && grid.options.url != '')) {
                            var x = ahref.indexOf('?');
                            if (x != -1) ahref = ahref.substring(x, ahref.length);
                        }
                        if (grid.options.url.indexOf('?') != -1 && ahref.indexOf('?') == 0) {
                            ahref = ahref.replace('?', '&');
                        }
                        grid.loadData(grid.options.url + ahref);
                    });
                });
            }
        }
        if (cm&&this.options.columnModel != cm)
		{
             this.options.columnModel = cm;
             this.draw();
        }
        this.reset();
        this.hideLoader();
    },
    setList: function(data) {
        return this.options.list = data;
    },
    getData: function() {
        return this.options.list;
    },
    getDataByRow: function(row) {
        if (row >= 0 && row < this.options.list.length)
            return this.options.list[row];
    },
    setDataByRow: function(row, data) {
        if (row >= 0 && row < this.options.list.length) {
            this.options.list[row] = data;
            this.reset();
        }
    },
    setScroll: function(x, y) {
        var bDiv = this.container.getElement('.bDiv');
        new Fx.Scroll(bDiv).set(x, y);
    },
    isHidden: function(i) {
        return this.elements[i].hasClass(this.options.filterHideCls);
    },
    hideWhiteOverflow: function(i) {
        if (this.container.getElement('.gBlock'))
            this.container.getElement('.gBlock').dispose();

        var pReload = this.container.getElement('div.pDiv .pReload');
        if (pReload)
            pReload.removeClass('loading');
    },

    showWhiteOverflow: function(i) {
        // ************* white overflow & loader ************
        if (this.container.getElement('.gBlock'))
            this.container.getElement('.gBlock').dispose();

        var gBlock = new Element('div', {style:'top: 0px; left: 0px; background: white none repeat scroll 0% 0%;  -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; position: absolute; z-index: 999; opacity: 0.5; filter: alpha(opacity=50'});
        var bDiv = this.container.getElement('.bDiv');

        var top = 1;
        top += this.container.getElement('.tDiv') ? this.container.getElement('.tDiv').getSize().y : 0;
        top += this.container.getElement('.hDiv') ? this.container.getElement('.hDiv').getSize().y : 0;

        gBlock.setStyles({width:this.options.width, height: this.options.height - 1, top:0});
        gBlock.addClass('gBlock');
        this.container.appendChild(gBlock);
        var pReload = this.container.getElement('div.pDiv .pReload');
        if (pReload) pReload.addClass('loading');
    },
    showLoader: function() {
        if (this.loader) return;
        this.showWhiteOverflow();
        this.loader = new Element('div');
        this.loader.addClass('elementloader');
        this.loader.inject(this.container);
        this.loader.setStyles({top:this.options.height / 2 - 16, left:  this.options.width / 2});
    },
    hideLoader: function() {
        if (!this.loader) return;
        this.hideWhiteOverflow();
        this.loader.dispose();
        this.loader = null;
    },
    // API 全选
    selectAll: function() {
		var selected = this.selected;
	    var useSelectBox = this.useSelectBox;
        this.elements.each(function(el, i) {
			if (!el.hasClass('selected')) {
                selected.push(el.retrieve('row'));
                el.addClass('selected');
				if (useSelectBox) {
                      var selectBox = el.getElement('.selectbox');
                      if (selectBox) selectBox.setProperty('checked', 'checked');
                }
            }
        }, this);
    },
    // API 返选
    selectedConvert: function() {
		var selected = [];
	    var useSelectBox = this.useSelectBox;
        this.elements.each(function(el, i) {
            if (el.hasClass('selected')) 
			{
                selected.push(el.retrieve('row'));
                el.removeClass('selected');
				if (useSelectBox) {
                   var selectBox = el.getElement('.selectbox');
                   if (selectBox) selectBox.removeProperty('checked');
                }
            }
            else
			{
                el.addClass('selected');
				if (useSelectBox) {
                   var selectBox = el.getElement('.selectbox');
                   if (selectBox) selectBox.setProperty('checked', 'checked');
                }

			}
        }, this);
	    this.selected = selected;
    },
    getSelecteds: function(name) {
        //得到当前选择的字段数组
        var result = new Array();
        for (var i = 0; i < this.selected.length; i++) {
            result.include(this.getDataByRow(this.selected[i])[name]);
        }
        return result;
    },
    getSelectedIndices: function() {
        return this.selected;
    },
    setSelectedValue: function(name,value) {
        var el = this.container.getElement('li.selected input[name=' + name + ']');
        if (el) el.set('value',value);
    },
    setSelectedIndices: function(arr) {
        if (!arr) return;
        this.selected = arr;
        for (var i = 0; i < arr.length; i++) {
            var li = this.elements[arr[i]];
            this.onRowClick({target:li.getFirst(), control:false});
        }

    },
    onMouseOver: function(obj) {
        obj.columnModel.onMouseOver(obj.element, obj.list);
    },
    removeCaption: function() {
        var obj = this.container.getElement('.hDiv');
        if (obj) obj.empty();
        this.options.columnModel = null;
    },
    removeAll: function() {
        if (this.ulBody)
            this.ulBody.empty();
        this.selected = new Array();
        this.options.list = [];
    },
    setColumnModel: function(cmu) {
        if (!cmu)
            return;
        this.options.columnModel = cmu;
        this.draw();
    },
    setColumnProperty: function(columnName, property, value) {

        var cmu = this.options.columnModel;
        if (!cmu || !columnName || !property) return;
        columnName = columnName.toLowerCase();
        for (var i = 0; i < cmu.length; i++) {
            if (cmu[i].name.toLowerCase() == columnName) {
                cmu[i][property] = value;
                return;
            }
        }
    },
    setAutoColumnModel: function() {

        if (!this.options.list) return;
        var rowCount = this.options.list.length;
        if (!(rowCount > 0))
            return;
        this.options.columnModel = [];

        // uzmi schemu od prvog podatka
        for (var cn in this.options.list[0]) {
            var type = typeof(this.options.list[0][cn]) == "number" ? "number" : "string";
            this.options.columnModel.push({caption:cn, name:cn, type: type, edit:true});
        }
        this.fireEvent("autocolummodel", {target:this, columnModel:this.options.columnModel});
        this.draw();
    },
    setSize: function(w, h) {

        // Width
        this.options.width = w ? w : this.options.width;

        this.container.setStyle('width', this.options.width);

        var width = this.options.width - 2;
        if (this.options.buttons) this.container.getElement('.tDiv').setStyle('width', width);

        var hDiv = this.container.getElement('.hDiv');
        if (this.options.showCaption && hDiv) hDiv.setStyle('width', width);

        var bodyEl = this.container.getElement('.bDiv');
        bodyEl.setStyle('width', width);
        this.container.getElement('.pDiv').setStyle('width', width);

        // Height
        this.options.height = h ? h : this.options.height;

        bodyEl.setStyle('height', this.getBodyHeight());
        this.container.setStyle('height', this.options.height);

        // ako je kojim slucajem whiteOverflow namjesti
        var gBlock = this.container.getElement('.gBlock');
        if (gBlock)
            gBlock.setStyles({width:this.options.width, height: bodyEl.getSize().y });
    },

    onBodyScroll: function() {
        var hbox = this.container.getElement('.hDivBox');
        var bbox = this.container.getElement('.bDiv');
        var xs = bbox.getScroll().x;
        hbox.setStyle('position', 'relative');
        hbox.setStyle('left', -xs);
        this.rePosDrag();
    },

    onBodyClick: function() {

    },

    onBodyMouseOver: function() {
        //console.debug(this.onBodyScrollID);

    },

    onBodyMouseOut: function() {

    },
    // ************************* Drag columns events **************************
    rePosDrag: function() {
        if (!this.options.resizeColumns)
            return;
        var dragTempWidth = 0;
        var cDrags = this.container.getElements('.cDrag div');
        var scrollX = this.container.getElement('div.bDiv').getScroll().x;
        for (var c = 0; c < this.options.columnModel.length; c++) {
            var columnModel = this.options.columnModel[c];
            //if (columnModel.hide) continue;
            // hide-1
            var dragSt = cDrags[c];
            dragSt.setStyle('left', dragTempWidth + columnModel.width + (Browser.Engine.trident ? 1 : 1 ) - scrollX);
            if (!columnModel.hide)
                dragTempWidth += columnModel.width;
        }
    },

    onColumnDragComplete: function(target) {
        this.dragging = false;
        var colindex = target.retrieve('column');

        var cDrag = this.container.getElement('div.cDrag');
        var dragSt = cDrag.getElements('div')[colindex];
        var scrollX = this.container.getElement('div.bDiv').getScroll().x;

        this.sumWidth = 0;
        for (var c = 0; c < this.options.columnModel.length; c++) {
            var columnModel = this.options.columnModel[c];
            if (c == colindex) {
                var pos = dragSt.getStyle('left').toInt() + scrollX - this.sumWidth - (Browser.Engine.trident ? -1 : 1 );
            } else if (!columnModel.hide)
                this.sumWidth += columnModel.width;
        }
        if (pos < 30) pos = 30;
        this.options.columnModel[colindex].width = pos;

        this.sumWidth += pos;

        this.ulBody.setStyle('width', this.sumWidth + this.visibleColumns * (Browser.Engine.trident ? 1 : 1 ));
        var hDivBox = this.container.getElement('div.hDivBox');

        hDivBox.setStyle('width', this.sumWidth + this.visibleColumns * 2);

        // Caption
        var columns = hDivBox.getElements('div.th');
        var columnObj = columns[colindex];

        columnObj.setStyle('width', pos - (Browser.Engine.trident ? 6 : 6 ));

        var visibleColumns = this.visibleColumns;

        // radi accordiana
        var elements = this.ulBody.getElements('li.tr');

        // sve kolone u body
        elements.each(function(el, i) {
            el.setStyle('width', this.sumWidth + 2 * visibleColumns); // inace se Div-ovi wrapaju

            if (!el.hasClass('section')) {
                var columns = el.getElements('div.td');
                var columnObj = columns[colindex];
                columnObj.setStyle('width', pos - (Browser.Engine.trident ? 6 : 6 ));
            }

        });

        this.rePosDrag();
    },
    onColumnDragStart: function(target) {
        this.dragging = true;
    },
    onColumnDragging: function(target) {
        target.setStyle('top', 1);
    },
    overDragColumn: function(evt) {
        evt.target.addClass('dragging');
    },
    outDragColumn: function(evt) {
        evt.target.removeClass('dragging');
    },

    // ************************* Caption events ********************************
    clickCaptionColumn: function(evt) {
        if (this.dragging) return;
        var colindex = evt.target.retrieve('column');
        var columnModel = this.options.columnModel[colindex];
        evt.target.removeClass(columnModel.sort);
        columnModel.sort = (columnModel.sort == 'ASC') ? 'DESC' : 'ASC';
        evt.target.addClass(columnModel.sort);
        this.sortIndex = colindex;
        //hide-1
        this.sort(colindex);
    },

    overCaptionColumn: function(evt) {
        if (this.dragging) return;
        var colindex = evt.target.retrieve('column');
        var columnModel = this.options.columnModel[colindex];
        evt.target.addClass(columnModel.sort);
    },

    outCaptionColumn: function(evt) {
        if (this.dragging) return;
        var colindex = evt.target.retrieve('column');
        var columnModel = this.options.columnModel[colindex];
        if (!this.sortIndex)
            evt.target.removeClass(columnModel.sort);
        else {
            var hDivBoxThs = this.container.getElements('.th');
            for (var i = 0; i < hDivBoxThs.length; i++) {
                var colI = hDivBoxThs[i].retrieve('column');
                if (colI != this.sortIndex) {
                    hDivBoxThs[i].removeClass('ASC');
                    hDivBoxThs[i].removeClass('DESC');
                }
            }
        }
    },

    getBodyHeight: function() {
        var captionHeight = this.options.showCaption ? 24 + 2 : 0;  //+2 radi bordera
        var toolbarHeight = this.options.buttons ? this.container.getElement('.tDiv').getStyle('height').toInt() : 0;
        var paginationToolbar = this.options.pagination ? 26 : 0;
        return this.options.height - captionHeight - toolbarHeight - paginationToolbar - 2 - this.options.titleHeight; //+2 radi bordera
    },

    renderData: function() {
        this.ulBody.empty();
        if (this.options.list && this.options.list.length) {
            var columnCount = this.options.columnModel.length;
            var rowCount = this.options.list.length;

            for (var r = 0; r < rowCount; r++) {
                var rowdata = this.options.list[r];
				rowdata.index = r;
                var li = new Element('li',{'class':'tr'});
                li.setStyle('width', this.sumWidth + 2 * this.visibleColumns);
                li.store('row', r);
                this.ulBody.appendChild(li);

                if (this.options.tooltip) {
                    this.options.tooltip.attach(tr);
                }

                for (var c = 0; c < columnCount; c++) {
                    var columnModel = this.options.columnModel[c];
                    var div = new Element('div',{'class':'td','filed':columnModel.name});
                    div.setStyle('width', columnModel.width - 6);
                    li.appendChild(div);

                    if (!columnModel.hide && this.options.accordion && this.options.showTog && columnModel.input == 'tog') {
                        div.appendChild(new Element('div', {'class':'toggleicon'}));
                    }

                    if (columnModel.hide) div.setStyle('display', 'none');

                    if (columnModel.onMouseOver) {
                        div.onmouseover = this.onMouseOver.bind(this, {element:div, columnModel:columnModel, data:rowdata });
                    }

                    // title
                    if (columnModel.caption) div.caption = rowdata[columnModel.caption];

                     var value = rowdata[columnModel.name];
                     if ($type(value) == 'string') {
                           value = value.replace(/\$\{/g, "$\\{").substitute({'index':r}).replace(/\$\\\{/g, "${");
                      }

                    if (this.options.editMode && columnModel.edit && columnModel.input != 'tog' || columnModel.input.indexOf('button') != -1 || columnModel.input.indexOf('select') != -1 || columnModel.input.indexOf('selectbox') != -1) {
                        if (columnModel.input == "select") div.setAttribute("keyValue", value);
                         if (rowdata && (columnModel.input == "button" || columnModel.input == "cbutton")) {
                             columnModel.blink = columnModel.link.replace(/\$\{/g, "$\\{").substitute(rowdata).replace(/\$\\\{/g, "${");

                         }
                        if (columnModel.input == "checkbox" && value == "" && columnModel.name == "select") //没有值就默认为id
                            value = div.getAttribute("keyValue");
                        var inputEl = createInputElement(columnModel, value);
                        if (columnModel.input != 'selectbox' && columnModel.input.indexOf('select') != -1 && !this.options.editMode) {
                            //修复IE selectDisabled bug
                            var selectLock = function(event) {
                                event.stop();
                                var el = event.target;

                                function ie6OptionSelected() {
                                    this.selected = true;
                                }
                                var key = el.getAttribute("keyValue");
                                var opts = el.options;
                                for (var i = 0; i < opts.length; i++) {
                                    if (opts[i].value == key) {
                                        if (Browser.Engine.trident4)
                                            ie6OptionSelected.delay(1, opts[i]);
                                        else  opts[i].selected = true;
                                    }
                                }
                                return false;
                            };
                            inputEl.set("keyValue", div.getAttribute("keyValue"));
                            inputEl.addEvent('change', selectLock.bind(inputEl));
                            inputEl.setAttribute('lock', "true");
                        }
                        if (columnModel.input == 'selectbox') {
                            inputEl.set('class', 'selectbox');
                            inputEl.addEvent('change', this.onSelectBoxClick.bind(this));
                        }
                        div.appendChild(inputEl);
                    } else {
                        if (columnModel.input != 'tog') {
                            if (columnModel.labelFunction != null) {
                                div.innerHTML = columnModel.labelFunction(rowdata, r, columnModel);
                            } else {
                                if (columnModel.align) div.setStyles({'text-align': columnModel.align});
                                if (value==null||value=='')
                                { if (columnModel.type=='string')
                                    value = '&nbsp;';
                                  else
                                    value = '0';
                                }
								if (columnModel.expression)
								{
									value = columnModel.expression.substitute(rowdata);
								}
                                div.set('html', value);
                            }
                        }
                    }

                } // for column

                if (this.options.accordion) {
                    var li2 = new Element('li',{'class':'section'});
                    li2.addClass('section-' + r);
                    li2.setStyle('width', this.sumWidth + 2 * this.visibleColumns);
                    this.ulBody.appendChild(li2);
                    if (this.options.accordionRenderer)
                        this.options.accordionRenderer({parent:li2, row:r, grid:this, rowdata: rowdata});
                }
            }
            if (this.calendar)  this.calendar.cssInit();
            if (this.colorBox)  this.colorBox.cssInit();
        }
    },

    // ************************* Main draw function ***************************
    draw: function() {
        this.removeAll(); // reset variables and only empty ulBody
        this.container.empty(); // empty all

        // ************************* Common ***************************************
        var width = this.options.width - (Browser.Engine.trident ? 2 : 2 ); //-2 radi bordera
        var columnCount = this.options.columnModel ? this.options.columnModel.length : 0;

        // ************************* Container ************************************
        if (this.options.width)  this.container.setStyle('width', this.options.width);

        this.container.addClass('JDataTable');
        //标题
        var titleDiv = new Element('div',{'class':'JDTTitlePane'});
        titleDiv.setStyle('width', width + 2);
        titleDiv.set('html', this.options.title);
        this.container.appendChild(titleDiv);
        this.options.titleHeight = titleDiv.getStyle('height').toInt();

        // ************************* Toolbar **************************************
        if (this.options.buttons) {
            var tDiv = new Element('div',{'class':'tDiv JDTButtonPane'});
            tDiv.setStyle('width', width);
            tDiv.setStyle('height', 25 + (Browser.Engine.trident ? 2 : 0 ));
            this.container.appendChild(tDiv);

            var bt = this.options.buttons;
            for (var i = 0; i < bt.length; i++) {
                var fBt = new Element('div');
                tDiv.appendChild(fBt);
                if (bt[i].separator) {
                    fBt.addClass('btnseparator');
                    continue;
                }
                fBt.addClass('fbutton');
                if ($type(bt[i]).toLowerCase() == 'element') {
                    fBt.adopt(bt[i]);
                } else {
                    var cBt = new Element('div');
                    cBt.addEvent('click', bt[i].onclick.bind(this, [bt[i].bclass, this]));
                    cBt.addEvent('mouseover', function() {
                        this.addClass('fbOver');
                    });
                    cBt.addEvent('mouseout', function() {
                        this.removeClass('fbOver');
                    });
                    fBt.appendChild(cBt);
                    var spanBt = new Element('span');
                    spanBt.addClass(bt[i].bclass);
                    spanBt.setStyle('padding-left', 20);
                    spanBt.set('html', bt[i].name);
                    cBt.appendChild(spanBt);

                }
            }
        }

        // ************************* Caption ***************************************
        var hDiv = new Element('div',{'class':'hDiv'});
        hDiv.setStyle('width', width); // borderi u FF
        this.container.appendChild(hDiv);

        var hDivBox = new Element('div',{'class':'hDivBox'});
        hDiv.appendChild(hDivBox);

        this.sumWidth = 0;
        this.visibleColumns = 0;
        for (var c = 0; c < columnCount; c++) {
            var columnModel = this.options.columnModel[c];
            var caption = columnModel.caption;
            if (caption) {
                if (caption.indexOf('|') != -1) caption = caption.substring(0, caption.indexOf('|'));
            }

            var div = new Element('div', {'html':caption});
            // ******************************************
            // ****** default postavke columnModela *****
            if (columnModel.width == null)  columnModel.width = 100;
            columnModel.sort = 'ASC';
            // ******************************************

            // ********************** Caption events **************************
            if (this.options.sortCaption) {
                div.addEvent('click', this.clickCaptionColumn.bind(this));
                div.addEvent('mouseout', this.outCaptionColumn.bind(this));
                div.addEvent('mouseover', this.overCaptionColumn.bind(this));
            }

            div.store('column', c);
            div.store('dataType', columnModel.type);
            div.addClass('th');
            div.setStyle('width', columnModel.width - (Browser.Engine.trident ? 6 : 6 ));
            hDivBox.appendChild(div);

            if (columnModel.hide)
                div.setStyle('display', 'none');
            else {
                this.sumWidth += columnModel.width;
                this.visibleColumns++;
            }

        }
        hDivBox.setStyle('width', this.sumWidth + this.visibleColumns * 2);
        if (!this.options.showCaption)
            hDiv.setStyle('display', 'none');
	    // ************************* Column size drag *****************************
        if (this.options.height) {
            var bodyHeight = this.getBodyHeight();
            this.container.setStyle('height', this.options.height);
        }

        if (this.options.resizeColumns) {
            var cDrag = new Element('div'); //拖动线
            cDrag.addClass('cDrag');
            var toolbarHeight = this.options.buttons ? tDiv.getStyle('height').toInt() : 0; // toolbar
            cDrag.setStyle('top', toolbarHeight + this.options.titleHeight);
            this.container.appendChild(cDrag);
            var dragTempWidth = 0;
            for (var i = 0; i < columnCount; i++) {
                var columnModel = this.options.columnModel[i];
                var dragSt = new Element('div');
                var captionHeight = this.options.showCaption ? 24 + 2 : 0; // +2 border

                dragSt.setStyles({top:1,left: dragTempWidth + columnModel.width, height: captionHeight, display:'block'}); // bodyHeight+
                dragSt.store('column', i);
                cDrag.appendChild(dragSt);

                // Events
                dragSt.addEvent('mouseout', this.outDragColumn.bind(this));
                dragSt.addEvent('mouseover', this.overDragColumn.bind(this));

                var dragMove = new Drag(dragSt, {snap:0});
                dragMove.addEvent('drag', this.onColumnDragging.bind(this));
                dragMove.addEvent('start', this.onColumnDragStart.bind(this));
                dragMove.addEvent('complete', this.onColumnDragComplete.bind(this));

                if (columnModel.hide)
                    dragSt.setStyle('display', 'none');
                else
                    dragTempWidth += columnModel.width;
            }
        }
        // ************************* Body *****************************************
        var bDiv = new Element('div', {'class':'bDiv'});
        if (this.options.width) bDiv.setStyle('width', width);

        bDiv.setStyle('height', bodyHeight);
        this.container.appendChild(bDiv);

        //  scroll event
        this.onBodyScrollBind = this.onBodyScroll.bind(this);
        bDiv.addEvent('scroll', this.onBodyScrollBind);

        this.ulBody = new Element('ul');
        this.ulBody.setStyle('width', this.sumWidth + this.visibleColumns * (Browser.Engine.trident ? 1 : 1 ));
        bDiv.appendChild(this.ulBody);

        if (this.options.pagination && !this.container.getElement('div.pDiv')) {
            var pDiv = new Element('div', {'class':'pDiv'});
            pDiv.setStyle('width', width);
            pDiv.setStyle('height', 25);
            this.container.appendChild(pDiv);

            var h = '<div class="pGroup"><select class="rp" name="rp">';
            // *****
            var optIdx;
            var setDefaultcount = false;
            for (optIdx = 0; optIdx < this.options.countOptions.length; optIdx++) {
                if (this.options.countOptions[optIdx] != this.options.count)
                    h += '<option value="' + this.options.countOptions[optIdx] + '">' + this.options.countOptions[optIdx] + '</option>';
                else {
                    setDefaultcount = true;
                    h += '<option selected="selected" value="' + this.options.countOptions[optIdx] + '">' + this.options.countOptions[optIdx] + '</option>';
                }
            }
            // *****

            h += '</select></div>';
            h += '<div class="btnseparator"></div><div class="pGroup"><div class="pFirst pButton"></div><div class="pPrev pButton"></div></div>';
            h += '<div class="btnseparator"></div><div class="pGroup"><span class="pcontrol"> <input class="cpage" type="text" value="1" size="4" style="text-align:center"/> / <span class="maxPage">&nbsp;</span></span></div>';
            h += '<div class="btnseparator"></div><div class="pGroup"><div class="pNext pButton"></div><div class="pLast pButton"></div></div>';
            h += '<div class="btnseparator"></div><div class="pGroup"><div class="pReload pButton"></div></div>';
            h += '<div class="btnseparator"></div><div class="pGroup"><span class="pPageStat"></div>';

            if (this.options.filterInput) h += '<div class="btnseparator"></div><div class="pGroup"><span class="pcontrol"><input class="cfilter" type="text" value="" style="" /><span></div>';

            var pDiv2 = new Element('div', {'class':'pDiv2','html':h});

            // set this.options.count value from this.options.countOptions array
            var rpObj = pDiv2.getElement('.rp');
            if (!setDefaultcount && rpObj.options.length > 0) {
                this.options.count = rpObj.options[0].value;
                rpObj.options[0].selected = true;
            }
            // ********

            pDiv2.getElement('.pFirst').addEvent('click', this.firstPage.bind(this));
            pDiv2.getElement('.pPrev').addEvent('click', this.prevPage.bind(this));
            pDiv2.getElement('.pNext').addEvent('click', this.nextPage.bind(this));
            pDiv2.getElement('.pLast').addEvent('click', this.lastPage.bind(this));
            pDiv2.getElement('.pReload').addEvent('click', this.refresh.bind(this));
            pDiv2.getElement('.rp').addEvent('change', this.countChange.bind(this));
            pDiv2.getElement('input.cpage').addEvent('keyup', this.pageChange.bind(this));

            if (this.options.filterInput) pDiv2.getElement('input.cfilter').addEvent('change', this.firstPage.bind(this)); // goto 1 & refresh
            pDiv.adopt(pDiv2);
        }

    },

    firstPage: function() {
        this.options.currentPage = 1;
        this.refresh();
    },

    prevPage: function() {
        if (this.options.currentPage > 1) {
            this.options.currentPage--;
            this.refresh();
        }
    },

    nextPage: function() {
        if ((this.options.currentPage + 1) > this.options.maxpage) return;
        this.options.currentPage++;
        this.refresh();
    },

    lastPage: function() {
        this.options.currentPage = this.options.maxpage;
        this.refresh();
    },

    countChange: function() {
        this.options.currentPage = 1;
        this.options.count = this.container.getElement('.rp').value;
        this.refresh();
    },

    pageChange: function() {
        var np = this.container.getElement('div.pDiv2 input').value;
        if (np > 0 && np <= this.options.maxpage) {
            if (this.refreshDelayID)
                $clear(this.refreshDelayID);
            this.options.currentPage = np;
            this.refreshDelayID = this.refresh.delay(1000, this);
        }
    },
    // API
    gotoPage: function(p) {
        if (p > 0 && p <= this.options.maxpage) {
            this.options.currentPage = p;
            this.refresh();
        }
    },
    setCount: function(p) {
        if (p > 0) {
            this.options.count = p;
            this.refresh();
        }
    },
    // API, not doc
    sort: function(index, by) {
        if (index < 0 || index >= this.options.columnModel.length) return;
        if (this.options.onStart) {
            this.fireEvent('onStart');
        }
        var caption = this.container.getElements('.th');
        var el = caption[index];
        if (by != null)
            el.addClass(by.toLowerCase());

        if (el.hasClass('ASC')) {
            el.sortBy = 'ASC';
        } else if (el.hasClass('DESC')) {
            el.sortBy = 'DESC';
        }

        if (this.options.serverSort) {
            this.options.sortOn = this.options.columnModel[index].name;
            this.options.sortBy = el.sortBy;

            this.refresh();
        } else {
            // Sorting...
            this.elements.sort(el.compare);
            this.elements.injectInside(this.ulBody);

            // Update selection array because indices has been changed
            this.selected = new Array();
            this.elements.each(function(el, i) {
                if (el.hasClass('selected')) {
                    this.selected.push(el.retrieve('row'));
                }
            }, this);

            // Filter
            if (this.filtered) {
                this.filteredAltRow();
            } else {
                this.altRow();
            }
        }

    },
    altRow: function() {
        this.elements.each(function(el, i) {

            if (i % 2) {
                el.removeClass('erow');
            } else {
                el.addClass('erow');
            }
        });
    },
    filteredAltRow: function() {
        this.ulBody.getElements('.' + this.options.filterSelectedCls).each(function(el, i) {
            if (i % 2) {
                el.removeClass('erow');
            } else {
                el.addClass('erow');
            }
        });
    },
    // API
    filter: function(form) {
        //var form = $(form);
        var col = 0;
        var key = '';
        if (!(form.length > 0)) this.clearFilter();
        key = form;
        if (key) {
            for (var i = 0; i < this.options.list.length; i++) {
                var dat = this.options.list[i];

                for (var c = 0; c < this.options.columnModel.length; c++) {
                    var columnModel = this.options.columnModel[c];
                    if (columnModel.type == "checkbox") continue;
                    var el = this.elements[i];
                    if (this.options.filterHide) {
                        el.removeClass('erow');
                    }

                    if (dat[columnModel.name] != null && dat[columnModel.name].toLowerCase().indexOf(key) > -1) {
                        el.addClass(this.options.filterSelectedCls);
                        if (this.options.filterHide) {
                            el.removeClass(this.options.filterHideCls);
                        }
                        break;
                    } else {
                        el.removeClass(this.options.filterSelectedCls);
                        if (this.options.filterHide) {
                            el.addClass(this.options.filterHideCls);
                        }
                    }
                }
            }

            if (this.options.filterHide) {
                this.filteredAltRow();
                this.filtered = true;
            }
        }
    },

    // API
    clearFilter: function() {
        this.elements.each(function(el, i) {
            el.removeClass(this.options.filterSelectedCls);
            if (this.options.filterHide) {
                el.removeClass(this.options.filterHideCls);
            }
        }, this);
        if (this.options.filterHide) {
            this.altRow();
            this.filtered = false;
        }
    }
});
