/* JavaScript/ActionScript API
 * The JavaScript/ActionScript API facilitates interaction between the Flash movie and the web page in which it resides.
 *
 * The following functions can be invoked by the Flash movie:
 *
 * •	_ddTrack
 * •	_ddLink
 * •	_ddShowCard
 * •	_ddFindStore
 *
 * The Flash movie will use ActionScript’s ExternalInterface to interact with JavaScript on the containing page.
 * Note that the Flash embed must set  * allowScriptAccess to "always" for the JavaScript/ActionScript API to work.
 *
 * Function: _ddTrack
 * This function allows the Flash movie to fire tracking events. It then delegates to the Google Analytics _trackPageview() function.
 * Expects
 * PageLabel: a value that corresponds to the Google Analytics page label specified in the measurement plan for the event to be tracked.
 * Returns
 * Nothing.
 *
 * Function: _ ddLink
 * This function allows the Flash movie to direct the browser to another URL, optionally in a new window.
 * Expects
 * Url: the URL to which the browser window should open.
 * NewWindow: indicates whether a new browser window should be spawned.
 * Returns
 * Nothing.
 *
 * Function: _ ddShowCard
 * This function allows the Flash movie to display the E-card component.
 * This function will be patterned after the solution implemented for Bases Loaded: it will do some
 * JavaScript/div/iframe devilry (perhaps using ThickBox) to show the invite form/preview/confirm screens.
 * Expects
 * Nothing.
 * Returns
 * Nothing.
 *
 * Function: _ ddFindStore
 * This function allows the Flash movie to transfer control to the Store Locator on DunkinDonuts.com with a user-supplied ZIP code.
 * Expects
 * ZipCode: a five-digit USPS ZIP code
 * Returns
 * Nothing.
 *
 */
 
 /* global cachePath variable */
 var cachePath = '/assets/v1/';
 if(glCachePath != 'undefined') {
 	cachePath = glCachePath;
 }

 /* onload events */
 window.onload = function() {
 	// attach validation to form
 	if($('dd_ecardForm')) {
 		ecardForm = $('dd_ecardForm');
 		ecardForm.onsubmit = function() { 
 			return _ddValidateEcardForm();
 		}
 	}
 	// load flash
 	if($('ddGlFlash')) {
		var flashvars = {CachePath: cachePath};
		var params = {
			wmode: "transparent",
			allowscriptaccess: "always",
			allowfullscreen: "false",
			quality: "high",
			bgcolor: "#FFFFFF"
		};
		var attributes = {id: "dd_gl_flashcontent",name: "dd_gl_flashcontent"};
		swfobject.embedSWF(cachePath+'swf/shell.swf', "ddGlFlash", "100%", "650", "9.0.0","",flashvars,params,attributes);
 	}
 	// alternate content timeout
 	setTimeout("if($('ddGlAlternate')) {$('ddGlAlternate').style.display = 'block';}",3000);
 	// preload a few images
 	if($('ecardLoad')) {
 		var ecLoad = new Array();
 		var loadStr = '';
 		ecLoad[0] = cachePath+'images/ec_background_friends.png';
 		ecLoad[1] = cachePath+'images/ec_background_truth.png';
 		ecLoad[2] = cachePath+'images/ec_background_toldyouso.png';
 		ecLoad[3] = cachePath+'images/ec_background_friends.gif';
 		ecLoad[4] = cachePath+'images/ec_background_truth.gif';
 		ecLoad[5] = cachePath+'images/ec_background_toldyouso.gif'; 		
 		
 		for(i=0;i<ecLoad.length;i++) {
 			loadStr += '<img src="'+ecLoad[i]+'" border="0" alt="">';
 		}
 		$('ecardLoad').innerHTML = loadStr;
 	}
 		
 }
 
 function _ddTrack(PageLabel) {
 	//alert('_ddTrack invoked. PageLabel:' + PageLabel);
 	pageTracker._trackPageview(PageLabel);
 }

 function _ddLink(Url, NewWindow) {
 	//alert('_ddLink invoked. Url:'+Url+' NewWindow:'+NewWindow);
 	if(NewWindow == "location")
	{
		window.location = Url;
	}
	else
	{
		var popup = window.open(Url);
		if(!popup) {
			alert("Looks like you've got a pop-up blocker that's preventing you from opening this link. Please disable it and try again.");
		}
	}
 }
 
function _ddSegment(arg)
{
	//alert('_ddSegment invoked. arg:' + arg);
	pageTracker._setVar(arg);
}

 function _ddShowCard(card) {
 	switch(card) {
 		case "1":
 			$('ecardType').className = 'eCard_truth';
 			$('ddGlCardType').value = '1';
 			break;
 		case "2":
 			$('ecardType').className = 'eCard_friends';
 			$('ddGlCardType').value = '2';
 			break;
 		case "3":
 			$('ecardType').className = 'eCard_toldyouso';
 			$('ddGlCardType').value = '3';
 			break;
 		default:
 			// no card type passed
 			$('ecardType').className = 'eCard_truth';
 			$('ddGlCardType').value = '1';
 			break; 			
 	}
 	scroll(0,0);
 	$('ddOpacity').style.display = 'block';
 	$('ddEcard').style.display = 'block';
 }
 
 function _ddHideCard() {
 	$('ddEcard').style.display = 'none';
 	$('ddEcardResponse').innerHTML = '';
 	$('ddEcardResponse').style.display = 'none';
 	$('ddOpacity').style.display = 'none';
 	_ddResetCard();
 }

 function _ddFindStore(ZipCode) {
 	//alert('_ddFindStore invoked. ZipCode:' + ZipCode);
 	if(ZipCode != 'enter your zip') {
 		window.open('https://www.dunkindonuts.com/aboutus/store/Search.aspx?zipcode='+ZipCode);
 	}
 }

 function $(strId) {
 	if(document.getElementById(strId)) {
 		return document.getElementById(strId);
 	}
 }
 
 function _ddValidateEcardForm() {
 	var fEmail = $('ddEcFriendEmail').value;
 	var yEmail = $('ddEcYourEmail').value;
 	var yName = $('ddEcName').value;
 	var arrFemails = fEmail.split(',');
 	var invFemails = new Array();
 	var invFemailcount = 0;
 	var errorCtnt = '<div class="ecErrorTop"></div><span><a href="javascript:_ddCloseEcardErr();"></a><b>Please fix the following errors</b><br><br>';
 	var flag = true;
 	
 	// all required fields
 	if((yName == '')||(yEmail == '')||(fEmail == '')) {
 		errorCtnt+=('- Please complete all the required fields.'+'<br /><br />');
 		flag = false;
 	} 
 	
 	// friends email(s)
 	if(fEmail != ''){
		for(i=0;i<arrFemails.length;i++) {
			if(!isValidEmail(arrFemails[i])) {
				invFemails[invFemailcount] = arrFemails[i];
				invFemailcount++;
				flag = false;
			}
			if(i>9) {
				errorCtnt+=('- A limit of 10 email addresses may be entered at a time. Each email address must be separated with a comma.'+'<br />'+'<br />');
				flag = false;
				break;
			}
		}
	}
 	if(invFemails.length > 0) {
 		errorCtnt+=('- The email address you entered is not in a valid format. Please try again. (Emails should be xx@xx.xx to be in valid format).<br />');
 		for(j=0;j<invFemailcount;j++) {
 			errorCtnt+=('&nbsp; &nbsp; Invalid email: <b>'+invFemails[j]+'</b><br>');
 		}
 	}
 	
 	// your email
 	if((yEmail != '')&&(!isValidEmail(yEmail))) {
 		errorCtnt+=('<br>- The email address you entered is not in a valid format. Please try again. (Emails should be xx@xx.xx to be in valid format).<br />');
 		errorCtnt+=('&nbsp; &nbsp;  Invalid email: <b>'+yEmail+'</b><br /><br />');
 		flag = false;
 	}
 	
 	
 	if(!flag) {
 		errorCtnt+=('</span><div class="ecErrorBot"></div>');
 		$('ecError').innerHTML = errorCtnt;
 		$('ecError').style.display = "block";
 	}
 	if(flag==true) {
 		_ddCloseEcardErr();
 		_ddGetEmailResponse();
 	}
 	return flag;
 }
 
 var responseCount = 0;
 function _ddGetEmailResponse() {
 	setTimeout("_ddCheckResponseVar();",500); // check frame every 1/2 second
 }
 
 function _ddCheckResponseVar() {
 	if(responseCount > 120) { // set one minute time out
 		_ddDisplayEmailServerFailure();
 	}
 	else {
		responseCount++;
		if(window.ddGlEmailFrame.emailResponse != undefined) {
			// we have response
			if(window.ddGlEmailFrame.emailResponse == '1') {
				_ddDisplayEmailFailure();
			} else if(window.ddGlEmailFrame.emailResponse == '0') {
				
				if ($('ddGlCardType').value == '1') {
					_ddTrack('/INTERACTIONS/SEND TRUTH IS OUT ECARD');
				} else if ($('ddGlCardType').value == '2') {
					_ddTrack('/INTERACTIONS/SEND FRIENDS DONT LET FRIENDS ECARD');					
				} else if ($('ddGlCardType').value == '3') {
					_ddTrack('/INTERACTIONS/SEND TOLD YOU SO ECARD'); 					
				}
					
				var toEmail = $('ddEcFriendEmail').value;
				var arrToEmail = toEmail.split(',');

 	            _ddTrack('/INTERACTIONS/ECARD SENT CONFIRMATION');
				_ddTrack('/NUMBER OF ECARD RECIPIENTS/' + arrToEmail.length);
					
				_ddDisplayEmailSuccess();
			}
			responseCount = 0;
			$('ddGlEmailFrame').src = 'emails/blank.html';
		} else {	
			// no response yet, check again
			_ddGetEmailResponse();
		}
	}
 }
 
 function _ddResetCard() {
 	$('eCardMsg').innerHTML = '';
 	$('ecError').innerHTML = '';
 	$('eCardCtnt').style.display = "block";
 	$('ddEcFriendEmail').value = '';
 	$('ddEcName').value = '';
 	$('ddEcYourEmail').value = '';
 	$('ddEcCC').checked = false;
 }
 
 function _ddDisplayEmailSuccess() {
 	var emailValue = $('ddEcFriendEmail').value;
 	var emails = emailValue.split(',');
 	var strEmails = '';
 	for(i=0;i<emails.length;i++) {
 		strEmails += '{'+emails[i].trim() + '}<br>';
 	}
 	$('eCardCtnt').style.display = "none";
 	$('eCardMsg').innerHTML = '<div>You have successfully sent your chosen ecard to:<br>'+strEmails+'<br><br><a href="javascript:_ddHideCard();"><img src="'+cachePath+'images/ec_closebtn.gif" border="0" alt=""></a></div>';
 }
 
 function _ddDisplayEmailFailure() {
 	$('eCardCtnt').style.display = "none";
 	$('eCardMsg').innerHTML = '<div>We are currently experiencing technical difficulties and this email could not be sent.<br>Please try again later.<br><br><a href="javascript:_ddHideCard();"><img src="'+cachePath+'images/ec_closebtn.gif" border="0" alt=""></a></div>';
 } 
 
 function _ddDisplayEmailServerFailure() {
 	$('eCardCtnt').style.display = "none";
 	$('eCardMsg').innerHTML = '<div>We are currently experiencing technical difficulties and this email could not be sent.<br>Please try again later.<br><br><a href="javascript:_ddHideCard();"><img src="'+cachePath+'images/ec_closebtn.gif" border="0" alt=""></a></div>';
 }  
 
 function _ddCloseEcardErr() {
 	$('ecError').innerHTML = '';
 	$('ecError').style.display = "none";
 }
 
 function isValidEmail(val){
 	var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
 	if (!val.match(re)) {
 		return false;
 	} else {
 		return true;
 	}
 }
 
 String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };


