
/**
 * TDataGrid
 */
var TDataGrid = TClass.extend(TWebControl, {

    /**
     * Constructor
     */
    initialize: function(name) {
        $C(TWebControl).initialize.call(this, name);

        this.fRows = new Object();
        this.fCells = new Object();

        this.fColumns = new Array();
        this.fPerPage = 0;
        this.fEditMode = false;
        this.fActiveEditElement = null;

        this.fMonthsFull = new Array();
        this.fMonthsShort = new Array();
        this.fWeekdaysFull = new Array();
        this.fWeekdaysShort = new Array();

        this.fPager = new TDataGridPager(name);

        this.fEventType = "";
        this.fSortColumn = "";
        this.fSortDirection = "asc";
        this.fSortByIndexList = {};
    },


    /**
     * Set records per page
     */
    setPerPage: function(aPerPage) {
        this.fPerPage = aPerPage;
    },


    /**
     * Get per page
     */
    getPerPage: function() {
        return this.fPerPage;
    },


    /**
     * Add properties
     */
    addProperties: function(aProperties) {
        for (var k in aProperties) {
            this.setProperty(k, aProperties[k]);
        }
    },


    /**
     * Set columns
     */
    setColumns: function(aColumns) {
        this.fColumns = aColumns;
    },


    /**
     * Set pager
     */
    setPager: function(inst) {
        this.fPager = inst;
    },


    /**
     * Set page index
     */
    setPageIndex: function(aValue) {
       this.fPager.setPageIndex(aValue);
    },


    /**
     * Get page index
     */
    getPageIndex: function() {
       return this.fPager.getPageIndex();
    },


    /**
     * Get sort column
     */
    getSortColumn: function() {
       return this.fSortColumn;
    },


    /**
     * Get sort direction
     */
    getSortDirection: function() {
       return this.fSortDirection;
    },


    /**
     * Set pages
     */
    setPages: function(aValue) {
       this.fPager.setPages(aValue);
    },


    /**
     * Set edit mode
     */
    setEditMode: function(aValue) {
       this.fEditMode = aValue;

       var footerBox = elem(this.getName() + "FooterRight");
       var tmpKey = this.getName() + "__tmp_footer";

       if (this.fEditMode) {
           if (!this.hasProperty(tmpKey)) {
               this.setProperty(tmpKey, footerBox.innerHTML);
               footerBox.innerHTML = "<input type='button' value='" + this.i18n("btn_save") + "' class='button' onclick='" + this.getName() + ".commitEdit();return false;' />&nbsp;<input type='button' value='" + this.i18n("btn_cancel") + "' class='button' onclick='" + this.getName() + ".cancelEdit();return false;' />";
           }
       }
       else {
           if (this.hasProperty(tmpKey)) {
               footerBox.innerHTML = this.getProperty(tmpKey);
               this.removeProperty(tmpKey);
           }
       }
    },


    /**
     * Is edit mode
     */
    isEditMode: function() {
       return this.fEditMode;
    },


    /**
     * Set data source
     */
    setDataSource: function(aDataSource) {
       this.buildTable(aDataSource);
       for (var i=0; i < this.fColumns.length; i++) {
           if (elem(this.getName()+'hc'+i)) {
               elem(this.getName()+'hc'+i).className = "dgSubHeader";
           }
       }

       if (this.fSortByIndexList[this.fSortColumn] && elem(this.getName()+'hc'+this.fSortByIndexList[this.fSortColumn])) {
           elem(this.getName()+'hc'+this.fSortByIndexList[this.fSortColumn]).className = "dgSubHeader " + (this.fSortDirection=="asc" ? "dgAsc" : "dgDesc");
       }
    },


    /**
     * Finish
     */
    finish: function() {
        this.fSortColumn = this.fProperties["initialsortcolumn"];

        this.fMonthsFull = this.i18n('M').split(',');
        this.fMonthsShort = this.i18n('m').split(',');
        this.fWeekdaysFull = this.i18n('W').split(',');
        this.fWeekdaysShort = this.i18n('w').split(',');

        this.fPager.addLocaleStrings(this.fI18N);
    },


    /**
     * Reload
     */
    reload: function() {
        this.load(this.getPageIndex());
    },


    /**
     * Load
     */
    load: function(aPageIndex) {
       if (this.isEditMode()) {
           this.setEditMode(false);
       }

       var data = {
            "__dg_etype"  :   this.fEventType,
            "__dg_ind"    :   aPageIndex ? aPageIndex : this.getPageIndex(),
            "__dg_pp"     :   this.fPerPage,
            "__dg_scol"   :   this.fSortColumn,
            "__dg_sdir"   :   this.fSortDirection
       };

       this.fireActionEvent(this.getName(), this.getName() + "_OnEvent", data);
    },


    /**
     * Row mouse over
     */
    rowMouseOver: function(id) {
        if (this.OnRowMouseOver && !this.isEditMode()) {
            this.OnRowMouseOver(this.fRows[id]);
        }
    },


    /**
     * Row mouse out
     */
    rowMouseOut: function(id) {
        if (this.OnRowMouseOut && !this.isEditMode()) {
            this.OnRowMouseOut(this.fRows[id]);
        }
    },


    /**
     * Row click
     */
    rowClick: function(id) {
        if (this.OnRowClick && !this.isEditMode()) {
            this.OnRowClick(this.fRows[id]);
        }
    },


    /**
     * Row double click
     */
    rowDblClick: function(id) {
        if (this.OnRowDoubleClick && !this.isEditMode()) {
            this.OnRowDoubleClick(this.fRows[id]);
        }
    },


    /**
     * Cell mouse over
     */
    cellMouseOver: function(id) {
        if (this.OnCellMouseOver && !this.isEditMode()) {
            this.OnCellMouseOver(this.fCells[id]);
        }
    },


    /**
     * Cell mouse out
     */
    cellMouseOut: function(id) {
        if (this.OnCellMouseOut && !this.isEditMode()) {
            this.OnCellMouseOut(this.fCells[id]);
        }
    },


    /**
     * Cell click
     */
    cellClick: function(id) {
        if (this.OnCellClick && !this.isEditMode()) {
            this.OnCellClick(this.fCells[id]);
        }
    },


    /**
     * Cell double click
     */
    cellDblClick: function(id) {
        if (this.OnCellDoubleClick && !this.isEditMode()) {
            this.OnCellDoubleClick(this.fCells[id]);
        }
    },


    /**
     * Build table
     */
    buildTable: function(arr) {
        if (!arr) return;

        this.fRows = new Object();
        this.fCells = new Object();

        if (this.OnBegin) {
            this.OnBegin();
        }

        var html = "";

        html += "<table id='" + this.getName() + "DataGrid' class='dgTable'";
        if (this.fProperties["cellspacing"] != null) {
            html += " cellspacing='" + this.getProperty("cellspacing") + "'";
        }
        if (this.fProperties["align"] != null) {
            html += " align='" + this.getProperty("align") + "'";
        }
        if (this.fStyle != null) {
            html += " style='" + this.fStyle + "'";
        }
        html += ">";

        var contentLeft = "";
        if (this.fProperties["header"] && this.fProperties["header"]["left"]) {
            contentLeft = this.fProperties["header"]["left"];
        }

        var contentCenter = "";
        if (this.fProperties["header"] && this.fProperties["header"]["center"]) {
            contentCenter = this.fProperties["header"]["center"];
        }

        var contentRight = "";
        if (this.fProperties["header"] && this.fProperties["header"]["right"]) {
            contentRight = this.fProperties["header"]["right"];
        }

        if (contentLeft!="" || contentCenter!="" || contentRight!="") {
            var htmlTable = "<table border='0' cellspacing='0' cellpadding='0' style='width:100%;'><tr><td class='dgLeft'>" + contentLeft + "</td><td class='dgCenter'>" + contentCenter + "</td><td class='dgRight'>" + contentRight + "</td></tr></table>";
            html += "<tr class='dgHeader'><td colspan='" + this.fColumns.length + "' class='dgHeader'>" + htmlTable + "</td></tr>";
        }

        var htmlHeadColumns = "";
        for (var i=0; i<this.fColumns.length; i++) {
            var columnDef = this.fColumns[i];
            var caption = columnDef["caption"];
            if (!caption) continue;
            var cellId = this.getName() + 'hc' + i;
            if (columnDef["sortby"]) {
                this.fSortByIndexList[columnDef["sortby"]] = i;
                caption = "<a class='dgLink' href='#' onclick=\"" + this.getName() + ".sortBy('" + columnDef["sortby"] + "');return false;\">" + columnDef["caption"] + "</a>";
            }
            htmlHeadColumns += "<td id='" + cellId + "' class='dgSubHeader'>" + caption + "</td>";
        }
        if (htmlHeadColumns && htmlHeadColumns != "") {
            html += "<tr class='dgSubHeader'>" + htmlHeadColumns + "</tr>";
        }

        for (i=0; i<arr.length; i++) {
            var record = arr[i];
            if (this.OnRecordBeforeRender) {
                var tmp = this.OnRecordBeforeRender(record);
                if (tmp) record = tmp;
            }

            var rowId = this.getName() + "_row_" + i;

            html += "<tr id='" + rowId + "' class='" + (i%2==0?'dgRowEven':'dgRowOdd') + "' " +
                        "onmouseover='" + this.getName() + ".rowMouseOver(this.id);' " +
                        "onmouseout='" + this.getName() + ".rowMouseOut(this.id);' " +
                        "onclick='" + this.getName() + ".rowClick(this.id);' " +
                        "ondblclick='" + this.getName() + ".rowDblClick(this.id);' " +
                      ">";

            for (var j=0; j<this.fColumns.length; j++) {
                var colId = rowId + "_col_" + j;
                var columnDef = this.fColumns[j];
                var style = columnDef["style"] ? " style='" + columnDef["style"] + "'" : "";
                html += "<td id='" + colId + "' class='dgTD'" + style + " " +
                            "onmouseover='" + this.getName() + ".cellMouseOver(this.id);' " +
                            "onmouseout='" + this.getName() + ".cellMouseOut(this.id);' " +
                            "onclick='" + this.getName() + ".cellClick(this.id);' " +
                            "ondblclick='" + this.getName() + ".cellDblClick(this.id);' " +
                         ">" + this.buildCellContent(record, this.fColumns[j], ((this.fPager.fPageIndex-1)*this.fPerPage)+i+1) + "</td>";
            }
            html += "</tr>";

            this.fRows[rowId] = record;
        }



        if ((this.fPerPage < 5000) && (this.fPerPage > arr.length)) {
            var diff = this.fPerPage - arr.length;
            var emptyHTML = "";
            for (var k=0; k<(diff-1); k++) {
                emptyHTML += "&nbsp;<br/>&nbsp;<br/>";
            }
            html += "<tr class='" + ((k+i)%2==0?'dgRowEven':'dgRowOdd') + "'><td class='dgTD' colspan='" + this.fColumns.length + "'>" + emptyHTML + "</td></tr>";
        }



        var htmlPager = this.fPager.toHtml();

        if (htmlPager || this.fProperties["footer"]) {
            html += "<tr class='dgFooter'>";
            html += "<td colspan='" + this.fColumns.length + "' class='dgFooter'>";
            html += "<table cellspacing='0' cellpadding='0' border='0' style='width:100%'><tr>";

            contentLeft = "";
            if (this.fProperties["footer"] && this.fProperties["footer"]["left"]) {
                contentLeft = this.fProperties["footer"]["left"];
            }

            contentCenter = "";
            if (this.fProperties["footer"] && this.fProperties["footer"]["center"]) {
                contentCenter = this.fProperties["footer"]["center"];
            }

            contentRight = "";
            if (this.fProperties["footer"] && this.fProperties["footer"]["right"]) {
                contentRight = this.fProperties["footer"]["right"];
            }

            var tdLeft = "<td class='dgLeft' id='" + this.getName() + "FooterLeft'>" + (htmlPager?htmlPager:"") + contentLeft + "</td>";
            var tdCenter = "<td class='dgCenter' id='" + this.getName() + "FooterCenter'>" + contentCenter + "</td>";
            var tdRight = "<td class='dgRight' id='" + this.getName() + "FooterRight'>" + contentRight + "</td>";

            html += tdLeft + tdCenter + tdRight;

            html += "</tr></table>";
            html += "</td>";
            html += "</tr>";
        }

        elem(this.getName()).innerHTML = html;




        for (var rowId in this.fRows) {
            var data = this.fRows[rowId]; // record
            var gridRow = new TDataGridRow(rowId, elem(rowId), data);
            gridRow.setParent(this);

            for (var j=0; j<this.fColumns.length; j++) {
                var cellId = rowId + "_col_" + j;
                var gridCell = new TDataGridCell(cellId, elem(cellId), this.fColumns[j]);
                gridCell.setParent(gridRow);
                gridRow.addCell(j, gridCell);
                this.fCells[cellId] = gridCell;
            }

            this.fRows[rowId] = gridRow;
        }



        // events

        if (this.OnRowPostRender) {
            for (rowId in this.fRows) {
                this.OnRowPostRender(this.fRows[rowId]);
            }
        }

        if (this.OnCellPostRender) {
            for (rowId in this.fRows) {
                var row = this.fRows[rowId];
                for (var j=0; j<row.size(); j++) {
                   this.OnCellPostRender(row.cellByPos(j));
                }
            }
        }

        if (this.OnFinish) {
            this.OnFinish();
        }
    },


    /**
     * Build cell content
     */
    buildCellContent: function(values, columnDef, seq) {

        var content = columnDef["content"] ? columnDef["content"] : "";
        var extractedStrings = content.match(/\{#.+?\}/g);

        if (extractedStrings) {
            for (var i=0; i<extractedStrings.length; i++) {
                var extrStr = extractedStrings[i].replace(/\{/, "").replace(/#/, "").replace(/\}/, "");
                var fieldValue = extractedStrings[i];
    
                if (extrStr == "seq") {
                    fieldValue = seq;
                }
                else if (values[extrStr] != null) {
                    fieldValue = values[extrStr];
                }
                else if (extrStr.indexOf("::timestamp::")>0) {
                    var a1 = extrStr.split("::");
                    if (a1.length == 3) {
                        if (values[a1[0]]) {
                            fieldValue = this.formatTimestamp(values[a1[0]], a1[2]);
                        }
                        else {
                            return "";
                        }
                    }
                }
                else if (extrStr.indexOf("::filesize")>0) {
                    var a1 = extrStr.split("::");
                    if (a1.length == 2) {
                        if (values[a1[0]]) {
                            fieldValue = filesizeToString(values[a1[0]]);
                        }
                        else {
                            return "";
                        }
                    }
                }
                else if (values[extrStr] == null) {
                    fieldValue = "";
                }

                if (columnDef["replace"] && columnDef["replace"][extractedStrings[i]]) {
                    var transformAA = columnDef["replace"][extractedStrings[i]];
                    if (transformAA[fieldValue])
                        fieldValue = transformAA[fieldValue];
                }
    
                content = content.split("{#" + extrStr + "}").join(fieldValue);
            }
        }

        if (columnDef["render"] && this[columnDef["render"]]) {
            content = this[columnDef["render"]].call(this, content, values);
        }

        return content;
    },


    /**
     * Format timestamp
     */
    formatTimestamp: function(str, format) {
        var y = 1900; var mon = 1; var d = 1; var h24 = '00'; var min = '00'; var sec = '00';
        var m = str.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+).*/i);
        if (m) {
            y = m[1]; mon = m[2]; d = m[3]; h24 = m[4]; min = m[5]; sec = m[6];
        }
        else {
            m = str.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+)/i);
            if (m) {
                y = m[1]; mon = m[2]; d = m[3]; h24 = m[4]; min = m[5];
            }
            else {
                m = str.match(/(\d+)-(\d+)-(\d+)/i);
                if (m) {
                    y = m[1]; mon = m[2]; d = m[3];
                }
                else {
                    m = str.match(/(\d+):(\d+):(\d+).*/i);
                    if (m) {
                        h24 = m[1]; min = m[2]; sec = m[3];
                    }
                    else {
                        m = str.match(/(\d+):(\d+).*/i);
                        if (m) {
                            min = m[1]; sec = m[2];
                        }
                        else {
                            m = str.match(/(\d+).*/i);
                            if (m) {
                                sec = m[1];
                            }
                        }
                    }
                }
            }
        }

        var date = new Date();
        date.setTime(Date.UTC(y, mon-1, d, 1, 1, 0));

        var dayWLZ = date.getDate();
        if (dayWLZ >= 0 && dayWLZ <=9)
            dayWLZ = "0" + dayWLZ;

        var temp1 = new Array();

        for (var i=0; i<format.length; i++) {

             var ch = format.charAt(i);

             if (ch == "H")
                 temp1.push(h24);
             else if (ch == "i")
                 temp1.push(min);
             else if (ch == "s")
                 temp1.push(sec);
             else if (ch == "j")
                 temp1.push(date.getDate());
             else if (ch == "d")
                 temp1.push(dayWLZ);
             else if (ch == "M")
                 temp1.push(this.fMonthsShort[date.getMonth()]);
             else if (ch == "F")
                 temp1.push(this.fMonthsFull[date.getMonth()]);
             else if (ch == "Y")
                 temp1.push(date.getFullYear());
             else if (ch == "D")
                 temp1.push(this.fWeekdaysShort[date.getDay()==0?6:date.getDay()-1]);
             else if (ch == "l")
                 temp1.push(this.fWeekdaysFull[date.getDay()==0?6:date.getDay()-1]);
             else
                 temp1.push(ch);
        }

        return temp1.join("");
    },


    /**
     * Change page index
     */
    changeIndex: function(aPageIndex) {
        this.fEventType = "changeIndex";
        this.load(aPageIndex);
    },


    /**
     * Go to the previous page
     */
    prev: function() {
        this.changeIndex(this.getPageIndex()-1);
    },


    /**
     * Go to the next page
     */
    next: function() {
        this.changeIndex(this.getPageIndex()+1);
    },


    /**
     * Sort by
     */
    sortBy: function(column, direction) {
        if (this.fSortColumn == column) {
            if (this.fSortDirection == "asc") {
                this.fSortDirection = "desc";
            }
            else {
                this.fSortDirection = "asc";
            }
        }
        else {
            this.fSortColumn = column;
            this.fSortDirection = 'asc';
        }

        if (direction && (direction == 'asc' || direction == 'desc')) {
            this.fSortDirection = direction;
        }

        this.fEventType = "sort";
        this.load(1);
    },


    /**
     * Commit edit
     */
    commitEdit: function() {
        if (!this.fActiveEditElement) return;

        if (this.fActiveEditElement.isRow && this.OnRowCommitEdit) {
            this.OnRowCommitEdit(this.fActiveEditElement);
        }
        else if (this.fActiveEditElement.isCell && this.OnCellCommitEdit) {
            this.OnCellCommitEdit(this.fActiveEditElement);
        }
    },


    /**
     * Cancel edit
     */
    cancelEdit: function() {
        this.setEditMode(false);
        if (this.fActiveEditElement) {
            this.fActiveEditElement.cancelEdit();
            this.fActiveEditElement = null;
        }
    }

});




/**
 * TDataGridRow
 */
var TDataGridRow = TClass.extend(TWebControl, {

    /**
     * Constructor
     */
    initialize: function(id, aDomElement, aData) {
        $C(TWebControl).initialize.call(this, id);

        this.isRow = true;
        this.domElement = aDomElement;

        this.data = aData;
        this.fCells = new Array();
    },


    /**
     * Add cell
     */
    addCell: function(key, aCell) {
        this.fCells[key] = aCell;
    },


    /**
     * Get number of cells
     */
    size: function() {
        return this.fCells.length;
    },


    /**
     * Get cell by position
     */
    cellByPos: function(pos) {
        return this.fCells[pos];
    },


    /**
     * Get cell by id
     */
    cellById: function(id) {
        for (var i=0; i < this.size(); i++) {
            var cell = this.cellByPos(i);
            if (cell.getProperty("id") == id) {
                return cell;
            }
        }

        return null;
    },


    /**
     * Simulate click
     */
    click: function() {
        this.getParent().rowClick(this.getName());
    },


    /**
     * Edit
     */
    edit: function() {
        for (var i=0; i < this.size(); i++) {
            this.cellByPos(i).edit();
        }

        this.getParent().fActiveEditElement = this;
    },


    /**
     * Cancel edit
     */
    cancelEdit: function() {
        for (var i=0; i < this.size(); i++) {
            this.cellByPos(i).cancelEdit();
        }
    },


    /**
     * Get fields
     */
    getFields: function() {
        var data = {};
        for (var i=0; i < this.size(); i++) {
            var cell = this.cellByPos(i);
            var key = cell.getFieldKey();
            var val = cell.getFieldValue();
            if (key != null && val != null) {
                data[key] = val;
            }
        }

        return data;
    }
});




/**
 * TDataGridCell
 */
var TDataGridCell = TClass.extend(TWebControl, {

    /**
     * Constructor
     */
    initialize: function(id, aDomElement, aProperties) {
        $C(TWebControl).initialize.call(this, id);

        this.isCell = true;
        this.domElement = aDomElement;

        for (var k in aProperties) {
           this.setProperty(k, aProperties[k]);
        }

        this.fFieldName = id + "_edit";
        this.fTempKeyName = id + "_tmp_value";
    },


    /**
     * Edit
     */
    edit: function() {
        var editable = this.getProperty("editable");
        if (!editable) return;

        var editType = editable["type"];
        if (!editType) return;

        this.getParent().getParent().fActiveEditElement = this;
        this.getParent().getParent().setEditMode(true);

        var fieldBoxName = this.fFieldName + "_box";
        var fieldValue = elem(this.getName()).innerHTML;
        if (editable["value"]) {
            var key = editable["value"].replace(/\{/, "").replace(/#/, "").replace(/\}/, "");
            fieldValue = this.fParent.data[key];
        }

        this.setProperty(this.fTempKeyName, elem(this.getName()).innerHTML);

        var dim = this.getDimension();

        if (editType == "string" || editType == "integer" || editType == "number") {
            this.removePadding();
            dim = this.getDimension();
            if (page.agent.isIE() || page.agent.isChrome()) {
                this.domElement.innerHTML = "<input type='text' id='" + this.fFieldName + "' class='inputText' style='width:" + (dim["w"]-0) + "px;height:100%' />";
            }
            else {
                this.domElement.innerHTML = "<input type='text' id='" + this.fFieldName + "' class='inputText' style='width:" + (dim["w"]-0) + "px;height:" + (dim["h"]-0) + "px' />";
            }
            elem(this.fFieldName).value = fieldValue;
        }
        else if (editType == "select") {
            this.removePadding();
            dim = this.getDimension();
            this.domElement.innerHTML = this.buildSelectTag(this.fFieldName, page.model.getProperty(editable["source"]), fieldValue, dim);
        }
        else if (editType == "checkbox") {
            this.removePaddingY();
            this.domElement.innerHTML = "<input type='checkbox' id='" + this.fFieldName + "' class='inputCheckbox' />";
            if (fieldValue == "t" || fieldValue == "on" || fieldValue == "true" || fieldValue == "1") {
                elem(this.fFieldName).checked = "checked";
            }
        }
        else if (editType == "date") {
            this.removePadding();
            this.domElement.innerHTML = "<span id='" + fieldBoxName + "'></span>";
            page.ajax.requestControl(fieldBoxName, this.fFieldName, "date_and_time", "TDateField", {"value" : fieldValue});
            page.ajax.bindRequestedControls();
        }
        else if (editType == "datetime") {
            this.removePadding();
            this.domElement.innerHTML = "<span id='" + fieldBoxName + "'></span>";
            page.ajax.requestControl(fieldBoxName, this.fFieldName, "date_and_time", "TDateTimeField", {"value" : fieldValue});
            page.ajax.bindRequestedControls();
        }
    },


    /**
     * Remove padding
     */
    removePadding: function() {
        this.removePaddingX();
        this.removePaddingY();
    },


    /**
     * Remove padding
     */
    removePaddingX: function() {
        var computedStyle = null;
        if (document.defaultView && document.defaultView.getComputedStyle) {
            computedStyle = document.defaultView.getComputedStyle(this.domElement, "");
        }
        else if (this.domElement.currentStyle) {
            computedStyle = this.domElement.currentStyle;
        }

        var padd = "1px";

        this.fTempPaddingRight = null;
        if (computedStyle && computedStyle.paddingRight) {
            this.fTempPaddingRight = computedStyle.paddingRight;
            this.domElement.style.paddingRight = padd;
        }

        this.fTempPaddingLeft = null;
        if (computedStyle && computedStyle.paddingLeft) {
            this.fTempPaddingLeft = computedStyle.paddingLeft;
            this.domElement.style.paddingLeft = padd;
        }
    },


    /**
     * Remove padding
     */
    removePaddingY: function() {
        var computedStyle = null;
        if (document.defaultView && document.defaultView.getComputedStyle) {
            computedStyle = document.defaultView.getComputedStyle(this.domElement, "");
        }
        else if (this.domElement.currentStyle) {
            computedStyle = this.domElement.currentStyle;
        }

        var padd = "1px";
        if (page.agent.isIE() || page.agent.isChrome()) {
            padd = "0px";
        }

        this.fTempPaddingTop = null;
        if (computedStyle && computedStyle.paddingTop) {
            this.fTempPaddingTop = computedStyle.paddingTop;
            this.domElement.style.paddingTop = padd;
        }

        this.fTempPaddingBottom = null;
        if (computedStyle && computedStyle.paddingBottom) {
            this.fTempPaddingBottom = computedStyle.paddingBottom;
            this.domElement.style.paddingBottom = padd;
        }
    },


    /**
     * Cancel edit
     */
    cancelEdit: function() {
        if (this.hasProperty(this.fTempKeyName)) {
            this.domElement.innerHTML = this.getProperty(this.fTempKeyName);
            this.removeProperty(this.fTempKeyName);
        }

        if (this.fTempPaddingTop) {
            this.domElement.style.paddingTop = this.fTempPaddingTop;
            this.fTempPaddingTop = null;
        }

        if (this.fTempPaddingRight) {
            this.domElement.style.paddingRight = this.fTempPaddingRight;
            this.fTempPaddingRight = null;
        }

        if (this.fTempPaddingBottom) {
            this.domElement.style.paddingBottom = this.fTempPaddingBottom;
            this.fTempPaddingBottom = null;
        }

        if (this.fTempPaddingLeft) {
            this.domElement.style.paddingLeft = this.fTempPaddingLeft;
            this.fTempPaddingLeft = null;
        }

        page.destroyWidget(this.fFieldName);
    },


    /**
     * Get field key
     */
    getFieldKey: function() {
        var editable = this.getProperty("editable");
        if (!editable) return null;

        if (!editable["key"]) {
            alert("No 'key' is found for this editable field");
            return null;
        }

        return editable["key"];
    },


    /**
     * Get field value
     */
    getFieldValue: function() {
        return getElementValue(this.fFieldName);
    },


    /**
     * Build select tag
     */
    buildSelectTag: function(controlName, options, value, dim) {
        if (!options) options = new Object();

        var html = "<select id='" + controlName + "' class='inputSelect' style='width:" + (dim["w"]) + "px;height:" + (dim["h"]-0) + "px' />";
        if (page.agent.isIE() || page.agent.isChrome()) {
            html = "<select id='" + controlName + "' class='inputSelect' style='width:100%;height:100%' />";
        }

        for (var i in options) {
            if (value && i==value) {
                html += "<option value='" + i + "' selected>" + options[i] + "</option>";
            }
            else {
                html += "<option value='" + i + "'>" + options[i] + "</option>";
            }
        }
        html += "</select>";
        return html;
    }
});




/**
 * TDataGridPager
 */
var TDataGridPager = TClass.extend(TWebControl, {

    /**
     * Constructor
     */
    initialize: function(name) {
        $C(TWebControl).initialize.call(this, name);

        this.fNumberOfPages = 1;
        this.fPageIndex = 1;
    },


    /**
     * Set pages
     */
    setPages: function(aValue) {
        this.fNumberOfPages = aValue;
    },


    /**
     * Set page index
     */
    setPageIndex: function(aValue) {
        this.fPageIndex = aValue;
    },


    /**
     * Get page index
     */
    getPageIndex: function() {
       return this.fPageIndex;
    },


    /**
     * To html
     */
    toHtml: function() {
        if (this.fNumberOfPages <= 1) {
           return "";
       }

       var html = "";
       html += "<table cellspacing='0' cellpadding='0' align='left'><tr><td class='pager'>";
       html += "<table cellspacing='0' cellpadding='0'><tr>";

       if (this.fPageIndex > 1) {
           html += "<td class='prev'><a href='#' onclick='" + this.getName() + ".prev();return false;'>" + this.i18n("prev") + "</a></td>";
       }

       html += "<td class='center'><select onchange='" + this.getName() + ".changeIndex(this.selectedIndex+1);return false;'>";

       for (var i=1; i <= this.fNumberOfPages; i++) {
          if (i == this.fPageIndex) {
              html += "<option value='" + i + "' selected>" + this.i18n("Page") + i + " " + this.i18n('Of') + " " + this.fNumberOfPages + "</option>";
          }
          else {
              html += "<option value='" + i + "'>" + this.i18n("Page") + i + " " + this.i18n('Of') + " " + this.fNumberOfPages + "</option>";
          }
       }

       html += "</select></td>";

       if (this.fPageIndex < this.fNumberOfPages) {
           html += "<td class='next'><a href='#' onclick='" + this.getName() + ".next();return false;'>" + this.i18n("next") + "</a></td>";
       }

       html += "</tr></table>";
       html += "</td></tr></table>";

       return html;
    }
});