/******************************************************************************
* Error codes
******************************************************************************/
//Error for when the XMLHttpRequest is unsupported or cannot be created
//this is a fatal error on this script
var ERR_CREATE_REQ = new Number(0);
//Error for when the get request returns no data.  This is not a fatal error,
//it can be caused by a 404 or an unresponsive server
var ERR_RETURN_NULL = new Number(0);
var max_media_auto;
var chat_auto;
var chat_list_auto;
var msgs_auto;
var logged_in = 0;
var date_auto;
var disconnected = 0;
var noconnection_auto;
var require_login = 0;

function noconnection_notify()
{
	//window.alert('dis');
	if(document.getElementById('disconnected') == undefined)
	{
	disconnectObj = document.createElement('div');
	document.getElementById('msgs').appendChild(disconnectObj);
	}
	disconnectObj.style.display = 'block';
	disconnectObj.setAttribute('id', 'disconnected');
	disconnectObj.className= 'msg red';

	disconnectObj.innerHTML = "Connection to this website was lost or there has been a problem with a request. Please check your internet connection or refresh the page.";

	disconnected = 1;

	noconnection_auto = setTimeout("myRequest.queuePost('msgs','autopost=1','msgs');", 10000);
}

function reconnected_notify()
{
	if(disconnected)
	{
		disconnected = 0;
		disconnectObj.style.display = 'none';
		clearTimeout(noconnection_auto);
	}
}

/******************************************************************************
* Ready State codes
*******************************************************************************
*     These are error codes in case there is an error
******************************************************************************/
//Error for when the XMLHttpRequest is unsupported or cannot be created
//this is a fatal error on this script
var RS_UNINITIALIZED = new Number(0);
var RS_LOADING = new Number(1);
var RS_LOADED = new Number(2);
var RS_INTERACTIVE = new Number(3);
var RS_COMPLETED = new Number(4);

/******************************************************************************
* AsyncXMLGetRequest - Wrapper class for XMLHttpRequest
*******************************************************************************
*   Properties:
*     xmlRequest - the queue of XMLHttpRequests
*     inRequest - a boolean that marks whether or not the queue is active
*     requestQueue - the queue of URLs to be requested
*     objectQueue - the queue of objects to be used in the "onService" routine
******************************************************************************/
function AsyncXMLGetRequest()
{
	this.xmlRequest = new Array();
	this.inRequest = new Boolean(false);
	this.requestQueue = new Array();
	this.objectQueue = new Array();
	this.postQueue = new Array();
	this.formQueue = new Array();
	this.queueCount = new Number(0);
}
/******************************************************************************
* AsyncXMLGetRequest::setup - setup method for AsyncXMLGetRequest
*******************************************************************************
*     allocates the newest item in the queue its own xml request.
******************************************************************************/
AsyncXMLGetRequest.prototype.setup = function()
{
	if(typeof XMLHttpRequest!='undefined')
	 {
		this.xmlRequest[this.queueCount] = new XMLHttpRequest();
		//window.alert('native IE support that also works in Firefox');
	}
/* AM SKIPPING THIS, SEEMS THE OBJECT ABOVE ALWAYS WORKS  */
/*
	else
	{
		try
		{
			this.xmlRequest[this.queueCount] = new ActiveXObject("Msxml2.XMLHTTP");
			//window.alert('test msxml2');
		}
		catch (e)
		{
			try
			{
				this.xmlRequest[this.queueCount] = new ActiveXObject("Microsoft.XMLHTTP");
				//window.alert('test msxml');
			}

			catch (E)
			{
				xmlhttp = null;
			}
		}

	}
*/

return;
}
/******************************************************************************
* AsyncXMLGetRequest::queueGetRequest - queue method for AsyncXMLGetRequest
*******************************************************************************
*     this method queues a request
******************************************************************************/
AsyncXMLGetRequest.prototype.queuePost = function(myUrl, myPostData, myObject, form_obj)
{
	if(typeof(form_obj) != undefined && form_obj != undefined && form_obj != '')
	{
		if(isArray(form_obj))
		{
			for(x=0;x<form_obj.length;x++)
			{
				form_data = form_obj[x];
				for(i=0; i<form_data.elements.length; i++)
				{
					if(form_data.elements[i].id)
					{
					//myPostData = myPostData + "&" + form_data.elements[i].id + "=" + form_data.elements[i].value;
					//window.alert("val" + form_data.elements[i].value);
						form_data.elements[i].id = form_data.elements[i].id.replace(/&/g, "[and]");
						form_data.elements[i].value = form_data.elements[i].value.replace(/&/g, "[and]");

						if(form_data.elements[i].type == "checkbox")
						{
							if(form_data.elements[i].checked == true)
							{
								myPostData = myPostData + "&" + form_data.elements[i].id + "=" + form_data.elements[i].value;
							}
						}
						else
						{
							myPostData = myPostData + "&" + form_data.elements[i].id + "=" + form_data.elements[i].value;
						}				
					}
				}	
			}
		}
		else
		{
			form_data = form_obj;

			for(i=0; i<form_data.elements.length; i++)
			{
				if(form_data.elements[i].id)
				{
				//myPostData = myPostData + "&" + form_data.elements[i].id + "=" + form_data.elements[i].value;
				//window.alert("val" + form_data.elements[i].value);
					form_data.elements[i].id = form_data.elements[i].id.replace(/&/g, "[and]");
					form_data.elements[i].value = form_data.elements[i].value.replace(/&/g, "[and]");

					if(form_data.elements[i].type == "checkbox")
					{
						if(form_data.elements[i].checked == true)
						{
							myPostData = myPostData + "&" + form_data.elements[i].id + "=" + form_data.elements[i].value;
						}
					}
					else
					{
						myPostData = myPostData + "&" + form_data.elements[i].id + "=" + form_data.elements[i].value;
					}				
				}
			}
		}
		//window.alert("post " + myPostData);
	}

	if(myPostData.indexOf('target') == -1)
	{
			myPostData = myPostData + "&" + "target=" + myObject;
	}
    if(this.inRequest == false)
	{
			this.inRequest = true;

			this.requestQueue[this.queueCount] = myUrl;
			this.objectQueue[this.queueCount] = myObject;
			this.postQueue[this.queueCount] = myPostData;
			this.formQueue[this.queueCount] = form_obj;
			this.setup();
			onRequest(this.objectQueue[this.queueCount]);
			this.queueCount++;

			this.sendPostRequest(myUrl, 0, myPostData);
	}
    else if(this.inRequest == true)
	{
		for(i=1;i<=this.queueCount;i++)
		{
			if(this.requestQueue[i] == myUrl && this.objectQueue[i] == myObject &&  this.postQueue[i] == myPostData &&  this.formQueue[i] == form_obj)
			{
				//window.alert('duplicate');
				// skip complete duplicate request already in queue
				return false;
			}
		}
		
		this.requestQueue[this.queueCount] = myUrl;
        this.objectQueue[this.queueCount] = myObject;
        this.postQueue[this.queueCount] = myPostData;
        this.formQueue[this.queueCount] = form_obj;
        this.setup();
        onRequest(myRequest.objectQueue[this.queueCount], myRequest.requestQueue[this.queueCount], myRequest.postQueue[this.queueCount], myRequest.formQueue[this.queueCount]);
        this.queueCount++;
	}
}

/******************************************************************************
* AsyncXMLGetRequest::sendPostRequest - sendPostRequest method for AsyncXMLGetRequest
*******************************************************************************
*     this method sends the specified request as POST
******************************************************************************/
AsyncXMLGetRequest.prototype.sendPostRequest = function(myUrl, qCount, postData)
{
    if(this.xmlRequest[qCount] == null)
	{
	    onRequestError(myRequest.objectQueue[0], ERR_CREATE_REQ, "Instance of XMLHttpRequest cannot be created or is null!");
	}
    else
	{
		if( (postData == '' || postData == undefined || postData.indexOf('remember_post') > -1) && document.getElementById(myRequest.objectQueue[qCount]) != undefined  )
		{
			postData = document.getElementById(myRequest.objectQueue[qCount]).getAttribute("post_data");
			//if(postData == undefined) postData = '';
			//window.alert(postData);
		}

		//window.alert(myUrl);
		//window.alert(this.qCount +" " + this.queueCount +" " +postData);

		if(myUrl.substring(0,1) == '/')
		{
			this.xmlRequest[qCount].open("POST", myUrl, true);
		}
		else
		{
			this.xmlRequest[qCount].open("POST", "/"+myUrl, true);
		}
		
		if(myUrl !== 'msgs')
		{
			document.body.style.cursor = 'wait';
		}
		this.xmlRequest[qCount].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		this.xmlRequest[qCount].setRequestHeader("Content-length", postData.length);
		this.xmlRequest[qCount].setRequestHeader("Connection", "close");
		this.xmlRequest[qCount].onreadystatechange = xmlHTTPStateChangePOST;
		this.xmlRequest[qCount].send(postData + "&ajax=1");

		//window.alert(postData);
        //this.xmlRequest[qCount].send("id=" + escape(idTextField.value));
	}
}

/******************************************************************************
* xmlHTTPStateChange - callback funciton
*******************************************************************************
*     this function is a callback used by the XMLHttpRequest object when there
*     is a change in the ready state.  If the ready state is 4, that means that
*     the content is loaded.  This function calls the onService routine always
*     with the number zero, because per a queue, the current element serviced
*     is always the first in.  After servicing, the first element in is
*     deleted from the queue, and if there are other requests waiting, the
*     next one in line will be handled, else the request chain is done.
******************************************************************************/
var myRequest = new AsyncXMLGetRequest();
function xmlHTTPStateChangePOST()
{
    //IF the request is uninitialized, before send() is called
    if(myRequest.xmlRequest[0].readyState == RS_UNINITIALIZED)
	{
	}
    //send() has not been called
    else if(myRequest.xmlRequest[0].readyState == RS_LOADING)
	{
	}
    //send() has been called, headers and status are available
    else if(myRequest.xmlRequest[0].readyState == RS_LOADED)
	{
	}
    //data is being downloaded
    else if(myRequest.xmlRequest[0].readyState == RS_INTERACTIVE)
	{
	}
    //the request has completed
    if(myRequest.xmlRequest[0].readyState == RS_COMPLETED)
	{
		if(myRequest.xmlRequest[0].responseText == null)
		{
	    	onRequestError(myRequest.objectQueue[0], ERR_RETURN_NULL, "Request returned null or no data!");
		}
		else
		{
			onServicePOST(myRequest.objectQueue[0], myRequest.requestQueue[0], myRequest.xmlRequest[0].responseText, myRequest.postQueue[0], myRequest.formQueue[0]);
		}

		myRequest.queueCount--;
		myRequest.requestQueue.splice(0, 1);
		myRequest.objectQueue.splice(0, 1);
		myRequest.postQueue.splice(0, 1);
		myRequest.formQueue.splice(0, 1);
		myRequest.xmlRequest.splice(0, 1);

		if(myRequest.queueCount == 0)
		{
			myRequest.inRequest = new Boolean(false);
			document.getElementById('ajax_status').src='/ext/images/ajax_idle.gif';
		}
		else
		{
			document.getElementById('ajax_status').src='/ext/images/ajax_loading.gif';
		    myRequest.sendPostRequest(myRequest.requestQueue[0], 0, myRequest.postQueue[0]);
		}
    }
}

/******************************************************************************
* onRequest - callback processing function
*******************************************************************************
*     this is called whenever a request is queued in AsyncXMLGetRequest.  This
*     function is passed the reference variable that was passed into the
*     queue, and can be used to prepare the object for the data.  Usually, this
*     function will take the form of a "loading" or "please wait" prompt, to
*     let the user know that the request has been queued, and you are awaiting
*     data.  The originally requested URL is passed in case it is needed.
******************************************************************************/
function onRequest(requestObj, requestURL)
{
	document.getElementById('ajax_status').src='/ext/images/ajax_loading.gif';
}
/******************************************************************************
* onService - callback processing function
*******************************************************************************
*     this is called whenever a request is serviced (meaning the data requested
*     has been recieved).  It can be used to update the object that requested
*     the data.  The originally requested URL is passed in case it is needed.
*     The data requested is passed as requestItem.
******************************************************************************/
function onServicePOST(requestObj, requestURL, requestItem, post_data, form_obj, js_tab_name)
{
	reconnected_notify();
	obj_name = new String(requestObj);

	var pane_id = '';
	if(obj_name.indexOf('max_media') > -1)
	{
		pane_id = 'max_media';
		//window.alert(obj_name);

		if(document.getElementById('max_media_chat') != undefined && document.getElementById('max_media_chat').style.display == 'none')
		{
			clearTimeout(chat_auto);
			clearTimeout(chat_list_auto);
		}
	}
	else if(obj_name.indexOf('summary_pane') > -1 && obj_name != "summary_pane_tabs")
	{
		pane_id = 'summary_pane';
		//window.alert(obj_name);
	}

	// identify container and tab elements
	// also clear the bottom pane
	if(pane_id != '')
	{
		var pane_container = document.getElementById(pane_id + '_container');
		var tabs = document.getElementById(pane_id + '_tabs');
	}

	if(requestObj !== '' && document.getElementById(requestObj) == undefined)
	{
		//window.alert(requestObj);
		// only allow this in the special panes
		if(pane_id != '')
		{
			//window.alert(requestObj);
			newObj = document.createElement('div');
			pane_container.appendChild(newObj);
			newObj.setAttribute('id',obj_name);
			//document.getElementById(
			//window.alert(requestObj.getAttribute('id'));
		}
		else
		{
			//window.alert(obj_name + 'does not exist');
			return;
		}
	}

	var autopost = 0;
	if(post_data.indexOf('autopost=1') > -1)
	{
		autopost = 1;
	}
	//if(requestObj == "login_msg") window.alert(requestItem);

	// parse html comments as script commands to evaluate
	var re_dml = new RegExp('<div style="display:none;" id="dml">(.*)</div id="dml">');

	var dml_objects = requestItem.match(re_dml);
	//retrieve DML objects

	// don't display this in any capacity to the client browser
	requestItem = requestItem.replace(re_dml, "");

	if(requestObj !== '')
	{
		var object = document.getElementById(requestObj);

		if(requestObj !== "msgs")
		{
			object.style.visibility = 'hidden';
			object.style.filter = "progid:DXImageTransform.Microsoft.Fade(Duration=1)";

			// set content into new element
			if(requestItem !== '') object.innerHTML = requestItem;

			if (object.filters)
			{
				object.filters[0].apply();
				if(object.style.height == 0) object.style.height = '0px';
				object.style.visibility = 'visible';
				object.filters[0].play();
			}
			else
			{
				object.style.visibility = 'visible';
				object.style.opacity = (0 / 100);
				object.style.MozOpacity = (0 / 100);
				object.style.KhtmlOpacity = (0 / 100);
				opacity(requestObj, 0, 100, 700); // Firefox and others
			}
		}


		object.style.display = 'block';
		document.getElementById(requestObj).setAttribute('url', requestURL);
	}
	//window.alert(dml_objects);
	if(dml_objects != null)
	{
	//if(obj_name != 'bottom_right_pane') window.alert(obj_name + " - " +dml_objects[1]);
		eval(dml_objects[1]);
	}
	else
	{
		//	if(obj_name != 'bottom_right_pane')	window.alert('null');
	}

	if((typeof(logged_in) == 'undefined' || !logged_in) && require_login && obj_name != "login_msg" && requestURL  != "msgs" && post_data.indexOf('autopost') == -1)
	{
		myRequest.queuePost('msgs', 'action=send_msg&autopost=1&msg=Your session has expired. Please log in.', 'bottom_right_pane');
		window.onbeforeunload=null;
		window.location.replace('/index.php');
		return;
	}

	if(pane_id != '')
	{
		var tab_content = '';
		var tab_controls;

		// hide all other elements in the container and display this one
		for(var i=0; i<pane_container.childNodes.length; i++)
		{
			//pane_container.childNodes[i].style.zIndex = 0 - i;
			var tab_name = pane_container.childNodes[i].getAttribute("tab_name");

			var highlighted = '';
			image_indicator = '';


			var tab_url;

			if(pane_container.childNodes[i].getAttribute('url') != undefined && pane_container.childNodes[i].getAttribute('url') != '')
			{
				tab_url = pane_container.childNodes[i].getAttribute('url');
				//window.alert('tab' + tab_url + tab_name + obj_name);
			}
			else
			{
				//window.alert('oops');
				tab_url = pane_container.childNodes[i].id;
			}
			//window.alert(tab_url);

			if(pane_container.childNodes[i].id == obj_name)
			{
				// check for JS override of tab name
				if(js_tab_name == undefined)
				{
						if(tab_name == undefined)
						{
							// if no previous name specified use last word in target
							fake_tab_name =  pane_container.childNodes[i].id;
							var split_name = fake_tab_name.split("_", 4);
							fake_tab_name = split_name.pop();
							fake_tab_name = capWords(fake_tab_name);
							pane_container.childNodes[i].setAttribute('tab_name',fake_tab_name);
						}
						// use previous name
						else
						{
							//window.alert(requestURL+obj_name+tab_name);
							// do nothing
						}
				}
				//javascript override
				else
				{
					pane_container.childNodes[i].setAttribute('tab_name',js_tab_name);
				}

				tab_name = pane_container.childNodes[i].getAttribute("tab_name");

				highlighted = 'background-color:#FFFFFF;';
				image_indicator = '';

				pane_container.childNodes[i].setAttribute("url", requestURL);
				//window.alert(obj_name  + requestURL);

				if (form_obj == undefined || requestURL == 'search' || requestURL == 'calendar')
				{
					var re_autopost = new RegExp('&autopost=1');
					var new_post_data = post_data.replace(re_autopost, '');
					pane_container.childNodes[i].setAttribute('post_data',new_post_data);
				}

				pane_container.childNodes[i].style.display = 'block';
				pane_container.childNodes[i].style.position = 'absolute';
				//pane_container.childNodes[i].style.left = "0px";
				//pane_container.childNodes[i].style.top ="0px";
				pane_container.childNodes[i].style.width = pane_container.style.width;
				//pane_container.childNodes[i].style.height = pane_container.style.height;
				pane_container.childNodes[i].style.overflow = pane_container.style.overflow;
				pane_container.childNodes[i].style.backgroundColor = pane_container.style.backgroundColor;
				//if(post_data.indexOf('autopost=1') == -1) pane_container.childNodes[i].focus();

				tab_refresh_click = 'myRequest.queuePost(\'' + tab_url  + '\', \'' + pane_container.childNodes[i].getAttribute('post_data') + '\', \'' + pane_container.childNodes[i].id + '\')';
				tab_controls = "<img src=\"/ext/images/close_button.gif\" style=\"cursor:pointer;\" onClick=\"destroy_tab('"+pane_container.childNodes[i].id+"');\" />";
				tab_controls += " &nbsp; ";
				tab_controls += "<img src=\"/ext/images/refresh_button.gif\" style=\"cursor:pointer;\" onClick=\""+tab_refresh_click+"\" />";

			}
			else
			{
				pane_container.childNodes[i].style.display = 'none';
			}

			// hide explicitly hidden or summary pane tabs
			var nodisplay;
			if(tab_name == "nodisplay" || pane_id == "summary_pane")
			{
				nodisplay = "display:none;";
			}


			
			tab_click = "show_pane_div('"+ pane_container.childNodes[i].id + "');";
			tab_content += '<button id="tab_' + pane_container.childNodes[i].id + '" style="cursor:pointer;height:30px;' + highlighted + nodisplay + '" onClick="'+tab_click+'">'  + tab_name + '</button>';
		}

	tabs.innerHTML = tab_content;
	document.getElementById('tabcontrols').innerHTML = tab_controls;
	}

	document.body.style.cursor = 'auto';
}
/******************************************************************************
* onRequestError - callback processing function
*******************************************************************************
*     this is called whenever there is an error with a request, either a file
*     not found, or trouble initializing the XMLHttpRequest
******************************************************************************/
function onRequestError(requestObj, errorCode, verboseError)
{
	noconnection_notify();
}

function show_pane_div(obj_name)
{
	pane_id = '';
	if(obj_name.indexOf('max_media') > -1)
	{
		pane_id = 'max_media';
	}
	
	// identify container and tab elements
	// also clear the bottom pane
	if(pane_id != '')
	{
		var pane_container = document.getElementById(pane_id + '_container');
		var tabs = document.getElementById(pane_id + '_tabs');
	}

	if(pane_id != '')
	{
		var tab_content = '';
		var tab_controls = "";

		// hide all other elements in the container and display this one
		for(var i=0; i<pane_container.childNodes.length; i++)
		{
			var tab_name = pane_container.childNodes[i].getAttribute("tab_name");

			var highlighted = '';
			image_indicator = '';
			if(pane_container.childNodes[i].id == obj_name)
			{
				tab_name = pane_container.childNodes[i].getAttribute("tab_name");
				
				var tab_url;
				if(pane_container.childNodes[i].getAttribute('url'))
				{
					tab_url = pane_container.childNodes[i].getAttribute('url');	
				}
				
				highlighted = 'background-color:#FFFFFF;';
				image_indicator = '';

				pane_container.childNodes[i].style.display = 'block';
				pane_container.childNodes[i].style.position = 'absolute';
				pane_container.childNodes[i].style.width = pane_container.style.width;
				pane_container.childNodes[i].style.overflow = pane_container.style.overflow;
				pane_container.childNodes[i].style.backgroundColor = pane_container.style.backgroundColor;

				tab_refresh_click = 'myRequest.queuePost(\'' + tab_url  + '\', \'' + pane_container.childNodes[i].getAttribute('post_data') + '\', \'' + pane_container.childNodes[i].id + '\')';
				tab_controls = "<img src=\"/ext/images/close_button.gif\" style=\"cursor:pointer;\" onClick=\"destroy_tab('"+pane_container.childNodes[i].id+"');\" />";
				tab_controls += " &nbsp; ";
				tab_controls += "<img src=\"/ext/images/refresh_button.gif\" style=\"cursor:pointer;\" onClick=\""+tab_refresh_click+"\" />";
			}
			else
			{
				pane_container.childNodes[i].style.display = 'none';
			}

			tab_click = "show_pane_div('"+ pane_container.childNodes[i].id + "');";
			tab_content += '<button id="tab_' + pane_container.childNodes[i].id + '" style="cursor:pointer;height:30px;' + highlighted  + '" onClick="'+tab_click+'">'  + tab_name + '</button>';
		}
	
	tabs.innerHTML = tab_content;
	document.getElementById('tabcontrols').innerHTML = tab_controls;
	}
}

function isArray(obj) {
   if (!obj.constructor || obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}