/**********************************************
*	Scott Ladyman 2006
*
***********************************************/
/* needs dom.js library */
var ajax = {
	
	cache : [],
	/*	states whether ajax is cuurently fetching data	*/
	active          : false,
	request			: false,
	response		: false,
	
	/*	this for auto creation of ajax url	*/
	requestPage     : "ajax.php",
	requestDir 		: "",	    
	requestVar  	: "request",
	requestURL		: "",	
	
	/*	for custom loading icon display */
	loader    	: true,
	loaderId  	: "ajax",
	loaderClass : "",
	loaderMsg 	: "",

	
	
	init : function() {
		var xmlhttp = false; //Clear our fetching variable
			try {
				xmlhttp = new ActiveXObject('Msxml2.XMLHTTP'); //Try the first kind of active x object.
			} catch (e) {
				try {
					
					xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); //Try the second kind of active x object
				} catch (e) {
					xmlhttp = false;
				}
			}
			if( !xmlhttp && typeof !XMLHttpRequest != 'undefined') {
				xmlhttp = new XMLHttpRequest(); //If we were able to get a working active x object, start an XMLHttpRequest
			}
		return xmlhttp;	
	},
	
	
	/******************************************************
		four main states/state codes, 
		Loading-1, Loaded-2, Interactive-3, Complete-4 
	******************************************************/	
	call : function(url, callback, method, frm) 
	{
		//	set METHOD of passing			
		if( !method )  method = "GET";
		// create the handle for the ajaxHttpRequest
		ajax.request = this.init();
		
		if( this.request && !ajax.active ){
			/*	ajax request has been activated, otherwise new request will overwrite old request */
			ajax.active = true;
			ajax.showLoader();
			/* when the server request is completed */
			ajax.request.onreadystatechange = function() {
				if( ajax.request.readyState == 4 ){ 
					 /* Upon successful HTTP request 200 = OK  */
					switch(ajax.request.status){
						case 200 :
							ajax.response = ajax.request.responseText;
							//	cache response
							ajax.cache.push({"url":url, "response":ajax.response});
							ajax.stop(ajax.request);
							callback();
						break;	
						case 404 :
							alert("Requested ajax page is missing :: " + ajax.request.status);
							ajax.stop(ajax.request);
						break;
					}
				}
			};
			
			// open the request, based on the form method type
			ajax.request.open(method, url, true); 
			//	HEAD can be used to check the status of a file, url is address
			if( method == "GET" || method == "HEAD" ){
				// send GET request
				ajax.request.send(null);
			}else{
				/* POST */
				//	form data may have already been setup due to form validation
				var data = (frm) ? forms.data(frm, true) : false;
				if( data || data !== ""){		
					//	IE problems that could occur	
					ajax.request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
					ajax.request.setRequestHeader("Content-length", data.length);
					ajax.request.setRequestHeader("Connection", "close");	
					
					ajax.request.send(data);
				}
				else{
					alert("You need to pass the form object before sending POST");
				}
			}
		}
	},


	/********************************************************
		simple GET request for ajax
	****************************************************** */
	get : function(request, func, useCache, rvar)
	{
		request = ajax.url(request, rvar);
		if( useCache ){
			var cache = ajax.cached(request)
			if( cache !== false ){
				ajax.response = cache;
				func();
				return;
			}
		}
		ajax.call(request, func, "GET", false);
	},

	/********************************************************
		simple POST request for ajax
	****************************************************** */
	post : function(request, func, frm)
	{
		//ajax.url(request)
		ajax.call(ajax.url(request), func, "POST", frm);
	},
	
		/* checks for stored requests that have already been posted */
	cached : function(request)
	{
		for(var c = 0; c < ajax.cache.length; c++){
			// ajax called has been cached...return instead of another call.
			if( ajax.cache[c].url == request){
				return ajax.cache[c].response;
			}
		}
		return false;
	},

	
	/********************************************************
		destory the ajax call/request
		otherwise it will continue to load the onchangestate
	****************************************************** */
	stop : function(request)
	{
		request.onreadystatechange = function(){};
		request.abort();
		/*	allow new ajax request */
		ajax.active = false;
		/*	show user ajax loading sign */
		if( ajax.loader ){
			ajax.autoLoaderShutoff();
		}
	},
	
	
	/* ********************************************** 
		WARNING DEPRECIATED!
		easiest way to decode json for javascript
	********************************************** */
	decodeJson : function( string )
	{
		//	depreciated, see dom file obj.string.json()
		return eval( '('+ string +')' );
	},
	

	

	/* ********************************************** 
		build the basic url string for ajax requests
	********************************************** */
	url : function(request, rvar, self, dir)
	{
		if( !dir  ) dir  = ajax.requestDir;
		if( !self ) self = ajax.requestPage;
		if( !rvar ) rvar = ajax.requestVar;
		var str = dir + self.replace(".php", "") + ".php?"+ rvar +"="+ request;
		return str.replace("&&", "&");
	},
	


	/********************************************
		setup a javascript script tag to 
		pass js script to dynamically load
		will need to ahve the content added to the DOM
	********************************************/
	loadJS : function(str, file)
	{
		//	setup script tag for loading js into head
		var head = dom.byTag("head")[0];
		if( !file ){
			var script 		= dom.create("script");
			script.type = "text/javascript";
			script.source = file;
			//	load js content into script tag
			if( document.all ){
				script.text = str;
			}else{
				script.innerHTML = str;
			}
		}
		else{
			//	to add js file...	
		}
		head.appendChild(script);
	},
	
	
	/* ********************************************** 
	Ensure to set the content to the obj first
	********************************************** */
	parseJS : function(content, obj)
	{
		//	create temp DOM obj to test againist
		if( !obj ) obj = dom.create("div"); 
		//	setup DOM elements from content parsed
		obj.innerHTML = content;
		//	extract script tags if any
		var scriptTags = dom.byTag("script", obj);
		for(var s = 0; s < scriptTags.length; s++){
			ajax.loadJS(scriptTags[s].innerHTML);
		}
		return content;
	},
	


	/************************************
	*	SHOW CUSTOM AJAX LOADING ICON	*
	*	class = "load", "true", "false" *
	*	setup in CSS					*
	************************************/
	setLoader : function(msg, setClass)
	{
		var obj = dom.byId(ajax.loaderId);
		if( obj ){
			ajax.loaderMsg 	 = "loading...";
			ajax.loaderClass = "load";
			if( setClass ) ajax.loaderClass = setClass;
			if( msg )      ajax.loaderMsg = msg;	
		}
	},
	
	
	showLoader : function(msg)
	{
		if( ajax.loader ){
			if( msg !== false ){
				ajax.setLoader(msg);	
			}
			var obj = dom.byId(ajax.loaderId);
			if( obj ){
				if( ajax.loaderMsg == "" ){
					ajax.setLoader();
				}
				obj.innerHTML = ajax.loaderMsg;
				obj.className = ajax.loaderClass;
				/* */
				sfx.setOpacity(obj, "101");
				obj.style.display = "block";
				/* clear so next display is set */
				ajax.loaderMsg 	= "";
				ajax.loaderClass = "";
				//if( hide ){
					/* user message that will hide after a period of time */
				//	ajax.hideLoader(true);	
				//}
			}
			return;
		}
	},
	
	
	hideLoader : function(fancy)
	{
		var obj = dom.byId(ajax.loaderId);
		if( obj && obj.style.display != "none" ){
			if( fancy ){
				/* maybe add flashing or fade out */
				setTimeout(function(){ 
					/* check to see if obj exists */
					sfx.fadeOut(obj);
				}, 0);
			}else{
				obj.style.display = "none";	
			}
			ajax.setLoader();
		}
	}, 
	
	
	/*	turn off "loading" display after simple request */
	autoLoaderShutoff : function()
	{
		var obj = dom.byId(ajax.loaderId);
		if( obj && obj.style.display == "block"){
			if( obj.innerHTML == "loading..." ||  obj.innerHTML == "searching..."){
				setTimeout(function(){ajax.hideLoader(true);}, 0);
			}
		}
	}
}