// JQuery functions
// input text replacer
(function( $ ){
  $.fn.inputTextReplacer = function( options ) {
	  var settings = {
		      'label'    : 'Label',
		      'cssClass' : 'helpertext'
		    };
	  if (options) $.extend( settings, options);
    return this.addClass(settings['cssClass']).val(settings['label']).focus(function(){
	  		if ($(this).val() == settings['label']) $(this).removeClass(settings['cssClass']).val('');
	  	}).blur(function(){
	  		if ($(this).val() == '') $(this).addClass(settings['cssClass']).val(settings['label']);
	  	});
  };
})( jQuery );

$(document).ready(function(){
	
	// Dropdowns
	var menuSlideSpeed = 150;
	$('#nav ul.main a').click(function(event){
		event.preventDefault();
		var submenu = $('div#nav div#' + $(this).attr('id') + '_sub');
		var navLi = $(this).parent();
		//If the submenu is hidden then show it
		if (submenu.is(":hidden"))
		{
			//If another submenu is showing then hide that first
			if ($('div#nav div.drop').is(":visible"))
			{
				$('div#nav div.drop:visible').slideUp(menuSlideSpeed);
				$("div#nav ul.main li").removeClass('open');
				
				setTimeout(function(){submenu.slideDown(menuSlideSpeed);}, menuSlideSpeed);
				navLi.addClass('open');
			}
			else
			{
				// show the submenu
				navLi.addClass('open');
				submenu.slideDown(menuSlideSpeed);
			}
		}
		else
		{
			//Hide the submenu when clicked a second time
			submenu.slideUp(menuSlideSpeed);
			navLi.removeClass('open');
		}
	});
	$('a.encloser').click(function(event){
		event.preventDefault();
		$('#nav li.open').removeClass('open');
		$(this).parent().slideUp(menuSlideSpeed);
	});
	//Set it up so that clicking on anything except the links/submenu will close the submenu
	var mouseInNav = false;
	$(document.body).click(function(){
			if (!mouseInNav) {
				// if mouse is outside nav div, slide up the submenu 
				$('div#nav div.drop:visible').slideUp(menuSlideSpeed);
				$("div#nav ul.main li.open").removeClass('open');
			}
		});
	// mouse in nav check
	$("div#nav").hover(function(){mouseInNav=true;},function(){mouseInNav=false;});
	
	//Make all external links open in a new window, via: Karl Swedberg @ (learningjquery.com)
	//$('a:not([name])').filter(function() {
	//		return this.hostname && this.hostname !== location.hostname;
	//	}).attr('target', '_blank');
  

 	// Search field replace
 	var goLabel = 'Search';
 	$('form#search input.searchfield').inputTextReplacer({'label':goLabel});
	$('form#search').submit(function(){
		if ($('form#search input.searchfield').val() == goLabel) {
			$('form#search input.searchfield').val('');
		}			
	});

	// Accordions
	$('div.ecAccordion').accordion({ 
			collapsible : true,
			active : false,
			autoHeight : false,
			navigation : true
		});
	$('div.ecAccordion h3 > a').click(function(){
			var ecAParent = $(this).parentsUntil('#tabby').last();
			if ( ecAParent.is('html') )
			{
				location.hash = $(this).attr('href');
			}
			else
			{
				location.hash = '#tablink.'+ecAParent.attr('id')+'.'+$(this).attr('href').substr(1);
			}
		});
	$('.lefty #portals').accordion({ 
			collapsible : true,
			active : false,
			autoHeight : false,
			header: '> div > h3'
		});
	//Disappearing links accordion fix
 	if ($.browser.msie) { 
 		$('div.ecAccordion div, #portals div').css('zoom', '1'); 
    } 
 	
	// Tabs
	$('#tabby').tabs();
	
	// Contact Us Dialog 
	if ($('a.openContactUsDialog').length)
	{
		$('div#content').append('<div id="contactUsDialog"></div>');
		// contact dialog div var
		var contactUsDialog = $("div#contactUsDialog"),
			cu_sendToHolder,
			cu_ajaxUrl = '/inc/ajax/contactUs.php';
		// loading ajax text with image
		// set dialog buttons
		function cu_setContactButtons(withSend) {
			if (withSend)	contactUsDialog.dialog('option','buttons',{'Send Message': function() { $('form#ContactUs', this).submit(); }, Close: function() { $(this).dialog('close'); }});
			else   contactUsDialog.dialog('option','buttons',{Close: function() { $(this).dialog('close'); } });
		}
		// dialog setup
		contactUsDialog.dialog({
				autoOpen: false,
				width: 515,
				height: 640,
				modal: true,
				title: 'Contact Us',
				close: function() {
					$(this).empty();
				}
			});
		// init dialog buttons
		cu_setContactButtons(false);
		// open the dialog on link click
		$('a.openContactUsDialog').live('click',function(e){
				e.preventDefault();
				// set sendTo
				cu_sendToHolder = $(this).attr('href').substr(1);
				// title for dialog
				var title = $(this).attr('title');
				if (!title)
					title = $(this).text();
				// showPhone
				var height = 640;
				var phone = 'no';
				if ($(this).attr('phone') == 'yes')
				{
					phone = 'yes';
					height = 660;
				}
				// loadUrl
				var loadUrl = cu_ajaxUrl + '?showPhone=' + phone;
				// open dialog with loading text
				contactUsDialog.html(ajaxLoaderDiv('Loading... Please Wait.'))
					.dialog('option','height',height)
					.dialog('option','title',title)
					.dialog('open')			
					.load(loadUrl, function(){cu_setContactButtons(true);});
			});
		// submit function for contact us form
		$('form#ContactUs').live('submit',function(){
				// show phone
				var phone = 'no';
				if ($('input#cudPhone', this).length)
					phone = 'yes';
				// gather the form data
				var data = {
					cudName : $('input#cudName', this).val(),
					cudEmail : $('input#cudEmail', this).val(),
					cudPhone : $('input#cudPhone', this).val(),
					cudSubject : $('input#cudSubject', this).val(),
					cudMessage : $('textarea#cudMessage', this).val(),
					cudProtector : $('#cudProtector', this).val(),
					cudTweety : $('input#cudTweety', this).val(),
					showPhone : phone,
					sendTo : cu_sendToHolder,
					location : window.location.toString()
				};
				// empty the div and show a submitting msg
				contactUsDialog.html(ajaxLoaderDiv('Submitting... Please Wait.'));
				cu_setContactButtons(false);
				// submit the data through ajax
				contactUsDialog.load(cu_ajaxUrl,data, function(response, status, xhr){
						if ($('a.closeContactUs',response).length) {
							$(this).dialog('option','height',200);
							cu_setContactButtons(false);
						} else {
							cu_setContactButtons(true);
						}
					});
				// stop the contact form from submitting (gets submitted through ajax)
				return false;
			});
		// close the dialog link
		$('a.closeContactUs').live('click',function(e){
				e.preventDefault();
				contactUsDialog.dialog('close');
			});
	}
	
	// lightbox
	$('div.lightbox').each(function(){
		$(this).find('a[rel^=lightbox]').lightBox();
		
	});
	
	// zebra striping tables
	$('table.alternatingHighlights tr:nth-child(odd)').addClass('rowHighlight');
	
	// IE6 sniffer
	if ($.browser.msie && parseInt($.browser.version) < 7 && !window.XMLHttpRequest)
	{
		$('#content').prepend('<div class="notice">You are using an older browser, which may impair some of this site\'s features. Please upgrade your browser or might we suggest <a href="http://www.google.com/chrome" target="_blank">Google Chrome</a> or <a href="http://www.mozilla.com/firefox" target="_blank">Mozilla Firefox</a>.</div>');
	}
	
	// hash checker
	var thisHash = location.hash.split(".");
	if ( thisHash[0] == '#tablink' )
	{
		if ( $('#'+thisHash[1]).is(':hidden') )
		{
			$('a[href="#'+thisHash[1]+'"]').click();
		}
		$('a[href="#'+thisHash[2]+'"]').click();
	}
	
	// auto form filler for custom users
	$('a.customUserAutoFormFiller').click(function(e){
		e.preventDefault();
		// show a loading image
		var parentBox = $(this).parent(),
			saveHtml = parentBox.html();
		parentBox.html(ajaxLoaderImage('notice')+' Loading...');
		$.ajax({
			type: "POST",
			url: "/inc/admissions/custom/ajax/getAutoFillDetails.php",
			cache: false,
			data: 'ajax=yes',
			dataType: "json",
			success: function(json) {
				if (json.status == 1) {
					for (var key in json)
					{
						switch (key)
						{
							case 'sex':
								if (json[key] == 'M') {
									$('[id$="sex-Male"]').attr('checked','checked');
								} else {
									$('[id$="sex-Female"]').attr('checked','checked');
								}
								break;
							case 'status':
								break;
							default:
								$('[id$="'+key+'"]').val(json[key]);
								break;
						}
					}
					parentBox.html('There you go! Now just a little left...');
				} else {
					alert('Ooops! There seems to be a problem with our form helper. Sorry!');
				}
			}
		});
	});
	
	// profile tooltip
	$("div.profile2pic a").tooltip({ 
	    bodyHandler: function() { 
	       return $(this).find('img').attr('alt').replace(/---/g,'<br />'); 
	    },
	    showURL: false
	});
	
	//Progressive enhacement - inject the controls
	$('<div class="leftArrow"></div>').appendTo('div#showcaseWrap').html('<a href="#">Previous</a>');
	$('<div class="rightArrow"></div>').appendTo('div#showcaseWrap').html('<a href="#">Next</a>');
	// showcase cycler
	$('div#showcase').cycle({ 
	    fx: 'fade',
		prev: '.leftArrow', 
	    next: '.rightArrow',
		//speed: 700,
		timeout: 7000,
		height: '300px',
		startingSlide: Math.floor( ($.makeArray($('#showcase div.slide')).length - 1) * Math.random())
	});
	// feature box cycler
	$('<ul></ul>').appendTo('div.controls');
	$('div#featureBox').cycle({ 
	    fx: 'scrollHorz',
		cleartypeNoBg: true,
		pager: 'div.controls ul',
		//speed: 400,
		timeout: 4000,
		height: '216px',
		pagerAnchorBuilder: function(idx, slide) {
	      return '<li><a href="#">' + (idx + 1) + '</a></li>'; 
	    } 
	});
	// load events@eckerd feed
	$('#eventsContent').load('/inc/events.php');
	// load events@eckerd feed on news' widget
	$('#newsEventsWidget').load('/inc/events.php?widget=1');
	
	// buttons
	$('.ecButton').button();
	
});

function ajaxLoaderDiv(text) {
	return '<div class="centerText"><p><br /><br /><br /><img src="/img/ajax-loader.gif" alt="loading..." /> ' + text + '</p></div>';
}
function ajaxLoaderImage(type) {
	var typer = '';
	if (type != '') typer = '-'+type;
	return '<img src="/img/ajax-loader'+typer+'.gif" alt="loading..." />';
}
