var stage=1;
var hints = {
		amountowed:						"This is the total amount of <i>unsecured</i> debt you have, to the nearest &pound;",
		creditorscount:				"Specify the number of individual creditors (cards, loans, utilities, etc) you owe to.",
		ccjhistory:						"Let us know if you have recieved any CCJs in the past three years.",
		ccjcount:							"Select the number of CCJs you have recieved in the past three years.",
		homeowner:						"Tell us here if you own your own home (ignore this if you rent, live with some else, etc).",
		mortgagevalue:				"Specify the full value of the mortgage you are currently paying, to the nearest &pound;.",
		outstandingmortgage:	"Specify how much of this mortgage there is still to pay, to the nearest &pound;.",
		securedloans:					"If you have any loans secured against this property, click this box.",
		securedloanamount:		"Enter the value of loans secured against this property, to the nearest pound.",
		disposableincome:			"How much do you have left each month after paying out essentials (bills, rent, mortgage, fuel, food, etc) to the nearest &pound;.",
		nametitle:						"Let us know how you are formally referred to",
		forename:							"Enter your first (or given) name, in full (not a nickname or abbreviation).",
		surname:							"Enter your surname (or family name), in full.",
		homephone:						"Enter your UK phone number here; don't use international prefixes.",
		mobilephone:					"Enter your UK mobile phone number here, if you have one.",
		email:								"Provide your email address so we can give immediate feedback on your application process.",
		housenumber:					"Please enter your house or flat number, such as 'Flat 1, 23' or '22b'",
		postcode:							"Please enter your current postcode to confirm your address and identity (eg, SW1A 1AA or SW1 2AA.",
		whentocontact:				"If you're a busy mum, in a quiet office, or tied up at college, certain times are better to contact you than others; let us know if you have special needs and we'll try to accomodate.",
		howtocontact:					"As much as possible, we'll communicate with you by the means you choose here; we may need to call from time to time though.",
		contactok:						"Click this box to confirm you understand our <a href='/news/terms-conditions' target='_new'>terms and conditions</a> and that we can start processing your application with our partners.",
		creditcheckok:				"While not nescessary, we will notify you if we need to make a credit check. If you tick this box, it gives your consent for us to run a credit check (<i>only</i> if we need to)."
}
//(function($) {
/*	$.fn.customFadeIn = function(speed, callback) {
		$(this).fadeIn(speed, function() {
			if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
			if(callback != undefined)
				callback();
		});
	};
	$.fn.customFadeOut = function(speed, callback) {
		$(this).fadeOut(speed, function() {
			if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
			if(callback != undefined)
				callback();
		});
	};
})(jQuery);*/


/*
jQuery.fn.fadeIn = function(speed, callback) { 
    return this.animate({opacity: 'show'}, speed, function() { 
        if (jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 
 
jQuery.fn.fadeOut = function(speed, callback) { 
    return this.animate({opacity: 'hide'}, speed, function() { 
        if (jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 
 
jQuery.fn.fadeTo = function(speed,to,callback) { 
    return this.animate({opacity: to}, speed, function() { 
        if (to == 1 && jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 
*/


// handle document initialisation
$(document).ready(function(){
	rt=[];
	$("#next").hide();
	$("#stage2").hide();
	$("div#ccjhistorypanel").fadeOut(10);
	$("div#securedloanamountpanel").fadeOut(10);
	$("div#homeownerpanel").fadeOut(10);
	goStage(1);	
	$("#applicationform").find('button,input,select').bind("focus",function(e){
		$("#feedback").html(hints[$(this).attr("id")]);
	}	);
	$("#applicationform").find('button,input,select').bind("blur",function(e){
		$("#feedback").html("");
	}	);
	$('#homephone').bind("blur",function(e){
		if($("#howtocontact option:selected").val()==false) {
			$("#howtocontact option[@selected='selected']").removeAttr("selected");
			$("#howtocontact option[@value='phone']").attr("selected","selected");
		}
	} );
	$('#mobilephone').bind("blur",function(e){
		if(!$("#howtocontact").val()) {
			$("#howtocontact option[@selected='selected']").removeAttr("selected");
			$("#howtocontact option[@value='mobile']").attr("selected","selected");
		}
	} );
	$('#howtocontact').bind("change",function(e){
		$("#applicationform").validate();
	} );
	$.validator.addMethod("phoneNumber", function(value, element) {
		l=0;
		for(j=0;j<value.length;j++) {
			if( /^\d$/i.test(value.charAt(j) )) {
				l++;
			}
		}
		if(l!=11) {
			return(this.optional(element)||false);
		}
		return this.optional(element) || /^0\d{2,4}[ -]{0,1}[\d]{3}[\d -]{1}[\d -]{1}[\d]{1,4}$/i.test(value);
	}, "Please check the format of your phone number.");  
	$.validator.addMethod("textName",function(value,element) {
		return this.optional(element) || /^[a-zA-Z]+[-\s{0,1}a-zA-Z+]*$/i.test(value);
	}, "Only letters, a space, or a hyphen can be entered.");
	$.validator.addMethod("postcode",function(value,element) {
		return this.optional(element) || /^[a-zA-Z]+[\d]+[a-zA-Z]*[\s]*[\d]*[a-zA-Z]+$/i.test(value);
	}, "Make sure you provide a valid postcode.");
	$.validator.addMethod("lessThan",function(value,element,params) {
		return this.optional(element) || (parseInt(value)<parseInt($("#"+params).val()));
	}, "Must be less than {0}.");

	var validator = $("#applicationform").validate({

		errorPlacement: function(error, element) {
			error.appendTo( $(element).next("label.error").next("span") );
			$(element).parents("div.question").addClass("bad");
			$(element).parents("div.question").removeClass("ok");
			//error.appendTo( element.next() );
//					error.appendTo( element.parent("p").next("label.error") );
		},
		errorElement: "p",
		success: function(label) {
			$(label).parents("div.question").addClass("ok");
			$(label).parents("div.question").removeClass("bad");
		},
		highlight: function(element, errorClass) {
			$(element).parents("div.question").addClass("bad");
			$(element).parents("div.question").removeClass("ok");
		},
		unhighlight: function(element, errorClass) {
			$(element).parents("div.question").addClass("ok");
			$(element).parents("div.question").removeClass("bad");
		},
		rules: {
			amountowed:{
				required:function(element){ return (isOnStage(1)); },
				minlength:3,
				maxlength:10,
				digits:true
			},
			creditorscount:{
				required:function(element){ return (isOnStage(1)) },
				digits:true
			},
			ccjhistory:{},
			ccjcount:{
				required:function(element){ 
					if(isOnStage(1)) {
						return $("#ccjhistory").attr("checked");
					}
					return false;
				}
			},
			homeowner:{},
			mortgagevalue:{
				required:function(element){ 
					if(isOnStage(2)==true) {
						return $("#homeowner").attr("checked");
					} else {
						return false;
					}
				},
				digits:true,
				minlength:3,
				maxlength:6
			},
			outstandingmortgage:{
				lessThan:"mortgagevalue",
				required:function(element){ 
					if(isOnStage(2)==true) {
						return $("#homeowner").attr("checked");
					} else {
						return false;
					}
				},
				digits:true,
				minlength:3,
				maxlength:7
			},
			securedloans:{},
			securedloanamount:{
				required:function(element){ 
					if(isOnStage(2)==true) {
						return (($("#securedloans").attr("checked"))&&($("#homeowner").attr("checked")));
					} else {
						return false;
					}
				},
				digits:true,
				minlength:3,
				maxlength:7
			},
			disposableincome:{
				required:function(element){return (isOnStage(2));}
			},
			nametitle:{
				required:function(element){return (isOnStage(3));}
			},
			forename:{
				required:function(element){return (isOnStage(3));},
				minlength:2,
				maxlength:50,
				textName:true
			},
			surname:{
				required:function(element){return (isOnStage(3));},
				minlength:2,
				maxlength:50,
				textName:true
			},
			homephone:{
				phoneNumber:true,
				required:function(element){
					if (!isOnStage(3)) {return(false);}
					return($('#howtocontact option:selected').val()=="phone");
				},
				minlength:11
			},
			mobilephone:{
				phoneNumber:true,
				required:function(element){
					if (!isOnStage(3)) {return(false);}
					return($('#howtocontact option:selected').val()=="mobile");
				},
				minlength:11
			},
			email:{
				required:function(element){return (isOnStage(3));},
				email:true,
				maxlength:150
			},
			housenumber: {
				required:function(element){return (isOnStage(3));},
				minlength:1,
				maxlength:30
			},
			postcode:{
				required:function(element){return (isOnStage(3));},
				maxlength:8,
				minlength:4,
				postcode:true
			},
			whentocontact:{
				required:function(element){return (isOnStage(3));}
			},
			howtocontact:{
				required: function(element) {return (isOnStage(3));}
			},
			contactok:{
				required:function(element){return (isOnStage(3));}
			},
			creditcheckok:{}
		},
		messages:{
			amountowed:{
				required:"Please enter how much you owe, in &pound; only.",
				minlength:"We cannot assist with this amount.",
				maxlength:"Please check the amount you entered.",
				digits:"Please enter a number (only the 0 to 9 characters)."
			},
			creditorscount:{
				required:"How many creditors (loans, credit card, utilities) you have.",
				digits:"How many creditors (loans, credit card, utilities) you have."
			},
			ccjhistory:{},
			ccjcount:{
				required:"Please specify how many CCJs you had in the past 3 years.",
				digits:"Please specify how many CCJs you had in the past 3 years."
			},
			homeowner:{},
			mortgagevalue:{
				required:"Please specify the total value of your mortgage, in &pound;.",
				digits:"Please enter a number (only the 0 to 9 characters).",
				minlength:"Your mortgage must be for an amount over &pound;1000",
				maxlength:"Please check the amount you entered."
			},
			outstandingmortgage:{
				required:"Please enter the amount left on your mortgage, to the nearest &pound;.",
				digits:"Please enter a number (only the 0 to 9 characters).",
				minlength:"The amount owed on your mortgage must be &pound;100 or greater.",
				maxlength:"Please check the amount you entered.",
				lessThan:"Your mortgage is for less than this amount."
			},
			securedloans:{},
			securedloanamount:{
				required:"Please enter the total value of loans secured on your home, in &pound;.",
				digits:"Please enter a number (only the 0 to 9 characters).",
				minlength:"Your outstanding secured loans must be &pound;100 or greater.",
				maxlength:"Please check the amount you entered."
			},
			disposableincome:{
				required:"We base your plan on your disposable income; please specify it.",
				notX:"Please select the most relevant range from the list."
			},
			nametitle:{
				required:"Please select a title from the list.",
				notX:"Please select a title from the list."
			},
			forename:{
				required:"We need to know your first name.",
				minlength:"Please provide your full forename, rather than an abbreviation."
			},
			surname:{
				required:"We need to know your surname.",
				minlength:"Please provide your full surname, rather than an abbreviation."
			},
			homephone:{
				phoneNumber:"Please check the format of your phone number.",
				minlength:"Check you provided an area code.",
				required:"You have asked that you contact us on this number."
			},
			mobilephone:{
				phoneNumber:"Please check the format of your mobile number.",
				minlength:"Phone numbers are usually 11 digits.",
				required:"You have asked that you contact us on this number."
			},
			email:{
				required:"We need to communicate via email; an address is necessary.",
				email:"Please check you entered your address correctly.",
				maxlength:"Please provide a shorter email address... sorry!"
			},
			housenumber: {
				required:"We need to know the or and flat number you live at.",
				minlength:"Specify <em>none</em> if you do not have a house number."
			},
			postcode:{
				required:"We need to know your postcode to process your application.",
				minlength:"Check your postcode is long enough.",
				maxlength:"Please check your postcode - it seems too long."
			},
			whentocontact:{
				required:"Please choose a time of day when it's best to contact you."
			},
			howtocontact:{
				required:"We need to know how to contact you - check your number too."
			},
			contactok:{
				required:"A tick acknowledges we can begin processing your application."
			}
		}		
	});
	
	$("#nextlink").click(function(){
		var valid=$("#applicationform").valid();
		if (valid==true) {
			feedbackStage(stage);
			stage++;
			if (stage<4) {
				goStage(stage);
				return;
			} else {
				$('#next').fadeOut(500);
//				alert("submit form!");
				
				var payload="";
				for (var i in hints) {
					if (payload.length>0) {
						payload=payload+"&";
					}
					if ($("#"+i).val()!="") {
						payload=payload+i+"="+escape($("#"+i).val()) ;
					} else {
						payload=payload+i+"="+( $("#"+i).attr('checked')?"yes":"" );
					}
				}
				payload=payload+"&rt="+rt.join(",");

				$("#stage2").slideUp();
				$.ajax({
					type:	"POST",
					url:	"collate.php",
					data:	payload,
					success:function(){
						completeSubmit();
					}
				});
				return;
			}
		} else {
			$("#feedback").html('<span style="weight:bold;color:red;">There are errors in the form</span> - please amend the highlighted areas and try again.');
		}
	});
	
	// set behaviours
	$("input#ccjhistory").click(function(){
		updateCcjPanel();
	})
	$("input#homeowner").click(function(){
		updateHomeownerPanel();
	})
	$("input#securedloans").click(function(){
		updateSecuredloansPanel();
	})

	// were we refered from another page? go directly to the form if so	
	if (document.referrer.indexOf('endthespend.com') != -1) { 
		startForm();
	} else {
		$('#stage1').flash(
	    { src: 		'static/intro.swf',
	    	width:	700,
	    	height:	345
	   	}, 
	    { version: '7.0' }
	);
	}
});

function isOnStage(testno) {
	return(testno==stage);
}

function updateCcjPanel() {
	if ($("input#ccjhistory").attr("checked")) {
		$("div#ccjhistorypanel").find("div.question").removeClass('ok');
		$("div#ccjhistorypanel").find("div.question").removeClass('bad');
		$("div#ccjhistorypanel").fadeIn(500);
	} else {
		$("div#ccjhistorypanel").fadeOut(500);
	}
};		
function updateHomeownerPanel() {
	if($("input#homeowner").attr("checked")) {
		$("div#mortgagevalue").find("div.question").removeClass('ok');
		$("div#mortgagevalue").find("div.question").removeClass('bad');
		$("div#outstandingmortgage").find("div.question").removeClass('ok');
		$("div#outstandingmortgage").find("div.question").removeClass('bad');
		$("div#homeownerpanel").fadeIn(500);
	} else {
		$("div#homeownerpanel").fadeOut(500);
	}
};

function updateSecuredloansPanel() {
	if($("input#securedloans").attr("checked")) {
		$("div#securedloanamount").find("div.question").removeClass('ok');
		$("div#securedloanamount").find("div.question").removeClass('bad');
		$("div#securedloanamountpanel").fadeIn(500);
	} else {
		$("div#securedloanamountpanel").fadeOut(500);
	}
};

function feedbackStage(stg) {
	var r=0;
	switch(stg) {
		case 1:
			if(Number($("#amountowed").val())>10000) {r++;}
			if(Number($("#creditorscount").val())>2) {r++;}
			if($("#ccjhistory").attr("checked")) {r++;}
			break;
		case 2:
			if($("#homeowner").attr("checked")) {
				if (Number($("#outstandingmortgage").val())>=
						(Number($("#outstandingmortgage").val()/2)) ) {
							r++; /* half mortgage left to pay */
				}
			}
			if(Number($("#disposableincome").val().split("-")[0])>=300) {
				r++; /* enough disposable income */
			}
			if($("#securedloans").attr("checked")) {
				if(Number($("#securedloansamount").val())>=5000) {
					r++; /* enough secured loans */
				}
			}
			break;
		case 3:
			r=1; 
			if($("#creditcheckok").attr("checked")) {r++;}
			if($("#howtocontact").val()=="phone") {r++;}
			break;
	}
	r=(r<1?1:r);
	// assign class based on r to stage stg
	$("div#feedback"+(stg)).addClass('feedbackresponse'+(r));
	rt[stg]=r;
//	alert("stage "+stg+", r="+(r));
}
		
function startForm() {
		// housekeeping
	updateHomeownerPanel();
	updateSecuredloansPanel();
	updateCcjPanel();

	$("#stage2").show();
	$("#stage1").slideUp();
	$("#next").fadeIn(500);
}

function completeSubmit() {
//	alert("submit completed!");
	$("#stage3").slideUp();
}

function updateStages(stg) {
	for(var i=1; i<4; i++) {
		if(i==stg) {
			$("#formblock"+String(i)).addClass('visibleStage');
			$("#formblock"+String(i)).removeClass('hiddenStage');
		} else {
			$("#formblock"+String(i)).addClass('hiddenStage');
			$("#formblock"+String(i)).removeClass('visibleStage');
		}
	}
}

function prepareStages(stg) {
	for(var i=1; i<4; i++) {
		if((i==stg)||(i==stg-1)) {
			$("#formblock"+String(i)).addClass('visibleStage');
			$("#formblock"+String(i)).removeClass('hiddenStage');
		} else {
			$("#formblock"+String(i)).addClass('hiddenStage');
			$("#formblock"+String(i)).removeClass('visibleStage');
		}
	}
}

function goStage(stg) {
	$("div.stagemiddle").animate({"scrollLeft":((stg-1)*690)},(500*stg),function(){
		updateStages(stg);
	});

	prepareStages(stg);
	$("div.question").removeClass("bad");
	$("div.question").removeClass("ok");	

	for (var i=1; i<4; i++) {
		var el="#p"+String(i);
		if(stg<i) { // done
			if (!ie6) {
				if ($(el).is('.current')) {
					$().removeClass('current');
				}
				if ($(el).is('.done')) {
					$(el).removeClass('done');
				}
				$(el).addClass('notdone');
			} else {
				$(el).after("<img id=\"p"+i+"\" src=\"static/"+i+"_notdone.png\" alt=\"Stage "+i+"\">").remove();
			}
		} else if(stg==i) { // current
			if(!ie6) {
				if ($(el).is('.done')) {
					$(el).removeClass('done');
				}
				if ($(el).is('.notdone')) {				
					$(el).removeClass('notdone');
				}
				$(el).addClass('current');
			} else {
				$(el).after("<img id=\"p"+i+"\" src=\"static/"+i+"_current.png\" alt=\"You are completing stage "+i+"\">").remove();
			}
		} else { // done
			if(!ie6) {
				if ($(el).is('.notdone')) {			
					$(el).removeClass('notdone');
				}
				if ($(el).is('.current')) {
					$(el).removeClass('current');
				}
				$(el).addClass('done');
			} else {
				$(el).after("<img id=\"p"+i+"\" src=\"static/"+i+"_done.png\" alt=\"You have completed stage "+i+"\">").remove();
			}
		}
	}
}

