/* ****************************************************************** //
Copyright (c) 2010 Nic Desjardins
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/ //

var XOBAJAX = {

	/**
	* POST object (params is a json object, func is a function that's run on return)
	* @param String url
	* @param Json Object params
	* @param Function func (default: null)
	* @param String method (default: POST) 
	*/
	postObject: function(url,params,func,method) {
		method = method=="GET" ? "GET" : "POST";
		var xhr = this.getAJAXObject();
		var parameters = '';
		if(Object.prototype.toString.call(params)=='[object Object]') {
			var i = 0;
			params = this.recurseCleanObj(params);
			for(var k in params) {
				
				// Check the type of request we're using
				switch(method) {
					
					// POST: if we're on argument 1 or more, we append a "&"
					case "POST":
						if(i > 0)
							parameters += "&";
						//
					break;
					
					// GET: always append, if we already have "?" then append "&", otherwise append "?"
					case "GET":
						if(String(url).indexOf("?") < 0) {
							parameters += "&";
						} else {
							parameters += "?";
						}
					break;
				}
				
				// Append <argument name> and "="
				parameters += k + "=";
				
				// Check if we're dealing w/ an object
				if(Object.prototype.toString.call(params[k])=='[object Object]') {
					// if we are JSON stringify it
					parameters += JSON.stringify(params[k]);
				} else {
					// otherwise just use it as is
					parameters += params[k];
				}
				
				// bump iteration count 
				i++;
				//parameters += (i>0 ? "&" : (method=="GET"&&String(url).indexOf("?")<0?"?":"")) + k + "=" 
				//	+(Object.prototype.toString.call(params[k])=='[object Object]' ? JSON.stringify(params[k]) : params[k]);
				//i++;
			}
		}
		
		if(method=="GET")
			url += parameters;
		//
		xhr.open(method, url, true);
	    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	    xhr.setRequestHeader("Content-length", parameters.length);
	    xhr.onreadystatechange = function(){if(xhr.readyState == 4 && xhr.status == 200){
			if(func && Object.prototype.toString.call(func)=="[object Function]"){
				func(xhr.responseText);
			}
		}};
		
		// Given the type of request and parameters send them or just send null
	    if(method=="POST" && parameters.length > 0) {
		    xhr.send(parameters);
		} else {
    		xhr.send(null);
		}
	}

	/**
	* Convert an array to an object (JSON doesn't like Array's)
	*/
	, arr2obj: function(arr) {
		if(Object.prototype.toString.call(arr)=='[object Array]') {
			obj = new Object();
			for(var k in arr) {
				obj[k] = arr[k];
			}
			return obj;
		} else {
			return arr;
		}
	}

	/**
	* Recurse an object and clean it
	*/
	, recurseCleanObj: function(obj) {
		if(obj==undefined||obj==null)
			obj = new Object();
		//
		if(Object.prototype.toString.call(obj)=='[object Object]') {
			for(var k in obj) {
				if(Object.prototype.toString.call(obj[k])=='[object Array]') {
					obj[k] = this.arr2obj(obj[k]);
				}
				if(Object.prototype.toString.call(obj[k])=='[object Object]') {
					obj[k] = this.recurseCleanObj(obj[k]);
				} else if(Object.prototype.toString.call(obj[k])=='[object String]'
					&& isNaN(obj[k])
				) {
					var clean = obj[k];
					//clean = clean.replace(/\n/g,'');
					clean = clean.replace(/\r/g,'');
					// why would I have the next line?
					// clean = clean.replace(/\"/g,'');
					clean = clean.replace(/\\/g,'');
					clean = encodeURIComponent(clean);
					obj[k] = clean+'';
					delete clean;
				}
			}
			return obj;
		} else {
			//return null;
		}
	}

	/**
	* Get an (AJAX) object!
	*/
	, getAJAXObject: function() {
	    var objXMLHttp=null;
	    try {
	        objXMLHttp = new ActiveXObject('Msxml2.XMLHTTP'); // Later IE
	    } catch (e) {
	        try {
	            objXMLHttp = new ActiveXObject('Microsoft.XMLHTTP'); // Earlier IE
	            var ie = true;
	        } catch (e) {
	            objXMLHttp = null;
	        }
	    }
	    if (objXMLHttp==null) {
	        var objXMLHttp=new XMLHttpRequest(); // IE7, Firefox, Safari
	    }
	    return objXMLHttp;
	}
}


