$(document).ready(function(){
	var buttons = "<span class='addRemoveButtons'><a href='#' class='addButton'></a><a href='#' class='minusButton disabled'></a></span>";
	$('span.addRemove').parents('fieldset').append(buttons);
	$('span.addRemove').parents('li').remove();
	formEvents();
});

formEvents = function(){
	//Element focus
	$('.addButton').parent().parent().find('input, select, textarea, .ac_input').focus(function(){
		//Remove all selected elements and highlight current one
		$('.highlightMe').removeClass('highlightMe');
		$(this).parents('li').addClass('highlightMe');
		//find('.element:last')
		//Disable all minus buttons and enable current group, if more than 1
		$('.minusButton').addClass('disabled');
		if($(this).parents('ol').children('li').size() > 1){
			$(this).parents('fieldset').find('.minusButton').removeClass('disabled');
		}
		
		//Enable + button
		$(this).parents('fieldset').find('.addButton').addClass('disabled');
		if($(this).parents('ol').find("*[valid='invalid']").size() == 0){
			$(this).parents('fieldset').find('.addButton').removeClass('disabled');
		}
	});
	
	//+ Button
	$('.addButton').bind('click', function(event){
		if(!$(this).hasClass('disabled')){
			var fSet = $(this).parent().parent();
			$(fSet).find('ol li:first').clone().appendTo($(fSet).find('ol')).hide();
			$(fSet).find('ol li:last span.message').removeClass('valid');
			$(fSet).find('ol li:last').find(':input:not(:radio,:checkbox,:hidden)').val('');
			$(fSet).find('ol li:last').fadeOut().fadeIn();
			$(fSet).find('ol li:last').find(':checkbox').removeAttr('checked');
			$(fSet).find('ol li:last *[default_value]').each(function(){
				$(this).val($(this).attr('default_value'));
			});
			$(fSet).find('ol li:last :input:not(:radio,:checkbox,[default_value],:hidden)').val('').parents('li').find('input[valid]').attr('valid','invalid');
			$(this).addClass('disabled');
			handleNewElements(fSet);
			formEvents();
			$(fSet).find('ol li:last').fadeIn().find('input:first').focus();
			var myPos = $(fSet).find('ol li:last input:first').position();
			var myPos = myPos.top + $(fSet).find('ol').scrollTop();
			$(fSet).find('ol').scrollTop(myPos);
			if(typeof setDirty != "undefined"){
				setDirty(true);
			}
		}
		return false;
	});
	
	//- Button
	$('.minusButton').bind('click', function(event){
		if(!$(this).hasClass('disabled')){
			var fSet = $(this).parent().parent();
			var focusOn = $(fSet).find('.highlightMe').next().find('input:first');
			var focusOn = $(focusOn).size() > 0 ? focusOn : $(fSet).find('.highlightMe').prev().find('input:first');
			$(fSet).find('.highlightMe').remove();
			$(this).addClass('disabled');
			$(focusOn).focus();
			handleNewElements(fSet, focusOn);
			formEvents();
			if(typeof setDirty != "undefined"){
				setDirty(true);
			}
		}
		return false;
	});
}

//Pass the + button's fieldset here (fs)
handleNewElements = function(fs, focusedOn){
	
	//Unbind our button events to prevent looping of add/remove
	$('.addButton').unbind('click');
	$('.minusButton').unbind('click');
	
	//Remove any disabled attributes
	var focusedOn = focusedOn ? focusedOn : '';
	if(!focusedOn){
		$(fs).find('ol li:last *[disabled]').removeAttr('disabled');
	}
	
	if(!focusedOn){
		var randomKey =  '-' + Math.random(); //Negative random key
	
		//Generate a new key for our clone element
		$(fs).find('ol li:last *[name]').each(function(){
			var myName = $(this).attr('name').replace(/\[-?\d*\]/, '['+randomKey+']');
			$(this).attr('name', myName);
		});
		$(fs).find('ol li:last *[for]').removeAttr('for');
	}
	
	//Do we have a validation field?  Then get the group name to pass to mfValidate.
	if($(fs).find('ol li:last input[valid]').size() > 0){
		//Let's find our elements group name
		$(fs).find('ol li:last *[valid]').mfValidate();
	}
	
	//Do we have an autocomplete field in this row?  Then get the select options and pass to ac
	$(fs).find('ol li:last .ac_input').each(function(){
		var AutocompleteValues = new Array();
		$(this).next().next().find('option').each(function(){
			AutocompleteValues.push($(this).text());
		});
		$(this).autocompleteArray(AutocompleteValues, {autoFill:true,selectFirst:true});
	});
	
	//Do we have masked input fields
	$(fs).find('ol li input[mask]:not(:disabled)').each(function(){
		$(this).unmask();
		$(this).mask();
	});
	
	//Do we have a date field
	$(fs).find('ol li:last input[smartdate]').each(function(){
		$(this).smartdate();
	});
	
	//Let's prepare our people autosave ajax funk
	if(typeof jQuery().mfAjaxSave != "undefined"){
		$('form#person').mfAjaxSave();
	}
}
