(function($) {
    $.ui = $.ui || {};
    $.fn.editortable = function(opts) {
        var myeditortable = false;

        if (this[0])
            myeditortable = new $.ui.editortable(opts, this[0]);

        return myeditortable;
    };
    $.ui.editortable = function(option, ele) {
        var cofig = $.extend(
         {
             items: [],
             data: null,
             width: 400,
             height: 400,
             formposition: 0,
             addRow: true,
             addWord: '添加行',
             selectRow: true,
             selectWord: '选择行',
             selectEvent: null,
             delRow: true,
             showDelRow: true,
             template: null,
             rails: true,
             storeDel: "",
             showHeader: true
         }, option);
        //--------defined id----------//
        var tableID = "myeditor" + $(ele).attr("id");
        var containerID = "myContainerID" + $(ele).attr("id");
        var toolbarID = "myToolbarID" + $(ele).attr("id");
        var addbtnID = "myaddBtnID" + $(ele).attr("id");
        var selectbtnID = "myselectBtnID" + $(ele).attr("id");
        //add container
        $(ele).html("<div id=\"" + containerID + "\" class=\"div-editor-container\"></div>");
        //add toolbar
        $("#" + containerID).width(cofig.width);
        $("#" + containerID).prepend("<div class=\"div-editor-toolbar\" id=\"" + toolbarID + "\"></div>");
        //render header
        var rowtemplate = "";
        RenderHeaderAndmakeRowTemplate();
        //initial
        InitializeRow();
        //bind delete event
        showDelRow();
        // Allow to add rows
        //判断是自定义事件还是默认
        if (cofig.addRow) {

            $("#" + toolbarID).append("<a id=\"" + addbtnID + "\" class=\"div-editor-tool-btn\" href=\"javascript:void(0);\"><span class=\"Add\" title=\"" + cofig.addWord + "\">" + cofig.addWord + "</span></a>");
            $("#" + addbtnID).click(function() {
                addRow(null, true);
                return false;
            });
        }
        //判断是自定义事件还是默认
        if (cofig.selectRow) {
            $("#" + toolbarID).append("<a id=\"" + selectbtnID + "\" class=\"div-editor-tool-btn\" href=\"javascript:void(0);\"><span class=\"Selected\" title=\"" + cofig.selectWord + "\">" + cofig.selectWord + "</span></a>");
            $("#" + selectbtnID).click(function() {
                if (cofig.selectEvent && $.isFunction(cofig.selectEvent)) {
                    cofig.selectEvent.call($(this));

                }
                return false;
            });
        }

        if (cofig.delRow) {

            //allow to delete at row end
            if (cofig.showDelRow) {
                $("#" + tableID).find('tr:first').each(function(index, elem) {
                    $(elem).append("<th class=\"div-th-delete\">删除</th>");
                });

            }
            //allow to delete at toolbar
            //$("#div-editor-toolbar").append("<a id=\"div-editor-tool-delete\" class=\"div-editor-tool-btn\" href=\"javascript:void(0);\"><span class=\"Delete\" title=\"删除行\">删除行</span></a>");
            //                $("#div-editor-tool-delete").click(function() {
            //                    var selectdeRow = SelectedRow();
            //                    if (selectdeRow == "") { alert("请选择要删除的行"); }
            //                    else {

            //                        var rowArray = selectdeRow.split(",");
            //                        for (var i = 0; i < rowArray.length; i++) {
            //                            //alert(rowArray[i]);
            //                            var delRowHtml = $("#div-editor-table").find("input[rowIndex='" + rowArray[i] + "']");
            //                             
            //                            //alert($(delRowHtml).parents('tr').eq(0).html())
            //                            DeleteRow($(delRowHtml).parents('tr').eq(0));
            //                        }
            //                    }
            //                    return true;
            //                });
        }

        // Allow to delete rows
        function showDelRow() {
            $("#" + tableID).find('a.div-row-delete').live("click", function() {
                DeleteRow($(this).parents('tr').eq(0));
                return true;

            });
        }

        //            //Allow to row click
        //            RowOnclick();
        //            //Allow to click Row
        //            function RowOnclick() {
        //                $("#div-editor-table").find('tr:not(.disableedit)').live("dblclick", function() { alert($(this).html()) })
        //            }
        function RenderHeaderAndmakeRowTemplate() {
            var header = [];
            var template = [];

            header.push("<div class=\"clear\"></div><div class=\"div-table-container\">");
            header.push("<table class=\"div-editor-table\" id=\"" + tableID + "\" ><thead><tr class=\"disableedit\">");
            template.push("<tr>");
            for (var i = 0, l = cofig.items.length; i < l; i++) {
                var item = cofig.items[i];
                header.push("<th class=\"" + item.thClass + "\" col=\"" + item.thName + "\">" + item.colName + "</th>");
                template.push("<td>");
                template.push(makeTemplate(item.type, item.colID, item.colClass, "", true));
                template.push("</td>")
            }
            header.push("</tr></thead><table></div>");
            template.push("</tr>");
            rowtemplate = template.join("");
            cofig.template = rowtemplate;
            $("#" + containerID).append(header.join(""));
            //是否显示标题
            if (!cofig.showHeader) {
                $("#" + tableID).find('tr:first').hide()

            }
            header = null;
            template = null;
        }
        function makeTemplate(tempType, name, cssClass, value, flag) {
            switch (tempType) {
                case "sltinput":
                    if (flag) {
                        return "<input name=\"" + name + "\" attrType=\"sltinput\"  type=\"text\" value=\"" + value + "\" class=\"" + cssClass + "\" />";
                    }
                    else {
                        return "<input name=\"" + name + "\"  readonly = \"readonly\" attrType=\"sltinput\"  type=\"text\" value=\"" + value + "\" class=\"" + cssClass + "\" />";
                    }

                    break;
                case "sltchk":
                    return "<input name=\"div-edit-checkbox\"  attrType=\"sltchk\" type=\"checkbox\" class=\"" + cssClass + "\" />";
                    break;
                case "sltDate":
                    return "<input id=\"" + name + "\"  readonly = \"readonly\" attrType=\"sltDate\" name=\"" + name + "\" value=\"" + value + "\" type=\"text\" class=\"" + cssClass + "\" />";
                    break;
                case "sltinandsel":
                    return "<input id=\"" + name + "\" attrType=\"sltinandsel\" name=\"" + name + "\" value=\"" + value + "\" type=\"text\" class=\"" + cssClass + "\" />";
                    break;
                default:
                    return "<input name=\"" + name + "\" attrType=\"sltinput\" type=\"text\" value=\"" + value + "\" class=\"" + cssClass + "\" />";
                    break;
            }
        }
        function InitializeRow() {
            var rows = cofig.data;
            if (rows != null && rows.length > 0) {
                for (var i = 0; i < rows.length; i++) {

                    addRow(rows[i], false)
                }
            }
        }

        /**
        * Function that allows o add new rows
        */
        function addRow(obj, flag) {
            //var tr = rowtemplate;
            var tr = cofig.template;
            cofig.formposition++;
            var cols = [];
            cols.push("<tr>");
            if ($(tr).find("input").length > 0) {
                $(tr).find("input").each(function(index, elem) {
                    // Change the name of the fields
                    var newName = '';
                    if (cofig.formposition !== '') {
                        newName = elem.name.replace(/\[[0-9]+\]/i, '[' + cofig.formposition + ']');
                    }
                    else {
                        cofig.formposition = $("#" + tableID + " tr").length - 1;
                        newName = elem.name;
                    }
                    var colindex = "colindex" + index;
                    cols.push("<td>");
                    var objvalue = (obj == null ? "" : obj[colindex]);
                    if (elem.attrType == "sltchk") {
                        if (flag) {
                            cols.push("<input name=\"div-edit-checkbox\" checked=\"true\" rowIndex=\"" + cofig.formposition + "\" rowNO=\"" + cofig.formposition + "\" value=\"" + objvalue + "\"  attrType=\"sltchk\" type=\"checkbox\" class=\"" + elem.className + "\" />");
                        }
                        else {
                            cols.push("<input name=\"div-edit-checkbox\" checked=\"true\" disabled=\"disabled\" checked=\"true\" rowIndex=\"" + cofig.formposition + "\" rowNO=\"" + cofig.formposition + "\" value=\"" + objvalue + "\"  attrType=\"sltchk\" type=\"checkbox\" class=\"" + elem.className + "\" />");
                        }
                    }
                    else {

                        cols.push(makeTemplate(elem.attrType, newName, elem.className, objvalue, flag));

                    }


                    cols.push("</td>");
                });
                if (cofig.delRow && cofig.showDelRow) {
                    cols.push("<td class=\"div-td-delete\"><a href=\"#\" class=\"div-row-delete\"><span class=\"Delete\">&nbsp;</span></a></td>");
                }

                cols.push("</tr>");


            }
            $("#" + tableID).append(cols.join(""));
            cols = null;
            //allow datepicker
            $(":text[class='div-input-date']", $("#" + tableID)).each(function(index, elem) {

                if (elem.attrType == "sltDate") {

                    $(elem).datepicker({ picker: "<img class='picker' align='middle' src='../../themes/shared/images/s.gif' alt=''/>" });
                }

            });

            //allow selectandinput
            $(":text[class='div-inputandselect-text']", $("#" + tableID + " tr:last")).each(function(index, elem) {
                if (elem.attrType == "sltinandsel") {
                    $(elem).addtionInfo();
                }
            });

        }
        //Allow to delete row
        function DeleteRow(elem) {
            if (cofig.rails) {
                var checkbox = $(elem).find("input[name='div-edit-checkbox']:first");
                if ($(checkbox).val() !== "") {
                    cofig.storeDel += $(checkbox).val() + ",";
                }
            }
            $(elem).remove();
            // alert(cofig.storeDel);
            //rownumber initialize
            var rowno = 0;
            $("#" + tableID).find("input[name='div-edit-checkbox']").each(function(index, elem) {
                rowno++;
                $(elem).attr("rowNO", rowno)
            })
            cofig.formposition = rowno;
            //alert(cofig.formposition);
        }
        /////----------API--------------------//////
        //获取选中的行编号
        this.GetSelectedRow = function(type) {
            var table = $("#" + tableID);
            var returnVal = [];

            $(table).find("input[name='div-edit-checkbox'][disabled='true']").each(function(index, elem) {

                returnVal.push($(elem).val());

            })
            return returnVal;
        };
        this.GetTable = function(table) {
            var table = $("#" + tableID);
            return table;
        };

        //添加行
        this.customAddRow = function(itemArray) {
            for (var i = 0; i < itemArray.length; i++) {

                addRow(itemArray[i], false)
            }
        }

    }
})(jQuery);
//===================uploader=====================
