var isValid = true;
var ERROR_CLASS = 'error';
var processing = false;
var second_added = false;
var m = [];
var PER_TICKET = 100;

$(document).ready(function() {
	                                                                             
	$('#num_of_tickets').change(function() {
		$('#tix_total').html("$" + ($(this).val() * PER_TICKET));
	});
	
	$('#num_of_tickets').trigger("change");

	$('#tickets_form').submit(function(e) {
		e.preventDefault();
		if(valid()) {
			if($('#submit_btn li a').text() == 'Submit') {
				showConfirmation();
			} else {
				buyTickets();
			}
		}
	});
	
	$('#submit').click(function(e) {
		e.preventDefault();
		$('#tickets_form').trigger("submit");
	});
	
	$('#add_secondary').click(function(e) {
		e.preventDefault();
		if(!second_added) {
			second_added = true;
			$('#add_secondary').parent().html("Secondary Name (optional)");
			$('.secondary_th').fadeIn(600);
		}
	});
	
	/* setup form validation triggers */
	$('#first_name').bind('blur change',function() {
		if(($(this).val()=='') || ($(this).val().length > 75) ) {
			isValid = false;
			$(this).addClass(ERROR_CLASS);
			$(this).siblings('label').addClass(ERROR_CLASS);
			m.push("Please enter your first name.");
		} else {
			$(this).removeClass(ERROR_CLASS);
			$(this).siblings('label').removeClass(ERROR_CLASS);
		}
	});
	
	$('#last_name').bind('blur change',function() {
		if(($(this).val()=='') || ($(this).val().length > 75) ) {
			isValid = false;
			$(this).addClass(ERROR_CLASS);
			$(this).siblings('label').addClass(ERROR_CLASS);
			m.push("Please enter your last name.");
		} else {
			$(this).removeClass(ERROR_CLASS);
			$(this).siblings('label').removeClass(ERROR_CLASS);
		}
	});
	
	$('#address').bind('blur change',function() {
		if($(this).val()=='') {
			isValid = false;
			$(this).addClass(ERROR_CLASS);
			$(this).siblings('label').addClass(ERROR_CLASS);
			m.push("Please enter your address.");
		} else {
			$(this).removeClass(ERROR_CLASS);
			$(this).siblings('label').removeClass(ERROR_CLASS);
		}
	});
	

	$('#country').bind('change',function() {
		
		if($(this).val()!='Australia') { //if a country other than AUS is seleted, change default to Email
		   $('input[name=tix_send]:eq(0)').attr("checked","checked");
		   $('#state option:eq(8)').attr("selected","selected");
		   $('input[name=tix_send]').attr("disabled","disabled");
		   $('#state').attr("disabled","disabled");
		} else {
			$('input[name=tix_send]').attr("disabled",false);
			$('#state').attr("disabled",false);
		}
		
	});
	
	$('#state').bind('blur change',function() {
		if($(this).val()=='') {
			isValid = false;
			$(this).addClass(ERROR_CLASS);
			$(this).siblings('label').addClass(ERROR_CLASS);
			m.push("Please enter your state or territory.");
		} else {
			$(this).removeClass(ERROR_CLASS);
			$(this).siblings('label').removeClass(ERROR_CLASS);
		}
	});
		
	$('#suburb').bind('blur change',function() {
		if($(this).val()=='') {
			isValid = false;
			$(this).addClass(ERROR_CLASS);
			$(this).siblings('label').addClass(ERROR_CLASS);
			m.push("Please enter your suburb.");
		} else {
			$(this).removeClass(ERROR_CLASS);
			$(this).siblings('label').removeClass(ERROR_CLASS);
		}
	});
	
	$('#postcode').bind('blur change',function() {
		if( ($(this).val()=='') || (!allowedChars($(this).val(),'1234567890abcdefghijklmnopqrstuvwxyz ')) ) {
			isValid = false;
			$(this).addClass(ERROR_CLASS);
			$(this).siblings('label').addClass(ERROR_CLASS);
			m.push("Please check that your postcode is correct.");
		} else {
			$(this).removeClass(ERROR_CLASS);
			$(this).siblings('label').removeClass(ERROR_CLASS);
		}
	});
	
	$('#day_phone').bind('blur change',function() {
		if($(this).val()!='') {
			if(!allowedChars($(this).val(),'1234567890') || ($(this).val().length > 25)) {
				isValid = false;
				$(this).addClass(ERROR_CLASS);
				$(this).siblings('label').addClass(ERROR_CLASS);
				m.push("Please check that your day phone only contains numbers and is less than 25 characters in length.");
			} else {
				$(this).removeClass(ERROR_CLASS);
				$(this).siblings('label').removeClass(ERROR_CLASS);
			}
		} else {
			$(this).removeClass(ERROR_CLASS);
			$(this).siblings('label').removeClass(ERROR_CLASS);
		}
	});
	
	$('#evening_phone').bind('blur change',function() {
		if($(this).val()!='') {
			if(!allowedChars($(this).val(),'1234567890') || ($(this).val().length > 25)) {
				isValid = false;
				$(this).addClass(ERROR_CLASS);
				$(this).siblings('label').addClass(ERROR_CLASS);
				m.push("Please check that your evening phone only contains numbers and is less than 25 characters in length.");
			} else {
				$(this).removeClass(ERROR_CLASS);
				$(this).siblings('label').removeClass(ERROR_CLASS);
			}
		} else {
			$(this).removeClass(ERROR_CLASS);
			$(this).siblings('label').removeClass(ERROR_CLASS);
		}
	});
	$('#mobile_phone').bind('blur change',function() {
		if($(this).val()!='') {
			if(!allowedChars($(this).val(),'1234567890') || ($(this).val().length > 25)) {
				isValid = false;
				$(this).addClass(ERROR_CLASS);
				$(this).siblings('label').addClass(ERROR_CLASS);
				m.push("Please check that your mobile phone only contains numbers and is less than 25 characters in length.");
			} else {
				$(this).removeClass(ERROR_CLASS);
				$(this).siblings('label').removeClass(ERROR_CLASS);
			}
		} else {
			$(this).removeClass(ERROR_CLASS);
			$(this).siblings('label').removeClass(ERROR_CLASS);
		}
	});
	
	$('#email').bind('blur change',function() {
		if($(this).val().search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) == -1) {
			isValid = false;
			$(this).addClass(ERROR_CLASS);
			$(this).siblings('label').addClass(ERROR_CLASS);
			m.push("Please check that your email address is correct.");
		} else {
			$(this).removeClass(ERROR_CLASS);
			$(this).siblings('label').removeClass(ERROR_CLASS);
		}
	});
	
	$('#dob_day').change(function() {
		if(($(this).val()!='') && ($('#dob_month').val()!='') && ($('#dob_year').val()!='')) {
			if(!isDate()) {
				isValid = false;
				$(this).siblings('label').addClass(ERROR_CLASS);
				m.push("Please check that your date of birth is correct.");
			} else {
				$(this).siblings('label').removeClass(ERROR_CLASS);
			}
		} else {
			$(this).siblings('label').removeClass(ERROR_CLASS);
		}
	});
	
	$('#dob_month').change(function() {
		$('#dob_day').trigger("change");
	});
	
	$('#dob_year').change(function() {
		$('#dob_day').trigger("change");
	});
	
	$('#card_type').change(function() {
		if( (allowedChars($('#card_number').val(), '0123456789- ')) && (isValidCreditCard($(this).val(),$('#card_number').val())) ) {
			$('#card_number').removeClass(ERROR_CLASS);
			$(this).siblings('label').removeClass(ERROR_CLASS);
			$('#card_number').siblings('label').removeClass(ERROR_CLASS);
		} else {
			isValid = false;
			$('#card_number').addClass(ERROR_CLASS);
			$(this).siblings('label').addClass(ERROR_CLASS);
			$('#card_number').siblings('label').addClass(ERROR_CLASS);
			m.push("Please check your credit card type and number.");
		}
	});
	
	$('#card_name').bind('blur change',function() {
		if($(this).val()=='') {
			isValid = false;
			$(this).addClass(ERROR_CLASS);
			$(this).siblings('label').addClass(ERROR_CLASS);
			m.push("Please enter the name that appears on your credit card.");
		} else {
			$(this).removeClass(ERROR_CLASS);
			$(this).siblings('label').removeClass(ERROR_CLASS);
		}
	});
	
	$('#card_number').bind('blur change',function() {
		$('#card_type').trigger("change");
	});
	
	$('#sec_code').bind('blur change',function() {
		if( (!isInteger($(this).val())) || ($(this).val()=='') || ($(this).val().length > 4) ) {
			isValid = false;
			$(this).addClass(ERROR_CLASS);
			$(this).siblings('label').addClass(ERROR_CLASS);
			m.push("Please check the security code for your credit card.");
		} else {
			$(this).removeClass(ERROR_CLASS);
			$(this).siblings('label').removeClass(ERROR_CLASS);
		}		
	});
	
	$('#expiry_mm').change(function() {
		var c = new Date();
		var cmon = c.getMonth();
		var cyear = c.getFullYear();
		if(($(this).val() == "") || ($('#expiry_yy').val() == "") || ($(this).val()=="MM") || ($('#expiry_yy').val()=="YYYY")) {
			isValid = false;
			$(this).siblings('label').addClass(ERROR_CLASS);
			m.push("Please select the expiry date of your credit card.");
		} else if ($('#expiry_yy').text() < cyear) {
			isValid = false;
			$(this).siblings('label').addClass(ERROR_CLASS);
			m.push("Please select the expiry date of your credit card.");
		} else if ( (Math.round($(this).val()) <= parseInt(cmon)) && (parseInt($('#expiry_yy :selected').text()) == cyear)) {
			isValid = false;
			$(this).siblings('label').addClass(ERROR_CLASS);
			m.push("Please select the expiry date of your credit card.");
		} else {
			$(this).siblings('label').removeClass(ERROR_CLASS);
		}
	});
	
	$('#expiry_yy').change(function() {
		$('#expiry_mm').trigger("change");
	});
	

});

function showConfirmation() {
	
	$('#tix_total_lbl').html("$" + ($('#num_of_tickets').val() * PER_TICKET));
	$('#num_tix_lbl').html($('#num_of_tickets').val());
	$('#title_lbl').html($('#title').val());
	$('#first_name_lbl').html($('#first_name').val());
	$('#last_name_lbl').html($('#last_name').val());
	$('#first_name_2_lbl').html($('#first_name_2').val());
	$('#last_name_2_lbl').html($('#last_name_2').val());
	$('#address_lbl').html($('#address').val());
	$('#country_lbl').html($('#country').val());
	$('#state_lbl').html($('#state').val());
	$('#suburb_lbl').html($('#suburb').val());
	$('#postcode_lbl').html($('#postcode').val());
	$('#day_phone_lbl').html($('#day_phone').val());
	$('#evening_phone_lbl').html($('#evening_phone').val());
	$('#mobile_phone_lbl').html($('#mobile_phone').val());
	$('#email_lbl').html($('#email').val());
	$('#dob_day_lbl').html($('#dob_day :selected').val()+'/'+$('#dob_month :selected').val()+'/'+$('#dob_year :selected').val());
		
	$('#card_type_lbl').html($('#card_type').val());
	$('#card_name_lbl').html($('#card_name').val());
	$('#card_number_lbl').html($('#card_number').val());
	$('#sec_code_lbl').html($('#sec_code').val());
	$('#expiry_mm_lbl').html($('#expiry_mm :selected').val()+'/'+$('#expiry_yy :selected').val());
		
	$('#mswa_general_lbl').html(($('#mswa_general:checked').val()=='yes')?'Please keep me up to date with other communications and activities from MS Society WA.':'');
	$('#post_ticket_lbl').html(($('input[@name=tix_send]:checked').val()=='post')?'Post':'Email');

	$('#submit_btn li a').html("Confirm");
	Cufon.replace('#submit_btn li a',{fontFamily:'abq'});
	$('<li id="back_btn"><a href="#">Back</a></li>').insertAfter($('#submit_btn li'));
	Cufon.replace('#back_btn a',{fontFamily:'abq'});
	
	$('#back_btn').click(function(e) {
		e.preventDefault();
		$('#tickets_form').show();
		$('#confirm_form').hide();
		$('#submit_btn li a').html("Submit");
		Cufon.replace('#submit_btn li a',{fontFamily:'abq'});
		$('#back_btn').remove();
	});

	$('#tickets_form').hide();
	$('#confirm_form').show();
	
}

function valid() {

	isValid = true; //innocent until proven guilty!
	m = [];//empty the message stack
	
	var num_tix = $('#num_of_tickets');
	var my_title = $('#title');
	var my_first = $('#first_name');
	var my_last = $('#last_name');
	var my_address = $('#address');
	var my_suburb = $('#suburb');
	var my_state = $('#state');
	var my_country = $('#country');
	var my_postcode = $('#postcode');
	var my_phone_d = $('#day_phone');
	var my_phone_e = $('#evening_phone');
	var my_mobile = $('#mobile_phone');
	var my_email = $('#email');
	var my_dob_dd = $('#dob_day');
	var my_dob_mm = $('#dob_month');
	var my_dob_yyyy = $('#dob_year');
	var card_type = $('#card_type');
	var card_name = $('#card_name');
	var card_number = $('#card_number');
	var sec_code = $('#sec_code');
	var expiry_mm = $('#expiry_mm');
	var expiry_yy = $('#expiry_yy');
	var further_info = $('#mswa_general');
	
	$('#first_name').trigger("change");
	$('#last_name').trigger("change");
	$('#address').trigger("change");
	$('#suburb').trigger("change");
	$('#postcode').trigger("change");
	$('#day_phone').trigger("change");
	$('#evening_phone').trigger("change");
	$('#mobile_phone').trigger("change");
	$('#email').trigger("change");
	
	if(((my_phone_d.val()=='') && (my_phone_e.val()=='') && (my_mobile.val()=='')) || ((!allowedChars(my_phone_d.val(),'1234567890')) || (!allowedChars(my_phone_e.val(),'1234567890')) || (!allowedChars(my_mobile.val(),'1234567890')))) {
		m.push('Please enter either your Day, Evening or Mobile phone number.');
		$("#day_phone").addClass(ERROR_CLASS);
		$('#day_phone').siblings('label').addClass(ERROR_CLASS);
		$("#evening_phone").addClass(ERROR_CLASS);
		$('#evening_phone').siblings('label').addClass(ERROR_CLASS);
		$("#mobile_phone").addClass(ERROR_CLASS);
		$('#mobile_phone').siblings('label').addClass(ERROR_CLASS);
		isValid = false;
	} else {
		$("#day_phone").removeClass(ERROR_CLASS);
		$('#day_phone').siblings('label').removeClass(ERROR_CLASS);
		$("#evening_phone").removeClass(ERROR_CLASS);
		$('#evening_phone').siblings('label').removeClass(ERROR_CLASS);
		$("#mobile_phone").removeClass(ERROR_CLASS);
		$('#mobile_phone').siblings('label').removeClass(ERROR_CLASS);
	}
			
	$('#dob_day').trigger("change");
	$('#dob_month').trigger("change");
	$('#dob_year').trigger("change");
	$('#card_type').trigger("change");
	$('#card_name').trigger("change");
	$('#sec_code').trigger("change");	
	//$('#expiry_mm').trigger("change");
	$('#expiry_yy').trigger("change");	
	
	if($('#confirmation:checked').val()!='yes') {
		m.push('Please confirm that your details are correct.');
		$("#confirmation").addClass(ERROR_CLASS);
		$('#confirmation').siblings('label').addClass(ERROR_CLASS);
		isValid = false;
	} else {
		$("#confirmation").removeClass(ERROR_CLASS);
		$('#confirmation').siblings('label').removeClass(ERROR_CLASS);
	}
	
	if(m.length >0) {
		if ($.browser.msie) {
			alert(m.join('\n'));
		} else {
			if($('#olbg').length) {
				var olbg = $('#olbg');
			} else {
				var olbg = $('<div id="olbg"></div>');
			}
			if($('#errmsgs').length) {
				var de = $('#errmsgs');
			} else {
				var de = $('<div id="errmsgs"></div>');	
			}
			de.html('<h2>Please address the following problems</h2><p>'+m.join("<br />")+'</p><br /><a href="#" id="close_errs">OK</a>');
			$('body').append(de);
			$('body').append(olbg);
			
			de.css({'margin-top':'-'+$(de).height()/2+'px'});
			$('#close_errs').bind('click',function(e) {
				e.preventDefault();
				de.fadeOut(100,function(){
					de.remove();
					olbg.fadeOut(100,function(){
						olbg.remove();
					});
				});
			});
			$('#olbg').bind('click',function(e) {
				e.preventDefault();
				de.fadeOut(100,function(){
					de.remove();
					olbg.fadeOut(100,function(){
						olbg.remove();
					});
				});
			});
		}
	}
	
	return isValid;
}

function checkField(f) {
	var r = true;
	var v = $(f).val();
	if(v == '') {
		$(f).addClass(ERROR_CLASS);
		if($(f).siblings('label')) {
			$(f).siblings('label').addClass(ERROR_CLASS);
		}
		r = false;
	} else {
		$(f).removeClass(ERROR_CLASS);
		if($(f).siblings('label')) {
			$(f).siblings('label').removeClass(ERROR_CLASS);
		}
	}
	return r;
}

function allowedChars(str,chars) {

	var r = true;

	if(chars.length>0) {
		
		var x = -1;
		for(i=0;i<str.length;i++) {
			x = str.charAt(i).toLowerCase();
			if(chars.indexOf(x,0) == -1) {
				r = false;
			}
		}
	} else {
		r = false;
	}
	
	return r;
	
}

function isValidCreditCard(type, ccnum) {

	//strip everything but numbers
	var v = "01234567890";
	var w = '';
	for(i=0;i<ccnum.length;i++) {
		x = ccnum.charAt(i).toLowerCase();
		if(v.indexOf(x,0) != -1) {
			w += x;
		}
	}
	ccnum = w;

   if (type == "Visa") {
      // Visa: length 16, prefix 4, dashes optional.
      var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "Mastercard") {
      // Mastercard: length 16, prefix 51-55, dashes optional.
      var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "Amex") {
      // American Express: length 15, prefix 34 or 37.
      var re = /^3[4,7]\d{13}$/;
   } else {
	   return false;
   }
   if (!re.test(ccnum)) return false;
   ccnum = ccnum.split("-").join("");
   var checksum = 0;
   for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
      checksum += parseInt(ccnum.charAt(i-1));
   }
   for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
      var digit = parseInt(ccnum.charAt(i-1)) * 2;
      if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
   }
   if ((checksum % 10) == 0) {
	   $('#card_number').val(ccnum);
	    return true;
   } else {
	    return false;
   }
}


// Declaring valid date character, minimum year and maximum year
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
	for (i = 0; i < s.length; i++){   
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	return true;
}

function stripCharsInBag(s, bag){
	var i;
	var returnString = "";
	for (i = 0; i < s.length; i++){   
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

function daysInFebruary (year){
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
	} 
	return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var strMonth=$('#dob_month').val();
	var strDay=$('#dob_day').val();
	var strYr=$('#dob_year').val();

	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);

	if ((month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false;
	}
	if (year<minYear || year>maxYear){
		return false;
	}
return true
}

function buyTickets() {
	
	//grab the total
	num_tix = $('#num_of_tickets').val();
	if(!processing) {
		startProcess();
		var disabled_fields = $('#tickets_form').find(':input:disabled').removeAttr('disabled');
		var serialised_data = $('#tickets_form').serialize();
		disabled_fields.attr("disabled","disabled");
		$.ajax({
			url:'buy_tickets.php',
			type:'GET',
			data: serialised_data,
			success:function(data) { 
				//stopProcess();
				processing=false;
				//we have a response
				if(data.substr(0,1)=='0') {
					var ePop = 'Sorry, there was a problem with the information you submitted.\nPlease review your information and click "Submit" to try again.';
					if(data.length>1) {
						var eMsg = data.substr(2);
						if(eMsg.length) {
							ePop = 'Sorry, there was a problem with the information you submitted.\n'+eMsg;
						}
					}
					alert(ePop);
					stopProcess();
				} else {
					var tmp_date = new Date();
					tmp_date = tmp_date.getTime();
					var order_id = "MSMHL"+tmp_date;
					//run ecommerce analytics
					_gaq.push(['_addTrans',
						order_id,             // order ID - required
						'MS Society WA',      // store name
						$('#num_of_tickets').val() * 100,        // total - required
						'0',                  // tax
						'0',                  // shipping
						$('#suburb').val(),   // city
						$('#state').val(),    // state or province
						$('#country').val()   // country
					]);
					
					_gaq.push(['_addItem',
						order_id,           // order ID - required
						'MHL2012',           // SKU/code - required
						'MHL2012 Ticket',        // product name
						'Tickets',   // category or variation
						'100',          // unit price - required
						$('#num_of_tickets').val()    // quantity - required
					]);
					
					_gaq.push(['_trackTrans']); //submits transaction to the Analytics servers
					
					_gaq.push(function() {
						location.href="/thank-you.html";
					});
					
				}
			}
	
		});	
	}
}

function startProcess() {
	processing = true;
	$('#submit').html('Loading');
	Cufon.replace('#submit',{fontFamily:'abq'});
}

function stopProcess() {
	processing = false;
	$('#submit').html('Submit');
	Cufon.replace('#submit',{fontFamily:'abq'});
}
