/*
Events: "Error", "BeginRequest", "RequestComplete", "readyStateChange", "Complete"
*/
var ajax = 
{
	obj:null,
	obj_list:[],
	queues:[],
	busy:false,
	form:null,
	allow_multiple:true,
	async:true,
	disable_page:true,
	mode:"release",
	current:{},
	headers: [{Name:"User-Agent", Value:"Mozilla/5.0 (Windows; co_ajax) co_ajax/1.1"}],
	disable_caching : false,
	EventHandlers:{}
};
if (ajax.mode == "debug")
{
	var co_debugger = null;
	Co_Tools.AddEventListener(window, "load", function()
	{
		co_debugger = document.createElement("DIV");
		co_debugger = document.body.appendChild(co_debugger);
		co_debugger.style.cssText = "position:absolute;top:0px;left:0px;background-color:#ffffff;border:1px solid #abcdef;height:200px;width:400px;overflow:auto;";
		co_debugger.innerHTML = "<b>AJAX DEBUGGER:</b>(<a href=\"javascript:void(0);\" onclick=\"ajax.clear_debugger();\">clear</a>)</a><br>";
		
	});
}
ajax.init=function()
{
	var obj;
	try
	{
		obj = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (e)
	{
		try
		{
			obj = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (oc)
		{
			obj = null;
		}
	}
	if(!obj && typeof(XMLHttpRequest) != "undefined")
		obj = new XMLHttpRequest();
	if (obj==null)
	{
		this.debug("Could not create connection object.");
		this.FireEvent("Error", {Text:"Ajax Not Supported"});
	}
		
  return obj;
}

//ajax.ajaxDefaultHeader = "User-Agent", "Mozilla/5.0 (Windows; co_ajax) co_ajax/1.1";
//ajax.ajaxHeader = ajax.ajaxDefaultHeader;
ajax.replaceHeader=function(s_name, s_value)
{
	for(var i=0;i<this.headers.length;i++)
	{
		if(this.headers[i].Name==s_name)
		{
			this.headers[i].Value=s_value;
			return true;
		}
	};
	this.addHeader(s_name, s_value);
	return false;
}
ajax.addHeader=function(s_name, s_value)
{
	this.headers.push({Name:s_name,Value:s_value});
}
ajax.removeHeader=function(s_name)
{
	for(var i=0;i<this.headers.length;i++)
	{
		if(this.headers[i].Name==s_name)
			this.removeHeaderAt(i);
	}
}
ajax.removeHeaderAt=function(idx)
{
	this.headers.splice(idx, 1);
}
ajax.getFirstAvailable = function()
{
	if (!this.allow_multiple) return 0;
	var i;
	for (i = 0; i < this.obj_list.length; i++)
	{
		if (this.obj_list[i] == null)
			return i;
	}
	return i;
}

ajax.request=ajax.Request=function(args)
{
	if (this.busy&&!this.allow_multiple)
	{
		this.queues.push(args);
		return;
	}
	this.FireEvent("beginRequest", {State:"BeginRequest"});
	this.busy = true;
	//needed so that ajaxed pages do not get cached
	
	var request_method = args["method"] || this.request_method || "POST";
	
	if (request_method.toUpperCase() == "GET" && ((typeof(args.disable_caching) == "undefined" && !this.disable_caching) || args.disable_caching == false))
	{
		args.co_rand_cache = (new Date).getTime()+"."+(Math.random()*99999999);
	}
		
	var post_data='';
	for (var arg in args)
	{
		switch (arg.toLowerCase())
		{
			case "uri" : case "func" : case "params" : case "obj" : case "method" : case "disable_caching" :
				continue;
			default :
				post_data += "&" + arg + "=" + encodeURIComponent(args[arg]);
			break;
		}
	}
	
	this.current = args;
	uri = args["uri"];
	
	if (request_method.toUpperCase() != "GET" || uri.indexOf("?") == -1)
	{
		if (request_method.toUpperCase() == "GET")
			post_data = "?" + post_data.substr(1);
		else
			post_data = post_data.substr(1);
	}

	var uri_regex = new RegExp('(http(?:s?)):\/\/?((.*?)\/)?((.*)\/)?(.*)?(' + document.domain + ')', 'gi');

	if(!uri_regex.test(uri) && /http/gi.test(uri))
	{
		var tmp_uri = uri;
		var uri_protocol = tmp_uri.match('(http(?:s?))')[0];
		uri = tmp_uri.replace(/(http(?:s?):\/\/)/gi, '');
		uri='/scripts/remoteAjax.asp?protocol=' + uri_protocol + '&uri=' + encodeURIComponent(uri);
	}
	
	var idx = this.getFirstAvailable();
	this.obj_list[idx] = {};
	this.obj_list[idx].args = args;
	this.obj = this.obj_list[idx].obj = this.init();
	if (!this.obj)
	{
		this.debug("Ajax not supported");
		return false;
	};
	
	this.debug(uri + (request_method.toUpperCase()=="GET"? post_data : ""));
	
	this.obj.open(request_method, uri + (request_method.toUpperCase()=="GET" ? post_data : ""), this.async);
	
	//the function must be re-set every time.
	this.obj.onreadystatechange = function()
		{
			ajax.ReadyStateChanged(idx);
		}
	for(var i=0;i<this.headers.length;i++)
	{
		this.obj.setRequestHeader(this.headers[i].Name, this.headers[i].Value);
	}
	if (request_method=="POST")
	{
		this.obj.setRequestHeader("Method", "POST " + uri + " HTTP/1.1");
		this.obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	}
	if (typeof(page)=="function" && this.disable_page)
	{
		if (typeof(this.PageControl)=="undefined")
			this.PageControl = new page();
		this.PageControl.disable();
	}
	this.obj.send(post_data);
	if(!this.async)
	{
		this.request_complete();
		return this.obj;
	}
	return true;
}
ajax.response = function(cur_obj)
{
	var func = cur_obj.args.func || null;

/* check content type for json.
		if json, call Co_Tools.ConvertTextToJSON();
		return_obj.responseJSON = [jsonContent];
*/
	if(func)
	{
		var obj=cur_obj.args.obj||null;
		var params=cur_obj.args.params||null;
		var return_obj=cur_obj.obj;
		if (return_obj.getResponseHeader("content-type") == "text/x-json" || return_obj.getResponseHeader("content-type") == "text/json")
		{
			if (params == null) params = [];
			var responseJSON = JSON.parse(return_obj.responseText);
			params = [responseJSON].concat(params);
		}
		if(obj)
		{
			if(params)
			{
				func.apply(obj, [return_obj].concat(params));
			}
			else
			{
				func.apply(obj, [return_obj].concat());
			}
		}
		else
		{
			if(params)
			{
				func.apply(null, [return_obj].concat(params));
			}
			else
			{
				func.apply(null, [return_obj].concat());
			}
		}
	}
	
	this.request_complete();
	if (this.queues.length>0)
	{
		this.request(this.queues.shift());
	}
}
ajax.request_complete=function()
{
	/*re-enable the page after the request completes.*/
	if (typeof(this.PageControl)!="undefined"&&this.disable_page)
		this.PageControl.enable();
	this.busy = false;
	this.FireEvent("requestComplete", {State:"RequestComplete"});
}
ajax.debug=function(s)
{
	if(this.mode=="debug" && typeof(co_debugger) != "undefined")
		co_debugger.innerHTML += s + "<br>";
}
ajax.clear_debugger = function()
{
	if(this.mode=="debug" && typeof(co_debugger) != "undefined")
		co_debugger.innerHTML = "<b>AJAX DEBUGGER:</b>(<a href=\"javascript:void(0);\" onclick=\"ajax.clear_debugger();\">clear</a>)</a><br>";
}

ajax.ReadyStateChanged=function(idx)
{
	if(!this.async)
		return;
		
	var cur_obj = this.obj_list[idx];
	this.FireEvent("readyStateChange", {State:cur_obj.obj.readyState});
	if (cur_obj.obj.readyState!=4)
		return;
	
	ajax.response(cur_obj);
	if (parseInt(cur_obj.obj.status) >= 400)
		this.FireEvent("Error", {Status:cur_obj.obj.status,Text:""});
	else
		this.FireEvent("complete", {State:"Complete"});
	
	if (this.obj_list[idx].readyState == 4)
		this.obj_list[idx] = null;
	cur_obj = cur_obj.obj = null;
}

ajax.isLoggedIn=ajax.IsLoggedIn=function()
{
	this.async=false;
	var args={uri:'/scripts/ajax/ajax_functions.asp',action:'isLoggedIn'};
	var response=this.request(args);
	this.async=true;
	return (response.responseText == "true");
}

ajax.AddEventListener=ajax.AddEventHandler=function(evName, func, obj, paramsArray, single_use)
{
	if (typeof(this.EventHandlers[evName.toLowerCase()])=="undefined")
		this.EventHandlers[evName.toLowerCase()]=[];
	this.EventHandlers[evName.toLowerCase()].push({func:func,obj:obj,params:paramsArray,single_use:single_use||false});
}
ajax.FireEvent=function(evName, ev)
{
	var handlers=this.EventHandlers[evName.toLowerCase()];
	if (typeof(handlers)=="undefined") return;
	
	for (var i=0;i<handlers.length;i++)
	{
		this.RunEventHandler(handlers[i].func, handlers[i].obj, handlers[i].params, ev);
		if(handlers[i].single_use)
			this.EventHandlers[evName.toLowerCase()].splice(i, 1);
	}
}
ajax.RunEventHandler=function(f,o,p,ev)
{
	try 
	{
		if(p)
			f.apply(o,[ev].concat(p));
		else
			f.apply(o);
	} 
	catch (e){}
}
String.prototype.Replace = function(o,n) 
{
	return this.split(o).join(n);
}

function activate_javascript(Container)
{
	if (typeof(Container) == "string")
		Container = document.getElementById(Container);
	if (Co_BrowserInfo.IsIE)
	{
		activate_javascript_ie(Container);
		return;
	}
	//firefox enables scripts by setting innerHTML
//	if (Co_BrowserInfo.IsFirefox) return;
	var script_tags=Container.getElementsByTagName("script"),new_script;
	
	var head_tag = document.getElementsByTagName('head')[0]; 
	for (var i=0;script_tags.length>i;i++)
	{
		if (script_tags[i].getAttribute("src"))
		{
			new_script = document.createElement('script'); 
			new_script.id = script_tags[i].getAttribute("id") || "ajax_script_" + i; 
			new_script.type = script_tags[i].getAttribute("type") || "text/javascript";
			new_script.language = script_tags[i].getAttribute("language") || "javascript";
			new_script.src = script_tags[i].getAttribute("src"); 
			head_tag.appendChild(new_script);
		}
		else
		{
			try
			{
				window.eval(script_tags[i].innerHTML);
			}
			catch (ex) {/* if there's an error in the code I dont want to stop loading other items */}
		}
	}
}

function activate_javascript_ie(Container_Elm)
{
	if (!Co_BrowserInfo.IsIE) return;
	var script_tags=Container_Elm.getElementsByTagName("script");
	for (var i=0;script_tags.length>i;i++)
	{
		if (script_tags[i].getAttribute("src"))
		{
			script_tags[i].src = script_tags[i].getAttribute("src");
		}
		else
		{
			script_tags[i].text=script_tags[i].innerHTML;
		}
	}
}
