/**
 * Clears a text form element when it has the style 'clear-default'
 */
function clickClear() {
	if ($('input.clear-default').size() > 0) {
		$('input.clear-default').each(function(index) {
			this.defaultValue = $(this).val();
			$(this).click(function() {
				if ($(this).val() == this.defaultValue) {
					$(this).val('');
				};
			}).focus(function() {
				if ($(this).val() == this.defaultValue) {
					$(this).val('');
				};
			}).blur(function() {
				if ($(this).val() == "") {
					$(this).val(this.defaultValue);
				};
			});
		});
		
		// Clear out form defaults on submit
		$('form').submit(function(event) {
			$('input.clear-default').each(function(index) {	
				if ($(this).val() == this.defaultValue) {
					$(this).val('');
				};
			});
		});
	};
}


var internationalAddress = {
	$stateSelect: $(),
	
	/**
	 * Swaps between State to State/Province and Zip to Postal	
	 * @param {Object} fieldset jQuery object with the fieldset containing the Address to change
	 * @param {String} type "usa" or "international" If its USA say "usa", otherwise use "international"
	 */
	swapStatePostal: function (fieldset, type) {
		if (type == null) {
			type = "international";
		};

		var $state = $(fieldset).find('p.state');
		var $stateLabel = $state.find('label');
		var $zipCodeLabel = $(fieldset).find('p.zip label');
		
		var createStateInput = function() {
		var inputStateProvince = document.createElement('input');
		$(inputStateProvince).attr({
			type: 'text',
			id: internationalAddress.$stateSelect.attr('id'),
			name: internationalAddress.$stateSelect.attr('name')
		});
		return inputStateProvince;
		};

		if (type == "usa") {
			// Change Labels
			$stateLabel.text("State");
			$zipCodeLabel.text("Zip Code");
			
			// Make sure state is showing
			$('p.state', fieldset).show();
			
				// If the state text input is there we want to remove it
				if ($state.find('input').length > 0) {
					$stateInput = $state.find('input:first');
					$stateInput.remove();
				};
				// If there is no select we want to add it
				if ($state.find('select').length <= 0) {
					$state.append(internationalAddress.$stateSelect);
				};
				
				// Add validation on the zip code
				if ($('p.zip input', fieldset).hasClass('validateZip') == false) {
					$('p.zip input', fieldset).addClass('validateZip');
				};
				
					
				//make state a required field
				if( $('p.state select', fieldset).hasClass('requiredSelect') == false) {
					$('p.state select', fieldset).addClass('requiredSelect');
				};				
		} else if (type == "canada") {
			// Change Labels
			$stateLabel.text("State/Province");
			$zipCodeLabel.text("Postal Code");
			
			// Make sure state is showing
			$('p.state', fieldset).show();
			
			// If the select is visible, we want to put it into the local variable and remove it.
			if ($state.find('select').length > 0) {
				internationalAddress.$stateSelect = $state.find('select:first').clone();
				$state.find('select:first').remove();				
			};	
			// If there is no input we want to add it
			if ($state.find('input').length <= 0) {
				$state.append(createStateInput());
			};		
			
			// Remove validation on the postal code
			if ($('p.zip input', fieldset).hasClass('validateZip') == true) {
				$('p.zip input', fieldset).removeClass('validateZip');
			};
			

			if ($('p.zip input', fieldset).hasClass('requiredText') == false) {
				$('p.zip input', fieldset).addClass('requiredText');
			};			
			
			if( $('p.state input', fieldset).hasClass('requiredSelect') == true) {
				$('p.state input', fieldset).removeClass('requiredSelect');
			};
			
			if( $('p.state input', fieldset).hasClass('requiredText') == false) {
				$('p.state input', fieldset).addClass('requiredText');
			};
		} else if (type == "international") {
			// Change Labels
			$zipCodeLabel.text("Postal Code");
			
			// If its international we want to remove both the state select and the state input
			$state.hide();
			if ($state.find('select').length > 0) {
				internationalAddress.$stateSelect = $state.find('select:first').clone();
			};
			if ($state.find('input').length > 0) {
				$state.find('input:first').remove();
			};
			// Remove validation on the postal code
			if ($('p.zip input', fieldset).hasClass('validateZip') == true) {
				$('p.zip input', fieldset).removeClass('validateZip');
			};
			
		};	
	},
	
	init: function() {
	if ($('fieldset.school').size() <= 0) {
		$('fieldset:has(select[name*="country"])').each(function(index) {
			var $currentFieldset = $(this);
			$(this).find('select[name*="country"]').change(function() {
				if ($(this).attr('value') == 'CA') {
					internationalAddress.swapStatePostal($currentFieldset, 'canada');
				} else if ($(this).attr('value') != 'US') {
					internationalAddress.swapStatePostal($currentFieldset, 'international');
				} else {
					internationalAddress.swapStatePostal($currentFieldset, 'usa');
					};
				});
			});
		};
	}
};

/**
 * Sets up the handlers for the Mailing Address swap
 */
function mailingAddress () {	
	/**
	 * Toggles the visibility of the Mailing Address
	 * @param {Boolean} isOnLoad Set this to true if this is onLoad. If it is true, it skips animation.
	 */
	var toggleMailingAddress = function (isOnLoad) {
		isOnLoad = (isOnLoad == null) ? false : isOnLoad;

		if ($('#mailing_address_no:checked').val() == "no") {
			(isOnLoad) ? $('#mailing_address').show() : $("#mailing_address").slideDown('slow');
			
			//Validation
			$('#mailing_street_line1').addClass('requiredText');
			$('.from').addClass('requiredDate');
			$('.to').addClass('requiredDate');
			$('#mailing_city').addClass('requiredText');
			$('#mailing_zip').addClass('requiredText');
		
		} else {
			(isOnLoad) ? $('#mailing_address').hide() : $('#mailing_address').slideUp('slow');
			
			//Validation
			$('#mailing_street_line1').removeClass('requiredText');
			$('.from').removeClass('requiredDate');
			$('.to').removeClass('requiredDate');
			$('#mailing_city').removeClass('requiredText');
			$('#mailing_zip').removeClass('requiredText');
		};
	};
	
	
	toggleMailingAddress(true);
	
	$('#permanent_address input[name=mailing_address]').click(function() {
		toggleMailingAddress();
	});
}


/**
 * Sets up the handlers for the Residency Information
 */
function residency () {
	/**
	 * Toggles the visibility of the Residency Information
	 */
	var toggleResidency = function () {
		if ($('#resident_alien_yes:checked').val() == "yes") {
			$('.registration').show();
			$('.visa').hide();
			$('.registration #registration_number').addClass('requiredText');
			$('.visa #type_of_visa').removeClass('requiredText');
		} else if ($('#resident_alien_no:checked').val() == "no") {
			$('.registration').hide();
			$('.visa').show();
			$('.registration #registration_number').removeClass('requiredText');
			$('.visa #type_of_visa').addClass('requiredText');
		} else {
			$('.registration').hide();
			$('.visa').hide();
		}
	};
	
	if ($('#resident_alien_yes').length > 0) {
		toggleResidency();
		
		$('input[name=resident_alien]').click(function() {
			toggleResidency();
		});
	};
}


/**
 * Sets up the handlers for the Parent Additional Contact Info
 */
function parentContact () {
	/**
	 * Toggles the visibility of the Parent additional Contact Info
	 * @param {jQuery Object} $currentParent A jQuery object of the parent(object) Parent(Semantic name, also .parent)
	 * @param {Boolean} isOnLoad Set this to true if this is onLoad. If it is true, it skips animation.
	 */
	var toggleParentContact = function ($currentParent, isOnLoad) {
		var $currentParentContact = $currentParent.find('.contact');
		isOnLoad = (isOnLoad == null) ? false : isOnLoad;

		if ($currentParent.find('input[type="radio"]:checked').val() == "yes") {
			(isOnLoad) ? $currentParentContact.show() : $currentParentContact.fadeIn('slow');
		} else {
			(isOnLoad) ? $currentParentContact.hide() : $currentParentContact.fadeOut('slow');
		};
	};
	
	if ($('.parent').length > 0) {
		$('.parent').each(function(index) {
			var $currentParent = $(this);

			toggleParentContact($currentParent, true);

			$currentParent.find('input[type="radio"]').click(function() {
				toggleParentContact($currentParent);
			});
		});
	};
}	

var siblings = {
	$siblingClone: '',
	
	/**
	 * Toggles the visibility of the Mailing Address
	 * @param {Boolean} isOnLoad Set this to true if this is onLoad. If it is true, it skips animation.
	 */
	toggleSiblings: function (isOnLoad) {
		isOnLoad = (isOnLoad == null) ? false : isOnLoad;
		if ($('input[name=siblings]:checked').val() == "yes") {
			(isOnLoad == false) ? $('.sibling').slideDown('fast') : $('.sibling').show();
			$('p.add-more a').show();
			/*siblings.validate();*/
		} else {
			(isOnLoad == false) ? $('.sibling').slideUp('fast') : $('.sibling').hide();
			$('p.add-more a').hide();
			/*siblings.removeValidation();*/
		};
	},
	
	validate : function () {
		$('fieldset.sibling input').addClass('requiredText');
	},
	
	removeValidation : function () {
		$('fieldset.sibling input').removeClass('requiredText');
	},
	
	duplicateSibling: function() {
		var newSibling = $(siblings.sibling).clone();
		var items = $('fieldset.sibling').size();
	
		newSibling.html(newSibling.html().replace(RegExp('_[0-9]_', 'gi'), '_' + (items+1) + '_'));
		newSibling.html(newSibling.html().replace(/#[0-9]/, '#' + (items+1)));

		newSibling.hide();
		
		return newSibling;
	},
	
	listener: function() {
		$('p.add-more a').click(function(event) {
			event.preventDefault();
			$(this).parent().before(siblings.duplicateSibling()).prev().slideDown();
			
				$('fieldset.sibling:last input').val('');
			siblings.deleteListener();
			
			// Increase the hidden count
			$('input#sibling_count').val($('fieldset').size());
			/*siblings.validate();*/
		});
	},
	

	
	shiftSibling: function() {
		$('fieldset.sibling').each(function(index) {
			var fieldsetIndex = index;
			$('label', $(this)).each(function(index) {
				var currentLabel = $(this).attr('for');
				currentLabel  = currentLabel.replace(/_[0-9]{1,2}_/gi, '_'+(fieldsetIndex + 1)+'_');
				$(this).attr('for', currentLabel);
			});
			$('select, input', $(this)).each(function(index) {
				var currentName = $(this).attr('name');
				var currentId = $(this).attr('id');
				currentName = currentName.replace(/_[0-9]{1,2}_/gi, '_'+(fieldsetIndex + 1)+'_');
				currentId = currentId.replace(/_[0-9]{1,2}_/gi, '_'+(fieldsetIndex + 1)+'_');
				$(this).attr({'id': currentId, 'name': currentName});
			});
			$('legend', $(this)).text('Sibling #' + (fieldsetIndex + 1));
		});
		
	},
	
	deleteListener: function() {
		$('fieldset.sibling .delete a').click(function(event) {
				event.preventDefault();
				
				var fieldsetCount = $('fieldset.sibling').size();
				var fieldset = $(this).parent().parent();
				var index = $('fieldset.sibling').index(fieldset);
				var fieldsetsAfter = fieldsetCount - (index + 1);
				
			

				$(this).parent().parent().slideUp('fast', function() {
					$(this).remove();																   
					if (fieldsetsAfter > 0) {
						siblings.shiftSibling();
					};
					
					// Decrease the hidden count
					$('input#sibling_count').val($('fieldset').size());
					
						siblings.deleteListener();
				});
				
			
		});
	},
	
	/**
	 * Sets up the handlers for the Siblings
	 */
	init: function () {
		if ($('#siblings_yes').length > 0) {
			siblings.toggleSiblings(true);
			$('input[name="siblings"]').click(function() { siblings.toggleSiblings(); });
		};
		if ($('fieldset.sibling').size() > 0) {
			siblings.sibling = $('fieldset.sibling:first').clone();
			siblings.listener();
			siblings.deleteListener();
		};
	}
};

/**
 * Roanoke College Connections
 */
var connections = {
	$connectionEmployedClone: '',
	$connectionAttendClone: '',
	
	/**
	 * Toggles the visibility of the Mailing Address
	 * @param {String} type Either "employed" or "attend" depending upon which kind of Connection(Semantic) you are talking about 	  
	 * @param {Boolean} isOnLoad Set this to true if this is onLoad. If it is true, it skips animation.
	 */
	toggleConnections: function (isOnLoad) {
		isOnLoad = (isOnLoad == null) ? false : isOnLoad;
		if ($('input[name=relative_attend]:checked').val() == "yes") {
			(isOnLoad == false) ? $('.relative').slideDown('fast') : $('.relative').show();
			$('p.add-more a').show();
			connections.validate();
		} else {
			(isOnLoad == false) ? $('.relative').slideUp('fast') : $('.relative').hide();
			$('p.add-more a').hide();
			connections.removeValidation();
		};
	},
	
	
	validate : function () {
		$('fieldset.relative input').addClass('requiredText');
	},
	
	removeValidation : function () {
		$('fieldset.relative input').removeClass('requiredText');
	},
	
	duplicateConnection: function() {
		var newRelative = $(connections.relative).clone();
		var items = $('fieldset.relative').size();

		newRelative.html(newRelative.html().replace(RegExp('_[0-9]_', 'gi'), '_' + (items+1) + '_'));
		newRelative.html(newRelative.html().replace(/#[0-9]/, '#' + (items+1)));
		
		newRelative.hide();
		
		return newRelative;
	},
	
	listener: function() {
		$('p.add-more a').click(function(event) {
			event.preventDefault();
			$(this).parent().before(connections.duplicateConnection()).prev().slideDown();
		
					
				$('fieldset.relative:last input').val('');
					connections.deleteListener();
			// Increase the hidden count
			$('input#connection_count').val($('fieldset').size());
			connections.validate();
		});
	},
	


	shiftConnections: function() {
		$('fieldset.relative').each(function(index) {
			var fieldsetIndex = index;
			$('label', $(this)).each(function(index) {
				var currentLabel = $(this).attr('for');
				currentLabel  = currentLabel.replace(/_[0-9]{1,2}_/gi, '_'+(fieldsetIndex + 1)+'_');
				$(this).attr('for', currentLabel);
			});
			$('select, input', $(this)).each(function(index) {
				var currentName = $(this).attr('name');
				var currentId = $(this).attr('id');
				currentName = currentName.replace(/_[0-9]{1,2}_/gi, '_'+(fieldsetIndex + 1)+'_');
				currentId = currentId.replace(/_[0-9]{1,2}_/gi, '_'+(fieldsetIndex + 1)+'_');
				$(this).attr({'id': currentId, 'name': currentName});
			});
			$('legend', $(this)).text('Relative #' + (fieldsetIndex + 1));
		});
		
	},

		
	deleteListener: function() {
		$('fieldset.relative .delete a').click(function(event) {
				event.preventDefault();
				
				var fieldsetCount = $('fieldset.relative').size();
				var fieldset = $(this).parent().parent();
				var index=$('fieldset.relative').index(fieldset);
				var fieldsetsAfter = fieldsetCount - (index + 1);

				$(this).parent().parent().slideUp('fast', function() {
					$(this).remove();																   
					if (fieldsetsAfter > 0) {
						connections.shiftConnections();
					};
					
					// Decrease the hidden count
					$('input#connection_count').val($('fieldset').size());
					connections.deleteListener();
				});
				
				
			});
	},
	
	/**
	 * Sets up the handlers for the connections
	 */
	init: function () {
		if ($('#relative_attend_yes').length > 0) {
			connections.toggleConnections(true);
			$('input[name="relative_attend"]').click(function() { connections.toggleConnections(); });
		};
		if ($('fieldset.relative').size() > 0) {
			connections.relative = $('fieldset.relative:first').clone();
			connections.listener();
			connections.deleteListener();
		};
	}	
};

/**
 * Handles firing the fadeInBlock method for the optional page
 */
var optional = {
	/**
	 * Given a jQuery object, this will blink it yellow and fade it back to transparent
	 * @param {Object} block A jQuery object representing the object to 'blink'
	 */
	fadeInBlock: function (block) {
		$(block).animate({backgroundColor:"#FAF39E"}, 100, null, function() {
			$(block).animate({backgroundColor:"transparent"}, 800);
		});
	},
	
	fade: function() {
		var currentHash = document.location.hash;
		// On page load
		if (currentHash == "#photo" || currentHash == "#ethnicity" || currentHash == "#religion") {
			fadeInBlock(currentHash);
		}

		// On current page
		var $hashLinks = $('#nav-section li a:contains("Optional")').siblings('ul').find('li a');
		$hashLinks.click(function(event) {
			currentHash = "#" + $(this).attr('href').split("#")[1];
			fadeInBlock(currentHash);
		});
	},
	
	otherCollege: function() {
		$('#selecting .test input').keypress(function() {
			var isFull = true;
		
			$('#selecting .other-colleges input').each(function(index) {
				if ($.trim($(this).val()).length <= 0) {
					isFull = false;
				};
			});
		
			if (isFull) {
				var count = $('#selecting .other-colleges input').size();
				var $newCollege = $('#selecting .other-colleges input:last').clone();
				
				$newCollege.attr({'name': 'other_college_' + (count + 1), 'id': 'other_college_' + (count + 1), 'value': ''});
				$('#selecting .other-colleges input:last').after($newCollege);
				optional.otherCollege();
			};
		});
	},
	
	init: function() {
		optional.fade();
		optional.otherCollege();
	}
};

/**
 * Additional Info Page
 */
var additionalInfo = {
	
	deleteActivity: function(selector) {
			
	
	
		$('input[type="checkbox"]', selector).click(function(event) {
			event.preventDefault();
			if ($(this).not(':checked')) {
				var activity = ($(this).siblings('input[type*="text"]').val() != "") ? $(this).siblings('input[type*="text"]').val() : 'this activity';
				if (confirm("Are you sure you would like to remove "+activity+"?")) {
					$(this).parent().remove();
				};
			};
		});
	},

	/**
	 * Creates an additional activity input field
	 * @param {String} currentFieldset The string version of the fieldset's ID
	 * @param {Number} index The current number of extra activites within a fieldset
	 * @returns The newly created activity which is two inputs (checkbox and text) inside a paragraph.
	 * @type Object
	 */
	createActivity : function (currentFieldset, index) {
		var $activity = $('<li class="input-first-inline extra"><input type="checkbox" checked="yes" /></li>');
		var inputField = '<input type="text" name="' + currentFieldset + '_' + index + '" value="" id="' + currentFieldset + '_' + index + '" class="requiredText" />';
		$activity.append(inputField);

		additionalInfo.deleteActivity($activity);
		return $activity;
	},

	/**
	 * Handles the add more buttons on the activities and awards page
	 */
	handleAddMore : function () {
		$('form p.add-more a').click(function(event) {
			event.preventDefault();
			var currentFieldset = $(this).parents('fieldset').attr('id');
			var	extraCount = $('.extra', $(this).parents('fieldset')).size();
			$(this).parents().siblings('ul').append(additionalInfo.createActivity(currentFieldset, extraCount + 1));
		});
	},


	/**
	 * Handles additional info within a p or div
	 */
	handleAdditional : function () {
		/**
		 * If there is a checkbox within a container and it is checked this will add the class 'enabled' and show the div with the class .additional
		 * @param {Object} container A jQuery object representing the container holding the checkbox
		 * @param {Object} selector The selector to look for the checkbox with
		 */
		var toggleAdditional = function (container, selector) {
			if ($(selector, $(container)).is(':checked') && $(container).hasClass('extra') == false) {
				$(container).addClass('enabled');
				if ($(':has(".additional")', $(container))) $('.additional', $(container)).show();
				additionalInfo.validate(container);
			} else {
				$(container).removeClass('enabled');
				if ($(':has(".additional")', $(container))) $('.additional', $(container)).hide();
				additionalInfo.removeValidate(container);
			};
		};

		$('fieldset > ul > li').each(function(index) {		
			if ($(':has("div.additional")', this)) $('div.additional', this).hide();

			// var selector = ($(this)[0].nodeName == "P") ? '> input[type="checkbox"]' : '> p > input[type="checkbox"]';
			var selector = '> input[type=checkbox]';
			
			toggleAdditional(this, selector);

			var container = this;
			$(selector, this).click(function(event) {
				toggleAdditional(container, selector);
			});
		});
	},

	/**
	 * Handles collapsible fieldsets
	 */
	handleCollapsible : function () {
		$('form fieldset.collapsible legend').click(function(event) {
			event.preventDefault();
			if ($(this).parent().hasClass('collapsed')) {
				$(this).siblings().slideDown();
				$(this).parent().removeClass('collapsed');
			} else {
				$(this).siblings().slideUp();
				$(this).parent().addClass('collapsed');
			};
		});
	},
	
	validate : function (container) {
		$('.additional:has(p)', $(container)).addClass('requiredRadio');
		$('.additional dl .input-first-inline', $(container)).addClass('requiredRadio');
		$('.additional dl dd #key_club_additional', $(container)).addClass('requiredText');
	},
	
	removeValidate : function (container) {
		$('.additional:has(p)', $(container)).removeClass('requiredRadio');
		$('.additional dl .input-first-inline', $(container)).removeClass('requiredRadio');
		$('.additional dl dd #key_club_additional', $(container)).removeClass('requiredText');
	},
	
	init : function() {
		if ($('#activities-awards').size() > 0) {
			additionalInfo.handleAdditional();
			additionalInfo.handleAddMore();
			additionalInfo.handleCollapsible();
			additionalInfo.deleteActivity('li.extra');
			$('li.extra input[type=checkbox]').attr('checked','checked');
		};
	}
};

function references () {
	var toggleReferences = function (isOnLoad) {
		var isOnLoad = (isOnLoad) ? isOnLoad : false;
		if ($('#references input[type="radio"]:checked').size() <= 0) return;
		if ($('#references input[type="radio"]').index($('#references input[type="radio"]:checked')) == 0) {		
			(isOnLoad) ? $('#references div').hide() : $('#references div').slideUp('fast');
			
			//Remove validation
			$('#reference_1_name').removeClass('requiredText');
			$('#reference_1_position').removeClass('requiredText');
			$('#reference_1_home_phone').removeClass('requiredText');
			$('#reference_2_name').removeClass('requiredText');
			$('#reference_2_position').removeClass('requiredText');
			$('#reference_2_home_phone').removeClass('requiredText');
			
		} else {
			(isOnLoad) ? $('#references div').show() : $('#references div').slideDown('fast');
			
			//Validate
			$('#reference_1_name').addClass('requiredText');
			$('#reference_1_position').addClass('requiredText');
			$('#reference_1_home_phone').addClass('requiredText');
			$('#reference_2_name').addClass('requiredText');
			$('#reference_2_position').addClass('requiredText');
			$('#reference_2_home_phone').addClass('requiredText');
		};
	};
	
	if ($('fieldset#references').size() > 0) {
		$('#references div').hide();
		
		toggleReferences(true);
		
		$('#references input[type="radio"]').click(function(event) {
			toggleReferences();
		});
	};
}



function scholarsEssay () {
	var toggleScholarsEssay = function (isOnLoad) {
		var isOnLoad = (isOnLoad) ? isOnLoad : false;
		var $essay = $('.essay p:last');
		if ($('.essay input[type="radio"]').index($('.essay input[type="radio"]:checked')) == 1) {
			(isOnLoad) ? $essay.show() : $essay.slideDown('fast');
			$('.essay p #essay_file').addClass('requiredText');
		} else {
			(isOnLoad) ? $essay.hide() : $essay.slideUp('fast');
			$('.essay p #essay_file').removeClass('requiredText');
		};
	};
	
	if ($('.essay').length > 0 && $('h1').text() == "Essay") {
		$('.essay p:last').hide();
		toggleScholarsEssay(true);
		$('.essay input[type=radio]').click(function(event) {
			toggleScholarsEssay();
		});
	};
}

function gettingStarted () {
	var toggle = function(isOnLoad) {
		var isOnLoad = (isOnLoad) ? isOnLoad : false;
		var $when = $('span.applied-before-when');
		
		if ($('input[name=applied_before]').index($('input[name=applied_before]:checked')) == 0 ) {
			(isOnLoad) ? $when.show() : $when.fadeIn();
			
			//validate
			$('#applied_before_yes_when').addClass('requiredSelect');
		} else {
			(isOnLoad) ? $when.hide() : $when.fadeOut();
			
			///remove validation
			$('#applied_before_yes_when').removeClass('requiredSelect');
		};
	};
	
	if ($('input[name=applied_before]')) {
		toggle(true);
	
		$('input[name=applied_before]').click(function(event) {
			toggle();
		});
	};
}

String.prototype.toProperCase = function() {
	return this.toLowerCase().replace(/^(.)|\s(.)/g, function($1) { return $1.toUpperCase(); });
};

String.prototype.toValue = function() {
	return this.toLowerCase().replace(/(^\s*|\s*$)/g, '').replace(/\s/g, '_').replace(/[^A-Za-z_-]/g, '').replace(/[_]+/g, '_');
};

var schoolsAttended = {
	school: $(),
	 	
	/**
	 * Loads the JSON Data and appends it to the proper select box
	 * @param {jQuery Object} fieldset jQuery object of the current fieldset
	 * @param {String} section Name of section (state, city, country, school)
	 */
	selectLoader: function(fieldset, section) {
		var feed = '';
		var stateString = '';
		
		var country = $('p.country select', fieldset).val();
		var city = $('p.city select', fieldset).val();
		var state = $('p.state select', fieldset).val();
		
		schoolsAttended.clearSelect(fieldset, section);
		
		switch (section.toLowerCase()) {
			case 'country':
				feed = 'http://webapps.roanoke.edu/xmlfeeds/ceeb.cfc?method=GetEducationData&countrylist&callback=?';
				break;
			case 'city':
				feed = 'http://webapps.roanoke.edu/xmlfeeds/ceeb.cfc?method=GetEducationData&country=' + country;
				stateString = (state != "" && $('p.state:visible', fieldset).size() > 0) ? '&state=' + state : '';
				feed = feed + stateString + '&callback=?';
				break;
			case 'school':
				feed = 'http://webapps.roanoke.edu/xmlfeeds/ceeb.cfc?method=GetEducationData&country=' + country + '&city=' + city.toUpperCase();
				//console.log(state);	
				stateString = (state != "" && $('p.state:visible', fieldset).size() > 0) ? '&state=' + state : '';
				feed = feed + stateString + '&callback=?';
				break;
			default:
		}
				
		$.getJSON(feed,
		 	function (data) {
				//console.log(feed);
				if (section.toLowerCase() == 'school') {
					$.each(data.DATA, function(i, item) {
						if (item != null) {
							$('p.name select', fieldset).append('<option value="' + item[0] + '">' + item[1].toProperCase() + '</option>');
						};
					});
				} else { //if (section.toLowerCase() == 'country') 
					$.each(data.DATA, function(i, item) {
						if (item != null && item[0]) {
							$('p.' + section.toLowerCase() + ' select', fieldset).append('<option value="' + item[0].toProperCase() + '">' + item[0].toProperCase() + '</option>');
						};
					});
				};
			}
		);
	},
	
	/**
	 * Listens to the dropdown boxes changing. On change it fires the selectLoader function.
	 * @param {jQuery Object} fieldset (Optional) jQuery object of the current fieldset. If no parameter is passed the function goes over every fieldset
	 */
	selectListener: function(fieldset) {
		// If no fieldset is passed then do it to every fieldset
		if (fieldset == null) {
			$('fieldset').each(function(index) {
				schoolsAttended.selectListener($(this));
			});
			return;
		}
		
		$('p.state', fieldset).hide();
		
		schoolsAttended.selectLoader(fieldset, 'Country');
		
		// State isn't shown unless the item is US
		$('p.country select', fieldset).change(function() {
			if ($(this).val() == "usa") {
				$('p.state', fieldset).show();
				schoolsAttended.clearSelect(fieldset, 'State');
			} else {
				$('p.state', fieldset).hide();
				schoolsAttended.selectLoader(fieldset, 'City');
			};
		});
		
		// Show cities once location or state is selected
		$('p.state select', fieldset).change(function() {
			schoolsAttended.selectLoader(fieldset, 'City');
		});
		
		// Show Schools once city is selected
		$('p.city select', fieldset).change(function() {
			schoolsAttended.selectLoader(fieldset, 'School');
		});
 	},

	/**
	 * Clears out the old options in a dropdown box
	 * @param {jQuery Object} fieldset jQuery object of the current fieldset
	 * @param {String} section Name of the current section
	 */
	clearSelect: function(fieldset, section) {
		var innerSection = (section.toLowerCase() != "school") ? section.toLowerCase() : 'name';
		
		if (innerSection != 'state') {
			$('p.' + innerSection + ' select option', fieldset).each(function(index) {
				if ($(this).val() != '' && $(this).val() != 'usa' && $(this).val() != 'InternationalHS' && $(this).val() != 'HomeSchool' && $(this).val() != 'NoSchool') {
					$(this).remove();
				};
			});
		};
		
		//console.log(section);	
		if (innerSection == "country") {
			schoolsAttended.clearSelect(fieldset, 'state');
		} else if (innerSection == "state") {
			schoolsAttended.clearSelect(fieldset, 'city');
		} else if (innerSection == "city") {
			schoolsAttended.clearSelect(fieldset, 'school');
		};
	}, 
	
	/**
	 * Using the first school as a clone, it creats a new fieldset of a school with the correct numbers and input names
	 */
	duplicateSchool: function() {
		var newSchool = $(schoolsAttended.school).clone();
		var schools = $('fieldset.school').size();
		
		newSchool.html(newSchool.html().replace(RegExp('_[0-9]_', 'gi'), '_' + (schools + 1) + '_'));
		newSchool.attr('id', 'school_' + (schools + 1));
		newSchool.html(newSchool.html().replace(/#[0-9]/, '#' + (schools + 1)));
		
		$('p.name span', newSchool).remove();
		$('p.name select', newSchool).show();
		$('div.location', newSchool).show();
		
/*		$('p.input-first input[type=radio]', newSchool).attr('checked',false);*/
		
		// above command does not clear the radio buton for IE - remove the radio buttons and re-create in the clone fieldset
		// Added 2009-06 KJohnson
		$('p.input-first input[type=radio][value=yes]', newSchool).after('<input type="radio" value="yes" name="school_i_boarding_school" id="school_i_boarding_school_yes">').remove();
		$('p.input-first input[type=radio][value=no]', newSchool).after('<input type="radio" value="no" name="school_i_boarding_school" id="school_i_boarding_school_yes">').remove();
		newSchool.html(newSchool.html().replace(RegExp('_i_', 'gi'), '_' + (schools + 1) + '_'));
		
		$('.dates-attended select, .graduation-date select, .dates-attended input, .graduation-date input', newSchool).val('');		
		
		$('div.location .country select',newSchool).attr('class','requiredSelect')
		$('div.location .city select',newSchool).attr('class','requiredSelect')
		$('p.name select',newSchool).attr('class','requiredSelect')		

		

		newSchool.hide();
		
		return newSchool;
	},
	
	/**
	 * Add More link event listener
	 */
	listener: function() {
		$('p.add-more a').click(function(event) {
			event.preventDefault();
			$(this).parent().before(schoolsAttended.duplicateSchool()).prev().slideDown();

			schoolsAttended.deleteListener();
			
			schoolsAttended.selectListener($('fieldset:last'));
		
			// Increase the hidden count
			$('input#school_count').val($('fieldset').size());
		});
	},
	
	/**
	 * When schools are deleted the numbers need to be changed, this takes care of it
	 * @param {Integer} deletedIndex The position where the school was deleted
	 */

	shiftSchools: function() {
		$('fieldset.school').each(function(index) {
			var fieldsetIndex = index;
			$('label', $(this)).each(function(index) {
				var currentLabel = $(this).attr('for');
				currentLabel  = currentLabel.replace(/_[0-9]{1,2}_/gi, '_'+(fieldsetIndex + 1)+'_');
				$(this).attr('for', currentLabel);
			});
			$('select, input', $(this)).each(function(index) {
				var currentName = $(this).attr('name');
				var currentId = $(this).attr('id');
				currentName = currentName.replace(/_[0-9]{1,2}_/gi, '_'+(fieldsetIndex + 1)+'_');
				currentId = currentId.replace(/_[0-9]{1,2}_/gi, '_'+(fieldsetIndex + 1)+'_');
				$(this).attr({'id': currentId, 'name': currentName});
			});
			$('legend', $(this)).text('School #' + (fieldsetIndex + 1));
		});
		
		//schoolsAttended.selectListener();
	},
	
	/**
	 * School Delete Listener
	 */
	deleteListener: function() {
		$('fieldset.school .delete a').click(function(event) {
				event.preventDefault();
				
				var fieldsetCount = $('fieldset.school').size();
				var fieldset = $(this).parent().parent();
				var index = $('fieldset.school').index(fieldset);
				var fieldsetsAfter = fieldsetCount - (index + 1);

				$(this).parent().parent().slideUp('normal', function() {
					$(this).remove();																	 
					if (fieldsetsAfter > 0) {
						schoolsAttended.shiftSchools();
					};
		
					
					// Decrease the hidden count
					$('input#school_count').val($('fieldset').size());
					schoolsAttended.deleteListener();
			});
		});
	},
	
	init: function() {
		if ($('fieldset.school').size() > 0) {
			schoolsAttended.school = $('fieldset.school:first').clone();
			schoolsAttended.listener();
			schoolsAttended.deleteListener();
			schoolsAttended.selectListener();
		};
	}
};





var academicDismissal = {
	radioToggle: function(inputName, $target, isOnLoad) {
		var isOnLoad = (isOnLoad) ? isOnLoad : false;
		if ($('input[name=' + inputName + ']').index($('input[name=' + inputName + ']:checked')) == 0) {
			// First option — usually Yes
			(isOnLoad) ? $target.show() : $target.slideDown(500);
			academicDismissal.validate(inputName);
		} else {
			// Second option - usually No
			(isOnLoad) ? $target.hide() : $target.slideUp(500);
			academicDismissal.removeValidate(inputName);
		};
	},
	
	listener: function() {
		$('input[name=dismissed]').click(function() {
			academicDismissal.radioToggle('dismissed', $('#academic-dismissal'));
			academicDismissal.radioToggle('dismissed', $('#academic-dismissal-reapply'));
			academicDismissal.radioToggle('eligible_reapply', $('#academic-dismissal-reapply p.term'));					
			academicDismissal.radioToggle('dismissed', $('#academic-dismissal-reason'));			
		});
	},
	
	termListener: function() {
		$('input[name=eligible_reapply]').click(function() {
			academicDismissal.radioToggle('eligible_reapply', $('#academic-dismissal-reapply p.term'));
		});
	},
	
	validate: function(inputName) {
		if(inputName == 'dismissed') {
			$('#academic-dismissal .input-first').addClass('requiredRadio');
			$('#suspension_school_name').addClass('requiredText');
			$('#dismissal_reason').addClass('requiredText');
		} else if(inputName == 'eligible_reapply') {
			$('#eligible_reapply_term').addClass('requiredText');
		}
	},
	
	removeValidate: function(inputName) {
		if(inputName == 'dismissed') {
			$('#academic-dismissal .input-first').removeClass('requiredRadio');
			$('#suspension_school_name').removeClass('requiredText');
			$('#dismissal_reason').removeClass('requiredText');
		} else if(inputName == 'eligible_reapply') {
			$('#eligible_reapply_term').removeClass('requiredText');
		}
	},

	init: function() {
		if ($('#academic-dismissal').size() > 0) {
			academicDismissal.radioToggle('dismissed', $('#academic-dismissal'), true);
			academicDismissal.radioToggle('dismissed', $('#academic-dismissal-reapply'), true);			
			academicDismissal.radioToggle('eligible_reapply', $('#academic-dismissal-reapply p.term'), true);
			academicDismissal.radioToggle('dismissed', $('#academic-dismissal-reason'), true);
			academicDismissal.listener();
			academicDismissal.termListener();
		};
	}
};

var help = {	
	toggleHandler: function() {
		$('#help h4 a').click(function(event) {
			event.preventDefault();
			$('#help ul').slideToggle('normal', function() {
				resizeMain();
			});
		});
	},
	
	closeHandler: function() {
		$('#help ul li.close a').click(function(event) {
			event.preventDefault();
			$('#help ul').slideUp('normal', function() {
				resizeMain();
			});
		});
	},
	
	init: function() {
		if ($('#help').size() > 0) {
			$('#help ul').hide();
			help.toggleHandler();
			help.closeHandler();
		};
	}
};

/**
 * Resizes the content-main section to be at least as tall as the navigation
 */
function resizeMain () {
	var navSectionHeight = $('#nav-section').height() + 100;
	var contentMainHeight = $('#content-main').height();
	var contentInnerHeight = $('#content-inner').height();
	var helpHeight = $('#content-sub').height();
	var newHeight = '';
	var selector = '';
	
	if (contentMainHeight < navSectionHeight) {
		newHeight = navSectionHeight;
		selector = '#content-main';
	} else if (contentInnerHeight < $('#content-sub').height()) {
		newHeight = $('#content-sub').height();
		selector = '#content-inner';
	};
	
	$(selector).height(newHeight);
}

function printPage () {
	if ($('.print a').size() > 0) {
		$('.print a').click(function(event) {
			event.preventDefault();
			window.print();
		});
	};
}

$(document).ready(function() {	
	// Fire Objects
	academicDismissal.init();
	additionalInfo.init();
	connections.init();
	help.init();
	internationalAddress.init();
	optional.init();
	siblings.init();
	schoolsAttended.init();
	
	// Fire Functions
	clickClear();
	gettingStarted();
	mailingAddress();
	parentContact();
	references();
	residency();
	scholarsEssay();
	
	printPage();
	$('#wrapper').show();
	$('#wrapper-noscript').hide();
	
	// Resize Body Last
	// resizeMain();
	

});