/**
 * Function reveals or hides the menu items on the menu bar 
 * 
 * @param integer n The index of the menu to be revealed
 */
function revemenu(n)
{
  	for( i=1; i<=6; i++ ) 
  	{
  		var menu_id = "men" + i;
  		var menu_object = document.getElementById(menu_id);
  		if ( null == menu_object )
  		{
  			continue;
  		}
  	
   		if (n != i) 
   		{
    		menu_object.style.visibility="hidden";
   		}
   		else 
   		{
   			menu_object.style.visibility="visible";
   		}
  	}
}

/**
 * Variables used in scrollText() - must be outside the function or will not work as 
 * function is recursive.
 */
var message = 	"Welcome to Chopper's Domain - the home of a hero among men^" +
          		"There are loads of sounds to listen to so turn your speakers on!^" +
          		"Check out all of Chopper's mates in Chopper's H.A.M.s^" +
          		"Behold the incredible limits of Chopper's stomach in Challenge Beaker^" +
          		"Want to know whether to approach a woman?  Visit the Moose Scale!^" +
          		"Theres some great links on the front page such as Ill Mitch and Super Greg!^" +
          		"Finally don't forget to pay your tribute to the great Igor Biscan^" +
          		"^";
var scrollSpeed = 25;
var lineDelay   = 1500;
var txt         = "";

/**
 * Recursively called function to control the scrolling text accross the bottom of the screen
 * 
 * @param integer pos The position in the message to continue the scrolling text
 */
function scrollText(pos) 
{
  	if (message.charAt(pos) != '^') 
  	{
    	txt    = txt + message.charAt(pos);
    	status = txt;
    	pause  = scrollSpeed;
  	}
  	else 
  	{
    	pause = lineDelay;
    	txt   = "";
    	if (pos == message.length-1) { pos = -1; }
  	}
  	pos++;
  	setTimeout("scrollText('"+pos+"')",pause);
}

/**
 * Function sets focus on a field specified by the field identifier passed in.
 * 
 * @param [String] fieldId The id of the field to set focus
 */
function setFocus(fieldId)
{
	document.getElementById(fieldId).focus();
}

/**
 * Function sets focus on the first field in the first form on the current screen.
 */
function setFocusFirstField(loggedin)
{
	try
	{
		var bFound = false;
		for ( f=0, fl=document.forms.length; f<fl; f++ )
		{
			if ( f == 0 && loggedin && fl > 1 )
			{
				// User is logged in, and there is more than 1 form on the screen
				// skip the first form which is the voting form.
				continue;
			}
			
			for ( i=0, il=document.forms[f].length; i<il; i++ )
			{
				if ( document.forms[f][i].type != "hidden" )
				{
					if ( document.forms[f][i].disabled != true )
					{
						document.forms[f][i].focus();
						var bFound = true;
					}
				}
				if (bFound == true)
				{
					break;
				}
			}
			if (bFound == true)
			{
				break;
			}
		}
	}
	catch(e)
	{
		// do nothing
	}
}

/**
 * Function validates the form for creating a football team
 * 
 * @param object form The form object
 * @param boolean admin indicates whether or not the form is on an admin page
 * @return boolean True if the form is valid else false
 */
function validatePlayers(form, admin)
{
    var blnOK = true;
    var posArr = new Array(form.gk.value,form.df1.value,form.df2.value,form.df3.value,form.df4.value,form.md1.value,form.md2.value,form.md3.value,form.md4.value,form.st2.value,form.st2.value);
    for( var i=0, l=posArr.length; i<l; i++ ) 
    {
        if ( posArr[i] == -1 ) 
        {
            blnOK = false;
            alert("You must select a player for every position");
            break;
        }
    }

    if ( blnOK && !validate("text", form.teamName, "team name") ) 
    {
		blnOK = false;
    }
    if ( admin && blnOK && !validate("text", form.teamPoints, "points total") ) 
    {
		blnOK = false;
    }

    return blnOK;
}

/**
 * Function validates changes made to a rodent in the admin page
 * 
 * @return boolean True if the form is valid else false
 */
function validateAdminRodent()
{
	var blnOK = true;
	rodentGenus = document.getElementById("rodentGenus");
	rodentSpecies = document.getElementById("rodentSpecies");
	rodentCommon = document.getElementById("rodentCommon");
	
	if ( !validate("text", rodentGenus, "Genus") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", rodentSpecies, "Species") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", rodentCommon, "Common Name") ) 
	{
		blnOK = false;
	}
	return blnOK;
}

/**
 * Check that for an animal fight, two DIFFERENT animals are selected
 * 
 * @param object form The form object to be validated
 * @return boolean True the two animals are different, else false
 */
function checkDuplicate(form)
{
    var anml1 = form.animal1.value;
    var anml2 = form.animal2.value;
    var noDup = true;

    if ( anml1 != " " && anml2 != " " )
    {
        if ( anml1 == anml2 )
        {
            alert("Please select two DIFFERENT animals, this fight would be a draw");
            noDup = false;
        }
    }
    return noDup;
}

/**
 * This function validates the new user sign up page.  Each field is validated and an 
 * appropriate message appears if not complete.
 * 
 * @param object form The form object to be validated
 * @return boolean True if the form is valid else false
 */
function validateSignup(form)
{
	var blnOK = true;

	if ( !validate("email", form.nw_email, "email address") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("password", new Array(form.nw_password1,form.nw_password2), "Password") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", form.nw_firstname, "first name") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", form.nw_surname, "surname") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", form.nw_job, "job title") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", form.nw_town, "home town") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("combo", form.nw_country, "country") ) 
	{
		blnOK = false;
	}
	
	return blnOK;
}

/**
 * This function validates the password request page, complaining if the form is not complete
 * 
 * @param object form The form object to be validated
 * @return boolean True if the form is valid else false
 */
function validatePassword(form)
{
	if ( !validate("email", form.lost_email, "email address") ) 
	{
		return false;
	}
	else if (form.lost_email.value.toLowerCase() == "chopper32uk@gmail.com")
	{
		alert("Sod off Whitey!");
		return false;
	}
	return true;
}

/**
 * This function validates the edit user details screen.  Appropriate pop-ups 
 * appear if the form is not completed.
 * 
 * @param object form The form object to be validated
 * @return boolean True if the form is valid else false
 */
function validateEdit(form)
{
	var blnOK = true;

	if ( !validate("text", form.ed_Opassword, "current password to make changes") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("email", form.ed_email, "Email Address") ) 
	{
		blnOK = false;
	}
	if ( !isblank(form.ed_Npassword1.value) || !isblank(form.ed_Npassword2.value) )
	{
		// Only validate if a new password has been entered.
		if ( blnOK && !validate("password", new Array(form.ed_Npassword1, form.ed_Npassword2), "Password") ) 
		{
			blnOK = false;
		}
	}
	if ( blnOK && !validate("text", form.ed_firstname, "first name") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", form.ed_surname, "surname") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", form.ed_job, "job title") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", form.ed_town, "home town") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("combo", form.ed_country, "country") ) 
	{
		blnOK = false;
	}
	
	return blnOK;
}

/**
 * Loops through all the checkboxes on the adminEmail page, selecting specific users to email,
 * and if none are selected, flags an error.
 * 
 * @param object form The form object to be validated
 * @return boolean True if the form is valid else false
 */
function validateEmail(form)
{
	if ( !validate("checkboxlist", form["EmailArr[]"], "at least one user to email") ) 
	{
		return false;
	}
	return true;
}

/**
 * This function ensures that an option has been selected in a list of radio buttons
 * NOTE - relies on form ONLY containing 1 radio button set followed by a submit.
 * 
 * @param object form The form object to be validated
 * @return boolean True if the form is valid else false
 */
function validateRadioButtons(form)
{
	var i;
	var selected = false;
	for ( i=0, l=form.length; i<(l-1); i++ )
	{
		if ( form.elements[i].checked )
		{
			selected = true;
			break;
		}
	}
	if ( !selected )
	{
		alert("Sorry, you must select ONE of the options");
		return false;	
	}
	return true;	
}

/**
 * This function checks that in an Animal Fight animal drop down, a valid animal is selected
 * 
 * @param object form The form object to be validated
 * @return boolean True if the form is valid else false
 */
function validateAnimalSelect(form)
{
	if ( !validate("combo", form.animal.value, "animal") ) 
	{
		return false;
	}	
	return true;
}

/**
 * This function validates the details of an animal details screen, making sure there are no
 * blank fields.
 * 
 * @param object form The form object to be validated
 * @return boolean True if the form is valid else false
 */
function validateAnimalDetails1(form)
{
	var blnOK = true;
	if ( !validate("text", form.nw_animal, "animal name") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", form.nw_comment, "animal victory comment") ) 
	{
		blnOK = false;
	}
	return blnOK;
}

/**
 * This function validates the details of an animal details screen, making sure there are no
 * blank fields.
 * 
 * @param object form The form object to be validated
 * @return boolean True if the form is valid else false
 */
function validateAnimalDetails2(form)
{
	var blnOK = true;
	if ( !validate("text", form.ed_animal, "animal name") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", form.ed_comment, "animal victory comment") ) 
	{
		blnOK = false;
	}
	return blnOK;
}

/**
 * This function validates the edit user details screen.  Appropriate pop-ups appear 
 * if the form is not completed.
 * 
 * @param object form The form object to be validated
 * @return boolean True if the form is valid else false
 */
function validateAdminEdit(form)
{
	var blnOK = true;

	if ( !validate("email", form.ed_email, "email address") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", form.ed_firstname, "first name") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", form.ed_surname, "surname") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", form.ed_job, "job title") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", form.ed_town, "home town") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("combo", form.ed_country, "country") ) 
	{
		blnOK = false;
	}
	
	return blnOK;
}

/**
 * This function makes sure that a non-blank challenge beaker form has been submitted.
 * 
 * @param object form The form object to be validated
 * @return boolean True if the form is valid else false
 */
function validateChallenge(form)
{
	var blnOK = true;
	if ( !validate("text", form.suggestion, "challenge") ) 
	{
		blnOK = false;
	}	
	return blnOK;
}

/**
 * This function ensures a blank email form is not sent
 * 
 * @param object form The form object to be validated
 * @return boolean True if the form is valid else false
 */
function validateEmailForm(form)
{
	var blnOK = true;
	if ( !validate("text", form.emailMsg, "email message") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", form.emailSubject, "email subject") ) 
	{
		blnOK = false;
	}	
	return blnOK;
}

/**
 * Validates the delete wedding gift(s) form
 * 
 * @param object form The form object to be validated
 * @return boolean True if the form is valid else false
 */
function validateDeleteWeddingGiftsForm(form)
{
	if ( !validate("checkboxlist", form["giftDeleteChoice[]"], "at least one gift to delete") ) 
	{
		return false;
	}
	return true;
}

/**
 * Validates the wedding gift form for updating or adding gifts
 * 
 * @param object form The form object to be validated
 * @return boolean True if the form is valid else false
 */
function validateWeddingGiftForm(form)
{
	var blnOK = true;
	if ( !validate("text", form.Gift_Name, "Gift Name") ) 
	{
		blnOK = false;
	}
	if ( blnOK && !validate("text", form.Gift_Store, "Store") ) 
	{
		blnOK = false;
	}
	return blnOK;
}

/**
 * Validates the select wedding gift for update form
 * 
 * @param object form The form object to be validated
 * @return boolean True if the form is valid else false
 */
function validateSelectUpdateGiftForm(form)
{
	if ( !validate("combo", form.updateFormOption, "Gift") ) 
	{
		return false;
	}
	return true;
}

/**
 * Validates the delete wedding song suggestion(s) form
 * 
 * @param object form The form object to be validated
 * @return boolean True if the form is valid else false
 */
function validateDeleteWeddingSongForm(form)
{
	if ( !validate("checkboxlist", form["songDeleteChoice[]"], "at least one song to delete") ) 
	{
		return false;
	}
	return true;
}

/**
 * Generic field validation function.  If invalid an alert is displayed and the 
 * invalid field is given a red border.  The field types to be validated are:
 * email, password, text, combo and checkboxlist.
 * 
 * @param string type The type of the field to be validated
 * @param object element The element object to be validated
 * @param string fieldName The name of the field to be displayed in the alert
 * @return boolean True if the form is valid else false
 */
function validate(type, element, fieldName)
{
	var blnOK = true;
	
	switch (type)
	{
		case "email" :
		// Ensures an email address is not blank and in the correct format
			if ( isblank(element.value) ) 
			{
				alert("You must enter an email address");
				element.className = "invalid";
				blnOK = false;
				break;
			}
			
			if ( 0 != element.value.search(/^([a-z0-9][a-z0-9\._-]*[a-z0-9]@[a-z0-9][a-z0-9\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z])$/i) ) 
			{
				alert("The email address entered is not in the correct format.  Please try again.");
				element.className = "invalid";
				blnOK = false;
				break;
			} 
			
			element.value = trim(element.value);
			element.className = "normal";
			break;
			
		case "password" :
			// Ensures two identical passwords have been entered
			if ( isblank(element[0].value) || isblank(element[1].value) ) 
			{
				alert("You must enter a password twice");
				element[0].className = "invalid";
				element[1].className = "invalid";
				blnOK = false;
				break;		
			}
			
			if ( element[0].value != element[1].value ) 
			{
				alert("The two passwords you entered are not identical.  Please try again");
				element[0].value = "";
				element[1].value = "";
				element[0].className = "invalid";
				element[1].className = "invalid";
				blnOK = false;
				break;
			}
	
			element[0].className = "normal";
			element[1].className = "normal";		
			break;
			
		case "text" :
			// Ensures a text field is not blank
			if ( isblank(element.value) ) 
			{
				alert("You must enter a valid " + fieldName);
				element.className = "invalid";
				blnOK = false;
				break;
			}
			
			element.value = trim(element.value);
			element.className = "normal";
			break;
			
		case "combo" :
			// Ensures a value is selected from the dropdown
			if ( element.value == " " ) 
			{
				alert("You must select a " + fieldName + " from the list");
				element.className = "invalid";
				blnOK = false;
				break;
			}
			
			element.className = "normal";
			break;
			
		case "checkboxlist" :
			// Ensures at least one checkbox in the list is checked
			if ( null == element.length )
			{
				var selected = element.checked;
			}
			else
			{
				var selected = false;
				for ( var i=0, l=element.length; i<l; i++ ) 
				{
					if (element[i].checked) 
					{
						selected = true;
						break;
					}
				}
			}
			if (!selected) 
			{
				alert("Sorry, you must select " + fieldName);
				return false;
			}	
	}
	
	if ( !blnOK )
	{
		// Set focus on the invalid field
		if ( type == "password" )
		{
			element[0].focus();
		}
		else
		{
			element.focus();
		}
	}
	return blnOK;
}

/**
 * Function displays the div with the Id passed in
 * 
 * @param string d The identifier of the div to be displayed
 */
function showDiv(d)
{
    document.getElementById(d).style.display = "block";
}

/**
 * Function hides the div with the Id passed in
 * 
 * @param string d The identifier of the div to be hidden
 */
function hideDiv(d)
{
    document.getElementById(d).style.display = "none";
}

/**
 * Disables a specified field
 * 
 * @param string f The identifier of the field to be disabled
 */
function disableField(f)
{
    document.getElementById(f).disabled = true;
}

/**
 * Enables a specified field
 * 
 * @param string f The identifier of the field to be enabled
 */
function enableField(f)
{
    document.getElementById(f).disabled = false;
}

/**
 * Function returns true if a field value is blank
 * 
 * @param string s The string to be tested
 * @return boolean True if the string is blank else false
 */
function isblank(s)
{
	var tempStr = trim(s);
    if ( tempStr.length == 0 || s == null ) 
    {
        return true;
    }
    return false;
}

/**
 * Function will check or uncheck all checkboxes within the form specified
 * 
 * @param string formName The name of the form to search for checkboxes
 * @param boolean checked True if all checkboxes are to be checked or false if unchecked
 */
function checkAllOnForm(formName, checked)
{
	var formElement = document.forms[formName];
	for( i=0, l=formElement.length; i<l; i++ )
	{
    	if( formElement[i].type == 'checkbox' )
    	{
	  		formElement[i].checked = checked;
	  	}
	}
}

/**
 * Used by adminFooty.php to allow a child window to update a field value in the parent window
 * 
 * @param string f The identifier of the field to be written to
 * @param string val The value to be written to the field
 */
function setParentFieldValue(f, val)
{
    document.getElementById(f).value = val;
}

/**
 * Function trims the leading and trailing spaces from a string
 * 
 * @param string strText The string to be trimmed
 * @return string The 'trimmed' string
 */
function trim(strText) 
{ 
    // this will get rid of leading spaces 
    while (strText.substring(0,1) == ' ') 
    {
        strText = strText.substring(1, strText.length);
    }

    // this will get rid of trailing spaces 
    while (strText.substring(strText.length-1,strText.length) == ' ')
    {
        strText = strText.substring(0, strText.length-1);
	}
   	return strText;
}

/******* IFRAME FUNCTIONS **********/

/**
 * Handler function for registering a user as being logged in
 */
function loggedInUserHandler() {};

/**
 * Function unregisters a user from being logged in to a state of logged out
 * 
 * @param [String] verifyId The verification Id for the AJAX call
 * @param [Integer] id The user id
 * @param [String] root The path back to the root directory
 */
loggedInUserHandler.unset = function(verifyId, id, root)
{
	if ( root == "" )
	{
		root = "./";
	}
	
	var xmlString = "<Users><User><Id>" + id + "</Id></User></Users>";
	Parameters.initialise();
	Parameters.addParameter("xmlString", xmlString);
	Parameters.addParameter("verifyId", verifyId);
	Services.callService(root, "deleteLoggedInUser", loggedInUserHandler);
}

/**
 * Onsuccess function for handling a request from the loggedInUserHandler
 */
loggedInUserHandler.onSuccess = function()
{
	var result = Services.getRequestXML();
	if (null != result)
	{
		Utils.setCursorDefault();
	}
}

/**
 * Function handles the opening/closing of the logged in user list iframe
 */
function handleIframeClick(root)
{
	if ( iframeObject.raised == true )
	{
		iframeObject.closeIframe();
	}
	else
	{
		iframeObject.openIframe(root);
	}
}

/**
 * Object representing the logged in user list iframe
 */
function iframeObject() {};
iframeObject.raised = false;

/**
 * Function to launch the iFrame
 */
iframeObject.openIframe = function(root)
{
	var myButton = document.getElementById("loggedinButton");
	var myDiv = document.getElementById("myIframe");
	myDiv.style.display = "block";
	myDiv.style.left = "140px";
	myDiv.style.top = (myButton.offsetTop + 25) + "px";
	myDiv.innerHTML = "<iframe name=\"userIframe\" src=\"" + root + "iframe.php\" width=\"100%\" height=\"100%\" frameborder=\"1\" scrolling=\"0\" allowtransparency=\"false\"></iframe>";
	this.raised = true;
	myButton.value = "Hide Users";
}

/**
 * Function to close the iFrame
 */
iframeObject.closeIframe = function()
{
	var myDiv = document.getElementById("myIframe");
	myDiv.style.display = "none";
	myDiv.innerHTML = "";
	this.raised = false;
	document.getElementById("loggedinButton").value = "Show Users";
}