
function activateLiveSearchCounter() {
  searchForm.find(':input').change(countResults);
}

function countResults() {
  if(searchForm.length) {
    $.post('/teachings/searches/count_results', searchForm.serialize(), handleLiveSearchCounterResult);
  }
};

function handleLiveSearchCounterResult(count) {
  var resultCount = $('.result-count');
  resultCount.text(count)
  if(parseInt(count)) {
    resultCount
      .animate({ color: '#00CC33' }, 300)
		  .animate({ color: 'white' }, 300);
    searchForm.find('input[type=submit]').removeAttr('disabled');
  } else {
    resultCount.animate({ color: 'red' }, 300);
    searchForm.find('input[type=submit]').attr('disabled', 'disabled');
  }
}

function activateContactUsLink() {
  $('a[href=#footer]').click(function(){
    $.scrollTo('#footer', 800, {easing:'easeout'});
    $('#lighthouse')
      .animate({ backgroundColor: '#E5E15C' }, 500)
  	  .animate({ backgroundColor: '#111111' }, 500);
  	return false;
  });
}

function activatePlayButtons() {
  $('#results .teaching').each(function(){
    var teaching = $(this);
    
    // AUDIO
    var downloadAudioButton = teaching.find('.download-audio');
    // Insert the 'play audio' button
    var playAudioButton = downloadAudioButton.after('<li><a href="#" class="audio">play<br/>audio</a></li>').next();
    // Add a click event to the 'play audio' button
    playAudioButton.click(function(){
      playAudioFile(teaching);
      $(this).remove();
      return false;
    });

    // VIDEO
    var downloadVideoButton = teaching.find('.download-video');
    
    if (downloadVideoButton) {
      // Insert the 'play video' button
      var videoPlayerDivId = 'video-player-'+teaching.attr('id');
      var playVideoButton = downloadVideoButton.after('<li><a href="#'+videoPlayerDivId+'-wrapper" class="video">play<br/>video</a></li>').next().find('a');
  
      $(playVideoButton).click(function(event){
        $(this).unbind();
        embedVideoFile(teaching);
        $(this).fancyZoom({ edgy: true, height : 357, width : 635 });
        $(this).trigger('click', event);
        return false;
      });
      
    }
  });
}

function playAudioFile(teaching) {
  // Insert the list element for the audio player
  var audioPlayerListItemId = 'audio-player-'+teaching.attr('id');
  teaching.after('<li class="audio-player"><div id="'+audioPlayerListItemId+'"><p>You need to install the latest Flash player to play this audio. Please download it <a href="http://www.adobe.com/go/gntray_dl_getflashplayer">here</a>.</p></div></li>');
  
  // Create the SWF Object and embed the Flash file
  var audioFileUrl = teaching.find('.download-audio a').attr('href');
  swfobject.embedSWF('/audio-player.swf', audioPlayerListItemId, '897', '34', '9.0.0', false, { mediaFile : audioFileUrl });
}

function embedVideoFile(teaching) {
  var videoPlayerDivId = 'video-player-'+teaching.attr('id');
  
  // Insert the player
  teaching.append('<div id="'+videoPlayerDivId+'-wrapper"><div id="'+videoPlayerDivId+'"><p>You need to install the latest Flash player to play this video. Please download it <a href="http://www.adobe.com/go/gntray_dl_getflashplayer">here</a>.</p></div></div>');
  var videoFileUrl = teaching.find('.download-video a').attr('href');
  swfobject.embedSWF('/jwplayer.swf', videoPlayerDivId, '635', '357', '9.0.0', false, {
    autostart : true,
    controlbar : 'over',
    file : videoFileUrl,
    image: '/images/lighthouse-video.png',
    skin : '/overlay.swf'
  }, { allowfullscreen : true });

}

function activateDateHintToggler() {
  $('#search_date_to').change(toggleDateHint);
}

function toggleDateHint(show) {
  if(!$('span.to').length && $('span.from')) {
    $('span.from').after('<span class="to">Dec 31</span>');
  }
  if($('#search_date_to').val() == '3000') {
    $('span.to').fadeOut('fast');
  } else {
    $('span.to').fadeIn('fast');
  }
}

function maskLongTeachingTitles() {
  var allTeachings = $('#teachings ol li');
  allTeachings.filter('.odd').append('<img src="/images/long-title-mask-odd.png" class="title-mask" />');
  allTeachings.filter('.even').append('<img src="/images/long-title-mask-even.png" class="title-mask" />');
}

function addTitleToLongTeachingTitles() {
  $('#teachings li a').each(function(){
    var link = $(this);
    if(link.text().length > 45) {
      link.attr('title', link.text());
    };
  });
}

function activateHomePageRotator() {
  $("#secondary-images").jCarouselLite({
    speed:1000,
    vertical: true
  });
  
  var first = true;
  
  var advanceSecondary = function() {
    if(!first) {
      jQuery.fn.jCarouselLite.next();
    } else {
      first = false;
    }
  }
  
  $('#primary-images').cycle({
    before:    advanceSecondary,
    fx:        'fade',
    hoverTarget: '#primary-images, #secondary-images',
    pause: true,
    slideExpr: 'li',
    speed: 1000,
    timeout:   6500
  });
  
  
  
}

var CufonProxy = {
  replace : function(selector) {
    $(selector).addClass('pre-cufon');
    Cufon.replace(selector);
  }
}

var searchForm;
$(document).ready(function(){
  
  activatePlayButtons();
  
  // ============================
  // = Search Teachings Archive =
  // ============================
  searchForm = $('#new_search');
  activateLiveSearchCounter();
  countResults();
  toggleDateHint();
  activateDateHintToggler();
  // ========
  // = Home =
  // ========
  maskLongTeachingTitles();
  addTitleToLongTeachingTitles();
  // ==============
  // = Contact Us =
  // ==============
  activateContactUsLink();
  // =========
  // = Cufon =
  // =========
  // CufonProxy.replace('#navigation a');
});

$(window).load(function(){
  activateHomePageRotator();
});