$(document).ready(function(){
    // FAQ submission form
    $('.force + .submit').hover(function(e){
        $(this).css('background', "transparent url('/resources/site_images/btn-reg-submit-on.png') no-repeat left top"); 
    }, function(e){
        $(this).css('background', "transparent url('/resources/site_images/btn-reg-submit-off.png') no-repeat left top");
    });
    
    if ($('form .social').length > 0) {
        force_ask_form.init();
    }

	// GAA Force registration form
	if ($('#force-reg-form').length > 0){
		force_registration.init();
	}
	
	// GAA Force FAQ list
	if ($('#faq-list').length > 0 || $('.force.social.faq').length > 0) {
	    force_faq_list.init();
	}
	
});


var force_ask_form =
{
    do_submit: true,
    
    init: function(){
        $('form#freeform').submit(force_ask_form.validate_form)
    },
    
    validate_form: function(e){
        force_ask_form.do_submit = true;
        $('form .error').removeClass('error');
        $('form#freeform .req').each(function(index, element){
            if (! ($(this).val().length > 0)) {
                force_ask_form.do_submit = false;
                $(this).parent().addClass('error');
            }
        });
        $('form#freeform .email').each(function(index, element){
            if (! $(this).val().match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
                force_ask_form.do_submit = false;
                $(this).parent().addClass('error');
            }
        });
        
        if (!force_ask_form.do_submit) {
            e.preventDefault();
            return false;
        }
    }
}


var force_faq_list =
{
    speed: 500,
    
    init: function() {
        var openers = $('.questions li .expand');
        openers.click(force_faq_list.toggle_answer);
        openers.prev().find('.answer').hide();
    },
    
    toggle_answer: function(e) {
        if ($(this).hasClass('open')) {
            $(this).prev().find('.answer').slideUp(force_faq_list.speed, function(){$(this).parent().next().removeClass('open');});
        }
        else {
            $(this).addClass('open');
            $(this).prev().find('.answer').slideDown(force_faq_list.speed);
        }
        
        e.preventDefault();
        return false;
    }
};


var force_registration = 
{
	form: {},
	
	init: function(){
		force_registration.form = $('#force-reg-form');
		force_registration.preload_buttons();
		force_registration.start_tabs();
		force_registration.other_init(force_registration.form.find('#force_title'), force_registration.form.find('#force_other_title').parent());
		force_registration.other_init(force_registration.form.find('#force_how_heard'), force_registration.form.find('#force_other_how_heard').parent());
		force_registration.same_address_init();
		force_registration.other_facility_init();
		force_registration.init_help_tips();
		force_registration.init_word_counts();
	},
	
	preload_buttons: function(){
		var cache = [];
		force_registration.form.find('img.rollover').each(function(){
			var img = $(this);
			var src = img.attr('src');
			var onSrc = src.replace('-off', '-on');
			
			var cache_image = document.createElement('img');
			cache_image.src = onSrc;
			cache.push(cache_image);
		});
	},
	
	start_tabs: function(){
		var tab_links = force_registration.form.find('.stages');
		tab_links.tabs(".form-sections > div", {
			onBeforeClick: force_registration.validate_tab,
			onClick: force_registration.update_tab_hash
		});
		
		var api = tab_links.data("tabs");
		force_registration.form.find('a.next').click(function(e){
			api.next();
			force_registration.set_hash_by_index(api.getIndex());
			e.preventDefault();
		});
		
		force_registration.form.submit(force_registration.validate_tab);
	},
	
	validate_tab: function(e, k){
		var currentIndex = force_registration.form.find('.stages a').index(force_registration.form.find('.stages a.current'));
		var result = true;
		var clickedElement = $(this);
		
		if (clickedElement.get(0).tagName == 'FORM'){
			validationErrors = force_registration.validate_all();
		} else if (currentIndex != -1){
			validationErrors = eval('force_registration.validate_'+currentIndex+'()');
		}
		
		if (typeof(validationErrors) !== 'undefined'){
			$('label, #club-areas .legend').removeClass('error-label');
			$('#map-opt-in .legend').removeClass('error-label');
			if (validationErrors.length > 0){
				for (i in validationErrors){
					if (validationErrors[i][0] == 'force_improve'){
						$('#club-areas .legend').addClass('error-label');
					} else if (validationErrors[i][0] == 'force_map_opt_in') {
						$('#map-opt-in .legend').addClass('error-label');
					} else {
						$('label[for="' + validationErrors[i][0] + '"]').addClass('error-label');
					}
				}
				result = false;
			} else {
				if (clickedElement.get(0).tagName == 'FORM'){
					force_registration.show_progress_message();
				}
				result = true;
			}
		}
		
		if (!result) {
			$('p.next-link span.error-label').remove();
		    $('p.next-link').prepend('<span class="error-label">Please fill in the required fields (highlighted in red) before progressing to the next step.</span>');
		} else {
			$('p.next-link span.error-label').remove();
		}
		
		return result;
	},
	
	show_progress_message: function(){		
		var submit_button = force_registration.form.find('.next-link input');
		
		submit_button.attr('disabled', true);
		
		off_src = submit_button.attr('src');
		on_src = off_src.replace('-off', '-on');
		submit_button.attr('src', on_src);
		submit_button.css('cursor', 'wait');
		
		force_registration.form.find('.next-link').prepend('<span class="progress-label">Please wait. Your entry is uploading.</span>');
	},
	
	validate_0: function(){
		var errors = [];
		
		if (!force_registration.required_field('force_title')) {errors.push(['force_title', 'Title is required']);}
		if (!force_registration.required_field('force_first_name')) {errors.push(['force_first_name', 'First name is required']);}
		if (!force_registration.required_field('force_surname')) {errors.push(['force_surname', 'Surname is required']);}
		
		var email = $('#force_email_address').attr('value');
		var confirm_email = $('#force_confirm_email_address').attr('value');
		if (email != '' && email != confirm_email){errors.push(['force_confirm_email_address', 'Your email entries do not match'])}
		if (!email.match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)){errors.push(['force_email_address', 'Email appears to be invalid'])}
		
		if (!force_registration.required_field('force_address_1')) {errors.push(['force_address_1', 'Address line 1 is required']);}
		if (!force_registration.required_field('force_town')) {errors.push(['force_town', 'Town is required']);}
		if (!force_registration.required_field('force_county')) {errors.push(['force_county', 'County is required']);}
		if (!force_registration.required_field('force_country')) {errors.push(['force_country', 'Country is required']);}
		
		if ($('#force_same_delivery_address_0').is(':checked')){
			if (!force_registration.required_field('force_delivery_address_1')) {errors.push(['force_delivery_address_1', 'Delivery address line 1 is required']);}
			if (!force_registration.required_field('force_delivery_town')) {errors.push(['force_delivery_town', 'Delivery town is required']);}
			if (!force_registration.required_field('force_delivery_county')) {errors.push(['force_delivery_county', 'Delivery county is required']);}
			if (!force_registration.required_field('force_delivery_country')) {errors.push(['force_delivery_country', 'Delivery country is required']);}
		}
		
		if (!force_registration.required_field('force_mobile')) {errors.push(['force_mobile', 'Mobile is required']);}
		if (!force_registration.check_phone_format('force_mobile')) {errors.push(['force_mobile'], 'Mobile number format is incorrect');}
		if (!force_registration.required_field('force_daytime_phone')) {errors.push(['force_daytime_phone', 'Daytime telephone is required']);}
		if (!force_registration.check_phone_format('force_daytime_phone')) {errors.push(['force_daytime_phone'], 'Daytime phone format is incorrect');}
		if (!force_registration.check_phone_format('force_evening_phone')) {errors.push(['force_evening_phone'], 'Evening phone format is incorrect');}
		if (!force_registration.required_field('force_how_heard')) {errors.push(['force_how_heard', 'Please tell us how you heard about GAA Force']);}
		
		var how_heard = force_registration.form.find('#force_how_heard').attr('value');
		if (how_heard == 'Other'){
			var how_heard_other = force_registration.form.find('#force_other_how_heard').attr('value');
			if (how_heard_other == ''){
				errors.push(['force_other_how_heard', 'Please tell us how you heard about GAA Force']);
			}
		}
		
		return errors;
	},
	
	validate_1: function(){
		var errors = [];
		
		if (!force_registration.required_field('force_club_name')) {errors.push(['force_club_name', 'Title is required']);}
		if (!force_registration.required_field('force_role_at_club')) {errors.push(['force_role_at_club', 'Tell us your role at the club']);}
		if (!force_registration.check_phone_format('force_contacts_phone')) {errors.push(['force_contacts_phone'], 'Contact phone format is incorrect');}
		if (!force_registration.required_field('force_club_address_1')) {errors.push(['force_club_address_1', 'Club address line 1 is required']);}
		if (!force_registration.required_field('force_club_town')) {errors.push(['force_club_town', 'Club town is required']);}
		if (!force_registration.required_field('force_club_county')) {errors.push(['force_club_county', 'Club county is required']);}
		if (!force_registration.required_field('force_club_country')) {errors.push(['force_club_country', 'Club country is required']);}
		
		return errors;
	},
	
	validate_2: function(){
		var errors = [];
		
		if (!force_registration.required_field('force_senior_members')) {errors.push(['force_senior_members', 'Number of senior members is required']);}
		if (!force_registration.required_field('force_junior_members')) {errors.push(['force_junior_members', 'Number of junior members is required']);}
		if (!force_registration.required_field('force_female_members')) {errors.push(['force_female_members', 'Number of female members is required']);}
		
		var facilities = 0;
		force_registration.form.find('#club-areas input[type="checkbox"]').each(function(){
			if ($(this).is(':checked')) {
				facilities = facilities + 1;
			}
		});
		if (facilities == 0){
			errors.push(['force_improve', 'Please choose areas needing improvement']);
		}
		
		var other_facilities = force_registration.form.find('#force_improve_other');
		var other_facilities_text = force_registration.form.find('#force_other_facilities').attr('value');
		if (other_facilities.is(':checked') && other_facilities_text == ''){
			errors.push(['force_other_facilities', 'Please enter text for other areas needing improvement']);
		}
		
		if (!force_registration.required_field('force_real_difference')) {errors.push(['force_real_difference', 'Tell us how Ulster Bank GAA Force would make a difference']);}
		if (!force_registration.required_field('force_how_will_benefit')) {errors.push(['force_how_will_benefit', 'Tell us how the makeover will benefit club members, the local community and surrounding areas']);}
		if (!force_registration.required_field('force_pivotal_role')) {errors.push(['force_pivotal_role', 'Tell us how the club plays a pivotal role in the community']);}
		
		var terms = force_registration.form.find('#force_terms');
		if (!terms.is(':checked')){
			errors.push(['force_terms', 'You must accept the terms and conditions']);
		}
		
		var map_opt_in = force_registration.form.find('input[name="force_map_opt_in"]:checked');
		if (map_opt_in.length == 0){
			errors.push(['force_map_opt_in', 'You must check the box to have your club promoted on the website map']);
		}
		
		return errors;
	},
	
	validate_all: function(){
		var validation_0 = force_registration.validate_0();
		var validation_1 = force_registration.validate_1();
		var validation_2 = force_registration.validate_2();
		
		var validation_all = validation_0.concat(validation_1, validation_2);
		
		if (validation_2.length == 0 && validation_all.length > 0){
			alert('There are problems with previous pages. Please go back and correct them before submitting the form.');
		}
		
		return validation_all;
		
	},
	
	required_field: function(css_id){
		var value = $('#'+css_id).attr('value');
		if (value == ''){
			return false;
		} else {
			return true;
		}
	},
	
	check_phone_format: function(css_id){
		var value = $('#'+css_id).attr('value');
		return (value.match(/^[\d\-\*\.x\+\(\)\s]*$/));
	},
	
	update_tab_hash: function(e, k){
		force_registration.set_hash_by_index(k);
		
		var stages = force_registration.form.find('.stages');
		var stageClass = k+1;
		stages.removeClass('stage-1').removeClass('stage-2').removeClass('stage-3');
		stages.addClass('stage-' + stageClass);
	},
	
	set_hash_by_index: function(k){
		document.location.hash = $(force_registration.form.find('.stages li a').get(k)).attr('href');
	},
	
	other_init: function(select_field, toggle_div){
		force_registration.toggle_other(select_field, toggle_div);
		select_field.change(function(){
			force_registration.toggle_other(select_field, toggle_div);
		});
	},
	
	toggle_other: function(select_field, toggle_div){
		if (select_field.attr('value') == 'Other'){
			toggle_div.show();
		} else {
			toggle_div.hide();
		}
	},
	
	same_address_init: function(){
		var radios = force_registration.form.find('input[name="force_same_delivery_address"]');
		force_registration.same_address_toggle();
		radios.change(force_registration.same_address_toggle);
	},
	
	same_address_toggle: function(){
		var radio = force_registration.form.find('#force_same_delivery_address_1');
		var fieldset = force_registration.form.find('#delivery_address');
		
		if (radio.is(':checked')){
			fieldset.hide();
		} else {
			fieldset.show();
		}
	},
	
	other_facility_init: function(){
		var checkbox = force_registration.form.find('#force_improve_other');
		force_registration.other_facility_toggle();
		checkbox.click(force_registration.other_facility_toggle);
	},
	
	other_facility_toggle: function(){
		var checkbox = force_registration.form.find('#force_improve_other');
		var other_div = force_registration.form.find('#force_other_facilities').parent();
		
		if (checkbox.is(':checked')){
			other_div.show();
		} else {
			other_div.hide();
		}
	},
	
	init_help_tips: function(){
		var icons = force_registration.form.find('.help-icon');
		icons.css('display', 'block');
		
		force_registration.form.find('.note').hide();
		
		icons.click(function(){
			var icon = $(this);
			var note = icon.parent().children('.note');
			
			note.slideToggle();
		});
	},
	
	init_word_counts: function(){
		$.each($('.word-count'), function(){
			var wc = $(this);
			var area = wc.parent().parent().find('textarea');
			
			force_registration.update_word_count(area);
			area.keyup(force_registration.update_word_count);
		});
	},
	
	update_word_count: function(e){
		if (e.currentTarget === undefined){
			var area = e;
		} else {
			var area = $(e.currentTarget);
		}
		
		var wc = area.parent().find('.word-count');
		var words = area.attr('value').match(/\S+/g);
		
		if (words == null || words.length == 0){
			wc.html('maximum 200 words');
		} else {
			wc.html(200 - words.length + ' words remaining');
		}
	}
	
}
