var league_lab_global_cache = {};

function extractID(idString){
	var working = idString;
	while(working.indexOf("_") != -1){
		working = working.substr(working.indexOf("_") + 1);
	}
	if(!isNaN(working))
		working = parseInt(working);
	return working;
}

function indexOf(value,arrayThing){
	for(var index in arrayThing){
		if(arrayThing[index] == value)
			return index;
	}
	return -1;
}

function refreshPage ()
{
	var page = new String(location.href);
	if (page.indexOf('#') != -1)
	{
		page = page.substr(0,page.lastIndexOf('#'));
		location.href = page;
	}
	else
	{
		location.reload (true);
	}
}

function getPixels(att)
{
	var working = "";
	var digits = "-0123456789";
	sAttribute = new String(att);
	
	for (var i = 0; i < sAttribute.length; i++)
	{
		if(sAttribute.charAt(i) == " ")
		{
			continue;
		}
		if (digits.indexOf(sAttribute.charAt(i)) == -1)
		{
			break;
		}
		else
		{
			working = working + sAttribute.charAt(i);
		}
	}
	return parseInt(working);
}

/*
	speed is in milliseconds. leave it off to make it instant
*/
function show(jQueryObject,speed){
	if(speed == undefined){
		jQueryObject.show();
	}else{
		jQueryObject.slideDown(speed);
	}
}

function hide(jQueryObject,speed){
	if(speed == undefined){
		jQueryObject.hide();
	}else{
		jQueryObject.slideUp(speed);
	}
}

function toggleView(jQueryObject,speed){
	if(speed == undefined){
		jQueryObject.toggle();
	}else{
		jQueryObject.toggle(speed);
	}
}

function showPopup (link, jQueryPopup)
{
	var x = $(link).offset().left - 400;
	var y = $(link).offset().top - 300;
	show (jQueryPopup.css("left",x).css("top",y));
}

function getFormToken()
{
	var element = document.getElementById("formToken");
	if(element)
	{
		return {
			"Name":$(element).attr("name"),
			"Value":$(element).attr("value")
		}
	}
	return {
		"Name":"",
		"Value":""
	}
}

function setTokenValue (data)
{
	var token = getFormToken();
	data[token["Name"]] = token["Value"];
}

//	trim strings natively
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

//	format a date in std form
Date.prototype.format = function()
{
	return (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear();
}

//	center an element
//	sRelativeTo is a jQ selector for the element inside which the object is positioned
jQuery.fn.center = function (sRelativeTo) {
	var win = $(window);
	var y = (win.height () - this.outerHeight ()) / 2;
	var x = (win.width () - this.outerWidth ()) / 2;
	
	if (sRelativeTo)
	{
		var offset = $(sRelativeTo).offset ();
		x = x - offset.left;
		y = y - offset.top;
	}
    this.css("position","absolute");
    this.css("top", y + win.scrollTop() + "px");
    this.css("left", x + win.scrollLeft() + "px");
    return this;
}


//	get the correct control type of an element
function getControlType (element)
{
	var tagname = '';
	$(element).each (
		function ()
		{
			tagname = this.tagName;
		}
	);
	
	if (tagname.toLowerCase() == 'select')
	{
		return 'select';
	}
	if ($(element).attr("type") == 'radio')
	{
		return 'radio';
	}
	
	return 'text';
}
//	generic functions for showing that a control is in progress, done being updated, or an error has occurred
	function controlInProgress (element)
	{
		switch (getControlType (element))
		{
			case 'select':
				selectInProgress (element);
				break;
			case 'radio':
				radioInProgress (element);
				break;
			case 'text':
				textInProgress (element);
				break;
		}
	}

	function controlFinished (element)
	{
		switch (getControlType (element))
		{
			case 'select':
				selectFinished (element);
				break;
			case 'radio':
				radioFinished (element);
				break;
			case 'text':
				textFinished (element);
				break;
		}	
	}
	
	function controlError (element)
	{
		switch (getControlType (element))
		{
			case 'select':
				selectError (element);
				break;
			case 'radio':
				radioError (element);
				break;
			case 'text':
				textError (element);
				break;
		}
	}

//	specific functions for control status of SELECT elements
	function selectInProgress (element)
	{
		$(element).append('<option value="__UPDATING__">...Updating...</option>');
		$(element).css({'color':'','background-color':''}).removeClass("error").addClass("updating");
		setSelectValue(element,"__UPDATING__");
	}

	function selectFinished (element)
	{
		$(element).children().remove("[value=__UPDATING__]");
		$(element).removeClass("updating").removeClass("error");
	}
	
	function selectError (element)
	{
		$(element).children().remove("[value=__UPDATING__]");
		$(element).removeClass("updating").addClass("error");
	}

//	specific functions for control status of TEXT INPUTS
	function textInProgress (element)
	{
		$(element).attr("value","...Updating...").css({'color':'','background-color':''}).removeClass("error").addClass("updating");
	}
	function textFinished (element)
	{
		$(element).removeClass("updating").removeClass("error");
	}
	function textError (element)
	{
		$(element).removeClass("updating").addClass("error");
	}
	
//	specific functions for control status of RADIO INPUTS	
	function radioInProgress (element)
	{
		getRadioStatusBox(element).html("...Updating...").css({'color':'','background-color':''}).removeClass("error").addClass("updating");
	}
	function radioFinished (element)
	{
		getRadioStatusBox(element).html("").removeClass("updating").removeClass("error");
	}
	function radioError (element)
	{
		getRadioStatusBox(element).html("...Error...").removeClass("updating").addClass("error");
	}
	function getRadioStatusBox (element)
	{
		return $(element).parent().children(".radioStatus").eq(0);
	}

//	getting and setting the values of different types of controls
	function setControlValue (element,value)
	{
		switch (getControlType (element))
		{
			case 'select':
				setSelectValue (element,value);
				break;
			case 'radio':
				setRadioValue (element,value);
				break;
			case 'text':
				setTextValue (element,value);
				break;
		}
	}
	function getControlValue (element)
	{
		switch (getControlType (element))
		{
			case 'select':
				return getSelectValue (element);
				break;
			case 'radio':
				return getRadioValue (element);
				break;
			case 'text':
				return getTextValue (element);
				break;
		}	
	}
	
//	specific get/set operations for SELECT boxes	
	function setSelectValue (element,value)
	{
		$(element).children().each(
			function ()
			{
				if ($(this).attr("value") == value || $(this).html() == value)
				{
					$(this).attr("selected","selected");
				}
				else
				{
					$(this).attr("selected","");
				}
			}
		);
	}
	function getSelectValue (element)
	{
		return $(element).children(":selected").attr("value");
	}

//	sepecific setters and getters for TEXT INPUTS
	function setTextValue (element,newVal)
	{
		$(element).attr("value",newVal);
	}
	function getTextValue (element)
	{
		return $(element).attr("value");
	}

//	setters and getters for RADIO INPUTS
	function setRadioValue (radio,newValue)
	{
		var jqMatch = cacheGetJQ ("input[name=" + $(radio).attr("name") + "]");
		jqMatch.each(
			function ()
			{
				$(this).attr("checked",($(this).attr("value") == newValue));
			}
		);
	}
	function getRadioValue (radio)
	{
		var val = $("input[name='" + $(radio).attr("name") + "']:checked").attr("value");
		if (val == undefined)
		{
			val = "";
		}
		return val;
	}
	
//	apply color codes to select boxes depending on what's selected
function selectColor (element)
{
	var color = '#000';
	var background = '#fff';
	switch ($(element).children(":selected").attr("value"))
	{
		case 'Incomplete':
		case 'PendingInvitation':
			color = '#555';
			background = '#eee';
			break;
		case 'Confirmed':
		case 'Accepted':
			color = "#070";
			break;
		case 'Cancelled':
		case 'Declined':
			color = "#ccc";
			break;
		case 'Offered':
		case 'Invited':
			color = "#007";
			break;				
		case 'Waitlist':
		case 'Not Offered':
			color = "#a30";
			break;
	}
	$(element).css({
		"color":color,
		"background-color":background
	});
}

/*
*	make an ajax call to 'postAddress' contianing 'postData'. The response is either ERROR, or
*	the new contents of the select box 'element'.
*/
function refillSelectBox (element,postAddress, postData, callback)
{
	selectInProgress (element);
	$.post(postAddress,postData,function(response,status)
	{
		if(status == "success" && response != "ERROR")
		{
			$(element).html(response);
			selectFinished (element);
			if (callback != undefined)
			{
				callback();
			}
		}
		else
		{
			refreshPage ();
			//selectError (element);
		}
	},"text");
}

/*
*	disable all controls inside the container(s) matching the selector, and make the container itself look disabled
*
*	NOTE: [selector] cannot be comma-separated becuase of the way it's concatenated
*/
function disable(selector)
{
	var wholeSelect = selector + " input," + selector + " select," + selector + " textarea";
	var jqSet = cacheGetJQ (wholeSelect);
	jqSet.attr("disabled",true).addClass("disabled");
	
	jqSet = cacheGetJQ (selector);
	jqSet.addClass("disabled").attr("disabled",true);
}

/*
*	enable all controls inside the container(s) matching the selector, and remove the disabled appearance from the container
*
*	NOTE: [selector] cannot be comma-separated becuase of the way it's concatenated
*/
function enable (selector)
{
	var wholeSelect = selector + " input," + selector + " select," + selector + " textarea";
	var jqSet = cacheGetJQ (wholeSelect);
	jqSet.removeAttr("disabled").removeClass("disabled");
	
	jqSet = cacheGetJQ (selector);
	jqSet.removeClass("disabled").removeAttr("disabled");
}

/*
*	retrieve a value from the global js cache
*/
function cacheGet (key)
{
	if (league_lab_global_cache[key])
	{
		return league_lab_global_cache[key];
	}
	else
	{
		return null;
	}
}
/*
*	retrieve a value from the global js cache. if not found, get the jquery set
*	that corresponds to the selector given by key
*/
function cacheGetJQ (key)
{
	var jqMatch = cacheGet(key);
	if (jqMatch == null)
	{
		jqMatch = $(key);
		cacheSet (key, jqMatch);
		//console.log ("!!! cache miss for " + key);
	}
	//else
	//{
	//	console.log ("   cache HIT for " + key);
	//}
	return jqMatch;
}

/*
*	set a value in the global cache
*/
function cacheSet (key, value)
{
	league_lab_global_cache[key] = value;
}
