/*
 *	Client-side code for the EMAP conference booking form
 */

var EMAP;

(function($){
	EMAP = {
		step1: function(rules){
			EMAP.validate(rules);
			EMAP.postcode();
			EMAP.validityListener(EMAP.proceedStatus);
			$(document).bind("close.facebox", function(){
				if ($.browser.msie && $.browser.version.substr(0,1)<7) {
					$("select").css("visibility", "visible");
				}
			}).bind("reveal.facebox", function(){
				if ($.browser.msie && $.browser.version.substr(0,1)<7) {
					$("select").css("visibility", "hidden");
				}
			});
			$('a[rel*=facebox]').facebox();
		},
		step2: function(rules){
			EMAP.validate(rules);
			EMAP.validityListener(EMAP.proceedStatus);


			$(".next_disabled").click(function(e){
			    e.preventDefault();
				$("[name=step2]").attr("action","?step=4");
				$("[name=step2]").submit();
			});
			$(".next").click(function(e){
			    e.preventDefault();
				$("[name=step2]").attr("action","?step=4");
				$("[name=step2]").submit();
			});
			$("[name=attending]").click(function(){
				if($("#attendingyes").attr("checked")){
					$("#product-selection").show("fast");
				}
				if($("#attendingno").attr("checked")){
					$("#product-selection").hide("fast");
				}
			});
			if(!$("#attendingyes").attr("checked")) {
				$("#product-selection").hide();
			}
		},
	
		step3: function(rules){
			EMAP.validate(rules);

			if($(".summary-attendees").text() === "" || $("[name=step2]").hasClass('edit_attendee'))  {
			  		EMAP.validityListener(EMAP.proceedStatus);
			}
			// when user option "anonymous" is yes, then disable name fields, otherwise enable
			var names = {firstname: "", surname: ""};
			var step3_anon = function(){
				// setting firstname and surname first so that 'else' does not replace values with nothing
				names.firstname = $("#firstname").val();
				names.surname = $("#surname").val();
				if($("#anon").attr("checked")){
					$("#attendee-details .error-container").css("display", "none");
					names.firstname = $("#firstname").val();
					names.surname = $("#surname").val();
					$("#firstname, #surname").attr("disabled", true).val("");
				} else{
					$("#attendee-details .error-container").css("display", "inline");
					$("#firstname").val(names.firstname);
					$("#surname").val(names.surname);
					$("#firstname, #surname").attr("disabled", false);
				}
			};
			
			$("#anon").change(step3_anon);
			step3_anon();
		},
	
		step4: function(rules){
			EMAP.validate(rules);
	  		EMAP.validityListener(EMAP.proceedStatus);
	
			$(".savelast").click(function(e){
			    e.preventDefault();
			//	$("[name=step2]").attr("action","?step=5");
				$("[name=step4]").submit();
			});
		},
		step4b: function(rules){
			EMAP.validate(rules);
	  		EMAP.validityListener(EMAP.proceedStatus);

			// when user option "provide details" is yes, then show address form, otherwise hide
			
			$(".savelast").click(function(e){
			    e.preventDefault();
			//	$("[name=step2]").attr("action","?step=5");
				$("[name=step4b]").submit();
			});
			
			if($("#anon").val()) {
				$(".anon_details").hide();
			}
			
			$("#anon").change(function(){
				$(".anon_details").toggle("fast");
			}); 	
			
			EMAP.postcode();
			// when "invoice address is the same as the other address" is checked, populate fields from the data
			EMAP.fillBookerAddress($("#same_as_booker_address"));

		},
	
		step5: function(rules){
			EMAP.validate(rules);
			EMAP.postcode();
			EMAP.validityListener(EMAP.proceedStatus);

			// when user option "invoice me" is selected, show PO Options, otherwise hide.
			if($("#paymentType").val() !== "invoice_me") {
				$("#po_choices").hide();
			}             

			$("#paymentType").change(function(){
				if($("#paymentType").val() === "invoice_me") {
					$("#po_choices").show("fast");
					$("fieldset.invoice_address legend").text("Invoice Address");	
				}
				else if($("#paymentType").val() === "credit_card") {
					$("#po_choices").hide("fast");
					$("fieldset.invoice_address legend").text("Card Holder's Address");
				}
				else {
					$("#po_choices").hide("fast");
					$("fieldset.invoice_address legend").text("Invoice Address");
				}
			});

			// when user option "have a PO Number" is selected, enable PO Field, otherwise disable.
			var po_num = $("#po_number").val();
			var last;
			var disable = function(e){
				var error = $("#po_number").nextAll(".error-container").eq(0);
				if($("#po_c").attr("checked")){
					$("#po_number").val(po_num).attr("disabled", false);
					error.css("display", "inline");
				} else{
					if("po_c" === last){
						po_num = $("#po_number").val();
					}
					$("#po_number").val("");
					$("#po_number").attr("disabled", true);
					error.css("display", "none");
				}
				
				if(e){
					last = e.target.id;
				}
			};
			$("[name=po_choice]").change(disable);
			disable();
			
			// when "invoice address is the same as the other address" is checked, populate fields from the data
			EMAP.fillBookerAddress($("#same_as_booker_address"));
                
		},
	
		step6: function(rules){
		},
	
		step8: function(rules){
		},

	
		addressFields: ["postcode", "address1", "address2", "address3", "towncity", "county", "country"],
		// common code
		postcodeInstance: false,
		postcode: function(){
			EMAP.postcodeInstance = $("#postcode").jPostcode({
				addressUrl: "/_media/javascript/get-address-by-id?pcaid=",
				addressesUrl: "/_media/javascript/get-addresses-by-postcode?postcode=",
				width: 240,
				fieldMap: {
					line1: "address1",
					line2: "address2",
					line3: function (name, val, json) {
						if (json.line4) {
							val += ", " + json.line4;
						}
						if (json.line5) {
							val += ", " + json.line5;
						}
						$("#address3").val(val);
					},
					post_town:"towncity",
					postcode:"postcode"
				},
				onPopulate: function (json) {
					$("#country").val("UK");
				},
				afterPopulate: function(){
					if(EMAP.validateInstance){
						$.each(EMAP.addressFields, function(i, id){
							$("#" + id).valid();
						});
						EMAP.proceedStatus(EMAP.validateInstance.checkForm());
					}
				},
				errornode: $("<label class='error'></label>").insertBefore($("#postcode")),
				errorFadeTime: 5000
			});
		},
		validateInstance: false,
		validate: function(rules){
			EMAP.validateInstance = $(".conferenceBookingForm").validate(rules);
			
			var containers = $(".error-container");
			for(var i = 0, l = containers.length; i < l; i++){
				if(containers.eq(i).children("label.error").length){
					EMAP.validateInstance.form();
					break;
				}
			}
		},
		validityListener: function(fns){
			var args = arguments;
			var callback = function(e){
		        $.each(args, function(i, fn){
		            fn(EMAP.validateInstance.checkForm());    
		        });
		    };
		    $("form.conferenceBookingForm").keyup(callback).click(callback).change(callback);
			callback();

		},
		proceedStatus: function(validity){
			var status_message = "You have not finished updating the details of one of the delegates.<br/>You must complete this before you can continue.";
			if($(".step_4.active").length) {
				status_message = "You must complete this form before you can continue.";
			}
			
			if(validity && $(".Incomplete").length === 0)
			{
				$(".booking_status dl dd").removeClass('not_proceed');
				$(".booking_status dl dd").addClass('proceed');
				$(".booking_status dl dd").text("You may proceed");
				$(".booking_status p.status_message").html("");
				if($(".next_disabled a").length > 0) {
					$(".next_disabled").addClass('next');
					$('.next_disabled').unbind('.clink');
					$(".next").removeClass('next_disabled');
				}
			}
			else
			{
				$(".booking_status dl dd").removeClass('proceed');
				$(".booking_status dl dd").addClass('not_proceed');
				$(".booking_status dl dd").text("You may not proceed");
				$(".booking_status p.status_message").html(status_message);
				if($(".next a").length > 0) {
					$(".next").addClass('next_disabled');
					$(".next_disabled").removeClass('next');
					$(".next_disabled").bind('click.clink',function(e){
					    e.preventDefault();
					});
				}
			}
		},
		fillBookerAddress: function(checkbox){
			var previous_values = {};
			var replace = function(e){
//				for hiding the address fields should that become necessary
//				var address_container = $(checkbox).parent(".field").next();
				if($(checkbox).attr("checked")){
					//address_container.hide();
					$.each(EMAP.addressFields, function(i, name){
						var field = $("[name=" + name + "]");
						previous_values[name] = field.val();
						field.val(booker_address[name]);
						if(e){
							field.valid();
						}
					});
				} else{
					//address_container.show();
					$.each(EMAP.addressFields, function(i, name){
						var field = $("[name=" + name + "]");
						field.val(previous_values[name]);
						if(e){
							field.valid();
						}
					});
				}
			};
			
			$(checkbox).click(replace);
			replace(false);
		}
	};
})(jQuery);
