var applicationForm = {
	formClass: '.application-form',
	togglerClass: '.buttons',
	currentForm: '',
	currentStep: '',
	init: function() {
		if($(this.formClass)) {
                        /* Hide the second form on the page and attach event handlers to buttons to switch forms */
			$(this.formClass).hide();
			$(this.togglerClass+' A').click(function (e){
				e.preventDefault();
				$(applicationForm.formClass).hide();
				applicationForm.currentForm = $(this).attr('href').replace('apply-now.jsp','')
				$(applicationForm.currentForm).show();
				$(applicationForm.currentForm).find('.step-switcher').unbind('click').bind('click', function(e) {
					e.preventDefault();
                                        if(applicationForm.validate(false)) {
                                            applicationForm.currentStep = $(this).attr('href').replace('apply-now.jsp#','');
                                            $(applicationForm.currentForm+' .steps').hide();
                                            $(applicationForm.currentForm+' .'+applicationForm.currentStep).show();
                                            $('html, body').animate({
                                                    scrollTop: $("."+applicationForm.currentStep).offset().top
                                            }, 0);
                                        }
				});
                                $(applicationForm.currentForm).find('.steps').hide();
                                $(applicationForm.currentForm).find('.step-1').show();
                                applicationForm.currentStep = "step-1";
			});
                        if(location.hash && location.hash != "") {
                            if($('.buttons A[href="apply-now.jsp'+location.hash+'"]')) {
                                $('.buttons A[href="apply-now.jsp'+location.hash+'"]').trigger('click');
                                location.hash = "";
                            }
                        }
                        $(this.formClass).submit(function() {
                            return applicationForm.validate(true);
                        });
                }
            
	},
	validate: function(submitting) {
                // Loop through each form <li> on the current step
		$(this.currentForm + ' .' + this.currentStep + ' LI').each(function(el, inc) {
                        // Textual rules
			$(this).find('INPUT:text, TEXTAREA').each(function() {
                            
                            // If not always required
                            if(!$(this).hasClass("optional")) {

                                // Check empties
				if($(this).val() == "") {
                                        $(this).parent().parent().addClass("hasError");
				}else{
					$(this).parent().parent().removeClass("hasError");
                                }
                            }
			});

                        // Check dropdowns
                        $(this).find('SELECT').each(function() {

                            // If not always required
                            if(!$(this).hasClass("optional")) {

                                // Check for nulls on integer-based dropdowns, otherwise check for null
                                if($(this).hasClass("int")) {
                                    if(parseInt($(this).find(":selected").val()) < 0) {
                                            $(this).parent().parent().addClass("hasError");
                                    }else{
                                            $(this).parent().parent().removeClass("hasError");
                                    }
                                } else {
                                    if($(this).find(":selected").val() == "") {
                                            $(this).parent().parent().addClass("hasError");
                                    }else{
                                            $(this).parent().parent().removeClass("hasError");
                                    }
                                }
                            }
			});
		});

                var errorMsg = "";

                // Specific validation

                // Private Form
                // Check previous address specified if resident at current address less than 3 years
                if(this.currentForm == "#private" && this.currentStep == "step-1") {
                    if(parseInt($('#currentTimeAtAddress  OPTION:selected').val()) < 3) {
                        if($('#previousAddress').val() == "" || $('#previousCountry').val() == "" || $('#previousPostCode').val() == "" || parseInt($('#previousTimeAtAddress OPTION:selected').val()) == -1) {
                            if($('#previousAddress').val() == "") { $('#previousAddress').parent().parent().addClass('hasError'); } else { $('#previousAddress').parent().parent().removeClass('hasError'); }
                            if($('#previousCountry').val() == "") { $('#previousCountry').parent().parent().addClass('hasError'); } else { $('#previousCountry').parent().parent().removeClass('hasError'); }
                            if($('#previousPostCode').val() == "") { $('#previousPostCode').parent().parent().addClass('hasError'); } else { $('#previousPostCode').parent().parent().removeClass('hasError'); }
                            if(parseInt($('#previousTimeAtAddress OPTION:selected').val()) == -1) { $('#previousTimeAtAddress').parent().parent().addClass('hasError'); } else { $('#previousTimeAtAddress').parent().parent().removeClass('hasError'); }
                            // $('#currentTimeAtAddress').parent().parent().addClass('hasError');
                            errorMsg += "&middot; Specified a previous address if at current address less than 3 years<br/>";
                        } else {
                            $('#previousAddress').parent().parent().removeClass('hasError');
                            $('#previousCountry').parent().parent().removeClass('hasError');
                            $('#previousPostCode').parent().parent().removeClass('hasError');
                            $('#previousTimeAtAddress').parent().parent().removeClass('hasError');
                            // $('#currentTimeAtAddress').parent().parent().removeClass('hasError');
                        }
                    } else {
                            $('#previousAddress').parent().parent().removeClass('hasError');
                            $('#previousCountry').parent().parent().removeClass('hasError');
                            $('#previousPostCode').parent().parent().removeClass('hasError');
                            $('#previousTimeAtAddress').parent().parent().removeClass('hasError');
                            // $('#currentTimeAtAddress').parent().parent().removeClass('hasError');
                    }
                }

                // Email validation
                if(this.currentForm == "#private" && this.currentStep == "step-1") {
                    if(!$('#email').val().match(/.+@.+\..+/i)) {
                        $('#email').parent().parent().addClass("hasError");
                         errorMsg += "&middot; Entered a valid email address<br/>";
                    } else {
                        $('#email').parent().parent().removeClass("hasError");
                    }
                }

                // Company Form
                // Email validation
                if(this.currentForm == "#company" && this.currentStep == "step-1") {
                    if(!$('#coEmail').val().match(/.+@.+\..+/i)) {
                        $('#coEmail').parent().parent().addClass("hasError");
                         errorMsg += "&middot; Entered a valid email address<br/>";
                    } else {
                        $('#coEmail').parent().parent().removeClass("hasError");
                    }
                }

                // All forms
                // Terms and conditions acceptance
                if(submitting) {
                    if($(this.currentForm+' .' + this.currentStep + ' LI.checkbox INPUT:not(:checked)').size() > 0) {
                        $(this.currentForm+' LI.checkbox').addClass("hasError");
                        errorMsg += "&middot; Accepted the terms and conditions and declaration<br/>";
                    }else{
                        $(this.currentForm+' LI.checkbox').removeClass("hasError");
                    }
                }

                if($(this.currentForm + ' .' + this.currentStep).find('LI').hasClass('hasError')) {
                    $('html, body').animate({
                        scrollTop: ($(applicationForm.currentForm + " ."+applicationForm.currentStep).offset().top - 80)
                    }, 0);
                    if(errorMsg != "") { errorMsg = "Please ensure all fields are populated, and that you have:<br/>"+errorMsg; }
                    else { errorMsg = "Please ensure all fields are populated, see below.<br/>"; }
                    $(this.currentForm+' .error').html(errorMsg);
                    return false;
                } else {
                    $(this.currentForm+' .error').html("");
                    return true;
                }
	}
};

$(document).ready(function() {
        /* Add behaviour to focus and blur of Request Callback form elements to hide/show when default/empty */
        if($('#callbackName').val() == "") { $('#callbackName').val("Your Name"); }
        if($('#callbackTelNo').val() == "") { $('#callbackTelNo').val("Telephone Number"); }
	$('#callbackName').focus(function() {
		if($(this).val() == "Your Name") {
			$(this).val("");
		}
	}).blur(function() {
		if($(this).val() == "") {
			$(this).val("Your Name");
		}	
	});
	
	$('#callbackTelNo').focus(function() {
		if($(this).val() == "Telephone Number") {
			$(this).val("");
		}
	}).blur(function() {
		if($(this).val() == "") {
			$(this).val("Telephone Number");
		}	
	});

        /* Validate Request Callback form */
        if($('#callbackForm')) {
            $('#callbackForm').submit(function() {
                if($('#callbackName').val() == "" || $('#callbackName').val() == "Your Name") {
                    $('.callbackError').text('Please enter your name');
                    return false;
                } else {
                    $('.callbackError').text('');
                }

                if($('#callbackTelNo').val() == "" || $('#callbackTelNo').val() == "Telephone Number") {
                    $('.callbackError').text('Please enter your telephone number');
                    return false;
                } else {
                    $('.callbackError').text('');
                }

                return true;
            });
        }
	
	applicationForm.init();
});