/*
Module Name : SSRSJS.muajaxer
Description : This module is to implement AJAX on any page. You just have to mention a few parameters to send either a variables or a form via AJAX. This single module works for all.
Pending Modification: Submition of Files via AJAX.
Developer : Tajinder Singh Namdhari
Developed On : 05-02-2008
Update On : 03-04-2008
License : LGPL
Company : SSRSJS Organisation
Website : http://www.ssrsjs.org
*/

/*Procedure to implement SSRSJS MultiuseAjaxer

Declare and object as below
	var myRequest=new sendAjaxRequest(trgtFormOrVar,trgtPage,trgtForm,trgtVarVal,trgtMethod,trgtObj,ignoreObj,diminishObj);
	
	Here the arguments are as below specifications:
		trgtFormOrVar -> Decides whether you are submitting a Form or just sending a GET Request, 0 Form and 1 for Variables
		 trgtPage -> URL of page to recieve the request
		trgtForm -> DOM ID of the Form, if you are submittin a Form. Otherwise a null ('')
		 trgtVarVal -> An Array containing Variable preceeding Value element, if send a GET Request. E.g. Array('rType','A','job','save')
		trgtMethod -> POST or GET in Single quotes. E.g.- ('POST')
		 trgtObj -> DOM ID of DIV,TD or any other Object to display response recieved for request made
		ignoreObj -> 0 or 1 depeding on either you want to point updated 'trgtObj' or not
		 diminishObj -> 1 or 0 depending on either you want to Diminish (to low opacity) the target object during updation or not
*/

function sendAjaxRequest(trgtFormOrVar,trgtPage,trgtForm,trgtVarVal,trgtMethod,trgtObj,ignoreObj,diminishObj,currHost,callItBack)
{
	var ajaxRequest=null;
	var errorTurn=0;
	var getStr="";
	var postStr="";
	var combinedString="";
	var currWaitId='cover' + Math.floor(Math.random()*101);
	var currHost=((currHost==null)||(currHost=='undefined'))?'':currHost;
	var callItBack=((callItBack==null)||(callItBack=='undefined'))?'':callItBack;
	
	this.posLeftX=function(obj)
	{
		var curleft = 0;
		if(obj.offsetParent)
			while(1) 
			{
			  curleft += obj.offsetLeft;
			  if(!obj.offsetParent)
				break;
			  obj = obj.offsetParent;
			}
		else if(obj.x)
			curleft += obj.x;
		return curleft;
	}
	
	this.posTopY=function(obj)
	{
		var curtop = 0;
		if(obj.offsetParent)
			while(1)
			{
			  curtop += obj.offsetTop;
			  if(!obj.offsetParent)
				break;
			  obj = obj.offsetParent;
			}
		else if(obj.y)
			curtop += obj.y;
		return curtop;
	}
	
	this.askToWait=function(currWaitId)
		{
			var currWait=document.createElement("div");
			currWait.setAttribute('id',currWaitId);
			currWait.setAttribute('style','position:absolute; top:35%; left:35%; display:none; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:18px; text-align:center; vertical-align:middle; border: 4px double #BBBBBB; color:#444444; background-color:#EEEEEE;');
			document.body.appendChild(currWait);
			
			document.getElementById(currWaitId).innerHTML='Wait while processing.......!';
		};
	
	//Function diminishing the target DOM Object
	this.dimIt=function(trgtId)
		{
			document.getElementById(trgtId).style.opacity='0.2';
			document.getElementById(trgtId).style.filter='alpha(opacity=20)';
			document.getElementById(currWaitId).style.display='block';
		};
	
	//Definition of function to encode and escape form field values
	this.makeParameters=function(trgtFormFields)
		{
			var lmt=trgtFormFields.length;
			for(i=0;i<lmt;i++)
			{
				if(i!=0)
				{	postStr+="&";	}
				
				if(trgtFormFields[i].type=='checkbox')
				{
					if(trgtFormFields[i].checked==true)
					{	postStr+=trgtFormFields[i].name + "=" + escape(encodeURI(trgtFormFields[i].value));	}
					else
					{	postStr+=trgtFormFields[i].name + "=" + '';	}
				}
				else if(trgtFormFields[i].type=='radio')
				{
					if(trgtFormFields[i].checked==true)
					{	postStr+=trgtFormFields[i].name + "=" + escape(encodeURI(trgtFormFields[i].value));	}
				}
				else
				{
					postStr+=trgtFormFields[i].name + "=" + escape(encodeURI(trgtFormFields[i].value));
				}
			}
		};
	
	if(trgtVarVal.length>0)
	{
		var lmt=trgtVarVal.length;
		for(i=0;i<lmt;i=i+2)
		{
			if(i!=0)
			{	getStr+="&";	}
			getStr+=trgtVarVal[i] + "=" + trgtVarVal[i+1];
		}
	}
	
	//Initialiazing the AjaxRequest Object
	if(window.XMLHttpRequest)
	{
		ajaxRequest=new window.XMLHttpRequest();
	}
	else
	{
		if(window.ActiveXObject)
		{
			ajaxRequest=new window.ActiveXObject("Microsoft.XMLHTTP");
			if(!ajaxRequest)
			{
				ajaxRequest=new window.ActiveXObject("Msxml2.XMLHTTP");
			}
			if(!ajaxRequest)
			{
				if($trgtFormOrVar==0)
				{
					document.getElementById(trgtForm).action=trgtPage + "?" + getStr;
					document.getElementById(trgtForm).method=trgtMethod;
					document.getElementById(trgtForm).submit();
				}
				else
				{	top.location.href=trgtPage + "?" + getStr;	}
			}
		}
		else
		{
			if(trgtFormOrVar==0)
			{
				document.getElementById(trgtForm).action=trgtPage + "?" + getStr;
				document.getElementById(trgtForm).method=trgtMethod;
				document.getElementById(trgtForm).submit();	
			}
			else
			{	top.location.href=trgtPage + "?" + getStr;	}
		}
	}
	//Definition of On ReadyStateChange function
	ajaxRequest.onreadystatechange=function()
		{
			if(ajaxRequest.readyState==4)
			{
				if(ajaxRequest.status==200)
				{
					document.getElementById(trgtObj).innerHTML=ajaxRequest.responseText;
					
					if(callItBack!='')
					{	eval(callItBack);	}
					
					if(ignoreObj==0)
					{
						//top.location.href='#'+trgtObj;
						window.scrollTo(0,document.getElementById(trgtObj).style.top);
					}
					
					/*To Execute JavaScript sent via AJAX Response - You have to put your JavaScript in <script>....</script> tags
					
					var toEval=currRqst.responseText.split('script>');
					var evalLmt=toEval.length;
					for(i=0;i<evalLmt;i++)
					{
						if((i%2)!=0)
						{
							toEval[i]=toEval[i].substr(0,toEval[i].length-2);
							eval(toEval[i]);
						}
					}
					*/
					ajaxRequest=null;
				}
				else
				{
					switch(ajaxRequest.status)
					{
						case 400:
							alert("Sorry! Server detected some malformed syntax i.e. 400 Bad Request.");
							break;
						case 401:
							alert("Sorry! It is an unauthorized access. i.e. 401");
							break;
						case 403:
							alert("Sorry! You cannot access this page i.e. 403 Forbidden");	
							break;
						case 404:
							alert("Sorry! This page dosen't exists or moved i.e. 404 Page Not Found");
							break;
						case 405:
							alert("Sorry! This request method is not allowed for the requested URI i.e. 405 Method not allowed");
							break;
						case 406:
							alert("Sorry! This request is not acceptable by server i.e. 406 Not acceptable");
							break;
						case 407:
							alert("Sorry! Proxy authentication required i.e. 407");
							break;
						case 408:
							alert("Sorry! You request timed out i.e. 408 Request Timeout");
							break;
						case 409:
							alert("Sorry! Request conflicted with resource state i.e. 409 Conflict");
							break;
						case 410:
							alert("Sorry! The request resource expired or lost i.e. 410 Gone");
							break;
						case 411:
							alert("Sorry! Request content length not specified i.e. 411 Lengh Required");
							break;
						case 413:
							alert("Sorry! The request entity is too large for server willing or able to process i.e. 413 Request Entity Too Large");
							break;
						case 414:
							alert("Sorry! The request URI is too large to be interpretted by the server i.e. 414 Request-URI Too Long");
							break;
						case 415:
							alert("Sorry! Server dosen't support this media type to be served i.e. 415 Unsupported Media type");
							break;
						case 500:
							alert("Sorry! An error occured at server i.e 500 Internal Server  Error");
							break;
						case 501:
							alert("Sorry! Server dosen't have functionality to serve this request i.e. 501 Not Implemented");
							break;
						case 502:
							alert("Sorry! Bad Gateway i.e. 502");
							break;
						case 503:
							alert("Sorry! Server is temporarily overloaded or under maintainance, so cannot process your request i.e. 503 Service Unavailable");
							break;
						case 504:
							alert("Sorry! Gateway timed out i.e. 504");
							break;
						case 505:
							alert("Sorry! The request's HTTP version is not supported by server i.e. HTTP Version Not Supported");
							break;
						case 12029:
						case 12030:
						case 12031:
						case 12152:
						case 12159:
							errorTurn++;
							if(errorTurn<=5)
							{	ajaxRequest.send(combinedString);	}
							else if(errorTurn>5)
							{	alert("A minor communication error with the server has occurred.\nThis error will not cause any loss of saved data.\nWe apologize for any inconvenience.\nPlease press OK to continue.");	}
							break;
						default:
							alert("Sorry! communication with server failed. Please try again! (" + ajaxRequest.status + ")\n[ Error Details : "+ajaxRequest.responseText+" ]");
							break;
					}
					ajaxRequest=null;
				}
				
				if(diminishObj==4)
				{
					document.getElementById(trgtObj).style.opacity='1';
					document.getElementById(trgtObj).style.filter='alpha(opacity=100)';
					document.body.removeChild(document.getElementById(currWaitId));
				}
				if(diminishObj==5)
				{
					document.getElementById(trgtObj).style.opacity='1';
					document.getElementById(trgtObj).style.filter='alpha(opacity=100)';
					if(document.getElementById('ajaxProcess'))
					{
						document.getElementById('ajaxProcess').innerHTML="";
						document.getElementById('ajaxProcess').style.display='none';
					}
				}
				
				delObj(this);
			}
		};
		
	if((trgtFormOrVar==0)&&(trgtMethod=='POST'))
	{
		ajaxRequest.open(trgtMethod,trgtPage,true);
		this.makeParameters(document.getElementById(trgtForm).elements);
		var combinedString=getStr + "&" + postStr;
		
		ajaxRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		ajaxRequest.setRequestHeader("Content-length",combinedString.length);
		//The Connection close request header is a hack that was being using to avoid a bug in Firefox later resolved after 2005
		//But keep this code for safety. Don't remove check for IE otherwise errors 12XXX will be encountered
		if(!(/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)))
		{	ajaxRequest.setRequestHeader("Connection","close");	}
		ajaxRequest.send(combinedString);
	}
	else if((trgtFormOrVar==0)&&(trgtMethod=='GET'))
	{
		ajaxRequest.open(trgtMethod,trgtPage,true);
		this.makeParameters(document.getElementById(trgtForm).elements);
		var combinedString=getStr + "&" + postStr;
		ajaxRequest.send(combinedString);
	}
	else if((trgtFormOrVar==1)&&(trgtMethod=='POST'))
	{
		ajaxRequest.open(trgtMethod,trgtPage,true);
		
		ajaxRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		ajaxRequest.setRequestHeader("Content-length",getStr.length);
		//The Connection close request header is a hack that is being using to avoid a bug in Firefox later resolved after 2005
		//But keep this code for safety. Don't remove check for IE otherwise errors 12XXX will be encountered
		if(!(/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)))
		{	ajaxRequest.setRequestHeader("Connection","close");	}
		ajaxRequest.send(getStr);
	}
	else
	{
		ajaxRequest.open(trgtMethod,trgtPage + "?" + getStr,true);
		ajaxRequest.send(null);
	}
	
	if(diminishObj==0)
	{
		document.getElementById(trgtObj).innerHTML='';
	}
	else if(diminishObj==1)
	{	document.getElementById(trgtObj).innerHTML="Wait while processing...!";	}
	else if(diminishObj==2)
	{	document.getElementById(trgtObj).innerHTML="<div style='background-image:url("+currHost+"images/graphics/processing.gif); border:0px;'>";	}
	else if(diminishObj==3)
	{
		document.getElementById(trgtObj).innerHTML="<div style='background-image:url("+currHost+"images/graphics/processing.gif); width:30px; height:30px; border:0px;'></div> Please Wait!....Processing Request!";
	}
	else if(diminishObj==4)
	{	this.askToWait(currWaitId);	this.dimIt(trgtObj);	}
	else if(diminishObj==5)
	{
		if(document.getElementById('ajaxProcess'))
		{
			document.getElementById('ajaxProcess').style.top='200px';
			document.getElementById('ajaxProcess').style.left='35%';
			document.getElementById('ajaxProcess').innerHTML="<div style='background-image:url("+currHost+"images/graphics/ajaxProcess.gif); width:auto; height:auto; border:0px;'><img src='"+currHost+"images/graphics/ajaxProcess.gif'></div>";
			currWaitId='ajaxProcess';
		}
		this.dimIt(trgtObj);
	}
}

function delObj(trgt)
{
	delete trgt;
}
