var myFormValidator = null;
var req = null;

window.addEvent('domready', function() {
	//We can use one Request object many times.
	req = new Request.HTML( { url:'/test/PPKpetinfo.php', 
		onSuccess: function(html) {
			//Inject the new DOM elements into the results fieldset.
			$('pet_forms').adopt(html);
			//increment the number of pets in the form
			var pet_count = parseInt($('pet_count').value);
			$('pet_count').value = ( isNaN(pet_count) ? 1 : pet_count ) + 1;
			var display_count = parseInt($('display_count').value);
			$('display_count').value = ( isNaN(display_count) ? 1 : display_count ) + 1;
			
			onUpdateSubForms();
		},
		//Our request will most likely succeed, but just in case, we'll add an
		//onFailure method which will let the user know what happened.
		onFailure: function() {
			alert("Oops there was an error, can't add pet right now");
		}
	} );

	//setup the form validation
	myFormValidator = new FormValidator($('PPKRegistration'), {
		onElementPass: onFieldPass,
		onElementFail: onFieldFail,
	    onFormValidate: onFormValidateComplete,
		stopOnFailure: true,
	    useTitles: true,
		evaluateOnSubmit: true,
		evaluateFieldsOnBlur: false,
		evaluateFieldsOnChange: false,
		serial: false
	});
	
	FormValidator.add('radioGroupRequired', {
		errorMsg : 'You must make a selection',
		test : function (element, props) {
			var result = false;

			var parent = element.getParent();
			if (parent != null) {
				//find all the radio buttons with in this "group"
				var inputs = parent.getElements('input[type=radio]');
				if (inputs != null) {
					//test each radio button
					inputs.each(function(el) {
						//check to see if at least one is checked
						result = result || el.checked;
					});
				}
			} else {
				//can't find a parent so we'll just validate this radio button for being checked
				result = field.checked;
			}
			
			return result;
		}
	});

	FormValidator.add('dateSelectorValid', {
		errorMsg : function (element, props) {
						return ( $pick(element.get('title'), 'Date') + ' is an invalid or incomplete.' );
					},
		test : function (element, props) {
			var result = false;

			if ($type(props.dateSelectorValid)) {
				var day = $(props.dateSelectorValid + '_day');
				var month = $(props.dateSelectorValid + '_month');
				var year = $(props.dateSelectorValid + '_year');

				var parts = ( (!FormValidator.getValidator('IsEmpty').test(day)) ? 1 : 0 ) +
							( (!FormValidator.getValidator('IsEmpty').test(month)) ? 1 : 0 ) +
							( (!FormValidator.getValidator('IsEmpty').test(year)) ? 1 : 0 );

				//better be 3 parts
				if (parts == 3) {
					//make sure the days are in range
					result = ( parseInt(day.get('value')) <= Date.daysInMonth(parseInt(month.get('value')) - 1, year.get('value')) );
				} else if (parts == 0) {
					//nothing selected, that's fine
					result = true;
				}
			}

			return result;
		}
	});

	FormValidator.add('dateSelectorRequired', {
		errorMsg : function (element, props) {
						return ( $pick(element.get('title'), 'Date') + ' is required.' );
					},
		test : function (element, props) {
			var result = false;

			if ($type(props.dateSelectorRequired)) {
				var day = $(props.dateSelectorRequired + '_day');
				var month = $(props.dateSelectorRequired + '_month');
				var year = $(props.dateSelectorRequired + '_year');
				
				var parts = (!FormValidator.getValidator('IsEmpty').test(day)) ? 1 : 0 +
							(!FormValidator.getValidator('IsEmpty').test(month)) ? 1 : 0 +
							(!FormValidator.getValidator('IsEmpty').test(year)) ? 1 : 0;

				//make sure at least 1 part is selected, after that its another validators issue to determine if the date is valid
				result = (parts > 0);
			}
			
			return result;
		}
	});
	
	onUpdateSubForms();
} );

function isDogRegistration(index) {
	var result = false;
	var element = $('type_' + index + '_dog');
	if ($type(element)) {
		result = element.checked;
	}
	return result;
}

function ToogleDogSection() {
	var pet_count = parseInt($('pet_count').value);
	var has_dog = false;
	
	for (var i=1; i<=pet_count; i++) {
		has_dog = has_dog || isDogRegistration(i);
	}

	var dog_section = $("dog_section");
	if (dog_section != null) {
		//if there is a dog, show the section
		if (has_dog) {
			dog_section.setStyle('display','block');
			dog_section.setStyle('visibility','visible');
		} else {
			dog_section.setStyle('display','none');
			dog_section.setStyle('visibility','hidden');
		}
	}
}

function onFieldPass(field) {
	displayValidationResult (field, null);
}

function onFieldFail(field, failures) {
	displayValidationResult (field, failures);
}

function onFormValidateComplete (valid, form, event) {
	if (!valid) {
		alert ('There are some errors with the form, please review the information you provided and make the necessary changes.')
	}
}

function displayValidationResult(field, failures) {
	var display_id = '';
	var display = null;
	var message = '';
	//is there a field
	if (field != null) {
		//assemble the message
		if (failures != null) {
			for (i=0; i< failures.length; i++) {
				var validator = myFormValidator.getValidator(failures[i]);
				message = message + (message.length > 0 ? ", " : "") + validator.getError(field);
			}
		}
		
		//first type to find the display wrapper
		display_id = field.get('id') + '_display';
		display = $(display_id);
		if (display == null) {
			//wrapper doesn't exist, add it
			display = new Element('span', { id: display_id, 'class' : 'validation_error' } )
			var parent = field.getParent();
			if (parent != null) {
				parent.adopt(display);
			}
		}
		//remove wappers child, the error display
		display.empty();
		//add the message
		if (failures != null) {
			display.appendText(message);
		}
	}
}

function onAddPet() {
	var pet_count = parseInt($('pet_count').value);
	pet_count = ( isNaN(pet_count) ? 1 : pet_count ) + 1;
	req.send('index=' + pet_count);	
}

function onRemovePet(index) {
	var display_count = parseInt($('display_count').value);

	//there always has to be one pet
	if (display_count > 1) {
		//delete the form
		$('pet_' + index).dispose();
		//track the removal
		$('display_count').value = ( isNaN(display_count) ? 1 : display_count ) - 1;
		//if this was the only dog registration the dog section might need to be removed
		ToogleDogSection();
		
		onUpdateSubForms();
	} else {
		alert ('At least one Pet is required');
	}
}

function onUpdateSubForms() {
	//get a list of the remove links
	var petforms = $('pet_forms');
	if (petforms != null) {
		var removelinks = petforms.getElements('span[class=remove_link]');
		if (removelinks != null) {
			removelinks.each(function(item, index) { ToogleRemoveLink(item); })
		}
	}
}

function ToogleRemoveLink(link) {
	var display_count = parseInt($('display_count').value);
	if (link != null) {
		if (display_count == 1) {			
			link.setStyle('display', 'none');
		} else {
			link.setStyle('display', 'inline');
		}
	}
}
