/**
 * 创建一个{@link IKE.CustomForm}对象
 * @class 自定义表单
 * @augments IKE.Control
 * @constructs
 */
IKE.CustomForm = Class(IKE.Control, {
    /**
    * 自定义表单table元素
    * @private
    */
    initRows:5,
    initCols:4,
    table: null,
    body: null,
    options: null,
    tableID:null,
    bodyID:null,
    selectedArray: new Array(),
    currentRow: null,
    initialize: function(tableID, bodyID, options) {
        this.tableID=tableID;
        this.bodyID=bodyID;
        this.createTable();
        if (typeof options != "undefined")
            this.setOptions(options);
        else this.setOptions();
        this.initializeControlsAndEvents();
    },
    createTable: function() {
        for (var i = 1; i <=this.initRows; i++) {  
            var row = $("<tr/>").attr("id", i).appendTo($("#" + this.bodyID));
            for (var j = 1; j <= this.initCols; j++) {
                
                 if(j==1&& i==1)
                 {
                    var cell = $("<th/>").attr("id", i + "/" + j).html("").addClass("disedit").addClass("firstRow").appendTo(row);
                 }
                 if(j==1&& i!=1) 
                 {
                    var cell = $("<td/>").attr("id", i + "/" + j).html("第"+(i-1)+"行").addClass("disedit").css({"width":50,"backgroundColor":"#F3F5F8"}).appendTo(row);
                 }
                   if(j!=1&& i==1)
                 {
                    var cell = $("<th/>").attr("id", i + "/" + j).html("第"+(j-1)+"列").addClass("disedit").addClass("firstRow").attr("align","center").appendTo(row);
                 }
                   if(j!=1&& i!=1)
                 {
                    var cell = $("<td/>").attr("id", i + "/" + j).html(i + "/" + j).appendTo(row);
                 }
            }
        }
        this.table = document.getElementById(this.tableID);  
        this.body = document.getElementById(this.bodyID);
    },
    setOptions: function(options) {
        this.options = {
            hoverColor: "#FFFDD7",        //移动时背景色   
            activeColor: "#FFFDD7",       //选中时背景色
            normalColor: "transparent",
            hover: true,                  //是否开启移动行背景色   
            choose: true,                 //是否开启选择   
            multiple: true,              //是否开启多选,开启后按Ctrl可以多选,取消功能需要同时开启
            editable:true,   
            title: true,                 //是否提示title   
            cancel: true,                //是否开启取消功能   
            dclick: true,                //是否双击   
            onClick: function() { },       //选中时附加方法   
            onCancel: function() { },       //取消选择时附加方法，此时取消功能必须开启   
            onMove: function() { },         //鼠标移动事件   
            onDClick: function() { }       //双击   
        };
        $.extend(this.options, options || {});

    },
    initializeControlsAndEvents: function() {
        this.OnClick = this.options.onClick;
        this.OnCancel = this.options.onCancel;
        this.OnMove = this.options.onMove;
        this.AddMouseEvent();
        this.resize();

    },
    selectedIndex: function(elem) {
        for (var i = 0; i < this.selectedArray.length; i++) {
            if (elem == this.selectedArray[i]) {
                return i;
            }
        }
        return -1;
    },
    //获取当前事件对象   
    getCurrentElement: function(e) {
        var elem = e.srcElement || e.target;
        if (elem.tagName.toUpperCase() == "TD") {
            return elem;
        }
        return null;
    },
    //    mouseOver: function(e) {
    //        //清除选中内容   
    //        document.selection ? document.selection.empty() : window.getSelection();
    //        var elem = this.getCurrentElement(e);
    //        if (elem == null) { return; }
    //        if (this.currentRow != null) {
    //            if (this.SelectedIndex(this.currentRow) < 0) {
    //                this.currentRow.style.backgroundColor = "transparent";
    //            }
    //            else {
    //                this.currentRow.style.backgroundColor = this.options.activeColor;
    //            }
    //        }
    //        elem.style.backgroundColor = this.selectedIndex(elem) < 0 ? this.options.hoverColor : this.options.activeColor;
    //        this.currentRow = elem;
    //        this.OnMove();
    //    },
    //移出表格后，恢复原色   
    //    mouseOut: function() {
    //        if (this.currentRow != null && this.selectedIndex(this.currentRow) < 0) {
    //            this.currentRow.style.backgroundColor = "transparent";
    //            this.currentRow = null;
    //        }
    //    },
    addSelected: function(elem) {
        this.selectedArray.push(elem);
    },
    //从集合中移除   
    removeSelected: function(elem) {
        var index = this.selectedIndex(elem);
        this.selectedArray.splice(index, 1);
    },
    mouseClick: function(e) {
        var elem = this.getCurrentElement(e);
        if (elem == null ||elem.className=="disedit") { return; };
        var index = this.selectedIndex(elem);
        if (index < 0) {
            if (this.options.multiple && this.options.cancel) {
                this.addSelected(elem);
            }
            else {
                this.clear();
                this.addSelected(elem);
            }
            elem.style.backgroundColor = this.options.activeColor;
            this.OnClick();
        }
        else if (this.options.cancel) {
            elem.style.backgroundColor = this.options.hover ? this.options.hoverColor : "transparent";
            this.removeSelected(elem);
            this.OnCancel();
        }
    },
    resize:function()
    { 
        $("#"+this.tableID).tableresizer({
                    row_border:"2px solid #CCC",
                    col_border:"2px solid #CCC"
                });
    },
    Editable:function(sender){   
            var elem=this.getCurrentElement(sender);   
            if(elem==null){return;}           
            if(!elem.lastChild || elem.lastChild.tagName != "TEXTAREA")   
            {   
                var box = document.createElement("textarea");   
                box.style.cssText = "background-color:transparent;border:none; font:12pt 宋体;margin:-2pt -1pt;width:100%; overflow:hidden";   
                box.rows = 1;   
                if(elem.align) box.style.textAlign = elem.align;   
                box.defaultValue = box.value = elem.innerHTML;   
                elem.innerHTML = "";   
                elem.appendChild(box);   
                box.onpropertychange = function()   
                {   
                    if(this.value) this.style.posHeight = this.scrollHeight;   
                }   
                box.onblur = function()   
               {   
                    if(this.value == this.defaultValue)   
                    {   
                        elem.innerText = this.value;   
                        elem.bgColor = "";   
                    }   
                }   
                box.focus();   
                elem.bgColor = "#effbff";   
           }         
        },         
    AddMouseEvent: function() {
        var me = this;
        if (this.options.hover) {
            //$("tbody tr td", $(this.table)).hover(function() {$(this).css("backgroundColor",me.options.hoverColor) }, function() { $(this).css("backgroundColor", me.options.normalColor); });
        }
        if (this.options.choose) {
            $(this.table).click(function(e) { me.mouseClick(e); });
        }
        if(this.options.editable){   
                //$(this.table).dblclick(function(e){me.Editable(e);});   
        }     
    },
    getTableCols: function(table) {
        var tableObject = table;
        if (!tableObject.rows || !tableObject.rows[0] || !tableObject.rows[0].cells) {
            return 0;
        }
        var cells = tableObject.rows[0].cells;
        var cols = 0;
        for (var col = 0; col < cells.length; col++) {
            if (cells[col].colSpan && cells[col].colSpan > 1) {
                cols = cols + cells[col].colSpan;
            }
            else {
                cols = cols + 1;
            }
        }
        return cols;
    },
    addRow: function() {
        var length = this.table.rows.length;
        var row = $("<tr/>").attr("id", (length + 1)).appendTo($(this.body));
        var colNumber = this.getTableCols(this.table);
        for (i = 1; i <= colNumber; i++) {
           //var cell = $("<td/>").attr("id", row.id + "/" + i).html((length + 1) + "/" + i).appendTo(row);
                 if(i==1) 
                 {
                    var cell = $("<td/>").attr("id", (length + 1) + "/" + i).html("第"+(length)+"行").addClass("disedit").css({"width":50,"backgroundColor":"#F3F5F8"}).appendTo(row);
                 }
                   if( i!=1)
                 {
                    var cell = $("<td/>").attr("id", (length + 1) + "/" + i).html((length + 1) + "/" + i).appendTo(row);
                 }
        }
        this.resize();
    },
    removeRow: function() {
        var length = this.table.rows.length;
        if (length <= 2) { alert("表格的行数不允许少于1"); }
        else {
            var row = $("#" + length);
            if (row) { $(row).remove(); }
        }
    },
    addColumn: function() {
        var length = this.getTableCols(this.table) + 1;
        for (var i = 0; i < this.table.rows.length; i++) {
                 if(i==0)
                 {
                    var cell = $("<th/>").attr("id", (i + 1) + "/" + length).html("第"+(length-1)+"列").addClass("disedit").addClass("firstRow").attr("align","center").appendTo($(this.table.rows[i]));
                 }
                 if(i!=0)
                 {
                    var cell = $("<td/>").attr("id", (i + 1) + "/" + length).html((i + 1) + "/" + length).appendTo($(this.table.rows[i]));
                 }
        }
    },
    removeColumn: function() {
        var colNumber = this.getTableCols(this.table);
        if (colNumber <= 2) { alert("表格的列数不允许少于1"); }
        else {
            for (var i = 0; i < this.table.rows.length; i++) {
                var cell = document.getElementById((i + 1) + "/" + (colNumber))
                if (cell) {
                    var parentElement = cell.parentNode;
                    if (parentElement) {
                        parentElement.removeChild(cell);
                    }
                }     
            }
        }
    },
    sortSelected: function() {
        if (this.selectedArray.length > 2) {
            this.selectedArray.sort(function(x, y) {
                var x1 = x.id.split("/");
                var y1 = y.id.split("/");
                return (parseInt(x1[0]) - parseInt(y1[0]) || parseInt(x1[1]) - parseInt(y1[1]));
            })
        } else {
            return;
        }
    },
    findCellById: function(cellID) {
        for (var i = 0; i < this.selectedArray.length; i++) {
            if (this.selectedArray[i].id == cellID) {
                return i;
            }
        }
        return -1;
    },
    getMaxRowIndex: function() {
        var MaxRowNum = 0;
        for (var i = 0; i < this.selectedArray.length; i++) {
            if (parseInt(this.selectedArray[i].id.split("/")[0]) > MaxRowNum) {
                MaxRowNum = parseInt(this.selectedArray[i].id.split("/")[0]);
            }
        }
        return MaxRowNum;
    },
    getMaxCellIndex: function() {
        var MaxColNum = 0;
        for (var i = 0; i < this.selectedArray.length; i++) {
            if (parseInt(this.selectedArray[i].id.split("/")[1]) > MaxColNum) {
                MaxColNum = parseInt(this.selectedArray[i].id.split("/")[1]);
            }
        }
        return MaxColNum;
    },
    getMinRowIndex: function() {
        var MinRowNum = 999999;
        for (var i = 0; i < this.selectedArray.length; i++) {
            if (parseInt(this.selectedArray[i].id.split("/")[0]) < MinRowNum) {
                MinRowNum = parseInt(this.selectedArray[i].id.split("/")[0]);
            }
        }
        return MinRowNum;
    },
    getMinCellIndex: function() {
        var MinColNum = 999999;
        for (var i = 0; i < this.selectedArray.length; i++) {
            if (parseInt(this.selectedArray[i].id.split("/")[1]) < MinColNum) {
                MinColNum = parseInt(this.selectedArray[i].id.split("/")[1]);
            }
        }
        return MinColNum;
    },
    checkMergeCells: function() {
        if (this.selectedArray.length < 2) {
            alert("您所选择的单元格无法合并！");
            return false;
        }
        //循环判断所选单元格是否组成一个矩形，只有形成一个矩形的单元格才能合并
        var addCellArray = [];
        for (var k = 0; k < this.selectedArray.length; k++) {
           
            if ((this.selectedArray[k].colSpan > 1) && (this.selectedArray[k].rowSpan > 1)) {
                var cellPoint = this.selectedArray[k].id.split("/")
                var colNum = parseInt(cellPoint[1]);
                var rowNum = parseInt(cellPoint[0]);
                for (var m = this.selectedArray[k].colSpan; m > 0; m--) {
                    for (var j = this.selectedArray[k].rowSpan; j > 0; j--) {
                        var cell = document.createElement("td");
                        var cellY = colNum + m - 1;
                        var cellX = rowNum + j - 1;
                        cell.id = cellX + "/" + cellY;

                        if (this.findCellById(cell.id) < 0) {
                            addCellArray.push(cell);
                        }
                    }
                }
            } else {        
                if (this.selectedArray[k].colSpan > 1) {
                    var cellPoint = this.selectedArray[k].id.split("/")
                    var colNum = parseInt(cellPoint[1]);

                    for (var m = this.selectedArray[k].colSpan; m > 0; m--) {
                        var cell = document.createElement("td");
                        var cellY = colNum + m - 1;
                        cell.id = cellPoint[0] + "/" + cellY;

                        if (this.findCellById(cell.id) < 0) {
                            addCellArray.push(cell);
                        }
                    }
                }
                if (this.selectedArray[k].rowSpan > 1) {
                    var cellPoint = this.selectedArray[k].id.split("/")
                    var rowNum = parseInt(cellPoint[0]);
                    for (var m = this.selectedArray[k].rowSpan; m > 0; m--) {
                        var cell = document.createElement("td");
                        var cellX = rowNum + m - 1;
                        cell.id = cellX + "/" + cellPoint[1];

                        if (this.findCellById(cell.id) < 0) {
                            addCellArray.push(cell);
                        }
                    }
                }
                
            }
        }
        for (var k = 0; k < addCellArray.length; k++) { this.selectedArray.push(addCellArray[k]); }
        //对所选的单元格进行排序               
        this.sortSelected();
        //取得最小的单元格和最大的单元格   
        var minRow = this.getMinRowIndex();
        var minCol = this.getMinCellIndex();
        var maxRow = this.getMaxRowIndex();
        var maxCol = this.getMaxCellIndex();
        var canMerge = 0;
        for (var i = minRow; i <= maxRow; i++) {
            for (var j = minCol; j <= maxCol; j++) {
                var isMerge = false;
                var cellId = i + "/" + j;
                for (var k = 0; k < this.selectedArray.length; k++) {
                    if (this.selectedArray[k].id == cellId) {
                        isMerge = true;
                        break;
                    }
                }
                if (isMerge == false) {
                    canMerge = canMerge + 1;
                    break;
                }
            }
        }
        return (canMerge > 0) ? false : true;
    },
    removeAllSelected: function() {
        var count = this.selectedArray.length;
        this.selectedArray.splice(0, count);
    },
    clear: function() {
        for (var i = 0; i < this.selectedArray.length; i++) {
            this.selectedArray[i].style.backgroundColor = "transparent";
        }
        this.removeAllSelected();
    },
    reDesign:function(rows,cells,options)
    {   
        this.initRows=rows||5;
        this.initCols=cells||4;
        this.createTable();
        if (typeof options != "undefined")
            this.setOptions(options);
        else this.setOptions();
        this.initializeControlsAndEvents();  
    },
    remove: function() {
        for (var i = 0; i < this.selectedArray.length; i++) {
            this.selectedArray[i].style.backgroundColor = "transparent";
        }
        $(this.body).empty();
        this.removeAllSelected();
    },
    mergeCells: function() {
        if (!this.checkMergeCells()) {
            alert("您所选择的单元格无法合并！");
            this.clear();
            this.removeAllSelected();
            return false;
        }
        var minRow = this.getMinRowIndex();
        var minCol = this.getMinCellIndex();
        var maxRow = this.getMaxRowIndex();
        var maxCol = this.getMaxCellIndex();
        //同行合并   
        if (minRow == maxRow) {
            var distance = parseInt(maxCol) - parseInt(minCol); //得到列差值      
            var tmpCell =document.getElementById(minRow + "/" + minCol);
            tmpCell.colSpan = distance + 1;
            for (var i = 0; i < this.selectedArray.length; i++) {
                if (this.selectedArray[i].id != tmpCell.id) {
                    var parentElement = this.selectedArray[i].parentNode;
                    if (parentElement) {
                        parentElement.removeChild(this.selectedArray[i]);
                    }
                }
            }
        }

        //同列合并   
        if (minCol == maxCol) {
            var distance = parseInt(maxRow) - parseInt(minRow); //得到列差值
            var tmpCell = document.getElementById(minRow + "/" + minCol);
            tmpCell.rowSpan = distance + 1;
            for (var i = 0; i < this.selectedArray.length; i++) {
                if (this.selectedArray[i].id != tmpCell.id) {
                    var parentElement = this.selectedArray[i].parentNode;
                    if (parentElement) {
                        parentElement.removeChild(this.selectedArray[i]);
                    }
                }
            }
        }
        //多行多列合并   
        if ((minRow != maxRow) && (minCol != maxCol)) {
            var row_distance = parseInt(maxRow) - parseInt(minRow); //得到行差值   
            var col_distance = parseInt(maxCol) - parseInt(minCol); //得到列差值
            var tmpCell = document.getElementById(minRow + "/" + minCol);
            tmpCell.rowSpan = row_distance + 1; //行合并   
            tmpCell.colSpan = col_distance + 1; //列合并     
            for (var i = 0; i < this.selectedArray.length; i++) {
                if (this.selectedArray[i].id != tmpCell.id) {
                    var parentElement = this.selectedArray[i].parentNode;
                    if (parentElement) {
                        parentElement.removeChild(this.selectedArray[i]);
                    }
                }
            }
        }
        this.clear();
        this.removeAllSelected();
    },
     splitCells:function(){   
            if(this.selectedArray.length<=0){   
                alert("请选择要拆分的单元格！");   
            }else{   
                for(var i =0;i<this.selectedArray.length;i++){   
                    if((this.selectedArray[i].colSpan>1)&&(this.selectedArray[i].rowSpan>1)){   
                       var cellPoint = this.selectedArray[i].id.split("/")   
                        var colNum = parseInt(cellPoint[1]);   
                        var rowNum = parseInt(cellPoint[0]);   
                       for(var m = this.selectedArray[i].colSpan;m>0;m--){   
                          for(var j = this.selectedArray[i].rowSpan;j>0;j--){    
                                var cellY = colNum+m-1;   
                                var cellX = rowNum+j-1;   
                               if(document.getElementById(cellX+"/"+cellY)){   
                              }else{   
                                    var insertCellNum = cellY-1;   
                                  for(var d=cellY;d>=0;d--){   
                                       if(document.getElementById(cellX+"/"+d)){   
                                            insertCellNum = d;   
                                           break;   
                                       }   
                                   }   
                                    var x=document.getElementById(cellX+"").insertCell(insertCellNum);   
                                    x.id =cellX+"/"+cellY;   
                                    x.innerHTML=cellX+"/"+cellY;                                                                     
                                }   
                           }   
                       }   
                       this.selectedArray[i].rowSpan = 1;   
                       this.selectedArray[i].colSpan = 1;   
                    }else{   
                        if(this.selectedArray[i].colSpan>1 ){   
                            var cellPoint = this.selectedArray[i].id.split("/")   
                            var colNum = parseInt(cellPoint[1]);   
                            for(var m = this.selectedArray[i].colSpan;m>0;m--){                                      
                                var cellY = colNum+m-1;                                   
                               if(document.getElementById(cellPoint[0]+"/"+cellY)){   
                                }else{                                   
                                  var x=document.getElementById(cellPoint[0]+"").insertCell(cellY-1);   
                                    x.id =cellPoint[0]+"/"+cellY;   
                                    x.innerHTML=cellPoint[0]+"/"+cellY;                                                                   
                                }   
                           }   
                           this.selectedArray[i].colSpan = 1;   
                        }   
                       if(this.selectedArray[i].rowSpan>1){   
                            var cellPoint = this.selectedArray[i].id.split("/")   
                            var rowNum = parseInt(cellPoint[0]);       
                            for(var m = this.selectedArray[i].rowSpan;m>0;m--){       
                                var cellX = rowNum+m-1;    
                                if(document.getElementById(cellX+"/"+cellPoint[1])){   
                                }else{   
                                    var x=document.getElementById(cellX+"").insertCell(cellPoint[1]-1);   
                                     x.id =cellX+"/"+cellPoint[1];   
                                     x.innerHTML=cellX+"/"+cellPoint[1];                                                                       
                                }   
                            }                                
                            this.selectedArray[i].rowSpan = 1;   
                        }   
                    }   
                }   
                this.clear();   
                this.removeAllSelected();   
            }   
        },             
       getDesignResult:function(){     
            return this.table.parentNode.innerHTML          
        } 

});