
$(document).ready(function(){

	
	// homepage slideshow
	if($('#slideshow_holder').length){

				// Initially set opacity on thumbs and add
				// additional styling for hover effect on thumbs
				var onMouseOutOpacity = 0.67;
				$('#thumbs ul.thumbs li, div.navigation a.pageLink').opacityrollover({
					mouseOutOpacity:   onMouseOutOpacity,
					mouseOverOpacity:  1.0,
					fadeSpeed:         'fast',
					exemptionSelector: '.selected'
				});
				
				// Initialize Advanced Galleriffic Gallery
				var gallery = $('#thumbs').galleriffic({
					delay:                     2500,
					numThumbs:                 6, // number of thumbs to show per page
					preloadAhead:              10,
					enableTopPager:            false,
					enableBottomPager:         false,
					imageContainerSel:         '#slideshow',
					controlsContainerSel:      '#controls',
					captionContainerSel:       '#caption',
					loadingContainerSel:       '#loading',
					renderSSControls:          true,
					renderNavControls:         true,
					playLinkText:              'Play Slideshow',
					pauseLinkText:             'Pause Slideshow',
					prevLinkText:              '&lsaquo; Previous Photo',
					nextLinkText:              'Next Photo &rsaquo;',
					nextPageLinkText:          'Next &rsaquo;',
					prevPageLinkText:          '&lsaquo; Prev',
					enableHistory:             true,
					autoStart:                 true,
					syncTransitions:           false,
					enableKeyboardNavigation:  false, /*required false with any form textarea and use of spacebar */
					defaultTransitionDuration: 900,
					onSlideChange:             function(prevIndex, nextIndex) {
						// 'this' refers to the gallery, which is an extension of $('#thumbs')
						this.find('ul.thumbs').children()
							.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
							.eq(nextIndex).fadeTo('fast', 1.0);

						// Update the photo index display
						this.$captionContainer.find('div.photo-index')
							.html('Photo '+ (nextIndex+1) +' of '+ this.data.length);
					},
					onPageTransitionOut:       function(callback) {
						this.fadeTo('fast', 0.0, callback);
					},
					onPageTransitionIn:        function() {
						var prevPageLink = this.find('a.prev').css('visibility', 'hidden');
						var nextPageLink = this.find('a.next').css('visibility', 'hidden');
						
						// Show appropriate next / prev page links
						if (this.displayedPage > 0)
							prevPageLink.css('visibility', 'visible');

						var lastPage = this.getNumPages() - 1;
						if (this.displayedPage < lastPage)
							nextPageLink.css('visibility', 'visible');

						this.fadeTo('fast', 1.0);
					}
				});

				/**************** Event handlers for custom next / prev page links **********************/

				gallery.find('a.prev').click(function(e) {
					gallery.previousPage();
					e.preventDefault();
				});

				gallery.find('a.next').click(function(e) {
					gallery.nextPage();
					e.preventDefault();
				});

	}// end homepage slideshow


	
	//set class for links to external sites and other document types
	//$('#content a[href^="http://"]').addClass('external').attr('target', '_blank');
	$('#content a[href$=".pdf"]').addClass('pdf').attr('target','_blank');
	$('#content a[href$=".ppt"]').addClass('powerpoint').attr('target','_blank');
	$('#content a[href$=".doc"]').addClass('word').attr('target','_blank');
	$('#content a[href$=".xls"]').addClass('excel').attr('target','_blank');
	$('#content a[href$=".csv"]').addClass('excel').attr('target','_blank');
	
	$('#content a.remove_external').removeClass('external').attr('target', '_blank');

	// GALLERY LIGHTBOX
	$('#gallery a:has(img)').attr('rel', 'gallery').fancybox({
		cyclic:true,
		transitionIn:'elastic',
		transitionOut:'elastic'
	});

	$("a.gallery").fancybox();


	
	 // ROUNDED IMAGES
	// any image that is floated right
	$('img[style*="float: right;"]').each(function(){
		$div = $('<div/>').addClass('rounded_image round_10').css('background',"url('"+$(this).attr('src')+"')");
		$(this).wrap($div);
	}); 



	
	// CLICK THROUGHS
	/*
	// click on the parent triggers the click of the first link
	$click_through = $('.ftr_events li');
	// keep the click from bubbling to the parent
	// which will trigger this
	// which will trigger the parent
	// ...
	$('a', $click_through).click(function(e){
		e.stopPropagation();
		console.log($(this));
		return true;
	});
	$click_through.click(function(e){
		$(this).find('a:first').trigger('click');
		return false;
	}).css({'background':'yellow', 'cursor':'pointer'});
	*/
	
	/*
	// example for the form inputs based off of the label associated with the input
	$('form input, form textarea').example(function(){
		return $('label[for="'+$(this).attr('id')+'"]').text();
	});
*/


	/* FTR CONTACT FORM */
	//example, use the hidden label
	$('#ftr_name, #ftr_email, #ftr_msg').example(function(){
		return $('label[for="'+$(this).attr('id')+'"]').text();
	});
	//ajax submit
	$('#ftr_contact').submit(function(){
		//VALIDATION
		var from_email = $("#ftr_email"),
			message = $("#ftr_msg"),
			subject = $("#ftr_name"),
			allFields = $([]).add(from_email).add(subject).add(message),
			validate_error = $("#ftr_contact_message"),
			bValid = true,
			error_message = new Array();
			allFields.removeClass('ui-state-error');
		//validate the email address
		// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
		var regrex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
		var valid_email = checkRegexp(from_email,regrex);
		if(!valid_email){

			bValid = bValid && false;
			$("#ftr_email").addClass('ui-state-error');
			error_message.push('You must supply a properly formatted email address');
		}		
		//make sure there's something in the message box
		var valid_message = checkLength(message,10,1000);
		if(!valid_message){
			bValid = bValid && false;
			$("#ftr_msg").addClass('ui-state-error');
			error_message.push('You must supply a message that is at least 10 characters long');
		}

		if (bValid) {
			//send the data
			$(this).after('<div class="ajax_loader"><p><img src="layout_imgs/loading_arrows.gif" alt="sending" />&nbsp;sending, please wait...</p></div>').hide();
			//start ajaxing the data
			$data = $(this).serialize();
			$.post("ajax_email.php",
				$data,
				function(data, textStatus){
					if(data){
						allFields.val('').blur();
						$('.ajax_loader').html('<p><strong>Success!</strong> Your email was sent successfully. <a class="show_form">Send another?</a></p>');
						//the link to show the form again
						$('#ftr .ajax_loader a.show_form').css({cursor:'pointer'}).click(function(){
							//blank the form and show the examples by calling blur
							allFields.val('').blur();
							$('#ftr_contact').show();
							$('.ajax_loader').remove();
							return false;
						});

					} else {
						makeDialog("<p><strong>Sorry</strong><p><p>Your email could not be sent at this time. Please try again later.</p>",'Email Failed to Send');
						//blank the form and show the examples by calling blur
						allFields.val('').blur();
						$('.ajax_loader').remove();
						$('#ftr_contact').show();
					}
				},
				"json"
			);
		} else {
			//throw the dialog for errors
			var text = "<p>Your email reported the following errors and could not be sent.</p><ul><li>"+error_message.join('</li><li>')+"</li></ul><p>Please fix the error(s) and try again.</p>";
			makeDialog(text,'Form Error');
			//call the blur to show the examples again
			allFields.blur();
		}
		return false;
	});	


	
	//example, use the hidden label
	// have set the comment form to have the class example
	$('.example').example(function(){
		return $('label[for="'+$(this).attr('id')+'"]').text();
	});
	
	// BLOG
	// toggle the comments
	$('a.view_comments').each(function(){
		var count = $(this).parent('.links').next('.comments').find('.comment').length;
		$(this).text($(this).text()+' ('+count+')');
	}).click(function(){
		$(this).trigger('toggle', true);
		return false;
	}).bind('toggle', function(event, jumpTo){
		$link = $(this);
		// slide the comments into place with a callback
		$(this).parent('.links').next('.comments').slideToggle('fast',function(){
			// toggle view/leave with hide
			text = $link.text();
			if(text.indexOf("View/Leave")>=0){
				text = text.replace("View/Leave","Hide");
				if(jumpTo)
					$link.trigger('jumpTo');
			} else {
				text = text.replace("Hide","View/Leave");
				// dont need a scroll to since we are already at the links
			}
			$link.text(text);
		});
		return false;	
	}).bind('jumpTo', function(){
		$.scrollTo($(this).parent(),'fast');	
	});
	// if there's only one blog post show the comments automatically
	if($('div.blog_post').length==1){
		$(this).find('a.view_comments').trigger('toggle',false);
	}
	// SUBMITTING COMMENTS
	$('.comment_form').submit(function(){
		if(!$(this).find('input[name="email"]').val()){
			alert('You must supply your email address');
			return false;
		} else if(!$(this).find('textarea').val()){
			alert('You must supply a comment');
			return false;
		}
		// save the parent div.comments for inserting new comment to proper place
		var $comments = $(this).parents('.comments');
		var i = $(this).find('input[name="i"]').val() * 1;
		var new_i = i;
		new_i = new_i + 1;
		
		var form_data = $(this).serialize();
		$.ajax({
			url:'blog_includes/ajax_comment.php',
			data: form_data,
			type: "POST",
			beforeSend: function(){
				$('body').css('cursor','wait');
				$('.comment_form input, .comment_form textarea').attr('disabled','disabled');
			},
			success: function(data){
				if(data!="0"){
					// insert the comment
					if($('.comment:last',$comments).length)
						$('.comment:last',$comments).after(data);
					else if($('.none',$comments).length)
						$('.none',$comments).replaceWith(data);
					else
						window.location.reload();// if there's neither of the two options just refresh cause I don't know whats going on

					// update the i count
					$('input[name^="i"]',$comments).val(new_i);

					// now update the comment link
					var text = $comments.prev('.links').children('a.view_comments').text();
					if(text.indexOf("(")>=0){
						text = text.replace(/\(\d+\)/, "("+i+")")
					} else {
						text += ' ('+i+')';
					}
					$link.text(text);
				} else {
					alert('Sorry, but there was an error and you comment could not be posted at this time. Please try again later');
				}
				$('body').css('cursor','auto');
				$('.comment_form input, .comment_form textarea').removeAttr('disabled').not('input[type="submit"]').not('input[type="hidden"]').val('');
			}
		});

		return false;
	});
	// ARCHIVE LIST
	$('#blog_archives li.year').click(function(){
		$(this).children('ul').toggle();
	}).find('li.month').click(function(){
		$(this).children('ul').toggle();
		return false;
	}).find('a').bind('click',function(e){
		e.stopPropagation();
	});

	// DIALOG LINKS
	$('a.dialog').click(function(){
		// do a dialog for the video embed
		makeDialog('<h3><img src="layout_imgs/loading_bar.gif" alt="loading" /> Loading '+$(this).attr('title')+'</h3><p>please wait</p>', $(this).attr('title'));
		var element_rel = $(this).attr('name');
		// ajax in the data
		$('#made_dialog').load($(this).attr('href')+(element_rel ? ' '+element_rel : ''), function(rsp){
			// animate the containers to show everything
			$(this).parent().css('width','705px').animate( {
				top: $(this).parent().offset().top - (screen.height/4) + 20,
				left: '50%',
				marginLeft: -($(this).width() / 2)
			}, 'fast');
		});

		return false;
	});

	
	
	// EVENT CAL
	if($('#event_cal').length){

		$('#event_cal').datepicker({
			showButtonPanel: true,
			onChangeMonthYear: function(year, month, inst){
				events.onChangeMonthYear(year, month, inst);
			},
			onRefresh: function(year, month, inst){
				events.onRefresh(year, month, inst);
			},
			beforeShowDay: function(date){
				return events.beforeShowDay($.datepicker.formatDate('mm-dd-yy', date));
			},
			onSelect:function(date,inst){
				date = date.replace(/\//g,"-");
				//hide every visible event that doesn't have class of d+date
				$('#event_list .event:not(.d'+date+'):visible').slideUp('fast');
				//show every non-visible event that has a class of d+date
				$('#event_list .event.d'+date+':hidden').slideDown('fast');
				
			},
			onTitleClick:function(year, month, inst){
				//show all the hidden events
				$('#event_list .event:hidden').slideDown('fast');
			}
		});

		//set the history stuff
		$.History.bind(function(hash){
			if(hash.length){
				d = hash.split("-");
				var date = new Date();
				date.setFullYear(d[0]);
				date.setMonth(d[1]-1, 1);
				date.setDate(1);

				//update the date picker
				$('#event_cal').datepicker('setDate', date);
			} else {
				// no hash means we are back to the first time of events
				// before we loaded the current months events so the user
				// is going back, so go back
				history.back();
			}
		});
	}


}); // end document ready


var events = {
	months: {},
	currentCalendar: {},
	emptyEventSelector: '#empty_event',
	eventListSelector: '#event_list',
	onChangeMonthYear: function(year, month, inst){

		if(!$.History.getState){
			$.History.setState(year+'-'+month);
		} else {
			$.History.setHash(year+'-'+month);
		}

		// if we don't already have the data get it
		if(this.months[year+''+month]==null)
			this._load(year, month, inst);
		else {
			// set the calendar and then refresh
			this.currentCalendar = this._exportCalendar(year, month);
			jQuery('#'+inst.id).datepicker('refresh');
		}
	},
	onRefresh: function(year, month, inst){
		//redraw the event calendar
		this._redrawList(year, month);
		jQuery('#made_dialog').remove();
	},
	beforeShowDay: function(date){
		//either return the currentCalendar date array or false
		if(this.currentCalendar[date])
			return this.currentCalendar[date];
		else
			return false;

	},
	// loads in the events using ajax
	_load: function(year, month, inst){
		var e = this;
		//load the data in with ajax
		$.ajax({
			url:'ajax_events',
			data: {'year':year, 'month':month, 'rel':$('#event_cal').find('span.code').text()},
			dataType: 'json',
			beforeSend: function(){
				makeDialog('<div style="padding:10px 10px 0 10px; font-size:12px;text-align:center;"> <img src="layout_imgs/loading_bar.gif" alt="loading bar" /><p>loading events, please wait</p></div>','Loading Events',{},250,50,true);
			},
			success: function(json){
				// ajax_events will return false if there's no events in the month
				if(json){
					var m = [];
					$(json).each(function(){
						// FORMAT THE DATA PROPERLY
						// make sure this is above category because category gets overriden
						this.calendar_color = this.category.calendar_color;
						this.category = this.category.category;
						this.date = $.datepicker.parseDate('yy-mm-dd',this.date);;
						this.calendar_month = $.datepicker.formatDate('M', this.date).toLowerCase();
						
						//ditch the unnecessary info
						delete this.category_id;

						if(this.has_multiple_events){
							this.start_date = $.datepicker.parseDate('yy-mm-dd',this.start_date);
							this.end_date = $.datepicker.parseDate('yy-mm-dd',this.end_date);
						} else {
							delete this.start_date;
							delete this.end_date;
						}
						

						//add the data to the month holder
						m.push(this);
					});
					e.months[year+''+month] = m;
				} else {
					e.months[year+''+month] = false;
				}
				//add the calendar data to this and refresh the datepicker
				e.currentCalendar = e._exportCalendar(year, month);
				jQuery('#'+inst.id).datepicker('refresh');
			},//end success
			error: function (XMLHttpRequest, textStatus, errorThrown) {
			  console.log(textStatus);
			  console.log(errorThrown);
			}
		});
	},
	_exportCalendar: function(year, month){
		calendar_info = {};
		
		//loop through the events for the month
		$(this.months[year+''+month]).each(function(){
			formatted_date = $.datepicker.formatDate('mm-dd-yy', this.date);

			if(calendar_info[formatted_date]){
				//add the title and category span
				calendar_info[formatted_date][2] =  calendar_info[formatted_date][2] + ", " + this.title;
				
				//first check to make sure we aren't doubling up on category markers
				var span = '<span class="category" style="background:#'+this.calendar_color+';"></span>';
				if(calendar_info[formatted_date][3].indexOf(span) == -1)
					calendar_info[formatted_date][3] = calendar_info[formatted_date][3] + span;

			} else {
				calendar_info[formatted_date] = [true, 'event', this.title, '<br /><span class="category" style="background:#'+this.calendar_color+';"></span>'];
			}
		});

		return calendar_info;

	},
	_redrawList: function(year, month){
		//make sure to empty out the event list
		var $event_list = jQuery(this.eventListSelector);
		$event_list.empty();
		
		//are there events in this month?
		if(this.months[year+''+month]){
			//setup a refrence to this for the scope change in the loop
			var e = this;

			//now loop through the events in the current month
			$(e.months[year+''+month]).each(function(){
				//console.log(this);

				// touchup the title and time description to keep
				if(!this.title)
					this.title = "Untitled Event";
				if(!this.time || this.time=="false")
					this.time = "No time supplied";

				var date_class = 'd'+jQuery.datepicker.formatDate('mm-dd-yy',this.date);

				// check if this event_id is already added to an event
				if($('#e'+this.event_id, $event_list).length){
					// if there is already an event with the event id as a class
					// then add the date class so everything will still collapse properly
					$('#e'+this.event_id, $event_list).addClass(date_class);
				
				} else {


/*
				//clone and add data to the empty event
				var event = jQuery(e.emptyEventSelector).clone().removeAttr('id').addClass('d'+jQuery.datepicker.formatDate('mm-dd-yy',this.date)).
				find('.category').
					css('color','#'+this.calendar_color).text(this.category).
					prepend($('<span />').addClass('calendar_color round_5').css('background','#'+this.calendar_color)).end().
				find('.day_calendar').
					addClass(this.calendar_month).append(jQuery.datepicker.formatDate('d',this.date)).end().
				find('.month').
					text(this.calendar_month).end().
				find('.title').
					html(this.title).end().
				find('.time').
				text(this.time).end();
*/



	//clone and add data to the empty event  from aaawmn
					var event = jQuery(e.emptyEventSelector).clone().removeAttr('id').addClass(date_class).attr('id','e'+this.event_id).
					find('.calendar_color').
						css('background','#'+this.calendar_color).end().
					find('.title').
						html(this.title).end().				
					find('p.time').
						text(this.time).end();
			
	
				// handle the day calendars
				if(!this.has_multiple_events){
					event.find('div.repeating_days').hide();
	
					event.find('div.single_day').find('.day_calendar').
						addClass(this.calendar_month).append(jQuery.datepicker.formatDate('d',this.date)).end().
					find('.month').
						text(this.calendar_month).end();

				} else {
					var start_month = jQuery.datepicker.formatDate('M',this.start_date);
					start_month = start_month.toLowerCase();
					
					var end_month = jQuery.datepicker.formatDate('M',this.end_date);
					end_month = end_month.toLowerCase();
					
					event.find('div.single_day').hide();

					event.find('div.repeating_days').find('.start_day').
						addClass(start_month).
						append(jQuery.datepicker.formatDate('d',this.start_date)).end().
					find('.month').
						text(start_month).end().
					find('.end_day').
						addClass(end_month).
						append(jQuery.datepicker.formatDate('d',this.end_date)).end().
					find('.month').
						text(end_month).end();
				}
			
				
				// repeat note
					if(this.repeat_statement){
						event.find('p.repeats').html(this.repeat_statement);
					} else {
						event.find('p.repeats').hide();
					}
		
				
				
				// handle description
				if(this.description){
					//console.log($(event).find('.description'));
					$(event).find('.description').html(this.description);
				} else {
					$(event).find('.description').remove();
				}
				
				// special event flg
				if(this.special_event!=0){
					$(event).find('.special_event a').attr('href',this.special_event);
				} else {
					$(event).find('.special_event').remove();
				}
			
				$event_list.append(event);

			
				}	
			
			});
		} else {
			//notify that theres no events this month
			var msg = 'There are currently no events scheduled for this month. Please check back at a later date.';

			jQuery('<div/>').addClass('error').append('<p><strong>'+msg+'</p></strong>').appendTo(this.eventListSelector);
		}
	},
	//can't _formatTime because of the scope within the ajax function in _load
	formatTime: function(time){
		if(!time)
			return false;

		time_parts = time.split(':');
		hours = time_parts[0];
		minutes = time_parts[1];	

		var suffix = "am";
		if(hours >= 12) {
			suffix = "pm";
			hours = hours - 12;
		}
		if(hours == 0) {
			hours = 12;
		}
		
		format_time = hours+':'+minutes+suffix;

		return format_time;
	}
};



function makeDialog(text, dialog_title, buttons, width, height, hideTitleBar){
	if(!buttons){
		buttons = {
			Ok: function() {
				$(this).dialog('close');
			}
		}
	}

	$('<div id="made_dialog">'+text+'</div>').dialog({
		title: dialog_title,
		dialogClass: hideTitleBar ? 'hide_title' : 'alert',
		bgiframe: true,
		modal: true,
		stack:true,
		autoOpen:true,
		width: width ? width : 460,
		minHeight: height ? height : 220,
		draggable: true,
		resizable: true,
		buttons: buttons,
		close: function(event, ui){
			$(this).remove();
		}
	});
}


function checkRegexp(o,regexp) {
	if ( !( regexp.test( o.val() ) ) ) {
		return false;
	} else {
		return true;
	}
}

function checkLength(o,min,max) {
	if ( o.val().length > max || o.val().length < min ) {
		return false;
	} else {
		return true;
	}
}


window.alert = function(txt){
	makeDialog(txt, 'The page said:');
}

//CATCH CONSOLE.LOG FOR NO-FIREBUG
if (typeof console == 'undefined' || typeof console.log == 'undefined') { console = { log : function (text) { return false; } } }

function makeGoogleMap(address){
	var base = "http://maps.google.com/maps?f=q&hl=en&geocode=&time=&date=&ttype=&q=";
	return base + escape(address);
}


