/*
  -------------------------------------------------------------------------
	File: do.jx.js
	
	Description: XMLHTTPRequest Operations Handling 
    
	Version: 1.03.07072010 - Revision: 11.4.0
	
	Based on the Original: [File: jx.js, Version: V3.01.A , Url: http://www.openjs.com/scripts/jx/]
	
	Complements: My complements to http://www.openjs.com/scripts/jx/ for providing nice & simple approach to Ajax Requests. 
					I thank them for the Prototype they've provided at the above URL.
	
	Modified by: Ronnie Depp. 
	
	Author: Salman Ahmad a.k.a. Ronnie Depp
	
	Author's Comments: More modifications done to make it more customizable & reusable to fit my needs. 
						(Added more Implementations of GET/POST methods to improve usability in all cases encountered so far, 
						 ResponseTypes handlings, Parameters to the Callback function & other such modifications done).
	
	Usage: This Javascript is meant to be used on www.theboxerring.com
	
	Contact Information: To reach Ronnie Depp, is detailed below.
	--
	
	Web: 
	---
		URL:						http://ronniedepp.co.cc
		
		Personal Blog: 				http://ronnydepp.blogspot.com
		Tech Blog: 					http://techbytes-from-ronnie.blogspot.com
		Facebook: 					http://www.facebook.com/ronny.depp
		Google Profile: 			http://www.google.com/profiles/mr.salman.ahmad
		JTV Profile: 				http://en.justin.tv/ronny_depp/profile
		Actionscript.org Profile: 	http://www.actionscript.org/forums/member.php3?u=89000

	eMail and Instant Messaging: 
	---------------------------
		Gmail/GoogleTalk:			mr.salman.ahmad@gmail.com - (Google Talk)
		MSN/Hotmail:				salmanahmed70@hotmail.com - (Live Messenger)
		Yahoo!:						me.ronny@yahoo.com - (Yahoo! IM)
		AOL/AIM:					captronnydepp@aim.com - (AIM)
		Skype:						othenticmedia - (Skype)

	Voice: 
		
		Cell 1: +92.313.407.0856
		Cell 2: +92.321.424.4248 (inactive - will be active soon)
		Landline: +92.423.507.8155 (my wireless)

	Snail Mail, Location: 
		
		Postal Address: 43, block K, Model Town Co-operative Society, Lahore, 54700, Punjab, Pakistan.
		
	--
	
	Copyright (C) 2009-2010 Ronnie Depp - http://ronniedepp.co.cc - All rights reserved.
	
	For updates, customized solutions OR usage of this file in your own implementations, 
	please contact me, via my e-mailbox: mr.salman.ahmad@gmail.com OR Skype ID: othenticmedia
	
	Direct your Queries, Comments & Suggestions to: mr.salman.ahmad@gmail.com
  -------------------------------------------------------------------------  
*/
jx = {
	//Create a xmlHttpRequest object - this is the constructor. 
	getHTTPObject : function() {
		var http = false;
		//Use IE's ActiveX items to load the file.
		if(typeof ActiveXObject != 'undefined') {
			try {http = new ActiveXObject("Msxml2.XMLHTTP");}
			catch (e) {
				try {http = new ActiveXObject("Microsoft.XMLHTTP");}
				catch (E) {http = false;}
			}
		//If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document.
		} else if (window.XMLHttpRequest) {
			try {http = new XMLHttpRequest();}
			catch (e) {http = false;}
		}
		return http;
	},
	// This function is called from the user's script. 
	//Arguments - 
	//	url	- The url of the serverside script that is to be called. Append all the arguments to 
	//			this url - eg. 'get_data.php?id=5&car=benz'
	//	callback - Function that must be called once the data is ready.
	//	format - The return type for this function. Could be 'xml','json' or 'text'. If it is json, 
	//			the string will be 'eval'ed before returning it. Default:'text'
	load : function (url,params,callback,method,format,element_loading_dispay, loadingHandler, addParamsToRequest, extraParamsToPassToCallBack, requestName) {
		var http = this.init(); //The XMLHttpRequest object is recreated at every call - to defeat Cache problem in IE
		
		if(!http||!url) 
		{
			var failed_msg = false;
			if(!http) {
				failed_msg = 'WEB BROWSER is Outdated:'+'\n\n'
			+'Dear Visitor, \nYour web browser does not support: AJAX (a browser technology present in Modern Web Browsers).'
			+'\n\n'+'This website uses state-of-the-art features, which depend on AJAX technology to enhance your web browsing experience.' 
			+ '\n\n' + 'Please upgrade your Browser to the latest version to browse this webiste.' 
			+ '\n\n' + 'Otherwise, you will not be able to access certain Features/Sections properly on this website.';
				alert(failed_msg); 
			}
			if(!url) {
				failed_msg = 'Dear Visitor, \nAn internal error has occured on this webpage, while trying to access information from Server.'
			+'\n\n'+'REASON: \nThe URL/Address for the requested resource on Server is missing.' 
			+ '\n\n' + 'Please report this error in detail with Full URL of current page in your Browser\'s ADDRESS BAR to Web Developer by e-mail at: <mr.salman.ahmad@gmail.com>' 
			+ '\n\n' + 'We apologize for the inconvenience.\n\nThank you!';
				alert(failed_msg); 
			}
			return;
		}
		if (http.overrideMimeType) http.overrideMimeType('text/xml');

		if(!format) var format = "text";//Default return type is 'text'
		format = format.toLowerCase();
		
		if(loadingHandler){// Show the Loading Animation
			loadingHandler(element_loading_dispay);
		}
		
		if(addParamsToRequest){
			//Kill the Cache problem in IE.
			var now = "uid=" + new Date().getTime();
			//params += (params.indexOf("?")+1) ? "&" : "?";
			//params += now;
			if(method.toUpperCase()=='POST') {document.cacheKiller = "?"+now;}
			else{
				params += (params.indexOf("?")+1) ? "&" : "?";
				params += now;
			}
		}

		http.onreadystatechange = function () {//Call a function when the state changes.
			if (http.readyState == 4) {//Ready State will be 4 when the document is loaded.
				if(http.status == 200) {
					var result = "";
					if(http.responseText) {
						result = http.responseText;
						if(loadingHandler){// Hide the Loading Animation
							loadingHandler(element_loading_dispay);
						}
						//alert(result);
					} else { 
						result = '{"error":true, "err_msg":"server did not return any Response  for [ '+requestName+' ] request. \\n\\nhttp.status: '+((http.status) ? http.status : undefined)+', \\nhttp.statusText: '+((http.statusText) ? http.statusText : undefined)+', \\nhttp.responseText: '+((http.responseText) ? http.responseText : '')+'"}';
						/*for(var ajx in http){
							alert('property: '+ajx);
						}*/
					}
			// 		------------------------------------------------------------------------
			// 		Handle ResponseTypes [ 0:h:html, 1:j:json, 2:x:xml, 3:t:text:plaintext ]
			// 		------------------------------------------------------------------------
					//If the return is in JSON format, eval the result before returning it.
					if(format.charAt(0) == "j" || format == "json" || format == "j" || format == 1) {
						//\n's in JSON string, when evaluated will create errors in IE
						//alert(result);
						try { result = eval('('+result+')'); }
						catch(e){ alert('error parsing jSon_response_string from server'); }
					} else if(format.charAt(0) == "h" || format == "html" || format == "h" || format == 0) {
						if(result.indexOf('response_is_not_from_shoppingcart')==-1) // handle Shopping Cart responses
						{
//							result = result.replace(/[<]/g,"&lt;");
//							result = result.replace(/[>]/g,"&gt;");
//							result = result.replace(/[\n\r]/g,"<br />");
							var idx1 = result.indexOf('<body')+5;
							var idx2 = result.indexOf('</body>');
							result = result.substring(idx1, idx2);//(idx1+284)
							idx1 = result.indexOf('>')+1;
							result = result.substring(idx1, result.length-1);
							alert("result.length: "+result.length+"\n\nresult (trimmed): \n"+result);
							/*result = result.replace(/["]/g,"&lt;DOUBLE-QOUTE&gt;");
							result = result.replace(/[']/g,"&lt;DOUBLE-QOUTE&gt;");
							result = result.replace(/[\\]/g,"\\");
							*/
							alert("i'm here");
							/**/
						}
					}
	
					//Give the data to the callback function.
					if(callback) {
						if(extraParamsToPassToCallBack) {
							if(typeof(extraParamsToPassToCallBack)=='string') {
								for(var i=0; i<extraParamsToPassToCallBack.length; i++){ // strip Whitespaces out of it.
									if(extraParamsToPassToCallBack.indexOf(" ")) {
										var pattern = /\s/g;
										var regex = pattern.compile(""+pattern+"");
										extraParamsToPassToCallBack = extraParamsToPassToCallBack.replace(pattern, ''); 
									}
								}
								extraParamsToPassToCallBack = extraParamsToPassToCallBack.split(',');
								var builtCallback = 'callback(result';
								for(var m=0; m<extraParamsToPassToCallBack.length; m++) { // reBuild the Callback.
										builtCallback += ', ' + extraParamsToPassToCallBack[m].toString();
								}
								builtCallback += ')';
								// Build : callback
								eval(builtCallback);
							}
							else callback(result, extraParamsToPassToCallBack);
						} else {
							callback(result);
						}
					}
				} else { //An error occured
					//if(error) error(http.status);
					alert("XMLHTTPRequest (Ajax) Failed for Unknown Reason.\n\nPlease check if you are still connected to The Internet. \n\nTry again after connecting back to The Internet.\n\n- - - Error Details follow beneath - - -\n\nhttp.status: "+http.status+"\nhttp.statusText: "+http.statusText+"\n\nhttp.responseText: "+http.responseText+"\nhttp.getAllResponseHeaders(): "+http.getAllResponseHeaders());
				}
			}// END : if request completed
			/*
			else if (http.readyState==0) {
				//alert("http.readyState: "+http.readyState+" - The request is not initialized"+"\nhttp.status: "+http.status+"\nhttp.statusText: "+http.statusText+"\nhttp.getAllResponseHeaders(): "+http.getAllResponseHeaders());
			}// The request is not initialized
			else if (http.readyState==1) {
				//alert("http.readyState: "+http.readyState+" - The request has been set up"+"\nhttp.status: "+http.status+"\nhttp.statusText: "+http.statusText+"\nhttp.getAllResponseHeaders(): "+http.getAllResponseHeaders());
			}// The request has been set up
			else if (http.readyState==2) {
				//alert("http.readyState: "+http.readyState+" - The request has been sent"+"\nhttp.status: "+http.status+"\nhttp.statusText: "+http.statusText+"\nhttp.getAllResponseHeaders(): "+http.getAllResponseHeaders());
			}// The request has been sent
			else if (http.readyState==3) {
				//alert("http.readyState: "+http.readyState+" - The request is in process"+"\nhttp.status: "+http.status+"\nhttp.statusText: "+http.statusText+"\nhttp.getAllResponseHeaders(): "+http.getAllResponseHeaders());
			}// The request is in process
			*/
			
		}// END : function [http.onreadystatechange]
		
		// GET or POST method to use?
		if (method == "POST"){
			http.open('POST', url + (document.cacheKiller) , true);
			http.setRequestHeader("Content-type", "application/x-www-form-URLencoded");
			http.setRequestHeader("Content-length", params.length);
			http.setRequestHeader("Connection", "close");
			http.send(params);
		} else {
			http.open('GET', url + params, true);
			http.send(null);
		}
	},
	init : function() {return this.getHTTPObject();}
}

