
// VALIDATE.JS  Client-side contest validation
//				Used by all contests after April 2009
//				Contests created before April 2009 use contest.js for validation
// --------------------------------------------------------------------------------

// main form validation wrapper
function validateForm() {
	clearAllErrors();	
	document.body.style.cursor="wait";
	var captcha_reqd = document.contestForm.captcha_reqd.value;
	if (captcha_reqd=="1") {
		beginCaptchaCheck(); // will call beginEntryCodeCheck with true/false on callback depending on results
	} else {
		beginEntryCodeCheck(true); // will call validateMainForm with true/false on callback depending on results
	}
}
// initiate form checking with captcha
function beginCaptchaCheck() {
	var url = '/contestapp/captcha.php?' + Math.random();
	var postStr = document.contestForm.captcha.name + "=" + encodeURIComponent( document.contestForm.captcha.value );
	makeRequest(url, postStr);
}
function beginEntryCodeCheck(success) {
	// if a valid entry code is required, initiate the check
	if (typeof document.contestForm.entry_code_reqd != "undefined") { 
		if (document.contestForm.entry_code_reqd.value == "1") {
			// convert success boolean to a single digit number
			if (success) {
				var successnum=1;
			} else {
				var successnum=0;
			}			
			var url = '/contestapp/entrycode.php?' + Math.random();
			var postStr = "success="+successnum+"&idcontest="+encodeURIComponent(document.contestForm.idcontest.value)+"&code=" + encodeURIComponent(document.contestForm.entry_code.value);
			makeEntryCodeRequest(url, postStr);
		} else {
			validateMainForm(success);
		}
	} else { // if no valid entry code is required, move right to validate the main form
		validateMainForm(success);
	}
}
// validate form fields aside from captcha
function validateMainForm(prevState) {
	document.body.style.cursor="auto";			
	if (typeof prevState == "undefined") {
		prevState=true;
	}
	var custom=validateCustomFields();
	var standard=validateStandardFields(custom);	
	var displayUploadReminder = checkForPartialUploads(); 
	if (prevState && standard && custom) { // if all validation passed...
		if (displayUploadReminder) { // if a file upload reminder is required....
			if (typeof reminderText == "undefined") { // if no contest-specific reminderText is set, use a default phrase
				var reminderText="Are you sure you wish to submit the form without completing a file attachment upload?\n\nClick 'Cancel' to choose an attachment file, and then click the 'Upload' button. Otherwise, click 'OK' to continue without a file attachment.";
			}
			if (confirm(reminderText)) { // ok clicked, submit the form
				document.contestForm.submit(); 
			} else { // cancel clicked, don't submit yet so they can fix the upload
				document.getElementById("overallError").style.display="block";				
				return false;
			}
		} else { //no file upload reminder is required, submit!
			document.body.style.cursor="auto";		
			document.contestForm.submit();			
		}
	} else { // some validation failed
		document.getElementById("overallError").style.display="block";
		document.body.style.cursor="auto";		
		return false;
	}
}
// see if any non-required upload fields have blank values
// if so, a reminder will be popped up on submission
// this is to prevent the problem whereby visitors forget to the click the "Upload" button after choosing a file
function checkForPartialUploads() {
	var q_type;
	var q_reqd;
	for (i=0; i<9999 ; i++) {
		if (document.getElementById("cq"+i)) { // if the question exists...
			q_type=document.getElementById("cq_type"+i).value;
			q_reqd=document.getElementById("cq_reqd"+i).value;
			if (q_reqd=="0" && q_type=="6" && document.getElementById("cq"+i).value.length<1) {
				return true; // one found, abort and return true so reminder is displayed
			}
		}
	}
	return false; // none found, no reminder will display
}
function validateStandardFields(success) {
	var min_age = document.contestForm.min_age.value;
	var max_age = document.contestForm.max_age.value;	
	var reFocus=0;
	if (document.contestForm.first_name.value.length<1) {
		reFocus=setError("first_name","First Name is required.", reFocus);
		success=0;
	}
	if (document.contestForm.last_name.value.length<1) {
		reFocus=setError("last_name","Last Name is required.", reFocus);
		success=0;		
	}	
	if (document.contestForm.age.value<1 || document.contestForm.age.value.length<1 || !isInteger(document.contestForm.age.value)) {
		reFocus=setError("age","Age is required and must be a number.", reFocus);
		success=0;		
	} else {
		var enteredAge=parseInt(document.contestForm.age.value);		
		if (enteredAge<parseInt(min_age) || enteredAge>parseInt(max_age)) {
			reFocus=setError("age","Entrants must be between " + min_age + " and " + max_age + " years of age.", reFocus);
			success=0;		
		}		
	}
	if (document.contestForm.email.value.length<1 || !isValidEmailFormat(document.contestForm.email.value)) {
		reFocus=setError("email","Valid Email address is required.", reFocus);
		success=0;		
	}
	if (document.contestForm.phone.value.length<1 || !isValidPhoneFormat(document.contestForm.phone.value)) {
		reFocus=setError("phone","Valid Home Phone number is required.", reFocus);
		success=0;		
	}			
	if (document.contestForm.mobile.value.length>0 && !isValidPhoneFormat(document.contestForm.mobile.value)) {
		reFocus=setError("mobile","If provided, Cell Phone number must be valid.", reFocus);
		success=0;		
	}
	if (document.contestForm.address_street.value.length<1) {
		reFocus=setError("address_street","Address is required.", reFocus);
		success=0;		
	}				
	if (document.contestForm.city.value.length<1) {
		reFocus=setError("city","City is required.", reFocus);
		success=0;		
	}				
	if (document.contestForm.province.value.length<1) {
		reFocus=setError("province","Province is required.", reFocus);
		success=0;		
	}			
	if (document.contestForm.postal_code.value.length<1 || !isValidPostalCodeFormat(document.contestForm.postal_code.value)) {
		reFocus=setError("postal_code","Valid Postal Code is required.", reFocus);
		success=0;		
	}
	if (document.contestForm.country.value.length<1) {
		reFocus=setError("country","Country is required.", reFocus);
		success=0;		
	}		
	if (!document.contestForm.privacy_policy.checked) {
		reFocus=setError("privacy_policy","You must agree to the contest rules and regulations to enter this contest.", reFocus);
		success=0;		
	}		
	return success;
}
function validateCustomFields() {
	var q_type;
	var q_is_mandatory;
	var q_answer;
	var user_answer;
	var reFocus=0;	
	var success=1;
	for (i=0; i<9999 ; i++) {
		if (document.getElementById("cq"+i)) { // if the question exists...
			q_type=document.getElementById("cq_type"+i).value;
			q_reqd=document.getElementById("cq_reqd"+i).value;
			if (q_type=="1" || q_type=="2" || q_type=="3") { // text or textfield or select
				user_answer=document.getElementById("cq"+i).value;
			} else if (q_type=="4") { // checkbox list
				user_answer=getCheckRadioSelectedValues("cq"+i);
			} else if (q_type=="5") { // radio list
				user_answer=getCheckRadioSelectedValues("cq"+i);				
			} else if (q_type=="6") { // file upload
				user_answer=document.getElementById("cq"+i).value;			
			}
			if (q_reqd=="1" && user_answer.length==0) {
				reFocus=setError("cq"+i,"An answer to this question is required.", reFocus);
				success=0;						
			}
			if ( (q_type=="1" || q_type=="2") && user_answer.length<document.getElementById("aminlen"+i).value ) { // if text or textarea, check min length is reached
				reFocus=setError("cq"+i,"Answer must be at least " + document.getElementById("aminlen"+i).value + " characters in length. (Current length: " + user_answer.length + ").", reFocus);
				success=0;							
			}
			if ( (q_type=="1" || q_type=="2") && user_answer.length>document.getElementById("amaxlen"+i).value ) { // if text or textarea, check max length not exceeded
				reFocus=setError("cq"+i,"Answer cannot exceed " + document.getElementById("amaxlen"+i).value + " characters in length. (Current length: " + user_answer.length + ").", reFocus);
				success=0;							
			}			
			if (document.getElementById("cqa"+i)) {
				user_answer=user_answer.toLowerCase();
				if (md5(user_answer.toLowerCase()) != document.getElementById("cqa"+i).value) {
					reFocus=setError("cq"+i,"This answer is incorrect.  Please try again.", reFocus);
					success=0;						
				}
			}			
		}
	}
	return success;
}
// make form and instructions visible
function showEntryForm() {
	document.contestForm.style.display="block";
	document.getElementById("contest_instructions").style.display="block";		
}
// clear all previously set error messages on the form
function clearAllErrors() {
	var tags=document.getElementsByTagName("*");
	for (i=0; i<tags.length; i++) {
		if (tags[i].className.substring(0,5)=="error") {
			//tags[i].innerHTML="";
			tags[i].style.display="none";
		}
	}
}
// set an error message
function setError(field, text, reFocus) {
	if (field.length && text.length) {
		document.getElementById("error_"+field).innerHTML=text;
		document.getElementById("error_"+field).style.display="block";
		if (reFocus==0) {
			document.getElementById(field).focus();
		}
		return 1;
	}
	return reFocus;
}
// return selected values for a set of radios or checkboxs
function getCheckRadioSelectedValues(id) {
	var allvals="";
	var ischecked;
	var val;
	var num=eval("document.contestForm."+id+".length");
	for (var i=0; i<num; i++) {
		ischecked=eval("document.contestForm."+id+"["+i+"].checked");
		if (ischecked) {
			val=eval("document.contestForm."+id+"["+i+"].value");
			allvals+=val;
		}
	}
	return allvals;
}
// return true if string is a valid 10-digit phone number
function isValidPhoneFormat(str) {
	var cleaned = str.replace(/[\(\)\.\-\ ]/g, '');
	if (isNaN(parseInt(cleaned))) {
		return false;
	}
	if (!(cleaned.length == 10)) {
		return false;
	}
	return true;
}
// return true if string is a valid email address format
function isValidEmailFormat(str) {
	if (str.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) {
		return true;
	} else {
		return false;
	}
}
// return true if string is a valid Canadian postal code format
function isValidPostalCodeFormat(str) {
	str=str.toLowerCase();
	// first check for valid characters; note D, F, I, O, Q and U are not allowed
	var valid="0123456789abceghjklmnprstvwxyz ";
	for (i=0; i<str.length; i++) { 
		if (valid.indexOf(str.charAt(i)) == -1)  {
			return false;
		}
	}	
	// then check for correct ordering; either with or without space is fine
	if (str.length == 6 && str.search(/^[a-ceghj-npr-tv-z]\d[a-ceghj-npr-tv-z]\d[a-ceghj-npr-tv-z]\d$/) != -1) {
		return true;
	} else if (str.length == 7 && str.search(/^[a-ceghj-npr-tv-z]\d[a-ceghj-npr-tv-z](-|\s)\d[a-ceghj-npr-tv-z]\d$/) != -1) {
		return true;
	} else {
		return false;
	}
	return true;
}
// return true if string can be converted to an integer
function isInteger(str) {
	var valid = "0123456789 ";
	for (i=0; i<str.length; i++) { 
		if (valid.indexOf(str.charAt(i)) == -1)  {
			return false;
		}
	}
	return true;
}
// return true if string is purely alphanumeric
function isAlphaNumeric(str) {
	var valid = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
	for (i=0; i<str.length; i++) { 
		if (valid.indexOf(str.charAt(i)) == -1)  {
			return false;
		}
	}
	return true;	
}
// if thindata login is required for the contest, this function is called onload to verify
// that the thindata cookie is present and pre-populate some contest form fields
function checkUser(url) {
	var akey=getCookie("akey");
	var at=getCookie("at")
	var pd=getCookie("pd")	
	if (akey==null || at==null || pd==null) {
		//window.location='http://uat.sso.cbc.ca/SSOAuthenticationDomain.ashx?mode=Login&RedirectURL='+url; // DEV & QA
		window.location='https://sso.cbc.ca/SSOAuthenticationDomain.ashx?mode=Login&RedirectURL='+url; // PROD
	} else {
		document.contestForm.first_name.value=parseString(pd,"First Name");		
		document.contestForm.last_name.value=parseString(pd,"Last Name");				
		document.contestForm.city.value=parseString(pd,"City");	
		setSelectValue("province",getProvinceCode(parseString(pd,"Province")));
		document.contestForm.email.value=parseString(at,"e");
		document.contestForm.u.value=parseString(at,"u");
		showEntryForm();		
	}
}
// return value for given cookie
function getCookie(name) {
	name+="=";
	var chunks = document.cookie.split(';');
	for(var i=0; i<chunks.length; i++) {
		var chunk = chunks[i];
		while (chunk.charAt(0)==' ') {
			chunk = chunk.substring(1,chunk.length);
		}
		if (chunk.indexOf(name) == 0) {
			return chunk.substring(name.length,chunk.length);
		}
	}
	return null;
}
// parse out a single value from a url string of name value pairs
function parseString(str, val) {
	var parts=str.split('&');
	for (var i=0; i<parts.length; i++) {
		pair=parts[i].split('=');
		if (pair[0]==val) {
				return pair[1];
		}
	}
	return "not found";
}
// set value of a given select/option box to the given value
function setSelectValue(sel, val) {
	sel=document.getElementById(sel);
	for(i=0; i<sel.length;  i++) {
		if(sel[i].value==val) {
			sel.selectedIndex=i;
		}
	}
}
// get the two-letter abbreviation for the given province
// (used by checkUser function when converting thindata member information)
function getProvinceCode(prov) {
	if (prov=="Alberta") return "AB";
	if (prov=="British Columbia") return "BC";
	if (prov=="Manitoba") return "MB";
	if (prov=="New Brunswick") return "NB"; 
	if (prov=="Newfoundland") return "NL";
	if (prov=="Newfoundland and Labrador") return "NL";
	if (prov=="Northwest Territories") return "NT"; 
	if (prov=="Nova Scotia") return "NS"; 
	if (prov=="Nunavut") return "NU"; 
	if (prov=="Ontario") return "ON";			
	if (prov=="Prince Edward Island") return "PE"; 
	if (prov=="PEI") return "PE"; 	
	if (prov=="Quebec") return "QC"; 
	if (prov=="Saskatchewan") return "SK"; 
	if (prov=="Yukon") return "YT"; 
	return "AB"; // AB is the default only because it is the first alphabetically, honest.
}
function utf8_encode ( string ) {
    // Encodes an ISO-8859-1 string to UTF-8
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_utf8_encode/
    // +       version: 810.621
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
    string = (string+'').replace(/\r\n/g,"\n");
    var utftext = "";
    var start, end;
    var stringl = 0;
    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;
        if (c1 < 128) {
            end++;
        } else if((c1 > 127) && (c1 < 2048)) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc != null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }
    if (end > start) {
        utftext += string.substring(start, string.length);
    }
    return utftext;
}
function md5 ( str ) {
    // Calculate the md5 hash of a string
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_md5/
    // +       version: 810.112
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // + namespaced by: Michael White (http://getsprink.com)
    // +    tweaked by: Jack
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: md5('Kevin van Zonneveld');
    // *     returns 1: '6e658d4bfcb59cc13f96c14450ac40b9'
    var RotateLeft = function(lValue, iShiftBits) {
        return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
    };
    var AddUnsigned = function(lX,lY) {
        var lX4,lY4,lX8,lY8,lResult;
        lX8 = (lX & 0x80000000);
        lY8 = (lY & 0x80000000);
        lX4 = (lX & 0x40000000);
        lY4 = (lY & 0x40000000);
        lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
        if (lX4 & lY4) {
            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
        }
        if (lX4 | lY4) {
            if (lResult & 0x40000000) {
                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
            } else {
                return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
            }
        } else {
            return (lResult ^ lX8 ^ lY8);
        }
    };
    var F = function(x,y,z) { return (x & y) | ((~x) & z); };
    var G = function(x,y,z) { return (x & z) | (y & (~z)); };
    var H = function(x,y,z) { return (x ^ y ^ z); };
    var I = function(x,y,z) { return (y ^ (x | (~z))); };
    var FF = function(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };
    var GG = function(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };
    var HH = function(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };
    var II = function(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };
    var ConvertToWordArray = function(str) {
        var lWordCount;
        var lMessageLength = str.length;
        var lNumberOfWords_temp1=lMessageLength + 8;
        var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
        var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
        var lWordArray=Array(lNumberOfWords-1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while ( lByteCount < lMessageLength ) {
            lWordCount = (lByteCount-(lByteCount % 4))/4;
            lBytePosition = (lByteCount % 4)*8;
            lWordArray[lWordCount] = (lWordArray[lWordCount] | (str.charCodeAt(lByteCount)<<lBytePosition));
            lByteCount++;
        }
        lWordCount = (lByteCount-(lByteCount % 4))/4;
        lBytePosition = (lByteCount % 4)*8;
        lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
        lWordArray[lNumberOfWords-2] = lMessageLength<<3;
        lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
        return lWordArray;
    };
    var WordToHex = function(lValue) {
        var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
        for (lCount = 0;lCount<=3;lCount++) {
            lByte = (lValue>>>(lCount*8)) & 255;
            WordToHexValue_temp = "0" + lByte.toString(16);
            WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
        }
        return WordToHexValue;
    };
    var x=Array();
    var k,AA,BB,CC,DD,a,b,c,d;
    var S11=7, S12=12, S13=17, S14=22;
    var S21=5, S22=9 , S23=14, S24=20;
    var S31=4, S32=11, S33=16, S34=23;
    var S41=6, S42=10, S43=15, S44=21;
    str = utf8_encode(str);
    x = ConvertToWordArray(str);
    a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
    xl = x.length;
    for (k=0;k<xl;k+=16) {
        AA=a; BB=b; CC=c; DD=d;
        a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
        d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
        c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
        b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
        a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
        d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
        c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
        b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
        a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
        d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
        c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
        b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
        a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
        d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
        c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
        b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
        a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
        d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
        c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
        b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
        a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
        d=GG(d,a,b,c,x[k+10],S22,0x2441453);
        c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
        b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
        a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
        d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
        c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
        b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
        a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
        d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
        c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
        b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
        a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
        d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
        c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
        b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
        a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
        d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
        c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
        b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
        a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
        d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
        c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
        b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
        a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
        d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
        c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
        b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
        a=II(a,b,c,d,x[k+0], S41,0xF4292244);
        d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
        c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
        b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
        a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
        d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
        c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
        b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
        a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
        d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
        c=II(c,d,a,b,x[k+6], S43,0xA3014314);
        b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
        a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
        d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
        c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
        b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
        a=AddUnsigned(a,AA);
        b=AddUnsigned(b,BB);
        c=AddUnsigned(c,CC);
        d=AddUnsigned(d,DD);
    }
    var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
    return temp.toLowerCase();
}
// gets the browser specific XmlHttpRequest Object 
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest(); // Mozilla, Safari, IE7, etc.
	} else if (window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP"); // IE6
	} 
}

// initiate the AJAX request for captcha check
function makeRequest(url, param) {
	// if our readystate is either not started or finished, initiate a new request
	if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
	   receiveReq.open("POST", url, true);
	   receiveReq.onreadystatechange = updatePage; 
	
	   // add HTTP headers to the request
	   receiveReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	   receiveReq.setRequestHeader("Content-length", param.length);
	   receiveReq.setRequestHeader("Connection", "close");
	
	   // make the request
	   receiveReq.send(param);
	 }   
}
// called every time our XmlHttpRequest objects state changes for captcha check
function updatePage() {
	if (receiveReq.readyState == 4) {
		if (receiveReq.responseText=="ok") { 
			beginEntryCodeCheck(true);
		} else {
			document.getElementById('error_captcha').innerHTML = "Text did not match image. Please try again.";
			document.getElementById('error_captcha').style.display = "block";
			img = document.getElementById('imgCaptcha'); 
			img.src = '/contestapp/create_image.php?' + Math.random();
			beginEntryCodeCheck(false);
		}
	}
}
// initiate the AJAX request for entry code check
function makeEntryCodeRequest(url, param) {
	// if our readystate is either not started or finished, initiate a new request
	if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {

		receiveReq.open("POST", url, true);
		receiveReq.onreadystatechange = entryCodeUpdatePage; 
		
		// add HTTP headers to the request
		receiveReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		receiveReq.setRequestHeader("Content-length", param.length);
		receiveReq.setRequestHeader("Connection", "close");
		
		// make the request
		receiveReq.send(param);
	 }   
}
// called every time our XmlHttpRequest objects state changes for entry code check
function entryCodeUpdatePage() {
	if (receiveReq.readyState == 4) {
		if (receiveReq.responseText=="ok0") { // entry code ok, but captcha was bad
			validateMainForm(false);
		} else if (receiveReq.responseText=="ok1") { // entry code and captcha ok
			validateMainForm(true);		
		} else {
			var desc = document.contestForm.entry_code_desc.value;
			if (desc.length<1) { desc="Entry Code";	}
			document.getElementById('error_entry_code').innerHTML = desc + " is not valid. Please try again."; // + "[" + receiveReq.responseText +"]";
			document.getElementById('error_entry_code').style.display = "block";
			validateMainForm(false);
		} 
	}
}
// if contest is closed, redirect
function checkIfClosed(closed_date,closed_url) {
	if (typeof serverDateHour != "undefined") {
		if (parseInt(serverDateHour) >= parseInt(closed_date)) {
			window.location.href=closed_url;
		}
	}
}
// pad a number to 2 digits with a 0 in front, if necessary, and convert to string
function pad2(num) {
	num = num.toString();
	if (num.length==1) {
		return '0'+num.toString();
	} else {
		return num.toString();
	}
}
// create XmlHttpRequest object
var receiveReq = getXmlHttpRequestObject();
