/* ---------------------------------------------------------------
   Author : Remi Palard
   january 2007
   remi.palard@gmail.com  
/* --------------------------------------------------------------- */

Event.observe(window, 'load', initLoad, false);
var GFF, MPTH, CATH;

// Please Keep the session after a jsp login
var Session = {'gift' : '', 'isGFF' : false, 'miles' : '1', 'gffFirstname' : 'Remi', 'gffLastname' : 'Palard', 'gffCust1' : '123', 'gffCust2' : '456', 'gffCust3' : '789'}

var isInitCompleted = false;

/* --------------------------------------------------------------- */  

function initLoad() {
	// Gift For friends popup
	GFF = new GiftForFriend();
	// For confirm Adress page navigation
	CATH = new t08_confirmAddress();
	if(typeof( window[ 'memberProfileData' ] ) != "undefined")
	{
		MPExtend.prototype = new memberProfile();
		MPExtend.prototype.constructor = MPExtend;
		MPExtend.prototype.parent = memberProfile.prototype;
	}
	CAExtend.prototype = new r08_confirmAddress();
	CAExtend.prototype.constructor = CAExtend;
	CAExtend.prototype.parent = r08_confirmAddress.prototype;
	
	// Member profile
	MPTH = new MPExtend();
	ConfirmProfile = new CAExtend();
		
	isInitCompleted = true;
	// For demo only
	//Layer.init('threshold', 't08_threshold.html');	
}

function displayAddress(){
	var delay = 0;
	while(!isInitCompleted && delay < 1000){
		delay += 300;
		pausecomp(300);
	}
	
	if(!isInitCompleted) initLoad();
	
	CATH.display();
}
	
/* --------------------------------------------------------------- */
// Member Profile functions
/* --------------------------------------------------------------- */

var t08_confirmAddress = Class.create();
t08_confirmAddress.prototype = {
	
	initialize: function() {
		this.displayPH = 't08_addressPH';
		this.editPH = 't08_editAddressPH';			
	},
	
	display: function() {
		
		while(!isInitCompleted){
			 pausecomp(300);
		}
		
		// Load URL
		if (Session['isGFF'] == true) this.displayURL = '/renom08/ThresholdGFFDisplayAddress_Ajax.jsp';		
		else this.displayURL = '/renom08/ThresholdDisplayAddress_Ajax.jsp';					
		
		var ajax = new Ajax.Updater( {success: this.displayPH}, this.displayURL, {
				method: 'get', 
				asynchronous:true,						
				onLoading : function() { 
					//Element.hide(container); 
					//Element.show(spinner);
				},
				onComplete : this.displayPageIsLoaded.bind(this),	
				onFailure: function() {
					Element.update(this.displayPH, 'Loading Error');
				}
			});		
	},
	
	displayPageIsLoaded: function () {
		
		$('fadeLayer').onclick = startThresholdStepCancel;
		$('r08_benefitsCloseText').onclick = startThresholdStepCancel;
		$('r08_benefitsCloseButton').onclick = startThresholdStepCancel;	
		
		// Show block        
		Element.hide(this.editPH);		
		Element.show(this.displayPH);      
		
		// For classic gift booking
		if (Session['isGFF'] != true) MPTH.verifyProfile();
		
		// Scroller
		Sc.start('r08_contentCATH','r08_containerCATH','r08_scrollerCATH','r08_scrollAreaCATH');				
	},
	
	edit: function () {
		
		this.editURL = '/renom08/ThresholdEditAddress_Ajax.jsp';
		var ajax = new Ajax.Updater( {success: this.editPH}, this.editURL, {
				method: 'get', 
				asynchronous:true,						
				onLoading : function() { 
					//Element.hide(container); 
					//Element.show(spinner);
				},
				onComplete : this.editPageIsLoaded.bind(this),		
				onFailure: function() {
					Element.update(this.editPH, 'Loading Error');
				}
			});			
	},
	
	editPageIsLoaded: function() {	
		
		// Show
		Element.hide(this.displayPH);
		Element.show(this.editPH);	
		
		MPTH.editProfile();	
		
		// Scroller
		Sc.restart();		
			
	},
	
	confirm: function() {
		var ajaxCall;
		var registeringURL = '/renom08/ThresholdGiftOrder_Ajax.jsp';
		var failureURL = '/error.do';
		var spinner = 'r08_confirmSpinner';
		var params = 'gift=' + Session['gift'];
		
		// Save data 					
		ajaxCall = new Ajax.Request( registeringURL, {
			method: 'post',
			parameters: params, 
			onLoading : function(){
				
				// Spinner
				r08_setSpinnerPosition();	
				
				
				// Disable fadelayer onclick
				$('fadeLayer').onclick = function() { };					
							
				// Disable the window 
				Layer.close();					
				
				// Show spinner
				Element.toggle('fadeLayer');				
				Element.toggle(spinner);
			},
			onComplete : function(oRequest){ 
				
				// Server response
				if (oRequest.responseText.trim() == 'OK') {
					
					// Enable fadelayer onclick
					$('fadeLayer').onclick = function() {Layer.close();};							
					
					// hide the spinner
					Element.toggle('fadeLayer');								
					Element.toggle(spinner); 					
				
					// Start the confirm layer
					if (Session['isGFF'] == true) Layer.init('thresholdConfirmGift', '/renom08/ThresholdConfirm.jsp');						
					else Layer.init('thresholdConfirmGift', '/renom08/ThresholdConfirm.jsp');								
					
				} else {
											
					// Redirect to error page				
					window.location = failureURL;										
				}				
			},		
			onFailure: function(){			
				
				// Redirect to error page
				window.location = failureURL;
			}
		});						
	}
}

   
/* --------------------------------------------------------------- */
// MPExtend extend memberProfile() in r08_benefits.js
/* --------------------------------------------------------------- */	

function MPExtend() {
		
	MPExtend.prototype.formIsValid = function() {	
			
		// Hide error box
		Element.hide('r08_step3ErrorBox');			
			
		// Scrollto confirm box
		Sc.scrollToDiv($(ConfirmProfile.link));
			
		// Confirm Box
		ConfirmProfile.show();
	}		
}

/* --------------------------------------------------------------- */	
// CAExtend extend r08_confirmAddress in r08_benefits.js
/* --------------------------------------------------------------- */	

function CAExtend() {
	
	// New validation block in r08_renom07.html => use CAExtend.confirm
	this.ph = 'r08_confirmAddressBlockTH'; 	
	
	/* --------------------- */	

	CAExtend.prototype._reset = function() {	
		
		// hide	
		this.hide();	
		Element.hide('r08_POBox');
		// Reinit step3 display 
		MPTH.editProfile();
	}	       
	
	/* --------------------- */	

	CAExtend.prototype.confirm = function() {	
		var ajaxCall;
		var spinner = 't08_confirmSpinner';		
		var registeringProfileURL = '/renom08/UpdateProfile_Ajax.jsp';	
		var timeoutErrorText = 'Server Error: please try again later';
		var params;
		
		// Register Member Profile
		if ($('r08_addressForm')) params = Form.serialize('r08_addressForm');			
		
		// hide the confirm block	
		this.hide();	
	
		// Save data 					
		ajaxCall = new Ajax.Request( registeringProfileURL, {
			method: 'post', 
			parameters: params, 
			onLoading : function(){
				
				// Disable fadelayer onclick				
				$('fadeLayer').onclick = function() { };
				
				// Spinner
				r08_setSpinnerPosition();	
				Element.hide('r08_containerCATH');										
				Element.hide('t08_editAddressPH');				
				Element.toggle(spinner);
									
			},
			onComplete : function(oRequest){ 
				
				
				// Enable fadelayer onclick
				$('fadeLayer').onclick = startThresholdStepCancel;
							
				
				// Server response
				var responseText = oRequest.responseText.trim();
				if (responseText.substr(0,2) == 'OK') {
					
					// hide the spinner
					Element.show('r08_containerCATH');			
					Element.show('t08_addressPH');																					
					Element.toggle(spinner); 				
					
					// Register Javascript Data
					var arrayValue = responseText.split('@|@');
					
					memberProfileData['firstName'] = escape(arrayValue[1]);
					memberProfileData['middleName'] = escape(arrayValue[2]);
					memberProfileData['lastName'] = escape(arrayValue[3]);
					memberProfileData['addr_type'] = escape(arrayValue[4]);
					memberProfileData['businessName'] = escape(arrayValue[5]);
					memberProfileData['businessTitle'] = escape(arrayValue[6]);
					memberProfileData['streetNumber'] = escape(arrayValue[7]);
					memberProfileData['streetName'] = escape(arrayValue[8]);
					memberProfileData['unit'] = escape(arrayValue[9]);
					memberProfileData['direction'] = escape(arrayValue[10]);
					memberProfileData['POBox_ZipCode'] = escape(arrayValue[11]);
					memberProfileData['POBox_Branch'] = escape(arrayValue[12]);
					memberProfileData['POBox_RoadNumber'] = escape(arrayValue[13]);
					memberProfileData['countryCode'] = escape(arrayValue[14]);
					memberProfileData['provinceStateCode'] = escape(arrayValue[15]);
					memberProfileData['city'] = escape(arrayValue[16]);
					memberProfileData['postalCode'] = escape(arrayValue[17]);
					memberProfileData['tel_AreaCode'] = escape(arrayValue[18]);
					memberProfileData['tel_PhoneNumber'] = escape(arrayValue[19]);
					memberProfileData['email'] = escape(arrayValue[20]);		
							
					// Reinit step3 display 
					MPTH.verifyProfile();				
					
					// Reset scroller
					Sc.restart()					
					
				} else {		
		
					// hide the spinner
					Element.show('r08_containerCATH');			
					Element.show('t08_editAddressPH');																					
					Element.toggle(spinner); 				
					
					// Show error On form
					Element.update('r08_step3ErrorText',oRequest.responseText.trim());			
					Element.show('r08_step3ErrorBox');		
								
					// Reset scroller
					Sc.restart()					
									
				}				
			},		
			onFailure: function(){						
				
				// Show error On form
				Element.update('r08_step3ErrorText',timeoutErrorText);			
				Element.show('r08_step3ErrorBox');	
								
				// Reset scroller
				Sc.restart()						
			}
		});		
	}
}


/* --------------------------------------------------------------- */	

/* --------------------------------------------------------------- */
// Gift functions
/* --------------------------------------------------------------- */

function showGifts(miles) {
	var ajaxUpdater;	
	var rootURL = './';
	var ph = 't08_gifts';
	var container = 'r08_containerGF';
	var spinner = 't08_giftsSpinner';	
	//var URL = 'showMiles.php';	
	var URL = '/renom08/ThresholdGiftsTiers_Ajax.jsp';	
	
	// Init Scroll
	Sc.start('r08_contentGF','r08_containerGF','r08_scrollerGF','r08_scrollAreaGF');	
	
	// Miles
	if (miles == null) miles = Session['miles'];
	else Session['miles'] = miles;

	// Ajax call
	ajaxUpdater = new Ajax.Updater( {success: ph}, URL, {
		method: 'post', 
		asynchronous:true,		
		parameters: 'thresholdId=' + miles, 
		onLoading : function(){ 
			Element.hide(container); 
			Element.show(spinner);
		},
		onComplete : function(){ 
			Element.hide(spinner);
			Element.show(container); 
			
			// restart scroller
			Sc.restart();	
			if (Session['gift'] != '' && $(Session['gift']) ) Sc.scrollToDiv(Session['gift']);			
			
			// Menu hightlight
			var menu = Array(1,2,3,4);						
			for(var i=0;i<menu.length;i++) {
				$('menu' + menu[i]).className = (menu[i] == miles) ? 'r08_stepTitle_on' : 'r08_stepTitle';	
			}
			
		},		
		onFailure: function(){
			Element.update(ph, 'Loading Error');
		}
	});	
	
}

/* --------------------------------------------------------------- */

function orderGift(gift) {
	
	// Save Gift in jsSession
	Session['gift'] = gift;		
	Session['isGFF'] = false;		
	
	// Launch
	Layer.close();
	Layer.init('thresholdConfirmAddress', '/your_aeroplan/top_tier_benefits/threshold_gifts_2008/confirm_address.do?productID='+gift);
}

/* --------------------------------------------------------------- */

function editGift() {
	
	// Cleanup
	Layer.close();
	$('threshold').innerHTML ="";
	
	//Re-init
	Layer.init('threshold', '/your_aeroplan/top_tier_benefits/threshold_gifts_2008/gifts_list.do');	
}

/* --------------------------------------------------------------- */

function t08_showHelp(link,id) {
	var pos,ph;
	if(id == null) ph = 'r08_giftHelpBlock';
	else ph = id;
	
	// Set position
	pos = findPos($(link.id));
	$(ph).style.left = (pos[0] - 30) + 'px';
	$(ph).style.top = (pos[1] - 90) + 'px'; 		
	
	// show	
	Element.show(ph);
}

/* --------------------------------------------------------------- */

function t08_hideHelp(id) {
	var ph;

	if(id == null) ph = 'r08_giftHelpBlock';
	else ph = id;	
	
	// hide	
	Element.hide(ph);	
}

/* --------------------------------------------------------------- */

var GiftForFriend = Class.create();
GiftForFriend.prototype = {
	
	initialize: function() {
		var fade, miniLayer, miniLayerError, miniLayerLogin, Layer, posInPage, LayerDim, miniLayerDim;		
	},
	
	setPosition : function () {			
		
		// Get dimension		
		this.posInPage = findPos(this.Layer);	
		
		this.LayerDim = Element.getDimensions(this.Layer);

		this.miniLayerDim = Element.getDimensions(this.miniLayer);

		//console.info(this);

		// Set position
		this.miniLayer.style.left = (this.posInPage[0] + (this.LayerDim.width/2) - (this.miniLayerDim.width/2) ) + 'px';
		this.miniLayer.style.top = (this.posInPage[1] + (this.LayerDim.height) + (this.miniLayerDim.height) ) + 'px'; 			
	},
	
	show: function(gift) {
		
		// GetElements
		this.fade = $('fadeLayer');
		this.miniLayer = $('t08_giftForFriend');	
		this.miniLayerError = $('gffErrorBlock');
		this.miniLayerLogin = $('gffLoginBlock');		
		this.Layer = $('r08_layerXY');		
		
		// Set position
		this.setPosition();
		
		// Fade
		this.fade.onclick = this.hide.bind(this);
		this.fade.style.zIndex = 3;
		
		// show	
		Element.show(this.miniLayer);		
		
		// Save Gift in jsSession
		Session['gift'] = gift;	
		Session['isGFF'] = true;
		
		// Button Submit
		this.checkForm();
		
	},	
  	
  hide: function() {
  	
  	// Cleanup	
  	Form.getElements('t08_gffForm').each( function(el) { el.value = ''; });
		Element.hide(this.miniLayerError);  	
		Element.show(this.miniLayerLogin);	  	
  	
		// Hide
		Element.hide(this.miniLayer);  	
  	
		// Fade  	
		this.fade.style.zIndex = 1;		
		this.fade.onclick = function() { Layer.close(); };  	
  },
  
  retry: function() {
		Element.hide(this.miniLayerError);  	
		Element.show(this.miniLayerLogin);		
  },
  
  showError: function(error) {
  	Element.update('gffErrorText',error);
  	
		Element.show(this.miniLayerError);  	
		Element.hide(this.miniLayerLogin);		
  }, 
  
  checkForm: function(field,event) { 	
  	var fieldsAreCorrect = true;
  	var subButton = $('gffSubmit');
		
		// Filter event
		if (event != null) {
			var isNN = (navigator.appName.indexOf("Netscape")!=-1);
    	var keyCode = (isNN) ? event.which : event.keyCode;
    	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];  	  	
			if (filter.include(keyCode)) return;
		}		
		// Check form elements
		if ($F('gffFirstname') == '') fieldsAreCorrect = false;
		if ($F('gffLastname') == '') fieldsAreCorrect = false;	
		if ($F('gffCust1').length < 3 || $F('gffCust2').length < 3 || $F('gffCust3').length < 3) fieldsAreCorrect = false;	
		
		// Autotab
		if (field) {
			if (field.id == 'gffCust1' && $F('gffCust1').length == 3) $('gffCust2').focus(); 
			if (field.id == 'gffCust2' && $F('gffCust2').length == 3) $('gffCust3').focus();				
			if (field.id == 'gffCust3' && $F('gffCust3').length < 3) fieldsAreCorrect = false;
		}
		
		// Submit Button
		if (fieldsAreCorrect) {
			subButton.className = 'r08_proceedButton';
			subButton.onmouseover = function() { this.className = 'r08_proceedButton_on'; }			
			subButton.onmouseout = function() { this.className = 'r08_proceedButton'; }		
			subButton.onclick = this.submit.bind(this);	
		} else {			
			if (subButton.className == 'r08_proceedButton') {
				subButton.className = 'r08_proceedButton_disabled';
				subButton.onmouseover = '';			
				subButton.onmouseout = '';	
				subButton.onclick = '';		
			}
		}			
  },  
  
  submit: function() {   
		var ajaxCall;	
		var spinner = 'gffSpinnerBlock';	
		//var URL = 'giftForFriendLogin.php';  	
		var URL = '/renom08/ThresholdGiftForFriendLogin_Ajax.jsp'; 	
		var params = Form.serialize('t08_gffForm');
		
		// Ajax call
		ajaxCall = new Ajax.Request( URL, {
			method: 'post', 
			asynchronous:true,
			parameters: params, 
			onLoading : function(){ 
				Element.hide('gffLoginBlock'); 
				Element.show(spinner);
			},
			
			onComplete : function(oRequest){ 
			
				// Hide the spinner																					
				Element.hide(spinner); 					
				
				// Server response
				if (oRequest.responseText.trim() == 'OK') {			

					// Register Javascript Data in Session
					Form.getElements('t08_gffForm').each(function(el) {
						Session[el.name] = escape(el.value);
					});					
												
					// Launch
					GFF.hide();
					Layer.close();
					
					window.location = '/your_aeroplan/top_tier_benefits/threshold_gifts_2008/gffAdress.do?productID='+Session['gift'];
					
					//Layer.init('thresholdConfirmAddress', '/your_aeroplan/top_tier_benefits/threshold_gifts_2008/confirm_address.do');
					
				} else {			
					GFF.showError(oRequest.responseText);
				}
			},
			
			onFailure: function() {
				alert('Ajax Error');
			}
		});	  	
  } 
}

function selectedGiftToggle() {
	var target = 't08_selectedGiftDetails';
	var launcher = 't08_selectedGiftSummary';	
	
	// Toggle
	Element.toggle(launcher);	
	Element.toggle(target);
	
	// Scroller
	Sc.restart();	
}

/* --------------------------------------------------------------- */	
// Tools
/* --------------------------------------------------------------- */

function print_r(el) {
	alert($H(el).inspect());
}

/* --------------------------------------------------------------- */	

function debug(el) {
	if ($('debug')) Element.update('debug',el);
}

function pausecomp(millis)
{
	var date = new Date();
	var curDate = null;

	do { curDate = new Date(); }
	while(curDate-date < millis);
} 

/* --------------------------------------------------------------- */	

String.prototype.trim = function() {
	a = this.replace(/^\s+/, '');
	return a.replace(/\s+$/, '');
};


/* --------------------------------------------------------------- */
function startThresholdStepCancel() {
	var orig, dx, dy ;
	
	
	// Position
	orig = findPos($('r08_layerXY'));
	dy = orig[1] + 31; // 31
	dx = orig[0] + 190; // 190 cf css layer dimension
	
	// Fade up
	$('fadeLayer').style.zIndex = 2;
	$('threshold').style.zIndex = 1;	
	
	// Apply style
	$('r08_stepThresholdCancel').style.top = dy + 'px';
	$('r08_stepThresholdCancel').style.left = dx + 'px';			
	$('r08_stepThresholdCancel').style.zIndex = 5000;		
	
	// Show
	Element.show('r08_stepThresholdCancel');
}


/* --------------------------------------------------------------- */	
function stopThresholdStepCancel() {
	
	// Fade down
	$('fadeLayer').style.zIndex = 1;
	$('threshold').style.zIndex = 2;		
	
	// Show
	Element.hide('r08_stepThresholdCancel');
}

/* --------------------------------------------------------------- */
function exitThresholdStepCancel() {
	
	// Fade down
	$('fadeLayer').style.zIndex = 1;
	$('threshold').style.zIndex = 2;			
	
	// Close layer
	Layer.close();
	
	// Show
	Element.hide('r08_stepThresholdCancel');
}

