/// <reference path="jquery.js"/>
/*
* window
* version: 1.0.0 (13/03/2011)
* @ jQuery v1.4.4*
*/
//------------------StringBuilder---------------------------
function StringBuilder() {
    this.__strings__ = new Array;
    
     if (typeof StringBuilder._initialized == "undefined") {
        StringBuilder.prototype.append = function (str) {
            this.__strings__.push(str);
        };
        
        StringBuilder.prototype.prvAppend = function (str) {
            this.__strings__.unshift(str);
        };  
          
        StringBuilder.prototype.tostring = function () {
            return this.__strings__.join("");
        };
        StringBuilder._initialized = true;
     }
}
//------------------Format---------------------------
String.prototype.format = function()
 {
     var args = arguments;
     return this.replace(/\{(\d+)\}/g,               
         function(m,i){
             return args[i];
         });
 }
 String.format = function() {
     if( arguments.length == 0 )
         return null;
 
    var str = arguments[0];
     for(var i=1;i<arguments.length;i++) {
         var re = new RegExp('\\{' + (i-1) + '\\}','gm');
         str = str.replace(re, arguments[i]);
    }
    return str;
}
//-----------------------------------------------------
function importjs(url){
    var script = document.createElement("script");
    script.defer = false;
    script.language = "JavaScript";
    script.type = "text/javascript";
    script.src = url;
    var head = document.getElementsByTagName("head")[0];
    head.appendChild(script);
}
function importlink(url){
    var link = document.createElement("link");
    link.href = url;
    link.rel="stylesheet";
    link.type = "text/css";
    var head = document.getElementsByTagName("head")[0];
    head.appendChild(link);
}

function getRootPath()
{
    var strFullPath=window.document.location.href;
    var strPath=window.document.location.pathname;
    var pos=strFullPath.indexOf(strPath);
    var prePath=strFullPath.substring(0,pos);
    var postPath=strPath.substring(0,strPath.substr(1).indexOf('/')+1);
    if(prePath.indexOf("http://localhost:")!=-1)
     return (prePath+postPath);
    else
     return prePath;
} 
          
var root = getRootPath();
importjs(root+'/window/form/jquery.form.js');
importlink(root+'/window/_css/window.css');
//当前数据窗口实例数组
var WindowInstances = {};
//使用闭包
(function($) { 
         $.WINDOW_STATE ={
            PAGING:-1,//当前窗口未包含查询集 并且 状态为 数据分页

            QUERY:1,//状态为 查询
            INSERT:2 //状态为 录入
        };
        $.ORDER_TYPE={
            DESC:"DESC",
            ASC:"ASC"
        };
        $.REQUEST_TYPE={
            PAGING:1,
            INSERT:2,
            DELETE:3,
            MODIFY:4,
            QUERY :5,
            QUERY_ITEM:6,
            QUERY_EDIT_ITEM:7,
            ROW_COMMAND:8,
            SELECT_ROW_COMMAND:9
        };
        $.Window = function(options,funtions){
          
		       this.opts = jQuery.extend({
			        placeholder_id:null,
			        columns:null,//列信息
			        show_mode_type:"Table",//显示类型
			        show_mode_setting:null,//显示模式参数
			        current_page_index:1,//当前页
			        current_query_index:1,//当前查询索引
			        current_page_count:0,//所有分页行总数
			        current_query_count:0,//所有查询行总数
			        page_size :20,//每页大小
			        request_url:null,//请求 URL
                    ticWidth:35, //表格 索引列的宽度
                    tccWidth:35, //表格checkbox列宽度
                    tocWidth:50,  //表格操作列宽度
			        //WINDOW组件 ID 值
                    insert_panel_id:null,//录入面板ID
                    insert_form_id:null,//录入面板Form ID
                    
                    modify_panel_id:null,//编辑面板ID
                    modify_form_id:null,//编辑面板Form ID
                    
                    query_panel_id:null, //查询面板ID
                    
                    insert_setting:null, //录入配置
			        window_state: $.WINDOW_STATE.PAGING,
			        current_query:null, //记录WINDOW 第一次查询
			        current_select_row:null, //当前的选择行 ID 主键
			        current_focus_row:null, //当前数据移动到的行 ID mouseover
			        current_resize_header:null,
			        //组件 集合
			        table_header_wrap:null, //表头包裹DIV ID
			        table_header:null, //表头TABLE ID
			        table_content_wrap:null, //包裹内容DIV ID
			        table_content:null, //内容TABLE ID
			        window_header:null, //WINDOW HEADER DIV ID
			        window_pageItem:null,//WINDOW 分页选项 DIV ID
			        window_content:null,//WINDOW 内容 DIV ID
			        window_footer:null,//WINDOW 脚 DIV ID
			        window_all_pager:null,///WINDOW 所有数据分页 DIV ID
			        window_query_pager:null,//WINDOW 查询分页 DIV ID
			        window_all_count:null,//WINDOW 所有数据分页计数 SPAN ID
			        window_query_count:null,//WINDOW 所有查询分页计数 SPAN ID
			        window_hfedit_id:null,//WINDOW 编辑row主键 ID
			        window_header_toolber:null, //WINDOW header TOOLBER
			        window_resize_mark:null,//拖动线,
			        window_all_div_count:null,//所有分页页数显示SPAN
			        window_query_div_count:null, //查询分页页数显示SPAN
			      //  window_query_div_select:null,//查询分页选择页数
		          //  window_all_div_select:null,//所有分页选择页数
		            window_all_div_input:null,//所有分页选择页数
                    window_query_div_input:null,//查询分页选择页数
                    window_close_Insert_state:null //关闭录入状态
		        },options||{});
		        // 接口集合 this.funs.validInsert
		        this.funs = jQuery.extend({  
		           format:function(dataitem,cname,value){ //数据格式化
		                return value;
		           },
		           formatOperColumn:function(windowID,dataRow,id){
		                return  String.format
		                ("<a href=\"javascript:void(0)\" onclick=\"WindowInstances['{0}']._Edit('{1}')\">[编辑]</a>", windowID,id);
                   },
		           beforeInsertSubmit: function (){return true;},//验证录入数据 和执行先关操作
                   beforeModifySubmit:function(){return true},//验证编辑数据 和执行先关操作
                   beforeShowEdit:function(row){},//显示编辑数据之前 填充数据处理方法
                   beforeShowInsert:function(){},
                   selectIndexChanging:function(selectrow){}, //行选择索引改变前
                   selectIndexChanged:function(selectrow){}, //行选择索引改变后
                   beforeDeleting:function(){return confirm('您确定要删除选中项吗？');}
		        },funtions||{});
		        if(WindowInstances[this.opts .placeholder_id]!=null){
		            throw this.opts .placeholder_id+"该实例已存在！";
		        }

               var id = this.opts.placeholder_id;
               this.opts.table_header_wrap = String.format("{0}_{1}",id,"t_h_w")
               this.opts.table_header = String.format("{0}_{1}",id,"t_h");
               this.opts.table_content_wrap = String.format("{0}_{1}",id,"t_c_w")
               this.opts.table_content = String.format("{0}_{1}",id,"t_c");
               this.opts.window_header = String.format("{0}_{1}",id,"window_h");
               this.opts.window_pageItem = String.format("{0}_{1}",id,"psi")
               this.opts.window_content = String.format("{0}_{1}",id,"window_c");
               this.opts.window_footer = String.format("{0}_{1}",id,"window_f");
               //所有数据分页
               this.opts.window_all_pager = String.format("{0}_{1}",id,"window_a_p");
               this.opts.window_all_count = String.format("{0}_{1}",id,"acount");
               this.opts.window_all_div_count = String.format("{0}_{1}",id,"all_pager_s_c");

               this.opts.window_all_div_input = String.format("{0}_{1}",id,"all_pager_s_i");
             
               //查询分页
               this.opts.window_query_count = String.format("{0}_{1}",id,"qconut");
               this.opts.window_query_pager = String.format("{0}_{1}",id,"window_q_p");
               this.opts.window_query_div_count = String.format("{0}_{1}",id,"query_pager_s_c");
        
               this.opts.window_query_div_input = String.format("{0}_{1}",id,"query_pager_s_i");
               
               this.opts.window_hfedit_id =String.format("{0}_{1}",id,"eidtID");
               this.opts.window_header_toolber = String.format("{0}_{1}",id,"tb")
               this.opts.window_resize_mark = String.format("{0}_{1}",id,"w_rs_m");
               //录入状态
               this.opts.window_close_Insert_state = String.format("{0}_{1}",id,"w_c_i_s");
               //所有数据分页
                if(this.opts.show_mode_type=="Table")
                {
                this.tableMode();
                }
                WindowInstances[this.opts.placeholder_id] = this;//保存实例
                this.getPaginInfo(this.opts.current_page_index); 
                //录入初始化
                this._initInsert();
                //删除初始化
                this._initDelete();
                //修改初始化
                this._initModify();
                //查询初始化
                this._initQuery();
                //清除垃圾(html)
                this._clear();
                //  $("body").show(); 
	    } 
        $.extend($.Window, {
            _SymbolToName:function(type)
            {
                var name = '';
                switch(type)
                {
                    case "Equals":
                    return "等于";
                    break;
                    case "NotEquals":
                    return "不等于";
                    break;
                    case "Contains":
                    return "包含";
                    break;
                    case "GreaterThan":
                    return "大于";
                    break;
                    case "LessThan":
                    return "小于";
                    break;
                    case "NotContains":
                    return "不包含";
                    break;
                    case "StartContains":
                    return "字符开头";
                    break;
                    case "EndContains":
                    return "字符结尾";
                    break;
                    case "isNull":
                    return "没有值";
                    break;
                    case "isNotNull":
                    return "有值";
                    break;
                }
    
            },
            /////<summary>
            ///// 不匹配
            /////</summary>
            notMatch:function(input,reg)
            {
                 if(!input.val().match(reg)){
                    input.addClass( "ui-state-error" );
                    return true;
                 }
                 input.removeClass( "ui-state-error" );
                 return false;
            },
            /////<summary>
            ///// 不是整型
            /////</summary>
             _isInt:function(sText){
                  var reg =/^\d*$/;
                  return sText.match(reg);
            },
            message:function(msgstr,type){
                  var msg = $("#window_message_div");
                  if(msg.size()==0){
                        $("body").append("<div id='window_message_div' class='window_message' style='display:none'></div>");
                        msg = $("#window_message_div");
                  }else{
                    if(msg.css('display')=="block")
                         return;
                  }
                  type = type==null?0:type; //0 正确 1 警告
                  if(type==0)
                    msg.get(0).className="window_message window_message_success";
                  else
                    msg.get(0).className="window_message window_message_warning"; 
                    
                  msg.html(msgstr).css({
                        'top' : ($(window).height()-msg.height())/3+$(document).scrollTop(),
		                'left' :($(window).width()-msg.width())/2+$(document).scrollLeft()
		               
                  }).show();
                  setTimeout('$("#window_message_div").hide("drop",{},200,function(){$("#window_message_div").removeAttr("style").hide()}); ',2000);
                  //$("#window_message_div").removeAttr("style").hide() 对付IE怪胎的方法 
            },
            isEmpty:function(input){
                 if($.trim(input.val())==""){
                      input.get(0).focus();
                      input.addClass( "ui-state-error" );
                      $.Window.message("该项是必填项！请填写！",1);
                      return true;
                  }
                  input.removeClass( "ui-state-error" );
                  return false;
            },
            /////<summary>
            ///// 不是整型
            /////</summary>
            /////<param name="obj">jquery对象</param>
            /////<param name="allowNull">是否允许null 默认不允许</param> 
            notInt:function(input,allowNull){
                var value = $.trim(input.val());
                allowNull = allowNull==null?false:allowNull
                if(allowNull){
                    if(value=="")
                        return false;
                }
                else{
                    if($.Window.isEmpty(input))
                        return true; 
                }

                if(this._isInt(value)){
                    input.removeClass( "ui-state-error" );
                    return false;
                }
                input.get(0).focus();
                input.addClass( "ui-state-error" );
                return true;
            },
            load:function(str){
                var mask = $("#window_mask_div");
                var elapsed = $("#window_mask_elapsed");
                if(mask.size()==0){
                      mask = $("<div id='window_mask_div'></div>").css({
				            'display'	: 'none',
				            'position'	: 'absolute',
				            'clear'		: 'both',
				            'overflow'	: 'hidden',
				            'z-index'	: 10000,
				            'top'		: 0,
				            'left'		: 0,
				            'width'		: $(document).width(),
				            'height'	: $(document).height(),
                            'opacity'			: '0.100',
                            'background-color'	: '#fff',
                            'display'			: 'block'
			          });
			          $(window).resize(function(){
                          $("#window_mask_div").css({
                                'width'		: $(document).width(),
                                'height'	: $(document).height()
                          });
                      });
			          $("body").append(mask);
			     }else{
			         mask.css({
				        'width'	: $(document).width(),
				        'height': $(document).height()
			         });
			     }
			     if(elapsed.size()==0){
                    elapsed = $("<div id='window_mask_elapsed'></div>").css({
                        'position' : 'absolute',
                        'z-index' : 10001,
                       	'top' : ($(window).height()/3)-(elapsed.height()/3)+$(document).scrollTop(),
		                'left' :($(window).width() /2)-(elapsed.width()/2)+$(document).scrollLeft(),
		                'display' : 'block'
                    });
                    elapsed.html("<span class='window_loading' id='window_mask_elapsed_text' ></span>");
                    $("body").append(elapsed);
			     }else{
		            elapsed.css({
                       	'top' : ($(window).height()/3)-(elapsed.height()/3)+$(document).scrollTop(),
		                'left' :($(window).width()/2)-(elapsed.width()/2)+$(document).scrollLeft(),
		                'display' : 'block'
                    });
			     } 
			     $("#window_mask_elapsed_text").text(str);
                mask.show();
                elapsed.show();
            },//取消屏蔽
            unload:function(){
                 $("#window_mask_div").hide();
                 $("#window_mask_elapsed").hide();
            },
            as_th_index:"thi",
            as_th_checkbox:"thc",
            as_th_oper:"thoper",
            class_content_tr:"table_content_tr"
           
        });
        $.extend($.Window.prototype, {
                ///<summary>
                //构造分页组件
                ///</summary>
                _initAllPager:function(type){
                        var window = this;
                        //所有数据分页
                        var allPage = $("#{0}".format(this.opts.window_all_pager));
                        var tr = $("<tr></tr>");
                        
                        $("<td>|分页:</td><td  title='首页' width='20' ><span class=\" ui-corner-all ui-icon ui-icon-seek-first\" style='display:block;'></span></td>").appendTo(tr).children().hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); })
                        .bind('click', function() {
                            if(window.opts.current_page_index!=1){
                                 window.getPaginInfo(1)
                            }
                            
                        });
                         $("<td  title='上一页' width='20' ><span class=\"ui-corner-all ui-icon ui-icon-seek-prev\" style='display:block;' ></span></td>").appendTo(tr).children().hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); })
                        .bind('click', function() {
                            if(window.opts.current_page_index>1){
                                window.getPaginInfo(window.opts.current_page_index-1);
                            }
                        });
                        tr.append("<td>|页</td>");
                        var input = $("<td  title='页码' width='20'  ><input type=\"text\" id=\"{0}\" value=\"0\" maxlength=\"7\" size=\"2\" class=\"ui-pg-input\"\></td>".format(this.opts.window_all_div_input)).appendTo(tr).children().bind('keydown', function(event) {
                              if(event.keyCode=="13") {
                                   var index = parseInt(this.value);
                                   var pagecount = Math.ceil(parseInt(window.opts.current_page_count)/parseInt(window.opts.page_size));
                                   if(index>0&&index<=pagecount)
                                        window.getPaginInfo(index)
                                   else
                                        $.Window.message("页码超出索引！",1);
                              }
                        });
                        $("<td>/</td>").appendTo(tr);
                        $(String.format("<td><span id='{0}'></span><td>",this.opts.window_all_div_count)).appendTo(tr);
                        
                        $("<td title='下一页'  width='20'><span class=\"ui-corner-all ui-icon ui-icon-seek-next\" style='display:block;' ></span></td>").appendTo(tr).children().hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); })
                        .bind('click', function() {
                            var pagecount = Math.ceil(parseInt(window.opts.current_page_count)/parseInt(window.opts.page_size));
                            if(window.opts.current_page_index<pagecount){
                                window.getPaginInfo(window.opts.current_page_index+1);
                            }
                        });
                        
                        $("<td title='尾页' width='20'  ><span class=\"ui-corner-all ui-icon ui-icon-seek-end\" style='display:block;' ></span></td>").appendTo(tr).children().hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); })
                        .bind('click', function() {
                            var pagecount = Math.ceil(parseInt(window.opts.current_page_count)/parseInt(window.opts.page_size));
                            if(window.opts.current_page_index!=pagecount){
                                window.getPaginInfo(pagecount);
                            }
                        })

                        allPage.append($("<table border='0' class='window_pager'></table>").append(tr));
                }, 
                //<summary>
                //构造查询分页组件
                //</summary>
                _initQueryPager:function(){
                        var window = this;
                        var pager = $("#{0}".format(this.opts.window_query_pager));
                        var tr = $("<tr></tr>");
                        
                        $("<td>|查询分页:</td><td  title='首页' width='20' ><span class=\" ui-corner-all ui-icon ui-icon-seek-first\" style='display:block;'></span></td>").appendTo(tr).children().hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); })
                        .bind('click', function() {
                            if(window.opts.current_query_index!=1){
                                 window.getQueryInfo(1)
                            }
                        });
                        $("<td  title='上一页' width='20' ><span class=\"ui-corner-all ui-icon ui-icon-seek-prev\" style='display:block;' ></span></td>").appendTo(tr).children().hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); })
                        .bind('click', function() {
                            if(window.opts.current_query_index>1){
             
                                window.getQueryInfo(window.opts.current_query_index-1);
                            }
                        });
                        tr.append("<td>|页</td>");
                        var input = $("<td  title='页码' width='20'  ><input type=\"text\" id=\"{0}\" value=\"0\" maxlength=\"7\" size=\"2\" class=\"ui-pg-input\"\></td>".format(this.opts.window_query_div_input)).appendTo(tr).children().bind('keydown', function(event) {
                              if(event.keyCode=="13") {
                                   var index = parseInt(this.value);
                                   var pagecount = Math.ceil(parseInt(window.opts.current_query_count)/parseInt(window.opts.page_size));
                                   if(index>0&&index<=pagecount)
                                        window.getQueryInfo(index)
                                   else
                                        $.Window.message("页码超出索引！",1);
                              }
                        });
                        $("<td>/</td>").appendTo(tr);
                        $(String.format("<td><span id='{0}'></span><td>",this.opts.window_query_div_count)).appendTo(tr);
                        
                        $("<td title='下一页'  width='20'><span class=\"ui-corner-all ui-icon ui-icon-seek-next\" style='display:block;' ></span></td>").appendTo(tr).children().hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); })
                        .bind('click', function() {
                            var pagecount = Math.ceil(parseInt(window.opts.current_query_count)/parseInt(window.opts.page_size));
                            if(window.opts.current_query_index<pagecount){
                                window.getQueryInfo(window.opts.current_query_index+1);
                            }
                        });
                        
                        $("<td title='尾页' width='20'  ><span class=\"ui-corner-all ui-icon ui-icon-seek-end\" style='display:block;' ></span></td>").appendTo(tr).children().hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); })
                        .bind('click', function() {
                            var pagecount = Math.ceil(parseInt(window.opts.current_query_count)/parseInt(window.opts.page_size));
                  
                            if(window.opts.current_query_index!=pagecount){
                                window.getQueryInfo(pagecount);
                            }
                        })

                     
                         $("<td title='取消查询' width='20'><span class=\"ui-corner-all ui-icon ui-icon-circle-close\" style='display:block;' ></td>").appendTo(tr).children().hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); })
                        .bind('click', function() {
                             $("#{0}".format(window.opts.window_query_pager)).html("");
                             window.getPaginInfo(window.opts.current_page_index);
                        })
                        pager.append($("<table border='0' class='window_pager'></table>").append(tr));
                },
                //初始化输入
                _initInsert:function(){ 
                    if(this.opts.insert_setting!=null){//是否设置录入配置 如果无则不初始
                            //录入面板ID
                            this.opts.insert_panel_id= String.format("{0}_{1}",this.opts.placeholder_id,"_insertPanel");
                            //录入FromID
		                    this.opts.insert_form_id= String.format("{0}_{1}",this.opts.placeholder_id,"_insertForm");
        		            
                            var panel = $("<div id='{0}' class='dialog'></div>".format(this.opts.insert_panel_id));
                            var form = $("<form id='{0}' method='post'></form>".format(this.opts.insert_form_id));
                            panel.append(form);
                            //获取录入面板内容
                            var oldContent =  $("#{0}".format(this.opts.insert_setting.insert_panel));
                            var content = $(
                                          oldContent.html()
                            );
                            //将所有INPUT ID号替换成
                            var inputs = content.find(":input");
                            for(var index =0;index<inputs.length;index++){
                                var ipt = inputs.eq(index);
                                ipt.attr("id",String.format("{0}_i_{1}",this.opts.placeholder_id,ipt.attr("id")));
                            }
                            //将所有图片HTML对象ID替换成
                            var imgs = content.find("img");
                            for(var index=0;index<imgs.length;index++){
                                var img = imgs.eq(index);
                                img.attr("id",
                                            String.format("{0}_i_{1}",this.opts.placeholder_id,img.attr("id"))
                                );
                            }
                            form.html(content);
                            $("body").append(panel);
                            var height = oldContent.attr("height");
                            height = height==null?content.height()+140:parseInt(height);
                            panel.dialog({ 
                                    title:"录入",
                                    autoOpen: false,
                                    width:content.width()+50,
                                    height:height
                            });
                            var window = this;
                            $("#{0}".format(this.opts.insert_setting.insert_button)).bind('click', function() {
                                      window._insert();
                            });
                    }      
                },
            
                //初始化删除
                _initDelete:function(){
                    if(this.opts.delete_setting!=null)
                    { 
                        var window = this;
                        $("#{0}".format(this.opts.delete_setting.button_id)).bind('click',function(){
                                window._delete();
                        });
                    }
                },
                //初始化编辑
                _initModify:function(){
                    if(this.opts.modify_setting!=null)
                    {
                            this.opts.modify_panel_id = 
                            String.format("{0}_{1}",this.opts.placeholder_id,"_modifyPanel");//编辑面板ID
                            this.opts.modify_form_id = 
                            String.format("{0}_{1}",this.opts.placeholder_id,"_modifyForm");//编辑FromID

                            var panel = $(
                            String.format("<div id='{0}' class='dialog' ></div>",this.opts.modify_panel_id)
                            );
                            var form = $(
                            String.format("<form id='{0}' method='post'></form>",this.opts.modify_form_id)
                            );

                            panel.append(form);
                            //是否和录入面板相同
                            var content = $(
                            $("#{0}".format(this.opts.modify_setting.modify_panel)).html()
                            );
                            var inputs = content.find(":input");
                            for(var index =0;index<inputs.length;index++){
                                var ipt = inputs.eq(index);
                                ipt.attr("id",
                                String.format("{0}_m_{1}",this.opts.placeholder_id,ipt.attr("id"))
                                );
                            }
                            //将所有图片HTML对象ID替换成
                            var imgs = content.find("img");
                            for(var index=0;index<imgs.length;index++){
                                var img = imgs.eq(index);
                                img.attr("id",
                                    String.format("{0}_m_{1}",this.opts.placeholder_id,img.attr("id"))
                                );
                            }
                            form.html(content);
                            form.append(
                                    String.format("<input id='{0}' name='editID' type='hidden' />",
                                    this.opts.window_hfedit_id)
                                );
                        
                            $("body").append(panel);
                            panel.dialog({ 
                                title:"编辑",
                                autoOpen: false,
                                width:content.width()+50,
                                height:content.height()+160
                            });
                    }
                },
                ///<summary>
                /// 获取编辑INPUT元素
                ///</summary>
                ///<param name="id">录入面板id</param>
                getMI:function(id){
                    return $("#"+this.opts.placeholder_id+'_m_'+id);
                },
                ///<summary>
                //获取录入INPUT元素
                ///</summary>
                ///<param name="id">录入面板id</param>
                getII:function(id){
                    return $("#"+this.opts.placeholder_id+'_i_'+id);
                },
                ///<summary>
                //获取录入 或 编辑面板 INPUT元素 在录入 和编辑是同一个面板的情况能减少编码
                ///</summary>
                ///<param name="id">id</param>
                ///<param name="insert">是否是录入面板</param>
                getI:function(id,insert){
                    return insert?$("#"+this.opts.placeholder_id+'_i_'+id):$("#"+this.opts.placeholder_id+'_m_'+id);
                },
                //初始化查询
                _initQuery:function(){
                    if(this.opts.query!=null)
                    {
                       var query = this.opts.query;
                       if(query.query_list==null){
                            return;
                       }
                       var panel;
                       if(query.query_panel==null){//是否存在查询面板 不存在将自动创建
                            this.opts.query_panel_id = String.format("{0}_{1}",this.opts.placeholder_id,"_dialogQuery");
                            panel = $(
                                String.format("<div id='{0}'></div>",this.opts.query_panel_id)
                            );
                       }else{
                            this.opts.query_panel_id = query.query_panel;
                            
                            panel = $(String.format("#{0}",this.opts.query_panel_id));
                       }
                       //构造自动列
                        var qtable = $("<table border='0'cellspacing=\"3\" ></table>");
                        var querylist = query.query_list;
                        var isExistNull = false;
                        for(var i in querylist){
                            var query_item = querylist[i];
                            var input;
                            if(query_item.html_id==null){//如果没有指定HTML 则自动创建
                                isExistNull = true;
                                query_item.html_id = String.format("{0}__query_{1}",this.opts.query_panel_id,i);
                                
                                var tr = $(
                                String.format("<tr><td>{0}:</td><td align='right' style='white-space: nowrap'><input type='text' id='{1}'/></td></tr>",query_item.alias_name,query_item.html_id)
                                );
                                qtable.append(tr);
                                input = tr.find(":input");
                        
                            }else{
                                input =  $("#{0}".format(query_item.html_id));
                            } 

                            if(query_item.symbol_types.length>1)
                            {
                                 var select=
                                 String.format("<select id='{0}_s_{1}'>",this.opts.placeholder_id,query_item.html_id); 
                                  
                                 for(var sindex in query_item.symbol_types){
                                    select+=String.format("<option value='{0}'>{1}</option>",
                                    query_item.symbol_types[sindex].type,
                                    $.Window._SymbolToName(query_item.symbol_types[sindex].type)
                                    );
                                 }
                                  select+="</select>";  
                                 input.before(select);
                            }
                            //是否有自动生成的查询输入框
                            if(isExistNull){
                                panel.prepend(qtable);
                            }
                        }
                        
                       var window = this;
                       $("body").append(panel);// 写入文档
                       panel.dialog({
                            title:"查询面板",
                            autoOpen:false,
                            buttons:{
                                    "查询":function(){
                                        window.Query();
                                     }
                                   }
//                            width:panel.width()+50,
//                            height:panel.height()+170
                       });
               
                       $("#{0}".format(query.query_button)).bind('click', function() {
                
                             $("#"+window.opts.query_panel_id).dialog("open");
                       });
                       
                    }
                },
                //清除垃圾代码
                _clear:function()
                {
                        if(this.opts.insert_setting!=null)
                        $("#{0}".format(this.opts.insert_setting.insert_panel)).remove();
                        if(this.opts.modify_setting!=null)
                        $("#{0}".format(this.opts.modify_setting.modify_panel)).remove();
                },
                _insert:function(){  
                   
                        var form = $("#{0}".format(this.opts.insert_form_id));
                        var dialog =  $("#{0}".format(this.opts.insert_panel_id));
                        var json={
                            "request_type":$.REQUEST_TYPE.INSERT,
                            "options":this.opts
                        };
                        var window = this;
                        var options = 
                        { 
                                url:this.opts.request_url,
                                data:{windowID:this.opts.placeholder_id,windowRequest:encodeURI($.toJSON(json))},
                           //   iframe:true,
                                dataType:  'json', 
                                success:function(data){
                                     $.Window.unload();
                                     if(data.state==1){
                                    
                                       //判断是否构造头部
                                       var isbh = window.opts.window_state==$.WINDOW_STATE.INSERT?false:true;
                                       if(isbh){
                                           $("#{0}".format(window.opts.window_close_Insert_state)).show();
                                           window.tableFillContent(window.formatData(data.value,isbh,true));
                                       }else
                                           window.tableFillContent(window.formatData(data.value,isbh,false));
                                        //当第一条数据显示后设置录入状态
                                        window.opts.window_state=$.WINDOW_STATE.INSERT;
                                     }else{
                                        $.Window.message(data.value,1);
                                     }
                                },
                                error: function() {$.Window.unload(); $.Window.message("录入数据失败！",1); return false; } 
                        }; 
                        form.resetForm();
                        this.funs.beforeShowInsert();
                        dialog.dialog("option",{
                                                 buttons: {
                                                 "保存": function() {
                                                    if(window.funs.beforeInsertSubmit()){
                                                        $.Window.load("保存中");
                                                    }else{
                                                        return false;
                                                    }
                                                    form.ajaxSubmit(options); 
                                                  },
                                                 "重置":function(){
                                                      form.resetForm();
                                                  }
                                                }
				                            });
                        dialog.dialog("open");
                },
                
                _delete:function(){
                    if(!this.funs.beforeDeleting()){ 
                        return;
                    }
                    //获取CHECKBOX 所在列索引
                    var headtd = $(
                    String.format("#{0}",
                    this.opts.table_header)).children("thead").children(":eq(0)").children();
                    var index ;
                    for(index=0;index<headtd.size();index++){
                        if(headtd.eq(index).attr("id")==
                        String.format("{0}_{1}",this.opts.placeholder_id,$.Window.as_th_checkbox))
                        break;
                    }
                    var checklist = $("#{0}".format(this.opts.table_content)).find("tbody").children("tr")
                    var deleteList = new Array();//选中项主键集合
                    var deleteTr = new Array();//选中 tr jquery 对象 集合
                    //获取选中项
                    for(var i=0;i<checklist.size();i++){
                       var trItem = checklist.eq(i);
                       var cbItem = trItem.children(":eq("+index+")").children("input[type='checkbox']")
                       if(cbItem.attr("checked"))
                       {  
                           deleteTr.push(trItem);
                           deleteList.push("'{0}'".format(cbItem.val()));
                       }
                    }
                    if(deleteList.length>0){
                        //发送删除请求
                        var json = {
                            "request_type":$.REQUEST_TYPE.DELETE,
                            "options":this.opts,
                            "deleteKeys":deleteList.join(',')
                        };
                        var window = this;
                        $.ajax({
                               type: "POST",
                               dataType:"json",
                               url:this.opts.request_url,
                               data: {windowID:this.opts.placeholder_id, windowRequest:$.toJSON(json)},
                               success: function(data){
                                     $.Window.unload();
                                     if(data.state==1){
                                        //删除所有选中项
                                        for(var i=0;i<deleteTr.length;i++){
                                            deleteTr[i].remove();
                                        }
                                        $.Window.message("总共删除【"+data.value+"】行记录",0);
                                     }else{
                                        $.Window.message(data.value,1);
                                     }
                               },
                               error:function (XMLHttpRequest, textStatus, errorThrown) {
                                    $.Window.message("出错了",1);
                                    $.Window.unload();
                               },
                               beforeSend: function(XMLHttpRequest){ 
                                    $.Window.load("正在删除所有选中项...");
                               }
                      });  
                  }else{
                        $.Window.message('请选择删除项！',1);
                  }
                },
                QueryItem:function(key,handler){
                    var json = {
                            "request_type":$.REQUEST_TYPE.QUERY_ITEM,
                            "options":this.opts,
                            "key":key
                    };
                    var window = this;
                    $.ajax({
                               type: "POST",
                               dataType:"json",
                               url:this.opts.request_url,
                               data: { windowID:this.opts.placeholder_id,windowRequest: $.toJSON(json)},
                               success: function(data){
                                    $.Window.unload()
                                    if(data.state==1){
                                        handler(data.value);
                                    }else{
                                        $.Window.message(data.value,1);
                                    }
                               },
                               beforeSend:function(){
                                    $.Window.load('加载中...');
                                    return true;
                               },
                               error: function() {$.Window.unload(); $.Window.message("加载失败！",1); return false; } 
                           });
                },
                ///<summary>
                /// 编辑行
                ///</summary>
                ///<param name="keyID">主键ID</param>
                _Edit:function(keyID){
                    var json = {
                            "request_type":$.REQUEST_TYPE.QUERY_EDIT_ITEM,
                            "options":this.opts,
                            "key":keyID
                    };
                    var window = this;
                   
                    $.ajax({
                               type: "POST",
                               dataType:"json",
                               url:this.opts.request_url,
                               data: { windowID:this.opts.placeholder_id,windowRequest: $.toJSON(json)},
                               success: function(data){
                                   $.Window.unload()
                                   if(data.state==1){
                                        var dr = data.value;
                                        
                                        
                                        $("#{0}".format(window.opts.modify_form_id)).resetForm();
                                        window.funs.beforeShowEdit(dr); //必须放在下面不然无法在该方法中设置input的值 原因 resetForm();
                                        $("#{0}".format(window.opts.window_hfedit_id)).val(keyID);//设置KEY ID
                                        var json={
                                                    "request_type":$.REQUEST_TYPE.MODIFY,
                                                    "options":window.opts
                                        };
                                        var options = { 
                                            url:window.opts.request_url,
                                            data: { windowID:window.opts.placeholder_id,windowRequest:encodeURI($.toJSON(json))},
                                            dataType:  'json', 
                                            success:function(data){
                                                $.Window.unload();
                                                if(data.state==1){
                                                    $(String.format("#{0}",window.opts.modify_panel_id)).dialog("close");
                                                    
                                                    var newRow = $(window.formatData(data.value,false));
                                                    var oldRow = $(String.format("#{0}",window.opts.current_select_row)).replaceWith(newRow);
                                                    newRow.attr("id",oldRow.attr("id"));
                                                    
                                                    if(window.opts.show_mode_setting.is_show_row_index){
                                                        //获取旧行 中的行索引 赋到新行
                                                        newRow.children(":eq(0)").text(oldRow.children(":eq(0)").text());
                                                    }
                                                    window._bindRowEvent(newRow);
                                                    newRow.addClass('ui-state-error');
                                                }else{
                                                    $.Window.message(data.value,1);
                                                }
                                            },
                                            error: function() {$.Window.unload(); $.Window.message("保存失败！",1); return false; } 
                                         };          
                                         $(String.format("#{0}",window.opts.modify_panel_id)).dialog("option",{
                                                            buttons: {
                                                             "保存":function(){
                                                                  if(window.funs.beforeModifySubmit()){
                                                                    $.Window.load('保存编辑中...');
                                                                  }else{
                                                                     return;
                                                                  }
                                                                  $(String.format("#{0}",
                                                                  window.opts.modify_form_id)).ajaxSubmit(options); 
                                                             },
                                                             "重置":function(){
                                                                  $(String.format("#{0}",
                                                                  window.opts.modify_form_id)).resetForm();
                                                             }
                                                        }
                                                     });
                                         $("#{0}".format(window.opts.modify_panel_id)).dialog("open");
                                        
                                         //填充格式数据
                                         for(var i in dr){
                                                switch(dr[i].type)
                                                {
                                                    case "Radio":
                                                         $("#"+window.opts.placeholder_id+"_m_"+dr[i].name).attr("checked",dr[i].value);
                                                        break;
                                                    case "Select":
                                                        var sl =
                                                        $(String.format("#{0}_m_{1}",
                                                        window.opts.placeholder_id,dr[i].name))
                                        
                                                        if(dr[i].option!=null){
                                                            var soptions = dr[i].option;
                                                            var sb = new StringBuilder();
                                                            sb.append("<option value=''>选择</option>");
                                                            for(var o in soptions){
                                                                sb.append(
                                                                String.format("<option value='{0}' >{1}</option>",
                                                                soptions[o].value,soptions[o].text)
                                                                );
                                                            }
                                                            sl.html(sb.tostring());
                                                        }
                                                        sl.val(dr[i].value);
                                                        if(sl.children(":selected").val()!=dr[i].value){
                                                            sl.append(String.format(
                                                            "<option value='{0}'>{1}</option>",dr[i].value,dr[i].value)
                                                            );
                                                            sl.val(dr[i].value);
                                                        }
                                                        break;
                                                    case "CheckBox":
                                                        $(String.format("#{0}_m_{1}",window.opts.placeholder_id,
                                                        dr[i].name)).attr("checked",dr[i].value=="True"?true:false);
                                                        break;
                                                    case "Text":
                                                        $(String.format("#{0}_m_{1}",window.opts.placeholder_id,
                                                        dr[i].name)).val(dr[i].value);
                                                        break;
                                            
                                                   }
                                            }
                                       }else{
                                            $.Window.message(data.value,1);
                                       }
                               },
                               beforeSend:function(){
                                    $.Window.load('加载中...');
                                    return true;
                               },
                               error: function() {$.Window.unload(); $.Window.message("加载失败！",1); return false; } 
                           });
                },
                refurbishRow:function(rows){
      
                    var content = $(String.format("#{0}",this.opts.table_content)).children("tbody");
                    var list = $.evalJSON(rows);
                    for(var index in list){
                        var newRow = $(this.formatData(String.format("[{0}]",$.toJSON(list[index])),false));
                        var oldRow = content.children(String.format("[key='{0}']",newRow.attr("key"))).replaceWith(newRow);
                        newRow.attr("id",oldRow.attr("id"));                         
                        if(this.opts.show_mode_setting.is_show_row_index){
                            //获取旧行 中的行索引 赋到新行
                            newRow.children(":eq(0)").text(oldRow.children(":eq(0)").text());
                        }
                        this._bindRowEvent(newRow);
                    }
                },
                ///<summary>
                /// 查询处理
                ///</summary>
                Query:function(){
                      var list = this.opts.query.query_list;
                      var query_params = new StringBuilder();
                      for(var index in list){
                        var item = list[index];
                    
                        var input = $(String.format("#{0}",item.html_id))
             
                        if($.trim(input.val())!="")//获取查询
                        {
                           var stype ;
                           if(item.symbol_types.length>1){
                                stype = $(
                                    String.format("#{0}_s_{1}",this.opts.placeholder_id,item.html_id)
                                ).val();
                           }else{
                                stype = item.symbol_types[0].type;
                           }
                           query_params.append(
                               String.format(
                                   '{"column_name":"{0}","type":"{1}","symbol":"{2}","value":"{3}"},'
                                   ,item.column_name,item.data_type,stype,$.trim(input.val())
                                   ));
                        }
                        
                      }
                    //alert(query_params.tostring());
                      var currentQueryJson = query_params.tostring();
                      if(currentQueryJson!="")
                        currentQueryJson =String.format("[{0}]",currentQueryJson.substring(0,currentQueryJson.length-1));
                      if(currentQueryJson!=""){
                          this.opts.current_query= $.evalJSON(currentQueryJson); //设置当前查询
                          
                          //判断是否是第一次查询
                          if($("#{0}".format(this.opts.window_query_pager)).html()==""){
                            this._initQueryPager();
                          }
                          
                          this.getQueryInfo(1);
                      }
                    
                },
                ///<summary>
                /// 数据分页
                ///</summary>
                ///<param name="count">数据总数</param>
                ///<param name="currentIndex">当前分页索引</param> 
                renderingPaging:function(count,currentIndex){
                        $("#{0}".format(this.opts.window_all_count)).text(
                        String.format("(共有{0}行数据 当前第{1} 页)",count,currentIndex)
                        );
                        var pagecount = Math.ceil(parseInt(count)/parseInt(this.opts.page_size));
                        this.opts.current_page_count = count;
                        $("#{0}".format(this.opts.window_all_div_count)).text(pagecount);
                        $("#{0}".format(this.opts.window_all_div_input)).val(currentIndex);
                 
                },
                getPaginInfo:function(pageindex)
                {            
                    //当页索引大于总数者显示最后一页
                    var maxindex = Math.ceil(parseInt(this.opts.current_page_count)/parseInt(this.opts.page_size));
                    maxindex =maxindex==0?1:maxindex
                    this.opts.current_page_index = pageindex>maxindex?maxindex:pageindex;
                 
                    var json={
                        "request_type":$.REQUEST_TYPE.PAGING,
                        "options":this.opts
                    } 
                    var window = this;
                    $.ajax({
                        type: "POST",
                        dataType:"json",
                        url: this.opts.request_url,
                        data: { windowID:this.opts.placeholder_id,windowRequest:$.toJSON(json)},
                        success: function(data){
                                $.Window.unload();
                                if(data.state==1){
                                   window.opts.window_state=$.WINDOW_STATE.PAGING;
                                   window.tableFillContent(window.formatData(data.value,true));
                                   
                                   window.renderingPaging(data.dataCount,window.opts.current_page_index);
                                }else{
                                     $.Window.message("没有返回的数据错误了",1);
                                }
                        },
                        error:function (XMLHttpRequest, textStatus, errorThrown) {
                            $.Window.message("出错啦！ 无法获取信息！",1);
                            $.Window.unload();
                        },
                        beforeSend: function(XMLHttpRequest){ 
                            $.Window.load("加载中...");
                        }
                    });
                },//获取分页数据
                renderingQuery:function(count,currentIndex){
                        $("#{0}".format(this.opts.window_query_count))
                        .text(String.format("(查询{0}行数据 当前第{1} 页)",count,currentIndex+1));
                        var pagecount = Math.ceil(parseInt(count)/parseInt(this.opts.page_size));
                        this.opts.current_query_count = count;
                        $("#{0}".format(this.opts.window_query_div_count)).text(pagecount);
                        $("#{0}".format(this.opts.window_query_div_input)).val(currentIndex);

                },
                getQueryInfo:function(pageindex){
                    //当页索引大于总数者显示最后一页
                    var maxindex = Math.ceil(parseInt(this.opts.current_query_count)/parseInt(this.opts.page_size));
                    maxindex =maxindex==0?1:maxindex
                    this.opts.current_query_index = pageindex>maxindex?maxindex:pageindex;
      
                    var json={
                        "request_type":$.REQUEST_TYPE.QUERY,
                        "options":this.opts
                    } 
                    
                    var window = this;
                    $.ajax({
                        type: "POST",
                        dataType:"json",        
                        url: this.opts.request_url,
                        data: { windowID:this.opts.placeholder_id,windowRequest:$.toJSON(json)},
                        success: function(data){
                                $.Window.unload();
                                if(data.state==1){
                                   window.opts.window_state=$.WINDOW_STATE.QUERY;
                                   window.tableFillContent(window.formatData(data.value,true));
                                   window.renderingQuery(data.dataCount,window.opts.current_query_index);
                                }else{
                                   $.Window.message("没有返回的数据错误了",1);
                                }
                        },
                        error:function (XMLHttpRequest, textStatus, errorThrown) {
                            $.Window.message("出错啦！ 无法获取信息！",1);
                            $.Window.unload();
                        },
                        beforeSend: function(XMLHttpRequest){ 
                            $.Window.load("加载中...");
                        }
                    });
                },
                refurbish:function(){
                    if(this.opts.window_state==$.WINDOW_STATE.PAGING){
                        this.getPaginInfo(this.opts.current_page_index);
                    }else if(this.opts.window_state==$.WINDOW_STATE.QUERY){
                        this.getQueryInfo(this.opts.current_query_index);
                    }else if(this.opts.window_state==$.WINDOW_STATE.INSERT){
                        this.getPaginInfo(this.opts.current_query_index);
                    }
                },
                setPageSize:function(value){
                    this.opts.page_size = parseInt(value);
                    this.refurbish();
                },
                getSelectRowKey:function(){
                    return $(String.format("#{0}",this.opts.current_select_row)).attr("key");
                },
                getFocusRowKey:function(){
                    return $(String.format("#{0}",this.opts.current_focus_row)).attr("key");
                },
                getCheckedRowKeys:function(){
                    //获取CHECKBOX 所在列索引
                    var headtd = $(String.format("#{0}",this.opts.table_header)).children("thead").children(":eq(0)").children();
                    var index ;
                    for(index=0;index<headtd.size();index++){
                        if(headtd.eq(index).attr("id")==String.format("{0}_{1}",this.opts.placeholder_id,$.Window.as_th_checkbox))
                        break;
                    }
                    var checklist = $("#{0}".format(this.opts.table_content)).find("tbody").children("tr")
                    var list = new Array();//选中项主键集合
                    //获取选中项
                    for(var i=0;i<checklist.size();i++){
                       var trItem = checklist.eq(i);
                       var cbItem = trItem.children(":eq("+index+")").children("input[type='checkbox']")
                       if(cbItem.attr("checked"))
                       {  
                           list.push("'{0}'".format(cbItem.val()));
                       }
                    }
                    return list;
                },
                ////-------------------------------表格模式-----------------------------------------------------
                ///<summary>
                /// 构造表格显示模式
                ///</summary>
                tableMode:function(){
                        var id = this.opts.placeholder_id;
                        var windowPanel = $(String.format("#{0}",id));
                       // 在IE 6 7下DIV 不设置高度也没有内容html 则height()获取的值变成最后已个DIV元素的HEIGHT了 奇怪
//                        var isAutoHeight = false;
//                        if ($.browser.msie&&$.browser.version =='7.0'||$.browser.version =='6.0')
//                            if(windowPanel.get(0).style.height==""){ alert("我是IE垃圾浏览器");isAutoHeight=true;}
//                        else
//                            if(windowPanel.height()<22)isAutoHeight=true;
                        windowPanel.html("&nbsp;");//对付IE怪癖
                        if(windowPanel.height()<22)windowPanel.height(400);//默认高度是400px    
                        //-----------------
		                var builder = new StringBuilder();
		                
                        builder.append(String.format("<div id='{0}' class=\"ui-state-default window_header\"  >",this.opts.window_header));
                        
                        builder.append("<ul id='{0}' class='ui-widget ui-helper-clearfix window_toolber'>".format(this.opts.window_header_toolber));
                        
                        builder.append(String.format("<li><span id='{0}'></span></li>",this.opts.window_all_count));
                        
                        builder.append(String.format("<li><span id='{0}'></span></li>",this.opts.window_query_count));
                        builder.append(
                                String.format("<li><select id='{0}' ><option value=\"10\">10</option><option value=\"18\" selected='selected' >20</option><option value=\"30\">30</option></select></li>"
                                             ,this.opts.window_pageItem)
                                );
                        builder.append("</ul>");
                        builder.append("</div>")
                        //WINDOW 内容 
                       
                        
                        builder.append(
                                String.format("<div id='{0}' class='window_content'>",
                                this.opts.window_content
                                )
                            );
                        
                        builder.append("</div>");
                        //window Table 底部    
                        builder.append(String.format("<div id='{0}' class='ui-state-default window_footer'>",this.opts.window_footer));
                        builder.append("<table border=\"0\"><tr>");
                        builder.append(
                                    String.format("<td><div id='{0}'></div></td>",
                                                  this.opts.window_all_pager)
                                    );
                        builder.append(
                                    String.format("<td><div id='{0}' ></div></td><td><span id='{1}' title='退出录入状态' class=\"ui-icon ui-icon-closethick\" style='display:none;' onclick=\"WindowInstances['{2}']._cancalInsertState()\"></span></td></tr></table>",  
                                    this.opts.window_query_pager,
                                    this.opts.window_close_Insert_state,
                                    id
                                    ));
                        //退出录入状态

                        
                        builder.append("</div>");
                        builder.append("<div id='{0}' class='window_resize_mark' style='display: none; left: 389px; top: 0px; height: 195px;'>&nbsp;</div>".format(this.opts.window_resize_mark))
                        windowPanel.html(builder.tostring());
                        $("#{0}".format(this.opts.window_close_Insert_state)).hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); })
                        //计算内容区域高度
                        var mh= $("#{0}".format(this.opts.placeholder_id)).height();
                        var hh = $("#{0}".format(this.opts.window_header)).height()+2;//加上边框
                        var fh = $("#{0}".format(this.opts.window_footer)).height()+2;//加上边框
                    
                        $("#{0}".format(this.opts.window_content)).height(mh-hh-fh);
                        //
                        var window = this;
                        if(this.opts.toolber_setting!=null)
                        {
                            if(this.opts.toolber_setting.show_fefurbish){
                                
                                var toolber = $("#{0}".format(this.opts.window_header_toolber));
                                var refresh = 
                                $("<li class='ui-corner-all' title='刷新'><span class=\"ui-icon  ui-icon-refresh\" style='display:block;'></span></li>").hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); })
                                .bind('click', function() {
                                    window.refurbish();
                                });
                                toolber.append(refresh);
                                
                            }
                        }
                        
                        //分页设置  
                        var selectPs = $(String.format("#{0}",this.opts.window_pageItem));
                         
                        if(this.opts.page_size_item!=null)
                        {
                            var list = this.page_size_item.split(',');
                            var html = new StringBuilder();
                            for(var i in list){
                                    html.append(String.format("<option value='{0}'>{1}</option>"),list[i],list[i]);
                            }
                            selectPs.html(html.tostring());
                        } 
                       selectPs.val(this.opts.page_size);
                       if(selectPs.val() != this.opts.page_size)
                            selectPs.append("<option value='{0}' selected='selected' >{0}</option>".format(this.opts.page_size));
                       
                       selectPs.change(function(){
                           window.setPageSize(this.value);
                       });
                       //设置默认列宽
                       var columns = this.opts.columns;
                       for(var ci in columns){
                           columns[ci].width = columns[ci].width==-1?125:columns[ci].width;
                       }
                       //初始化分页组件
                       this._initAllPager();
                       
                },
                ///<summary>
                /// 构造表格显示模式 
                ///</summary>
                ///<param name="data">格式的数据</param>
                ///<param name="isheader">是否显示头</param> 
                ///<param name="isifh">是否是第一次录入格式表头</param> 
                formatData:function(data,isheader,isifh){
                    var dataList  = $.evalJSON(data);; 
                 
                    var showMode = this.opts.show_mode_setting;
                    var columnlist = this.opts.columns;
                    var builder = new StringBuilder();
                    var swidth=0;
                    var cheight=0;
                    var widthTr = new StringBuilder();//内容第一行用户设置单元格宽度
                    if(isheader){
                        //--------计算表格宽度-----------
                        for(var ci in columnlist){
                           if(columnlist[ci].is_show)
                           //计算总宽度
                           swidth+=columnlist[ci].width;
                        }
                        if(showMode.is_show_row_index)
                           swidth+=this.opts.ticWidth;
                        if(showMode.is_show_checkbox)
                           swidth+=this.opts.tccWidth;
                        if(showMode.is_show_oper_column)
                           swidth+=this.opts.tocWidth;
                       //---------内容表格高度计算--------
                       var ch= $("#{0}".format(this.opts.window_content)).height();
                       cheight=ch-22;
                       
                    }
                    //-------end table width ---------
                    if(isheader){//是否设置表头
                        //header tr html
                        var hc = new StringBuilder();
                        widthTr.append("<tr class='tablefirstRow'>");
                        hc.append("<tr>");
                        if(showMode.is_show_row_index){  
                            hc.append("<th id='{0}_{1}' width='{2}px' class='ui-state-default'><div class='window_th'>序号</div></th>"
                            .format(this.opts.placeholder_id,$.Window.as_th_index,this.opts.ticWidth));
                             widthTr.append(String.format("<td style='width:{0}px;'></td>",this.opts.ticWidth));
                        }
                        if(showMode.is_show_checkbox){
                            hc.append(
                            String.format("<th id='{0}_{1}' width='{2}px' class='ui-state-default' ><input id=\"cbAllSelect\" type=\"checkbox\" onclick=\"WindowInstances['{3}'].allSelect(this)\" /></th>"
                            ,this.opts.placeholder_id,$.Window.as_th_checkbox,this.opts.tccWidth,this.opts.placeholder_id)
                            );
                            widthTr.append(String.format("<td style='width:{0}px;'></td>",this.opts.tccWidth));
                            
                        }
                        if(showMode.is_show_oper_column){
                            hc.append("<th id='{0}_{1}' width='{2}px' class='ui-state-default'><div class='window_th'>操作</div></th>".format(
                            this.opts.placeholder_id,$.Window.as_th_oper,this.opts.tocWidth));
                            widthTr.append(String.format("<td style='width:{0}px;'></td>",this.opts.tocWidth));
                        }
                        
                        for(var i in columnlist){
                            var clm = columnlist[i];
                            var isshow = clm.is_show;
                            if(columnlist[i].is_show)
                            {
                                //设置当前排序列
                                if(clm.is_order){
                                    var order = clm["order"];
                                    var ocln = order.default_order?(order.order_type==$.ORDER_TYPE.DESC)?
                                    clm.alias_name +"<span>▼</span>": clm.alias_name+"<span>▲</span>":clm.alias_name;
                                    hc.append(
                                    String.format("<th id='{0}_{1}'  class='ui-state-default' width='{2}px' style=\"cursor:pointer\" onmouseover=\"$(this).addClass('ui-state-focus')\" onmouseout=\"$(this).removeClass('ui-state-focus')\"  cname='{4}' ><div class='window_th' onclick=\"WindowInstances['{3}'].columnOrderBy('{4}')\" >{5}</div></th>",
                                    this.opts.placeholder_id,"th"+i,clm.width,this.opts.placeholder_id,
                                    clm.alias_name,ocln)
                                    ); 
                                }else{
                                    hc.append(String.format("<th id='{0}_{1}' cname='{3}' width='{2}' class='ui-state-default' ><div class='window_th'>{3}</th>",this.opts.placeholder_id,"th"+i,clm.width,clm.alias_name));
                                }
                                widthTr.append(String.format("<td style='width:{0}px;'></td>",clm.width));
                            }
                        }
                        
                        hc.append("</tr>");
                        widthTr.append("</tr>")
                        //------end  header tr html ---- 
                        builder.append(
                            String.format("<div id='{0}' class='ui-state-default headerWrap'>",
                            this.opts.table_header_wrap)
                        );
                        builder.append(String.format("<table id='{0}' border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width='{1}px' class='tableHeader'>",
                            this.opts.table_header,swidth)
                        );
                        builder.append("<thead>");
                        builder.append(hc.tostring());
                        builder.append("</thead>");
                        builder.append("</table>");
                        builder.append("</div>");
                        
                    }

                    //---------table content html-------------------
                    var tc = new StringBuilder();
                    
                    for(var rowIndex in dataList){
                        var dataItem = dataList[rowIndex];//获取数据项
                   
                        for(var index in columnlist){//赋值
                            var column = columnlist[index];//获取列对象
                            if(column.is_key)
                            {
                                var key_id = dataItem[column.alias_name]
                                if(this.opts.window_state!=$.WINDOW_STATE.INSERT){
                                    tc.append(String.format(
                                        "<tr class='{0}'  id='{1}_r_{2}' key='{3}'>",$.Window.class_content_tr,
                                        this.opts.placeholder_id,rowIndex,key_id)
                                        );
                                }else{
                                    tc.append(String.format(
                                        "<tr class='{0}' id='{1}_r_{2}' key='{3}'>",$.Window.class_content_tr,
                                        this.opts.placeholder_id,$(String.format("#{0}",this.opts.table_content)).children('tbody').children().size(),key_id)
                                        );
                                }
                                //设置行号
                                if(showMode.is_show_row_index){
                                    //设置 录入状态 序号
                                    if(this.opts.window_state==$.WINDOW_STATE.INSERT){
                                        tc.append(
                                            String.format("<td>{0}</td>",
                                                $(String.format("#{0}",this.opts.table_content)).children('tbody').children().size())
                                            );
                                    }
                                    else{
                                        tc.append(
                                            String.format("<td>{0}</td>",
                                            isifh?1:(this.opts.current_page_index-1)*(this.opts.page_size)+(parseInt(rowIndex)+1)
                                            )
                                        );
                                    }
                                   
                                }
                                if(showMode.is_show_checkbox){
                                    tc.append(
                                    String.format("<td><input type='checkbox' value='{0}'/></td>",
                                    key_id));
                                    
                                }
                                if(showMode.is_show_oper_column){//设置是否有操作列
                                    tc.append("<td>");
                                 
                                     
                                    tc.append(this.funs.formatOperColumn(this.opts.placeholder_id,dataItem,key_id));
                                       
                                   
                                    
                                    tc.append("</td>");
                                }
                                break;
                            }
                        }
                        for(var index in columnlist){//赋值
                            var column = columnlist[index];//获取列对象
                            var aliasName = column.alias_name//获取列名
                            var value = dataItem[aliasName]//获取数据
                            if(column.is_show){
                                tc.append(
                                String.format("<td>{0}&nbsp;</td>"
                                ,this.funs.format(dataItem,aliasName,value))
                                );
                                
                            }
                        }
                        tc.append("</tr>");
                    }
                    //------------------table content html------------------
                    //是否设置表头
                    if(isheader){
                        builder.append(
                            String.format("<div id='{0}' style='height:{1}px' class='ui-widget-content contentWrap'>",this.opts.table_content_wrap,cheight)
                        );
                        builder.append(
                            String.format("<table id='{0}' border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width='{1}' class='tableContent'>",
                            this.opts.table_content,swidth)
                        );
                        builder.append(widthTr.tostring());
                        builder.append(tc.tostring());
                        builder.append("</table>");
                        builder.append("</div>");

                    }else
                        builder.append(tc.tostring());
                    return builder.tostring();
                },
                //列排序
                columnOrderBy:function(asName){
                    var columns = this.opts.columns;
                    for( var i in columns)
                    {
                        var order = columns[i]["order"];
                        if(order==null) continue;
                        if(columns[i].alias_name==asName)
                        {
                            order.default_order = true;
                            order.order_type = order.order_type == $.ORDER_TYPE.DESC?$.ORDER_TYPE.ASC:$.ORDER_TYPE.DESC
                        }else{
                            order.default_order = false;
                        }
                    }
                    this.refurbish();
                    
                },
                //取消录入状态
                _cancalInsertState:function(){
                   if(this.opts.window_state==$.WINDOW_STATE.INSERT){
                        $("#{0}".format(this.opts.window_close_Insert_state)).hide(); 
                        this.refurbish();
                   }else{
                        $("#{0}".format(this.opts.window_close_Insert_state)).hide(); 
                   }
                },
                tableFillContent:function(content){
                    var body = null;
                    if(this.opts.window_state==$.WINDOW_STATE.PAGING||this.opts.window_state==$.WINDOW_STATE.QUERY){
                         $("#{0}".format(this.opts.window_content)).html(content);
                         body =$("#{0}".format(this.opts.table_content)).children('tbody').children("tr");
                         this._bindHeadeResize();
                    }else if(this.opts.window_state==$.WINDOW_STATE.INSERT){
                        body = $(content);
                        var panel = $("#{0}".format(this.opts.table_content))
                        .children('tbody').append(body);
                    }
                    this._bindRowEvent(body); 
               },
               _bindHeadeResize:function(){
               //设置表格内容滚动对齐
                 var window = this;
                 $("#{0}".format(this.opts.table_content_wrap)).scroll(function() {
                        $("#{0}".format(window.opts.table_header))
                        .css("left","-"+$(this).scrollLeft()+"px")
                 });
                 var resize="<span class='window_resize' style='cursor:col-resize;'>&nbsp;</span>";
                 $("#{0}".format(this.opts.table_header)).children("thead").children(":eq(0)").children("th")
                .each(function(i){
                       var th = $(this);
                       var reobj = $(resize);
                       if(th.attr("cname")==null)return;
                       th.prepend(reobj);
                });
                 var tc = $("#{0}".format(window.opts.window_content));//拖动主键
                       tc.unbind();
                       tc.mousedown(function(e){
                            if ($(e.target).closest("th>span.window_resize").length != 1) { return; }
                            if(window.opts.current_resize_header==null){
                                var dobj =$(e.target);
                                var pt =dobj.offset();
                                window.opts.current_resize_header = dobj.parent();
                                
                                document.onselectstart=function(){  return false;};
                                $("body").addClass("ff_not_select");
                                var hf = window.opts.current_resize_header.offset();
                                this.curd = $("#{0}".format(window.opts.window_resize_mark)).css(
                                //2是边框不然无法触发MOUSEUP
                                {left:(hf.left+window.opts.current_resize_header.width()+2),
                                top:hf.top}).show().height($("#{0}".format(window.opts.window_content)).height());
                                this.hmin = hf.left+50;
                            }
                       });
                       tc.mousemove(function(e){
                            if(window.opts.current_resize_header!=null){
                                
                                if(e.pageX+2>this.hmin){
                                    this.curd.css({left:e.pageX+2});
                                }
                            }
                        });
                        tc.mouseup(function(){
                            if(window.opts.current_resize_header!=null){
                                var rm = $("#{0}".format(window.opts.window_resize_mark));
                                var h = window.opts.current_resize_header;
                                var am= rm.offset().left -(h.offset().left+h.width());

                                var newWidth =h.width()+am;
                                h.attr("width",h.width()+am);
                                //设置内容表格 列的宽度
                                var headtd = $(
                                String.format("#{0}",
                                window.opts.table_header)).children("thead").children(":eq(0)").children();
                                
                                var index ;
                                for(index=0;index<headtd.size();index++){
                                    if(headtd.eq(index).attr("id")==h.attr("id"))
                                    break;
                                }
                                var tr = $("#{0}".format(window.opts.table_content)).children('tbody')
                                .children(":eq(0)");
                                tr.children(":eq({0})".format(index)).width(newWidth);
                                //更新配置JSON
                  
                                for(var i in window.opts.columns)
                                {
                                    if(window.opts.columns[i].alias_name == h.attr("cname")){
                                        window.opts.columns[i].width=newWidth;
                                        break;
                                    }
                                }
                                //更新 header content table width
                                var header = $("#{0}".format(window.opts.table_header));
                                var ths = header.children("thead").children(":eq(0)").children();
                                var content = $("#{0}".format(window.opts.table_content));
                                
//                                        var tds = content.children("tbody").children(":eq(0)").children();
                                var newwidth = 0;
                                for(var thi=0;thi<ths.size();thi++)
                                    newwidth+=parseInt(ths.eq(thi).attr("width"));
                                header.attr("width",newwidth);
//                                        var newcwidth = 0;
//                                        for(var tds=0;tds<tds.size();tds++)
//                                            newcwidth+=parseInt(tds.eq(tds).attr("width"));
                                content.attr("width",newwidth);
                                //收尾工作
                                rm.hide();
                                document.onselectstart=function(){return true;};
                                $("body").removeClass("ff_not_select");
                                window.opts.current_resize_header = null;
                                    //清空临时数据
                                this.hmin=null;
                                this.curd=null;
                            }
                        });
               },
               _bindRowEvent:function(row){
                	 this.opts.current_select_row=null; //清空当前选中行
			         this.opts.current_focus_row=null; //清空焦点行
			         var window = this;
			         row.unbind();
                     row.click(function(){
                        var sitem = $(this);

                        window.funs.selectIndexChanging(window.opts.current_select_row);
                        this.className = String.format("{0} ui-state-error ",$.Window.class_content_tr);
                        sitem.siblings()
                        .each(function(){
                            
                            if(this.id!="")
                            this.className=$.Window.class_content_tr;
                        });
                        window.opts.current_select_row = this.id;
                        window.funs.selectIndexChanged(window.opts.current_select_row);
                    })
                    
                    .mouseover(function(){
                        var oitem = $(this);
                        window.opts.current_focus_row = this.id;
                      oitem.toggleClass("window_mouseover");//.css("font-weight","normal");
                    }).mouseout(function(){
                      $(this).toggleClass("window_mouseover");
                   
                    });
                    
//                      .mouseover(function(){
//                        window.opts.current_focus_row = this.id;
//                        var split = this.className.split(' ');
//                      
//                        var ish = true;
//                        for(var i = 0 ;i<split.length;i++){
//                            if(split[i]=='ui-state-highlight'){
//                                ish = false;
//                                break;
//                            }
//                        }
//                        if(ish){
//                            this.className='ui-widget-content ui-state-focus';
//                            this.style.fontWeight = "normal";
//                        }
//                    }).mouseout(function(){
//                    
//                        if(this.className=="ui-widget-content ui-state-focus")
//                        this.className="ui-widget-content";
//                    });  

                },
                ///<summary>
                /// CHECKEBOX 选中 或不选中
                ///</summary>
                allSelect:function(obj){
                    var cb =$(obj).attr("checked");
                    var headtd = $(
                    String.format("#{0}",
                    this.opts.table_header)).children("thead").children(":eq(0)").children();
                    
                    var index ;
                    for(index=0;index<headtd.size();index++){
                        if(headtd.eq(index).attr("id")==
                        String.format("{0}_{1}",this.opts.placeholder_id,$.Window.as_th_checkbox))
                        break;
                    }
                  
                    var checklist = $("#{0}".format(this.opts.table_content)).children("tbody").children();
           
                    for(var i=0;i<checklist.size();i++)
                    {
                       checklist.eq(i)
                       .children(":eq("+index+")")
                       .children("input[type='checkbox']")
                       .attr("checked",cb);

                    }
                    
                    
                    
                },
                ///<summary>
                /// 行命令
                ///</summary>
                rowCommand:function(command,callback,key){
                    var json={
                        "request_type":$.REQUEST_TYPE.ROW_COMMAND,
                        "options":this.opts,
                        "command":command,
                        "key":key==null?$("#"+this.opts.current_focus_row).attr("key"):key
                    }
                    var window = this;
                    $.ajax({
                        type: "POST",
                        dataType:"json",
                        url: this.opts.request_url,
                        data: { windowID:this.opts.placeholder_id,windowRequest:$.toJSON(json)},
                        success: function(data){
                                $.Window.unload();
                          
                                if(data.state==1){ 
                                   if(callback!=null){
                                        callback(data.value);
                                   }
                                }else{
                                   $.Window.message(data.value,1);
                                }
                        },
                        error:function (XMLHttpRequest, textStatus, errorThrown) {
                            $.Window.message("出错啦！",1);
                            $.Window.unload();
                        },
                        beforeSend: function(XMLHttpRequest){ 
                            $.Window.load("执行中...");
                        }
                    });
                },
                //<summary>
                // 选中操作
                ///</summary>
                selectRowCommand:function(command,callback){
                    var list = this.getCheckedRowKeys();
                    if(list.length>0){
                        var json = {
                            "request_type":$.REQUEST_TYPE.SELECT_ROW_COMMAND,
                            "options":this.opts,
                             "command":command,
                            "selectKeys":list.join(',')
                        };
                        var window = this;
                        var result = null;
                        $.ajax({
                            type: "POST",
                            dataType:"json",
        
                            url: this.opts.request_url,
                            data: { windowID:this.opts.placeholder_id,windowRequest:$.toJSON(json)},
                            success: function(data){
                                $.Window.unload();
                                if(data.state==1){ 
                                    if(callback!=null)
                                        callback(data.value);
                                        //待解决问题 操作选中项 后更新这些选中项
                                    
                                }else{
                                    $.Window.message(data.value,1);
                                }
                            },
                            error:function (XMLHttpRequest, textStatus, errorThrown) {
                                $.Window.message("出错啦！",1);
                                $.Window.unload();
                            },
                            beforeSend: function(XMLHttpRequest){ 
                                $.Window.load("执行中...");
                            }
                        });
                         
                    }else{
                        $.Window.message('请选择项！',1);
                    }
                }
        });
       
})(jQuery);

//-------------JSON---------------------
(function($){$.toJSON=function(o)
{if(typeof(JSON)=='object'&&JSON.stringify)
return JSON.stringify(o);var type=typeof(o);if(o===null)
return"null";if(type=="undefined")
return undefined;if(type=="number"||type=="boolean")
return o+"";if(type=="string")
return $.quoteString(o);if(type=='object')
{if(typeof o.toJSON=="function")
return $.toJSON(o.toJSON());if(o.constructor===Date)
{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
if(o.constructor===Array)
{var ret=[];for(var i=0;i<o.length;i++)
ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]";}
var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;if(typeof o[k]=="function")
continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
{if(string.match(_escapeable))
{return'"'+string.replace(_escapeable,function(a)
{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};})(jQuery);