$().ready(function(){
		
		var unitsEntered;
		var currencySymbol;
		
		$("input#jsEnabled").val("true");
		
		$.validator.addMethod("unitsVerify", function(value) {
													
												value = $.trim(value);
												
												if(!value)
													return false;
													
												var units =  parseInt(value,10);
												if(units < 500)
													return false;
													
												return Boolean(!(units%500));
												
												unitsEntered = units;
												return true;
									  		 }
									  , 'Invalid amount of units! <br />It must be in multiples of 500 <br />(e:g 500,1000,2500,5000,10000 etc)');
		
		$("#signupForm").validate({
			rules: {
				currency: "required",
				units: "unitsVerify"
			},
			messages: {
				currency: "Please select a currency"
				//units: "Invalid amount of units."
			},
			errorElement: "p",
			errorContainer: $("#summary")
	    });
		
		$("#signupForm").bind("invalid-form.validate", function() {
										$("p.error").addClass("alert");
										$("span#summary").html("The form contains error. Please correct them.");
					});
		$("select#currency").bind("change",function(e){
												calculateTotal(this);	
										  });
		$("input#units").bind("blur",function(e){
												calculateTotal($("select#currency"));	
										  });
		function calculateTotal(e){

			if(isFormValid() === false)
				return;
				
			var currency = $(e).val();
			var unitsEntered = unitsEntered || $("input#units").val();
			switch(currency){
				
				case "naira":
					currencySymbol = "NAIRA";
					setAmount(unitsEntered * 100);
					break
				case "dollars":
					currencySymbol = "USD";
					setAmount(unitsEntered * 0.8584);
					break;
				case "pounds":
					currencySymbol = "GBP";
					setAmount(unitsEntered * 0.4393);
					break;
				case "euro":
					currencySymbol = "EUROS";
					setAmount(unitsEntered * 0.5542);
					break;				
			}
			
		}
		
		function setAmount(amount){
			
			$("input#totalAmountInput").val(amount);
			$("span#totalAmount").html(new NumberFormat(amount).toFormatted() + " "+currencySymbol);
			$("input#formattedTotalAmountInput").val(new NumberFormat(amount).toFormatted() + " "+currencySymbol);
		}
		
		function isFormValid(){
			return $("#signupForm").valid();
		}

});