/*
	CopyRight (c) 2008 - Hamed.AtaeiDoost
	
	Methods:
		init(URL, ResultPanel, PictureLocation, LoadingTEXT);
			URL: destination page (asp, php, aspx, ...)
			ResultPanel: data recived show in this element {can null}
			PictureLocation: location of picture for loading show this element {can null}
			LoadingTEXT: text for loading that show unti data is process. this text show in PictureLocation {can null}
		important(BOOLEAN);
			is true alway that data recived check the data is Valid or no
			if not valid last value of elements back
		setSecureCode(STRING);
			STRING: each thing set for this variable you most response.write in end of text in Dynamic Page(asp, php, ...)
		setErr(STRING);
			STRING: if important is true and event not valid data handel then this STRING alert for user
		send(Option, FunctionNext);
			Option: a tag for send server. keyword is 'option';
			FunctionNext: name of function that you want when data recived run it. {can ''}
			
	How to use:
	//////////////
		HTML:
			<input onclick="JavaScript: myajax.send('','');" type="button" value="click"/>
		JAVASCRIPT:
			var myajax = new clsAjax;
			myajax.init('ajax.asp',document.getElementById('destination'), document.getElementById('Picture'), 'loading');
			myajax.important(true);
	/////////////
*/

function clsAjax(){
	var url = '';
	var panelresult = null;
	var pictureLocation = null;
	var innerhtml = 'LOADING';
	var qstr = '';
	var self = null;
	var functionName = '';
	var isImportant = false;
	var SecureCode = 'AjaxanFin';
	var temppictureLocation = new Array;
	var temppanelresult = new Array;
	var ErrMessage = '';
	var IsPicANDtext = false;
	
	this.init = function(URL, presult, plocation, inner){
		url = URL;
		panelresult = presult;
		pictureLocation = plocation;
		innerhtml = inner;
		IsPicANDtext = presult==plocation;
	}
	
	this.important = function(state){
		isImportant = state;
		if(!state)
			SecureCode = '';
	}
	
	this.setSecureCode = function(str){
		SecureCode = str;
	}
	
	this.setErr = function(str){
		ErrMessage = str;
	}
	
	this.setQuery = function(str){
		qstr = str;	
	}
	
	this.returnQuery = function(){
		return qstr;	
	}
	
	function ord(c){
		return c.charCodeAt(0);
	}

	function chr(n){
		return String.fromCharCode(n);
	}
	
	function updatepage(str){
		if(panelresult!='[object]')   panelresult = document.getElementById(panelresult);
		if(panelresult=='[object]'){
			try{panelresult.className = '';}catch(e){};
			try{pictureLocation.className = '';}catch(e){};
		}
		if (isImportant){
			var bb = true;
			if(str.indexOf(SecureCode)>-1){
				var temp = str.substr(str.indexOf(SecureCode), SecureCode.legnth);
				if (temp == SecureCode)
					str = str.substr(0,str.length-SecureCode.length);
				else
					bb=false;
			}else{
				bb=false;
			}
		}else{
			str = str.substr(0,str.length-SecureCode.length);
			bb=true;
		}
		if(!bb){
			if (ErrMessage!='')
				alert(ErrMessage);
			str = temppanelresult['innerHTML'];
			if(!IsPicANDtext){
				try{pictureLocation.innerHTML=temppictureLocation['innerHTML'];}catch(e){}
				try{pictureLocation.className=temppictureLocation['className'];}catch(e){}
			}
		}
		try{
		panelresult.className = temppanelresult['className'];
		panelresult.innerHTML = str;
		}catch(e){}
		if(bb)
			if(!IsPicANDtext)
				try{pictureLocation.style.display = "none";}catch(e){};
		if(functionName!='' && functionName)
			setTimeout(functionName, 1);
	} 
	
	this.send = function(option, FN) {
		if (url==''){
			alert("Error! url is null");
			return false;
		}
		functionName = FN;
		var xmlHttpReq = false; 
		self = this;
		// Mozilla/Safari 
		if (window.XMLHttpRequest) { 
			self.xmlHttpReq = new XMLHttpRequest(); 
		} 
		// IE 
		else if (window.ActiveXObject) { 
			self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); 
		}
		self.xmlHttpReq.open('POST', url, true); 
		self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); 
		self.xmlHttpReq.onreadystatechange = dataRecived;
		while(qstr.indexOf("+",0)>-1)
			qstr = qstr.replace("+","%2B");
		while(qstr.indexOf(" ",0)>-1)
			qstr=qstr.replace(" ","+");
		var x = this.optimize(this.getquerystring(option));
		self.xmlHttpReq.send(x);
	}
	
	function dataRecived(){
		if (self.xmlHttpReq.readyState == 4){
			updatepage(self.xmlHttpReq.responseText);
		}
	}
	
	this.clear = function (){
		qstr="";
	}

	this.optimize = function (str){
		if(qstr=='') return;
		try{
			var arrQuery = str.split("&");
		}catch(e){return;}
		var arrResult = new Array;
		var result;
		var state=true,t1,t2;
		try{
			for(var i=0, j=0, t; i<arrQuery.length;i++)
				if(arrQuery[i].indexOf('=')>-1)
					if(arrQuery[i].substr(arrQuery[i].indexOf('=')).length>1){
						t1 = arrQuery[i].substr(0,arrQuery[i].indexOf('='));
						for(t=0,state=true;t<arrResult.length-1;t++)
							if(t1.toLowerCase()==arrResult[t].substr(0,arrResult[t].indexOf('=')).toLowerCase()){
								state=false;
								t=arrResult.length+1;
							}
						if(state){
							arrResult[j] = arrQuery[i];
							j++;
						}
					}	
		for(i=0;i<arrResult.length;i++)
			result+=arrResult[i]+'&';
		result = result.replace('undefinednull=null&null=null&','');
		result = result.replace('undefinednull=null&','');
		result = result.replace('undefined','');
		}catch(e){result=qstr;}
		return result;
	}
	
	this.getquerystring = function (option) {
		if (panelresult !='[object]') panelresult = document.getElementById(panelresult);
		try{
			temppanelresult['innerHTML'] = panelresult.innerHTML;
			temppanelresult['className'] = panelresult.className;
			panelresult.className = "Ajax_Panel_Refresh";
		}catch(e){}
		try{
			if (pictureLocation !='[object]') pictureLocation = document.getElementById(pictureLocation);
		}catch(e){}
		try{
			temppictureLocation['innerHTML'] = pictureLocation.innerHTML;
			temppictureLocation['className'] = pictureLocation.className;
			pictureLocation.className = "Ajax_Panel_Refresh";
			pictureLocation.innerHTML = innerhtml;
		}catch(e){}
		this.addKey("option",option);
		var i;
		while (qstr.indexOf("&null=null&&null=null&")>-1)
			qstr = qstr.replace("&null=null&&null=null&", "&null=null&");
		return qstr;
	}	
	
	
	this.addKey = function (name,value){
		if (name=="") return 0;
		this.delKey(name);
		qstr = qstr + name.toLowerCase() + '=' + enCode(value) + '&null=null&';
	}
	

	this.delKey = function (name){
		if(qstr=='')
			return;
		if(name=='')
			return;
		name=name.toLowerCase();
		while(qstr.indexOf(name+'=')>-1)
			qstr = qstr.replace(name+'=','null=');
	}
	
	this.returnKey = function (name){
		qstr = this.optimize(qstr);
		var temp = qstr.split("&")
		var Params = new Object ();
		var key;
		for(var i=0;i<temp.length;i++){
			key = temp[i].split("=");
			if(key[0].toLowerCase()==name.toLowerCase())
				return key[1];
		}
		return '';
	}
	
	function enCode(str){
		var temp;
		temp=0;
		str = str.toString();
		while(str.indexOf('%',temp)>-1){
			str = str.substr(0,str.indexOf('%',temp)) +'%25'+ str.substr(str.indexOf('%',temp)+1,str.length);
			temp = str.indexOf('%',temp)+3;
		}
		/*while(str.indexOf("+",0)>-1)
			str = str.replace("+","%2B");
		while(str.indexOf(" ",0)>-1)
			str = str.replace(" ","+");
		*/while(str.indexOf('&',0)>-1)
			str = str.replace('&','%26');
		return str;
	}
}
