// Global variables
var selected_color = "#00ff00";
var unselected_color = "#ffffff";
var survivor_schedule_win;

/* =========================== Utility stuff, used everywhere =========================== */
function GetSelectValue(form_name, select_name)
{
	return(document.forms[form_name].elements[select_name].options[document.forms[form_name].elements[select_name].selectedIndex].value);
}

function SelectValue(select)
{
	return(select.options[select.selectedIndex].value);
}

function GetRadioValue(form_name, radio_name)
{
	var radio_array = document.forms[form_name].elements[radio_name];

	for(var i=0; i<radio_array.length; i++)
	{
		if(radio_array[i].checked == true)
			return(radio_array[i].value);
	}
	
	// Getting here means no radio button was checked
	return(null);
}

function HandleClickableText(element_name)
{
	var this_element = document.getElementById(element_name);
						
	if(this_element)		// Only do stuff if we have an element that corresponds to this id
	{
		if(this_element.type == "checkbox")
			this_element.checked = !(this_element.checked);
		else if(this_element.type == "radio")
			this_element.checked = true;
	}
}

function ValidEmail(email)
{
	if((email.indexOf("@") == -1) || (email.indexOf(".") == -1))
	{
		return(false);
	}
	
	return(true);
}

// We need a way to set attributes that works on all browsers - IE is dumb/etc
function SetAttribute(element, name, value)
{
	if(element.attributes.length > 0)			// This is probably IE, with its oodles of default elements
	{		
		var attribute_name = name.toLowerCase();
		
		if((element.attributes[0]) && (element.attributes[0].name))		// IE 6
		{
			for(var i=0; i<element.attributes.length; i++)
			{
				if(element.attributes[i].name.toLowerCase() == attribute_name)
				{
					element.attributes[i].value = value;
					return;
				}
			}
		}
		else															// IE 5.5 needs some really ugly stuff
		{
			if(attribute_name == "class")
			{
				element.className = value;	
			}
			else if(attribute_name == "rowspan")
			{
				element.rowSpan = value;
			}
			else if(attribute_name == "colspan")
			{
				element.colSpan = value;
			}
			else
			{
				element[name] = value;
			}

			return;
		}
	}
	
	// If we made it here, either we're one of the good guys (Firefox/Safari) or we don't have this attribute yet
	element.setAttribute(name, value);
}
/* ================================ End of utility stuff ================================ */

// /pools/grid.php
function OpenOutcomesWindow(entry_id)	
{
	var week = document.mainform.week.value;

	window.open("/pools/outcomes.php?e=" + entry_id + "&week=" + week, "outcomeswin_" + entry_id + "_" + week, "height=600,width=540,scrollbars=yes");
}

// /register/index.php
function CheckAccountForm(isForgotPW)
{
	var this_form = document.forms["mainform"];

	if(this_form.firstname.value == "")
	{
		this_form.firstname.focus();
		alert("You must enter a first name.");
		return(false);
	}
	else if(this_form.lastname.value == "")
	{
		this_form.lastname.focus();
		alert("You must enter a last name.");
		return(false);
	}
	else if(this_form.email.value == "")
	{
		this_form.email.focus();
		alert("You must enter a valid e-mail address.");
		return(false);
	}
	else if((GetRadioValue("mainform", "display_name_pref") == 2) && (this_form.elements["display_name"].value == ""))
	{
		this_form.display_name.focus();
		alert("If you choose \"Display Name\" in Name Preferences, then you cannot leave the Display Name field blank.");
		return(false);
	}
	
	if(isForgotPW == 1)		// Force them to enter a password
	{
		if(this_form.password1.value == "")
		{
			this_form.password1.focus();
			alert("You must update your password.");
			return(false);
		}
	}
	else if(this_form.password1.value != "")
	{
		if(this_form.password1.value != this_form.password2.value)
		{
			this_form.password1.focus();
			alert("Your passwords do not match.  Please try again.");
			return(false);
		}
	}
	
	return(true);
}

// /picks/pool.php
function HandleClick(team, game)
{
	if(document.mainform.elements["c" + team].checked == false)			// User un-checked something
	{
		// Uncheck our currently-selected team
		document.getElementById("name" + team).style.background = unselected_color;
		
		// Wipe out our hidden form entry
		document.mainform.elements["game" + game].value = "";
	}
	else
	{
		// Uncheck the other team, if necessary
		document.mainform.elements["c" + games[team]].checked = false;
		
		// Un-color the other team
		document.getElementById("name" + games[team]).style.background = unselected_color;
		
		// Finally, color our new choice
		document.getElementById("name" + team).style.background = selected_color;
		
		// And store the value they selected in our hidden form field
		document.mainform.elements["game" + game].value = team;
	}
}

// /pools/player.php
function ChangePlayerName()
{
	window.location.href = "/pools/players/" + GetSelectValue("mainform", "user");
}

// /pools/player.php
function ChangePlayerYear()
{
	window.location.href = "/pools/players/" + GetSelectValue("mainform", "year");
}

// /teams/team.php
function ChangeTeamYearSpread(teamid)
{
	var year = GetSelectValue("mainform", "year");
	
	if(year != 0)
		window.location.href = "/teams/" + teamid + "/" + year;
	else
		window.location.href = "/teams/" + teamid + "/all";
}

// /teams/index.php
function CheckHeadToHead()
{
	var team1 = SelectValue(document.getElementById("team1"));
	var team2 = SelectValue(document.getElementById("team2"));
	
	if((team1 == 0) || (team2 == 0))
		return(false);
	else if(team1 == team2)
	{
		alert("You can't pick the same team twice.");
		return(false);
	}
		
	// If we made it here, we're good to go
	window.location.href = "/teams/" + team1 + "/vs/" + team2;
}

// /schedule/index.php
function ChangeSchedule()
{
	var newWeek = GetSelectValue("mainform", "week");
	
	if(newWeek != 99)		// 99 is playoffs
		window.location.href = "/schedule/" + newWeek + "/" + GetSelectValue("mainform", "year");
	else
		window.location.href = "/schedule/playoffs/" + GetSelectValue("mainform", "year");
}

// /standings/index.php
function ChangeStandings()
{
	window.location.href = "/standings/" + document.mainform.week.options[document.mainform.week.selectedIndex].value + "/" + document.mainform.year.options[document.mainform.year.selectedIndex].value;
}

// /picks/picks_pickem.php
function ChangePicks(from)
{
	var entryid;

	if((from == 2) && (document.forms["mainform"].elements["entry"]))
		entryid = GetSelectValue("mainform", "entry");
	else
		entryid = GetSelectValue("mainform", "year");
		
	window.location.href = "/picks/" + entryid + "/" + GetSelectValue("mainform", "week");
}

// /picks/picks_survivor.php
function ChangePicksSurvivorYear()
{
	window.location.href = "/picks/" + GetSelectValue("mainform", "year");
}

// /picks/picks_survivor.php
function ChangePicksSurvivorEntry()
{
	window.location.href = "/picks/" + GetSelectValue("mainform", "entry");
}

// /pools/pickem.php
function OpenGrid(poolid, year)
{
	var week = GetSelectValue("gridform", "week");
	var url = "/pools/" + poolid + "/" + year + "/grid/" + week;
	
	window.open(url, "gridwin_" + poolid + "_" + year + "_" + week);
}

// /picks/picks_pickem.php
function HandlePicksSubmit()
{
	var games_picked;
	var num_games;
	
	num_games = document.mainform.numgames.value;
	
	games_picked = 0;
	for(i=1; i<games.length; i++)
	{
		if(games[i])		// Only look at games that are defined
		{
			if((document.mainform.elements["c" + i].checked) && (!(document.mainform.elements["c" + i].disabled)))
				games_picked++;
		}
	}
	
	if(games_picked == (num_games - 1))
	{
		if(!(confirm("You have left only one game blank.\nAre you sure you want to do this?")))
			return(false);
	}
	else if((games_picked == num_games) && (document.mainform.totalpoints.value == ""))
	{
		if(!(confirm("You've picked all your games, but left the Total Points tiebreaker blank.\nAre you sure you want to do this?")))
		{
			document.mainform.totalpoints.focus();
			return(false);
		}
	}
	
	document.mainform.submitbutton.disabled = true;
	document.mainform.submitbutton.value = "Please Wait...";
	
	return(true);
}

// /pools/pool.php
function OpenPoolPlayer()
{
	var entry = GetSelectValue("playerform", "entry");
	
	if(entry == 0)
		return;
	
	window.open("/pools/players/" + entry, "entry_" + entry);
}

// /pools/grid_survivor.php
function OpenSurvivorGrid(poolid, year)
{
	window.open("/pools/" + poolid + "/" + year + "/grid", "survivor_grid_" + poolid + "_" + year);
}

// /pools/pool.php
function ChangePoolYear(poolid)
{
	window.location.href = "/pools/" + poolid + "/" + GetSelectValue("mainform", "year");	
}

// /pools/rankings.php
function ChangeRankings(poolid)
{
	window.location.href = "/pools/" + poolid + "/" + GetSelectValue("mainform", "year") + "/rankings/" + GetSelectValue("mainform", "week");
}

// /login/index.php
function CheckLoginForm(formname)
{
	var this_form = document.forms[formname];
	
	if(this_form.email.value == "")
	{
		this_form.email.focus();
		alert("You must enter your e-mail address in order to log in.");
		return(false);
	}
	
	if(this_form.password.value == "")
	{
		this_form.password.focus();
		alert("You must enter your password in order to log in.");
		return(false);
	}
	
	return(true);
}

// /picks/survivor.php
function CheckTeamChoice()
{
	if(document.mainform.pick.options[document.mainform.pick.selectedIndex].value == 0)
		return(false);
	
	return(true);
}

// /picks/survivor.php
function OpenSurvivorSchedule(entryid, picknum)
{
	survivor_schedule_win = window.open("/picks/survivor_schedule.php?e=" + entryid + "&picknum=" + picknum, "survivor_schedulewin_" + entryid, "height=664,width=600,scrollbars=yes,resizable=yes");
}

// /picks/survivor.php
function CloseSurvivorScheduleWindow(team, picknum)
{
	if(survivor_schedule_win)
		survivor_schedule_win.close();
	
	document.mainform.pick.value = team;
	document.mainform.picknum.value = picknum;
	document.mainform.submit();
}

// /picks/survivor_schedule.php
function HighlightSurvivorPick(team)
{
	if(selected_team != 0)		// This means we have a team to un-highlight
		document.getElementById("name" + selected_team).style.background = unselected_color;

	// Highlight our new selection
	document.getElementById("name" + team).style.background = selected_color;
	
	selected_team = team;
	
	// Make sure the button says the right thing
	document.mainform.submitbutton.value = "Save Pick";
}

// /news/index.php
function ChangeNewsYear()
{
	window.location.href = "/news/" + GetSelectValue("mainform", "year");
}

// /admin/roster.php
function CheckRosterForm()
{
	var action = GetSelectValue("mainform", "action");

	// If they didn't pick an action, just stop here
	if(action == 0)
		return(false);
	
	// Zoom through and get a count
	var checked_count = 0;
	for(var i=0; i<document.forms["mainform"].elements.length; i++)
	{
		if((document.forms["mainform"].elements[i].name.substring(0, 5) == "user_") && (document.forms["mainform"].elements[i].checked))
			checked_count++;
	}
	
	if(checked_count == 0)
	{
		alert("You have not selected any users.");
		return(false);
	}
	
	if(action == 5)	// Drop user from pool
	{	
		// Make sure they really want to do this
		var msg = "Are you sure you want to drop ";
		if(checked_count == 1)
			msg += "this user"
		else
			msg += "these " + checked_count + " users";
		msg += " from the pool?  This action cannot be undone.";
		
		if(!(confirm(msg)))
			return(false);
	}
	
	return(true);
}

// /admin/rebuys.php
function CheckRebuysForm()
{
	var action = GetSelectValue("mainform", "action");
	
	// If they didn't pick an action, just stop here
	if(action == 0)
		return(false);
	
	// Zoom through and get a count
	var checked_entries = [];
	var entry_id;
	for(var i=0; i<document.forms["mainform"].elements.length; i++)
	{
		if((document.forms["mainform"].elements[i].name.substring(0, 6) == "entry_") && (document.forms["mainform"].elements[i].checked))
		{				
			entry_id = (document.forms["mainform"].elements[i].name.match(/^entry_([0-9]+)$/))[1];
			checked_entries.push(entry_id);
		}
	}
	
	if(checked_entries.length == 0)
	{
		alert("You haven't selected any entries.");
		return(false);
	}
	
	if(action == 2)
	{
		var msg = 'Are you sure you want to take away a rebuy for ';
		msg += ((checked_entries.length == 1) ? 'this user' : 'these users');
		msg += '? This is effectively eliminating them from the pool.';
		
		if(!(confirm(msg)))
		{
			return false;
		}
	}
	
	return(true);
}

// /admin/picks.php
function AdminPicksChooseUser(pool_id)
{
	var entry_id = GetSelectValue("mainform", "entry");
	
	if(entry_id > 0)
		window.location.href = "/admin/" + pool_id + "/picks/" + entry_id;
}

function AdminPicksEditPick(pool_id, entry_id, weeknum, picknum)
{
	window.location.href = "/admin/" + pool_id + "/picks/" + entry_id + "/" + weeknum + "-" + picknum + "#edit";
}

function CheckPicksAdminForm()
{
	if(document.forms["mainform"].elements["newpick"])
	{	
		if(document.forms["mainform"].elements["newpick"].selectedIndex == 0)
			return(false);
	}
	
	return(true);
}

// /join/pool_xyz.php
function CheckSignupForm()
{
	var this_form = document.forms["signupform"];
	var email1 = this_form.elements["email1"].value;
	var email2 = this_form.elements["email2"].value;
	var first_name = this_form.elements["first_name"].value;
	var last_name = this_form.elements["last_name"].value;
	var pw = this_form.elements["password"].value;
	
	// We need to figure out which they're doing - new signup, or old login
	if((first_name != "") && (last_name != "") && (email1 != "") && (email2 == "") && (pw == ""))
	{
		// Must be a new signup
		if(!(ValidEmail(email1)))
		{
			alert("You have entered an invalid e-mail address.\nIt must be of the form \"user@domain.com\".\nPlease try again.");
			this_form.elements["email1"].focus();
			return(false);
		}
	}
	else if((first_name == "") && (last_name == "") && (email1 == "") && (email2 != "") && (pw != ""))
	{
		// Must be a login
		if(!(ValidEmail(email2)))
		{
			alert("You have entered an invalid e-mail address.\nIt must be of the form \"user@domain.com\".\nPlease try again.");
			this_form.elements["email2"].focus();
			return(false);
		}
	}
	else if((first_name == "") && (last_name == "") && (email1 == "") && (email2 == "") && (pw == ""))
	{
		// Everything's blank
		alert("You must either enter your name and e-mail address to sign up, or your e-mail and password from previous years.");
		return(false);
	}
	else if(((first_name != "") || (last_name != "") || (email1 != "")) && ((email2 == "") && (pw == "")))
	{
		// They're trying to sign up new
		if(first_name == "")
		{
			alert("You must enter your first name if you're new to the site.");
			this_form.elements["first_name"].focus();
			return(false);
		}
		else if(last_name == "")
		{
			alert("You must enter your last name if you're new to the site.");
			this_form.elements["last_name"].focus();
			return(false);
		}
		else if(email1 == "")
		{
			alert("You must enter your e-mail address if you're new to the site.");
			this_form.elements["email1"].focus();
			return(false);
		}
	}
	else if(((first_name == "") && (last_name == "") && (email1 == "")) && ((email2 != "") || (pw != "")))
	{
		// They're trying to log in
		if(email2 == "")
		{
			alert("You must enter your e-mail address if you're trying to log in.");
			this_form.elements["email2"].focus();
			return(false);
		}
		else if(pw == "")
		{
			alert("You must enter your password if you're trying to log in.");
			this_form.elements["password"].focus();
			return(false);
		}
	}
	else
	{
		// Don't know what they're trying to do
		alert("If you're new to the website, only fill in the first/last name and e-mail fields.\nIf you're a returning user, only fill in the e-mail and password fields.");
		return(false);
	}
	
	this_form.elements["submitbutton"].disabled = true;
	
	return(true);
}

function addCommas(num) {
    num += '';
    var parts = num.split('.');
    var part1 = parts[0];
    var part2 = (parts.length > 1) ? ('.' + parts[1]) : '';
        
    var regex = /(\d+)(\d{3})/;
    while (regex.test(part1)) {
        part1 = part1.replace(regex, '$1' + ',' + '$2');
    }
    
    return part1 + part2;
}

function getFloat(num) {
    num += '';
    num = num.replace(/,/, '');
    
    return parseFloat(num);
}

function htmlEntify(text) {
    text = text.replace(/"/g, '&quot;');
    text = text.replace(/</g, '&lt;');
    text = text.replace(/>/g, '&gt;');
    
    return text;
}


    