var myfunctions = {
	textresize : function(){
		var $cookie_name = "textsize";
		var originalFontSize = $("#main").css("font-size");


		$("#text_sizer .reset").bind("click",function(){
				$("#main").css("font-size", originalFontSize);
				$.cookie($cookie_name, originalFontSize);
				$('#text_sizer').trigger('reset');
		});

		$("#text_sizer .smaller").bind("click",function(){
				var currentFontSize = $("#main").css("font-size");
				var currentFontSizeNum = parseFloat(currentFontSize, 10);
				var newFontSize = currentFontSizeNum - (currentFontSizeNum*.2);
				if (newFontSize > 12) {
					$("#main").css("font-size", newFontSize);
					$.cookie($cookie_name, newFontSize);
					$('#text_sizer').trigger('resized');
				}
				return false;
		});

		$("#text_sizer .bigger").bind("click",function(){
				var currentFontSize = $("#main").css("font-size");
				var currentFontSizeNum = parseFloat(currentFontSize, 10);
				var newFontSize = currentFontSizeNum*1.2;
				if (newFontSize > 12 && newFontSize <40) {
					$("#main").css("font-size", newFontSize);
					$.cookie($cookie_name, newFontSize);
					$('#text_sizer').trigger('resized');
				}
				return false;
		});

		$('#text_sizer').bind('resized', function(){
			$('#text_sizer_msg:hidden').slideDown('fast');
		})
		.bind('reset', function(){
			$('#text_sizer_msg:visible').slideUp('fast');
		});
	}
}

$(document).ready(function(){
	
	//TEXT RESIZING
	myfunctions.textresize();
	
	//DROPDOWN MENU
	$('ul.sf-menu').supersubs({ 
            minWidth: 12,   // minimum width of sub-menus in em units 
            maxWidth: 27,   // maximum width of sub-menus in em units 
            extraWidth: 1     // extra width can ensure lines don't sometimes turn over 
                               // due to slight rounding differences and font-family 
        }).superfish();  // call supersubs first, then superfish, so that subs are 
                         // not display:none when measuring. Call before initialising 
                         // containing tabs for same reason. 

	//EXAMPLE FOR SEARCH FORM
	$('#hdr .search_frm #q').example(function() {
       return $(this).attr('title'); 
    });

	//LINK ICONS
	$('a[href^="http://"]').attr('target','_blank').not('.no_icon').append('<span class="link_icon external"></span>');
	$('a[href$="pdf"]').not('.no_icon').attr('target','_blank').append('<span class="link_icon pdf"></span>');
	$('a[href$="doc"],a[href$="docx"],a[href$="rtf"],a[href$="txt"]').not('.no_icon').attr('target','_blank').append('<span class="link_icon word"></span>');
	$('a[href$="xls"],a[href$="xlsx"],a[href$="csv"]').not('.no_icon').attr('target','_blank').append('<span class="link_icon excel"></span>');
	$('a[href$="ppt"],a[href$="pptx"]').not('.no_icon').attr('target','_blank').append('<span class="link_icon ppt"></span>');

	//SERVICES
	$('h2.service').click(function(){
		$(this).toggleClass('open')
			.toggleClass('closed')
			.next('.organizations')
				.slideToggle();
	});
	$('#service_jumps a').click(function(){
		$($(this).attr('rel')).click();
	});

	// BLOG
	// toggle the comments
	$('a.view_comments').each(function(){
		var count = $(this).parent('.links').next('.comments').find('.comment').length;
		if(count)
			$(this).text($(this).text()+' ('+count+')');
	}).click(function(){
		$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");
			} else {
				text = text.replace("Hide","View/Leave");
			}
			$link.text(text);
		});
		return false;
	});
	// if there's only one blog post show the comments automatically
	if($('div.blog_post').length==1){
		$(this).find('a.view_comments').click();
	}
	// 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();
	});
	// 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;
	});


	// PROGRAM RELATED EVENTS
	$('p.full_event a').click(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 event info, please wait</p></div>','Loading Event Info',{},250,50,true);

		$('#made_dialog').load(
			$(this).attr('href'),
			function(){
				// set the close click
				$(this).find('#event_info_hdr a').click(function(){
					$('#made_dialog').remove();
					return false;
				});

				// animate the containers to show everything
				console.log($(this).parent().parent());
				$(this).parent().animate( {width:"780px", left: "50%", marginLeft: "-390px", top: $(this).parent().offset().top - (screen.height/4) - 50}, 'fast');
				$(this).css('padding','0').animate(
					{ width: "780px", minHeight: "300px"},
					'fast'
				);
			}
		);
		

		return false;
	});


	// CLASSES BY COUNTY
	$('.toggle_dates').click(function(){
		if($(this).hasClass('plus')){
			var $el = $(this).next('.other_dates');
		} else {
			var $el = $(this).parent('.other_dates');
		}
		$el.slideToggle('fast');
	});


	// 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();
			}
		});
	}
	


});

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},
			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();

						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;
						}
						
						//ditch the unnecessary info
						delete this.category_id;
						delete this.repeat_days;
						delete this.exceptions;

						//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;

			//console.log(e.months[year+''+month]);

			//now loop through the events in the current month
			$(e.months[year+''+month]).each(function(){
				// 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(date_class).attr('id','e'+this.event_id).
					find('.calendar_color').
						css('background','#'+this.calendar_color).end().
					find('h2.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();
					}
					
					// handle location
					if(!this.location_name){
						event.find('h3').hide().end().find('p.address').hide();
					} else {
						event_location = this.location_name ? '<strong>'+this.location_name+'</strong><br /> ' : '';
						event_location += this.address_1 ? this.address_1+'<br /> ' : '';
						event_location += this.address_2 ? this.address_2+'<br /> ' : '';
						event_location += this.city ? this.city+', ' : '';
						event_location += this.state ? this.state+' ' : '';
						event_location += this.zip ? this.zip : '';
						event_location += this.address_1 ? '<br /><a href="'+makeGoogleMap(this.address_1+' '+(this.address_2 ? this.address_2 : '')+' '+this.city+' '+this.state+' '+this.zip)+'" title="map" target="_blank">map<span class="link_icon external"></span></a>' : '';

						event.find('p.address').html(event_location);
					}

					// repeat note
					if(this.repeat_statement){
						event.find('p.repeats').html(this.repeat_statement);
					} else {
						event.find('p.repeats').hide();
					}
					
					// handle the full event link
					if(this.has_description==false && this.has_multiple_events==false){
						event.find('p.full_event').addClass('note').html('no additional details supplied');
					} else {
						event.find('p.full_event a').attr('href','event_info?event_id='+this.event_id+'&date='+(this.date.getTime()/1000)).click(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 event info, please wait</p></div>','Loading Event Info',{},250,50,true);

							$('#made_dialog').load(
								$(this).attr('href'),
								function(){
									// set the close click
									$(this).find('#event_info_hdr a').click(function(){
										$('#made_dialog').remove();
										return false;
									});

									// animate the containers to show everything
									$(this).parent().animate( {width:"780px", left: "50%", marginLeft: "-390px", top: $(this).parent().offset().top - (screen.height/4) - 50}, 'fast');
									$(this).css('padding','0').animate(
										{ width: "780px", minHeight: "300px"},
										'fast'
									);
								}
							);
							

							return false;
						});
					}
				
					$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
	});
}

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

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