/// Sound in Theory Form Validator v0.5 ///


;(function($) {

	$.fn.sitVal = function(settings) {
		// defaults
		formParentID = $(this)[0].id;

		settings = $.extend({}, $.fn.sitVal.defaults, settings); // this means use defaults, but accept settings if they are passed in on the plugin call

		// Set the submit button id
		function getSubmit() {
			$('#' + formParentID + ' input').each(function() {
				if ($(this).attr('type') == 'image' || $(this).attr('type') == 'submit') { // if its a submit or an image
					if ($(this).attr('id') != 'undefined') {
						submitID = $(this).attr('id');
					}
				}
			});
			return submitID;
		}

		getSubmit();

		function errorBox(theFields) {
			theBox = '<div id="cError"><p>' + settings.introText + '</p><ul>' + theFields + '</ul></div>';
			return theBox;
		}

		// add star to required labels, make array of required labels
		reqLabels = new Array();
		function makeRequired() {
			$('#' + formParentID + ' label').each(function(i) {
				if ($(this).hasClass('required')) {
					$(this).html($(this).html() + '<span> *</span>');
					reqLabels.push($(this)); // adds to the end of the array
				}
			});
			// set style for asterix
			$('#' + formParentID + ' label span').css({ fontSize: '18px', color: 'red' });
		}
		makeRequired();



		// validate
		function validate() {
			try {
				$('#cError').remove();
				valid = true;
				theFields = "";
				$(reqLabels).each(function(i) {
					assocInput = $(this).attr('for');

					if ($('#' + assocInput).val() == "" || $('#' + assocInput).val() == settings.selectDefault) { // if the required field equals nothing or please select...
						theFields += '<li>' + reqLabels[i].html() + '</li>'; // add its name to the list
						valid = false;
					}
				});
				if (valid == false) {
					$('#' + formParentID).after(errorBox(theFields)); //insert error box after the form
					return false;
				} else {
					return true
				}

				//	alert(theFields);
				return false;
			} catch (err) {
				console.log(err);
			}

		}
		$('#' + submitID).click(function() {
			if (validate()) {
				return true;
			} else {
				return false;
			}


		});
	}

	$.fn.sitVal.defaults = {
		selectDefault: '-- Please Select --',
		introText: "Please complete the following fields above:"
	}


})(jQuery);
	





