/*
 * Desc:	Custom JavaScript functions and variables used in the Community Trust Fund application
 * Author:	Graham Faulkner
 */

// global JavaScript variables used in the CTF application
var CTF_BASE_URL = "https://www.cccc.org/ctf/";
var BASE_URL = "http://www.cccc.org/"; 


// determine whether a particular form field is empty - if so make its background red
// and return an error value
function checkEmptyField(elem)
{
	if (!$F(elem)) // form field has no value i.e. getValue is null/empty
	{
		$(elem).setStyle( {backgroundColor: '#ffcccc'} );
		return 1;
	} else {
		$(elem).setStyle( {backgroundColor: '#ffffff'} );
		return 0;
	}
} /* end checkEmptyField() */



// determine whether a particular form field is a numeric value (int or float/decimal)
function checkNumericField(elemID)
{
	var number = $F(elemID);
	number = number.replace(/\,/g,''); // remove any commas from number
	if (isNaN(number) || !number || number <= 0 )
	{
		$(elemID).setStyle( {backgroundColor: '#ffcccc'} );
		return 1;
	} else {
		$(elemID).setStyle( {backgroundColor: '#ffffff'} );
		return 0;
	}
} /* end checkNumericField() */



// determine whether a particular form field is a numeric value in dollar format (int or float/decimal).
// http://regexlib.com/REDetails.aspx?regexp_id=196
function checkDollarField(elemID)
{
	var number = $F(elemID);
	result = /^\$?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(number.toString());
	if (result) {
		$(elemID).setStyle( {backgroundColor: '#ffffff'} );
		return 0;
	} else { // not a dollar format value
		$(elemID).setStyle( {backgroundColor: '#ffcccc'} );
		return 1;
	}
} /* end checkDollarField() */



// http://javascript.internet.com/forms/currency-format.html
function dollarFormat(num) 
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) {
		num = "0";
	}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10) {
		cents = "0" + cents;
	}	
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
		num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
	}	
	return (((sign)?'':'-') + '$' + num + '.' + cents);
} /* end dollarFormat() */



// highlight a certain form field or element, using the id value as parameter
function highlightElem(elem)
{
	$(elem).setStyle( {backgroundColor: '#ffcccc'} );
} /* end highlightElem() */


// the form submission function needs to check for radio button group names that
// are generated dynamically by the controller - therefore it is somewhat generic
// in its implementation
function checkRadioBtns(formID)
{
	var errors = 0;
		
	// get array of all radio group names
	var theForm = $(formID);
	var btnGroups = new Array();
	var prevName = "";
	var btns = theForm.getInputs('radio');
	btns.each(function(btn) {
			if (btn.name != prevName)
			{
				btnGroups.push(btn.name); 
			}
			prevName = btn.name;
		});
	
	// make sure there is at least one selection in each group
	// show warning if required
	for (i = 0; i < btnGroups.length; i++)
	{
		var numChecked = 0;
		
		// ******************************* IMPORTANT ******************************************
		// assumes there is an element (e.g. div) that is parent node of the radio button group
		// and has an ID value matching radio group's NAME
		var btnName = $(formID).select('[name="'+btnGroups[i]+'"]');
		
		// only perform check if the button group is set to visible
		if ($(btnGroups[i]).visible() == true)
		{
			for (j=0; j<btnName.length; j++) // see which one is selected in this category
			{
				if (btnName[j].checked)
				{
					numChecked++;	
				}
			}
			if (numChecked == 0) // they didn't make a selection in this category
			{
				errors++;
				$(btnGroups[i]).setStyle( {backgroundColor: '#ffcccc'} ); // highlight missing category
			} else {
				$(btnGroups[i]).setStyle( {backgroundColor: '#ffffff'} );
			}
		}
	}
	if (errors > 0)
	{
		alert("You need to make a selection in each radio button group, as indicated.");
		return false;
	} else {
		return true;	
	}	
} /* end checkRadioBtns() */



// the form submission function needs to check that each <select> has
// a valid selection value (i.e. none blank)
function checkDropDownLists(formID)
{
	var errors = 0;
	
	// get list of all form elements
	var allElem = $(formID).getElements();
	allElem.each(function(elem) {
			// if it is a visible (non-hidden) <select> tag, make sure it has a valid selection
			// otherwise highlight it and show error message
			if ( elem.type == "select-one" && elem.visible() )
			{
				if (elem.value == '')
				{		
					errors++;
					elem.setStyle( {backgroundColor: '#ffcccc'} ); // highlight missing category
				} else {
					elem.setStyle( {backgroundColor: '#ffffff'} );
				}
			} 
		});
	if (errors > 0)
	{
		alert("You need to make a selection for each drop down list.");
		return false;
	} else {
		return true;	
	}
} /* end checkDropDownLists() */


// get the list of all id values for <select>s in the respective form 
// select hidden lists based on boolen "inclHidden" parameter
function getDropDownLists(formID, inclHidden)
{
	var list = new Array();
	var allElem = $(formID).getElements();
	
	allElem.each(function(elem) {
		if (elem.type == "select-one")
		{
			if (inclHidden)
			{
				list.push(elem.id); 	// get ids of ALL lists
			} else {
				if (elem.visible())
				{
					list.push(elem.id); // get ids of only the visible lists
				}
			}
		} 
	});
	
	return list;
} /* end getDropDownLists() */


// uncheck all radio buttons with the specified "name" attribute
// taken from http://www.faqts.com/knowledge_base/view.phtml/aid/7199
function unCheckRadio(oRadio) 
{
	var or = document.getElementsByName(oRadio);
	for (var i = 0; i < or.length; i++) {
		or[i].checked = false;
	}
} /* end unCheckRadio() */


// uncheck all checkboxs with the specified "name" attribute
// adapted from http://www.faqts.com/knowledge_base/view.phtml/aid/7199
function unCheckCheckbox(oCheckbox) 
{
	var cbx = document.getElementsByName(oCheckbox);
	for (var i = 0; i < cbx.length; i++) {
		cbx[i].checked = false;
	}
} /* end unCheckCheckBox() */


// Turn the submit button on or off, depending on whether the user has checked 
// a checkbox. Used for "agree to disclaimer" type forms.
function toggleAgree()
{
	if ($('cbxAgree').checked == true)
	{
		$('btnSubmit').enable();	
	} else {
		$('btnSubmit').disable();	
	}
} /* end toggleAgree() */


// compare two text strings
function textMatches(str1, str2)
{
	if (str1 != str2)
	{
		return false;
	} else {
		return true;
	}
} /* end textMatches() */


// Validate phone number for 10 digit US numbers.
// phoneField - The HTML input field containing the phone number to validate.
// format - Integer value that defines how to format the text field.
// http://www.dynamicajax.com/fr/Validating_Phone_Numbers_With_JavaScript-.html
function validatePhone(phoneField, format) 
{	
	var error = 0;
	var num = phoneField.value.replace(/[^\d]/g,'');
	if(num.length != 10) {  
		error++;
	} else {		
		//Email was valid.  If format type is set, format the Phone to the desired style.
		switch(format) 
		{
		case 0: //Format (xxx)-xxx-xxxx
   			phoneField.value = "(" + num.substring(0,3) + ")-" + num.substring(3, 6) + "-" + num.substring(6);
   			break;
		case 1: //Format xxx-xxx-xxxx
   			phoneField.value = num.substring(0,3) + "-" + num.substring(3, 6) + "-" + num.substring(6);
   			break;
		default: //Format xxxxxxxxxx
   			phoneField.value = num;
   			break;
		} /* end switch */
	} /* end if */
	return error;
} /* end validatePhone() */


// custom email validation
// http://javascript.internet.com/forms/email-validation---basic.html
function validateEmail(addr) 
{
	var error = 0;
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(addr))
	{
		error = 0;
	} else {
		error++;	
	}
	return error;
} /* end validateEmail() */


// http://www.webdeveloper.com/forum/showthread.php?t=95583
function isValidPostalCode(postalcode)
{
	if (postalcode.length == 6 && postalcode.search(/^[a-zA-Z]\d[a-zA-Z]\d[a-zA-Z]\d$/) != -1) {
		return true;
	} else if (postalcode.length == 7 && postalcode.search(/^[a-zA-Z]\d[a-zA-Z](-|\s)\d[a-zA-Z]\d$/) != -1) {
		return true;
	} else {
		return false;
   	}
   	return true;
} /* end isValidPostalcode() */


// tests for valid person name - only alphabet characters, apostrophe and hyphen allowed
function isValidName(name)
{
	if (name.search(/^[a-zA-Z \'-]$/) != -1) {
		return true;
	} else {
		return false;
	}
} /* end isValidName() */


// http://stackoverflow.com/questions/136617/how-do-i-programatically-force-an-onchange-event-on-an-input
function fireEvent(element,event)
{	
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else {
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
} /* end fireEvent() */

