/*
	functions.forms.js
	Form Validation / Interactivity Functions
	Created: Aug. 5, 2008
	Creator: Matt Kircher, Mainline Media LLC
	
	FRENCH SYMBOL TABLE
	&aacute; = \u00E1	&agrave; = \u00E0	&eacute; = \u00E9
	&egrave; = \u00E8	&iacute; = \u00ED	&igrave; = \u00EC
	&oacute; = \u00F3	&ograve; = \u00F2	&uacute; = \u00FA
	&ugrave; = \u00F9	&ccedil; = \u00E7	
	
	&Aacute; = \u00C1	&Agrave; = \u00C0	&Eacute; = \u00C9
	&Egrave; = \u00C8	&Iacute; = \u00CD	&Igrave; = \u00CC
	&Oacute; = \u00D3	&Ograve; = \u00D2	&Uacute; = \u00DA
	&Ugrave; = \u00D9	&Ccedil; = \u00C7
	
	[ http://www1.tip.nl/~t876506/utf8tbl.html ]
*/

/* GENERAL */
function getPageLanguage(){
	return ($('body > div.english').length == 1)?"EN":"FR";
}

function addPageLanguageToPost(formData, jqForm, options){
	formData.push({ name: 'page_language', value: getPageLanguage() });
	return true;
}

function addNotificationBar(mssg){
	
	var message = $('<div class="notification_bar"><p>'+mssg+'&nbsp;&nbsp;&nbsp;<a href="#">ok</a></p></div>');
	$(message).find('a').bind('click', function(){ 
		$('.notification_bar').slideUp(400, function(){ 
			$('.notification_bar').remove(); 
		});
		return false;
	}).end().hide().prependTo($('body')).slideDown(400);
	var t = setTimeout("$('.notification_bar').slideUp(700, function(){ $('.notification_bar').remove(); })", 5000);
	return true;
}

function validateEmail(e){
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return filter.test($.trim(e));
}

function setupForm(){
	//remove required attention classes from required fields
	$('form .required').bind('change', function(){
		if($.trim($(this).val()) != ""){
			$(this).removeClass('required_attention');
			if($(this).get(0).nodeName == "SELECT"){
				if($(this).next().attr('class') == "select_required_attention"){
					$(this).next().remove();
				}
			}
		}
	});
	
	//bind blur / focus actions
	if(!$.browser.msie){
		$('form input[type="text"]')
		.bind('focus', function(){ $(this).addClass('highlighted_form_field'); })
		.bind('blur', function(){  $(this).removeClass('highlighted_form_field'); });
	}
	
	//set focus to first form field
	$('form input[tabindex="1"]').focus();
}

function validateForm(f){
	
	var specificForm = ($.trim(f) == "")?'form':f;
	
	//setup valid object
	var valid = { status:true, response:'', element:null };
	
	//remove classes, go through and check for non-values
	$(specificForm+' .select_required_attention').remove();
	$(specificForm+' .required')
	.removeClass('required_attention')
	.each(function(){
		if(($(this).val() == "" || $(this).val() == null)){
			$(this).addClass('required_attention');
			valid.status = false;
			valid.response = (getPageLanguage()=="EN")?'One or more required fields have not been completed. Please complete them and resubmit the form.':'Un ou des champs obligatoires n\'ont pas \u00E9t\u00E9 compl\u00E9t\u00E9. Veuillez les compl\u00E9ter et soumettre le formulaire de nouveau.';
			if(valid.element == null){ valid.element = $(this); }
			
			if($(this).get(0).nodeName == "SELECT"){
				$(this).after('<span class="select_required_attention">&lsaquo;&mdash;</span>');
			}
		}
	});
	
	//if email is not of the form 'name@email.com', don't validate
	if(valid.status){
		$(specificForm+' input.required[name="email"]').each(function(){				
			if(!validateEmail($(this).val())){
				$(this).addClass('required_attention');
				valid.status = false;
				valid.response = (getPageLanguage()=="EN")?'Please supply a valid email address.':'Veuillez fournir un courriel valide.';
				valid.element = $(this);
			}
		});
	}
	
	//display alert, focus on first non-valued field
	if(!valid.status){ alert(valid.response); $(valid.element).focus(); }
	return valid.status;
}


/* CONTACT FORM */

	var contactFormOptions = {
		url:		'../includes/forms.process.php?action=sendContactEmail',
		type:		'POST',
		dataType:	'json',
		beforeSubmit:	validateContactForm,
		success:	showContactFormThankYou
	}

	function setupContactForm(){
		
		//general setup
		setupForm();
			
		//form action setup
		$('#contactForm').ajaxForm(contactFormOptions);
	}
	
	function validateContactForm(formData, jqForm, options){
			
		formData.push({ name: 'page_language', value: getPageLanguage() });
		return validateForm('#contactForm');
	}
	
	function showContactFormThankYou(responseText, statusText){
		$('#contactForm').slideUp(700, function(){
			$('#main-content').append(responseText['successHTML']);
			
			$m = (getPageLanguage() == "EN")?'Contact form was sent successfully!':'la forme de contact a \u00E9t\u00E9 envoy\u00E9e avec succ\u00E8s !';
			addNotificationBar($m);
		});
	}
	
/* PATROL ENROLLMENT */

	var recruitmentFormOptions = {
		url:		'../includes/forms.process.php?action=sendPatrolEnrollmentEmail',
		type:		'POST',
		dataType:	'json',
		beforeSubmit:	validateRecruitmentForm,
		success:	showRecruitmentFormThankYou
	}

	function setupRecruitmentForm(){
		
		//general setup
		setupForm();
		
		//form action setup
		$('#recruitmentSignupForm').ajaxForm(recruitmentFormOptions);
	}
	
	function validateRecruitmentForm(formData, jqForm, options){
			
		formData.push({ name: 'page_language', value: getPageLanguage() });		
		return validateForm('#recruitmentSignupForm');
	}
	
	function showRecruitmentFormThankYou(responseText, statusText){
		$('#recruitmentSignupForm').hide();
		
		$('#main-content').append('<hr />'+responseText['successHTML']);
		$m = (getPageLanguage() == "EN")?'Recruit form was sent successfully!':'Formulaire d\'inscription patrouille envoy\u00E9e avec succ\u00E8s !';
		addNotificationBar($m);
	}

/* TRANSACTION FORM */
		
	function validateTransaction(){
	
	var valid = { status:true, response:'', element:null };
	
	//check length of CC#
	if(!$.trim($('#transaction_name').val()).length){
		valid.status = false;
		valid.response = (getPageLanguage()=="EN")?"Please enter the credit card holder's name.":"Veuillez \u00E9crire le holder' par la carte de cr\u00E9dit ; nom de s.";
	}
	
	//check length of CC#
	if(($('#transaction_number').val().length != 16 && ($('#transaction_type').val() == "VISA" || $('#transaction_type').val() == "MASTERCARD")) ||
	   ($('#transaction_number').val().length != 15 && $('#transaction_type').val() == "AMEX")){
		valid.status = false;
		valid.response = (getPageLanguage()=="EN")?"Please enter a valid credit card number.":"Veuillez entrer un num\u00E9ro de carte de cr\u00E9dit valide.";
	}
	
	//check expiration
	var currenttime = new Date();
	var now 	  = (currenttime.getMonth() < 10)?'0'+currenttime.getMonth():currenttime.getMonth();
	    now 	  = currenttime.getFullYear()+'-'+currenttime.getMonth();
	var expdate 	  = $('#transaction_year').val()+"-"+$('#transaction_month').val();
	if(expdate < now){
		valid.status = false;
		valid.response = (getPageLanguage()=="EN")?"Your credit card expiration date is too soon. Please use a different credit card.":"La date d'\u00E9ch\u00E9ance sur la carte de cr\u00E9dit n'est pas valide. Veuillez v\u00E9rifier les d\u00E9tails de la carte et corriger.";
	}
	
		
	if(!valid.status){
		//focus on problem element
		alert(valid.response); $(valid.element).focus();
		valid.status = false;
	}
	return valid.status;
}

/* SKI SCHOOL SIGNUP */

	var skiSchoolConfirmOptions = {
			url:		'../includes/forms.process.php?action=confirmSkiSchoolInfo',
			type:		'POST',
			dataType:	'json',
			beforeSubmit:	validateSkiSchoolInfo,
			success:	showSkiSchoolConfirmation
		}
		
	var skiSchoolSubmitOptions = {
			url:		'../includes/forms.process.php?action=submitPurchaseOrderInfo',
			type:		'POST',
			dataType:	'json',
			beforeSubmit:	addPageLanguageToPost
		}
		
	function setupSkiSchoolForm(){
			
			//general setup
			setupForm();
			
				//text limitations
				$('input[name="registrant[]"]').alpha({ allow:" " });
				
				//css formatting
				$('#contact_country').css({ width:'103px' });	//country select
				$('select[name="language[]"]').css({ width:'75px' });	//language select
				$('select[name="skill[]"]').css({ width:'83px' });	//skill level select
				
				//add new student functionality
				var addNewStudentSwitchFunctionality = function(){
					$('#ski-school-signup-registrants tbody input[name="new_student[]"]').each(function(){
						$(this).bind('click', function(){
							if($(this).is(':checked')){ $(this).parent().find('input:eq(1)').attr('value', 'Yes'); }
							else			     { $(this).parent().find('input:eq(1)').attr('value', 'No'); }
						});
					});
				}
				
				addNewStudentSwitchFunctionality();
				
				//add registrant button functionality
				$('#add_registrant').bind('click', function(){
					$('#ski-school-signup-registrants')
					.append($('table tbody tr:first').clone())
					.find('tbody tr:last')
					.find('input[type="text"]').attr('value', '').end()
					.find('input[type="checkbox"]').attr('checked', false).end()
					.find('input[name="new_student_value[]"]').attr('value', 'no').end()
					.find('select option:first').attr('selected', true).end()
					.find('td:last').html('<input type="button" value="x" />')
					.find('input').bind('click', function(){
						var ask = (getPageLanguage()=="EN")?'Are you sure you want to remove this registrant?':'\u00CAtes-vous s\u00FBr vous voulez-vous enlever ce registrant ?'
						if(confirm(ask)){
							$(this).parent().parent().remove();
						}
					});
							
					addNewStudentSwitchFunctionality();
				});
				
				//reset functionality
				$('#reset').bind('click', function(){ $('input[type="hidden"]').attr('value', 'No'); });
					
			//form action setup
			$('#ski-school-signup').ajaxForm(skiSchoolConfirmOptions);
				
			//edit registrants functionality
			$('#back').bind('click', function(){
				
				$('#ski-school-signup').ajaxForm(skiSchoolConfirmOptions);
								
				$('#back').hide();
				$('#submit').hide();
				
				//transition animation		
				$('#confirmation_step')
				.css({ opacity:1 })
				.animate({ opacity:0 }, 700, function(){
					$('#confirmation_step').slideUp(700, function(){
						
						$('#confirmation_step').empty();
						
						$('#step1, #step2, #step3')
						.css({ opacity:0 })
						.slideDown(500, function(){
							$('#reset').show();						
							$('#submit').attr('value', (getPageLanguage()=="EN")?'Confirm':'Confirmez').show();
							$('#step1, #step2, #step3').animate({ opacity:1 }, 700); 
							$('#order_disclaimer').removeAttr('disabled');
						});
					});
				});
			});
		}
		
	function validateSkiSchoolInfo(formData, jqForm, options){
			
			formData.push({ name: 'page_language', value: getPageLanguage() });
			
			//check normal form stuff
			if(!validateForm('#ski-school-signup')){ return false; }
			else{
				//check unique form stuff
				var valid = { status:true, response:'', element:null };
					
					//membership checked?
					if(!$('#membership1').is(':checked') && !$('#membership2').is(':checked') && !$('#membership3').is(':checked')){
						valid.status = false;
						valid.response = (getPageLanguage()=="EN")?"Please select your membership level.":"Veuillez choisir votre niveau d'adhésion";
					}
					
					if(!$('#order_disclaimer').is(':checked')){
						valid.status = false;
						valid.response = (getPageLanguage()=="EN")?"Please read and accept the above conditions before submitting your registration.":"Vous devez lire et accepter les conditions ci-dessus avant de soumettre votre inscription.";
					}
				
				
				if(!valid.status){
					//focus on problem element
					alert(valid.response); $(valid.element).focus();
				} else {
					//valid form submission, do transition animation
					$('#order_disclaimer').attr('disabled', "disabled");
					
					$.scrollTo('#main-content',700);
					$('#reset').hide();
					$('#submit').hide();
					
					$('#step1, #step2, #step3')
					.animate({ opacity:0 }, 700, function(){ 
						$('#step1, #step2, #step3').slideUp(700, function(){
							$('#confirmation_step')
							.css({ opacity:0 })
							.slideDown(700, function(){ 
								$('#back').show();
								$('#submit').show().attr('value', (getPageLanguage()=="EN")?'Submit Registration':'Soumette l\'enregistrement');
								$('#confirmation_step').animate({ opacity:1 }, 700); 
							});							 
						});								 
					});
				}
				return valid.status;
			}
		}
		
	function showSkiSchoolConfirmation(responseText, statusText){
			
			$('#confirmation_step').html(responseText['confirmation']);	//display confirmation info
			
			$('#ski-school-signup').ajaxFormUnbind();
			$('#ski-school-signup').attr('action', 'order-transaction.php').attr('method', 'post');
		}
		
		
/* PASSE 76 SIGNUP */

	var passe76ConfirmOptions = {
			url:		'../includes/forms.process.php?action=confirmPasse76Info',
			type:		'POST',
			dataType:	'json',
			beforeSubmit:	validatePasse76Info,
			success:	showPasse76Confirmation
		}
		
	var passe76SubmitOptions = {
			url:		'../includes/forms.process.php?action=submitPurchaseOrderInfo',
			type:		'POST',
			dataType:	'json',
			beforeSubmit:	addPageLanguageToPost
		}

	function setupPasse76Form(){
	
			//general setup
			setupForm();
			
				//text limitations
				$('input[name="registrant_fname[]"], input[name="registrant_lname[]"]').alpha();
				
				//css formatting
				$('#contact_country').css({ width:'103px' });	//country select
				$('select[name="language[]"]').css({ width:'75px' });	//language select
								
				//add registrant button functionality
				$('#add_registrant').bind('click', function(){
					$('#passe76-signup-registrants')
					.append($('table tbody tr:first').clone())
					.find('tbody tr:last')
					.find('input[type="text"]').attr('value', '').end()
					.find('input[type="checkbox"]').attr('checked', false).end()
					.find('input[name="new_student_value[]"]').attr('value', 'no').end()
					.find('select option:first').attr('selected', true).end()
					.find('td:last').html('<input type="button" value="x" />')
					.find('input').bind('click', function(){
						var ask = (getPageLanguage()=="EN")?'Are you sure you want to remove this registrant?':'\u00CAtes-vous s\u00FBr vous voulez-vous enlever ce registrant ?'
						if(confirm(ask)){
							$(this).parent().parent().remove();
						}
					});
				});
									
			//form action setup
			$('#passe76-signup').ajaxForm(passe76ConfirmOptions);
				
			//edit registrants functionality
			$('#back').bind('click', function(){
				
				$('#passe76-signup').ajaxForm(passe76ConfirmOptions);
				
				$('#back, #reset, #submit').hide();
				
				//transition animation		
				$('#confirmation_step')
				.animate({ opacity:0 }, 700, function(){
					$('#confirmation_step').slideUp(700, function(){
						
						$('#confirmation_step').empty();
						
						var elements = '#step1, #step2';
						elements += ($('#pass1').is(':checked'))?', #step3':'';
							
						$(elements)
						.css({ opacity:0 })
						.slideDown(500, function(){
							$('#reset').show();						
							$('#submit').attr('value', (getPageLanguage()=="EN")?'Confirm':'Confirmez').show();
							$('#step1, #step2, #step3').animate({ opacity:1 }, 700); 
						});
					});
				});
			});
			
			//pass type functionality
			$('#pass1').bind('click', function(){
				if($(this).is(':checked')){
					$('#step3').slideDown(700);
				}				
			});
			$('#pass2').bind('click', function(){
				if($(this).is(':checked')){
					$('#step3').slideUp(700);
				}				
			});
		}
		
	function validatePasse76Info(formData, jqForm, options){
			
			formData.push({ name: 'page_language', value: getPageLanguage() });
			
			//if submitting gift card info, make the form be "complete" 
			//by forcing values onto existing inputs
			if($('#pass2').is(':checked')){
				$('#step3 tbody tr:eq(0)')
				.find('input[name="registrant_fname[]"]').attr('value', 'x').end()
				.find('input[name="registrant_lname[]"]').attr('value', 'x');
			}
			
			//check normal form stuff
			if(!validateForm('#passe76-signup')){ return false; }
			else {
				//check unique form stuff
				var valid = { status:true, response:'', element:null };
					
					//membership checked?
					if(!$('#pass1').is(':checked') && !$('#pass2').is(':checked')){
						valid.status = false;
						valid.response = (getPageLanguage()=="EN")?"Please select your intended pass type.":"Veuillez choisir votre niveau d'adh\u00E9sion";
					}
				
				
				if(!valid.status){
					//focus on problem element
					alert(valid.response); $(valid.element).focus();
				} else {
					//valid form submission, do transition animation
					$.scrollTo('#main-content',700);
					$('#reset').hide();
					$('#submit').hide();
					
					$('#step1, #step2, #step3')
					.animate({ opacity:0 }, 700, function(){ 
						$('#step1, #step2, #step3').slideUp(700, function(){
							$('#confirmation_step')
							.css({ opacity:0 })
							.slideDown(700, function(){ 
								$('#back').show();
								$('#submit').show().attr('value', (getPageLanguage()=="EN")?'Submit Registration':'Soumette l\'enregistrement');
								$('#confirmation_step').animate({ opacity:1 }, 700); 
							});							 
						});								 
					});
				}
				return valid.status;
			}
		}

	function showPasse76Confirmation(responseText, statusText){
			
			$('#confirmation_step').html(responseText['confirmation']);		//display confirmation info
			
			$('#passe76-signup').ajaxFormUnbind();
			$('#passe76-signup').attr('action', 'order-transaction.php').attr('method', 'post');
		}		
		
/* SEASON PASS SIGNUP */

	var seasonPassConfirmOptions = {
			url:		'../includes/forms.process.php?action=confirmSeasonPassInfo',
			type:		'POST',
			dataType:	'json',
			beforeSubmit:	validateSeasonPassInfo,
			success:	showSeasonPassConfirmation
		}
		
	var seasonPassSubmitOptions = {
			url:		'../includes/forms.process.php?action=submitPurchaseOrderInfo',
			type:		'POST',
			dataType:	'json',
			beforeSubmit:	addPageLanguageToPost
		}
		
	function setupSeasonPassForm(){
			
			//general setup
			setupForm();
			
				//text limitations
				$('input[name="registrant_fname[]"], input[name="registrant_lname[]"]').alpha();
				
				//css formatting
				$('#contact_country').css({ width:'103px' });		//country select
				$('select[name="language[]"]').css({ width:'75px' });	//language select
				$('input[name="registrant_fname[]"], input[name="registrant_lname[]"]').css({ width:'70px' });
								
				//add registrant button functionality
				$('#add_registrant').bind('click', function(){
					$('#season-pass-signup-registrants')
					.append($('table tbody tr:first').clone())
					.find('tbody tr:last')
					.find('input[type="text"]').attr('value', '').end()
					.find('input[type="checkbox"]').attr('checked', false).end()
					.find('input[name="new_student_value[]"]').attr('value', 'no').end()
					.find('select option:first').attr('selected', true).end()
					.find('td:last').html('<input type="button" value="x" />')
					.find('input').bind('click', function(){
						var ask = (getPageLanguage()=="EN")?'Are you sure you want to remove this registrant?':'\u00CAtes-vous s\u00FBr vous voulez-vous enlever ce registrant ?'
						if(confirm(ask)){
							$(this).parent().parent().remove();
						}
					});
				});
					
			//form action setup
			$('#season-pass-signup').ajaxForm(seasonPassConfirmOptions);
				
			//edit registrants functionality
			$('#back').bind('click', function(){
				
				$('#season-pass-signup').ajaxForm(seasonPassConfirmOptions);
								
				$('#back').hide();
				$('#submit').hide();
				
				//transition animation		
				$('#confirmation_step')
				.css({ opacity:1 })
				.animate({ opacity:0 }, 700, function(){
					$('#confirmation_step').slideUp(700, function(){
						
						$('#confirmation_step').empty();
						
						$('#step1, #step2, #step3')
						.css({ opacity:0 })
						.slideDown(500, function(){
							$('#reset').show();						
							$('#submit').attr('value', (getPageLanguage()=="EN")?'Confirm':"Soumettre l'enregistrement").show();
							$('#step1, #step2, #step3').animate({ opacity:1 }, 700);
							$('#order_disclaimer').removeAttr('disabled');
						});
					});
				});
			});
		}
		
	function validateSeasonPassInfo(formData, jqForm, options){
			
			formData.push({ name: 'page_language', value: getPageLanguage() });
			
			//check normal form stuff
			if(!validateForm('#season-pass-signup')){ return false; }
			else{
				//check unique form stuff
				var valid = { status:true, response:'', element:null };
					
					$('select[name="program[]"]').each(function(){
						if($.trim($(this).val()) == ""){
							valid.status = false;
							valid.response = (getPageLanguage()=="EN")?"Please specify all pass types for you order.":"Veuillez sp\u00E9cifier tous les types de passage pour vous ordre.";
							valid.element = $(this);
							
							return false;
						}						   
					});
					
					//couple checked and even?
					$('select[name="program[]"]').each(function(){
						var couple_count = $('select[name="program[]"]').filter('[value="2912"]').length;
						
						if($(this).val() == 2912 && couple_count%2 != 0){
							valid.status = false;
							valid.response = (getPageLanguage()=="EN")?"Please add another 'Couples' pass to your order.":"Veuillez ajouter un autre 'Couples' passe \u00e0 votre ordre.";		
							
							return false;
						}
					});
					
					if(!$('#order_disclaimer').is(':checked')){
						valid.status = false;
						valid.response = (getPageLanguage()=="EN")?"Please read and accept the above conditions before submitting your registration.":"Vous devez lire et accepter les conditions ci-dessus avant de soumettre votre inscription.";
					}
				
				
				if(!valid.status){
					//focus on problem element
					alert(valid.response); $(valid.element).focus();
				} else {
					//valid form submission, do transition animation
					$('#order_disclaimer').attr('disabled', "disabled");
					
					$.scrollTo('#main-content',700);
					$('#reset').hide();
					$('#submit').hide();
					
					$('#step1, #step2')
					.animate({ opacity:0 }, 700, function(){ 
						$('#step1, #step2').slideUp(700, function(){
							$('#confirmation_step')
							.css({ opacity:0 })
							.slideDown(700, function(){ 
								$('#back').show();
								$('#submit').show().attr('value', (getPageLanguage()=="EN")?'Submit Registration':'Soumette l\'enregistrement');
								$('#confirmation_step').animate({ opacity:1 }, 700); 
							});							 
						});								 
					});
				}
				return valid.status;
			}
		}
		
	function showSeasonPassConfirmation(responseText, statusText){
			
			$('#confirmation_step').html(responseText['confirmation']);	//display confirmation info
			
			$('#season-pass-signup').ajaxFormUnbind();
			$('#season-pass-signup').attr('action', 'order-transaction.php').attr('method', 'post');
		}


/* NEWSLETTER SIGNUP */		
	
	var newsletterSubmitOptions = {
			url:		'../includes/forms.process.php?action=submitNewsletterSignup',
			type:		'POST',
			dataType:	'json',
			beforeSubmit:	cleanupNewsletterSignup,
			success:	showNewsletterSignupResponse
		}
		
	function setupNewletterForm(){
			
			setupForm(); 								//general setup
			
			$('#newsletter-signup').ajaxForm(newsletterSubmitOptions);	//form action setup
			
			$('#newsletter-submit').attr('disabled', true);			//disable submit button (so enter key doesn't affect it)
			
			$('#newsletter-cancel').bind('click', function(){		//reset functionality
				$('#newsletter-email, #newsletter-signup-button').show();
				$('#newsletter_signup_options, #newsletter-submit, #newsletter-cancel').hide();
				tb_remove();
			});
			
			$('#newsletter-signup-button').bind('click', function(){	//signup functionality
				if(!validateForm('#newsletter-signup')){ return false; }
				else {
					var heading = (getPageLanguage() == 'EN')?'<h3>Newsletter Options</h3>':'<h3>Options de bulletin</h3>';
					var summary_en = '<p class="summary">Your newsletter will be sent to the following email address:<br /><b>'+$('#newsletter-email').val()+'</b></p>';
					var summary_fr = '<p class="summary">Votre bulletin sera envoy\u00E9 \u00E0 l\'adresse courriel suivante:<br /><b>'+$('#newsletter-email').val()+'</b></p>';
					var summary = (getPageLanguage() == 'EN')?summary_en:summary_fr;
					
					$('#newsletter_signup_options')
					.find('h3, .summary').remove().end()
					.prepend(heading+summary)
					.show();
					
					$('#newsletter-submit').attr('disabled', false);
					$('#newsletter-submit, #newsletter-cancel').show();
					$('#newsletter-email, #newsletter-signup-button').hide();
					
					$('#newsletter-module a.thickbox').trigger('click');
				}							     
			});
		}
		
	function cleanupNewsletterSignup(formData, jqForm, options){
			
			formData.push({ name: 'page_language', value: getPageLanguage() });
			
			$('#newsletter-submit').attr('disabled', true);
			$('#newsletter-email, #newsletter-signup-button').show();
			$('#newsletter_signup_options, #newsletter-submit, #newsletter-cancel').hide();
			tb_remove();
		}
		
	function showNewsletterSignupResponse(responseText, statusText){
			$('#newsletter-email').val("");
			
			addNotificationBar(responseText['message']);
		}


/* SURVEY */

	var surveySubmitOptions = {
			url:		'../includes/forms.process.php?action=submitSurveyResults',
			type:		'POST',
			dataType:	'json',
			beforeSubmit:	addPageLanguageToPost,
			success:	showSurveyFinish
		}
	
	function setupSurveyForm(){
			
			setupForm();
			
			$('#survey-form')
			.ajaxForm(surveySubmitOptions)
			.find('fieldset:gt(0)')
			.hide();
			
			$('#survey_start_button').bind('click', function(){
										
				//check contact info
				if($.trim($('#survey_fname').val()) == "" ||
				   $.trim($('#survey_lname').val()) == "" ||
				   $.trim($('#survey_email').val()) == "" ||
				   $.trim($('#survey_city').val()) == ""){
					
					var response = (getPageLanguage()=="EN")?'One or more required fields have not been completed. Please complete them to start the survey.':'Un ou des champs obligatoires n\'ont pas été complété. Veuillez les compléter et soumettre le formulaire de nouveau.';
					
					//check contact email format
					if(!validateEmail($('#survey_email').val())){
						response = (getPageLanguage()=="EN")?'Please supply a valid email address.':'Veuillez fournir un courriel valide.';
					}
					alert(response);
				}else {
					$('#survey-form fieldset#start').hide();
					$('#survey_questions fieldset:eq(0)').show();
				}				
			});
			
			$('#survey-form .survey_next_button').bind('click', function(){
				
				var p = $(this).parent();
				var question_answered = false;
				
				$(p).find('input').each(function(){
					if($(this).is(':checked')){
						question_answered = true;
						return false;
					}
				});
				
				if(question_answered){
					$(this).parent().hide().next().show();
				} else {
					response = (getPageLanguage()=="EN")?'To continue, please supply an answer to this question.':'Pour continuer, satisfaire fournissez une r\u00e9ponse \u00e0 cette question.';
					alert(response);
				}
			});
			
			
			$('#survey-form fieldset#privacy, #survey-form fieldset#rules')
			.find('input[type="button"]').bind('click', function(){
				$('#survey-form fieldset').hide();
				$('#survey-form fieldset#start').show();											   
			});
			$('#survey-form a.survey_privacy_link').bind('click', function(){
				$('#survey-form fieldset').hide();
				$('#survey-form fieldset#privacy').show();
			});
			$('#survey-form a.survey_rules_link').bind('click', function(){
				$('#survey-form fieldset').hide();
				$('#survey-form fieldset#rules').show();
			});
		
		}
		
	function showSurveyFinish(responseText, statusText){
			
			$('#survey-form fieldset').hide();
			
			$('#survey_close_button').bind('click', function(){ tb_remove(); addNotificationBar(responseText['message']); });
			$('#survey-form fieldset#end').show();
		}
		
/* COUPONS */

	var couponSubmitOptions = {
			url:		'../includes/forms.process.php?action=submitCoupon',
			type:		'POST',
			dataType:	'json',
			beforeSubmit:	validateCouponForm,
			success:	showCoupon
		}
	
	function setupCouponForm(){
			
			setupForm();
			$('#coupon-form').ajaxForm(couponSubmitOptions);
		}
		
	function validateCouponForm(formData, jqForm, options){
			
			formData.push({ name: 'page_language', value: getPageLanguage() });
			
			//check normal form stuff
			if(!validateForm('#coupon-form')){ return false; }			
			$('#coupon-form').ajaxForm(couponSubmitOptions);
		}
		
	function showCoupon(responseText, statusText){
			$('#coupon-form').hide();
			$('<div id="coupon_frame">'+responseText['coupon']+'</div>').insertAfter($('#coupon-form'));
			$('#coupon-form').remove();
		}
		
		
/* WEATHER REPORT */
	
	function setupWeatherReport(){
		
		$('#weather-overview .print a').click(function(){
				window.print();
				return false;
		});
		
		$('#weather-overview .email a').click(function(){
			$('#weatherReportForm').submit();
			return false;
		});
		
		var emailWeatherReportOptions = {
			url:		'../includes/forms.process.php?action=emailWeatherReport',
			type:		'POST',
			dataType:	'json',
			resetForm:	true,
			beforeSubmit:	function(formData, jqForm, options){
				
				var email = prompt((getPageLanguage()=="EN")?'Please enter your email address':'Veuillez \u00E8crire votre un courriel.');
				if(!validateEmail(email)){
					alert((getPageLanguage()=="EN")?'Please supply a valid email address.':'Veuillez fournir un courriel valide.')
					return false;
				} else {
					formData.push({ name: 'page_language', value: getPageLanguage() });
					formData.push({ name: 'email', value: email });
					return true;
				}
			},
			success:	function(data){
				
				if(data['mailsent'] == true){
					$('#weatherReportForm input[name="email"]').attr('value', '');
					alert("We attempted to send a weather report to "+data['email']+".\n\nPlease add postmaster@skimontblanc.com to your 'NOT SPAM' list\n(sometimes it adds our emails to your spam box).");
				}					
			}
		}
		
		$('#weatherReportForm').ajaxForm(emailWeatherReportOptions);
	}


/* GIFT CARD SIGNUP */

	var giftCardConfirmOptions = {
		url:		'../includes/forms.process.php?action=confirmGiftCardInfo',
		type:		'POST',
		dataType:	'json',
		beforeSubmit:	validateGiftCardInfo,
		success:	showGiftCardConfirmation
	}
		
	function setupGiftCardForm(){
		
		//general setup
		setupForm();
		
			//text limitations
			$('input[type="text"]').not('#recipient_address, #contact_address, #contact_zipcode, #ss_contact_email, #contact_phone1, #recipient_zipcode, #gift_amount').alpha({ allow:'#,. '});
			$('#recipient_address, #contact_address').alpha({ allow:'#,. 0123456789'});
			$('#gift_amount').numeric({allow:'.'});
		
		//same info button
			$('#same_info').bind('change', function(){
				
				if($(this).is(':checked')){
					$('#recipient_fname').val($('#contact_fname').val());
					$('#recipient_lname').val($('#contact_lname').val());
					$('#recipient_address').val($('#contact_address').val());
					$('#recipient_city').val($('#contact_city').val());
					$('#recipient_state').val($('#contact_state').val());
					$('#recipient_zipcode').val($('#contact_zipcode').val());
					$("#recipient_country").val($('#contact_country option:selected').val());
				} else {
					$('#recipient_fname, #recipient_lname, #recipient_address, #recipient_city, #recipient_state, #recipient_zipcode').val('');
					$("#recipient_country").val($('#contact_country option:selected'));
				}
			});
		
		//form action setup
		$('#gift-card-signup').ajaxForm(giftCardConfirmOptions);
			
		//edit registrants functionality
		$('#back').bind('click', function(){
			
			$('#gift-card-signup').ajaxForm(giftCardConfirmOptions);
							
			$('#back').hide();
			$('#submit').hide();
			
			//transition animation		
			$('#confirmation_step')
			.css({ opacity:1 })
			.animate({ opacity:0 }, 700, function(){
				$('#confirmation_step').slideUp(700, function(){
					
					$('#confirmation_step').empty();
					
					$('#step1, #step2, #step3')
					.css({ opacity:0 })
					.slideDown(500, function(){
						$('#reset').show();						
						$('#submit').attr('value', (getPageLanguage()=="EN")?'Confirm':"confirmer").show();
						$('#step1, #step2, #step3').animate({ opacity:1 }, 700);
					});
				});
			});
		});
	}
	
	function validateGiftCardInfo(formData, jqForm, options){
		
		formData.push({ name: 'page_language', value: getPageLanguage() });
		
		//check normal form stuff
		if(!validateForm('#gift-card-signup')){ return false; }
		else{
			//check unique form stuff
			var valid = { status:true, response:'', element:null };
				
				if($('#gift_amount').val() > 250 || $('#gift_amount').val() < 0){
					valid.status = false;
					valid.response = (getPageLanguage()=="EN")?"Please enter a gift card amount between $1 and $250.":"Veuillez choisir un montant pour la Carte cadeau entre 1 $ et 250 $";
				}
			
			if(!valid.status){
				//focus on problem element
				alert(valid.response); $(valid.element).focus();
			} else {
				//valid form submission, do transition animation
				$('#order_disclaimer').attr('disabled', "disabled");
				
				$.scrollTo('#main-content',700);
				$('#reset').hide();
				$('#submit').hide();
				
				$('#step1, #step2, #step3')
				.animate({ opacity:0 }, 700, function(){ 
					$('#step1, #step2, #step3').slideUp(700, function(){
						$('#confirmation_step')
						.css({ opacity:0 })
						.slideDown(700, function(){ 
							$('#back').show();
							$('#submit').show().attr('value', (getPageLanguage()=="EN")?'Submit':'soumettre');
							$('#confirmation_step').animate({ opacity:1 }, 700); 
						});							 
					});								 
				});
			}
			return valid.status;
		}
	}
	
	function showGiftCardConfirmation(responseText, statusText){
		
		$('#confirmation_step').html(responseText['confirmation']);	//display confirmation info
		
		$('#gift-card-signup').ajaxFormUnbind();
		$('#gift-card-signup').attr('action', 'order-transaction.php').attr('method', 'post');
	}
	
/* PHOTO UPLOAD */

	var photoUploadSubmitOptions = {
		type:		'POST',
		url:		'../includes/forms.process.php?action=uploadUserPhoto',
		dataType:	'json',
		iframe:	true,
		target:	'#hidden-json-form-receiver',
		beforeSubmit:	validatePhotoUpload,
		success: 	showPhotoUploadConfirmation
	}
		
	function setupPhotoUploadForm(){
		
		//general setup
		setupForm();
		
		//text limitations
		$('#contact_name, #photo_name, #photo_location, #photo_caption').alpha({ allow:' '});
		$('#photo_desc').alpha({ allow:',. 0123456789'});
		
		//form action setup
		$('#photoUploadForm').ajaxForm(photoUploadSubmitOptions);
	}
	
	function validatePhotoUpload(formData, jqForm, options){
		
		$('input[name="page_language"]').val(getPageLanguage());
		
		//check normal form stuff
		if(!validateForm('#photoUploadForm')){ return false; }
		else{
			//check unique form stuff
			var valid = { status:true, response:'', element:null };
				
				if($.trim($('#photo_desc').val()) == ''){
					valid.status = false;
					valid.response = (getPageLanguage()=="EN")?"Please give this photo a description.":"Veuillez inscrire une description.";
				}
				
				if(!$('#photo_terms').is(':checked')){
					valid.status = false;
					valid.response = (getPageLanguage()=="EN")?"Please read and accept the above conditions before submitting your photo.":"Veuillez lire et accepter les conditions avant de soumettre vos photos.";
				}
			
			if(!valid.status){
				//focus on problem element
				alert(valid.response); $(valid.element).focus();
			}
			
			return valid.status;
		}
	}
	
	function showPhotoUploadConfirmation(responseText, statusText){
		
		if(responseText['status'] != "OK"){
			alert(responseText['successHTML']);
			
		} else {
			$('#photoUploadForm').slideUp(700, function(){
				
				$('#main-content #photoUploadForm fieldset').html(responseText['successHTML']);
				
				$('#photoUploadForm').slideDown(700, function(){
					$m = (getPageLanguage() == "EN")?'Your photo was uploaded successfully!':'Votre photo a \u00E9t\u00E9 t\u00E9l\u00E9charg\u00E9e avec success !';
					addNotificationBar($m);
				});
			});
		}
	}

