/* Place any extra javascript in here for all contests. 
 * Be sure to clean it out periodically.
 */

// Global variables used for checkbox population
var _vpPartner1OptIn = false;
var _vpPartner2OptIn = true;
var _vpPartner3OptIn = true;
var _vpPartner4OptIn = true;
var _vpPartner5OptIn = true;
var _vpPartner6OptIn = true;
var _vpPartner285OptIn = true;
var _vpPartner286OptIn = false;
var _vpPartner287OptIn = false;

var vp_usaPostal = /(^\d{5}$)/;
var vp_canPostal = /(^\D{1}\d{1}\D{1}$)|(^\D{1}\d{1}\D{1}\d{1}\D{1}\d{1}$)|(^\D{1}\d{1}\D{1}\s\d{1}\D{1}\d{1}$)|(^\D{1}\d{1}\D{1}[+]\d{1}\D{1}\d{1}$)/;
var _vpContestZip;

function vp_noPostalGeo() {$("#postalGeoForm").show();}

function vp_postalEntry() {
	_vpContestZip = $("#postalEntryCode").val();
	_vpContestUSId = $("#usaContestId").val();
	_vpContestCanadaId = $("#canContestId").val();
	
	$("#postalError").hide();
	if (vp_usaPostal.test(_vpContestZip)) {
		vp_formSet("process");
		setTimeout("vp_showContest(_vpContestUSId)",500);
	} else if (vp_canPostal.test(_vpContestZip)) {
		vp_formSet("process");
		setTimeout("vp_showContest(_vpContestCanadaId)",500);
	} else {
		$("#postalGeoForm").show();
		$("#postalError").show();
		vp_$("postalEntryCode").focus();
	}
}

function vp_readCookieContest() {
	var vp_ca = document.cookie.split(';');
	var nameEQ = "VALPAK_ZIP=";
	var regExp = /VALPAK_ZIP/;
	for( var i = 0; i < vp_ca.length; i++ )
	{
		var c = vp_ca[i];
		if( c.match(regExp) )
		{
			vp_VisitorZip = c.split("=")
			return vp_VisitorZip[1];
		}
	}
}

/////////////////////// Survey functions - temp ///////////////////////
// Global variables
var phoneNumber = "";
var phonePattern = /^(\d{3})-(\d{3})-(\d{4})$/;
var _vpSurveyEmailOptIn = true;
var _vpSurveyMobileOptIn = false;
// Parse mobile phone fields
function parseMobile() {
	if (vp_$("mobileNumber").value != "") {
		phoneNumber = vp_$("mobileNumber").value.split("-");
		vp_$("mobile1").value = phoneNumber[0];
		vp_$("mobile2").value = phoneNumber[1];
		vp_$("mobile3").value = phoneNumber[2];
	}
}
// Combine mobile phone fields
function combineMobile() {
	if (vp_$("mobile1").value != "" && vp_$("mobile2").value != "" && vp_$("mobile3").value != "") {
		vp_$("mobileNumber").value = vp_$("mobile1").value + "-" + vp_$("mobile2").value + "-" + vp_$("mobile3").value;
	}
	else {
		vp_$("mobileNumber").value = "";
	}
}
// Form validation
function validateMobile() {
	var error = false;
	
	if (vp_$("mobileOptInBox").checked) {
		combineMobile();
		_vpSurveyMobileOptIn = true;
		vp_$("mobileOptIn").value = true;
		
		if (phonePattern.test($("#mobileNumber").val())) {
			$("#mobileOptError").html("").hide();
		}
		else {
			$("#mobileOptError").html("Please provide valid mobile phone or uncheck this box").show();
			$("#mobileNumber, #mobile1, #mobile2, #mobile3").val("");
			error = true;
		}
	}
	else {
		combineMobile();
		_vpSurveyMobileOptIn = false;
		vp_$("mobileOptIn").value = false;
		
		if (phonePattern.test($("#mobileNumber").val())) {
			$("#mobileOptError").html("Please check this box when providing mobile phone").show();
			error = true;
		}
		else {
			$("#mobileOptError").html("").hide();
			$("#mobileNumber, #mobile1, #mobile2, #mobile3").val("");
		}
	}
	return error;
}
// Validate & combine fields and submit (Survey)
function vp_submitSurvey(question) {
	// email validation
	if (vp_$("emailOptInBox").checked) {
		_vpSurveyEmailOptIn = true;
		if ($("#emailCoupons").val() != 1) {vp_$("emailCoupons").value = 2;}
	}
	else {
		_vpSurveyEmailOptIn = false;
		vp_$("emailCoupons").value = 0;
	}
	
	var catCollection = "";
	var catError = false;
	var genderError = false;
	var mobileError = false;
	var total = 0;
	// Validate categories
	for (var i=0; i < document.contestForm.cats.length; i++) {
		if (document.contestForm.cats[i].checked) {
			catCollection += document.contestForm.cats[i].value + ",";
			total ++;
		}
	}
	if (total == 0) {
		catError = true;
		$("#catError").html('Please choose one or more categories').show();
	}
	else {
		catError = false;
		$("#catError").hide();
	}
	
	// Validate gender
	if (question == 'gender') {
		if (!document.contestForm.sex[0].checked &&
			!document.contestForm.sex[1].checked) {
			genderError = true;
			$("#genderError").html('Gender required').show();
		}
		else {
			genderError = false;
			$("#genderError").hide();
			// Concat gender
			if (document.contestForm.sex[0].checked)
				document.contestForm.optionalQuestion3.value = document.contestForm.sex[0].value;
			if (document.contestForm.sex[1].checked)
				document.contestForm.optionalQuestion3.value = document.contestForm.sex[1].value;
		}
	}
	
	// Concat categories
	$("#categories").val(catCollection);
	
	// Validate mobile phone
	if (question == 'mobile') {
		mobileError = validateMobile();
	}
	
	if (!catError && !genderError && !mobileError) {
		// Submit survey
		vp_submitContest();
	}
}

// Parse category check boxes (Survey)
function vp_parseCats() {
	var catArray = new Array();
	catArray[0] = '<td><input type="checkbox" name="cats" id="103" value="103" /></td><td class="checkbox" style="padding:3px 6px 0 3px"><div class="label2">Beauty</div><div class="tiny">(hair salons, spas, cosmetics)</div></td>';
	catArray[1] = '<td><input type="checkbox" name="cats" id="108" value="108" /></td><td class="checkbox" style="padding:3px 6px 0 3px"><div class="label2">Dining and Restaurants</div><div class="tiny">(pizza, fast food, sit down)</div></td>';
	catArray[2] = '<td><input type="checkbox" name="cats" id="110" value="110" /></td><td class="checkbox" style="padding:3px 6px 0 3px"><div class="label2">Entertainment and Travel</div><div class="tiny">(video rental, movie theaters,<br /> hotels, airlines)</div></td>';
	catArray[3] = '<td><input type="checkbox" name="cats" id="109" value="109" /></td><td class="checkbox" style="padding:3px 6px 0 3px"><div class="label2">General Services</div><div class="tiny">(carpet cleaning, dry cleaners, maid services)</div></td>';
	catArray[4] = '<td><input type="checkbox" name="cats" id="111" value="111" /></td><td class="checkbox" style="padding:3px 6px 0 3px"><div class="label2">Grocery</div><div class="tiny">(groceries, grocery stores)</div></td>';
	catArray[5] = '<td><input type="checkbox" name="cats" id="102" value="102" /></td><td class="checkbox" style="padding:3px 6px 0 3px"><div class="label2">Health and Medical</div><div class="tiny">(dentists, drug stores, optical)</div></td>';
	catArray[6] = '<td><input type="checkbox" name="cats" id="104" value="104" /></td><td class="checkbox" style="padding:3px 6px 0 3px"><div class="label2">Home and Garden</div><div class="tiny">(plumbing, handyman,<br /> lawn maintenance)</div></td>';
	catArray[7] = '<td><input type="checkbox" name="cats" id="106" value="106" /></td><td class="checkbox" style="padding:3px 6px 0 3px"><div class="label2">Professional Services</div><div class="tiny">(pet care, insurance, legal)</div></td>';
	catArray[8] = '<td><input type="checkbox" name="cats" id="107" value="107" /></td><td class="checkbox" style="padding:3px 6px 0 3px"><div class="label2">Shops and Retail</div><div class="tiny">(department stores, shoes, electronics)</div></td>';
	catArray[9] = '<td><input type="checkbox" name="cats" id="101" value="101" /></td><td class="checkbox" style="padding:3px 6px 0 3px"><div class="label2">Transportation and Auto</div><div class="tiny nowrap">(oil & lube, car wash, auto repair)</div></td>';
	var catDiv = '<table class="px3" cellpadding="0" cellspacing="0" width="323"><tr>';
	var i = 0;
	var randomCat;
	
	while (i < catArray.length) {
		// generate random num between 0 and arraylength-1
		randomCat = Math.floor(Math.random() * catArray.length);
		// if element hasn't been marked as "selected"
		if (catArray[randomCat] != "selected") {
			catDiv = catDiv + catArray[randomCat];
			if (i % 2 != 0 && i != 9) {catDiv = catDiv + '</tr><tr>';}
			// mark element as selected
			catArray[randomCat] = "selected";
			i++;
		}
	}
	catDiv = catDiv + '</tr></table>';
	$("#catDiv").html(catDiv);
	
	if ($("#categories").val() != "") {
		var cat = vp_$("categories").value.split(",");
		for (var i=0; i < document.contestForm.cats.length; i++) {
			if (cat[i] == "101") vp_$("101").checked = true;
			if (cat[i] == "102") vp_$("102").checked = true;
			if (cat[i] == "103") vp_$("103").checked = true;
			if (cat[i] == "104") vp_$("104").checked = true;
			if (cat[i] == "106") vp_$("106").checked = true;
			if (cat[i] == "107") vp_$("107").checked = true;
			if (cat[i] == "108") vp_$("108").checked = true;
			if (cat[i] == "109") vp_$("109").checked = true;
			if (cat[i] == "110") vp_$("110").checked = true;
			if (cat[i] == "111") vp_$("111").checked = true;
		}
	}
}

// Parse gender radio buttons (Survey)
function vp_parseGender() {
	if ($("#gender").val() != "") {
		sex = $("#gender").val();
		if (sex == "Male") document.contestForm.sex[0].checked = true;
		if (sex == "Female") document.contestForm.sex[1].checked = true;
	}
}

// Random Number Generator functions (used for Survey)
function NextRandomNumber() {
  var hi   = this.seed / this.Q;
  var lo   = this.seed % this.Q;
  var test = this.A * lo - this.R * hi;
  if (test > 0)
    this.seed = test;
  else
    this.seed = test + this.M;
  return (this.seed * this.oneOverM);
}

// Generate a random number 
function RandomNumberGenerator() {
  var d = new Date();
  this.seed = 2345678901 +
    (d.getSeconds() * 0xFFFFFF) +
    (d.getMinutes() * 0xFFFF);
  this.A = 48271;
  this.M = 2147483647;
  this.Q = this.M / this.A;
  this.R = this.M % this.A;
  this.oneOverM = 1.0 / this.M;
  this.next = NextRandomNumber;
  return this;
}

// Randomly get a contestID for survey.
function getRandomContestId() {
	// Build up an array of contest Ids.
	//var contestIdArray = new Array(263, 264, 265, 266, 267, 268, 269, 270, 271, 275, 276, 277);
	// Random number generator.	
	//var rand = new RandomNumberGenerator();
    // Generate randomly.
	//var index = Math.floor((contestIdArray.length) * rand.next());
    //return contestIdArray[index];
	return 275;
}

//Start Martha Contest (288)
function vp_gamePlayed() {
	ContestReg.gameComplete(288);
}

// Accept a game completion for Martha Stewart (288)
function vp_gameOver() {
	ContestReg.getPage("contestTAF", null, vp_processGameOver);
}

// Process a game completion for Martha Stewart (288)
function vp_processGameOver(data) {
	$("#contestRegData").html(data);
    	
// Execute any dynamically generated JS code in the taf data
	var jsCode = $("#tafJS").text();
	if (jsCode && (jsCode !== "")) {eval(jsCode);}
}

