$(document).ready(function() {
   // nav prep
   $('#nav>li').each(function(i) {
      $(this).addClass('nav-'+(i));
   });
   $('#nav li li.current').parent().parent().addClass('current');
	/*   $('body:not("#home") #nav > li').each(function() {
      $(this).not('.current').addClass('not_current');
   });
   Cufon.replace('#nav > li > a', {
      textShadow: '-1px -1px rgba(0, 0, 0, 0.2)'
   });
   Cufon.replace('#content h2, #sidebar h3, #home-links li a, #home-content h3', {
      hover: true
   });
   */
   // makes styling easier
   $('ul').each(function() {
   $(this).find('li:last-child').addClass('last');
   $(this).find('li:first-child').addClass('first');
   });
   // nav accordion
   $('body:not("#home") #nav > li a').click(function() {
         targetLI = $(this).parent();
         if (targetLI.hasClass('current')) {
            targetLI.addClass('open');
         };
         targetUL = targetLI.find('ul');
         // close all lists
         $('#nav li').children('ul').slideUp('fast');
         $('#nav>li').each(function() {
            $(this).removeClass('current');
         });
         // if ul was already open, simply remove current class and keep closed.
         if (targetLI.hasClass('open')) {
            targetLI.removeClass('open');
            return false;
         // if not, open new one and add current class
         } else {
            targetUL.slideDown('fast');
            targetLI.addClass('current');
         };
         // prevent default action for only the ones who dont have a url set
   		if ( $(this).attr('href') == '#' ) {
   			return false;
   		}
   });

   // 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);
      };
   });
   // Search Submission
   $("#search_go").click(
		function() {
			$("#searchForm").submit();
			return false;
		}
	);
   // Make external links validate
   $('a.external').attr('target', '_blank');
   // Event List
   $('#caltabs li a').bind('click', switchCalTabs);
   if($.browser.msie && parseFloat($.browser.version) < 8){
      $('.sermon-buttons').each(function() {
         var bWidth = 0;
         $(this).find('li a').each(function() {
            bWidth+=$(this).width();
         });
         bLength = bWidth+7;
         $(this).css('width', bLength);
      });
   }
   
   sermonSort();
   embedVideo();
   calHovers();
   
   $('.sl_video a, #mb_video a, a.video').live('click', playVideo);	
   $('.sl_listen a, li#listen a, #mb_jukebox a, p.play a').live('click', playAudio);		
   
   $('#mini-cal caption a').live('click', miniCalSwitch);
   $('#events-calendar caption a').live('click', switchCalendar);
});

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

// 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(){
	if($(this).attr('rel').length > 1){
		var place = $(this).attr('href');
	} else {
		var place = 'http://cpmassets.com/video.php?video='+$(this).attr('href');
	}
	window.open(place, 'videoPlayer', 'width=640,height=320,scrollbars=0,statusbar=0,address=0');
	return false;
}

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

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

function calHovers(){
	$("table.calendar").delegate("td", "mouseover mouseleave", function(e){
	    e = $.event.fix(e);
	    if(e.type == 'mouseover'){
	
	        var posX = e.currentTarget.offsetLeft+(e.currentTarget.clientWidth-4);
	        var posY = e.currentTarget.offsetTop+(e.currentTarget.clientHeight-10);
	
	        $(this).find("ul").css({
	            top:posY+"px",
	            left:posX+"px"
	        });
	
	    } else {
	        $(this).find("ul").css({ left:"-999em"});
	    }
    });
}

// embed video player in page
function embedVideo(){
	// Video Embedding
	var vid = 1;
	$('.video').each(function(){
		var vurl = $(this).attr('onclick').toString();
		vurl = vurl.split('waspPopup')[1];
		vurl = vurl.split('\',')[0].replace('\'', '').replace('(', '');
		$(this).before('<div id="video'+vid+'">'+vurl+'</div>');		
		$(this).remove();
		
		var flashvars = { 
			file: vurl,
			autostart:'false',
			frontcolor: 'ffffff',
			lightcolor: 'cc9900',
			skin: 'http://www.longtailvideo.com/jw/upload/overlay.swf',
			controlbar: 'over'
		};
		
		var params = { wmode:'transparent' };
		var attributes = {  };
		
		if($(this).find('img').attr('src')){
			flashvars.image = $(this).find('img').attr('src');
		}
		swfobject.embedSWF("/file/media/player.swf", "video"+vid, "620", "440", "9.0.0", "/file/media/expressInstall.swf", flashvars, params, attributes);		
		$(this).remove();								
		vid++;			
	});
}

$(".Reset_area a").click(function(){	
		var key	= "reset";
		var val = "reset";				
		
		$('#sermon-list').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-list').html(o).css({height:'auto', background:'none'});			
			$('#current').hide();
			$('#all-messages').focus();
			Logos.ReferenceTagging.lbsBibleVersion = "NIV";
		    Logos.ReferenceTagging.lbsLinksOpenNewWindow = true;
		    Logos.ReferenceTagging.lbsLibronixLinkIcon = "dark";
		    Logos.ReferenceTagging.lbsNoSearchTagNames = [ "h1", "h2", "h3" ];
		    Logos.ReferenceTagging.tag();
		}
		);	
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-list').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-list').html(o).css({height:'auto', background:'none'});			
			$('#current').hide();
			$('#all-messages').focus();
			Logos.ReferenceTagging.lbsBibleVersion = "NIV";
		    Logos.ReferenceTagging.lbsLinksOpenNewWindow = true;
		    Logos.ReferenceTagging.lbsLibronixLinkIcon = "dark";
		    Logos.ReferenceTagging.lbsNoSearchTagNames = [ "h1", "h2", "h3" ];
		    Logos.ReferenceTagging.tag();
		}
		);		
	}	
	
	$('.sorter').change(function(){
	
		if ( $.lastSort != $(this).attr('id') && $.lastSort != undefined ) {
			if ( $.lastSort == 'month' ) {
				var opt = 'Month';
			}
			if ( $.lastSort == 'series' ) {
				var opt = 'Series';
			}
			if ( $.lastSort == 'category' ) {
				var opt = 'Topic';
			}
			if ( $.lastSort == 'speaker' ) {
				var opt = 'Speaker';
			}
			$('#select'+$.lastSort).text(opt);
			$('#'+$.lastSort).find('option').eq(0).attr('selected','selected');
		}
		$.lastSort = $(this).attr('id');
		
		window.location.hash = this.id+'_'+this.value;
		$('#sermon-list').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-list').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 = "NIV";
				    Logos.ReferenceTagging.lbsLinksOpenNewWindow = true;
				    Logos.ReferenceTagging.lbsLibronixLinkIcon = "dark";
				    Logos.ReferenceTagging.lbsNoSearchTagNames = [ "h1", "h2", "h3" ];
				    Logos.ReferenceTagging.tag();					
				}
			);
		}
	});		
	/* END SERMON SORTING */
}


