/* ================================================================================================
// MODAL DEFAULTS: establish defaults for the modal
================================================================================================ */
	
	jQuery.modal.options = {
		width: 300,
		height: 300,
		backgroundImage: 'none'
	};
	
/* ================================================================================================
// MODALS: preparing the document for modal activity
================================================================================================ */

	jQuery.modal = function(options) {
		// watch for window resizing so we can recalculate the modal metrics
		jQuery(window).resize(function(){
			jQuery.modal.position();
		});
		
		// watch for window scrolling so we can reposition the modal
		jQuery(window).scroll(function(){
			jQuery.modal.position();
		});
	
		jQuery(document).ready(function(){
			// ...inject the modal box & overlay and hide them away for later use!
			jQuery('body').prepend('<div id="modalOverlay"><div id="modalBox"></div></div>');
		});
		
		// extend default options with instance options
		jQuery.modal.options = jQuery.extend(jQuery.modal.options, options);
	
		// register a live event to watch for any triggers (a.modal) to be clicked
		jQuery('a.modal').live('click', function(e) {
			e.preventDefault();
			
			// extract the ID of the event we need to request data for
			$id = jQuery(this).attr('href').replace('#', '');
			
			// ask the event-modal model to give us data!
			// we hand the data off to a function that will inject it into the DOM
			jQuery.get('_library/_ajax/eventModal.php', { id: $id }, function(data){
				jQuery.modal.loadModal(data);
			});
		});
		
		// register a live event to watch for any triggers (a.modal) to be clicked
		jQuery('a.theatre').live('click', function(e) {
			e.preventDefault();
			
			// extract the ID of the event we need to request data for
			$id = jQuery(this).attr('href').replace('#', '');
			
			// ask the event-modal model to give us data!
			// we hand the data off to a function that will inject it into the DOM
			jQuery.get('_library/_ajax/videoModal.php', { id: $id }, function(data){
				jQuery.modal.loadModal(data);
			});
		});
	};

/* ================================================================================================
// MODAL EVENTS: Modal window event handler for calendar
================================================================================================ */

	jQuery.modal.loadModal = function($contents) {
		
		// set up the modal's metrics
		jQuery.modal.position();
		
		jQuery('#modalOverlay').hide();
		
		jQuery('#modalBox').empty().prepend($contents);
		
		// fade in the modal!
		jQuery('#modalOverlay').fadeIn();
		
		// register live overlay-hiding event to capture any #closeme links in the AJAX'd content		
		jQuery('#modalBox #closeme').live('click', function(e){
			e.preventDefault();
			jQuery('#modalOverlay').fadeOut('slow', function(){
				jQuery('#modalBox').empty();
			});
		});
		
		jQuery('#email-event').hide();
		
		// register live event to show/hide the email form
		jQuery('#modalBox #emailme').toggle(function(e){
			e.preventDefault();
			jQuery('#email-event', '#modalBox').slideDown('fast');
			jQuery('#modalBox #messages').css({
				webkitBorderBottomRightRadius: 0,
				webkitBorderBottomLeftRadius: 0,
				borderBottom: 'none'
			});
		}, function(e){
			e.preventDefault();
			jQuery('#email-event', '#modalBox').slideUp('fast', function(){
				jQuery('#modalBox #messages').css({
					webkitBorderBottomRightRadius: 15,
					webkitBorderBottomLeftRadius: 15,
					borderBottom: '1px solid black'
				});
			});
		});
		
		// register live event to print it!!!
		jQuery('#modalBox #printme').live('click', function(e){
			e.preventDefault();
			frames['event-printer-copy'].focus();
			frames['event-printer-copy'].print();
		});
		
		jQuery('#email-event-go').live('click', function(e){
			e.preventDefault();
			$id = jQuery('#email-event #event input').val();
			$email = jQuery('#email-event #email input').val();
			jQuery.modal.registerNotification($id, $email);
		});
	};
	
/* ================================================================================================
// EVENT NOTIFICATIONS: fire an event to register a notification via AJAX
================================================================================================ */

	jQuery.modal.registerNotification = function($id, $email) {
		$fail = 0;
		jQuery.ajax({
			type: "POST",
			url: "_library/_ajax/eventModal.php?mode=email",
			data: "event="+$id+"&email="+$email,
			dataType: 'xml',
			success: function(msg){
				jQuery('message', msg).each(function(){
					if(jQuery(this).attr('tone') == 'fail' || jQuery(this).attr('tone') == 'epicfail') $fail++;
					jQuery('<div></div>').appendTo('#modalBox #messages').addClass(jQuery(this).attr('tone')).html(jQuery(this).text()).slideDown();
				});
				if($fail == 0) {
					jQuery('#modalBox #buttons input').attr('disabled', 'disabled');
					jQuery('#email-event', '#modalBox').slideUp('fast', function(){
						jQuery('#modalBox #messages').css({
							webkitBorderBottomRightRadius: 15,
							webkitBorderBottomLeftRadius: 15,
							borderBottom: '1px solid black'
						});
					});
				}
			},
			error: function($xhrObj, $status, $errorObj) {	
				jQuery('<div></div>').appendTo('#modalBox #messages').addClass('epic-fail').html($status).slideDown();
			}
		});
	}

/* ================================================================================================
// POSITION: position the modal & adjust the overlay's metrics
================================================================================================ */

	jQuery.modal.position = function() {
		jQuery('#modalOverlay').css({
			zIndex: 9998,
			top: jQuery(window).scrollTop(),
			left: jQuery(window).scrollLeft(),
			width: jQuery(window).width(),
			height: jQuery(window).height()
		});
		
		jQuery('#modalBox').css({
			zIndex: 9999,
			position: 'absolute',
			height: jQuery.modal.options.height,
			width: jQuery.modal.options.width,
			top: (jQuery('#modalOverlay').height() / 2) - (jQuery.modal.options.height / 2),
			left: (jQuery('#modalOverlay').width() / 2) - (jQuery.modal.options.width / 2)
		});
	};

/* ================================================================================================
// JUMPDATE: create dropdowns for selecting calendar dates
================================================================================================ */

	jQuery.jumpDate = function() {
		jQuery('#jump-date #jump-year').numericOptions({from:2009,to:2012});
		var letters = ['January','February','March','April','May','June','July','August','September','October','November','December'];	
		jQuery('#jump-date #jump-month').numericOptions({from:1,to:12,labels:letters});
		jQuery('#jump-date #jump-day').numericOptions().datePulldown({year:jQuery('#jump-year'),month:jQuery('#jump-month')});
		
		jQuery('#jump-year, #jump-month, #jump-day', '#jump-date').change(function(){
			jQuery('#jump-date-string').val(jQuery('#jump-date #jump-year').val()+"-"+jQuery('#jump-date #jump-month').val()+"-"+jQuery('#jump-date #jump-day').val());
		});
	};



function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

/* ================================================================================================
//
// 
// BEGIN PROCEDURALS
// 
//
================================================================================================ */


	// !Instantiate Modal handler
	// ----------------------------------------------------------------------
	// instantiate the Modal extension
	jQuery.modal({ width: 600, height: 400 });
	
	// !Event: Document Ready
	// ----------------------------------------------------------------------
	// define what to do after the document has completed loading
	jQuery(document).ready(function(){
	
		// Find links where the 'href' attribute does not contain the 
		// string returned by location.hostname (essentially, links that
		// point to pages not in this domain) and set their target to '_blank',
		// to get around the W3C validator kirking out on them:
		
/* 		jQuery("a:not(a[href*="+location.hostname+"])").attr('target', '_blank'); */
		jQuery("a[rel*='external']").attr('target', '_blank');
		
		// !Attach Text Sizing Behavior
		// ----------------------------------------------------------------------
		// setting up the text resizer
		
		jQuery('body').css('font-size', Get_Cookie('fairhaven'));
		
		jQuery('#toolbar li#small a').click(function(){
			jQuery('body').css('font-size', '62.5%');
			Set_Cookie('fairhaven', '62.5%');
			return false;
		});
		
		jQuery('#toolbar li#medium a').click(function(){
			jQuery('body').css('font-size', '70%');
			Set_Cookie('fairhaven', '70%');
			return false;
		});
		
		jQuery('#toolbar li#large a').click(function(){
			jQuery('body').css('font-size', '77.5%');
			Set_Cookie('fairhaven', '77.5%');
			return false;
		});
		
		// !Render JumpDate
		// ----------------------------------------------------------------------
		// render date-selection dropdowns for the calendar
		jQuery.jumpDate();

		// !FAQs & Hidden Blocks
		// ----------------------------------------------------------------------
		// set up drawers for the FAQs & hidden content blocks
		jQuery("#about.faq .contain, #employment.hrfaqs .contain, #lifestyle.attractions .contain, .currentnews .contain, #lifestyle.health .contain, #resident.pricing .contain,").each(function(){
			$this = jQuery(this);
			jQuery('.expand', this).hide();
			jQuery('.static', $this).css('cursor', 'pointer' ).addClass('open').toggle(function(){
				jQuery(this).next('.expand').slideDown();
				jQuery(this).parent('.contain').addClass('expanded');
				jQuery(this).removeClass('open');
				jQuery(this).addClass('close');
			}, function(){
				jQuery(this).next('.expand').slideUp();
				jQuery(this).parent('.contain').removeClass('expanded');
				jQuery(this).removeClass('close');
				jQuery(this).addClass('open');



			});
		});
		
		// !Campus Map
		// ----------------------------------------------------------------------
		jQuery('#lifestyle.campusmap #media').css('overflow', 'hidden');

/*	jQuery('#lifestyle.campusmap #media img').imagetool({
			viewportWidth: 800,
			viewportHeight: 255,
			topY: 100
		}); */
		
		// !Form Input Masking
		// ----------------------------------------------------------------------
		jQuery('form input.phone').mask("999-999-9999", { placeholder: "_" });
		jQuery('form input.date').mask("99/99/9999", { placeholder: "-" });
		jQuery('form input.ssn').mask("999-99-9999", { placeholder: "_" });
		
		// !Form Validation
		// ----------------------------------------------------------------------
		jQuery('#contact.moreinfo form').validate();
		jQuery('#employment.application form').validate();

		// !Conditional Form Questions
		// ----------------------------------------------------------------------
		
		// conditionals
		jQuery('.conditional-field .conditional-questions').hide();
		jQuery('.conditional-field input, .conditional-field select').click(function(){
			if(jQuery(this).hasClass('condition')) {
				$more = jQuery(this).siblings('.conditional-questions').eq(0);
				jQuery('input, textarea', $more).removeAttr('disabled');
				$more.fadeIn('fast');
				jQuery('input, textarea', $more).eq(0).focus();
			} else if(!jQuery(this).hasClass('condition') && jQuery(this).is(':checked')) {
				$more = jQuery(this).siblings('.conditional-questions').eq(0);
				jQuery('input, textarea', $more).attr('disabled', 'disabled');
				$more.fadeOut('fast');
			};
		});
		
		// anticonditionals
		jQuery('.anticonditional-field input, .anticonditional-field select').click(function(){
			if(jQuery(this).hasClass('condition')) {
				$more = jQuery(this).siblings('.conditional-questions').eq(0);
				jQuery('input, textarea', $more).removeAttr('disabled');
				$more.fadeOut('fast');
				jQuery('input, textarea', $more).eq(0).focus();
			} else if(!jQuery(this).hasClass('condition') && jQuery(this).is(':checked')) {
				$more = jQuery(this).siblings('.conditional-questions').eq(0);
				jQuery('input, textarea', $more).attr('disabled', 'disabled');
				$more.fadeIn('fast');
			};
		});
			
		// !Form Element Cloning
		// ----------------------------------------------------------------------
		$emp = jQuery('.previous-employer').eq(0);
		jQuery('.add-previous-employer').click(function(){
			$emp.clone().appendTo('#previous-employers-list');
		});
		
		$ref = jQuery('.professional-reference').eq(0);
		jQuery('.add-professional-reference').click(function(){
			$ref.clone().appendTo('#professional-references-list');
		});
	});
