/**
 * @fileoverview scripts/common.js
 * @author Chris Vincent
 * 
 * Repository for commonly used JavsScript utility functions.
 */
 
/***********************************************************************/

/**
 * 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()
{
	try
	{
		var bFound = false;
		for ( f=0, fl=document.forms.length; f<fl; f++ )
		{
			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 logging into the admin section of the site.
 * Both a username and a password must be specified.
 * 
 * @param object form The form object
 * @return boolean true if the form is valid else false
 */
function validateLoginForm(form)
{
    var blnOK = true;
    if ( !validate("text", form.loginusername, "Username") ) 
    {
		blnOK = false;
    }
    if ( blnOK && !validate("text", form.loginpassword, "Password") ) 
    {
		blnOK = false;
    }

    return blnOK;
}

/***********************************************************************/

/**
 * 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, calendar 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;
			}
			
		case "calendar" :
			// Ensures a date field is in the correct format and is a valid date
			if ( isblank(element.value) ) 
			{
				alert("You must complete a " + fieldName);
				element.className = "invalid";
				blnOK = false;
				break;
			}
			else if ( !check_date(element) )
			{
				alert("You must enter a valid " + fieldName + " in the format DD/MM/YYYY");
				element.className = "invalid";
				blnOK = false;
				break;
			}
			
			element.value = trim(element.value);
			element.className = "normal";
			break;
			
		case "whitespace" :
			// Ensures a field value does not contain whitespace
			if ( -1 != element.value.indexOf(" ") ) 
			{
				alert(fieldName + " cannot contain spaces.");
				element.className = "invalid";
				blnOK = false;
				break;
			}
			
			element.value = trim(element.value);
			element.className = "normal";
			break;
			
		case "file" :
			// 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.className = "normal";
			break;
	}
	
	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 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;
}

/***********************************************************************/

/**
 * Loads the google map for the club
 * 
 * @param string pLat Latitude
 * @param string pLong Longitude
 */
function loadClubMap(pLat, pLong) 
{
	if (GBrowserIsCompatible()) 
	{
    	var map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(pLat, pLong), 14);
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		var marker = new GMarker(new GLatLng(pLat, pLong));
		map.addOverlay(marker);
  	}
}

/***********************************************************************/

/**
 * Checks a date entered is in the correct format
 * 
 * @param Object field Field object containing the date
 * @return Boolean True if the date is ok, else false 
 */
function check_date(field)
{
	var blnOk = true;
	var checkstr = "0123456789";
	var DateField = field;
	var Datevalue = "";
	var DateTemp = "";
	var seperator = "/";
	var day;
	var month;
	var year;
	var leap = 0;
	var err = 0;
	var i;
	err = 0;
	DateValue = DateField.value;
	/* Delete all chars except 0..9 */
	for (i = 0; i < DateValue.length; i++) {
		if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
			DateTemp = DateTemp + DateValue.substr(i,1);
		}
	}
	DateValue = DateTemp;
	
	// Always change date to 8 digits - string
	if (DateValue.length == 6) {
		// if year is entered as 2-digit / always assume 20xx
		DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); 
	}
	
	if (DateValue.length != 8) {
		// year is wrong if year = 0000
		err = 19;
	}
	
	// Validation of year 
	year = DateValue.substr(4,4);
	if (year == 0) {
		err = 20;
	}
	// Validation of month
	month = DateValue.substr(2,2);
	if ((month < 1) || (month > 12)) {
		err = 21;
	}
	// Validation of day
	day = DateValue.substr(0,2);
	if (day < 1) {
		err = 22;
	}
	
	// Validation leap-year / february / day
	if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
		leap = 1;
	}
	if ((month == 2) && (leap == 1) && (day > 29)) {
		err = 23;
	}
	if ((month == 2) && (leap != 1) && (day > 28)) {
		err = 24;
	}
	
	// Validation of other months
	if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
		err = 25;
	}
	if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
		err = 26;
	}

	// if no error, write the completed date to Input-Field (e.g. 13.12.2001)
	if (err == 0) {
		DateField.value = day + seperator + month + seperator + year;
	}
	else {
		blnOk = false;
	}

	return blnOk;
}
