var Global = Class.create();
Global.CONTEXT_PATH = '';

/**
 * by leili
 * @requires 
 * url,请求的url
 * form,表单无素或表单ID
 * callback,回调方法
 * callerArguments, 调用者的arguments
 * loginCallback,当timeout之后，进行登录完成后，进行的回调方法。此方法在callerArguments为空时，有效
 * other,其它参数(字符串形式:如&a=1&b=2)
 * action,执行结果元素或其ID
 * region,window的显示的范围
 * asynchronous，同步与否，默认为true
 * isHideVeil, 是否显示遮罩和loading图标
 */
var Request = Class.create({
	initialize: function(options){
	
		Object.extend(this, options);

		this.form = $(this.form);
		this.action = $(this.action);
		this.region = $(this.region)||$(document.body);
		if(this.asynchronous==null)
			this.asynchronous = true;

		this.backupJson = this.jsonObject;
		this.jsonObject = null;
		this.isHideVeil=this.isHideVeil||false;
		if(!this.isHideVeil){
			this.veil = this.initVeil();
			this.showVeil();
	        this.showLoading();
		}
		
        this.removeStatus();

		if(this.other){
		  if(this.other.charAt(0) != '&') 
			this.other = '&' + this.other;
		}else{
		  this.other = '';
		}
		
		var paramsValueString =  this.form?Form.serialize(this.form):'';
		
		Element.disableFormElements(this.region);
		
		var params = paramsValueString+this.other;
		//params = params + '&responseType='+this.responseType;
		//alert("submit---->"+params);
		
		var myAjax = new Ajax.Request(this.url,{method:"post",parameters:params,onComplete:this.callbackBySuccess.bind(this),onException:this.callbackByException.bind(this),asynchronous:this.asynchronous});
//		if(!myAjax.options.asynchronous){
//		  this.callbackBySuccess(myAjax.transport);
//		}
		myAjax=null;

	},
	
	jsonObject:null,
	
	backupJson:null,
	
	responseType:'json',
	
	remove: function(){
		Element.enableFormElements(this.region);
		 if(!this.isHideVeil){
			  this.hideVeil();
			  this.removeLoading();
			  //if(this.action) this.action.innerHTML = "";
		 }
		 backupJson = null;
	},

	processTimeout : function(){
		//var win = top.Request.createLoginWindow(this);
		//win.show(true);
		top.location.href=Global.LOGIN_PATH||Global.CONTEXT_PATH+"/";
	},
	
	callbackBySuccess: function(request){
			(function(request){
			  try{
				   var jsonString=request.responseText;
				   //alert("result---------->"+jsonString);
			      (new Function("this.jsonObject="+jsonString)).call(this);
				  switch(this.jsonObject.result){
				      case 0x00001:
					      if(this.callerArguments || this.loginCallback){
					    	  this.remove();
					    	  this.processTimeout();
					      }else{
					    	  top.location.href = Global.LOGIN_PATH||Global.CONTEXT_PATH+"/";
					      }
						  break;
					  default:
					      this.callback();
						  if(!this.hasError && this.jsonObject.successMessage) this.showSuccess(this.jsonObject.successMessage||"");
				  }
				  
			  }catch(e){
				  alert(e.message);
			  }
			}).call(this,request);
		  this.timeoutIds.push(setTimeout(this.remove.bind(this),500));
	},
		
	callbackByException: function(request,e){
		  this.showError(e);
		  if(this.backupJson){
			  this.jsonObject = this.backupJson; 
		  }
		  this.timeoutIds.push(setTimeout(this.remove.bind(this),500));
	},
	timeoutIds: [],
	hasError:false,
	showLoading: function(){
		this.container.innerHTML = "<img src='" + Global.CONTEXT_PATH + "/images/load.gif' border='0'>";
	},
	showSuccess: function(msg){
	    if(this.action){
	    	$(this.action).className="success";
	    	$(this.action).show();
	    	this.action.innerHTML = "<!--img src='" + Global.CONTEXT_PATH + "/images/success.gif' border='0' /--> " + (msg||"") + "";
	    }
	},
	removeLoading: function(){
		this.container.innerHTML = "";
	},
	showError: function(error){
		this.hasError = true;
	    if(this.action){
	    	$(this.action).show();
	    	$(this.action).className="error";
	    	if(error && error.title){
	    		this.action.innerHTML = "<table border='0' cellspacing='0' cellpadding='0'><tr>"+
				"<td width='16'><img src='" + Global.CONTEXT_PATH + "/images/error.gif' border='0' /></td>"+
				"<td align='left' style='font-weight:bold'>" + error.title + "</td></tr>" +
				"<tr><td></td><td>" + error.detail + "</td></tr>"
				"</table>";
	    	}else{
				this.action.innerHTML = "<!--img src='" + Global.CONTEXT_PATH + "/images/error.gif' border='0' /--> " + (error||"") + "";
	    	}
	    	
		}
	},
	removeStatus: function(){
		if(this.action){
			$(this.action).hide();
			this.action.innerHTML = "";
		}
	},
	initVeil: function(){
		var result = document.createElement("div");
		result.style.position = "absolute";
		//Position.absolutize(result);

		result.style.top = '0px';
		result.style.left = '0px';
		result.style.background = "url(" + Global.CONTEXT_PATH + "/images/dark_bg.gif)";
		
		
		var bodyClientHeight = this.region.offsetHeight||document.body.offsetHeight;
		var bodyClientWidth = this.region.offsetWidth||document.body.offsetWidth;
		
		result.style.height = bodyClientHeight + "px";
		result.style.width =  bodyClientWidth + "px";
		
		Element.setOpacity(result,0.2);
		result.style.zIndex = 99;
        Element.setStyle(this.region,{position:'relative'});
		result.hide();
		
		var load = new Element("div");								
		load.setStyle({position:'absolute'});
		load.setStyle({top:0,left:0,width:bodyClientWidth + "px",height:bodyClientHeight + "px",zIndex:100});
		
		var table = new Element("table");
		table.setStyle({width:'100%',height:'100%'});
		load.insert(table);
		
		
		var tbody = new Element("tbody");
		table.insert(tbody);
		
		var tr = new Element("tr");
		tbody.insert(tr);
		
		
		var td = new Element("td");
		tr.insert(td);
		
		var div = new Element("div");
		div.align = "center";
		td.insert(div);
		
		this.region.appendChild(load);
		this.container = div;
		this.container.parent = load;
		
		this.region.appendChild(result);
		return result;
	},
	showVeil: function (){
		this.veil.show();
		this.container.parent.show();
	},
	hideVeil: function(){
		this.veil.hide();
		this.container.parent.hide();
	}
}); 


Request.createLoginWindow = function(request){
	var tempFun = null;
	if(request.callerArguments){
		tempFun = (function(){
			request.callerArguments.callee($A(request.callerArguments));
		}).bind(request);
	}else{
		tempFun = request.loginCallback.bind(request);
	}
	
	if(signInWin==null){
		signInWin = new UI.Window({url: Global.CONTEXT_PATH+"/user/auth.do?method=signInInput",width: 355, height: 204, callback:tempFun});
	}
	
	Global.DEFAULT_WINDOW_MANAGER.push(signInWin);
	return signInWin;
};



var HTMLRequest =Class.create(Request, {
	responseText:"",
	callbackBySuccess:function(request){
		try{
			if(request.responseJSON){
				if(request.responseJSON.result==0x00001){
					if(this.callerArguments || this.loginCallback){
					    this.processTimeout();
				    }else{
				    	top.location.href = Global.CONTEXT_PATH+'/';
				    }
				}
			}else{
				this.responseText=request.responseText;
				try{
					if(this.responseText.isJSON()){
						this.jsonObject=this.responseText.toJSON();
					}
				}catch(e){
					this.jsonObject=null;
				}
				this.callback(request);
			}
		  }catch(e){
			  alert(e.message);
		  }
		  this.timeoutIds.push(setTimeout(this.remove.bind(this),500));
	},
	callbackByException:function(request,e){
		  this.showError(e);
		  this.timeoutIds.push(setTimeout(this.remove.bind(this),500));
	}
	
}); 
