﻿/* last update: 2010-01-29 */
var listtableUrl = null;

/* for datapicker */
var dateoption = {
    dateFormat: 'yy-mm-dd',
    showOn: 'button',
    buttonImage: WEBSITEPATH + 'global/jquery/images/calendar.gif',
    buttonImageOnly: true,
    onClose: function() { this.focus(); }
};

document.documentElement.onkeydown = function(evt) {
    var b = !!evt, oEvent = evt || window.event;
    if (oEvent.keyCode == 8) {
        var node = b ? oEvent.target : oEvent.srcElement;
        var reg = /^(input|textarea)$/i, regType = /^(text|textarea|password)$/i;
        if (!reg.test(node.nodeName) || !regType.test(node.type) || node.readOnly || node.disabled) {
            if (b) {
                oEvent.preventDefault();
                oEvent.stopPropagation();
            }
            else {
                oEvent.cancelBubble = true;
                oEvent.keyCode = 0;
                oEvent.returnValue = false;
            }
        }
    }
}

String.prototype.trim = function() {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

function token() {
    var hex = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
    var t = '';
    for (var i = 0; i < 16; i++) {
        t += hex[Math.floor(Math.random() * 16)];
    }
    return t.toUpperCase();
}
jQuery.Web = {
    get: function(url, data) {
        if (data && typeof (data) != 'string') {
            data = jQuery.param(data);
        }
        if (data) {
            url += (url.match(/\?/) ? "&" : "?") + data + '&token=' + token();
            data = null;
        } else {
            url += (url.match(/\?/) ? "&" : "?") + 'token=' + token();
        }
        var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
        xhr.open('GET', url, false);
        xhr.send(null);

        return xhr.responseText;
    },
    xml: function(url, data) {
        var doc = null;
        var text = jQuery.Web.get(url, data);
        if (document.implementation.createDocument) {
            var parser = new DOMParser();
            doc = parser.parseFromString(text, 'text/xml');
        } else if (window.ActiveXObject) {
            var doc = new ActiveXObject('Microsoft.XMLDOM');
            doc.async = 'false';
            doc.loadXML(text);
        }
        return doc;
    }
};

function HttpUrl() {
    return window.location.pathname + window.location.search;
}
function EscapeUrl() {
    return escape(window.location.pathname + window.location.search);
}
function ReGobackUrl(u) {
    var url = '';
    if (listtableUrl != null) {
        url = escape(listtableUrl);
    } else {
        url = EscapeUrl();
    }
    if (u.indexOf('?') == -1) {
        return '?url=' + url;
    } else {
        return '&url=' + url;
    }
}
function ReWriteUrl(url) {
    window.location.href = url + ReGobackUrl(url);
}
function ReWriteHref(o) {
    o.href = o.href + ReGobackUrl(o.href);
}
function ReWriteForm(f, u) {
    f.method = 'GET';
    f.__VIEWSTATE.disabled = true;
    if (u) {
        f.action = u;
    } else {
        f.action + '&url=' + EscapeUrl();
    }
}

/*
o: object
t: type (win, href, sync)
u: url
w: width
h: height
p: parameter of winlayer
*/
function BtnLinkClick(o, t, u, w, h, p) {
    u = GetAbsoluteUrl(u);
    switch (t) {
        case 'win':
            top.OpenLayerWindow(u, w, h, p);
            break;
        case 'href':
            window.location.href = u + ReGobackUrl(u);
            break;
    }
}

function BtnActClickBefore(p) {
    return true;
}

function BtnActClickCallBack(ids) {
    
}
/*
o: object
t: type (win, href, sync)
u: url
w: width
h: height
s: (s or m)single or multi, default m
p: parameter of winlayer
*/
function BtnActClick(o, t, u, w, h, s, p) {
    var ids = ChkBoxValues(o, s);
    if (ids == null) {
        return false;
    }

    var p = {u:u, w:w, h:h, ids:ids};
    if (!BtnActClickBefore(p, ids)) {
        return false;
    }
    
    u = p.u;
    w = p.w;
    h = p.h;
    ids = p.ids;
    
    u = GetAbsoluteUrl(u);
    u = u.replace('{0}', ids);

    BtnOpenWindow(t, u, w, h, p);
    BtnActClickCallBack(ids);
}

/*
o: object
u: url
s: (s or m)single or multi, default m
*/
function BtnDelClick(o, u, s) {
    var ids = ChkBoxValues(o, s);
    if (ids == null) {
        return false;
    } else if (!confirm(top.GetResource('pub_msg_sureToDel'))) {
        return false;
    }

    u = GetAbsoluteUrl(u);
    u = u.replace('{0}', ids);

    var rel = $.Web.get(u);
    if (rel == 'OK') {
        LoadCurrentPage();
    } else {
        showError(rel);
    }
}

/*
o: object
u: url
s: (s or m)single or multi, default m
m: message
f: function(ids)
*/
function BtnSyncClick(o, u, s, m, f) {
    var ids = ChkBoxValues(o, s);
    if (ids == null) {
        return false;
    } else if (m) {
        if (!confirm(m)) {
            return false;
        }
    }

    if (f) {
        if (!f(ids)) {
            return false;
        }
    }

    u = GetAbsoluteUrl(u);
    u = u.replace('{0}', ids);

    var rel = $.Web.get(u);
    if (rel == 'OK') {
        LoadCurrentPage();
    } else {
        showError(rel);
    }
}

/*
u: url
*/
function BtnGoBack(u) {
    if (u) {
        window.location.href = u;
    } else {
        var url = HttpUrl();
        var s = url.indexOf('url=');
        var e = url.indexOf('&', s);
        if (s == -1) {
            window.history.go(-1);
        } else {
            if (e == -1) {
                url = url.substring(s + 4);
            } else {
                url = url.substring(s + 4, e);
            }
            window.location.href = unescape(url);
        }
    }
}

/*
t: type (win, href, sync)
u: url
w: width
h: height
p: parameter of winlayer
*/
function BtnOpenWindow(t, u, w, h, p) {
    switch (t) {
        case 'win':
            top.OpenLayerWindow(u, w, h, p);
            break;
        case 'href':
            window.location.href = u + ReGobackUrl(u);
            break;
    }
}

/*
o: object
t: type (href, sync)
u: url
*/
function BtnOrderClick(o, u) {
    var listtable = GetListtable(o);
    var datascroll = $('dl.datascroll', listtable);

    u = GetAbsoluteUrl(u);

    $.ajax({
        type: 'GET',
        cache: false,
        url: u,
        beforeSend: page_synclayer,
        success: page_callback,
        error: function(e) {
            showError(e.responseText);
        }
    });

    function page_synclayer() {
        LoadSyncLayer(datascroll);
    }

    function page_callback(res, status) {
        if (listtableUrl == null) {
            LoadContentPage(o, HttpUrl());
        } else {
            LoadContentPage(o, listtableUrl);
        }
    }
}

/*
o: object
s: s-single, m-mutlti, n-can no select (default m)
*/
function ChkBoxValues(o, s) {
    var table = GetCurrentTable(o);
    var names = $("input.chkbox[checked]", table).map(function() {
        return $(this).val();
    }).get().join(",");

    if (!s) {
        s = 'm';
    }

    if (s != 'n') {
        if (names.length == 0) {
            alert(top.GetResource('pub_msg_selectNoOne'));
            return null;
        }
        if (s == 's') {
            if (names.indexOf(',') > -1) {
                alert(top.GetResource('pub_msg_selectOnlyOne'));
                return null;
            }
        }
    }
    return names;
}

function GetAbsoluteUrl(u) {
    if (u.substring(0, 1) != '/') {
        var path = window.location.pathname;
        var pos = path.lastIndexOf('/') + 1;
        u = path.substring(0, pos) + u;
    }
    return u;
}

var resource = [[]];
function GetResource(key) {
    var len = resource.length;
    for (var i = 0; i < len; i++) {
        if (resource[i][0] == key) {
            return resource[i][1];
        }
    }

    var res = $.Web.get(WEBSITEPATH + 'admin/general/GetLanguage.aspx?key=' + escape(key));
    resource[len] = [key, res];

    return res;
}
//get the current form
function GetCurrentForm(o) {
    if (!o) {
        return document.getElementsByTagName('FORM')[0];
    }
    var tag = o;
    var name = '';
    var i = 0;
    while (true) {
        name = tag.tagName.toLowerCase();
        if (name == 'form') {
            return tag;
        }
        tag = tag.parentNode;

        i++;
        if (i > 20) {
            break;
        }
    }
    return null;
}

//get the current table
function GetCurrentTable(o) {
    var tag = o;
    var name = '';
    var i = 0;
    while (true) {
        name = tag.tagName.toLowerCase();
        if (name == 'table') {
            return tag;
        }
        tag = tag.parentNode;

        i++;
        if (i > 20) {
            break;
        }
    }
    return null;
}

/* get the current listtalbe */
function GetListtable(o) {
    if (o == null) {
        return $('table.listtable')[0];
    }
    var tag = o;
    var name = '';
    var i = 0;
    while (true) {
        name = tag.tagName.toLowerCase();
        if (name == 'table' && tag.className == 'listtable') {
            return tag;
        }
        tag = tag.parentNode;

        i++;
        if (i > 5) {
            break;
        }
    }
    return null;
}

//reset the current form
function ResetForm(o) {
    var form = GetCurrentForm(o);
    if (form != null) {
        form.reset();
    }
}

//submit the current form
var isSubmitForm = false;
function SubmitForm(o) {
    var form = GetCurrentForm(o);
    if (form != null) {
        if (SubmitFormCtrl(form) != false && isSubmitForm == false) {
            isSubmitForm = true;
            form.submit();
        }
    }
}

//submit form's control
function SubmitFormCtrl(f) {
    alert('The \'SubmitFormCtrl(f)\' method or operation is not implemented.');
    return false;
}

var validator = null;
function FormValidator() {
    this.Check = check;
    this.Reg = regiester;

    //check input box not allow empty
    this.InputNotEmpty = fnInputNotEmpty;

    //check dropdownlist selected 0 or not
    this.SelectNotZero = fnSelectNotZero;   

    //check dropdownlist selected value or not
    this.SelectNotEmpty = fnSelectNotEmpty;

    //check the input value equal the p.val
    this.Equals = fnEquals;

    //check the data exist in database or not
    this.IsExist = fnIsExist;

    //check the input value is INT number or not (not allow empty)
    this.IntNumber = fnIntNumber;

    //check the input value is INT number or not (allow empty)
    this.IntNullableNumber = fnIntNullableNumber;

    //check the input value not equal the p.val
    this.NotEquals = fnNotEquals;

    //check the input value only includes letter, number and _ (not allow empty)
    this.TextKey = fnTextKey;

    //check the input value match yyyy-MM-dd or not
    this.DateYYMMdd = fnDateYYMMdd;

    //check email address
    this.EmailAddress = fnEmailAddress;

    //check it matches the regex or not
    this.Regex = fnRegex;

    //check input length
    this.CheckMaxLen = fnCheckMaxLen;

    var array = new Array();
    var setting = { val: '', msg: 'error message', nullable: false };

    /*
    e: the object for jquery
    r: the check function
    p: the parameter for check-function { val: value, msg: error message}
    */
    function regiester(e, r, p) {
        p = $.extend({}, setting, p || {});
        $(e).blur(function() {
            execute($(this), r, p);
        });
        array[array.length] = [e, r, p];
    }

    function fnInputNotEmpty(o, p) {
        if (o.val().trim().length == 0) {
            p.msg = top.GetResource('pub_msg_inputNotEmpty');
            return false;
        }
        return true;
    }
    function fnSelectNotZero(o, p) {
        var value = o.get(0).value;
        if (value.trim() == "0") {
            p.msg = top.GetResource('pub_msg_selectNotEmpty');
            return false;
        }
        return true;
    }
    function fnSelectNotEmpty(o, p) {
        var value = o.get(0).value;
        if (value.trim() == "") {
            p.msg = top.GetResource('pub_msg_selectNotEmpty');
            return false;
        }
        return true;
    }
    function fnEquals(o, p) {
        return (o.val().trim() == p.val);
    }
    function fnIsExist(o, p) {
        var rel = $.Web.get(WEBSITEPATH + 'admin/CommonPages/DataChecker.ashx?type=' + p.type + '&method=' + p.method, p.args);
        if (rel != 'OK') {
            p.msg = top.GetResource('pub_msg_dataIsExist');
            return true;
        }
        return false;
    }
    function fnIntNumber(o, p) {
        var val = o.val().trim();
        if (val.length == 0) {
            p.msg = top.GetResource('pub_msg_inputNotEmpty');
            return false;
        }
        if (/^[0-9]*$/.test(val) == false) {
            p.msg = top.GetResource('pub_msg_dataNotMatch');
            return false;
        }
        return true;
    }
    function fnIntNullableNumber(o, p) {
        var val = o.val().trim();
        if (/^[0-9]*$/.test(val) == false) {
            p.msg = top.GetResource('pub_msg_dataNotMatch');
            return false;
        }
        return true;
    }
    function fnNotEquals(o, p) {
        return (o.val().trim() != p.val);
    }
    function fnTextKey(o, p) {
        var val = o.val().trim();
        if (val.length == 0) {
            p.msg = top.GetResource('pub_msg_inputNotEmpty');
            return false;
        }
        if (/^[a-zA-Z0-9_]*$/.test(val) == false) {
            p.msg = top.GetResource('pub_msg_dataNotMatch');
            return false;
        }
        return true;
    }

    function fnEmailAddress(o, p) {
        var val = o.val().trim();
        if (val.length == 0) {
            //p.msg = top.GetResource('pub_msg_inputNotEmpty');
            return true;
        }
        if (/^[\w\.-]+(\+[\w-]*)?@([\w-]+\.)+[\w-]+$/.test(val) == false) {
            p.msg = top.GetResource('pub_msg_emailNotMatch');
            return false;
        }
        return true;
    }

    function fnDateYYMMdd(o, p) {
        var val = o.val().trim();
        if (val.length == 0) {
            return true;
        }
        var rex = new RegExp("^((19[0-9]{2}|2[0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))$|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))$|((([0-9]{2})(0[48]|[2468][048]|[13579][26])$|((0[48]|[2468][048]|[3579][26])00))-02-29)$");
        if (!rex.test(val)) {
            p.msg = top.GetResource('pub_msg_dateNotMatch');
            return false;
        }

        if (p.begin || p.end) {
            var beginDate = '';
            var endDate = '';
            if (p.begin) {
                beginDate = $(p.begin).val();
                endDate = o.val().trim();
            } else {
                beginDate = o.val();
                endDate = $(p.end).val();
            }
            startDate = beginDate.replace(/-/gi, "");
            endDate = endDate.replace(/-/gi, "");
            if (parseFloat(startDate) > parseFloat(endDate)) {
                p.msg = top.GetResource('pub_msg_endstartdate');
                return false;
            }
        }

        return true;
    }

    function fnRegex(o, p) {
        if (o.val().trim().length == 0) {
            p.msg = top.GetResource('pub_msg_inputNotEmpty');
            return false;
        }
        var reg = null;
        var val = p.val;

        if (typeof (val) == 'object') {
            reg = new RegExp(val)
        } else {
            reg = new RegExp(val, 'gi')
        }

        p.msg = top.GetResource('pub_msg_dataNotMatch');
        if (reg.test(o.val())) {
            return true;
        }
        return false;
    }

    function fnCheckMaxLen(o, p) {
        var val = o.val().trim();
        var maxLen = o.attr('maxlen');
        if (getByteLen(o.val()) > parseInt(maxLen, 10)) {
            p.msg = top.GetResource('pub_msg_outofLength');
            return false;
        }
        return true;
    }

    function check() {
        var errors = new Array();
        $(array).each(function() {
            var c = this;
            $(c[0]).each(function() {
                var bool = execute($(this), c[1], c[2]);
                if (bool == false) {
                    errors[errors.length] = $(this);
                }
            });
        });

        if (errors.length > 0) {
            errors[0].focus();
            return false;
        } else {
            var form = GetCurrentForm();
            var inputs = $(':text,textarea', form);
            inputs.each(function(i) {
                if (this.id.length > 0) {
                    if ($(this).attr('maxlen')) {
                        var bool = execute($(this), validator.CheckMaxLen, {});
                        if (bool == false) {
                            errors[errors.length] = $(this);
                            return;
                        }
                    }
                }
            });

            if (errors.length > 0) {
                errors[0].focus();
                return false;
            }
            else {
                return true;
            }
        }
    }

    function getByteLen(str) {
        var i, sum = 0;
        for (i = 0; i < str.length; i++) {
            if ((str.charCodeAt(i) >= 0) && (str.charCodeAt(i) <= 255)) {
                sum = sum + 1;
            }
            else {
                sum = sum + 2;
            }
        }
        return sum;
    }

    function execute(o, r, p) {
        var parent = o.parent();
        var msgbox = $('.input_msg_error,.input_msg_right', parent);
        var bool = r(o, p);

        if (bool == true) {
            var maxLen = o.attr('maxlen');
            if (getByteLen(o.val()) > maxLen) {
                if (msgbox.size() == 0) {
                    msgbox = $('<input class="input_msg_error" disabled="disabled" title="" />');
                    msgbox.addClass('input_msg_error');

                    msgbox.attr('title', top.GetResource('pub_msg_outofLength'));
                    parent.append(msgbox);
                }
                else {
                    if (msgbox.hasClass('input_msg_right')) {
                        msgbox.removeClass('input_msg_right')

                        msgbox.addClass('input_msg_error');
                        msgbox.attr('title', top.GetResource('pub_msg_outofLength'));
                        parent.append(msgbox);
                    }
                    else {
                        msgbox.attr('title', top.GetResource('pub_msg_outofLength'));
                    }
                }

                return false;
            }
        }

        if (bool == false) {
            $(this).val('');
            if (msgbox.size() == 0) {
                msgbox = $('<input class="input_msg_error" disabled="disabled" title="" />');
                parent.append(msgbox);
            } else {
                if (msgbox.hasClass('input_msg_right')) {
                    msgbox.removeClass('input_msg_right')
                }
                msgbox.addClass('input_msg_error');
            }
            msgbox.attr('title', p.msg);
        } else {
            if (msgbox.size() == 0) {
                msgbox = $('<input class="input_msg_right" disabled="disabled" title="" />');
                parent.append(msgbox);
            } else {
                if (msgbox.hasClass('input_msg_error')) {
                    msgbox.removeClass('input_msg_error')
                }
                msgbox.addClass('input_msg_right');
            }
            msgbox.attr('title', '');
        }
        return bool;
    }
}

function showError(error) {
    var title = null;
    var re = new RegExp('<title>(.+?)<\/title>', 'gi');
    if (re.test(error)) {
        title = RegExp.$1;
    }
    error = error.replace(/<head[^>]*>((.|\s)*?)<\/head>/gi, '');
    error = error.replace(/<\/table>([\s\S]*)/gi, '</table>');
    error = error.replace(/<span[^>]*>((.|\s)*?)<\/span>/gi, '');
    error = error.replace(/<!--((.|\s)*?)-->/gi, '');
    error = error.replace(/<html[^>]*>((.|\s)*?)<br[^>]*>/gi, '');

    error = error.replace(/<([^>]*)>/gi, '');
    error = error.replace(/&quot;/gi, '"');
    error = error.replace(/\t/gi, '');
    error = error.replace(/  /gi, '');
    error = error.replace(/\r\n\r\n/gi, '');

    if (title != null) {
        error = error.replace(title, '');
        alert(title + '\r\n\r\n' + error);
    } else {
        alert(error);
    }
}
function showRequest(formData, jqForm, options) {
    var bool = true;
    if (validator) {
        bool = validator.Check();
    }
    if (bool == true) {
        $.blockUI({ message: null });
    }
    return bool;
}
function afterResponse(res) { }
function showResponse(response, status) {
    if (status == 'success') {
        var text = response.responseText;
        var re = new RegExp('<script[^>]*>((.|\s)*?)<\/script>', 'gi');
        if (re.test(text)) {
            var code = RegExp.$1;
            code = code.replace('history.go(-1);', '');
            eval(code);
        }
        afterResponse(text);
    } else {
        showError(response.responseText);
    }
    $.unblockUI();
}

/*
list table controls
t: (type)
o: object
e: event
r: url
*/
function ListtableClick(t, o, e, r) {
    switch (t) {
        case 'chkbox':
            if (o.checked == true) {
                SelectOneRow(o.parentNode.parentNode);
            } else {
                UnSelectOneRow(o.parentNode.parentNode);
            }
            SetAllChkBoxState();
            break;
        case 'radio':
            UnSelectAllRows();
            SelectOneRow(o.parentNode.parentNode);
            break;
        case 'rowclk':
            if (e.srcElement) {
                if (e.srcElement.tagName.toLowerCase() == 'input') {
                    return;
                }
            } else {
                if (e.target.tagName.toLowerCase() == 'input') {
                    return;
                }
            }
            UnSelectAllRows(o.tagName.toLowerCase());
            SelectOneRow(o);
            SetAllChkBoxState();
            if (r) {
                LoadContentPage(r);
            }
            break;
        case 'multrowclk':
            if (e.srcElement) {
                if (e.srcElement.tagName.toLowerCase() == 'input') {
                    return;
                }
            } else {
                if (e.target.tagName.toLowerCase() == 'input') {
                    return;
                }
            }
            if (IsChkboxChecked(o) == false || IsChkboxChecked(o) == null) {
                SelectOneRow(o);
            } else {
                UnSelectOneRow(o);
            }
            SetAllChkBoxState();
            break;
        case 'chkall':
            if (o.checked == true) {
                SelectAllRows();
            } else {
                UnSelectAllRows();
            }
            break;
    }

    function SelectOneRow(row) {
        row.style.backgroundColor = '#E9F2FF';
        $(".whitebg", row).css('background-color', '#fff');

        SetCheckboxState(row, true);
    }

    function UnSelectOneRow(row) {
        row.style.backgroundColor = '#fff';
        SetCheckboxState(row, false);
    }

    function SelectAllRows() {
        var c = GetCurrentTable(o);
        $('.body', c).each(function() {
            SelectOneRow(this);
        });
    }

    function UnSelectAllRows(tag) {
        var c = GetCurrentTable(o);
        $('.body', c).each(function() {
            UnSelectOneRow(this);
        });
    }

    function SetCheckboxState(o, b) {
        var chkboxs = $('input.chkbox:eq(0)', o)[0];
        if (!chkboxs) {
            return;
        }
        if (!chkboxs.disabled) {
            chkboxs.checked = b;
        } else {
            o.style.backgroundColor = '#ffffff';
        }
        if (!(e == null && t != 'chkall')) {
            SelectOneRowCallback(chkboxs);
        }
    }

    function SetRadioState(o, b) {
        var tds = o.getElementsByTagName('td');
        if (tds.length > 0) {
            var chkboxs = tds[0].getElementsByTagName('input');
            if (chkboxs.length == 1) {
                if (!chkboxs[0].disabled) {
                    chkboxs[0].checked = b;
                } else {
                    o.style.backgroundColor = '#ffffff';
                }
            }
        }
    }

    function SetAllChkBoxState() {
        var c = GetListtable(o);
        var chkbox_all = $('input.chkbox_all', c);
        if (chkbox_all.size() > 0) {
            chkbox_all[0].checked = ($('input.chkbox', c).size() == $('input.chkbox:checked', c).size());
        }
    }

    function IsChkboxChecked(o) {
        var checks = $('input.chkbox:eq(0)', o);
        if (checks.size() > 0) {
            return checks[0].checked;
        }
        return null;
    }
}
function SelectOneRowCallback(o) {

}

var InitListtable_FixHeight = 0;
function InitListtable() {
    var listtable = $('table.listtable');
    var dl_datascroll = $('dl.datascroll', listtable);
    var div_datascroll = $('div.datascroll', listtable);
    var foot = $('tr.foot', listtable);

    if (div_datascroll.size() > 0) {
        var widths = 0;
        var columns = $('tr.column th', div_datascroll);
        columns.each(function() {
            widths += parseInt($(this).attr('fixwidth'), 10);
        });

        $('table.listtable', div_datascroll).css('width', widths);
        columns.each(function() {
            this.style.width = (parseInt($(this).attr('fixwidth'), 10) / widths) * 100 + '%';
        });

        $('dl.datascroll', div_datascroll).scroll(function() {
            dl_datascroll[0].scrollTop = this.scrollTop;
        })
    }

    listtable.each(function() {
        var columns = $('tr.column th', this);
        var datas = $('table.datatable', this).children().children();
        datas.each(function() {
            if ($(this).children().size() != columns.size()) {
                return true;
            }
            $(this).children().each(function(j) {
                this.style.width = columns[j].style.width;
            });
            return false;
        });
        datas.each(function() {
            $(this).children()[0].style.borderLeft = 'none';
        });
    });

    function setListtableHeight() {
        var win_height = $(window).height();
        var data_top = $(dl_datascroll).offset().top;
        var foot_height = $('td:first', foot).height();
        if (foot_height == null) {
            foot_height = 0;
        }

        var fix_height_1 = win_height - data_top - foot_height - 10 - InitListtable_FixHeight;
        $(dl_datascroll).css('height', fix_height_1);

        if (div_datascroll.size() > 0) {
            $(div_datascroll).css('height', fix_height_1 + 27).css('width', (listtable.width() - $(div_datascroll).parent().attr('fixwidth')));
        }
    }

    if (foot.size() == 1) {
        var href = null;
        $('a', foot).each(function() {
            href = $(this).attr('href');
            if (href.indexOf('://') > -1) {
                href = href.substring(href.indexOf('/', 7));
            }
            var re = new RegExp('((\\?|&)(_=[^&]*))', 'ig');
            if (re.test(href) == true) {
                href = href.replace(RegExp.$1, '');
            }
            $(this).attr('href', 'javascript:LoadContentPage(this.parentNode, \'' + href + '\')');
        });
    }

    $(window).resize(function() {
        setListtableHeight();
    });
    setTimeout(function() {
        setListtableHeight();
    }, 20);
}

function LoadSyncLayer(o) {
    o.html('<div class="datasynclayer" style="height:' + o.height() + 'px;">&nbsp;</div>');
}

function LoadCurrentPage() {
    if (listtableUrl == null) {
        LoadContentPage(null, HttpUrl());
    } else {
        LoadContentPage(null, listtableUrl);
    }
}
function LoadContentCallback(res) {

}
function LoadContentPage(o, href) {
    listtableUrl = href;

    var listtable = GetListtable(o);
    var datascroll = $('dl.datascroll', listtable);

    $.ajax({
        type: 'GET',
        cache: false,
        url: href,
        beforeSend: page_synclayer,
        success: page_callback,
        error: function(e) {
            showError(e.responseText);
        }
    });

    $('input.chkbox_all', listtable).attr('checked', '');

    function page_synclayer() {
        LoadSyncLayer(datascroll);
    }
    function page_callback(res, status) {
        var re1 = new RegExp('<dl\\sclass="datascroll">([\\s\\S]+?)</dl>', 'img');
        if (re1.test(res) == true) {
            var html = RegExp.$1;
            datascroll.html(html);
        } else {
            showError(res);
            return;
        }
        var re2 = new RegExp('<dl\\sid="pagerBar">([\\s\\S]+?)</dl>', 'img');
        if (re2.test(res) == true) {
            var html = RegExp.$1;
            $('#pagerBar', listtable).html(html);
        }
        InitListtable();
        LoadContentCallback(res);
    }
}

function DisplaySearchPanel(o) {
    var panel = $('#divListSearchPanel');
    if (panel.css('display') == 'none') {
        panel.css({
            top: $(o).position().top + $(o).height(),
            left: $(o).position().left + $(o).width() - panel.width()
        }).show();
        $('.listtable tr:gt(0)').one('click', function() {
            panel.hide();
        });
        OpenLayerMover(panel, '');
    } else {
        panel.hide();
    }
}

var divLayerHolder = new Array();
var divLayerCloseEvent = new Array();
var divLayerHtml = '<div id="{0}" class="divLayerWindow"><div class="corn tpbd"></div><div class="head lrbd"><div class="left">title</div><div class="rigt" onclick="CloseLayerWindow(\'{0}\')">&nbsp;</div></div><div class="body lrbd"><div class="ifrm" style="height:{1}px"><iframe id="{0}" name="{0}" width="100%" scrolling="no" frameborder="0" src="{2}" style="border:0px;"></iframe></div></div><div class="corn btbd"></div></div>';
function OpenLayerWindow(u, w, h, p) {
    var ops = $.extend({
        pos: 5,
        css: {},
        move: true,
        modal: true,
        stack: '',
        handle: null,
        inner: null
    }, p || {});
    
    var id = token();
    var url = u + (u.match(/\?/) ? "&" : "?") + 'token=' + token();
    if (url.substring(0, 1) != '/') {
        var path = window.location.pathname;
        var pos = path.lastIndexOf('/') + 1;
        url = path.substring(0, pos) + url;
    }
    if (ops.inner != null) {
        url += '&inner=' + ops.inner.name;
    }
    var dom;
    var width = $(window).width()
    var height = $(window).height();
    var html = divLayerHtml.replace(/\{0\}/g, id).replace('{1}', h).replace('{2}', url);

    if (ops.modal) {
        var obj = { message: html, css: {
                border: 'none',
                width: w,
                left: (width - w) / 2,
                top: (height - h) / 2
            }
        };
        if (ops.inner == null || ops.inner.name == 'frmMain') {
            $.blockUI(obj);
            divLayerHolder[divLayerHolder.length] = [id, ''];
        } else {
            $('#' + ops.inner.name).block(obj);
            divLayerHolder[divLayerHolder.length] = [id, ops.inner.name];
        }
        dom = $('#' + id).parent();

    } else {
        dom = $(html).appendTo(document.body).css({
            position: 'absolute',
            width: w
        });

        switch (ops.pos) {
            case 0:
                dom.css(ops.css);
                break;
            case 5:
                dom.css({
                    left: (width - w) / 2,
                    top: (height - h) / 2
                });
                break;
            case 9:
                dom.css({
                    right: 0,
                    bottom: 0
                });
                break;
        }
        dom.show();
    }

    $('div.ifrm', dom).css({
        width: w - 10
    });

    if (ops.move) {
        OpenLayerMover(dom, ops.stack, $('div.left', dom));
    }
}
function OpenLayerMover(o, stk, handle) {
    if (handle) {
        handle.css({
            cursor: 'move'
        });
    }
    o.draggable({
        stack: stk,
        handle: handle,
        containment: 'window',
        helper: function() {
            var E = $('#divLayerMover');
            if (E.size() == 0) {
                E = $('<div id="divLayerMover" />').css({
                    border: 'dotted 1px black',
                    backgroundColor: '#fff',
                    cursor: 'move',
                    zIndex: 4000,
                    width: $(this).width(),
                    height: $(this).height(),
                    opacity: 0.6
                }).appendTo(document.body);
            }
            return E[0];
        },
        stop: function(event, ui) {
            $(this).css({
                top: ui.helper.position().top,
                left: ui.helper.position().left,
                right: '',
                bottom: ''
            });
        }
    });
}

function OpenLayerSetPos(w, h, e) {
    var name = e.name, obj = null;
    var len = divLayerHolder.length;
    for (var i = 0; i < len; i++) {
        if (divLayerHolder[i][0] == name) {
            var parent = divLayerHolder[i][1];
            obj = (parent == '') ? window : '#' + parent;
            break;
        }
    }
    var width = $(obj).width(), height = $(obj).height();
    var pos_x = (width - w) / 2 + 'px', pos_y = (height - h) / 2 + 'px';
    $('#' + e.name + ' .body:first').css('height', h + 'px');
    $('#' + e.name + ' iframe:first').css('height', h + 'px');
    $('#' + e.name).parent().css('width', w + 'px').css('left', pos_x).css('top', pos_y);
}
function CloseLayerWindowEventReg(e, f) {
    divLayerCloseEvent[divLayerCloseEvent.length] = [e.name, f];
}
function CloseLayerWindow(t) {
    if (typeof (t) == 'object') {
        t = t.name;
    }
    var close = false;
    var len = divLayerHolder.length;
    var events = divLayerCloseEvent.length;
    for (var i = 0; i < len; i++) {
        if (divLayerHolder[i][0] == t) {
            var parent = divLayerHolder[i][1];
            divLayerHolder.splice(i, 1);
            for (var j = 0; j < events; j++) {
                if (divLayerCloseEvent[j][0] == t) {
                    var r = divLayerCloseEvent[j][1];
                    r();
                    divLayerCloseEvent.splice(j, 1);
                    break;
                }
            }
            if (parent == '') {
                $.unblockUI();
            } else {
                $('#' + parent).unblock();
            }
            close = true;
            break;
        }
    }
    if (close == false) {
        $('#' + t).remove();
    }
}
$(document).keydown(function(oEvent) {
    if (oEvent.keyCode == 27) {
        if (top.divLayerHolder.length > 0) {
            top.CloseLayerWindow(top.divLayerHolder[top.divLayerHolder.length - 1][0]);
        }
    }
});

function leftMenuItemDisplay(o) {
    var t = GetCurrentTable(o);
    var u = $(t).next();
    u.toggle(0, function() {
        if (this.style.display == 'block') {
            $(o).removeClass('nav_point_open').addClass('nav_point_close');
        } else {
            $(o).removeClass('nav_point_close').addClass('nav_point_open');
        }
    });
}

function GetHelpByPage(o) {
    alert(window.location.pathname);
}

function FocusOnOneElement() {
    var selects = $('select');
    var inputs = $('input:text');
    var select_count = selects.size();
    var input_count = inputs.size();

    if (select_count > 0 && input_count > 0) {
        if (selects.offset().top > inputs.offset().top) {
            if (inputs[0].disabled == true) {
                inputs[1].focus();
            } else {
                inputs[0].focus();
            }
        } else {
            if (selects[0].disabled == false) {
                selects[0].focus();
            }
        }
    } else if (input_count > 0) {
        for (var i = 0; i < input_count; i++) {
            if (inputs[i].disabled == false) {
                inputs[i].focus();
                break;
            }
        }
    } else if (select_count > 0) {
        for (var i = 0; i < select_count; i++) {
            if (selects[i].disabled == false) {
                selects[i].focus();
                break;
            }
        }
    }
}

/*
t: typename of assembley
p: paramters, format {param=value},{param=value}
o: object to be binding
f: function after binded
*/
function SelectLoaderDatabind(t, p, g, f) {
    var rel = $.Web.get(WEBSITEPATH + 'admin/CommonPages/DropdownLoader.aspx?type=' + t + '&value=' + escape(p));
    if (rel.indexOf('NG-') == 0) {
        alert(rel.substring(3));
        return;
    }

    g[0].length = 0;
    $(rel).children().appendTo(g);

    if (f) {
        setTimeout(function() {
            f(g);
        }, 10);
    }
}

function OpenHTMLeditor(target) {
    top.OpenLayerWindow(WEBSITEPATH + 'admin/general/HTMLeditor.aspx?target=' + target, 900, 500, { inner: window });
}

function ShowValidateCode(o) {
    var pos = $(o).position();
    var layer = $('#ValidateLayer');
    if (layer.size() == 0) {
        var div = '<div id="ValidateLayer" style="position:absolute; text-align:center; display:none;">{0}</div>';
        var img = '<img id="imValidateCode" src="#" style="cursor:pointer;" onclick="ReloadValidateCode(this.id)" alt="看不清？点击重新获取" />';
        var html = div.replace(/\{0\}/gi, img);
        layer = $(html).appendTo(document.body);
    }
    layer.css({
        left: pos.left,
        top: pos.top
    }).show();

    ReloadValidateCode('imValidateCode');

    $(o).one('blur', function() {
        //layer.hide();
    });
}
function ReloadValidateCode(id) {
    var img = document.getElementById(id);
    var url = WEBSITEPATH + 'global/ValidateCode.aspx?token=' + token();
    img.src = url;
}

var KE_Items = ['undo', 'redo', '|', 'title', 'fontname', 'fontsize', 'textcolor', 'bgcolor', 'bold', 'italic', 'underline', 'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist', 'subscript', 'superscript', '|', 'remote_image', 'flash', 'advtable', 'hr', '|', 'source', 'fullscreen'];
var KE_Item2s = ['undo', 'redo', '|', 'title', 'fontname', 'fontsize', 'textcolor', 'bgcolor', 'bold', 'italic', 'underline', 'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist', 'subscript', 'superscript', '|', 'advtable', 'hr', '|', 'source', 'fullscreen'];
var KE_Colors = [['#000000', '#993300', '#333300', '#003300', '#003366', '#000080', '#333399', '#333333'], ['#800000', '#FF6600', '#808000', '#008000', '#008080', '#0000FF', '#666699', '#808080'], ['#FF0000', '#FF9900', '#99CC00', '#339966', '#33CCCC', '#3366FF', '#800080', '#969696'], ['#FF00FF', '#FFCC00', '#FFFF00', '#00FF00', '#00FFFF', '#00CCFF', '#993366', '#C0C0C0'], ['#FF99CC', '#FFCC99', '#FFFF99', '#CCFFCC', '#CCFFFF', '#99CCFF', '#CC99FF', '#FFFFFF']];


