//Globals
var gDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];

//Form functions

//Button functions
function submitbutton(inIDElementForm, inIDElementAction, inAction) {
	//Set a value and submit a form (Useful for multiple-button forms)
	$(inIDElementAction).value = inAction;
	$(inIDElementForm).submit();
}

function disablebutton(inIDElement, inTextReplace) {
	if ($(inIDElement).type == "button") {
		//Handle input button
		$(inIDElement).value = inTextReplace;
		$(inIDElement).disabled = true;
		$(inIDElement).className = $(inIDElement).className+"-disabled";
	} else {
		//Handle a href buttons
		$(inIDElement).update(inTextReplace);
	}
}

function enablebutton(inIDElement, inTextReplace) {
	if ($(inIDElement).type == "button") {
		//Handle input button
		$(inIDElement).value = inTextReplace;
		$(inIDElement).disabled = false;
		$(inIDElement).className = $(inIDElement).className.substr(0, $(inIDElement).className.search("-disabled"));
	} else {
		//Handle a href buttons
		$(inIDElement).update(inTextReplace);
	}
}

function submitbuttondisable(inIDElementForm, inIDElementAction, inAction, inIDElementButton, inTextReplace) {	
	disablebutton(inIDElementButton, inTextReplace);
	submitbutton(inIDElementForm, inIDElementAction, inAction);
}

//Executes the submitbutton function when the user hits Enter
function submitbuttondisableEnter(inEvent, inIDElementForm, inIDElementAction, inAction, inIDElementButton, inTextReplace) {
	var keycode;
	
	if (window.event) {
		keycode = window.event.keyCode;
	} else if (inEvent) {
		keycode = inEvent.which;
	} else {
		return true;
	}

	if (keycode == 13) {
	   submitbuttondisable(inIDElementForm, inIDElementAction, inAction, inIDElementButton, inTextReplace);
	   
	   return false;
	} else {
	   return true;
	}
}
//End button functions

function buttonstatus(inIDButton, inTextReplace, inStatus) {
	$(inIDButton).disabled = !inStatus;
	$(inIDButton).value = inTextReplace;
}

function get_group_value(inIDElement) {
	//Get all element values
	var outElements = $$('input[id^="'+inIDElement+'"]:not(:disabled)');
	return outElements.pluck('value');
}

function get_group(inIDElement) {
	//Get all elements
	var outElements = $$('input[id^="'+inIDElement+'"]');
	return outElements;
}

function get_groupe(inIDElement, inElementType) {
	//Get all elements
	inElementType = typeof(inElementType) != "undefined" ? inElementType : "";
	var outElements = $$(inElementType+'[id^="'+inIDElement+'"]');
	return outElements;
}

function group_serialize_replace(inIDElement, inStringFind, inStringReplace) {
	var outSerializeString = "";
	var outSerialize = get_group(inIDElement).invoke('serialize').invoke("replace", inStringFind, inStringReplace);
	
	outSerialize.collect(function(inString) {
		outSerializeString = outSerializeString+"&"+inString;
	});
	
	return outSerializeString;
}

//Checkbox functions
function toggleCheck(inField) {
	inField.checked = !inField.checked;

	return true;
}

function getCheckedValue(inObject) {
	if (!inObject) {
		return "";
	}
	
	var radioLength = inObject.length;
	
	if (radioLength == undefined) {
		if (inObject.checked) {
			return inObject.value;
		} else {
			return "";
		}
	}
	
	for (var i = 0; i < radioLength; i++) {
		if (inObject[i].checked) {
			return inObject[i].value;
		}
	}
	
	return "";
}

function checkall(inField, inCheck) {
	if (inField.length != undefined) {
		for (var i = 0; i < inField.length; i++) {
			inField[i].checked = inCheck;
		}
	} else {
		inField.checked = inCheck;
	}
	return true;
}

function check_group(inIDElement, inStatus) {
	//Get all elements
	var outElements = $$('input[id^="'+inIDElement+'"]');
	outElements.invoke('writeAttribute', 'checked', inStatus);
}

function ischecked(inFormName, inField) {
	outField = eval("document.forms."+inFormName+"['"+inField+"']");
	outStatus = false;
	
	if (outField.length != undefined) {
		for (var i = 0; i < outField.length; i++) {
			if (outField[i].checked) {
				outStatus = true;
			}
		}
	} else {
		outStatus = outField.checked;
	}
	
	return outStatus;
}
//End checkbox functions

//End form functions

//Template functions

//Begin class switching functions
var g_classSwitcher = new Array(); //Store classes in this var for later use

function classChange(in_idelement, in_class) {
	g_classSwitcher[in_idelement] = $(in_idelement).className;
	$(in_idelement).className = in_class;
}

function classRestore(in_idelement) {
	$(in_idelement).className = g_classSwitcher[in_idelement];
}
//End class switching functions

function loadFormCSS() {
	for (i = 0; i < document.forms.length; i++) {
		for (j = 0; j < document.forms[i].elements.length; j++) {
			outElement = document.forms[i].elements[j];
			outType = outElement.type;
			outClass = outElement.className;

			if ((outType == "text" || outType == "password") && outClass == "text-default") {
				/*
				outElement.onfocus = function() {
					this.className = "text-default-selected";
				}

				outElement.onblur = function() {
					if (this.className == "text-default-selected") {
						this.className = "text-default";
					}
				}

				outElement.onmouseover = function() {
					if (this.className == "text-default") {
						this.className = "text-default-hover";
					}
				}
				outElement.onmouseout = function() {
					if (this.className == "text-default-hover") {
						this.className = "text-default";
					}
				}
				*/

				outElement.observe("focus", function(event){
					this.className = "text-default-selected";
				});
				
				outElement.observe("blur", function(event){
					if (this.className == "text-default-selected") {
						this.className = "text-default";
					}
				});

				outElement.observe("mouseover", function(event){
					if (this.className == "text-default") {
						this.className = "text-default-hover";
					}
				});
				
				outElement.observe("mouseout", function(event){
					if (this.className == "text-default-hover") {
						this.className = "text-default";
					}
				});
			} else if (outType == "textarea" && outClass == "textarea-default") {
				outElement.onfocus = function() {
					this.className = "textarea-default-selected";
				}
				outElement.onblur = function() {
					this.className = "textarea-default";
				}
				outElement.onmouseover = function() {
					if (this.className == "textarea-default") {
						this.className = "textarea-default-hover";
					}
				}
				outElement.onmouseout = function() {
					if (this.className == "textarea-default-hover") {
						this.className = "textarea-default";
					}
				}
			} else if (outType == "select-one" && outClass == "select-default") {
				outElement.onfocus = function() {
					this.className = "select-default-selected";
				}
				outElement.onblur = function() {
					if (this.className == "select-default-selected") {
						this.className = "select-default";
					}
				}
				outElement.onmouseover = function() {
					if (this.className == "select-default") {
						this.className = "select-default-hover";
					}
				}
				outElement.onmouseout = function() {
					if (this.className == "select-default-hover") {
						this.className = "select-default";
					}
				}
			}
		}
	}

	return true;
}

function toggleHideFancy(inTarget) {
	Effect.toggle(inTarget, "appear", {duration: 0.5});
}

function toggleSlide(inTarget) {
	Effect.toggle(inTarget, "slide", {duration: 0.5});
}

function toggleBlind(inTarget) {
	Effect.toggle(inTarget, "blind", {duration: 0.5});
}

function setHideSlide(inTarget, inStatus) {
	if (inStatus) {
		Effect.SlideDown(inTarget);
	} else {
		Effect.SlideUp(inTarget);
	}
}

function setCenter(inElement) {
	$(inElement).absolutize;
	$(inElement).setStyle({
		left: ((document.viewport.getWidth()/2) - ($(inElement).getWidth()/2) + document.viewport.getScrollOffsets()["left"])+'px',
		top: ((document.viewport.getHeight()/2) - ($(inElement).getHeight()/2) + document.viewport.getScrollOffsets()["top"])+'px'
	});
}

function setLoadingSmall(inIDElement, inString) {
	Element.update(inIDElement, "<div style=\"margin: 10px;\" class=\"loading-default\">"+inString+"</div>");
}

function setloading(in_idelement) {
	$(in_idelement).update("<div class=\"loading-center-large\">&nbsp;</div>");
}

//End template functions

//String functions
function alphanumericupper(inEvent, inElement) {
	outValue = inElement.value.replace(/[^a-zA-Z0-9]+/g,'');
	inElement.value = outValue.toUpperCase();
}

function alpha_dash(inString) {
	outValue = inString.replace(/[^a-zA-Z0-9\-]+/g,'-');
	outValue = outValue.toLowerCase();
	
	return outValue;
}

function setsearchenginelink(in_string, in_idelement) {
	if ($(in_idelement).value == "") {
		$(in_idelement).value = alpha_dash(in_string);
	}
}

function parseBool(inValue) {
	var outStatus = false;

	if (inValue.toString().toLowerCase() == "true" || inValue == true || parseInt(inValue) == 1) {
		outStatus = true;
	}
	
	return outStatus;
}

function parseBoolInt(inValue) {
	var outStatus = 0;

	if (parseBool(inValue)) {
		outStatus = 1;
	}
	
	return outStatus;
}

function trim(value) {
	return LTrim(RTrim(value));
}

function RTrim( value ) {
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}

function LTrim( value ) {
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}
//End string functions

//Account functions
function loginload(in_url) {
	var opt = {
		method: "get", 
		onSuccess: function(t) {
			if (parseBool(t.responseText)) {
				if (in_url != '') {
					window.location = in_url;
				} else {
					alert("You are now logged in.");
				}
			} else {
				//Show you are not logged in, please sign up, or log in window.
				setCenter("loginholder");
				toggleHideFancy("loginholder");
			}
		}
	}
	new Ajax.Request("/httprequest/user.php?type=loggedin", opt);
}

function loginfrompopup() {
	Element.update("loginstatus", "requesting your details ...");
	var opt = {
		method: "post", 
		onSuccess: function(t) {
			if (parseBool(t.responseText)) {
				Element.update("loginstatus", "Login Successful");
				alert("Successfully logged you in.");
				toggleHideFancy('loginholder');
			} else {
				Element.update("loginstatus", "Login Failed");
				alert("We could not retrieve your details. Please try again or use the forgotten password link.");
			}
		}
	}
	new Ajax.Request("/httprequest/login.php?task=login&email="+$F("email")+"&password="+$F("password")+"&persistlogin="+$F("persistlogin"), opt);
}
// End account functions

// Begin status bar functions
var statusbar_hide;
var statusbar_show;

function showStatusBar(in_status) {
	var out_idelement_bar = "StatusBar";
	var out_idelement_text = "StatusMessage";

	//Cancel existing transitions
	if (typeof(statusbar_hide) != "undefined") {
		statusbar_hide.cancel();
	}
	if (typeof(statusbar_show) != "undefined") {
		statusbar_show.cancel();
	}

	//Reset status bar
	$(out_idelement_bar).hide();

	//Show the status bar
	var statusbar_show = new Effect.Appear(out_idelement_bar, { duration: 0.5 });

	$(out_idelement_text).update(in_status);

	//Fade out after a second
	setTimeout('var statusbar_hide = new Effect.Fade("'+out_idelement_bar+'", { duration: 5.0 });', 1000);
	
	return true;
}
// End status bar functions

function loadhash (in_url, in_hash) {
	window.location = in_url+"#!"+in_hash;

	if (location.pathname == in_url) {
		window.location.reload (false);
	}
	
	return true;
}


var maximiseElementData = new Array();

function elementMaximise(in_idelement) {
	var out_element = $(in_idelement);
	
	maximiseElementData[in_idelement] = new Array();
	maximiseElementData[in_idelement]["width"] = out_element.style.width;
	maximiseElementData[in_idelement]["backgroundColor"] = out_element.style.backgroundColor;
	maximiseElementData[in_idelement]["borderBottom"] = out_element.style.borderBottom;
	maximiseElementData[in_idelement]["borderTop"] = out_element.style.borderTop;

	out_element.style.position = "absolute";
//	out_element.style.top = 0;
	out_element.style.left = 0;
	out_element.style.width = "100%";
	out_element.style.backgroundColor = "#ffffff";
	out_element.style.borderBottom = "3px solid black";
	out_element.style.borderTop = "3px solid black";
	out_element.setOpacity(0.9);
	
	$(in_idelement+"-max").hide();
	$(in_idelement+"-res").show();
}

function elementRestore(in_idelement) {
	var out_element = $(in_idelement);

	out_element.style.position = "relative";
	out_element.style.width = maximiseElementData[in_idelement]["width"];
	out_element.style.backgroundColor = maximiseElementData[in_idelement]["backgroundColor"];
	out_element.style.borderBottom = maximiseElementData[in_idelement]["borderBottom"];
	out_element.style.borderTop = maximiseElementData[in_idelement]["borderTop"];
	out_element.setOpacity(1);
	
	$(in_idelement+"-res").hide();
	$(in_idelement+"-max").show();
}

function createSelection(inIDElement, start, end){
	// get a reference to the input element
	var field = $(inIDElement);
	if( field.createTextRange ){
		var selRange = field.createTextRange();
		selRange.collapse(true);
		selRange.moveStart("character", start);
		selRange.moveEnd("character", end);
		selRange.select();
	} else if( field.setSelectionRange ){
		field.setSelectionRange(start, end);
	} else {
		if( field.selectionStart ){
			field.selectionStart = start;
			field.selectionEnd = end;
		}
	}
	field.focus();
};

//Autofill function for autocomplete fields
//Call using autoFill(event, this, "commentcategory-results");
function autoFill(event, in_object, id_element) {
	// if the last user key pressed was backspace, don't autofill
	if ($(id_element).firstChild != null && $(id_element).firstChild.childNodes[0] != undefined && event.keyCode != Event.KEY_BACKSPACE && event.keyCode != Event.KEY_SHIFT) {
		// fill in the value (keep the case the user has typed)
		//$input.val($input.val() + sValue.substring(prev.length));
		prev = in_object.value;
		firstentry = Element.collectTextNodes($(id_element).firstChild.childNodes[0]);
		
		if (prev.toLowerCase() == firstentry.toLowerCase().substring(0, prev.length)) {
			in_object.value = firstentry;
			// select the portion of the value not typed by the user (so the next character will erase)
			createSelection(in_object.id, prev.length, in_object.value.length);
		}
	}
}

String.prototype.formatMoney = function(c, d, t) {
	var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

