﻿/*

Ajax function v2.1
add ajaxproxy support v1.2
add more argument support v1.5
add async support v1.5
add another plan to solve domain problem,get only v1.6
add response status & reprogramed v2.0
add auto encode at get / more debug

itsuki@yeah.net 20080927
*/
//ajax 方式提交数据
function ajax(url) {
	url = url.toLowerCase();
	var search = (this.ajax.arguments.length>1)?this.ajax.arguments[1]:'';
	var method = ((this.ajax.arguments.length>2)?this.ajax.arguments[2]:'get').toLowerCase();
	var special = (this.ajax.arguments.length>3)?this.ajax.arguments[3]:null;
	
	var ver = '2.1 build0927';
	var xmlHttp,xmlHttpName;
	var response;
	var scriptObj;
	var defdocument = 'index.aspx';
	var proxy = true;
	var debug =false;
	var async = true;
	var jse = false;
	var suffix = true;
	var showerr = true;
	var timer = null;
	var timeout = 20;
	var responseObj = null;
	var stater = '_ajaxstatus';
	var ajaxstatus = 'loading';
	var imgpath = 'http://www.pk.com/images/ajax/';
	
	try {eval(special)} catch(e) {}
	try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}; if (typeof(xmlHttp)=='object')xmlHttpName='Msxml2.XMLHTTP';
	try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}; if (typeof(xmlHttp)=='object')xmlHttpName='Microsoft.XMLHTTP';
	try { xmlHttp = new XMLHttpRequest() } catch(e) {}; if (typeof(xmlHttp)=='object')xmlHttpName='XMLHttpRequest';
	
	if (xmlHttp == null) {jse == true;}
	if (window.location.search.indexOf('|debug')!=-1){debug=true};
	if (method=='post'){if(url.charAt(url.length-1) == '/'){url+=defdocument}}	//fix iis 6.0- (post default document)	
	
	$id = function(objname){return document.getElementById(objname)}
	
	//检查跨域
	gethost = function(location){
		new RegExp('.+?\:\/\/(.+?)\/','ig').exec(location);
		return RegExp.$1
	}
	if (url.indexOf(':\/\/')>0 && gethost(url)!=window.location.hostname) {
		if (method=='get'){jse = true};
		if (method=='post'){url = '/AjaxProxy/'+defdocument+'?'+encodeURI(url)};
	}
	
//	if (debug){
//			alert(
//					'ajax ver :' + ver +
//					//'\nscript 引擎:' + ScriptEngine() + ' Version ' + ScriptEngineMajorVersion() + '.' + ScriptEngineMinorVersion() + '.' +ScriptEngineBuildVersion() + 
//					//'\nxmlHttp =' + navatgor.userAgent + 
//					'\nxmlHttp = '+xmlHttpName+
//					'\nurl = '+url+
//					'\nsearch = '+search+
//					'\nmethod = '+method+
//					'\ndefdocument = '+defdocument+
//					'\nproxy = '+proxy+
//					'\ndebug = '+debug+
//					'\nasync = '+async+
//					'\njse = '+jse+
//					'\ntimeot = '+timeout+
//					'\nstater = '+stater+
//					'\nresponseObj = '+responseObj+
//					'\najaxstatus = '+ajaxstatus+
//					'\nimgpath = '+imgpath
//				)
//	}

	//缓存responseObj
	if (responseObj!=null) {
		try{ajaxobj_cache=$id(responseObj).innerHTML}catch(e){};
	}
	
	
	//添加删除节点
	appendChild = function(obj){
		try{document.getElementsByTagName('head')[0].appendChild(obj)}catch(e){
			try{document.body.appendChild(obj)}catch(e){};
		};
	}
	removeChild = function(obj){
		try{document.getElementsByTagName('head')[0].removeChild(obj)}catch(e){
			try{document.body.removeChild(obj)}catch(e){};
		};
	}
	
	
	//script方式跨域
	scriptExecute = function (url){
		var rdmid		= Math.random()*255;
		scriptObj		= document.createElement('script');
		scriptObj.type	= 'text\/javascript';
		scriptObj.id	= 'ajax_executer'+rdmid;
		appendChild(scriptObj);
		scriptObj		= $id('ajax_executer'+rdmid)
		
		scriptObj.onreadystatechange = function(){
			if (debug) alert('scriptExecute.readyState : ' + scriptObj.readyState)
			if (scriptObj.readyState == 'complate' || scriptObj.readyState=='loaded') {
				showstatus('complate');
				removeChild(scriptObj);
			}
			
		}
		
		//兼容opera
		scriptObj.onload = function(){
			if (debug) alert('scriptExecute.readyState : ' + onload)
			showstatus('complate');
			removeChild(scriptObj);
		}
		
		scriptObj.src	= url;
		if (debug) alert('scriptExecute url: \n' + url)
	}
	
	//标准反馈
	response = function(){
			if (xmlHttp.status == 200){
				if (debug){alert('default response : \n' + xmlHttp.responseText)};
				showstatus('complate');
				try{eval(xmlHttp.responseText);} catch(e){alert('返回数据执行错误');showstatus('error');}
			} else {
				showstatus('error');
				if (showerr){
					alert('读取数据失败 错误代码\:'+xmlHttp.status+'\n[URL\:'+url+']');
					if (debug)document.write(xmlHttp.responseText);
				};
			}
			
	}
	
//装载ajax反馈容器
	attachStater = function(){
		if ($id(responseObj) == null) return false ;
		if ($id(stater)==null){
			$id(responseObj).outerHTML = '<span id="'+stater+'" style="float:left"></span>' + $id(responseObj).outerHTML;
		}
	}
		
	//状态反馈
	showstatus = function(status){
		ajaxstatus = status;
		attachStater(stater);
		var obj = $id(stater);
		try{
			switch(status){
				case 'loading':
					obj.innerHTML = '<img src="'+imgpath+'/Loading.gif" title="与服务器通信中..." alt="与服务器通信中..." />';
					break;
				case 'complate':
					obj.innerHTML = '<img src="'+imgpath+'/complate.gif" title="完成" alt="完成" />';
					setTimeout('showstatus(\'blank\')',500)
					break;
				case 'lost':
					obj.innerHTML = '<img src="'+imgpath+'/lost_contact.gif" title="服务器超时未返回,点击尝试恢复" alt="服务器超时未返回,点击尝试恢复" style="cursor:hand" onclick="this.outerHTML=\'\';restore(\''+responseObj+'\')" />';
					break;
				case 'error':
					obj.innerHTML = '<img src="'+imgpath+'/error.gif" title="服务返回了一个错误,点击尝试恢复" alt="服务返回了一个错误,点击尝试恢复" style="cursor:hand" onclick="this.outerHTML=\'\';restore(\''+responseObj+'\')" />';
					ajaxstatus = 'complate';
					break;
				case 'blank':
					obj.innerHTML = '';
					ajaxstatus = 'complate';
			}
			clearTimeout(timer);
		}catch(e){}
	}
	
	//超时检测
	starttimer = function(){
		timer = setTimeout('timerchk()',timeout*1000);
	}
	timerchk = function(){
		if (ajaxstatus!='complate'){
			showstatus('lost');
		}
	}
	
	showstatus('loading');			//载入状态
	starttimer();					//超时计时器启动
	
	switch (method){
		default:	//get
			if(url.indexOf('?')==-1){url+='?'};
			url += search;
			if (suffix) url += '&'+ new Date().valueOf(Date);
			//对中文字符编码
			url = url.replace(/([^\x21-\x7E])/g,function($0,$1){return encodeURIComponent($1)});

			//跨域转向script代理
			if (jse){scriptExecute(url);return;}
				
			xmlHttp.open("get",url,async);
			xmlHttp.setRequestHeader("Content-Type","text/html;charset=UTF-8")
			xmlHttp.setRequestHeader("Contrn-charset","UTF-8"); 
			xmlHttp.setRequestHeader("If-Modified-Since","0");
			if (debug) alert('xmlHttp get :\nurl : '+url+'\nasync : '+async);
			xmlHttp.send('');
			break;
		case 'post':
			xmlHttp.open("post",url,async);
			xmlHttp.setRequestHeader("Content-Type","text/html;charset=UTF-8")
			xmlHttp.setRequestHeader("Contrn-charset","UTF-8"); 
			xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			xmlHttp.setRequestHeader("If-Modified-Since","0");
			if (debug) alert('xmlHttp post :\nurl : '+url+'\nsearch : '+search+'\nasync : '+async);
			xmlHttp.send(search);
			break;
	}
	
	
	if(async==false)response();			//如果强制同步直接反馈
	
	//异步反馈
	xmlHttp.onreadystatechange = function(){
		if (debug) alert('xmlHttp.readyState : ' + xmlHttp.readyState);
		if (xmlHttp.readyState == 4) {response();}
	}
	
}

//公共缓存ajax前端
var ajaxobj_cache = '';
function restore(obj){
	if(ajaxobj_cache!=''){
		try{$id(obj).innerHTML=ajaxobj_cache}catch(e){};
	}
}

//集合form内数据
function compform(formname){
	var objForm = document.forms[formname];
	var formItems = objForm.elements;
	var formItemsCount = formItems.length;
	var res = "";
	for(var i=0;i<formItemsCount;i++) {
		if(formItems[i].type == "radio" || formItems[i].type == "checkbox"){
			if (formItems[i].checked == true){
				res += (formItems[i].name) || (formItems[i].id);
				res += "=";
				res += formEncode(formItems[i].value);
				res += '&'
			}
		}else{
			res += (formItems[i].name) || (formItems[i].id);
			res += "=";
			res += formEncode(formItems[i].value);
			res += '&'
		}
	}
	return(res);
}

//psot 方式编码
function formEncode(str){
	//
	str = str.replace(/%/g, "%25");
	str = str.replace(/&/g, "%26");
	str = str.replace(/#/g, "%23");
	//str = str.replace(/?/g, "%3F");
	str = str.replace(/\+/g, "%2B");
	str = str.replace(/=/g, "%3D");
	str = str.replace(/ /g, "%20");
	str = str.replace(/\n/g, "<br/>");
	
	return(str);
}

function getchkvalue(obj){
	var tempstr = '';
	for(i=0;i<obj.length;i++){
		if(obj[i].checked == true){
			if (tempstr.length >0){tempstr += ',';}
			tempstr += obj[i].value;
		} 
	} 
	return tempstr;
}

function encode(str){
	return encodeURIComponent(str)	
}

function showobj(obj){
	if(obj.style.display == 'none'){
		obj.style.display = ''}
	else{obj.style.display = 'none'}
}