$(window).load(function(){
	// HOMEPAGE SLIDESHOW
	if($('#slideshow_holder #slides').length>0){
		$('#slideshow_holder #slides').nivoSlider({
			animSpeed:500,
			pauseTime:3000,
			directionNav:false
		});
	}
});
$(document).ready(function(){

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


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

	
	// INLINE RELATED LINKS
	var inline_links = new Array();
	var links = new Array();
	$('#content a').filter(function(){
		// class is not related
		if($(this).hasClass('not_related')==true)
			return false

		// contained in .opportunity
		if($(this).parents('.opportunity').length >= 1)
			return false

		// if here return true
		return true;
			
	}).each(function(){
		// if there's no text, return false (which is equvilant to continue)
		if($(this).text()=='')
			return false;

		if($.inArray($(this).attr('href'),inline_links)==-1){
			inline_links.push($(this).attr('href'));
			links.push({href:$(this).attr('href'),title: $(this).text()});
		}
	});
	if($(links).length>0){
		$inline_links = $('<ul />').addClass('inline_links');
		$(links).each(function(){
			$inline_links.append('<li><a href="'+this.href+'" title="'+this.title+'">'+this.title+'</a></li>');        
		});
		$('#related_links').append('<h5>Inline Links</h5>').append($inline_links);
		$('#related_links:hidden').show();
	}


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

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

	$('a[href="***back"]').click(function(){
		history.go(-1);
		return false;
	});


	// BECOME A MEMBER FORM
	// bind for other fill in
	$('#ethnicity_id').bind('changed',function(e,ids){
		ids = ids.split(',');
		// $.inArray returns the index when found or -1 if not found
		if($.inArray($(this).val(),ids) >= 0){
			// found, do some stuff
			$('#ethnicity_other_holder:hidden').slideDown('fast');
			$('#ethnicity_other').focus();
		} else {
			$('#ethnicity_other_holder:visible').slideUp('fast');
			$('#ethnicity_other').val('');
		}
	});
	$('#lives_with_id').bind('changed',function(e,ids){
		ids = ids.split(',');
		// $.inArray returns the index when found or -1 if not found
		if($.inArray($(this).val(),ids) >= 0){
			// found, do some stuff
			$('#lives_with_other_holder:hidden').slideDown('fast');
			$('#lives_with_other').focus();
		} else {
			$('#lives_with_other_holder:visible').slideUp('fast');
			$('#lives_with_other').val('');
		}
	});
	// trigger the change for selects onload to check for fields already filled out
	// like when there is a required field missing
	$('#member_form select[onchange]').trigger('change');
	
	// make member address copy over to parent_1_address
	$('[name="address"],[name="city"],[name="state"],[name="zip"]').change(function(){
		$parent = $('[name="parent_1_'+$(this).attr('name')+'"]');
		if(!$parent.val())
			$parent.val($(this).val());
	});


	
	// SECTIONS
	//handle different languages
	var langs = {
		'en' : {
			'jump_to_a_section':'Jump to a Section',
			'jump_to':'Jump to',
			'previous':'Previous',
			'next':'Next',
			'view_all_sections':'View All Sections',
			'all':'All',
			'submit':'Submit'
		},
		'es' : {
			'jump_to_a_section':'Saltar a una Secci&oacute;n',
			'jump_to':'Saltar a',
			'previous':'Anterior',
			'next':'Pr&oacute;ximo',
			'view_all_sections':'Ver Todas las Secciones',
			'all':'Todos',
			'submit':'Entregar'
		}
	}
	//spanish or english?
	if($('#content').hasClass('spanish')){
		var lang = langs.es;
	} else {
		var lang = langs.en;
	}	

	var $jumps = $('<ul id="member_form_jumps" />');
	var i = 1;
	var total = $('#member_form fieldset').length;
	$('#member_form fieldset').each(function(){
		// add the jump
		var $li = $('<li class="round_5" title="'+lang.jump_to+' '+$('legend',$(this)).text()+'">'+i+'</li>').data('fieldset', $(this));
		$jumps.append($li);
		// if there are errors in the form, add the class
		if($('label.form_error',$(this)).length>0){
			$li.addClass('error');
		}
		// add the li to the data of this fieldset
		$(this).data('li',$li);

		// no prev button on the first one
		if(i > 1){
			var $prev = $('<input class="previous" type="button" value="'+lang.previous+'" />').click(function(){
				$(this).parent().prev().trigger('show');
			});
			$(this).append($prev);
		}		
		// no next button on the last one, it already has a save
		if(i < total){
			var $next = $('<input class="next" type="button" value="'+lang.next+'" />').click(function(){
				$(this).parent().next().trigger('show');
			});
			$(this).append($next);
		}
		i++;

	// custom event for showing and hiding
	}).bind('show', function(){
		// make sure our next/previous buttons are visible
		$('.next, .previous', $(this)).show();

		$('#member_form fieldset:visible').not($(this)).hide().data('li').removeClass('current');
		$('#jump_holder .all').removeClass('current');

		$(this).show().data('li').addClass('current');
		$('input:first', $(this)).focus();

		$.scrollTo('#content','fast');
	
	// hide them all but the first
	}).not(':first').hide();

	// jump functionality
	$all_jump = $('<li class="all round_5" title="'+lang.view_all_sections+'">'+lang.all+'</li>').click(function(){
		// hide all the next/previous buttons
		$('.next, .previous').hide();

		// show all the sections
		$('#member_form fieldset').show();

		// remove and add class
		$('#jump_holder li.current').removeClass('current');
		$(this).addClass('current');
	});
	$jumps.append($all_jump);
	$('#jump_holder').append($jumps);
	$('li',$jumps).click(function(){
		$(this).data('fieldset').trigger('show');
	}).hover(
		function(){
			$('#jump_holder h5').text($(this).attr('title'));
		},
		function(){
			$('#jump_holder h5').text(jumps_default_text);
		}
	);
	$('#member_form_jumps li:first').addClass('current');
	//unwrap the submit button
	$submit = $('#member_form td.buttons input:submit').remove().attr('value',lang.submit);
	$('#member_form td.buttons').remove();
	$submit.addClass('submit').insertAfter('#member_form fieldset:last input.previous');



	// FAST FACTS
	if($('.fast_facts').length>0){
		// TABLE SETUP
		$('.fast_facts table').each(function(){
			// zebra stripe the table rows
			$('tr:even', $(this)).addClass('even');
			
			// add a tfoot like thead
			var colspan = $('tbody tr:first td', $(this)).length;
			 $('tbody', $(this)).after('<tfoot><tr><td colspan="'+colspan+'">&nbsp</td></tr></tfoot>');
		});


		// ACCORDIAN SETUP
		$('h2',$('.fast_facts')).addClass('accordian_heading').each(function(){
			$(this).nextUntil('.accordian_heading').wrapAll('<div class="accordian_content"></div>');
		}).click(function(){
			// this one is currently open
			if($(this).next('.accordian_content:visible').length>0){
				$(this).removeClass('open').next('.accordian_content').slideToggle();
			} else {
				$('.accordian_content:visible').slideToggle().prev().removeClass('open');
				$(this).addClass('open').next('.accordian_content').slideToggle(function(){
					$.scrollTo($(this).prev(), 'fast');	
				});				
			}
		});	
	}



	// HISTORY TIMELINE
	if($('#timeline_holder').length>0){
		// event click
		$('.year ul li').click(function(e){
			$('#history_content').html('<h2>'+$(this).find('span.hidden').text()+'</h2>'+$(this).find('.content').html());
		});
		// year heading click
		$('.year p.heading').click(function(e){
			$('#history_content').html('<h2>'+$(this).text()+'</h2>');
			$('li .content', $(this).parent()).each(function(){
				$('#history_content').append('<div class="history_portion">'+$(this).html()+'</div>');
			});
		});
		// start by clicking the first year
		$('.year:first-child p.heading').click();
		

		// figure out the number of years in the timeline
		var total_years = $('#timeline .year').length;
		var timeline_year_width = ($('#timeline .year').width() + ($('#timeline .year').css('marginRight').replace('px','')*1));
		var scroll_year_width = $('.scroll_year').width();
		var timeline_width = timeline_year_width * total_years;
		var container_width = $('#timeline_holder').width();

		// set the timeline to the total_years * the width of the year + padding
		$('#timeline').width(timeline_width);

		// add padding onto the scroll years so their width's fit
		var padding = Math.floor((($('#scroll').width()/total_years) - scroll_year_width)/2);
		$('.scroll_year').css('padding', '0 '+padding+'px');
		scroll_year_width = $('.scroll_year').outerWidth();

		if(timeline_width > container_width){
			
			// minus 2 pixel to account for the border
			$('#highlight').width((scroll_year_width/timeline_year_width)*container_width-2);

			$('#bar').width((scroll_year_width/timeline_year_width)*container_width).draggable({
				containment: 'parent',
				drag: function(event, ui){
					
					if(!this.elem){
						// run once for performance boosts
						this.elem = $('#timeline');
						
						/* The difference between the slider's width and its container: */
						this.maxSlide = ui.helper.parent().width()-ui.helper.width();

						/* The difference between the timeline's width and its container */
						this.cWidth = this.elem.width()-this.elem.parent().width();
						this.highlight = $('#highlight');
					}

					/* Translating each movement of the slider to the timeline: */
					this.elem.css({marginLeft:'-'+((ui.position.left/this.maxSlide)*this.cWidth)+'px'});
				
					/* Moving the highlight: */
					this.highlight.css('left',ui.position.left)
				}
			});
		}		
	}



	// DONATE PAGE
	if($('#donation_holder').length){
		$('select.campaign').change(function(){
			var $this = $(this),
				campaign = $('option:selected', $this).val(),
				suggested_amount = $('option:selected', $this).attr('data-suggested_amount'),
				input = $this.parents('form').find('input[id$="_amount"]');

			if(suggested_amount!=undefined && suggested_amount!=''){
				// always add the note
				input.next('p.suggested_note').html('We suggest a gift of '+suggested_amount+' for '+campaign);

				// change the amount if it's a prefilled or empty
				if(input.val()=='' || input.hasClass('suggested_amount')){
					input.val(suggested_amount);
					input.addClass('suggested_amount');
				}

			} else {
				input.next('p.suggested_note').html('');
			}

		}).change();

		$('input[name="amount"], input[name="a3"]').change(function(){
			$(this).removeClass('suggested_amount');
		});
	}



	// OPPORTUNITIES FILTER
	$('#opportunity_filter #location').change(function(){
		var val = $(this).val();

		if(val=='all'){
			$('.opportunity').show();
		} else {
			$('.opportunity').each(function(){
				if( $(this).is('[data-locations~="'+val+'"]') )
					$(this).show();
				else
					$(this).hide();
			});
		}

		if($('.opportunity:visible').length == 0)
			$('#no_opportunities').show();
		else
			$('#no_opportunities').hide();
	});

	
	// 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');			
			},
			minDate: '-1d'
		});

		//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, '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;
						delete this.start_date;
						delete this.end_date;
						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;

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

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

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