

/******************************************
  from default.aspx
******************************************/
var listOfCurrentPhotopasses= '';
function getRegistrationCompleteUrl()
{
    var sep='?';
    if (registrationCompleteUrl.indexOf('?')>=0)
        sep='&';
    return  registrationCompleteUrl + sep + 'token=' + getToken();
}

function urlDecode(utftext) {
        utftext=unescape(utftext);
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}

function queryStringGet(name) {
  if (name && window && window.location && window.location.search)
  {
        name=name.toLowerCase();
      var query = window.location.search.substring(1);
      var toks = query.split("&");
      for (var i=0;i<toks.length;i++) {
        var pair = toks[i].split("=");
        if (pair[0].toLowerCase() ==name && pair.length>1) {
          return urlDecode(pair[1]);
        }
      }
  }
  return null;
} 

var registrationCompleteUrl=queryStringGet('toURL');
if (!registrationCompleteUrl || registrationCompleteUrl.length==0)
    registrationCompleteUrl="registration_confirmation.aspx";
    
function showForgotPw() {
/*	
	//var dd1 = new YAHOO.util.DD("forgotpw");
   $('popoverShim').style.display="block";
	$('forgotpw').style.left = $('pageWrapper').offsetWidth/4;
	$('forgotpw').style.display="block";
	return false;
*/
    doHBPV('HtmlAccountToolsForgotPassword');
	var html = '';
	html += '<div id="innerForgotPw">';
	html += '<div class="header">Forgot My Password</div>';
	html += '<p>Did you forget your Password? Please enter your Email Address and First Name. We\'ll email a temporary password to you within one business day.</p>';
	
	
	
	html += '<form id="ForgotPwForm" action="" class="clear">';
	html += '<div class="errText" id="err_ForgotPwUserName">&nbsp;</div>';
	html += '<label for="ForgotPwUserName" class="reg">Email Address:</label><div class="star">*</div><input type="text" id="ForgotPwUserName" size="35" class="reg"/>';
	html += '<div class="errText" id="err_ForgotPwFirstName">&nbsp;</div>';
	html += '<label for="ForgotPwFirstName" class="reg">First Name:<br/>(Must match first name on the account)</label><div class="star">*</div><input type="text" id="ForgotPwFirstName" size="35" class="reg"/>';
	html += '</form>';
	html += '<div class="errGoofy" id="err_ForgotPwTop">';
	//html += '<img id="errimage" src="' + g_resourceFolder + 'images/goofy.gif" alt="" align="left"/>';
	html += '<div class="errText">Oops! An error has occurred.<br/>Please see comments above and resubmit.</div>';
	html += '</div>';
	html += '<div id="ForgotPwNote" class="note clear" >Note: Registration on DisneyPhotoPass.com is separate from registration on the Disney family of websites.</div>';
	html += '<br/><br/><a href="" onclick="return validateForgotPwForm();" style="border:0px"><img width="145px" height="24px" class="sendPasswordBtn" src="/skins/100147/resources/images/editor/blank.gif" border="0" onmouseover="this.style.backgroundPosition=\'1px -550px\'" onmouseout="this.style.backgroundPosition=\'0px -526px\'"/></a></div>';
	

	doPopover ('forgotPwPopover', 'Password Reset', html);	
	
	return false;
}


/******************************************
  forgotpassword
******************************************/


function validateForgotPwForm() {
	isValid = true;
	
	if ( !isValidDisneyEmail($('ForgotPwUserName').value) ) {
		$('err_ForgotPwUserName').innerHTML = Errors.INVALID_EMAIL;
		$('err_ForgotPwUserName').style.display = 'block';
		isValid = false;
	}
	if ( !isValidField( $('ForgotPwFirstName'),  $('err_ForgotPwFirstName'), 'Please enter your first name.' ) ) {
		isValid = false;
	}
	
	
	if (isValid == false) {
		$('ForgotPwNote').style.display = 'none';
		$('err_ForgotPwTop').style.display = 'block';
		doHBPV('HtmlAccountToolsForgotPasswordError');
	}
	else {
		// sdk call
		ezpJcmSdk.resetDisneyPassword( _brandID * 1, $F('ForgotPwUserName'), $F('ForgotPwFirstName'), EZP.util.Callback(this,completeResetPassword,UserExistsFail) );  
		//userExists(_brandID,$F('ForgotPwUserName'),EZP.util.Callback(this,UserExistsSuccess,UserExistsFail));
	}

	return false;
}

function UserExistsFail(obj)
{
   $('err_ForgotPwUserName').innerHTML = Errors.ACCOUNT_DOESNT_EXIST;
   $('err_ForgotPwUserName').style.display = 'block';
   doHBPV ('HtmlAccountToolsForgotPasswordError');
}

function completeResetPassword(obj)
{
	var html = '';
	html += '<div class="header">Your password has been emailed to you!</div>';
	html += '<p>Your new password has been sent to the email address you provided. This will be a temporary password that you can reset by visiting the "My Account" page after you have logged in. It usually takes a short period of time to receive your temporary password, but please allow up to one business day.</p>';
	html += '<p>Please be sure that your email service accepts emails from DisneyPhotoPass@ecommserv.com.</p>';
	html += '<a href="" class="butn" onclick="doHBLink(\'HtmlAccountToolsForgotPasswordConfContinue_Link\'); return doModalEnd(\'forgotPwPopover\');">LOG IN</a>';

	$('innerForgotPw').innerHTML = html;
	doHBPV('HtmlAccountToolsForgotPasswordConfirmation');
/*	
	// TODO:  check for real return value
	if (true)
	{
		$('ForgotPwGetInfo').style.display = 'none';
		$('ForgotPwSent').style.display = 'block';
	}
	else
	{
		$('errTop').style.display = 'block';
		$('err_ForgotPwFirstName').innerHTML =
		$('err_ForgotPwFirstName').style.display = 'block';
	}
*/
	return false;
}

function doForgotPwCreateAccount() {

	return false;
}

function doForgotPwClose() {
	$('forgotpw').style.display = 'none';
	$('popovershim').style.display='none';
	return false;
}



/******************************************
  from registration_gate
******************************************/

function checkAge(box){
	$('adult').checked = false;
	$('teen').checked = false;
	$('child').checked = false;
	box.checked = true;
}

function doContinueFromGate(){
	doHBLink('HtmlAccountToolsRegistrationGateContinue_Link');
	if ( $('adult').checked ) {
	    
		setAge('adult');
	}
	else if ( $('teen').checked ) {
		setAge('teen');
	}
	else if ( $('child').checked ) {
		setAge('child');
		location.href = 'registration_wearesorry.aspx';
		return false;
	}
	else {
		$('errAge').style.display = 'block';
		return false;
	}

	location.href = 'registration.aspx'  + window.location.search;
	return false;
}

function setAge(age) {
	var days = 365;
	var date = new Date();  // current date & time
	date.setTime ( date.getTime() + (days * 24 * 60 * 60 * 1000) );
	document.cookie = 'ezpUserAge=' + age + '; path=/; expires=' + date.toGMTString();
}

function doSignInFromGate() {
	var bContinue = true;
    doHBLink('HtmlAccountToolsRegistrationGateSignIn_Link');
	var user=$("login_username").value;
	var password=$("login_password").value;

	if ( !isValidField( $('login_username'),  $('errSignIn'), 'The email address you entered is invalid.  Please try again.') ) {
		bContinue = false;
	}
	else if ( !isValidField( $('login_password'),  $('errSignIn'), 'The password you entered is invalid.  Please try again.' ) ) {
		bContinue = false;
	}

	if ( whiteSpaceOnly(user) && whiteSpaceOnly(password) ) {
		$('errSignIn').innerHTML = 'Your Username and Password are needed in order to Sign In.  Please provide them to continue.';
		$('errSignIn').style.display = 'block';
		bContinue = false;
	}

	if (bContinue) {
		//$("btnSignIn").innerHTML = "Please Wait...";

		// sdk call
		// same as login from header, but don't reload the page on failure
		ezpJcmSdk.loginDisney( BrandId, user, password, EZP.util.Callback(null,completeLoginSuccess, completeLoginFromGateFailed) );
	}
	else
	{
	    doHBPV('HtmlAccountToolsRegistrationGateError');
	}

	return false;
}

function completeLoginFromGateFailed(obj) {
	doHBPV('HtmlAccountToolsRegistrationGateError');

	switch (obj.status) {
		case '999' :
		default :
		  var sMsg = Errors.NOT_REGISTERED;
	        if (obj._message == 'Invalid Password')
		        sMsg = Errors.INVALID_LOGIN;
		    else if (obj._message == 'Photopass Password')
		        sMsg = Errors.PHOTO_PASS_PASSWORD;
		    else if (obj._message == 'System Error')
		        sMsg = Errors.SYSTEM_ERROR;
		        
			$('errSignIn').innerHTML = sMsg;
			$('errSignIn').style.display = 'block';
	}
	//$("btnSignIn").innerHTML = "Continue";
	setToPleaseWaitBack();
	return false;
}

//  handle enter key on form, used by default.aspx and registration_gate
function handleEnterFromGate(e) {
	if ( $('login_username').value != "" || $('login_password').value != "") {
		var bEnterPressed = false;
		if ( window.event ) {
			if (window.event.keyCode == 13) { bEnterPressed = true; }
		}else if (e.which) {
			if (e.which == 13) { bEnterPressed = true; }
		}
		if (bEnterPressed) {
       		 loadLoadingMask("Loading.  Please Wait...");
		     doSignInFromGate();	
		}
	}
	return false;
}

function doLoginErrors() {
	if ( QueryString('error') != '' && QueryString('error') != null) {
	    var sMsg = Errors.NOT_REGISTERED;
	    if (QueryString('error') == 'IP')
		    sMsg = Errors.INVALID_LOGIN;
		else if (QueryString('error') == 'SE')
		    sMsg = Errors.SYSTEM_ERROR;
		else if (QueryString('error') == 'PP')
		    sMsg = Errors.PHOTO_PASS_PASSWORD;
		    
		$('errSignIn').innerHTML = sMsg;
		$('errSignIn').style.display = 'block';
	}
//	$("btnSignIn").innerHTML = "Continue";
	setToPleaseWaitBack();
}

function doAge1FromGate() {
	var age = getCookie('ezpUserAge');
	if ( age == 'child' ) {
		location.href = 'registration_wearesorry.aspx';
	}
}

function doAge2FromGate() {
	var age = getCookie('ezpUserAge');
	if (age == 'child') {
		location.href = 'registration_wearesorry.aspx';
	}
	else if (age == 'teen') {
		//$('teen').checked = true;
		//$('formChooseAge').disabled = true;
	}
	else {
		// show the page
	}
	
}

/******************************************
  from registration
******************************************/

function validatePhotoPasses()
{
	  successfulValidations = 0;
      loadLoadingMask("Validating Photo Pass...");
      if (PhotoPassesToAdd[0] != null)
      {
			for (var i=0; i<PhotoPassesToAdd.length; i++) {
	             if (!listOfCurrentPhotopasses.toUpperCase().match(PhotoPassesToAdd[i].toUpperCase()))
	               {
	               ezpJcmSdk.validPhotoPass(PhotoPassesToAdd[i], EZP.util.Callback(null, validPhotoPassAgg, validPhotoPassFail) );
	               }
	        }	
	   }
	         else
	    {
		    validPhotoPassSuccess(this);
	    }
}

function checkForWWW()
{
 
    if (Left($('Email').value.toUpperCase(),4)=='WWW.')
    {
	var yesBtn = '<a href="" onclick="validatePhotoPasses();return doModalEnd(\'alertverification\');" style="border:0px"><img width="82px" height="22px" class="yesBtn" src="/skins/100147/resources/images/editor/blank.gif" border="0" onmouseover="this.style.backgroundPosition=\'0px -645px\'" onmouseout="this.style.backgroundPosition=\'0px -620px\'"></a>';
	var noBtn = '<a href="" onclick="disableForm($(\'accountform\'),false);return doModalEnd(\'alertverification\');" style="border:0px"><img width="82px" height="22px" class="noBtn" src="/skins/100147/resources/images/editor/blank.gif" border="0" onmouseover="this.style.backgroundPosition=\'0px -694px\'" onmouseout="this.style.backgroundPosition=\'0px -669px\'"></a>';

    doPopover('alertverification', 'Email Address Verification', 'Valid email addresses do not usually begin with "www." If you register with an invalid email address, you will not be able to receive any email communication from <i>Disney\'s PhotoPass</i> team regarding your account or any orders placed online.<br/><br/>Are you sure you wish to register with this email address? If you\'re not sure, we recommend removing the "www." from the beginning of your email address to ensure a successful registration.<br/><br/>' + yesBtn + noBtn) ;
    }
    else
    {
    validatePhotoPasses();
    }
        
}

function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function submitRegisterForm() {
	disableForm($('accountform'),true)
	if (validateRegisterForm()){
	
	  checkForWWW();  
	  

	}
	else
	{
	disableForm($('accountform'),false)
	}
		
	return false;
}

var successfulValidations = 0;
function validPhotoPassAgg(obj)
{
    successfulValidations ++;
    if (successfulValidations == PhotoPassesToAdd.length)
        validPhotoPassSuccess(obj);
}

function validPhotoPassSuccess(obj)
{
    // register user
      
		// set a couple of special fields then check if the user exists
		$('BrandId').value = BrandId;
		$('UserName').value = $F('Email');
        $('MarketingOptIn').value = $('MarketingOptInDisplay').checked;
		setHiddenCountryFields();

		// sdk call
		ezpSecuritySdk.userExistsForm( EZP.util.Callback(null,completeUserExistsForm) );
}

function validPhotoPassFail(obj)
{
    //alert('photopass is not valid');
    var test;
    if (obj == 'USED_SAME_ACCOUNT')
        test = obj;
    else    
        test = obj._message;
    
    msg_invalid = "The Disney's PhotoPass ID you entered is invalid.  Please verify the PhotoPass ID and resubmit.";
    msg_claimed = "This Disney's PhotoPass ID is already associated with an account.  If you have already claimed this ID with another account, please log into that account to view your photos.";
    msg_claimedhere = "This Disney's PhotoPass ID already exists in your account. Any images associated with it will automatically populate as soon as they are available. Note: It can take up to 24 hours for your photos to be available in your account after they are taken.";
    msg_nophotos = "There are currently no photos associated with this Disney's PhotoPass ID.  Note:  It can take up to 24 hours for your photos to be available in your account after they are taken.";
    
    
    
    
    switch (test)
    {
        case 'USED':
            msg = msg_claimed;
            break;
        case 'USED_SAME_ACCOUNT':
            msg = msg_claimedhere;
            break;
        case 'VALID_NO_PHOTOS':
            msg = msg_nophotos;
            break;
        default:
            msg = msg_invalid
            break;
        
    }

    $('err_ppid0').innerHTML = msg;
		$('err_ppid0').style.display = 'block';
    $('errGoofy').style.display = 'block';
    hideLoadingMask();
    document.location="#";
    disableForm($('accountform'),false)
    
}


function completeUserExistsForm(obj) {
	//debugger;
	
	obj = String(obj);
	if (obj == 'true') {
		$('err_Email').innerHTML = Errors.ALREADY_REGISTERED;
		$('err_Email').style.display = 'block';
        hideLoadingMask();
		disableForm($('accountform'),false)
	}
	else {
		// pass empty string for pp, for now
		$('PhotoPass').value = "";

		// sdk call
		ezpJcmSdk.addDisneyContactForm( EZP.util.Callback(null, completeAddDisneyContactFormSuccess, completeAddDisneyContactFormFailed) );
	}
	return false;
}

function completeAddDisneyContactFormSuccess(obj) {
	//debugger;
	var user=$("UserName").value;
	var password=$("Password").value;
	// sdk call
	ezpJcmSdk.loginDisney( BrandId,user,password,EZP.util.Callback(null,completeNewUserLogin) );
}

function completeAddDisneyContactFormFailed(obj) {
	//debugger;
	$('err_Email').innerHTML = obj.statusText;
	$('err_Email').style.display = 'block';
	$('errGoofy').style.display = 'block';
    hideLoadingMask();
	disableForm($('accountform'),false)
}

function completeNewUserLogin(obj) {
	obj = String(obj);
	if (obj != 'false') {
		setToken(obj);

		// TODO: add photopass ids to account
		successfulAdds = 0;
		if ( PhotoPassesToAdd.length > 0 ) {
		
		for (var i=0; i<PhotoPassesToAdd.length; i++) {
			ezpJcmSdk.addPhotoPassToAccount( getToken(), PhotoPassesToAdd[i], EZP.util.Callback(null, completeAddPhotoPassAgg, completeAddPhotoPassFailed) );
            }
		}
		else {
			location.href=getRegistrationCompleteUrl();
		}
	}
	else {
		alert("The system encountered an error logging you in.");
		hideLoadingMask();
	}
	return false;
}

var successfulAdds = 0;
function completeAddPhotoPassAgg(obj)
{
    successfulAdds ++;
    if (successfulAdds == PhotoPassesToAdd.length)
        completeAddPhotoPassSuccess(obj);
}


function completeAddPhotoPassSuccess(obj) {
    location.href=getRegistrationCompleteUrl();
}

function completeAddPhotoPassFailed(obj) {
   
    alert('ERROR - Your account has been created, but the Disney\'s PhotoPass was not properly associated.');
    
		hideLoadingMask();
    disableForm($('accountform'),false);
    	location.href=getRegistrationCompleteUrl();
}


function validateRegisterForm() {
	var isValid = true;

	if ( !isValidField( $('Email'),  $('err_Email'), 'Enter your Email Address to complete registration.' ) ) {
		isValid = false;
	}
	else if ( !isValidDisneyEmail($('Email').value) ) {
		$('err_Email').innerHTML = Errors.INVALID_EMAIL;
		$('err_Email').style.display = 'block';
		isValid = false;
	}

	if ( !isValidField( $('reemail'),  $('err_reemail'), 'Retype your Email Address for validation.' ) ) {
		isValid = false;
	}

	if ( $F('Email').toLowerCase() != $F('reemail').toLowerCase() ){
		$('err_reemail').innerHTML = 'The validation Email Address is not the same as the first Email address entered.  Please confirm the addresses.';
		$('err_reemail').style.display = 'block';
		isValid = false;
	}

	if ( !isValidField( $('Password'),  $('err_Password'), 'Enter your Password to complete registration.' ) ) {
		isValid = false;
	}
	else if ( !isValidPassword($('Password').value) ) {
		$('err_Password').innerHTML = 'The Password entered is invalid.  Please try again.';
		$('err_Password').style.display = 'block';
		isValid = false;
	}

	if ( $F('Password') != $F('repassword') ){
		$('err_repassword').innerHTML = 'The validation Password is not the same as the first password entered.  Please confirm the passwords.';
		$('err_repassword').style.display = 'block';
		isValid = false;
	}

	if ( !validatePhotoPassIds() ) {
		isValid = false;
	}

	if ( !isValidField( $('FirstName'),  $('err_FirstName'), 'First Name field must not be blank.' ) ) {
		isValid = false;
	}
    
    if ( !isValidField( $('LastName'),  $('err_LastName'), 'Last Name field must not be blank.' ) ) {
		isValid = false;
	}
    
     if ( !isValidField( $('PhoneNumber'),  $('err_PhoneNumber'), 'Phone Number field must not be blank.' ) ) {
		isValid = false;
	}
    
    
     if ( !isValidField( $('ShippingAddress1'),  $('err_ShippingAddress1'), 'Address field must not be blank.' ) ) {
		isValid = false;
	}
    
      if ( !isValidField( $('ShippingCity'),  $('err_ShippingCity'), 'City field must not be blank.' ) ) {
		isValid = false;
	}
    
   	if ( !isValidSelect( $('ShippingCountry'),  $('err_ShippingCountry'), 'Country field must be selected.' ) ) {
		isValid = false;
	}
	
	if ( $F('ShippingCountry') == 'USA' || $('ShippingCountry').value == '') 
	    {
	    
	     if ( !isValidSelect( $('state'),  $('err_state'), 'State field must be selected.' ) ) {
		    isValid = false;
		    }
		    if ( !isValidField( $('zip'),  $('err_zip'), 'Zip Code field must not be blank.' ) ) {
	    	    isValid = false;
	        }
	    }
	    else if ( $F('ShippingCountry') == 'CAN' ) {
		   if ( !isValidSelect( $('province_ca'),  $('err_province_ca'), 'Province field must be selected.' ) ) {
		    isValid = false;
		    }
		    if ( !isValidField( $('postal_ca'),  $('err_postal_ca'), 'Postal Code field must not be blank.' ) ) {
	    	    isValid = false;
	        }
	    }
	    else {
	      if ( !isValidField( $('postal'),  $('err_postal'), 'Postal Code field must not be blank.' ) ) {
	    	    isValid = false;
	        }
	    }
	if ( ! isValid ) {
		$('errGoofy').style.display = 'block';
	}

	return isValid;
}

var PhotoPassesToAdd = new Array();
function validatePhotoPassIds() {
/*
	from PhotoPassFunctSpec_07_12_06_HTML.doc:
	"The following characters are not allowed to be used in the 2nd, 3rd, and 4th fields of a PhotoPass ID -> Z,1,I,O,0,2,S,5,B,8. All characters are allowed in the 1st field."
*/
    PhotoPassesToAdd = new Array();
	var isValidForm = true;
	

	var allboxes = $A( getElementsByClassName($('ppWrapper'), 'input', 'pp') ); // get all the boxes
	allboxes.each( function(onebox) {
		if (onebox.value != "" && parseInt(onebox.id.substring(6,7))==0) {	// if a box has a value and it's the first box in its group
			var isValidPass = true;

			// get the group
			var group = new Array();
			group[0] = onebox;
			group[1] = getNextPhotoPassBox(group[0]);
			group[2] = getNextPhotoPassBox(group[1]);
			group[3] = getNextPhotoPassBox(group[2]);
			group = $A(group);

			// check each box in the group
			group.each( function(box) {
				if (whiteSpaceOnly(box.value) || box.value.length!=4) {
					isValidPass = false;
				}
		
			})

			var pass = '';
			if (isValidPass) {
				group.each( function(box) {	 // concatenate the photopass
					pass += box.value;
				})
				PhotoPassesToAdd.push(pass); // store it for later
			}
			else {
				isValidForm = false;
			}

		}
	})

	if (!isValidForm) {
		$('err_ppid0').innerHTML = Errors.INVALID_PHOTOPASSID;
		$('err_ppid0').style.display = 'block';
	}
	return isValidForm;
}


function isValidPassword(val) {
	var s = new String(val);
	var re = /^[a-zA-Z0-9]{6,30}$/;	// matches 6 or more alpha-numeric characters
	return re.test(s);
}

function clearErrPassword(elem) {
	if ( isValidPassword(elem.value) ) {
		$('err_' + elem.id).innerHTML = '';
		$('err_' + elem.id).style.display = 'none';
	}
}

function clearErrEmail(elem) {
	if ( isValidDisneyEmail(elem.value) ) {
		$('err_' + elem.id).innerHTML = '';
		$('err_' + elem.id).style.display = 'none';
	}
}

function clearErrPhotoPassId(errId) {
	if ( !$(errId).innerHTML == '' ) {	//don't call validate if the err is not currently displayed
		if ( validatePhotoPassIds() ) {
			$(errId).innerHTML = '';
			$(errId).style.display = 'none';
		}
	}
}

var LastPPBox = 1;
function addAnotherId() {
	if (LastPPBox > 8) {
		alert('Maximum number of entries is 9.  You will have the opportunity to add more ID numbers after you complete registration.');
		return false;
	}
	else {
		$('pp_group' + ++LastPPBox).style.display = 'block';
		$('ppid' + LastPPBox + '_0').focus();
		return false;
	}
}


function setHiddenCountryFields() {
	if ( $F('ShippingCountry') == 'USA' || $('ShippingCountry').value == '') {
		$('ShippingStateProvince').value = $('state').value;
		$('ShippingPostalCode').value = $('zip').value;
	}
	else if ( $F('ShippingCountry') == 'CAN' ) {
		$('ShippingStateProvince').value = $('province_ca').value;
		$('ShippingPostalCode').value = $('postal_ca').value;
	}
	else {
		$('ShippingStateProvince').value = $('province').value;
		$('ShippingPostalCode').value = $('postal').value;
	}
}

function doAge1(){
    
	var age = getCookie('ezpUserAge');
	if ( age == 'child' ) {
		location.href = 'registration_wearesorry.aspx';
	}
	else if ( !(age == 'teen' || age == 'adult') ) {
		location.href = 'registration_gate.aspx';
	}
	else {
		// show the page
	}
}

function doAge2(){
    
	var age = getCookie('ezpUserAge');
	if (age == 'child') {
		location.href = 'registration_wearesorry.aspx';
	}
	else if (age == 'teen') {
		// show the page
		
		$('tbluptodatecol').style.display = 'none';
	    try{
		_hbPageView('HtmlAccountToolsRegistrationTeen');
		}
		catch(err)
		{
		
		}
	}
	else if (age == 'adult') {
		try{
		_hbPageView('HtmlAccountToolsRegistrationAdult');
		}
		catch(err)
		{
		}
		// show the page and 3rd column
		$('uptodatecol').style.display = 'block';
	}
	else {
		location.href = 'registration_gate.aspx';
	}
}

function callAutoFocus(elem) {
	var nextId = getNextPhotoPassBoxId(elem);
	//window.status=nextId;
	return autoFocus(elem, 4, nextId, event);
}

function getNextPhotoPassBoxId(elem) {
	var nextId = parseInt(elem.id.substring(6,7));
	nextId = elem.id.replace(/^(ppid\d_)\d$/, "$1" + ++nextId);
	return nextId;
}

function getNextPhotoPassBox(elem) {
	return $(getNextPhotoPassBoxId(elem));
}

function attachAutoFocus() {
	var theTag = 'input';
	var theClass = 'pp';

	var aElem = document.getElementsByTagName(theTag);

	for (var i=0; i<aElem.length; i++) {
		if (aElem[i].className && aElem[i].className.match(new RegExp('\\b'+theClass+'\\b'))) {
			aElem[i].onkeyup = function() {
				callAutoFocus(this); clearErrPhotoPassId('err_ppid0');
			}
		}
	}
	return false;
}


/******************************************
  from registration_update
******************************************/
function displayThirdColumn() {
	 displayFender('rightfender','bottomfender');
	var age = getCookie('ezpUserAge');
	
	if (age != 'teen') {
		$('uptodatecol').style.display = 'block';
	}
	else
	{
		$('tbluptodatecol').style.display = 'none';
	}
}

function doGetContactInfo() {
	// sdk call
	ezpRegistrationSdk.getContact( getToken(), EZP.util.Callback(null,completeGetContactInfo) );
}

// define a global var to cache contact info
var g_ContactInfo = null;
function completeGetContactInfo(obj) {
	g_ContactInfo = obj;
	sToken = getToken();
    ezpJcmSdk.photoPassGet(sToken,EZP.util.Callback(null,showPhotoPasses));
	$("Token").value=sToken;
    $("PhoneNumber").value=obj.PhoneNumber;
	$("CustomerID").value=obj.CustomerID;
	$("FirstName").value=obj.FirstName;
	$("LastName").value=obj.LastName;
	$("Email").value=obj.Email;
	$("reemail").value=obj.Email;
    $('MarketingOptIn').value = obj.MarketingOptIn;
    var optIn =  document.getElementById('MarketingOptInDisplay');
    if (obj.MarketingOptIn == true)
       { 
        optIn.checked = true;
       }
    else{optIn.checked = false;}
        //$('MarketingOptIn').checked = 'checked';
    
	// don't actually have the pw, just make it look like 6 chars
	$("Password").value='xxxxxx';
	$("repassword").value='xxxxxx';

	$("ShippingAddress1").value=obj.ShippingAddress.Address1;
	$("ShippingAddress2").value=obj.ShippingAddress.Address2;
	$("ShippingCity").value=obj.ShippingAddress.City;

	var country = trim(obj.ShippingAddress.Country);
	$("ShippingCountry").value = country;

	if ( country == 'USA' ) {
		$("state").value = obj.ShippingAddress.StateProvince;
		$("zip").value = obj.ShippingAddress.PostalCode;
	}
	else if ( country == 'CAN' ) {
		$("province_ca").value = obj.ShippingAddress.StateProvince;
		$("postal_ca").value = obj.ShippingAddress.PostalCode;
	}
	else {
		$("province").value = obj.ShippingAddress.StateProvince;
		$("postal").value = obj.ShippingAddress.PostalCode;
	}

	showCountryFields();
}
function showPhotoPasses(obj)
 {
   var sIDs = "";
   var sID = "";
    for(var i=0; i<obj.length; i++)
    {
        listOfCurrentPhotopasses += "," + obj[i];
       sID += obj[i].substring(0,4) + '-';
       sID += obj[i].substring(4,8) + '-';
       sID += obj[i].substring(8,12) + '-';
       sID += obj[i].substring(12,16);
       sIDs += sID + '<br/>';
       sID = '';
    }
    $('photopasses').style.display = 'block';
    $('photopasses').innerHTML = sIDs;
 }
 

function doUpdateContactForm() {
	disableForm($('accountform'),true)
	if (validateRegisterForm()){
        successfulAdds = 0;
        successfulValidations = 0;
        if (PhotoPassesToAdd[0] != null)
          {
                
            loadLoadingMask("Please Wait...");
    	   
    	   
			    for (var i=0; i<PhotoPassesToAdd.length; i++) {
			    if (!listOfCurrentPhotopasses.toUpperCase().match(PhotoPassesToAdd[i].toUpperCase()))
			    {
	                   ezpJcmSdk.validPhotoPass(PhotoPassesToAdd[i], EZP.util.Callback(null, validPhotoPassUpdateAgg, validPhotoPassFail) );
	                   }
	                   else
	                   {
	                        
	                        validPhotoPassFail('USED_SAME_ACCOUNT');
	                   }
	                }	
	       }
	       else
	            validPhotoPassUpdateSuccess(this);
       

//debugger;

		
	    
	}
	else
	    disableForm($('accountform'),false);

	return false;
}


function validPhotoPassUpdateAgg(obj)
{

    successfulValidations ++;
    if (successfulValidations == PhotoPassesToAdd.length)
        validPhotoPassUpdateSuccess(obj);
}

function validPhotoPassUpdateSuccess(obj)
{

    	$('BrandId').value = BrandId;
		$('UserName').value = $F('Email');
		$('MarketingOptIn').value = $('MarketingOptInDisplay').checked;
		setHiddenCountryFields();
      
		if ( g_ContactInfo.Email != $F('Email') ) {	// changing their email address
			// sdk call
			ezpSecuritySdk.userExistsForm( EZP.util.Callback(null,completeUpdateContactUserExists) );
		}
		else if ($F('Password') != 'xxxxxx') {	// changing their password
			// sdk call
			ezpSecuritySdk.validPassword($F('Password'), EZP.util.Callback(null,completeUpdateContactValidPassword) );
		}
		else {
			// sdk call
			ezpJcmSdk.updateDisneyContactForm( EZP.util.Callback(null,completeUpdateContactForm) );
		}
		disableForm($('accountform'),false);
}


function completeUpdateContactValidPassword(obj) {
	obj = String(obj);
	if (obj == 'true') {
		ezpSecuritySdk.setUserPassword(getToken(), $F('Password'), EZP.util.Callback(null,completeUpdateContactChangePassword) );
	}
	else {
		// sdk call
		$('err_Email').innerHTML = "Invalid Password";
		$('err_Email').style.display = 'block';
	}
	return false;
}

function completeUpdateContactChangePassword(obj) {
	obj = String(obj);
	if (obj == 'true') {
		ezpJcmSdk.updateDisneyContactForm( EZP.util.Callback(null,completeUpdateContactForm) );
	}
	else {
		// sdk call
		$('err_Email').innerHTML = "Password Change Failed";
		$('err_Email').style.display = 'block';
	}
	return false;
}

function completeUpdateContactUserExists(obj) {
	obj = String(obj);
	if (obj == 'true') {
		disableForm($('accountform'),false);
		$('err_Email').innerHTML = Errors.ALREADY_REGISTERED;
		$('err_Email').style.display = 'block';
	}
	else {
		// changing their email, also changing pw?
		if ($F('Password') != 'xxxxxx') {	// changing their password
			// sdk call
			ezpSecuritySdk.validPassword($F('Password'), EZP.util.Callback(null,completeUpdateContactValidPassword) );
		}
		else {
			// sdk call
			ezpJcmSdk.updateDisneyContactForm( EZP.util.Callback(null,completeUpdateContactForm) );
			
		}
	}
	return false;
}

function completeUpdateContactForm(obj) {
	
	
	obj = String(obj);
	if (obj != 'false') {
		
		if ( PhotoPassesToAdd.length > 0 ) {
		
		for (var i=0; i<PhotoPassesToAdd.length; i++) {
			ezpJcmSdk.addPhotoPassToAccount( getToken(), PhotoPassesToAdd[i], EZP.util.Callback(null, completeAddPhotoPassUpdateAgg, validPhotoPassFail) );
            }
		}
		else {
			completeAddPhotoPassUpdateSuccess(obj);
		}
		
		
	}
	else {
		alert('Not updated');
	}
	return false;
}

function completeAddPhotoPassUpdateAgg(obj)
{
    successfulAdds ++;
    if (successfulAdds == PhotoPassesToAdd.length)
        completeAddPhotoPassUpdateSuccess(obj);
}
function completeAddPhotoPassUpdateSuccess(obj)
{
    location.href="registration_confirmation.aspx?updated=true";
}
/******************************************
  from registration_confirmation
******************************************/

function doGetUserName() {
	// sdk call
	ezpRegistrationSdk.getContact( getToken(), EZP.util.Callback(null,completeGetUserName) );
}

function completeGetUserName(obj) {
	$('userName').innerHTML = 	String(obj.FirstName);
}

function doConfirmationMessage() {
	if ( QueryString("updated") == "true" ) {
	    doHBPV('HtmlAccountToolsRegistrationUpdateConfirmation');
		$('confirmAccountTitle').innerHTML = "YOUR ACCOUNT";
		$('confirmAccountHeader').innerHTML = '<span id="userName"></span>, your account has been updated!';
		$('confirmAccountContent').innerHTML = 'Thank you for updating your DisneyPhotoPass.com account. Your changes have been saved and will be reflected the next time you select the "My Account" link.<br/><br/><a href="photopass.aspx" style="border:0px"><img width="107px" height="34px" src="/skins/100147/resources/images/1x1.gif" border="0" class="continueBtn" onmouseover="this.style.backgroundPosition=\'0px -34px\'" onmouseout="this.style.backgroundPosition=\'0px 0px\'"/></a>';
		
	}
	else
	{
	    var toURL = getCookie('toURL');
        document.cookie = 'toURL=' ;
    
        if (toURL == '')
            toURL = 'photoalbum.aspx';
        
        $('getstarted').href = toURL;
    }
    $('confirmationContainer').style.display = 'block';

}

function DoShowOrderHistory()
{
       
  ezpDPPSdk.getOrderHistory(getToken(),EZP.util.Callback(this,ShowOrderHistory,FailResult));
            
}
 
 function ShowOrderHistory(obj)
{
   
    if (obj.orders.length == 0)
    {
     $('orderhistorylaunch').style.display='block';
     $('ordermessage').innerHTML = 'You have 0 orders placed';
    } 
    else
    {
        $('orderhistorylaunch').style.display='block';
        
        var sOrder = ' orders.';
        if (obj.orders.length == 1)
            sOrder = ' order.';
        $('ordermessage').innerHTML = 'You have placed ' + obj.orders.length + sOrder;
        $('ordermessage').innerHTML += '<br/><br/><a href="orderhistory.aspx" style="border:0"><img width="149px" height="24px" id="checkOrderStatus"class="checkOrderStatus" src="/skins/100147/resources/images/1x1.gif" border="0"   onmouseover="this.style.backgroundPosition=\'0px -1013px\'" onmouseout="this.style.backgroundPosition=\'0px -988px\'"/></a>';
    }
   
}

function FailResult(obj)
{

}

function DoShowDigitalDownload()
{
  getJobData('536',_acct,'DisplayDigitalLink');
}

function DisplayDigitalLink(obj)
{
if (obj.jobs.length > 0)
{
    $('digitaldownloadlaunch').style.display='block';
     $('digitaldownloadmessage').innerHTML = 'Your Disney PhotoDownload(s) are ready!<br/><br/><a href="digitallocker.aspx" style="border:none;"><img border="0" src="/skins/100147/resources/images/digitalbutton.gif"/></a>';
     }
}

function checkforredirect()
{
    var myToURL=queryStringGet('toURL');
   
    if (!myToURL || myToURL.length==0)
        myToURL="";
    else
        document.cookie = 'toURL=' + myToURL;   
    
}