// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function thisMovie(swf) {
  if(navigator.appName.indexOf("Microsoft") != -1) {
    return window[swf];
  } else {
    return document[swf];
  }
};


jQuery.fn.ohSnap = function (opt) {

  $(this).each( function() {
    jQuery("<img>")
      .addClass("ohSnap")
      .insertAfter(this)
      .attr( { src: "http://images.websnapr.com/?size=S&key=6JZK1LdaMi98&url=" + jQuery(this).attr("href") } );
  });
}

// Extend jquery to make visible/hidden selectors work for both visibility and display none,
//  as well as text selector to apply to both text inputs and textareas.
jQuery.extend(jQuery.expr[":"], {
  text    : "(a.tagName=='INPUT' && a.type=='text') || (a.tagName=='TEXTAREA')",
  visible : '"hidden"!=a.type && jQuery.css(a,"display")!="none" && jQuery.css(a,"visibility")!="hidden" && (jQuery(a).parent(":hidden").size() == 0)',
  hidden  : 'document != a && ("hidden"==a.type || jQuery.css(a,"display")=="none" || jQuery.css(a,"visibility")=="hidden" || (jQuery(a).parent(":hidden").size() > 0))'
});

jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} 
})

jQuery.fn.collapseList = function(settings) {
  // if no paramaters supplied...
  		settings = jQuery.extend({
  			collapseAfter: 5
  		}, settings);
  
  
  $j(this).after("<p class=\"collapse_buttons\"><a href=\"#\" class=\"show_all_message\">more...</a> <a href=\"#\" class=\"show_recent_only\">...less</a></p>")
  var size = settings.collapseAfter;
  var more_link = $j(this).parent().find(".show_all_message");
  var list = $j(this).children("li");
  if (list == null || list.length <= size)
  {
    more_link.hide();
  }
  else
  {
    more_link.prepend("and " + (list.length - size) + " ")
    
    // hide li after the 5th
    $j(this).children("li:gt(" + (size - 1) + ")").hide();
    
    $j(this).parent().find(".show_all_message").click(function(){
      $j(this).hide();
      $j(this).siblings(".show_recent_only").show();
      $j(this).parent().parent().find(".collapsible_list li:gt(" + (size - 1) + ")").slideDown();
      return false;
    });
    
    $j(this).parent().find(".show_recent_only").click(function(){
      $j(this).hide();
      $j(this).siblings(".show_all_message").show();
      $j(this).parent().parent().find(".collapsible_list li:gt(" + (size - 1) + ")").slideUp();
      return false;
    });
  }
}

jQuery.fn.vjustify=function() {
    var maxHeight=0;
    this.each(function(){
        if (this.offsetHeight>maxHeight) {maxHeight=this.offsetHeight;}
    });
    this.each(function(){
        jQuery(this).height(maxHeight + "px");
        if (this.offsetHeight>maxHeight) {
            jQuery(this).height((maxHeight-(this.offsetHeight-maxHeight))+"px");
        }
    });
};
 
jQuery.fn.equalizeCols = function() {
  jQuery(this).filter(function() {return jQuery(this).find(".auto_fill").length == 0;}).each(function() {
    jQuery(this).append(jQuery("<div class='auto_fill'></div>").height(0));
    }).css("height", "auto");

    var max_height= 0;
    jQuery(this).each(function() {
      var self= jQuery(this);
      var height= self.height() - self.find(".auto_fill").height();
      max_height=height > max_height ? height : max_height;
    });

    jQuery(this).each(function() {
      var self= jQuery(this);
      var height= self.height() - self.find(".auto_fill").height();
      self.find(".auto_fill").height(max_height - height);
    });
  }

// Use jQuery via $j(...)
var $j = jQuery.noConflict();


////
// Behaviors
$j(document).ready(function() {
  
  $j(".corner").corner();
  $j(".button").corner({
    tr: {radius: 4},
    tl: {radius: 4},
    bl: {radius: 4},
    br: {radius: 4}});
  
  $j("#hd").corner({tr: false, tl: false, autoPad: false});
  $j("#ft").corner({bl: false, br: false, autoPad: false});

  ////
  // Initialize flashbased audio players
  $j(".player").livequery(function(i){
    var link = $j(this).find("a")[0];
    var bg = ($j(this).parents('tr').hasClass('odd') ? '0xffffff' : '0xe9e9e9');
    var fid = this.id.split('-')[1]
    flashembed(this.id, {
       id:'flash-' + fid,
         src:'/swf/FlowPlayerDark.swf',
         width:'95%', 
         height:23,
         wmode:'transparent'
       },
       { config: {  
         autoPlay: false,
         autoBuffering: false,
         playList: [{ url: $j(link).attr("href") }],
         initialScale: 'fit', 
         useNativeFullScreen: false,
         showPlayButton: false,
         showFullScreenButton: false,
         showMenu: false,
         showVolumeSlider: false,
         controlBarBackgroundColor: bg,
         controlBarGloss: 'none',
         timeDisplayFontColor: '0x000000'
       }} 
      );
      
      $j(link).hide();
  });
  
  ////
  // initialize list view
  $j('.sermon_details_entry').removeClass('hide');

  
  $j('#sermon_list').Accordion({ 
      header: '.sermon_list_entry', 
      navigation: false, 
      event: 'click', 
      autoheight: false, 
      animated: false
  }).change(function(event, newHeader, oldHeader, newContent, oldContent) {
        if (/.*Loading\.\.\..*/.test(newContent.text())) {
          var sermon_id = newContent[0].id.split('_')[3]
          jQuery('#' + newContent[0].id).load('sermons/' + sermon_id)
        } 
  });
  
  $j('#sermon_list').activate(0);
  
  ////
  // Add ajaxiness to a few links
  $j("a[id^=play-]").hover(function() {
    var src = $j(this).children('img').attr('src');
    if (/play_old\.png.*$/.test(src))
    { 
    $j(this).children('img').attr('src', "/images/play_old_active.png");
      }
    else if (/pause_old_active\.png.*$/.test(src))
    {
     $j(this).children('img').attr('src', "/images/pause_old.png");
    }
  }, function() {
    var src = $j(this).children('img').attr('src');
    if (/play_old_active\.png.*$/.test(src))
    { 
    $j(this).children('img').attr('src', "/images/play_old.png");
      }
    else if (/pause_old\.png.*$/.test(src))
    {
     $j(this).children('img').attr('src', "/images/pause_old_active.png");
    } 
  });
  
  if ($j("#filters").length > 0) {
    $j("#filters").each(function() {
      var last = $j.cookie('last_filter');
      if (last == null || !/^.*_filter$/.match(last)) {
        $j(this).load('/series_filter/');
      }
      else {
        if (/^.*series_filter$/.match(last)) {
          $j(this).load('/series_filter',{},function(){
            $j("#sidebar, #content").equalizeCols();
          });
        }
        else if (/^.*speakers_filter$/.match(last)){
          $j(this).load('/speakers_filter',{},function(){
            $j("#sidebar, #content").equalizeCols();
          });
        }
        else if (/^.*tags_filter$/.match(last)){
          $j(this).load('/tags_filter',{},function(){
            $j("#sidebar, #content").equalizeCols();
          });
        }
      }
    });
  }

  $j("#filters #filters_menu a").livequery('click', function() {
    var url = $j(this)[0].href
    $j("#filters").load(url,{},function(){
        $j("#sidebar, #content").equalizeCols();
      });
    $j.cookie('last_filter', url)
    return false;
  });
  
  ////
  // add hotkeys
  if ($j.hotkeys)
  {
    // j - next sermon entry
    $j.hotkeys.add('j', {type:'keypress'}, function(){  
          var index = $j('#sermon_list .sermon_list_entry').index($j('.selected')[0]);  
      $j('#sermon_list').activate(index + 1);
    });
  
    // k - previous sermon entry
    $j.hotkeys.add('k', {type:'keypress'}, function(){  
          var index = $j('#sermon_list .sermon_list_entry').index($j('.selected')[0]);
      $j('#sermon_list').activate(index - 1);
    });
    
    // v - open sermon entry in new window
    $j.hotkeys.add('v', {type:'keypress'}, function(){  
          var href = $j('.selected a')[0].href;
      window.open(href);
    });
  }
  
  // Uncomment when channels feature is ready.
  // $j("#channel_selection a, #channel_selection img").bind('click keypress', function(event) {
  //     var code=event.charCode || event.keyCode;
  //     if(!code || (code && code == 13)) {// if no key code (mouse) or if enter is pressed
  //    event.preventDefault(); //prevent browser from following the actual href
  //         $j("#channels_container").toggle();
  //     }
  // });
  
  $j("a#subscribe_by_email").bind('click keypress', function(event) {
      var code=event.charCode || event.keyCode;
      if(!code || (code && code == 13)) {// if no key code (mouse) or if enter is pressed
      event.preventDefault(); //prevent browser from following the actual href
          $j("#email_subscribe").toggle();
      }
  }); 
  
  $j("a#filter_toggle_link").bind('click keypress', function(event) {
      var code=event.charCode || event.keyCode;
      if(!code || (code && code == 13)) {// if no key code (mouse) or if enter is pressed
      event.preventDefault(); //prevent browser from following the actual href
          $j("#filters_container").toggle();
      $j(".flash").toggle();
      }
  });   
  
  $j(".autoTooltip").tooltip({
    track: true,
    delay: 0,
    showURL: false,
    opacity: 1,
    fixPNG: true,
    showBody: " - ",
    extraClass: "pretty fancy",
    top: 15,
    left: -15
  });
  
  
  $j("a[id^=play-]").bind('click keypress', function(event) {
      var code=event.charCode || event.keyCode;
      if(!code || (code && code == 13)) {// if no key code (mouse) or if enter is pressed
      event.preventDefault(); //prevent browser from following the actual href
      var player = $j("#" + this.id + '-container > :first')[0];
      var isPlaying = player.getIsPlaying();
      var isPaused = player.getIsPaused();
      if (isPlaying && !isPaused)
      { 
        player.Pause();
        $j(this).children('img').attr('src', "/images/play_old.png");
        $j(this).parent().children('span').html('play');          
      }
      else
      {
        player.DoPlay();
        $j(this).children('img').attr('src', "/images/pause_old_active.png");
        $j(this).parent().children('span').html('pause');
      }
      }
  });
  
  // Handle links inside iframe-based widgets
  $j("#widget #channel_name #channel_selection a, #widget .show_description a,#widget #tag_filter a,#widget #speaker_filter a,#widget #series_filter a,#widget .series a,#widget .account a, #widget .speaker a,#widget .tag_list a,#widget #view_tabs li a").each(function() {
    var link = $j(this).attr('href');
    var w = $j("#sermon_details_container").width();
    var size = (w > 575 ? "large" : "medium")
    if (/.*\?.*/.match(link))
    {
      $j(this).attr('href', link + "&format=widget&s=" + size);
    }
    else
    {
      $j(this).attr('href', link + ".widget?s=" + size);
    }
  });
  
  $j("a[rel='external']").click(function() {
    $j(this).attr('target', '_blank');
  });
  
  ////
  // Collapsible lists
  $j("#related_sermons .collapsible_list").livequery(function() {
    $j(this).collapseList({collapseAfter: 5});
  });
  
  $j("#filters .collapsible_list").livequery(function() {
    $j(this).collapseList({collapseAfter: 8})
  });
  
  $j("#filters #tag_filter ul").livequery(function() {
    $j(this).collapseList({collapseAfter: 20})
  });


  ////
  // Sermon artwork form
  $j("input[name='sermon[artwork_type]']").click(function() {
    var value = $j(this).attr('value');
    $j.post('update_sermon_artwork_type/' + value);
  });
  
  $j(".artwork_option div[id$=image_uploader] a").click(function() {
    $j(this).parents(".artwork_option").find("input[name='sermon[artwork_type]']").click();
  });
  
  
  ////
  // $j("input").Watermark("Enter something")
  
  ////
  // Facebox
  $j('a[rel*=facebox]').facebox();
  
  ////
  // hide links
  $j("a.hide_it").livequery('click', function() {
    rel = $j(this).attr("rel")
    $j(rel).fadeOut();
  });


  ////
  // Edit sermon combo boxes.
  $j("input[id='speaker_name']").each(function(i, textbox){
    $j.getJSON('/speakers', function(data) {
      var speakers = data;

      $j(textbox).autocomplete(speakers, {
      	matchContains: true,
      	minChars: 0,
      	width: 258,
      	formatItem: function(data, i, n, value) {
    			return data.name;
    		}
      });
    });
    
    $j(textbox).blur(function() {
      $j(textbox).after("<span id=\"loading_" + textbox.id + "\" style=\"padding-left: 10px\"><img src=\"/images/spinner_moz.gif\"/>&nbsp;Updating...</span>");
      $j.post('speaker', { speaker: textbox.value }, null, 'json');
      $j("#sermon_artwork").load('sermon_artwork/edit')
      $j("#loading_" + textbox.id).fadeOut(2000);
      $j(textbox).effect("highlight", {}, 2000);
    });
  });
  

  $j("input[id='series_title']").each(function(i, textbox){
    // if (textbox.value != "") {
    //   $j(textbox).hide().after("<p>" + textbox.value + "&nbsp;&nbsp;<a href=''>change</a></p>")
    // }
    
    $j.getJSON('/series', function(data) {
      var series = data;

      $j(textbox).autocomplete(series, {
      	matchContains: true,
      	minChars: 0,
      	width: 258,
      	formatItem: function(data, i, n, value) {
    			return data.title;
    		}
      });
    });
    
    $j(textbox).blur(function() {
      $j(textbox).after("<span id=\"loading_" + textbox.id + "\" style=\"padding-left: 10px\"><img src=\"/images/spinner_moz.gif\"/>&nbsp;Updating...</span>");
      $j.post('series', { series: textbox.value }, null, 'json');
      $j("#sermon_artwork").load('sermon_artwork/edit')
      $j("#loading_" + textbox.id).fadeOut(2000);
      $j(textbox).effect("highlight", {}, 2000);
    });
  });
  
  
  // $j('#title input, #sermon_fieldset input, #sermon_fieldset textarea, #sermon_fieldset select').focus(function(){
  //     $j(this).parents('p').addClass("over");
  // }).blur(function(){
  //     $j(this).parents('p').removeClass("over");
  // });
  
  ////
  // Sparklines
  $j('.sparkline').sparkline('html', { type:'line', height:'30px', width:'40px' });
  
  
  ////
  // Widgets
  $j('.widget-image').hover(function(){
		$j(this).addClass('hover');
	}, function() {
		$j(this).removeClass('hover');
		});
		
	$j("div[id$='-widget-selector']").click(function(){
	  $j(".widget-image-selected").removeClass('widget-image-selected');
	  $j(this).addClass('widget-image-selected');
	  var type = this.id.split('-')[0]
	  $j("#widget-wizard").load('widgets/' + type + '_wizard');
	});
  
});
