// HTTP_Request object
function createRequestObject()
{
	var ro;
	var browser = navigator.appName;
	if(browser == "Microsoft Internet Explorer")
		ro = new ActiveXObject("Microsoft.XMLHTTP");
	else
		ro = new XMLHttpRequest();
	return ro;
}

// Globals
var http = createRequestObject();

// Standard AJAX function to get output from an external page web page
// Uses the HTTP_Request object to open a external(from itself) page, loads a loading.gif where it will put it's content,
// uses the HTTP_Request object and an anonymous function to update the given element on completion of the request
function getAjaxStyle(element, link, skipload, sync)
{
	if(sync == null || sync == 'undefined' || sync == 0)
		sync = true;
	else
		sync = false;
	if(skipload == null || skipload == 'undefined' || skipload == 0)
		skipload = false;
	else if(skipload != 'text')
		skipload = true;
	var http = createRequestObject();
	if(skipload == 'text')
		document.getElementById(element).innerHTML = '<br /><center><span style="color: #666666;">Loading...</span></center><br />';
	else if(!skipload)
		document.getElementById(element).innerHTML = '<center><img src="images/loading.gif" /></center><br />';
    http.open('get', link, sync);
    if(sync)
    {
	    http.onreadystatechange = function()
	    {
	        if(http.readyState == 4)
	        {
	            document.getElementById(element).innerHTML = http.responseText;
	        }
	    };
    }
    http.send(null);
}

//Processes 'link'
function processAjax(link)
{
	var http = createRequestObject();
    http.open('get', link, false);
    http.send(null);
}

// Function to collect information from a form(formName)
// Constructs the proper link from the given base 'link' and calls the proper process function based upon the passed 'method'
// updateElement is only used if the passed 'method' is 'update'
// If the passed 'method' is 'debug', then the link is constructed/alerted, a suggested PHP POST page is alerted,
// and the results of processing the completed 'link' are displayed in a dynamically created lightbox called debugConsole
function postAjaxStyle(formName, link, method, updateElement)
{
	var f = document.forms[formName];
	var checkboxIDs = [];
	var checkboxValues = [];
	var phpPostString = '';

	for(var i = 0; i < f.elements.length; i++)
	{
		if(f.elements[i].type != 'submit' && f.elements[i].type != 'button' && f.elements[i].type != 'image')
		{
			if(i == 0)
				link = link + '?';

			if(f.elements[i].type == 'select-one')
			{
				link += '&' + f.elements[i].id + '=' + urlencode(f.elements[i].options[f.elements[i].selectedIndex].value);
				if(method == 'debug')
					phpPostString += '$' + f.elements[i].id + ' = urldecode(getvar(\'' + f.elements[i].id + '\'));\n';
			}
			else if(f.elements[i].type == 'text' || f.elements[i].type == 'textarea' || f.elements[i].type == 'hidden')
			{
				link = link + '&' + f.elements[i].id + '=' + urlencode(f.elements[i].value.replace('+','$$'));
				if(method == 'debug')
					phpPostString += '$' + f.elements[i].id + ' = urldecode(getvar(\'' + f.elements[i].id + '\'));\n';
			}
			else if(f.elements[i].type == 'radio')
			{
				if(f.elements[i].checked)
				{
					link = link + '&' + f.elements[i].id + '=' + urlencode(f.elements[i].value);
					if(method == 'debug')
						phpPostString += '$' + f.elements[i].id + ' = urldecode(getvar(\'' + f.elements[i].id + '\'));\n';
				}
			}
			else if(f.elements[i].type == 'checkbox')
			{
				if(f.elements[i].checked)
				{
					var go = true;
					var idx = checkboxIDs.length;
					for(var j = 0; j < checkboxIDs.length; j++)
					{
						if(checkboxIDs[j] == f.elements[i].id)
						{
							go = false;
							idx = j;
						}
					}
					if(go)
						checkboxIDs.push(f.elements[i].id); 
					if(checkboxValues[idx] != '' && checkboxValues[idx] != undefined)
						checkboxValues[idx] = checkboxValues[idx] + ',' + f.elements[i].value;
					else
						checkboxValues[idx] = f.elements[i].value;
				}
			}
		}
	}
	for(var k = 0; k < checkboxIDs.length; k++)
	{
		link = link + '&' + checkboxIDs[k] + '=' + urlencode(checkboxValues[k]);
		if(method == 'debug')
			phpPostString += '$' + checkboxIDs[k] + ' = urldecode(getvar(\'' + checkboxIDs[k] + '\'));	// CSV data\n';
	}

	if(method == 'debug')
	{
		alert('COMPLETED LINK => ' + link);
		alert('SUGGESTED GETVARS FOR PHP POST PAGE:\n' + phpPostString);
	}
	else if(method == 'update')
	{
		getAjaxStyle(updateElement, link, 'text');
	}
	else
		processAjax(link);

	return true;
}

function openLightBoxOnCenter(ele, width, yPadding, cover)
{
	$(ele).setStyle('opacity', '0');
	if(yPadding == null || yPadding == 'undefined' || yPadding == 0)
		yPadding = 50;

	var scrollX = 0;
	var scrollY = 0;

	if(window.innerWidth)
	{
		bsw = window.innerWidth;
	}
	else if(document.documentElement)
	{
		bsw = document.documentElement.clientWidth;
	}
	else if(document.body)
	{
		bsw = document.body.clientWidth;
	}

	scrollX = getScrollXY('X');
	$(ele).setStyle('left', ((bsw / 2) + scrollX) + 'px');
	$(ele).setStyle('margin-left', '-' + (width / 2) + 'px');

	scrollY = getScrollXY('Y');
	$(ele).setStyle('top', (scrollY + parseInt(yPadding)) + 'px');
	
	if(width != null)
		$(ele).setStyle('width', width + 'px');
	else
		$(ele).setStyle('width', '400px');

	$(ele).setStyle('display', 'block');
	if(cover != false)
	{
		$('coverDiv').setStyle('opacity', '0');
		$('coverDiv').setStyle('display', 'block');
	}
	var lightBox = new Fx.Tween(ele);
	if(cover != false)
	{
		var coverBox = new Fx.Tween('coverDiv');
		coverBox.start('opacity', '0', '.7');
	}
	lightBox.start('opacity', '0', '1');
}

function closeLightBox(ele)
{
	var editBox = new Fx.Tween(ele);
	var coverBox = new Fx.Tween('coverDiv');
	editBox.start('opacity', '1', '0');
	coverBox.start('opacity', '.7', '0');
}

// Given a start time, an element to update, and a static time to add to the running time
// this will compute the current running time and place it into the given element
function currtime(element)
{
	var now = new Date();

	// Make month number correspond to month name
	var month = now.getMonth() + 1;
	if(month == 1) monthName = ("January");
	else if(month == 2) monthName = ("February");
	else if(month == 3) monthName = ("March");
	else if(month == 4) monthName = ("April");
	else if(month == 5) monthName = ("May");
	else if(month == 6) monthName = ("June");
	else if(month == 7) monthName = ("July");
	else if(month == 8) monthName = ("August");
	else if(month == 9) monthName = ("September");
	else if(month == 10) monthName = ("October");
	else if(month == 11) monthName = ("November");
	else monthName=("December");
	var date = now.getDate();
	// Add suffix to date (1st, 2nd, 4th, etc.)
	if(date == 1) suffix = ("st");
	else if(date == 2) suffix = ("nd");
	else if(date == 3) suffix = ("rd");
	else if(date == 21) suffix = ("st");
	else if(date == 22) suffix = ("nd");
	else if(date == 23) suffix = ("rd");
	else if(date == 31) suffix = ("st");
	else suffix = ("th");
	var year = now.getFullYear();
	var dateValue = monthName + ' ' + date + suffix + ', ' + year;

	// Time
	var hours = now.getHours();
	var minutes = now.getMinutes();
	var seconds = now.getSeconds();
	var timeValue = "" + ((hours > 12) ? hours - 12 : hours);
	if(timeValue == "0")
		timeValue = 12;
	timeValue += ((minutes < 10) ? ":0" : ":") + minutes;
	timeValue += ((seconds < 10) ? ":0" : ":") + seconds;
	timeValue += (hours >= 12) ? " PM" : " AM";

	document.getElementById(element).innerHTML = dateValue + ' ' + timeValue;
}

// Execute the given display action on the given element
function showHide(element, action)
{
	var ele = document.getElementById(element);
	ele.style.display = action;
}

function urlencode(str)
{
	var histogram = {}, tmp_arr = [];
	var ret = str.toString();

	var replacer = function(search, replace, str)
	{
		var tmp_arr = [];
		tmp_arr = str.split(search);
		return tmp_arr.join(replace);
	};
	
	// The histogram is identical to the one in urldecode.
	histogram["'"]   = '%27';
	histogram['(']   = '%28';
	histogram[')']   = '%29';
	histogram['*']   = '%2A';
	histogram['~']   = '%7E';
	histogram['!']   = '%21';
	histogram['%20'] = '+';
	
	// Begin with encodeURIComponent, which most resembles PHP's encoding functions
	ret = encodeURIComponent(ret);
	
	for(search in histogram)
	{
		replace = histogram[search];
		ret = replacer(search, replace, ret); // Custom replace. No regexing
	}

	// Uppercase for full PHP compatibility
	return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2)
	{
		return "%"+m2.toUpperCase();
	});
	
	return ret;
}

function urldecode(str)
{
	var histogram = {};
	var ret = str.toString();
	
	var replacer = function(search, replace, str)
	{
		var tmp_arr = [];
		tmp_arr = str.split(search);
		return tmp_arr.join(replace);
	};
	
	// The histogram is identical to the one in urlencode.
	histogram["'"]   = '%27';
	histogram['(']   = '%28';
	histogram[')']   = '%29';
	histogram['*']   = '%2A';
	histogram['~']   = '%7E';
	histogram['!']   = '%21';
	histogram['%20'] = '+';
 
	for(replace in histogram)
	{
		search = histogram[replace]; // Switch order when decoding
		ret = replacer(search, replace, ret); // Custom replace. No regexing
	}
	
	// End with decodeURIComponent, which most resembles PHP's encoding functions
	ret = decodeURIComponent(ret);
 
	return ret;
}

