jQuery(document).ready(function() {
	jQuery('.lightbox').each(function(index) {
		var el = jQuery(this);
		var parts = el.attr('title').split(' :: ', 2);

		var attributes = {};

		if (parts[1]) {
			parts[1] = parts[1].replace(', ', ',');
			var parts_attrs = parts[1].split(',');

			for (var i = 0, size = parts_attrs.length; i < size; i++) {
				var tmp = parts_attrs[i].replace(': ', ':').split(':');
				attributes[tmp[0]] = tmp[1];
			}
		}

		var url = el.attr('href');
		var base_attributes = {href:url, speed:0, overlayClose:false, opacity:0.5, title:parts[0]};
		if (url.charAt(0) == '#') {
			base_attributes.inline = true;
		} else {
			base_attributes.iframe = true;
		}
		jQuery.extend(attributes, base_attributes);

		el.removeAttr('title');
		el.colorbox(attributes);
	});
});

var prevent_doubleclick_enabled = false;

/**
 * @param  integer delay Delay in seconds
 * @return boolean
 */
function prevent_doubleclick(delay) {
	if (prevent_doubleclick_enabled) {
		return false;
	}

	var buttons = $$('button');
	buttons.each(function(el) {
		Element.addClassName(el, 'button_disabled');
	});

	prevent_doubleclick_enabled = true;

	if (typeof delay != 'undefined') {
		setTimeout('release_doubleclick()', delay * 1000);
	}

	return true;
}

function release_doubleclick() {
	$$('.button_disabled').invoke('removeClassName', 'button_disabled');
	prevent_doubleclick_enabled = false;
}

function selected_rows_highlight(el) {
	var checkboxes = el.getElementsBySelector('input[type=checkbox]');
	for (var i = 0, size = checkboxes.length; i < size; i++) {
		if (checkboxes[i].checked) {
			el.addClassName('rowSelected');

			// One is enough
			return;
		} else {
			// If we don't find one, we're probably going to unhighlight
			el.removeClassName('rowSelected');
		}
	}
}

function selected_rows_addevent(el) {
	var checkboxes = el.getElementsBySelector('input[type=checkbox]');
	for (var i = 0, size = checkboxes.length; i < size; i++) {
		checkboxes[i].observe('click', find_selected_rows);
	}
}

function find_selected_rows(add_onclicks) {
	if (typeof add_onclicks == 'boolean') {
		$$('.selectable').each(selected_rows_addevent);
	}
	$$('.selectable').each(selected_rows_highlight);
}

function render_scrollable_table(id, scroll_height) {
	var container  = $(id);
	var tbl_orig   = container.select('table').first();
	var tbl_header = tbl_orig.select('thead').first();

	if (typeof tbl_header != 'undefined') {
		var actual_height = tbl_orig.getHeight() - tbl_header.getHeight();

		// Get the width of the table.
		var total_width = tbl_orig.getWidth();

		// Set the width of the container div.
		container.setStyle({'width': total_width + 'px'});

		// Don't add the fixed height and scroll box if there isn't enough content to scroll.
		if (actual_height > scroll_height) {
			var col_widths = new Array();

			// Add fixed widths to the table header columns.
			tbl_header.select('th').each(function(item, index) {
				col_widths[index] = item.getWidth();
				item.writeAttribute({'width': col_widths[index]});
			});

			// Remove header from the original table.
			var tmp_header = tbl_header.remove();

			// Add fixed widths to the table body columns.
			tbl_orig.select('tr').first().select('td').each(function(item, index) {
				item.writeAttribute({'width': col_widths[index]});
			});

			// Collect all of the children of the table and remove them.
			var tmp_rows = [];
			tbl_orig.childElements().each(function(item, index) {
				tmp_rows[tmp_rows.length] = item.remove();
			});

			// Remove whitespace that was left behind.
			tbl_orig.update('');

			// Update the width of the container div.
			container.setStyle({'width': (total_width + 18) + 'px'});

			// Create table to hold the scrollable body.
			var tmp_tbl_body = $(tbl_orig.cloneNode(true));
			for (var i = 0, size = tmp_rows.size(); i < size; i++) {
				tmp_tbl_body.insert(tmp_rows[i]);
			}
			tmp_tbl_body.setStyle({'height': scroll_height + 'px'});

			// Add fixed header back into the DOM.
			var tmp_tbl_header = $(tbl_orig.cloneNode(true));
			tmp_tbl_header.insert(tmp_header);
			container.insert(tmp_tbl_header);

			// Add scrollable body into the DOM.
			var scroll_box = new Element('div', {'style': 'height: ' + scroll_height + 'px; overflow: auto;', 'class': 'scrolling_container'});
			scroll_box.insert(tmp_tbl_body);
			container.insert(scroll_box);

			// Remove original table.
			tbl_orig.remove();
		}
	}
}

function display_errors(errors) {
	var error_txt = "The following errors have occurred:\n";
	for (var i = 0, size = errors.size(); i < size; i++) {
		error_txt+= "- " + errors[i] + "\n";
	}
	alert(error_txt);
}

function findParent(elm, tag)
{
	while (elm && elm.tagName && elm.tagName.toLowerCase() != tag)
	{
		elm = elm.parentNode;
	}
	return elm;
}

function disable_button(el)
{
	Element.addClassName(el, 'button_disabled');
	Element.writeAttribute(el, {'disabled': 'disabled'});
}

function enable_button(el)
{
	Element.removeClassName(el, 'button_disabled');
	Element.writeAttribute(el, {'disabled': null});
}

String.prototype.nl2br = function()
{
	return this.replace( /\n/g, "<br />" );
}

String.prototype.br2nl = function()
{
	return this.replace(/<br\s*(\/)*>/g, "\n" );
}

function getCheckedValue(radioObj)
{
	if (!radioObj)
	{
		return '';
	}
	var radioLength = radioObj.length;
	if (radioLength == undefined)
	{
		if (radioObj.checked)
		{
			return radioObj.value;
		}
		else if (radioObj.value)
		{
			return radioObj.value;
		}
		else
		{
			return '';
		}
	}
	for (var i = 0; i < radioLength; i++)
	{
		if (radioObj[i].checked)
		{
			return radioObj[i].value;
		}
	}
	return '';
}

function IsNumeric(strString)
{
	var strValidChars = '0123456789.';
	var strChar;
	var blnResult = true;

	if (strString.length == 0) return false;

	//  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	{
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
		{
			blnResult = false;
		}
	 }
	return blnResult;
}

function round_number(original_number, decimals)
{
	var result1 = original_number * Math.pow(10, decimals);
	var result2 = Math.round(result1);
	var result3 = result2 / Math.pow(10, decimals);
	return result3;
}

function round_decimals(original_number, decimals)
{
	var result = round_number(original_number, decimals);
	return pad_with_zeros(result, decimals);
}

function pad_with_zeros(rounded_value, decimal_places)
{
	// Convert the number to a string
	var value_string = rounded_value.toString();

	// Locate the decimal point
	var decimal_location = value_string.indexOf('.');

	// Is there a decimal point?
	if (decimal_location == -1)
	{
		// If no, then all decimal places will be padded with 0s
		decimal_part_length = 0;

		// If decimal_places is greater than zero, tack on a decimal point
		value_string += decimal_places > 0 ? '.' : '';
	}
	else
	{
		// If yes, then only the extra decimal places will be padded with 0s
		decimal_part_length = value_string.length - decimal_location - 1;
	}

	// Calculate the number of decimal places that need to be padded with 0s
	var pad_total = decimal_places - decimal_part_length;

	if (pad_total > 0)
	{
		// Pad the string with 0s
		for (var counter = 1; counter <= pad_total; counter++)
		{
			value_string += '0';
		}
	}
	return value_string;
}

function generate_random_str(str_length)
{
	var random_id = '';
	var available_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
	for(var i = 0; i < str_length; i++)
	{
		var j = Math.floor(Math.random() * available_chars.length);
		random_id += available_chars.charAt(j);
	};
	return random_id;
}

function show_hint(e)
{
	var parentNode = e.parentNode;
	var parentTop = findPosY(parentNode);
	var parentLeft = findPosX(parentNode);
	var parentWidth = parentNode.offsetWidth;
	var hintNode = getElementsByClass('hint', parentNode);
	hintNode[0].style.top = parentTop + 'px';
	hintNode[0].style.left = (parentLeft + parentWidth + 25) + 'px';
	hintNode[0].style.display = 'inline';

	return;
}

function hide_hint(e)
{
	var parentNode = e.parentNode;
	var hintNode = getElementsByClass('hint', parentNode);
	hintNode[0].style.display = 'none';

	return;
}

function limit_textarea_length(field, limit) {
	field = $(field);

	if (typeof field == 'undefined') {
		throw 'Field does not exist. Cannot limit length.';
	}

	if ($F(field).length > limit) {
		field.value = $F(field).substring(0, limit);
	}

	return (limit - $F(field).length);
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function findPosX(obj)
{
	var curleft = 0;
	if(obj.offsetParent)
	{
		while(true)
		{
			curleft += obj.offsetLeft;
			if(!obj.offsetParent) break;
			obj = obj.offsetParent;
		}
	}
	else if(obj.x)
	{
		curleft += obj.x;
	}
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if(obj.offsetParent)
	{
		while(true)
		{
			curtop += obj.offsetTop;
			if(!obj.offsetParent) break;
			obj = obj.offsetParent;
		}
	}
	else if(obj.y)
	{
		curtop += obj.y;
	}
	return curtop;
}

function trim(sString, character)
{
	if(character == undefined)
	{
		character = ' ';
	}
	while(sString.substring(0, 1) == character)
	{
		sString = sString.substring(1, sString.length);
	}
	while(sString.substring(sString.length - 1, sString.length) == character)
	{
		sString = sString.substring(0, sString.length - 1);
	}
	return sString;
}

Array.prototype.inArray = function(value)
{
	for(var i = 0; i < this.length; i++)
	{
		if(this[i] === value)
		{
			return true;
		}
	}
	return false;
}

function addEvent(objAttrib, handler, addFunction)
{
	if((!document.all) && (document.getElementById))
	{
		objAttrib.setAttribute(handler, addFunction, 0);
	}
	// Workaround for IE 5.x
	if((document.all) && (document.getElementById))
	{
		objAttrib[handler] = new Function(addFunction);
	}
}

function cleanUp(a)
{
	 a = a.split("'").join("");
	 a = a.split("\"").join("");
	 a = a.split("&").join("");
	 a = a.split("#").join("");
	 a = a.split("$").join("");
	 a = a.split("%").join("");
	 a = a.split("^").join("");
	 a = a.split("*").join("");
	 a = a.split("!").join("");
	 a = a.split("\\").join("");
	 a = a.split("<").join("");
	 a = a.split(">").join("");
	 a = a.split("~").join("");
	 a = a.split(";").join("");
	return a;
}

function remove_default(entry, default_text)
{
	if (entry.value == default_text)
	{
		entry.value = '';
	};
}

function restore_default(entry, default_text)
{
	if (entry.value == '')
	{
		entry.value = default_text;
	};
}

/**
 * This method checks each character as they are entered into any
 * form field for an event 'Enter'. Once found, it will submit
 * the form object passed in at form_el
 *
 * @param object evt event
 * @param object form_el form name including the 'document.' part
 * @return boolean
 */
function searchModeKeyDown(evt, form_el, submit)
{
	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);

	if ((charCode == 13) || (charCode == 3)) // look for 'Return' 'Enter' keys
	{
		if (submit)
		{
			form_el.submit();
		}

		return false;
	}
	return true;
}

/**
 * Format numbers with ,.
 *
 * @access public
 * @param  integer num
 * @return string
 */
function addCommas(num)
{
	num += '';
	var x = num.split('.');
	var x1 = x[0];
	var x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function open_help(url, height, width)
{
	height = ((height != undefined) ? height : 350)
	width = ((width != undefined) ? width : 500)

	var w = window.open(url, 'help', 'scrollbars=1,resizable=1,height='+height+',width='+width);
	w.focus();

	return false;
}

function minutes_to_string(time)
{
	if (time < 60)
	{
		// Minutes and Seconds
		var minutes = Math.floor(time);
		var seconds = Math.round((time - Math.floor(time)) * 60);

		if (minutes > 0 && seconds > 0)
		{
			var time_val = minutes + ' ' + ((minutes == 1) ? 'min ':'mins ') + seconds + ' ' + ((seconds == 1) ? 'sec ':'secs ');
		}
		else if (minutes > 0)
		{
			var time_val = minutes + ' ' + ((minutes == 1) ? 'min ':'mins ');
		}
		else
		{
			var time_val = seconds + ' ' + ((seconds == 1) ? 'sec ':'secs ');
		}
	}
	else if (time >= 60 && time < 1440)
	{
		// Hours and Minutes
		var hours = Math.floor(time / 60);
		var minutes = Math.floor(((time / 60) - Math.floor(time / 60)) * 60);
		var seconds = Math.round((time - Math.floor(time)) * 60);

		if (minutes > 0)
		{
			var time_val = hours + ' ' + ((hours == 1) ? 'hr ':'hrs ') + minutes + ' ' + ((minutes == 1) ? 'min ':'mins ');
		}
		else if (seconds > 0)
		{
			var time_val = hours + ' ' + ((hours == 1) ? 'hr ':'hrs ') + seconds + ' ' + ((seconds == 1) ? 'sec ':'secs ');
		}
		else
		{
			var time_val = hours + ' ' + ((hours == 1) ? 'hr ':'hrs ');
		}
	}
	else
	{
		// Days and Hours
		var days = Math.floor(time / 1440);
		var minutes_left = (((time / 1440) - Math.floor(time / 1440)) * 1440);

		if (minutes_left >= 60)
		{
			var hours = Math.floor(minutes_left / 60);
			var minutes = Math.floor(((minutes_left / 60) - Math.floor(minutes_left / 60)) * 60);

			if (minutes > 0)
			{
				var time_val = days + ' ' + ((days == 1) ? 'day ':'days ') + hours + ' ' + ((hours == 1) ? 'hr ':'hrs ') + minutes + ' ' + ((minutes == 1) ? 'min ':'mins ');
			}
			else
			{
				var time_val = days + ' ' + ((days == 1) ? 'day ':'days ') + hours + ' ' + ((hours == 1) ? 'hr ':'hrs ');
			}
		}
		else
		{
			var minutes = Math.floor(minutes_left);

			if (minutes > 0)
			{
				var time_val = days + ' ' + ((days == 1) ? 'day ':'days ') + minutes + ' ' + ((minutes == 1) ? 'min ':'mins ');
			}
			else
			{
				var time_val = days + ' ' + ((days == 1) ? 'day ':'days ');
			}
		}
	}
	return time_val;
}

// Simulates PHP's date function
Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar])
			returnStr += replace[curChar].call(this);
		else if (curChar == "\\")
			returnStr += format.charAt(++i);
		else
			returnStr += curChar;
	}
	return returnStr;
};

Date.prototype.format_range = function(date2, date_format, time_format, timezone) {
	var returnStr = this.format(date_format) + ' ' + this.format(time_format);
	if (timezone) {
		returnStr += ' ' + timezone;
	}
	returnStr += ' - ';
	if (this.format('M j Y') == date2.format('M j Y')) {
		returnStr += date2.format(time_format);
	} else {
		returnStr += date2.format(date_format) + ' ' + date2.format(time_format);
	}
	if (timezone) {
		returnStr += ' ' + timezone;
	}
	return returnStr;
};

Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],

	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return "Not Yet Supported"; },
	// Year
	L: function() { return "Not Yet Supported"; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() == 0 ? 12 : (this.getHours() > 12 ? this.getHours() - 12 : this.getHours()); },
	G: function() { return this.getHours(); },
	h: function() { return (this.getHours() < 10 || (12 < this.getHours() < 22) ? '0' : '') + (this.getHours() < 10 ? this.getHours() + 1 : this.getHours() - 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (this.getTimezoneOffset() < 0 ? '-' : '+') + (this.getTimezoneOffset() / 60 < 10 ? '0' : '') + (this.getTimezoneOffset() / 60) + '00'; },
	T: function() { return "Not Yet Supported"; },
	Z: function() { return this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return "Not Yet Supported"; },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
}

function submit_form(form_id, onsuccess) {
	var params = $H({'output_type': 'ajax',
					 'rand': generate_random_str(10)
				   });

	params = params.merge($(form_id).serialize(true));

	// Make server request.
	new Ajax.Request('/index.php', {
		method: 'post',
		parameters: params,
		onSuccess: onsuccess
	});
}

function cancel_form(form_id, error_div) {
	$(form_id).reset();
	$(error_div).update('');
	$$('.field_error').invoke('removeClassName', 'field_error');
}

function process_success(transport, error_div) {
	if (transport.responseText) {
		var json = transport.responseText.evalJSON();
		if (json.success == true) {
			if (json.redirect_url) {
				window.location.href = json.redirect_url;
			} else {
				window.location.reload();
			}
		} else {
			if (json.ERRORS) {
				var msg = '';

				json.ERRORS.each(
					function (error) {
						if (typeof error == 'string') {
							msg += '<p>' + error + '</p>';
						}
					}
				);
				$(error_div).show();
				$(error_div).addClassName('field_error');
				$(error_div).update(msg);
			}

			if (json.ERROR_FIELDS) {
				json.ERROR_FIELDS.each(
					function (error_field) {
						$(error_field).addClassName('field_error');
					}
				)
			}

			release_doubleclick();
		}
	}
}

function select_tab(i) {
	$('tab' + i).up(1).descendants().each(function(el) {
		if (el.hasClassName('tabactive')) {
			el.removeClassName('tabactive');
			el.addClassName('tabinactive');
		}
		else if (el.hasClassName('tabcontent')) {
			el.hide();
		}
	});

	$('tab' + i).removeClassName('tabinactive');
	$('tab' + i).addClassName('tabactive');
	$('tabcontent' + i).show();
}

function show_inline_action(action_div, scroll) {
	// Hide any actions that might be displaying.
	$$('.inline_action').invoke('hide');

	// Hide any buttons so the action is primary.
	if ($('buttons')) {
		$('buttons').hide();
	}

	// Reset the form in the div.
	if ($(action_div + '_form')) {
		$(action_div + '_form').reset();
	}

	// Show the requested action.
	if ($(action_div)) {
		$(action_div).show();
		if (scroll) {
			$(action_div).scrollTo();
		}
	}
}

function cancel_inline_action(action_div) {
	$(action_div).hide();
	$$('.inline_error').invoke('update', '');
	$$('.field_error').invoke('removeClassName', 'field_error');
	if ($('buttons')) {
		$('buttons').show();
	}

	Element.scrollTo(document.body);
}
