var chosen_options = null;
$(document).ready(function() { //Declare some regex filters - can be changed later.
	//borrowed from jquery easing plugin
	//$.scrollTo(0);
	$.easing.elasout = function(x, t, b, c, d) {
		var s = 1.70158;
		var p = 0;
		var a = c;
		if (t == 0) return b;
		if ((t /= d) == 1) return b + c;
		if (!p) p = d * .3;
		if (a < Math.abs(c)) {
			a = c;
			var s = p / 4;
		} else var s = p / (2 * Math.PI) * Math.asin(c / a);
		return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
	};
	var letters_only = /^[A-Za-z -]+$/;
	var numbers_only = /^[0-9 -]+$/;
	var valid_email_regex = /^[\w-\.]{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,6}$/;
	var valid_ban_regex = /8[0-9]{9}/;
	var valid_msisdn_regex = /08[0-9]{8}/;
	var valid_dob_regex = /[0-9]{2}\/[0-9]{2}\/[0-9]{4}/; // Declare some variables
	var cust_type = '3customer';
	var tariff_type = '';
	var password_required = false;
	var business_password_required = false;
	var topup_details_required = false; // CSS fix
	$('input[name^=ThreeCustomer]').live('click', function() {
		$('tr.variable,tr.password_yes,tr.password_no').hide();
		debug("Changed customer type.", $(this).val());
		if ($(this).val() == 'false') {
			cust_type = 'non_3customer';
			pop_options($('#querytype'), tariff_options_none);
			$('input[name^=Tariff]').attr('checked', false).parent().parent().parent().hide();
		} else {
			cust_type = '3customer';
			if (!$('input[name^=Tariff]').val()) {
				pop_options($('#querytype'), ["Select a tariff above"]);
			}
			$('input[name^=Tariff]').parent().parent().parent().show();
		}
	});
	
	$('input[name^=Tariff]').live('click', function() {
		debug("Changed tariff type.", $(this).val());
		$('tr.variable,tr.password_yes,tr.password_no').hide();
		switch ($(this).val()) {
		case '3pay':
			tariff_type = '3pay';
			pop_options($('#querytype'), tariff_options_consumer, "Please choose an option.");
			$('tr.tariff_3pay').show();
			break;
		case 'Billpay':
			tariff_type = 'billpay';
			pop_options($('#querytype'), tariff_options_consumer);
			$('tr.tariff_billpay').show();
			break;
		case 'Business':
			tariff_type = 'business';
			pop_options($('#querytype'), tariff_options_business);
			$('tr.tariff_business').show();
			break;
		default:
			tariff_type = '';
			pop_options($('#querytype'), tariff_options_none);
			break;
		}
	});
	
	$('input[name^=Password]').live('click', function() {
		$('tr.password_yes, tr.password_no,tr.topup_mode').hide();
		$('tr.password_' + $(this).val()).show();
		password_required = ($(this).val() == 'yes');
	});
	
	$('input[name^=Admin]').live('click', function() { //$('tr.password_yes, tr.password_no').hide();
		debug($(this).val());
		if ($(this).val() == "yes") {
			$('tr.business_password').show();
		} else {
			$('tr.business_password').hide();
		}
		business_password_required = ($(this).val() == "yes");
	});
	
	$('#topup_value').change(function() {
		debug($(this).val());
		if ($(this).val() !== "_inv" && $(this).val() !== "default") {
			$('tr.topup_mode').show();
		} else {
			$('tr.topup_mode').hide();
		}
	});
	
	$('#querytype').live('change', function() {
		$('div.suggested_links').find("ul").remove(); 
		$('div.suggested_links:visible').fadeOut('fast', function(){
			
		});
		var c = window[chosen_options];
		var v = $(this).val();
			
		//console.log(v);
		if(v > -1){ // Valid value
			var current = c[v];
			var suboptions = current.sub_options;
			//console.log(suboptions);
			if(typeof suboptions != 'undefined' && suboptions.length > 0){
				pop_second_options($('#subquerytype'), suboptions);
				$('tr.subquery_type').show();
			}
		}
		
  	});

	
	/* New suggested help section */
	
	$arr = new Array();
	
	
	
	$('#contactForm').submit(function(e) {
		$('span.errors').remove();
		debug("Customer_type: ", cust_type);
		var errors = []; // Check name
		if ($('#first_name').val().length < 2 || $('#surname').val().length < 2) {
			errors[errors.length] = {
				error: "First Name/Surname are required field(s), and must be at least 2 characters in length.",
				scope: $('#first_name, #surname')
			};
		} else {
		
			if (!letters_only.test($('#first_name').val())) {
				errors[errors.length] = {
					error: "Your name can contain only letters, spaces, hyphens and apostrophes.",
					scope: $('#first_name, #surname')
				};
			}
		}
		
		if ($('#alt_no').val() !== '' && !numbers_only.test($('#alt_no').val())) {
			errors[errors.length] = {
				error: "Alternate contact number should contain digits and hyphens only.",
				scope: $('#alt_no')
			};
		}
		
		if ($('#query').val() == '') {
			errors[errors.length] = {
				error: "Please enter your query.",
				scope: $('#query')
			};
		} // Check valid email
		if (!valid_email_regex.test($('#email').val())) {
			errors[errors.length] = {
				error: "Your email address is invalid.",
				scope: $('#email')
			};
		} // Series of nested switch statements.. hold tight!
		
		
		var msisdn_entered = (cust_type == '3customer' && (tariff_type == '3pay' || tariff_type == 'billpay') && $('#mobile_no').val() != '');
		var ban_entered = (cust_type == '3customer' && (tariff_type == '3pay' || tariff_type == 'billpay') && $('#acc_no').val() != '');
		
		var msisdn_or_ban_entered = (msisdn_entered || ban_entered); 
		
		//debug("Debugging:", msisdn_entered, ban_entered, msisdn_or_ban_entered);
		
		
		switch (cust_type) {
		case '3customer':
			debug(tariff_type);
			switch (tariff_type) {
			case '3pay':
				if (!$('input[name^=Password]:checked').val()) {
					errors[errors.length] = {
						error: "Please select whether or not you know your account password.",
						scope: $('input[name^=Password]')
					};
				}
				if (password_required && $('#password').val() == '') {
					errors[errors.length] = {
						error: "Password is a required field.",
						scope: $('#password')
					};
				}
				if (!password_required && $('#topup_value').val() == 'default') {
					errors[errors.length] = {
						error: "You need to choose a top-up value, or choose Not Topped Up yet.",
						scope: $('#topup_value')
					};
					
				}
				if (!password_required && $('#topup_value').val() != 'default' && $('#topup_value').val() != '_inv' && $('#topup_mode').val() == 'default') {
					errors[errors.length] = {
						error: "You need to choose a top-up mode.",
						scope: $('#topup_mode')
					};
					
				}
				
				if(msisdn_or_ban_entered){
					if (msisdn_entered && !valid_msisdn_regex.test($('#mobile_no').val())) {
						errors[errors.length] = {
							error: "Your mobile number must be in the format 08XXXXXXXX.",
							scope: $('#mobile_no')
						};
					} 
					if (ban_entered && !valid_ban_regex.test($('#acc_no').val())) {
						errors[errors.length] = {
							error: "Your account number must be in the format 8XXXXXXXXX (10-digits beginning with 8).",
							scope: $('#acc_no')
						};
					} 
				} else {
					errors[errors.length] = {
						error: "One of MSISDN or Account No. is required.",
						scope: $('#acc_no')
					};
				}
				
				break;
			case 'billpay':
			
				if(msisdn_or_ban_entered){
					if (msisdn_entered && !valid_msisdn_regex.test($('#mobile_no').val())) {
						errors[errors.length] = {
							error: "Your mobile number must be in the format 08XXXXXXXX.",
							scope: $('#mobile_no')
						};
					} 
					if (ban_entered && !valid_ban_regex.test($('#acc_no').val())) {
						errors[errors.length] = {
							error: "Your account number must be in the format 8XXXXXXXXX (10-digits beginning with 8).",
							scope: $('#acc_no')
						};
					} 
				} else {
					errors[errors.length] = {
						error: "One of MSISDN or Account No. is required.",
						scope: $('#acc_no')
					};
				}
				
				if (!valid_dob_regex.test($('#dob').val())) {
					errors[errors.length] = {
						error: "Your date of birth must be in the format DD/MM/YYYY",
						scope: $('#dob')
					};
				} else {
					if (!valid_dob($('#dob').val(), valid_dob_regex)) {
						errors[errors.length] = {
							error: "Date of birth range invalid. Must be > 14 and < 90 years old.",
							scope: $('#dob')
						};
					}
				}
				if ($('#address_1').val() == '') {
					errors[errors.length] = {
						error: "Address 1 is a required field.",
						scope: $('#address_1')
					};
				}
				if ($('#county').val() == '0') {
					errors[errors.length] = {
						error: "County is a required field.",
						scope: $('#county')
					};
				}
				if (!msisdn_entered && !ban_entered) {
					errors[errors.length] = {
						error: "One of Account No. or MSISDN is required.",
						scope: $('#acc_no')
					};
				}
				break;
			case 'business':
				
				business_password_required = ($('input[name^=Admin]:checked').val() == "yes");
				
				debug("Business password required: ", business_password_required);
				
				if (business_password_required && $('#business_password').val() == '') {
					errors[errors.length] = {
						error: "You must fill in your business password",
						scope: $('#business_password')
					};
				}
				
				if (!business_password_required) {
					debug("Breakpoint");
					errors[errors.length] = {
						error: "Sorry but we are unable to share / discuss / resolve account related queries until we speak with your account administrator.",
						scope: $('input[name^=Admin]')
					};
				}
				break;
			default:
				errors[errors.length] = {
					error: "You must choose your tariff",
					scope: $('input[name^=Tariff]')
				};
				break;
			}
			break;
		case 'non_3customer':
			break;
		default:
			// Something went wrong, invalidate the form
			errors[errors.length] = {
				error: "An unknown error occurred",
				scope: $('tr td.terms')
			};
		}
		var valid_form = errors.length == 0;
		if (!valid_form) { //debug(errors);
			for (i in errors) {
				var d = $(document.createElement("span")).addClass("errors").html(errors[i].error); // if its a radio button, add it to the parent td, at the end, otherwise, add it directly after the input.
				if (errors[i].scope.is(":radio")) {
					errors[i].scope.parents("td:first").append(d);
				} else {
					errors[i].scope.after(d);
				}
			} // Scroll to the first error. 
			var $f = errors[0].scope;
			//$.scrollTo($f, 300);
		} else {
			$('#contactForm').append("<input type='hidden' name='querytype_text' value='" + $('#querytype').find(':selected').text() + "' />");
			//$('#contactForm').append();
		} 
		
		return valid_form;
	});
});

function populate_options_by_tariff(tariffValue) {
	switch (tariffValue) {
	case '3pay':
	case 'Billpay':
		pop_options($('#querytype'), tariff_options_consumer);
		break;
	case 'Business':
		pop_options($('#querytype'), tariff_options_business);
		break;
	default:
		pop_options($('#querytype'), [], {
			optionValue: "",
			optionText: "Please choose a tariff above."
		});
		break;
	}
}
function valid_dob(date_of_birth, regex) {
	var n = new Date();
	var min = n.setFullYear(n.getFullYear() - 14);
	n = new Date();
	var max = n.setFullYear(n.getFullYear() - 90);
	return to_us_date(date_of_birth) > max && to_us_date(date_of_birth) < min;
}
function to_us_date(str) { // Format the date as US format. Temporarily. Its not forever. I wouldnt be that mean. 
	var d = str.split("/");
	return Date.parse(d[1] + "/" + d[0] + "/" + d[2]);
}

function pop_options(target, options, defaultOption) {
	window[chosen_options] = options;
	target.children("option").remove();
	target.append($('<option></option>').html("Please choose an option.").attr("value", "-1").attr("selected", "selected"));
	//console.log(options);
	for (i in options) {
		var f = options[i].title;
		target.append($('<option></option>').html(f).val(i));
	}
	//console.log(window[chosen_options]);
}

function pop_second_options(selector, chosen_options){
	$('div.suggested_links').hide();
	selector.children().remove();
	selector.append($('<option></option>').html("Please choose an option.").attr("value", "-1").attr("selected", "selected"));
	//console.log(chosen_options);
	for (i in chosen_options) {
		var f = chosen_options[i].title;
		selector.append($('<option></option>').html(f).val(i));
	}
	selector.live("change", function(e){
		//console.log(e);
		$('div.suggested_links').find("ul").remove();
		var x = $(this).val();
		//console.log(x, chosen_options[x].links);
		if(typeof chosen_options[x].links != 'undefined' && chosen_options[x].links.length > 0){
			var u = $(document.createElement("ul"));
			for(i in chosen_options[x].links){
				var t = chosen_options[x].links[i];
				var $l = $(document.createElement("li")); 
				$l.append($(document.createElement("a")).attr("href", t.link_uri).attr("target", "_blank").append(t.link_title).addClass("int_trk").attr("title", "Help &amp; Support - " + t.link_title));
				$l.appendTo(u);
			}
			$('div.suggested_links').append(u).fadeIn("fast");
		}
	});
}

window.debug = function() {
	debug.history = debug.history || []; // store logs to an array for reference
	debug.history.push(arguments);
	if (this.console) {
		console.log(Array.prototype.slice.call(arguments));
	}
};

