/**
 * Newtouch Bairn JS Library 0.1
 * 
 * Depands on jQuery.js and newtouch-common.js
 * Copyright(c) 2009 Newtouch
 * 
 * xiaohua.ding@newtouch.cn
 *
 * 本文件中所有的以'_'符号开头的方法被认为是private的方法或属性，不对外部公开的。
 * 如果外部使用了以'_'符号开头的方法或属性，一旦出现问题将由使用者自己解决。
 *
 * 增加对Newtouch.Direct下所有方法的加密支持
 * gan.shen@newtouch.cn
 * 2010-05-21
 *
 */

Newtouch.message = {
	
	onLoad:function(){
		//TODO dosoming before load
	},
	offLoad:function(){
		//TODO dosoming after load
	},
	
	/**
	 * validate  
	 * 默认css依赖 newtouch-common.css 
	 */
	_error:'error',
	_fine:'fine',
	
	/**
	 * 输入框的验证信息
	 * @param input 验证的输入控件jQuery对象
	 * @param message 验证后显示的信息
	 * @param error 验证是否正确[true/false]
	 */
	validate:function(input,message,error){
	
		var msg = "";
		
		if(error){
		
			msg = this._errorHTML(input,message,this._error);
			input.addClass(this._error);
			
		}else{
		
			msg = this._errorHTML(input,message,this._fine);
			input.removeClass(this._error);
		}
		
		input.parent().find("span." + this._error + " label").replaceWith(msg);
	},
	
	_errorHTML:function(input,message,cls){
	
		var msgHTML = "<label class='" + cls + "' " + " generated='true' " + " for='" + input.attr("id") + "'> " + message + "</label>";
		return msgHTML;
	},
	
	showMsg:function(msg,sucess){
		alert(msg);
	}
};

Newtouch.Util = {

	/**
	 * 处理URI使之不带'?'和'#'及任何参数
	 * 如果URI带有'#'在ie下会导致不能提交请求
	 *
	 */
	helperUrl:function(url){
  		var index = url.indexOf("?");
  
	  	if(index>0){
	   		return url.substring(0,index);
	  	}
	  
	  	var indexSharp = url.indexOf("#");
	  
	  	if(indexSharp>0){
	   		return url.substring(0,indexSharp);
	  	}
	  	
	  	var indexSession = url.indexOf(";jsessionid");
	  	
	  	if(indexSession>0){
	  		return url.substring(0,indexSession);
	  	}
	  
	  	return url;
 	},

	/**
	 * 在action中也可以带上url的形式如下
	 * requiredpage.jsp.actionname
	 */
	helperAction:function(action){
		var point = action.lastIndexOf(".");
		if(point >= 0){
			var url = action.substring(0,point);
			var _action = action.substring(point+1,action.length);
			return {
				url:url,
				action:_action
			}
		}else{
			var url = this.helperUrl(document.URL);
			return {
				url:url,
				action:action
			}
		}
	},
	
	/**
	 * 把action作为参数放入到参数列表中。
	 */
	helperParams:function(params,action){
		if(typeof(params) == "string"){
			params = this._stringParams(params,action);
		}else{
			params['_action'] = action;
		}
		
		return params;
	},
	/**
	 * 处理返回值中的回车换行符号(\n\r)
	 * @param data 返回的responseText
	 * @param replacestr 把\n\r替换为指定的字符，默认为<br/>
	 */
	helperResponse:function(data,replacestr){
		if(typeof(data)=="object"){
			return data;
		}
		if(replacestr == undefined){
			replacestr = "<br/>";
		}
		
		while(data.indexOf("\n\r")>0){
			data = data.replace("\n\r",replacestr);
		}
	
		while(data.indexOf("\n")>0){
			data = data.replace("\n",replacestr);
		}
		while(data.indexOf("\r")>0){
			data = data.replace("\r",replacestr);
		}
		if(data.indexOf("\\")>0){
			data = data.replace(/\\/g,"\\\\");
		}
		return data;
	},
	
	/**
	 * 处理导出的参数只能为String类型。
	 */
	helperExportParams:function(params,action){
		return this._stringParams(params,action);
	},
	
	_stringParams:function(params,action){
	
		if(typeof(params) == "string"){
		
			if(params == ""){
			params = "_action="+action;
			}else{
				params += "&_action=" + action;
			}
			
		}else if(typeof(params) == "object"){
			for(var name in params){
				params += name + "=" + params[name] + "&";
			}
			
			params += "_action="+action;
		}
		
		return params;
		
	},
	stringToObject:function(string){
		if(string == null || string.length == 0){
			return {};
		}
		var stringArray = string.split("&");
		var stringObject = new Object();
		for(var i = 0 ;i < stringArray.length ; i++){
			var kv = stringArray[i].split("=");
			if(kv.length == 1){
				continue;
			}
			stringObject[kv[0]]=kv[1];   
		}
		return stringObject;
	}
	
};

Newtouch.Ajax = {

	_requestObject:function(url,params,successCallback,failCallback,syncCall){
		return {
			async: (syncCall != null && syncCall)? false: true,
			url:url,
			data:params,
			type:'POST',
			contentType:'application/x-www-form-urlencoded; charset=utf-8',
			success:function(data){
			
				data = Newtouch.Util.helperResponse(data);
				
				var response = null;
				if(data == ""){
					response = {err:null,result:null};
				}else{
					response = eval("(" + data + ")");
				}
				if(response.err == null){
					successCallback(response.result);
				}else{
					failCallback(response.err);
				}
			}
		};
	},
	/**
	 * 通过FORMID发送请求
	 * @param formId  FORM表单ID
	 * @param action  后台方法名
	 */
	sendForm:function(formId,action,successCallback,failCallback,syncCall){
	
		var ac = Newtouch.Util.helperAction(action);
		var params = $("#" + formId).formSerialize() + "&_action=" + ac.action;
		
		$.ajax(this._requestObject(ac.url,params,successCallback,failCallback,syncCall));
				
	},
	/**
	 * 通过Params发送请求
	 * @param valueMap  页面上的值 格式："{id:id,name:name}"
	 * @param action  后台方法名
	 */
	sendParams:function(valueMap,action,successCallback,failCallback,syncCall){
		
		var ac = Newtouch.Util.helperAction(action);
		var params = Newtouch.Util.helperParams(valueMap,ac.action);
		
		$.ajax(this._requestObject(ac.url,params,successCallback,failCallback,syncCall));
	}

};

Newtouch.Direct = {

	/**
	 * 导出用的方法。
	 * 手动添加参数
	 */
	sendParamsExport:function(params,action){
	
		var ac = Newtouch.Util.helperAction(action);
		var urlParams = Newtouch.Util.helperExportParams(params,ac.action);
		
		location.href = ac.url + "?" + urlParams;
	},
	
	/**
	 * 导出用的方法，通过form ID传入参数。
	 */
	sendFormExport:function(formId,action){
	
		var ac = Newtouch.Util.helperAction(action);
		var params = Newtouch.Util.helperParams($("#" + formId).formSerialize(),ac.action);
		
		location.href = ac.url + "?" + params;
	},
	/**
	 * 直接把数据当做form表单传递。
	 */
	postDataWithForm : function(action,params,bCrypto){
	
		var divElem = document.createElement("div");
		$(divElem).css("display","none");
		
		var form = document.createElement("form");
		
		form.method = "post";
		form.action = action;
		params = params||{};
		if(params["_target"]){
            form.setAttribute("target",params["_target"]);
        }
		for(var p in params){
			if(params[p]!=undefined&&p!="_target"){
				var input = document.createElement("input");
				$(input).attr("name",p);
				$(input).attr("value",params[p]);
				form.appendChild(input);
			}
		}
		
		$(divElem).append($(form));
		$("body").append($(divElem));
		
		 if(bCrypto==true){
	     	     return this._cryptoPost(form);
	      }
		
		form.submit();
	},
	/**
	 * 直接把数据当做form表单传递。
	 */
	postDataWithWizardForm : function(action,params,bCrypto){
	
		var divElem = document.createElement("div");
		$(divElem).css("display","none");
		
		var form = document.createElement("form");
		
		form.method = "post";
		form.action = action;
		params = params||{};
		if(params["_target"]){
            form.setAttribute("target",params["_target"]);
        }
		
		var wizardParams = "&";
		
		for(var p in params){
			if(params[p]!=undefined&&p!="_target"){
				var input = document.createElement("input");
				$(input).attr("name",p);
				$(input).attr("value",params[p]);
				
				wizardParams += (p +"=" + params[p] + "&");
				form.appendChild(input);
			}
		}
		
		var wizardInput = document.createElement("input");
		$(wizardInput).attr("name","_wzv");
		$(wizardInput).attr("value",wizardParams);
		form.appendChild(wizardInput);
		
		$(divElem).append($(form));
		$("body").append($(divElem));
		
		if(bCrypto==true){
	     	     return this._cryptoPost(form);
	    }else{
			form.submit();
		}
	},
	
	 _cryptoPost : function(form){
	     var p = Newtouch.Crypto.encrypt($(form).serialize());
	     
	     var divCp = document.createElement("div");
		 $(divCp).css("display","none");
		
		 var formCp = document.createElement("form");
		
		 formCp.method = "post";
		 formCp.action = $(form).attr("action");
		 if(form["target"]&&form["target"]!=""){
			 formCp["target"]=$(form).attr("target");
		 }
		 var input = document.createElement("input");
		 $(input).attr("name","_cp");
		 $(input).attr("value",p);
		 formCp.appendChild(input);
		 $(divCp).append($(formCp));
	     $("body").append($(divCp));
		 formCp.submit();
	 }
};

Newtouch.Crypto = {

      encrypt  :  function(plaintext) {
			return this._bytes2hex(this._ascii2bytes(plaintext));
      },
            
      _bytes2hex :  function(binArray) {

          	var hex = '0123456789ABCDEF';
          	var hexstr = '';

          	var length = binArray.length;
          	for (var i = 0; i < length; i ++) {
          		var byte = binArray[i];
          		var indx = byte >> 4;
          		var indx2 = byte - (indx << 4);

          		hexstr += hex.charAt(indx) + hex.charAt(indx2);
      		}

          return hexstr;
      },
      
      _ascii2bytes : function(w,len) {
    	  if(len==undefined) len = w.length;
    	  var bytes = new Array(len);
    	  for (var i=0; i<len; i++) {
			    bytes[i] = isNaN(w.charCodeAt(i))?0:w.charCodeAt(i);
    	  }
    	  return bytes;
      }
} ;



