$(document).ready(function(){		
	
	sermonSort();
	
	$('.sl_video a, #mb_video a, a.video').live('click', playVideo);	
	$('.sl_listen a, #mb_jukebox a, a.play').live('click', playAudio);		
   
   	$('.external').attr('target', '_blank');
   	$('#tabs li a').bind('click', switchCalTabs);
	$('#months').bind('change', switchCalMonth);
	$('#events-calendar caption a').live('click', switchCalendar);
	$('#list-view li a').live('click', switchEventList);
  	$('#category-filter').bind('change', sortEvents);

	// clear and restore search input
   $('input.clickClear').focus(function() {
      startText = $(this).val();
      $(this).val('');
   });
   $('input.clickClear').blur(function() {
      blurText = $(this).val();
      if (blurText == '') {
         $(this).val(startText);
      };
   });
   
   //Cufon.replace('#nav > li a', {fontFamily: 'regular'});
   //Cufon.replace('#primaryContent h2', { fontFamily: 'semibold' });
   
   $('#quicklinks li:last').addClass('last');
   $('ul').each(function() {
      $(this).find('li:first-child').addClass('first');
      $(this).find('li:last-child').addClass('last');
   });

	/* SERMON SORTING */		
	// see if there is something in the query string to initially load
	var sort = window.location.hash;
	// assign topbar parents a special class
    $('#topbar li').each(function() {
    var kids = $(this).children().size();
    if (kids > 1) {
    $(this).addClass('parent');
    };
    });
    
    // Append add this to footer links
    addThis();

});

// launch audio player
function playAudio(){
	window.open('http://cpmassets.com/audio-player.php?audio='+$(this).attr('href'), 'audioPlayer', 'width=210,height=30,status=0,toolbar=0'); 
	return false;
}

// launch video player
function playVideo(){
	var $self = $(this);

	if($self.attr('nodeName') !== 'A'){
		if($self.parent().attr('nodeName') == 'A'){
			var $self = $self.parent();
		} else {
			return;
		}
	}
	
	if($self.attr('rel').length > 1){
		var place = $self.attr('href');
	} else {
		var place = 'http://cpmassets.com/video.php?video='+$self.attr('href');
	}
	window.open(place, 'videoPlayer', 'width=640,height=320,scrollbars=0,statusbar=0,address=0');
	return false;
}

// sermon sorting functions
function sermonSort(){
/* SERMON SORTING */		
	// see if there is something in the query string to initially load
	var sort = window.location.hash;
	
	if(sort){
		var parts = sort.split('_');
		var key	= parts[0].replace('#', '');
		var val = parts[1];			
	
		
		$('#sermon-content').html('').css({height:'300px', background:'url(/img/ajax-loader.gif) no-repeat center center'});
		$.get('/ajax/sermons.php', {		
			key:key,
			val:val
		},
		function(o){			
			$('#sermon-content').html(o).css({height:'auto', background:'none'});			
			$('#current').hide();
			$('#all-messages').focus();
			Logos.ReferenceTagging.lbsBibleVersion = "ESV";
		    Logos.ReferenceTagging.lbsLinksOpenNewWindow = true;
		    Logos.ReferenceTagging.lbsLibronixLinkIcon = "dark";
		    Logos.ReferenceTagging.lbsNoSearchTagNames = [ "h1", "h2", "h3" ];
		    Logos.ReferenceTagging.tag();
		}
		);		
	}	
	
	$('.sorter').change(function(){
		window.location.hash = this.id+'_'+this.value;
		$('#sermon-content').html('').css({height:'300px', background:'url(/img/ajax-loader.gif) no-repeat center center'});
		if(this.selectedIndex !== 0){
			$.get('/ajax/sermons.php', { 
				'key':this.id,
				'val':this.value			
				}, 
				function(o){				

					//$('#primaryContent > h2').html(response[0]);
					$('#sermon-content').html(o).css({height:'auto', background:'none'});			
					$('#current').hide();					
					
					// reset sorter selects to first value
					$('.sorter').attr({ selectedIndex:0 })		
					$('#all-messages').focus().css('outline', 'none');
				    Logos.ReferenceTagging.lbsBibleVersion = "ESV";
				    Logos.ReferenceTagging.lbsLinksOpenNewWindow = true;
				    Logos.ReferenceTagging.lbsLibronixLinkIcon = "dark";
				    Logos.ReferenceTagging.lbsNoSearchTagNames = [ "h1", "h2", "h3" ];
				    Logos.ReferenceTagging.tag();					
				}
			);
		}
	});		
	/* END SERMON SORTING */
}

function switchCalTabs(){
	var div = '#'+$(this).attr('rel');
   if (div=="#events-calendar") {
      $('#events-calendar').show();
      $('#list-view').hide();
   } else {
      $('#list-view').show();
      $('#events-calendar').hide();
   };
	$('#tabs li').removeClass('current');
	$(this).parent().addClass('current');
	
	sortEvents();
	return false;
}

function switchCalMonth(){
	var month = $(this).val();
	$.get('/ajax/events.php', { month:month }, function(data){
		$('#events-calendar').html(data);
	});
}

function switchCalendar(){
	var parts = $(this).attr('href').split('/');
	var month = parts.pop();
	var year  = parts.pop();
	$.get('/ajax/events.php', { month:month, year:year }, function(data){
		$('#events-calendar').html(data);
		sortEvents();
	});
	
	return false;
}

function switchEventList(){
	var parts = $(this).attr('href').split('/');
	var endparts = parts.pop().split('-');
	var month = endparts.pop();
	var year  = endparts.pop();
	$.get('/ajax/events.php', { month:month, year:year, view:'list'}, function(data){
		$('#list-view').html(data);
	});
	return false;
}

function sortEvents(){	
	
	// show all calendar items and list items
	$('#events-calendar li, #list-view dl.event-info, .monthwrap, .monthlabel').fadeIn();
	$('.monthwrap .notice').remove();
	
	var $self = $('#category-filter');
	var $catname  = $self.find('option:selected').text();

	if($self.find('option:selected').val() > 0){	
	
		// If all events is not chosen, filter
		var $cat = 'category_'+$self.val();			
		$('#events-calendar li:not(.'+$cat+')').fadeOut();
		
		// Get the list
		var $months = $('div.monthwrap');
		
		$months.each(function(){
			var $monthname = $(this).find('dt:first').text();
			var $events = $(this).find('dl.event-info');

			var i = 0;
			$events.each(function(){
				if(!$(this).hasClass($cat)){					
					i++;	
					$(this).fadeOut();
				}
			});
			
			// They are all hidden
			if(i == $events.length) {
				$(this).find('.monthlabel').hide();
				$(this).append('<dt class="notice">There no events for the '+$catname+' category in '+$monthname);
			}
			i = 0;
		});			
			
	}		

}

function addThis(){	
	
	// Add on the script
	var scrpt = document.createElement('script');
	scrpt.type = 'text/javascript';
	scrpt.src = 'http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4c890b7c359274b2';
	document.getElementsByTagName('body')[0].appendChild(scrpt);
	
	// Now add the button
	var $ul = $('#footer ul');
	var lnk	= '<a href="http://www.addthis.com/bookmark.php?v=250" class="addthis_button">'
			 +'<img src="http://s7.addthis.com/static/btn/sm-plus.gif" width="16" height="16" border="0" alt="Share" />'
			 +'</a>';
			 
	$ul.find('li:last').append(lnk);
}
