$(document).ready(function(){

	var MSIEVersion = 0;
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
		var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
		if (ieversion>=8)
			MSIEVersion = 8;
		else if (ieversion>=7)
			MSIEVersion = 7;
		else if (ieversion>=6)
			MSIEVersion = 6;
		else if (ieversion>=5)
			MSIEVersion = 5;
	}else{
		MSIEVersion = -1;
	}
	
	if(MSIEVersion > 0 &&  MSIEVersion < 7){

		$(function(){
			
			$("<div id='ie6overlay'></div>")
				.css({
					'height': $(window).height()
				})
				.appendTo("body");
				
			$("<div id='ie6notice'><div id='ie6close'></div><img src='views/default/images/no-ie6.gif' alt='' style='float: left;'/><p style='padding-left: 225px;'><br /><strong>Sorry! This site doesn't support Internet Explorer 6.</strong><br /><br />If you'd like to be able to use all functions in faxtastic!, please <a href='http://www.browserchoice.eu'>upgrade your browser</a>.</p><div id='ie6info' title='"+navigator.userAgent+"'>&nbsp;</div></div>")
				.appendTo("body");
		});		
	}

	$('#ie6close').click(function(){
		$("#ie6notice").remove();
		$("#ie6overlay").remove();
	});



	// Set up modal dialogues
	$('#signupDialog').jqm({
		toTop: true,
		modal: true /* FORCE FOCUS */
	});


	if(pageStep == ""){
		num = chooseNumber($("#rateCode").val(),0);
	}
	
	if(pageStep == "details"){
		$("#claimFaxStep1").hide();
		$("#claimFaxStep2").show();
		$("span.chosenNumber").text($("#areaCode").val() + $("#pickedNumber").val());
		$("input#chosenNumber").val($("#pickedNumber").val());			
	}
	
	$("#getNumber")
		.click(function(e){
			e.preventDefault();
			getNumber();		
			return false;
		})
		.mouseover(function(e){
			changeButton($(this), e);
		})
		.mouseout(function(e){
			changeButton($(this), e);
		});
	
	$("#getYourDialingCode")
		.mouseover(function(e){
			changeButton($(this), e);
		})
		.mouseout(function(e){
			changeButton($(this), e);
		});
	
	
	$('.CloseButton')
		.click(function(){
			$("#signupDialog").jqmHide();
	});
	$('#cancel_FP')
		.click(function(){
			var src = $(this).attr("src").match(/[^\.]+/) + "";
			src = src.substring(0,src.length -5 ) + ".gif";
			$(this).attr("src", src);
			$("#signupDialog").jqmHide();
			return false;
		})
		.mouseover(function(e){
			changeButton($(this), e);
		})
		.mouseout(function(e){
			changeButton($(this), e);
		});
	$('#continue_FP')
		.click(function(){
			var complete = false;
			
			if($("#signupDetails_FP").valid()){
				//Create account in FT
				
				if($('#optOut:checked').val() == 1){ optOut = 1; }else{ optOut = 0; }
				
				$.ajax({
					type: "POST",
					url: ssl + "api/accounts/add('" + $('#email').val() + "','" + $('#password').val() + "','" + $('#firstname').val() + "','" + $('#lastname').val() + "','OK')",
					async: false,
					cache: false,
					timeout: 3000,
					success: function(msg){
						cid = msg;
					},
					error: function(){
						alert("Error adding account");
					}
				});
				if(cid != '"EmailInUse"'){
					
					// Select the number and reserve
					faxNumber = $("#chosenNumber").val();
					areaCode = $("#areaCode").val();
					
					$.ajax({
						type: "POST",
						url: ssl + "api/nums('" + areaCode + faxNumber + "')/reserve('" + cid + "')",
						async: false,
						cache: false,
						timeout: 3000,
						success: function(msg){
							res = msg;
						},
						error: function(){
							alert("Error reserving number");
						}
					});
					
					if(res == 'true'){			
						// Create account in Concord
						$.ajax({
							type: "POST",
							url: ssl + "api/accounts()/select('" + $('#email').val() + "')/billingaddress('" + $('#firstname').val() + "','" + $('#lastname').val() + "','" + $('#company').val() + "','" + $('#addr1').val() + "','" + $('#addr2').val() + "','" + $('#town').val() + "','" + $('#county').val() + "','United Kingdom','" + $('#postcode').val() + "','" + $('#phone').val() + "','','" + $('#email').val() + "','OK'," + optOut + ",'','" + $('#sourceTag').val() + "')",
							async: false,
							cache: false,
							timeout: 3000,
							success: function(msg){
								con = msg;
							},
							error: function(){
								alert("Error selecting number");
							}
						});
						
						if(con == 'true'){			
							// Assign the number to the customer
							$.ajax({
								type: "POST",
								url: ssl + "api/nums('" + areaCode + faxNumber + "')/assign('" + cid + "','" + $('#email').val() + "','','PDF','OK','0871free')",
								async: false,
								cache: false,
								timeout: 3000,
								success: function(msg){
									assNum = msg;
								},
								error: function(){
									alert("Error assigning number");
								}
							});
							
							if(assNum == 'true'){
									
								// Register the user to send faxes
								$.ajax({
									type: "POST",
									url: ssl + "api/send('" + cid + "')/register('" + $('#email').val() + "')",
									async: false,
									cache: false,
									timeout: 3000,
									success: function(msg){
										register = msg;
									},
									error: function(){
										alert("Error registering for send");
									}
								});
								if(register == 'true'){
									complete = true;
									$.ajax({
										type: "POST",
										url: ssl + "api/_sendWelcomePack('" + $('#email').val() + "', '" + $('#email').val() + "', '', '0871free', '" + areaCode + " " + faxNumber + "', '', '" + cid + "')",	
										async: false,	
										cache: false,
										timeout: 3000,
										success: function(msg){
											cid = msg;
										},
										error: function(){
											alert("Error sending welcome pack");
										}
									});
								}else{
								validator.showErrors({"formError": "Error in registering user to send - " + register});
							}
							}else{
								validator.showErrors({"formError": "Error in assigning number - " + assNum});
							}
						}else{
							validator.showErrors({"formError": "Error in creating concord record - " + con});
						}
					}else{
						if(res == '"NoSelection"'){ validator.showErrors({"formError": "No fax number selected"}); }
						if(res == '"NumNotAvailable"'){ validator.showErrors({"formError": "Fax number not available"}); }
						if(res.indexOf("InvalidStatus")){ validator.showErrors({"formError": res}); }
					}
				}else{
					validator.showErrors({"email": "Email in use"});
				}
			}
			
			return complete;
		})
		.mouseover(function(e){
			changeButton($(this), e);
		})
		.mouseout(function(e){
			changeButton($(this), e);
	});
	
	var validator = $("#signupDetails_FP").validate({
		errorContainer: "#messageBox",
		errorLabelContainer: "#messageBox ul",
		wrapper: "li class='frontpage'",
		rules: {
			email: {
				required: true,
				email: true,
				emailFree: true
			},
			password: {
				required: true,
				minlength: 5
			},
			password2: {
				equalTo: "#password",
				required: true,
				minlength: 5
			},
			postcode: {
				required: true,
				postalcode: true
			}
		},
		messages: {
			agree087: "You must agree to the OFCOM 087 regulations",
			firstname: "Enter your first name", 
			lastname: "Enter your last name",
			addr1: "Enter at least the first line of your address",
			town: "Enter your town",
			county: "Enter your county",
			postcode: {
				required: "Enter your postcode"
			},
			phone: "Enter a contact phone number",
			email: {
				required: "Please enter a valid email address"
			},
			password: {
				required: "Please provide a password",
				minlength: "Your password must be at least 5 characters long"
			},
			password2: {
				required: "Please confirm the password",
				minlength: "Your password must be at least 5 characters long",
				equalTo: "Please enter the same password as above"
			}
		}
	});

	// Check email has not been used when email input loses focus
	$.validator.addMethod('emailFree', function(value){
		var free = true;
		$.ajax({
			type: "POST",
			url: ssl + "api/accounts/available('"+value+"')",
			async: false,
			cache: false,
			timeout: 10000,
			success: function(msg){
				if(msg == '"InvalidEmail"'){ free = false; }
				if(msg == 'false'){
					free = false;
				}
			},
			error: function(){
				free = false;
			}
		});
		if(free) {
			$("#errorCont").css('display',"none");
			return true;
		}else{ return false;}
	}, 'Your email address is already registered with us. Please go to the <a href="{/q/metadata/root}control_panel">log in page</a>.');


	$.validator.addMethod('postalcode', function (value) {
		// Permitted letters depend upon their position in the postcode.
		var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
		var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
		var alpha3 = "[abcdefghjkpmnrstuvwxy]";                         // Character 3
		var alpha4 = "[abehmnprvwxy]";                                  // Character 4
		var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5
		
		// Array holds the regular expressions for the valid postcodes
		var pcexp = new Array ();
		
		// Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
		pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
		
		// Expression for postcodes: ANA NAA
		pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
		
		// Expression for postcodes: AANA  NAA
		pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "{1}" + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
		
		// Exception for the special postcode GIR 0AA
		pcexp.push (/^(GIR)(\s*)(0AA)$/i);
		
		// Standard BFPO numbers
		pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
		
		// c/o BFPO numbers
		pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
		
		// Overseas Territories
		pcexp.push (/^([A-Z]{4})(\s*)(1ZZ)$/i);
		
		// Load up the string to check
		var postCode = value;
		
		// Assume we're not going to find a valid postcode
		var valid = false;
		
		// Check the string against the types of post codes
		for ( var i=0; i<pcexp.length; i++) {
			if (pcexp[i].test(postCode)) {
				
				// The post code is valid - split the post code into component parts
				pcexp[i].exec(postCode);
				
				// Copy it back into the original string, converting it to uppercase and
				// inserting a space between the inward and outward codes
				postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
				
				// If it is a BFPO c/o type postcode, tidy up the "c/o" part
				postCode = postCode.replace (/C\/O\s*/,"c/o ");
				
				// Load new postcode back into the form element
				valid = true;
				
				// Remember that we have found that the code is valid and break from loop
				break;
			}
		}
		
		// Return with either the reformatted valid postcode or the original invalid postcode
		if (valid) {return true;} else return false;
	}, 'Please enter a valid postcode');
	
});

function getNumber(){
	var yourNumber, STDCode;
	STDCode = $("#areaCode").val();
	yourNumber = STDCode + " " + $("#pickedNumber").val();

	if(yourNumber.length == 12){
		$('#signupDialog').jqmShow();
		$("span.chosenNumber").text(yourNumber);
		$("input#areaCode").val(STDCode);
		$("input#chosenNumber").val($("#pickedNumber").val());
	}
	return false;		
}



function chooseNumber(rateCode){
	var found, number, codelen, n, STDCode;
	codeLen = 4;
	$("#STDCode").html('<div id="wait"></div>');
	$("#numberChosen").html('<div id="wait"></div>');
	$.ajax({
		type: "POST",
		url: ssl + "api/nums/search('" + rateCode + "')",
		async: false,
        cache: false,
        timeout: 1500,
		success: function(msg){
			number = eval('(' + msg + ')');
			if(number){
				STDCode = number.substr(0,4); 	// Pull the Area Code from the front of the number
				number = number.substr(codeLen); 	// Pull the Area Code from the front of the number
				$("#STDCode").text(STDCode);
				$("#areaCode").val(STDCode);
				$("#numberChosen").text(number);
				$("#pickedNumber").val(number);
				found = true;
			}else{
				$("#numberChosen").text("Sorry we currently have no numbers");
				found = false;
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			console.log(textStatus + " - " + errorThrown);
			found = false;
		}
	});
}
