var lang = "en";

var contestID;
var contestProvince;
var contestDOB;

var prize_id;
var prize_description;
var skill_question_id;
var skill_question;

var skill_timer;
var skill_timer_id;

var RecaptchaOptions = {theme:"blackglass"};

var mobile_api_path = "";

var legalAge = 18;

function initDentyneMobile() {
	lang = $("html").attr("lang");
	if (lang == "fr") {
		html_paths = html_paths_fr;
	}
	
	if ($.cookie('Dentyne_lockout') == "true") {
		$("#contest").load("agecheck-lockout-" + lang + ".html", "", ageLockoutLoaded);
	} else {
		$("#contest").load("agecheck-" + lang + ".html", "", ageVerificationLoaded);		
	}
	
	omniture("?pageName=mobile&language=" + lang);
	omniture("?event=event25");
}

function ageVerificationLoaded(responseText, textStatus, XMLHttpRequest) {
}

function validDate(strValue) {
	var dateRegExp = /^\d{1,2}(\-)\d{1,2}\1\d{4}$/;
	
	if (!dateRegExp.test(contestDOB)) {
		return false;
	} else {
		var today = new Date();
		var strSeparator = strValue.substring(2,3);
	    var arrayDate = strValue.split(strSeparator);
		var dateArrayLookup = { '01' : 31,
								'03' : 31, 
	                        	'04' : 30,
								'05' : 31,
	                        	'06' : 30,
								'07' : 31,
	                        	'08' : 31,
								'09' : 30,
	                        	'10' : 31,
								'11' : 30,
								'12' : 31 };
		var intDay = parseInt(arrayDate[0],10);

		if(dateArrayLookup[arrayDate[1]] != null) {
			if(intDay <= dateArrayLookup[arrayDate[1]] && intDay != 0)
				return true; //found in lookup table, good date
		}

		var intMonth = parseInt(arrayDate[1],10);
		var intYear = parseInt(arrayDate[2],10);
		if (intYear < 1950 || intYear >= today.getFullYear()) {
			return false;
		}
		if (intMonth == 2) { 
			if (intDay > 0 && intDay < 29) {
				return true;
			} else if (intDay == 29) {
				if ((intYear % 4 == 0) && (intYear % 100 != 0) || (intYear % 400 == 0)) {
					// year div by 4 and ((not div by 100) or div by 400) ->ok
					return true;
				}
			}
		}
	}
	
	return false;
}

function validAge(strValue) {
	var intDay;
	var intMonth;
	var intYear;
	
	var strSeparator = strValue.substring(2,3);
    var arrayDate = strValue.split(strSeparator);

	intDay = parseInt(arrayDate[0],10);
	intMonth = parseInt(arrayDate[1],10);
	intYear = parseInt(arrayDate[2],10);
	
	var userDOB = new Date(intYear, intMonth - 1, intDay);
	var today = new Date();

	var diff = new Date();
	diff.setTime( today.getTime() - userDOB.getTime() );

	var userAge = diff.getFullYear() - 1970;
	
	if (userAge < legalAge)
		return false;

	return true;
}

function ageVerification() {
	// check entries
	contestProvince = $("#contest form #province").val();
	
	switch(contestProvince) {
		case "AB":
		case "MB":
		case "NB":
		case "ON":
		case "PE":
		case "QC":
		case "SK":
			legalAge = 18
		break;

		case "BC":
		case "NF":
		case "NT":
		case "NU":
		case "YT":
		case "NS":
			legalAge = 19;
		break;		
	}
	
	contestDOB = $("#contest form #dob").val();
	
	if (!validDate(contestDOB)) {
		if (lang == "fr") {
			showRegistrationErrors(["DATE DE NAISSANCE est obligatoire."]);
		} else {
			showRegistrationErrors(["DATE OF BIRTH is required."]);
		}
	} else if (!validAge(contestDOB)) {
		ageLockOut();
	} else {
		$("#contest").load("contest-" + lang + ".html", "", mobileLoaded);
	}
}

function ageLockOut() {
	if ($.cookie('Dentyne_lockout') != "true") {
		var date = new Date();
		date.setTime(date.getTime() + (1 * 24 * 60 * 60 * 1000));
		$.cookie('Dentyne_lockout', 'true', { path: '/', expires: date });
	}
	$("#contest").load("agecheck-lockout-" + lang + ".html", "", ageLockoutLoaded);
}

function ageLockoutLoaded(responseText, textStatus, XMLHttpRequest) {
	// Sorry, but to enter this site you must be age of majority in your province of residence. Since you're not, you've been locked out for 24 hours.
	// D&#233;sol&#233;, mais pour visiter ce site, vous devez avoir l'&#226;ge de la majorit&#233; dans votre province de r&#233;sidence. Comme ce n'est pas le cas, votre compte est inaccessible pendant 24 heures.
}

function mobileLoaded(responseText, textStatus, XMLHttpRequest) {
	$("#contest form #upc").focus(function() {
		var regex=/[A-Za-z]/g;
		if (regex.test($(this).val())) {
			$(this).val("");
		}
	});
	omniture("?event=event7");
	
	Recaptcha.create(recaptcha_key.public, "recaptcha", {theme:"blackglass",lang:lang});
}

// run jQuery getScript to lazy load omniture tracking
function omniture(params) {
	$.getScript("../" + omniture_paths.track + params);
}

function showRegistrationErrors(errorArray) {
	$(".errors").html("");
	for (var i = 0; i < errorArray.length; i++) {
		var error = $("<li class='error'>" + errorArray[i] + "</li>");
		$(".errors").append(error);
	}
	$(".errors").show();
}

function submitRegistration() {
	$("#contest form #dob").val(contestDOB);
	$("#contest form #language").val(lang.toUpperCase());
	
	$.post(mobile_api_path + api_paths.register, $("#contest form").serialize(), function(data) {
		$(".errors").hide();
		if (data.success == "false") {
			// show errors
			if ("errors" in data) {
				if ("recaptcha_error" in data) {
					data.errors.push(data.recaptcha_error);
				}
				showRegistrationErrors(data.errors);
			} else if ("recaptcha_error" in data) {
				showRegistrationErrors(new Array(data.recaptcha_error));
			}
			Recaptcha.create(recaptcha_key.public, "recaptcha", {theme:"blackglass",lang:lang});
			// scroll to top
			scroll(0,0);
		} else if (data.success == "true") {
			omniture("?event=event3");
			omniture("?event=event8");

			$("#contest").html("");
			
			contestID = data.id;
			// check for instant win
			instantWinCheck(contestID);
		}
	}, "json");
}

function instantWinCheck(idValue) {
	$.post(mobile_api_path + api_paths.instant_win, {id:idValue}, function(data) {
		if (data.success == "false") {
			omniture("?event=event12");
			// throw event to continue as normal
			prize_description = "0";
			// go to the thank you screen
			registrationComplete();
		} else if (data.success == "true") {
			omniture("?event=event11");
			// get prize info and skill testing question deets
			skill_question_id = data.skill_question_id;
			skill_question = data.skill_question;
			prize_id = data.prize_id;
			prize_description = data.prize_description;
			// inform user of win
			$("#contest").load("instantwin-congratulations-" + lang + ".html", "", instantwinCongratsLoaded);
		}
	}, "json");
}

function instantwinCongratsLoaded(responseText, textStatus, XMLHttpRequest) {
	var prizeClass = "prize-" + prize_description;
	if (lang == "fr") prizeClass += "-fr";
	$("#contest .congratulations .prize").attr("class", prizeClass);
	// page has continue button, etc	
}

function skillTestingQuestion() {
	$("#contest").load("instantwin-skilltestingquestion-" + lang + ".html", "", skillTestingQuestionLoaded);
}

function skillTestingQuestionLoaded(responseText, textStatus, XMLHttpRequest) {
	skill_timer = 0;
	skill_timer_id = window.setInterval("skillTestingQuestionTimerUpdate()", 1000);
	$("#contest #question").html(skill_question);
}

function skillTestingQuestionTimerUpdate() {
	skill_timer++;
	var timerValue = (skill_timeout * 60) - skill_timer;
	var minutes = Math.floor(timerValue / 60);
	var seconds = timerValue - (minutes * 60);
	$("#timer").html(minutes + ":" + ((seconds < 10) ? "0" + seconds : seconds));
	if (minutes <= 0 && seconds <= 0) {
		window.clearInterval(skill_timer_id);
	}
}

function skillTestingQuestionSubmit() {
	var answer = $("#contest form [name=answer]").val();
	$.post(mobile_api_path + api_paths.skill_testing, {skill_question_answer:answer}, function(data) {
		if (data.success == "false") {
			$("#contest").load("contest-thanks-" + lang + ".html", "", registrationCompleteSorryLoaded);
		} else if (data.success == "true") {
			$("#contest").load("instantwin-form-" + lang + ".html", "", instantWinClaimFormLoaded);
		}
	}, "json");
}

function instantWinClaimFormLoaded(responseText, textStatus, XMLHttpRequest) {
	if (contestDOB) {
		$("#contest form #dob").val(contestDOB);
	}
	if (contestProvince) {
		$("#contest form #province").val(contestProvince);
	}
	omniture("?event=event14");
}

function instantWinClaimFormSubmit() {
	$.post(mobile_api_path + api_paths.instant_win_form, $("#contest form").serialize(), function(data) {
		if (data.success == "false") {
			// show errors, etc
			if ("errors" in data) {
				showRegistrationErrors(data.errors);
			}			
			scroll(0,0);
		} else if (data.success == "true") {
			omniture("?event=event15");
			$("#contest").load("instantwin-print-" + lang + ".html", "", instantWinPrintLoaded);
		}
	}, "json");
}

function instantWinPrintLoaded(responseText, textStatus, XMLHttpRequest) {
}

function registrationComplete() {
	omniture("?event=event4");
	$("#contest").load("contest-thanks-" + lang + ".html", "", registrationCompleteLoaded);
}

function registrationCompleteLoaded(responseText, textStatus, XMLHttpRequest) {
	$("#contest .sorry").remove();
}

function registrationCompleteSorryLoaded(responseText, textStatus, XMLHttpRequest) {
	$("#contest .default").remove();
}
