$(document).ready(function() {
   	// makes styling easier
   	$('ul').each(function() {
   		$(this).find('li:last-child').addClass('last');
   		$(this).find('li:first-child').addClass('first');
   	});
   
   	// 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);
    	};
    });
    // Make external links validate
    $('a.external').attr('target', '_blank');
   
    $('#side-events, #sidebarCalendar').find('caption a').live('click', miniCal);

   	sermonSort();
	embedVideo();
	
	$('.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');
   	$('#views li a').bind('click', switchCalTabs);
	$('#months').bind('change', switchCalMonth);
	$('#events-calendar caption a').live('click', switchCalendar);
	$('#list-view li a').live('click', switchEventList);
});



// 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;
}

// 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++;			
	});
}

// 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 = "NIV";
		    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 = "NIV";
				    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');
	$('#events-container div').hide();
	$(div).show();
	$('#views li').removeClass('current');
	$(this).parent().addClass('current');
	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);
	});
	return false;
}

function switchEventList(){
	var parts = $(this).attr('href').split('/');
	parts	  = parts.pop().split('-');
	var month = parts.pop();
	var year  = parts.pop();
	$.get('/ajax/events.php', { month:month, year:year, view:'list'}, function(data){
		$('#list-view').html(data);
	});
	return false;
}

function miniCal(){
	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){
		$('#sidebarCalendar').html(data);
	});
	return false;
}


// Columnize List

/**
 * Copyright (c) 2007 Ingo Schommer (www.chillu.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Splits a <ul>/<ol>-list into equal-sized columns.
 * 
 * Requirements: 
 * <ul>
 * <li>All list-elements need to have the same height.</li>
 * <li>List has to be blocklevel</li>
 * </ul>
 * 
 * Caution: margin-top/margin-left on <li> are overridden.
 * Doesn't react to changes to the DOM, you need to call the function
 * manually afterwards.
 * 
 * @see http://www.alistapart.com/articles/multicolumnlists
 */
jQuery.fn.columnizeList = function(settings){
	settings = jQuery.extend({
		cols: 3,
		width: '13',
		unit: 'em'
	}, settings);
	
  	var prevColNum = 0;
  	var size = $('li',this).size();
  	var computedColHeight = 0;
  	var baseFontSize = parseFloat($(this).css('font-size'));
  	$('li',this).each(function(i) {
		var currentColNum = Math.floor(((i)/size) * settings.cols);
		$(this).css('margin-left',(currentColNum*settings.width)+''+settings.unit);
		if(prevColNum != currentColNum) {
			$(this).css('margin-top','-'+(computedColHeight/baseFontSize)+'em');
			computedColHeight = $(this).height();
		} else {
			$(this).css('margin-top','0');
			computedColHeight += $(this).height();
		}
		prevColNum = currentColNum;
	});

	this.css('height',(size/settings.cols)*(parseFloat($('li:first',this).height())/baseFontSize)+'em');
	this.after('<br style="clear: left;">');
	
	var onchange = function(e) {
		if(!e.originalTarget || e.originalTarget.tagName != 'LI') return true;
		var scope = this; // caution: closure
		setTimeout(function() {$(scope).columnizeList(settings);}, 50);
	};
	
	this.one('DOMNodeInserted',onchange);
	this.one('DOMNodeRemoved',onchange);
	
	return this;
};

jQuery.fn.uncolumnizeList = function(){
	$('li',this).each(function(i) {
		if(!$(this).attr('style')) return;
		$(this).attr('style', 
			$(this).attr('style')
			.replace(/margin\-left[^,]*/g,'')
			.replace(/margin\-top[^,]*/g,'')
		);
	});
	$('ul',this).each(function(i) {
		if(!$(this).attr('style')) return;
		$(this).attr('style', 
			$(this).attr('style')
			.replace(/[^-]height[^,]*/g,'')
		);
	});
	$(this).height('auto');
	this.unbind('DOMNodeInserted');
	this.unbind('DOMNodeRemoved');
	
	return this;
}

