/******************************************************************************
Include file containing objects/functions used in contests.

MANIFEST
--------

	function checkForm(form):		Validate the standard contest entry form.
	function checkFormFR(form):		Same as above, with French error messages.
	function keyJump(textbox, targetID, length):
									Shift focus to another control once a 
									certain number of characters has been 
									entered into a textbox (assign to "onkeyup"
									event)	
	function getListIndex(selectList, value):
									Find the index of a value within a dropdown
									list									
Boolean tests:

	function isEmpty(string)
	function isValidLength(string, min, max)
	function isValidEmail(address)
	function isValidPostalcode(postalcode)
	function isNumeric(string, ignoreWhiteSpace)
	function isAlphanumeric(string, ignoreWhiteSpace)
	function isAlphabetic(string, ignoreWhiteSpace)
	function isWhitespace (string)
	function isRadioValue(ctlRadio)

Formatting functions:

	function removeBadCharacters(string)
	function removeSpaces(string)
	function trimWhitespace(string)

Image-swapping functions:

	function storeImage(passive_image, active_image)
	function swapImage(image)
	
******************************************************************************/

// whitespace characters
var whitespace = " \t\n\r";

/////////////////////////////////////////////////
// validate the standard competition form.
function checkForm(form) {

    var errors = 0;
    var isErrorRules = false
    var IsFocus = false;

	// First Name
	if (isEmpty(form.firstName.value)) {
	    if (IsFocus == false) {
	        form.firstName.focus();
	        IsFocus = true;
	    }
	    document.getElementById('errorFirstName').style.visibility = "visible";
	    errors += 1;
	}
	else {
	    document.getElementById('errorFirstName').style.visibility = "hidden";
	}

    // Last Name
	if (isEmpty(form.lastName.value)) {
	    if (IsFocus == false) {
	        form.lastName.focus();
	        IsFocus = true;
	    }
	    document.getElementById('errorLastName').style.visibility = "visible";
	    errors += 1;
	}
	else {
	    document.getElementById('errorLastName').style.visibility = "hidden";
	}
    
    // Address
	if (isEmpty(form.address.value)) {
	    if (IsFocus == false) {
	        form.address.focus();
	        IsFocus = true;
	    }
	    document.getElementById('errorAddress').style.visibility = "visible";
	    errors += 1;
	}
	else {
	    document.getElementById('errorAddress').style.visibility = "hidden";
	}

    // City
	if (isEmpty(form.city.value)) {
	    if (IsFocus == false) {
	        form.city.focus();
	        IsFocus = true;
	    }
	    document.getElementById('errorCity').style.visibility = "visible";
	    errors += 1;
	}
	else {
	    document.getElementById('errorCity').style.visibility = "hidden";
	}
    
    // Province
	if (isEmpty(form.province.value)) {
	    if (IsFocus == false) {
	        form.province.focus();
	        IsFocus = true;
	    }
	    document.getElementById('errorProvince').style.visibility = "visible";
	    errors += 1;
	}
	else {
	    document.getElementById('errorProvince').style.visibility = "hidden";
	}

	// Postal Code

	var PostalCode = form.postalCode1.value + form.postalCode2.value
	if (isValidPostalcode(PostalCode) == false) {
	    if (IsFocus == false) {
	        form.postalCode1.focus();
	        IsFocus = true;
	    }
	    document.getElementById('errorPostalCode').style.visibility = "visible";
	    errors += 1;
	}
	else {
	    document.getElementById('errorPostalCode').style.visibility = "hidden";
	}

	// Email
	if (isValidEmail(form.email.value) == false) {
	    if (IsFocus == false) {
	        form.email.focus();
	        IsFocus = true;
	    }
	    document.getElementById('errorEmail').style.visibility = "visible";
	    errors += 1;
	}
	else {
	    document.getElementById('errorEmail').style.visibility = "hidden";
	}
    
    // Telephone no.

	var Telephone = form.areaCode.value + form.phone1.value + form.phone2.value

	if (Telephone.length != 10 || IsPositiveInteger(Telephone) == false) {
	    if (IsFocus == false) {
	        form.areaCode.focus();
	        IsFocus = true;
	    }
	    document.getElementById('errorTelephone').style.visibility = "visible";
	    errors += 1;
	}
	else {
	    document.getElementById('errorTelephone').style.visibility = "hidden";
	}
    
    // Age
	if (isEmpty(form.age.value) || IsPositiveInteger(form.age.value) == false) {
	    if (IsFocus == false) {
	        form.age.focus();
	        IsFocus = true;
	    }
	    document.getElementById('errorAge').style.visibility = "visible";
	    errors += 1;
	}
	else {
	    document.getElementById('errorAge').style.visibility = "hidden";
	}
    
	// Gender
	if (!(form.male.checked == true ^ form.female.checked == true)) {
	    if (IsFocus == false) {
	        form.male.focus();
	        IsFocus = true;
	    }
	    document.getElementById('errorGender').style.visibility = "visible";
	    errors += 1;
	}
	else {
	    document.getElementById('errorGender').style.visibility = "hidden";
	}
    
    // Service Provider
	if (isEmpty(form.serviceProvider.value)) {
	    if (IsFocus == false) {
	        form.serviceProvider.focus();
	        IsFocus = true;
	    }
	    document.getElementById('errorServiceProvider').style.visibility = "visible";
	    errors += 1;
	}
	else {
	    document.getElementById('errorServiceProvider').style.visibility = "hidden";
	}

	// Rules - note this has a slighlty different behaviour
	if (form.agree.checked == false) {
	    if (IsFocus == false) {
	        form.agree.focus();
	        IsFocus = true;
	    }
	    isErrorRules = true;
	}


	if (errors > 0 || isErrorRules == true) {
	    var errorMsg = "";
	    if (errors > 0) {
	        var errorMsg = 'You need to fill in all fields before you can enter.' + '\nComplete all the fields and try again!';
	    }
		if (isErrorRules == true) {
		    errorMsg += '\nPlease agree to the rules and regulations.';
		}
		alert(errorMsg);
		return false;
	}
	else
		return true;
}

//
function IsPositiveInteger(x) {

    var iLen = x.length;
    var sCharcode = 0;
    for (var i = 0; i < iLen; i++) {
        sCharcode = x.charCodeAt(i);
        if (!((sCharcode >= 48 && sCharcode <= 57))) {
             return false;
        }
    }
    return true;
}

//////////////////////////////////////////////////
//Find the index of a value within a dropdown list
function getListIndex(selectList, selectValue) {
	var selectedIndex = 0;
	for(var i=0;i<selectList.length;i++) {
		if(selectList[i].value == selectValue) {
			selectedIndex = i;
		}
	}
	return selectedIndex
}




/***** BOOLEAN TESTS. ******/


// Check whether a string is empty
function isEmpty(string) {
	return ((string==null) || (string.length==0))
}



// Check that the number of characters in a string is between a max and a min
function isValidLength(string, min, max) {
	if (string.length < min || string.length > max) return false;
	else return true;
}

// Check that a Canadian postal code is valid
function isValidPostalcode(postalcode) {
	if (postalcode.search){
		if (postalcode.length == 6 && (postalcode.search(/^\s*[a-ceghj-npr-tvxy]\d[a-z](\s)?\d[a-z]\d\s*$/i) != -1)) return true;
		else return false;
	}	
}

/**
 * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

function isValidEmail(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
	}

// Check valid postal cose
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 {
        return false;
    }
}

// Check that a string contains only numbers
function isNumeric(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^\d\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\D/) != -1)) return false;
	}
	return true;
}


// Check that a string contains only letters and numbers
function isAlphanumeric(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^\w\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\W/) != -1)) return false;
	}
	return true;
}

// Check that a string contains only letters
function isAlphabetic(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^a-zA-Z\s]/) != -1) || (!ignoreWhiteSpace && string.search(/[^a-zA-Z]/) != -1)) return false;
	}
	return true;
}

// Returns true if string s is empty or whitespace characters only.
function isWhitespace (string) {
   var i;
    if (isEmpty(string)) return true;
    
    for (i = 0; i < string.length; i++) {   
		// Check that current character isn't whitespace.
		var c = string.charAt(i);
		if (whitespace.indexOf(c) == -1) return false;
		}
    // All characters are whitespace.
    return true;
}

// Check that a radio button has been picked
function isRadioValue(ctlRadio) {
	var radio_choice = false;

	// Loop from zero to the one minus the number of radio button selections
	for (counter = 0; counter < ctlRadio.length; counter++) {
		// If a radio button has been selected it will return true
		if (ctlRadio[counter].checked) {
			radio_choice = true;
		}
	}
	return radio_choice;
}



/***** FORMATTING FUNCTIONS. *****/


// Remove characters that might cause security problems from a string 
function removeBadCharacters(string) {
	if (string.replace) {
		string.replace(/[<>\"\'%;\)\(&\+]/, '');
	}
	return string;
}

// Remove all spaces from a string
function removeSpaces(string) {
	var newString = '';
	for (var i = 0; i < string.length; i++) {
		if (string.charAt(i) != ' ') newString += string.charAt(i);
	}
	return newString;
}


// Remove leading and trailing whitespace from a string
function trimWhitespace(string) {
	var newString  = '';
	var substring  = '';
	beginningFound = false;
	
	// copy characters over to a new string
	// retain whitespace characters if they are between other characters
	for (var i = 0; i < string.length; i++) {
		
		// copy non-whitespace characters
		if (string.charAt(i) != ' ' && string.charCodeAt(i) != 9) {
			
			// if the temporary string contains some whitespace characters, copy them first
			if (substring != '') {
				newString += substring;
				substring = '';
			}
			newString += string.charAt(i);
			if (beginningFound == false) beginningFound = true;
		}
		
		// hold whitespace characters in a temporary string if they follow a non-whitespace character
		else if (beginningFound == true) substring += string.charAt(i);
	}
	return newString;
}


//runs onkeypress for phone number textboxes
function validateNumeric(textBox, e) {
    var keycode;
    if (window.event) 
        keycode = window.event.keyCode;
    else if(e) 
        keycode = e.which;
    else 
    return true;
    
    //true if the keycode = 0 - 9 (ASCII)
    return (keycode > 47 && keycode < 58);
}

function blockPaste(elm, e) {

    var ctrl;
    if(window.event) 
        ctrl = event.ctrlKey;
    else
        ctrl = e.ctrlKey;
    
    return !ctrl;
}

function autoTab(elm, e, form) {   
    //get the keycode (make sure that it is not enter, shift, tab, alt, etc..
    e = e || window.event;
    var keycode = e.keyCode || e.which;
    
    if(keycode) {                
        //validate ASCII codes (more on http://www.asciitable.com)
        switch(keycode) {
            case 127: //delete
            case 8:   //backspace
            case 9:   //horizontal tab
            case 11:  //vertical tab??
            case 13:  //enter
            case 14:  //shift in
            case 15:  //shift out
            case 16:  //DLE - Data Link Escape (Shift Tab)
            case 27:  //escape
            case 37:  //left arrow key
            case 39:  //right arrow key
                return true;
                break;
        }
    }
     
    if(elm.value.length >= elm.maxLength) {
        form.focus();

    }
    
    return true;
}

function isJavaScriptEnabled() {
    var elm = document.getElementById('jsflag');
    if(elm)
        elm.value = "1";
}