// Generic character limit function for text fields
function limitChars(textid, limit, infodiv) {
    var text = jQuery(textid).val();
    var textlength = text.length;
    if(textlength > limit) {
		//jQuery(infodiv).html('You cannot write more then '+limit+' characters');
		jQuery(textid).val(text.substr(0,limit));
		return false;
    } else {
		jQuery(infodiv).html((limit - textlength) + ' '+ cam.resources.MAXIMUM_FIELD_LENGTH);
		return true;
    }
}

// Calling the generic character limit script for a text field. Add a class of 'character-limit' to any text element and it will use the maxlength property as the value for the limit.
function setTextfieldCharacterLimit() {
    jQuery('input.character-limit').each(function(index) {
		var character_limit = jQuery(this).attr('maxlength');
		jQuery(this).after('<span class="characters"></span>');
		limitChars(this, character_limit, jQuery(this).next('.characters'));
		jQuery(this).keyup(function(){
		    limitChars(this, character_limit, jQuery(this).next('.characters'));
		});
    });
}

// Calling the generic character limit script for a textarea Add a class of 'character-limit' to any textarea element and a class of 'characters-XXX' (where XXX is the limit) and it will split the class to get the value for the limit.
function setTextareaCharacterLimit() {
	jQuery('textarea.character-limit').each(function(index) {
		var character_classes = jQuery(this).attr('class').split(' ');
		var character_limit_class = character_classes[1];
		var character_limit_split = character_limit_class.split("characters-");
		var character_limit = character_limit_split[1];
		jQuery(this).after('<span class="characters"></span>');
		limitChars(this, character_limit, jQuery(this).next('.characters'));
		jQuery(this).keyup(function(){
			limitChars(this, character_limit, jQuery(this).next('.characters'));
		});
	});
}

// Generic function to handle minimum length message
function checkMinChars(textid, minlength, infodiv) {
    var text = jQuery(textid).val();
    var textlength = text.length;
    if(textlength >= minlength) {
        jQuery(infodiv).fadeOut('slow');
    }
    if(textlength < minlength && jQuery(infodiv).css('display') == 'none') {
        jQuery(infodiv).fadeIn('slow');
    }
}

// Generic minimum length function adds simple message underneath field. Set by using class min-characters, and min-characters-XXX (where XXX is minimum character length)
function setMinimumCharacterLength() {
    jQuery('.min-characters').each(function(index) {
        var min_character_length_split = jQuery(this).attr('class').split('min-characters-');
        var min_character_length = min_character_length_split[1];
        var min_character_msg = cam.resources.MINIMUM_FIELD_LENGTH.replace('[MIN_LENGTH]', min_character_length);
        jQuery(this).next('.characters').after('<p class="note min-characters">'+ min_character_msg + '</p>');
        checkMinChars(this, min_character_length, jQuery(this).nextAll('.min-characters'));
        jQuery(this).keyup(function(){
           checkMinChars(this, min_character_length, jQuery(this).nextAll('.min-characters')); 
        });
    });
};

// Update any radio-gallery fields, adding/removing selected classes and showing/hiding child elements
function updateRadioGallerySelection(field) {
    jQuery(field).closest('li').bind('click', function() {
		var fieldName = jQuery(field).attr('name');
		var fieldType = jQuery(field).get(0).tagName;

		// Reworked to fix IE child form field entry bug
		// Fix to prevent the hiding of all child fields everytime the label / li is clicked
		jQuery('[name="'+fieldName+'"]').each(function(index){
		    if(this!=field) jQuery(this).closest('li').removeClass('selected').find('div.child-fields').hide();
		});
        jQuery(this).addClass('selected');
        if(jQuery(this).find('div.child-fields').css('display') == 'none') {
            // Only fade in those that are hidden
            jQuery(this).find('div.child-fields').fadeIn().find('input').attr('disabled',false);
        }

		if (fieldType == "INPUT") {

		    // We must check the selected input? We can click either the LI OR Label. The LI won't check the input field (e.g. radio)
		    jQuery(this).children('input[type=radio]').attr('checked','checked');

			if(jQuery(this).hasClass('add-new')) {
				jQuery(this).closest('fieldset').next('.collect').slideDown('medium').addClass('open').find('.form-row').removeClass('disabled').find('input,select').attr('disabled',false);
				jQuery.scrollTo(jQuery(this),1000,{offset:-20})
			} else {
				jQuery(this).closest('fieldset').next('.collect').removeClass('open').find('.form-row').addClass('disabled').find('input,select').attr('disabled','disabled');
			};
			jQuery(this).siblings().find('div.child-fields input').attr('disabled','disabled').val('');
			jQuery(this).siblings('li.condensed').find('select').attr('disabled','disabled').fadeOut('medium', function() {
				jQuery(this).closest('label').find('span.field-value').show();
			});
		} else {
		    jQuery(this).siblings().find('div.child-fields input').attr('disabled','disabled').val('');
			jQuery('[name="'+fieldName+'"]').attr("checked", false);
			jQuery(this).find('span.field-value').hide();
			jQuery(this).find('[name="'+fieldName+'"]').attr('disabled',false).fadeIn();
			jQuery(this).find('span.field-value').text(jQuery(field).children('option:selected').text());
			jQuery(this).closest('fieldset').next('.collect').removeClass('open').find('.form-row').addClass('disabled').find('input,select').attr('disabled','disabled');
		};

		recalculateDeliveryModes();
    });
}

// Including any additional fields that are not directly part of the radio-gallery so that the behaviour is copied across to them
function selectRadioGalleryExtension(fieldID) {
    var fieldName = jQuery(fieldID).attr('name');
    jQuery('input[name="'+fieldName+'"]').parent().removeClass('selected');
    jQuery('select[name="'+fieldName+'"]').closest('li').removeClass('selected');
    jQuery('input[name="'+fieldName+'"]').siblings('div.child-fields').fadeOut();
    jQuery('select[name="'+fieldName+'"]').closest('li').find('div.child-fields').fadeOut();
    jQuery('input#'+fieldID).attr('checked','checked').parent('').addClass('selected');
    jQuery('input[name="'+fieldName+'"]:checked').siblings('div.child-fields').fadeIn();
}

function setupBooleanFields() {
	jQuery('.boolean-fields').each(function(index) {
		var primaryField = jQuery(this).find('.boolean-primary ul input');
		var primaryFieldName = jQuery(this).find('.boolean-primary ul input').attr('name');
		jQuery(primaryField).each(function(index) {
			if (jQuery(this).is(':checked')) {
				jQuery(this).closest('li').addClass('checked');
			};
		});

		if (jQuery('input[name="'+primaryFieldName+'"]').is(':checked:gt(0)')) {
			jQuery(primaryField).closest('.boolean-fields').addClass('active');
		} else {
			jQuery(this).find('.boolean').hide();
		};

		jQuery(this).find('.boolean-primary input').bind('click', function() {
			if (jQuery('input[name="'+primaryFieldName+'"]').is(':checked:gt(0)')) {
				jQuery(this).closest('.boolean-fields').addClass('active').find('.boolean').fadeIn();
			} else {
			    jQuery(this).closest('.boolean-fields').find('.boolean').fadeOut();
			    jQuery(this).closest('.boolean-fields').find('.boolean input[type="text"]').attr('value','');
				jQuery(this).closest('.boolean-fields').removeClass('active');
			}
		});	
	});
}


function setupDependentFields() {
	jQuery('.dependent-fields').each(function(index) {
		var primaryField = jQuery(this).find('.form-row.dependent-primary input');
    	    if (jQuery(primaryField).is(':checked')) {
    			jQuery(primaryField).closest('.dependent-fields').addClass('active');
    	    } else {
    			jQuery(this).find('.form-row.dependent').hide();
    	    };

		jQuery(this).find('.form-row.dependent-primary input').bind('click', function() {
			if (jQuery(this).attr('checked')) {
			    jQuery(this).closest('.dependent-fields').addClass('active').find('.form-row.dependent').slideDown('fast');
			} else {
			    jQuery(this).closest('.dependent-fields').find('.form-row.dependent').slideUp('fast');
			    jQuery(this).closest('.dependent-fields').find('.form-row.dependent input[type="text"]').attr('value','');
			    jQuery(this).closest('.dependent-fields').find('.form-row.dependent input[type="radio"],.form-row.dependent input[type="checkbox"]').attr('checked',false);
				jQuery(this).closest('.dependent-fields').removeClass('active');
			}
		});	
	});
}

function setupSiftableFields() {
	jQuery('.sift-field').each(function(index) {
		
		// On page load - get the value of the siftable element for and then show the relevant fields that match the class name
	    var siftableField = jQuery(this).find('select');
	    var siftableFieldValue = jQuery(this).find('select').val();
	    
	    jQuery(siftableField).parent().next('.siftable-fields').children('div').each(function(index) {
			if(jQuery(this).hasClass(siftableFieldValue)) {
			    jQuery(this).show();
			} else {
			    jQuery(this).hide();
			}
	    });
	
		// On change - get the value of the siftable element and then show the relevant fields that match the class name
	    jQuery(siftableField).bind('change', function() {
			var siftableFieldValue = jQuery(siftableField).val();
			jQuery(siftableField).parent().next('.siftable-fields').children('div').each(function(index) {
			    if(jQuery(this).hasClass(siftableFieldValue)) {
					jQuery(this).slideDown();
			    } else {
					jQuery(this).slideUp();
			    }
			});
	    });
	});
}


function formFieldFocus() {
	//Toggle a class on the parent of a form field when giving and removing focus on the field
	jQuery('form div input:text:not(.filter), form div input:password, form div textarea, form div select, form div input:file').each( function(intIndex){
	    jQuery(this).bind ('focus',function(){
		(jQuery(this).parent().addClass('focus'));
	    });
	    jQuery(this).bind ('blur',function(){
		(jQuery(this).parent().removeClass('focus'));
	    });
	});
	jQuery('form fieldset.checkbox-box li input').each( function(intIndex){
	    jQuery(this).bind ('click',function(){
		(jQuery(this).closest('li').toggleClass('checked'));
	    });
	});
}



function formValidate() {

	jQuery('.article .form-buttons').append('<div class="validation-message"><p><em>There are some problems with the information you have provided.</em><br>Please check the highlighted fields and submit the form again.</p></div>');

	jQuery('.article form').validate({
		errorContainer: 'div.form-buttons .validation-message',
		errorPlacement: function(error, element) {
			error.prependTo(element.parent());
		},
		errorElement: 'div',
		errorClass: 'errorfeedback',

		rules: {
			//firstname: 'required',
			//lastname: 'required',
			email_address: {
				required: true,
				email: true
			}//,
			//subject: 'required',
			//message: 'required',
			//telephone: 'required',
			//company_name: 'required',
			//company_postcode: 'required',
		},
				
		messages: {
			//firstname: '<em>Please enter your first name<\/em>',
			//lastname: '<em>Please enter your last name<\/em>',
			email_address: {
				required: '<em>Please enter an email address<\/em>',
				email: '<em>Please enter a valid email address<\/em>'
			}//,
			//subject: '<em>Please select a subject<\/em>',
			//message: '<em>Please enter a message<\/em>',
			//telephone: '<em>Please enter a telephone number<\/em>',
			//company_name: '<em>Please enter your company name<\/em>',
			//company_postcode: '<em>Please enter your company postcode<\/em>',
		},
		
		highlight: function(element, errorClass) {
			jQuery(element).addClass('error');
			jQuery(element).parent().addClass('error');
		},
		
		unhighlight: function(element, errorClass) {
			jQuery(element).removeClass('error');
			jQuery(element).parent().removeClass('error');				
		}

	});
}




jQuery(document).ready(function(){
	formFieldFocus();
	setupDependentFields();
	setupBooleanFields();
	setupSiftableFields();
	//setupFieldgroupCollapse();
	setTextfieldCharacterLimit();
	setTextareaCharacterLimit();
	setMinimumCharacterLength();
	formValidate();
});

			


