// JavaScript Document for JFC website

// Dreamweaver functions

// function to preload images - @dreamweaver
function MM_preloadImages() { // Image Preloader v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

// JFC functions

// function to show/hide sub navigation - @vic
function showSub(id) {
	var target = document.getElementById(id);
	if (target) {
		if (target.style.display=='block') {var shown = true;}
	}
	for (var i = 1; i<=30; i++) {
		if (document.getElementById('sub'+i)) {
			document.getElementById('sub'+i).style.display='none';}
		}	
	if (target) {
		if (!shown) {
			target.style.display = 'block';	
		}
	}
}

// function to show/hide sections - @vic
function showContent (contentNum, parentNum) {	
	
	/* Javascript-driven contents - uncomment this if contents shall be driven on the client side (by js)
	for (var i = 0; i<=30; i++) {		
		// hide all contents
		if (document.getElementById('content'+i)) {
			document.getElementById('content'+i).style.display = 'none';
		}	
		// and remove highlight from all nav
		if (document.getElementById('nav'+i)) {
			document.getElementById('nav'+i).style.color = '#A2300E';
		}
	}		
	
	// get target content
	var targetContent = document.getElementById("content" + contentNum);
	
	// show target content
	if (targetContent) {
			targetContent.style.display = 'block';	
	}
	*/
	// get corresponding navs
	var targetNav = document.getElementById("nav" + contentNum);
	var parentNav = document.getElementById("nav" + parentNum);
	
	// highlight corresponding nav
	if (targetNav) {
		targetNav.style.color = '#F00';	
		// remove class declaration from previous breadcrumbs items
		newBreadCrumbs = curBreadCrumbs.replace("class=current", ''); // for IE browsers
		newBreadCrumbs = newBreadCrumbs.replace("class=\"current\"", ''); // for Netscape-based browsers (e.g. Firefox)
	}
	
	// avoid duplicate breadcrumbs
	duplicate = (contentNum == parentNum) ? true : false;
	
	// append parent nav to initial breadcrumbs		
	if (parentNav && !duplicate) {		
		newBreadCrumbs += "&nbsp;&nbsp;>&nbsp;&nbsp;<a href=\"" + parentNav.href + "\">" + parentNav.innerHTML + "</a>";		
	} 
	// then append target nav
	if (targetNav) {	
		newBreadCrumbs += "&nbsp;&nbsp;>&nbsp;&nbsp;<a href=\"" + targetNav.href + "\" class=\"current\">" + targetNav.innerHTML + "</a>";
		// update display of breadcrumbs
		document.getElementById("breadcrumbs").innerHTML = newBreadCrumbs;
	}
	
	
}

// funtion to show/hide misc. content (used within TV Ads section and Happy Moments Promo) - @vic

function show (strPrefix, contentToShow) {
	// hide all related sections
	for (var i = 1; i<=30; i++) {	
		if (document.getElementById(strPrefix+i)) {
			document.getElementById(strPrefix+i).style.display = 'none';
		}
	}		

	if (contentToShow) {
		// show target section
		var target = document.getElementById(contentToShow);
		target.style.display = 'block'; 
	}
}


// function to validate store locator entry - @eric
function validateSearchString(formObj) 
{
	valid = true;
	targetForm = document.getElementById(formObj);
	var searchString = targetForm.store_search_string.value;
	var searchStringLen = searchString.length;
	//alert(searchStringLen);
	
	if((targetForm.store_search_string.value == '')||(searchStringLen < 2)||searchString.search(/W/) > -1)
	{
		
		valid = false;
	}
	
	return valid;
}

function setCountry(country)
{
		//alert('form1.setCountry.value');
		document.getElementById('setCountry').value = country;
		document.int_store_finder.submit();
}

//----------- Form validation functions ----------//

// function to validate form elements - @vic
function checkField (fieldName, fieldTitle, email, errorArea, customErrMsg) {
	element = document.getElementById(fieldName);
	if (element) {
		// check for empty value
		if (element.value.length <= 0) {
			if (customErrMsg) {
			document.getElementById(errorArea).innerHTML = customErrMsg;
			} else {
				document.getElementById(errorArea).innerHTML = "Please enter your " + fieldTitle + ".";
			}
			return false;
			
		} else {
			// validate email format
			if (email) {
				i = element.value.indexOf("@");
			 	j = element.value.indexOf(".",i);
				k = element.value.indexOf(",");
				kk = element.value.indexOf(" ");
				jj = element.value.lastIndexOf(".")+1;
				len = element.value.length;
			
				if ((i>0) && (j>(1+1)) && (k==-1) && (kk==-1) && (len-jj >=2) && (len-jj<=4)) {
					return true;
				} else {
					if (customErrMsg) {
					document.getElementById(errorArea).innerHTML = customErrMsg;
					} else {
						document.getElementById(errorArea).innerHTML = "Please enter your " + fieldTitle + ".";
					}
					return false;
				}
				
			} else {
				return true;
			}
		}
	}
}

// function to pop-up a window in the center of rhe screen
function popupWindow (URL, winName, width, height) {
	// set position for the window
	x = (screen.width) ? (screen.width-width)/2 : 0;
	y = (screen.height) ? (screen.height-height)/2 : 0;
	
	// pop the window up
	popupWin = window.open(URL, winName, "width=" + width + ", height=" + height + ", left=" + x + ", top=" + y +", toolbar=no, location=no, menubar=no, resizable=no, scrollbars=no, status=no, directories=no, menubar=no");
	
	// set focus to the pop-up window
	popupWin.focus();
}

// function to limit number of characters on textfields and text areas
function limitChars (field, maxNumChar, countField) {	
    if (field.value.length > maxNumChar) {
        field.value = field.value.substring(0, maxNumChar);
	} else {
		if (countField) {
			element = document.getElementById(countField);
			element.innerHTML = maxNumChar - field.value.length;
		}	
	}
}

//----------- Jollibee Happy Moments Functions ---------//

// function to validate user data upon registration (AJAX-based) - @vic
function checkReg (infoArea, formName, serverSidePage) {
	// hide error message
	document.getElementById(infoArea).innerHTML = "";
	
	// user must agree with the terms
	if (!document.getElementById("chk_agree").checked) {
		document.getElementById(infoArea).innerHTML = "Please tick on the box to indicate that you have read the promo mechanics.";
	}
	
	// check if birth date is correct
	birthYear = document.getElementById("sel_bdayYear").options[document.getElementById("sel_bdayYear").selectedIndex].value;
	birthMonth = document.getElementById("sel_bdayMonth").options[document.getElementById("sel_bdayMonth").selectedIndex].value;
	birthDay = document.getElementById("sel_bdayDay").options[document.getElementById("sel_bdayDay").selectedIndex].value;
	if (isDate (birthYear, birthMonth, birthDay) > 0) {
		document.getElementById(infoArea).innerHTML = "Please enter a valid date of birth.";		
	}
	
	// password fields should match.
	
	if (document.getElementById("txt_password").value != document.getElementById("txt_repeatPassword").value) {
		document.getElementById(infoArea).innerHTML = "Passwords do not match. Please check the passwords you entered.";
	}
	
	// check for empty fields and invalid email format
	checkField('txt_code', 'verification code', false, infoArea, "Please enter the code shown.");
	checkField('txt_contactNum', 'cntact number', false, infoArea, false);
	checkField('txt_lName', 'last name', false, infoArea, false);
	checkField('txt_fName', 'first name', false, infoArea, false);	
	checkField('txt_address', 'postal address', false, infoArea, false);
	checkField('txt_email', 'e-mail address', true, infoArea, "Please enter a valid e-mail address.");
	checkField('txt_repeatPassword', 'password', false, infoArea, "Please retype your password.");
	checkField('txt_password', 'password', false, infoArea, "Please enter a password for your account.");
	checkField('txt_userName', 'desired username', false, infoArea, false);
	
	// check for errors
	if (document.getElementById(infoArea).innerHTML == "") {
		// proceed with backend validation using AJAX
		// prepare array of variables for passing via post
		
		postvarUserName = new Array("username", "txt_userName");
		postvarEmail = new Array("email", "txt_email");
		postvarCode = new Array("code", "txt_code");
		postvar = new Array (postvarUserName, postvarEmail, postvarCode)
		
		// send variables through AJAX
		ajaxValidation (infoArea, formName, 'Please wait while checking your registration details...', 'Please wait while creating your account...', postvar, serverSidePage)
		
	} 

	// do not submit form (let AJAX do the form submission)
	return false;	

}

// function to check verification code when activating an account (AJAX-based) - @vic
function verifyCode (infoArea, formName, serverSidePage) {
	// hide error message
	document.getElementById(infoArea).innerHTML = "";
	
	// check for empty fields and invalid email format
	checkField('txt_vcode', 'verification code', false, infoArea, "Please enter the verification code.");
	
	// check for errors
	if (document.getElementById(infoArea).innerHTML == "") {
		// proceed with backend validation using AJAX
		
		// prepare array of variables for passing via post	
		postvarVerificationCode = new Array("verificationCode", 'txt_vcode');
		postvarVerificationURL = new Array("verificationURL", 'hdn_verificationURL');
		postvar = new Array(postvarVerificationCode, postvarVerificationURL);
		
		// send variables through AJAX
		ajaxValidation (infoArea, formName, 'Please wait while checking verification code...', 'Please wait while activating your account...', postvar, serverSidePage)
		
	} 
	
	// do not submit form (let AJAX do the form submission)
	return false;	
}

// function to validate user data upon log-in (AJAX-based) - @vic
function checkLogIn (usernameField, passwordField, infoArea, formName, serverSidePage) {
	// hide error message
	document.getElementById(infoArea).innerHTML = "";
	
	// check for empty fields and invalid email format
	checkField(passwordField, 'password', false, infoArea, false);
	checkField(usernameField, 'username', false, infoArea, false);
	
	
	// check for errors
	if (document.getElementById(infoArea).innerHTML == "") {
		// proceed with backend validation using AJAX
		
		// prepare array of variables for passing via post		
		postvarUserName = new Array("username", usernameField);
		postvarPassword = new Array("password", passwordField);
		postvar = new Array (postvarUserName, postvarPassword)
		
		// send variables through AJAX
		ajaxValidation (infoArea, formName, 'Verifying log-in details...', 'Logging in...', postvar, serverSidePage)
		
	} 

	// do not submit form (let AJAX do the form submission)
	return false;	

}

// function to show/hide entry submission forms - @vic
function showHMForm (nextStep, viewingOrSubmitting, serverSidePage) {
	// initialize variables
	errorMsg = "";

	if (viewingOrSubmitting == "submitting") {
		// hide error messages
		infoarea = "infoArea" + (nextStep - 1);
		document.getElementById(infoarea).innerHTML = "";
	 
		// check for empty field
		if (nextStep == 3) {
			checkField('text_story', 'story', false, 'infoArea2', false);
			checkField('txt_title', 'title', false, 'infoArea2', "Please enter a title for your story.");
		}
		if (nextStep == 4) {
			 if (!document.getElementById('chk_skipPhoto').checked) {
				// allow only .gif and .jpg files
				filePath = document.getElementById('file_photo').value;
				extension = filePath.substr(filePath.lastIndexOf('.')).toLowerCase();
				if (extension.lastIndexOf('jpg') == -1 && extension.lastIndexOf('jpeg') == -1 && extension.lastIndexOf('gif') == -1) {
					document.getElementById(infoarea).innerHTML = "Only .jpg and .gif files are accepted.";
				}
				checkField('file_photo', 'photo', false, 'infoArea3', "Please select your photo.");
			 }
		}
		if (nextStep == 5) {
			 if (!document.getElementById('chk_skipVideo').checked) {
				 // allow only .gif and .jpg files
				filePath = document.getElementById('file_video').value;
				extension = filePath.substr(filePath.lastIndexOf('.')).toLowerCase();
				if (extension.lastIndexOf('wmv') == -1 && extension.lastIndexOf('mov') == -1 && extension.lastIndexOf('avi') == -1 && extension.lastIndexOf('mpg') == -1 && extension.lastIndexOf('mpeg') == -1) {
					document.getElementById(infoarea).innerHTML = "Only .wmv, .mov, .avi, and .mpg files are accepted.";
				}
				 checkField('file_video', 'video', false, 'infoArea4', "Please select your video.");
			 }
		}
	 
		// check for errors
		if (nextStep > 2) {
			errorMsg = document.getElementById(infoarea).innerHTML;
		} 
	
	}
 
    if (errorMsg == "" || viewingOrSubmitting == "viewing") {
         if (nextStep < 5) {  
              // change background image of HM control panel
				if (viewingOrSubmitting == "submitting") {
					document.getElementById('HMCpanel').className = 'HMStep' + nextStep;
				} else if (viewingOrSubmitting == "viewing") {
					document.getElementById('HMCpanel').className = 'HMView' + nextStep;
				}
				// show the form
				show('entryStep', 'entryStep' + nextStep);
				//document.getElementById('entryStep' + nextStep).style.display = "block";				
				
         } else {
				
				// proceed with backend validation using AJAX
				// prepare array of variables for passing via post
				
				postvarTitle = new Array("title", "txt_title");
				postvarStory = new Array("story", "text_story");
				postvarPhoto = new Array("photo", "file_photo");
				postvarVideo = new Array("video", "file_video");
				postvar = new Array (postvarTitle, postvarStory, postvarPhoto, postvarVideo)
				
				// send variables through AJAX
				if (serverSidePage) {
					ajaxValidation ('infoArea4', 'frm_submitEntry', 'Please wait while submitting your entry...', 'Please wait while submitting your entry...', postvar, serverSidePage)
				}
          }
    }
	
	// do not submit form (let AJAX do the form submission)
	return false;		
}

// function to retrieve specific contest entries (AJAX-based) - @vic
function getEntry (entryID, serverSidePage) {
	// display wait message
	waitMsg = '<img src="./images/site_assets/icon_loading01.gif" style="margin-right: 10px; width: 32px; height: 32px; /> Loading...';
	document.getElementById('entryStory').innerHTML = waitMsg;
	
	// retrieve story
	
	// prepare array of variables for passing via post		
	postvarEntryID = new Array("userID", entryID);
	postvarEntryType = new Array("entryType", "story");
	postvar = new Array (postvarEntryID, postvarEntryType);
	
	// send variables through AJAX
	ajaxValidation ('entryStory', false, waitMsg, '', postvar, serverSidePage, true);	


	// retrieve title, date, and author of entry
	
	// prepare array of variables for passing via post		
	postvarEntryID = new Array("userID", entryID);
	postvarEntryType = new Array("entryType", "summary");
	postvar = new Array (postvarEntryID, postvarEntryType);
	
	waitMsg = '';
	
	// send variables through AJAX
	ajaxValidation ('entrySummary', false, waitMsg, '', postvar, serverSidePage, true);	

	// retrieve photo and video
	
	// prepare array of variables for passing via post		
	postvarEntryID = new Array("userID", entryID);
	postvarEntryType = new Array("entryType", "photo-video");
	postvar = new Array (postvarEntryID, postvarEntryType);
	
	waitMsg = '<div class="error" style="margin-right: 20px; width: 250px; height: 250px; text-align: left; float: left;">&nbsp;</div>';
	
	// send variables through AJAX
	ajaxValidation ('entryPhotoVideo', false, waitMsg, '', postvar, serverSidePage, true);
	

	// do not continue (let AJAX do the loading of details)
	return false;	

}

// AJAX function for server side validation (multiple field validation) - @vic
function ajaxValidation (infoArea, formName, verifyMsg, processingMsg, postvar, serverSidePage, directValue) {
	document.getElementById(infoArea).innerHTML = verifyMsg;
	var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				// alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
			
	xmlHttp.onreadystatechange = function () {
		// update info field
		document.getElementById(infoArea).innerHTML = verifyMsg;
		
		submitAJAXForm(infoArea, formName, processingMsg, xmlHttp.readyState, xmlHttp.responseText);
	}
			
	// combine post variables	
	
	for (i = 0; i < postvar.length; i++) {
		if (i==0) {
			if (directValue) {
				postVars = postvar[i][0] + "=" + postvar[i][1];
			} else {
				postVars = postvar[i][0] + "=" + document.getElementById(postvar[i][1]).value;	
			}
			
		} else {
			if (directValue) {
				postVars += "&" + postvar[i][0] + "=" + postvar[i][1];
			} else {
				postVars += "&" + postvar[i][0] + "=" + document.getElementById(postvar[i][1]).value;	
			}
		}
	}
	
	// debug	
	// alert("post variable to send = " + postVars);
		
	// open the request	
	xmlHttp.open("POST", serverSidePage ,true);
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", postVars.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.send(postVars);
	
	
}


// function to submit form used by AJAX functions - @vic
function submitAJAXForm (infoArea, formName, processingMsg, readyState, responseText) {
	// debug
	//alert(document.getElementById(infoArea).innerHTML);
	
	if (readyState == 4) {	
		document.getElementById(infoArea).innerHTML = responseText;
		if (formName && responseText == processingMsg) {
			document.getElementById(formName).submit();
		}
	}
}

// functio to check date format - @Jonas Raoni Soares Silva - http://www.joninhas.ath.cx

function isDate (y, m, d){ // v1.0
  if(typeof y == "string" && m instanceof RegExp && d){
     if(!m.test(y)) return 1;
     y = RegExp["$" + d.y], m = RegExp["$" + d.m], d = RegExp["$" + d.d];
  }
  d = Math.abs(d) || 0, m = Math.abs(m) || 0, y = Math.abs(y) || 0;
  return arguments.length != 3 ? 1 : d < 1 || d > 31 ? 2 : m < 1 || m > 12 ? 3 : /4|6|9|11/.test(m) && d == 31 ? 4
  : m == 2 && (d > ((y = !(y % 4) && (y % 1e2) || !(y % 4e2)) ? 29 : 28)) ? 5 + !!y : 0;
}

// function to pop-up a window in the center of rhe screen
function popupWindow (URL, winName, width, height) {
	// set position for the window
	x = (screen.width) ? (screen.width-width)/2 : 0;
	y = (screen.height) ? (screen.height-height)/2 : 0;
	
	// pop the window up
	popupWin = window.open(URL, winName, "width=" + width + ", height=" + height + ", left=" + x + ", top=" + y +", toolbar=no, location=no, menubar=no, resizable=no, scrollbars=no, status=no, directories=no, menubar=no");
	
	// set focus to the pop-up window
	popupWin.focus();
}