/** 
 * 自定义全局通用函数 
 *  
 * @author  
 */  
(function($) {  
    $.sendGet = function(url, data, callback, errCallback, type){  
        return $.send(url, data, callback, errCallback, type, 'GET');  
    }  
  
    $.sendPost = function(url, data, callback, errCallback, type){
        return  $.send(url, data, callback, errCallback, type, 'POST');
    } 
    
    $.sendPostTb = function(url, data, callback, errCallback, type){
        return  $.send(url, data, callback, errCallback, type, 'POST',false);
    }
  
    $.sendPut = function(url, data, callback, errCallback, type){  
        data._method='PUT';  
        return $.send(url, data, callback, errCallback, type, 'POST');  
    }  
  
    $.sendDelete = function(url, data, callback, errCallback, type){  
        data._method='DELETE';  
        return $.send(url, data, callback, errCallback, type, 'POST');  
    }  
      
    $.send = function(url, data, callback, errCallback, dtype, stype,async){  
        if ( jQuery.isFunction(data) ) {  
            if( !jQuery.isFunction( callback ) ){  
                dtype = callback;  
                errCallback = data;//没有定义错误处理方法时，采用成功的处理方式  
            }else{  
                dtype = errCallback;  
                errCallback = callback;  
            }  
            callback = data;  
            data = {};  
        }else if( !jQuery.isFunction( errCallback ) ) {  
            dtype = errCallback;  
            errCallback = callback;//没有定义错误处理方法时，采用成功的处理方式  
        }  
          
        if(stype==null){  
            stype = "GET";  
        }  
        
        if(async==null){  
        	async = true;  
        }
  
        //访问成功后回调  
        var cmpCallback = function( res, status ) {  
            var data = jQuery.parseJSON(res.responseText);  
            var code = 200;  
            try{  
                code = data.bq_status;  
            }catch(e){}  
  
        }  
          
        return jQuery.ajax({  
            type: stype,  
            url : url,  
            data: data, 
            async: async,
            success : function( data, status, xhr ){  
                var type = "success";  
                try{  
                    type = data.bq_type;  
                }catch(e){}  
                if(type=="error"){  
                    errCallback.call(this, data, status, xhr);  
                }else{  
                    callback.call(this, data, status, xhr);  
                }  
            },  
            error   : errCallback,  
            complete: cmpCallback,  
            dataType: dtype  
        });  
    }  
      
})(jQuery);

BusinessObject = function() {
	return {
		delegate : function(type) {
			for (var p in this) {
				if (typeof(this[p]) == "function") {
					if (p != 'delegate') {
						this[p] = function() {
							var mn = p;
							return function() {
							   if(type=="" || type==null) return "-1";
							   this.action = type;
							   var param = arguments[0];
							   var struts2MethodURL=this.action + "_" + mn;
							   if(this.module!="" && this.module.length>0 && this.module != null){
								   struts2MethodURL = this.module + "/" + struts2MethodURL;
							   }
							   function load_val(callback){
								 $.sendPostTb(
									  struts2MethodURL, 
									  param, 
									  function(data){
										 callback(data);  
								      },
									  null,
									  "json"
								  );
							   }
							   var jsonDATA = {};
							   load_val(function(data){
								   jsonDATA = data; 
							   });
							   return jsonDATA;
							};
						}();
					}
				}
			}
		 return this;
		}
	};
}();

var tempJsonData = {};

function getTempJsonData(){
	return tempJsonData;
}
function setTempJsonData(data){
	tempJsonData = data;
}


function renderDATA(data,row,rowsid){
    $.each(data, function(i,n){
     var jsonObj = eval(n);
     for(var property in jsonObj)
     {
      row.find("#"+property).text(jsonObj[property]);
     }
     row.appendTo("#"+rowsid);//添加到模板的容器中
     row = row.clone();
   });
  }

function renderDATAFORM(data,row){
    $.each(data, function(i,n){
    	var $this = row.find("#"+i);
    	var d_n = n;
    	if($this.is("[format='yyyy-MM-dd']")){
    		if(d_n.length>10){
    			d_n = d_n.substring(0,10);
    		}
    		row.find("#"+i).val(d_n);
    	}else if($this.is("select")){
    		var field_id = $this.attr("id");
    		$("#"+field_id+" option[value='"+d_n+"']").attr("selected", true);
    	}else if($this.is(":radio")){
			var field_name = $this.attr("name");
			$("[name="+field_name+"][value="+d_n+"]").attr("checked",true); 
		}else if($this.is(":checkbox")){
			var field_name = $this.attr("name");
			$("[name="+field_name+"]").attr("checked",false);
			$("[name="+field_name+"][value="+d_n+"]").attr("checked",true);
		}else{
    		row.find("#"+i).val(n);
    	}
    	
    });
  }

function renderDATAROW(data,row){
    $.each(data, function(i,n){
    	row.find("#"+i).text(n);
    });
  }

function getSearchData(data,rowName){
	var arr_data = [];
    $.each(data, function(i,n){
    	var jsonObj = eval(n);
    	arr_data[i] = jsonObj[rowName];
    });
    return arr_data;
  }

//------------自动加载修正----------------------------------
function renderSPAN(data,row,rowsid){
    $.each(data, function(i,n){
     var jsonObj = eval(n);
     row.find("span").each(function(){
    	if($(this).attr("id")+''!='undefined'){
    		var tid = $(this).attr("id");
    		if(jsonObj[tid]+''=='undefined'){
    			$(this).text('');
    		}else{
    			$(this).text(jsonObj[tid]);
    		}
    		
    	}
     });
     row.appendTo("#"+rowsid);//添加到模板的容器中
     row = row.clone();
   });
  }
//----------------------------------------------

function renderJSP(targetObj, templateURL, data) {
	$(targetObj).setTemplateURL(
			templateURL,
			null, {
				filter_data : false
			}).processTemplate(data);
}



function renderJSP1(targetObj, template, data) {
	  	$(targetObj).setTemplateElement(template);
		$(targetObj).processTemplate(data);

	  }

function loadCSS(css,target){
	
	
	var eHead = document.getElementById(target);
	var eLink = document.createElement("link");
	eLink.rel = "stylesheet";
	eLink.type = "text/css";
	eLink.href = css;

	eHead.appendChild(eLink);
}

function loadJS(js,callback){
	$.getScript(js,callback);
}


/**
 * 单条json转string
 * @param o
 * @returns {String}
 */
function json2str(o) { 
  var arr = []; 
  var fmt = function(s) { 
  if (typeof s == 'object' && s != null) return json2str(s); 
      return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s; 
  } 
  for (var i in o) arr.push("'" + i + "':" + fmt(o[i])); 
  return '{' + arr.join(',') + '}'; 
 }

/**
 * json数组转string
 * @param jsonArray
 * @returns {String}
 */
function JsonArrayToString(jsonArray){ 
    var JsonArrayString = "["; 
    for(var i=0;i<jsonArray.length;i++){ 
      JsonArrayString=JsonArrayString+json2str(jsonArray[i])+","; 
    } 
    JsonArrayString = JsonArrayString.substring(0,JsonArrayString.length-1)+"]"; 
    return JsonArrayString; 
}

/**
 * 获取表单数据
 * @param formid
 * @returns {String}
 */
function getFormData(formid){//serializeArray=json,serialize=string
	var jsonArray = $('#'+formid).serializeArray();
    var JsonArrayString = "{"; 
    for(var i=0;i<jsonArray.length;i++){ 
      JsonArrayString=JsonArrayString + "'" + jsonArray[i]["name"]+ "'" + ":"+ "'" + jsonArray[i]["value"]+"',"; 
    } 
    JsonArrayString = JsonArrayString.substring(0,JsonArrayString.length-1)+"}"; 
    return eval("(" + JsonArrayString + ")"); 
}

/**
 * 获取标准库表数据<select><option>
 **/
function getStdOption(data){
   var opetionType = "";
   var i=0;
   for(i=0;i<data[0].rowSet.length;i++){
	   var rowData = data[0].rowSet[i];
	   opetionType = opetionType + " <option value=\""+rowData.CODE_ID+"\">"+rowData.CODE_NAME+"</option>";
	}
   return opetionType;
}

/**
 * 获取标准库表数据根据code_id返回code_name<select><option>
 **/
function getCodeName(data,code_id){
   var code_name = "";
   var i=0;
   for(i=0;i<data.length;i++){
	   var rowData = data[i];
	   if(rowData.CODE_ID == code_id){
		   code_name = rowData.CODE_NAME;
	   }
	}
   return code_name;
}

function getUUIDName(data,uuid){
	   var name = "";
	   var i=0;
	   for(i=0;i<data.length;i++){
		 var rowData = data[i];
		 if(rowData.UUID == uuid){
		    name = rowData.NAME;
		 }
	   }
	   return name;
	}

function getRoleName(data,dpt_no){
	   var name = "";
	   var i=0;
	   if(dpt_no!=null && dpt_no!='' && dpt_no.split(',').length>1){
		   var dptnos = dpt_no.split(',');
		   for(var s in dptnos){
			   for(i=0;i<data.length;i++){
				  var rowData = data[i];
				  if(rowData.DPT_NO == dptnos[s]){
					 name = name + rowData.DPT_NAME + ',';
					 break;
				  }
			   }
		   }
		   name = name.substring(0, name.length - 1);
	   }else{
	     for(i=0;i<data.length;i++){
		   var rowData = data[i];
		   if(rowData.DPT_NO == dpt_no){
			 name = rowData.DPT_NAME;
			 break;
		   }
		 }
	   }
	   return name;
	}

function getPortletName(data,portlet_id){
	   var name = "";
	   var i=0;
	   for(i=0;i<data.length;i++){
		 var rowData = data[i];
		 if(rowData.PORTLET_ID == portlet_id){
		    name = rowData.NAME;
		 }
	   }
	   return name;
	}

/**
 * 单位数据根据code_id返回code_name<select><option>
 **/
function getUnitName(data,uuid){
   var name = "";
   var i=0;
   for(i=0;i<data.length;i++){
	   var rowData = data[i];
	   if(rowData.UUID == uuid){
		   name = rowData.NAME;
	   }
	}
   return name;
}

function getSysUserName(data,uuid){
	var name = "";
	var i=0;
	for(i=0;i<data.length;i++){
	   var rowData = data[i];
	   if(rowData.CODE == uuid){
		  name = rowData.EMNAME;
	   }
	}
   return name;
}

function getuuid_codeame(data,uuid){
   var code_name = "";
   var i=0;
   for(i=0;i<data.length;i++){
	   var rowData = data[i];
	   if(rowData.UUID == uuid){
		   code_name = rowData.CODE_NAME;
		   break;
	   }
	}
   return code_name;
}

/**
 * 从data单位树中找出最高一极的单位UUID
 **/
function getParentID(data,parent){
   var unit_id = "";
   var i=0;
   for(i=0;i<data.length;i++){
	   var rowData = data[i];
	   if(rowData.PARENT_ID == parent){
		   unit_id = rowData.UUID;
		   break;
	   }
	}
   return unit_id;
}

/**
 * 获取checkbox选中值
 */
 function getCheckBoxValue(checkboxname){
	 var str="";
     $("input[name='"+checkboxname+"']:checkbox").each(function(){ 
        if($(this).attr("checked")){
           str += $(this).val()+",";
        }
     });
     if(str.length>1){
    	 str = str.substring(0, str.length - 1);
     }
     return str;
 }


//修改名称显示
function changeNameDisplay(str,length){
    var l = str.length;
    if(l<length){
        return str;
    }else{
        return str.substring(0,length)+"...";
    }
}

//关闭
function closeFancyBox(alertContent,type){
    if(alertContent&&alertContent != ''){
    	if(type == 1){
        	fancyAlert(alertContent,"1");//成功
    	}else if(type == 0){
    		fancyAlert(alertContent,"0");//失败
    	}else if(type == 2){
    		fancyAlert(alertContent,"2");//警告
    	}
    }
    if(type == 1){
	    setTimeout(function(){
	    	$.fancybox.close(); // 关闭FancyBox 模态窗口
	    },1000);
    }else{
    	$.fancybox.close(); // 关闭FancyBox 模态窗口
    }
}
/**
 * 获取标准库表数据根据code_id返回code_name<select><option>
 **/
function getCodeName(data,code_id){
   var code_name = "";
   var i=0;
   for(i=0;i<data.length;i++){
	   var rowData = data[i];
	   if(rowData.CODE_ID == code_id){
		   code_name = rowData.CODE_NAME;
	   }
	}
   return code_name;
}

/**
 * 增加字段
 **/
function getDataAddNode(data,code_id,code_name){
   var i=0;
   for(i=0;i<data.length;i++){
	   var rowData = data[i];
	   rowData[code_id] = code_name;
	}
   return data;
}
//添加判断字段是否是部门还是人员
function getDataUnitOrUser(data, imageUrl){
	var i = 0;
	for(i=0;i<data.length;i++){
		var rowData = data[i];
		if(rowData["UUID"].indexOf("1_")>=0){
			rowData["icon"] = imageUrl + "/images/main/bumen.gif";
		}else if (rowData["UUID"].indexOf("2_")>=0){
			rowData["icon"] = imageUrl + "/images/main/renyuan.gif";
		}
	}
	return data;
}

//定义一些全局方法
(function($){
	$.getUrlParam = function(name){
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if (r!=null) return unescape(r[2]); return null;
	};
	$.getJwWindowPic = function(){
		return "icon-window-pic";
	};
	$.getJwAdvsearchPic = function(){
		return "icon-ext-advsearch";
	};
}(jQuery));


