// no conflicts with other frameworks
var $j = jQuery;

$(document).ready(function() {
  setupClassFormDropdownSubmit();
  setupLinkFormSubmit();
  setupSearch();
  setupShareThisPopup();
  setupShareLink();
  setupSelectUrlChange();
  setupSermonSeriesCarousel();
  setupSearchListingInput();
  setupNewCaptchaImage();
  setupTabify();
  setupJplayer();

  $j("a[rel^='prettyPhoto']").prettyPhoto({theme:'dark_rounded'});
  $j("a[rel^='popShareThis']").prettyPopin({width:462});
  $j("a[rel^='popLyrics']").prettyPopin({width:500});
   
  //Handler to switch ministries quickly from the Ministry dropdown
  $j('.ministry-dropdown').change(function(){
    window.location = $('select.ministry-dropdown').val();
  });

  // For truncating video descriptions
  $j('.truncatable').truncatable({limit: 350, more: ' &hellip; read more', less: true, hideText: '<br /><br />hide'});
  $j('.truncatableServe').truncatable({limit: 96, more: ' &hellip;', less: true, hideText: '<br /><br />hide'});
});

function setupJplayer(){
  //loop through each track div player and initialize the jPlayer
   $("div.player_container").each(function () {
    var $track_file = $(this).attr('title');
    var $player_id = $(this).attr('id');
    var $jp_interface_id = $(this).attr('rel');
   
    $("#" + $player_id).jPlayer({
      ready: function () {
        $("#" + $player_id).jPlayer("setMedia", {mp3: $track_file})
      },
      swfPath: "/views/site/js/jquery/jplayer",
      solution: "flash, html",
      supplied: "mp3",
      cssSelectorAncestor: "#jp_interface_" + $jp_interface_id
    })
    .bind($.jPlayer.event.play, function() { // Using a jPlayer event to avoid both jPlayers playing together.
      $("#" + $player_id).jPlayer("pauseOthers");
      $("#" + $player_id).jPlayer("play", 0);
    });
  });
}

function setupClassFormDropdownSubmit(){
  //submit the lass search form when the filter field is selected
  $j('.filter_general').change(function(){
    $j(this).closest("form").submit();
  });
  //submit the form when the filter field value is selected
  $j('.filter_detail').change(function(){
    $j(this).closest("form").submit();
  });
  $j('.btn_search_clear').click(function(){
    $j('.search_clear').val('');
  });
}

function setupLinkFormSubmit(){

  $('.quick_search').click(function() {
    $(this).closest("form").submit();
  });

}

function setupTabify(){
	$j('.scroll-pane-media').show().jScrollPane({autoReinitialise: true,verticalGutter: 20});
	$j('.video_description').show().jScrollPane({autoReinitialise: true});
	$j('.live_info_menu').tabify();
	$j('.scroll-pane').show().jScrollPane({autoReinitialise: true});
	$j('.live_notes').show().jScrollPane({autoReinitialise: true});
	$j('.chat_box').show().jScrollPane({autoReinitialise: true});
	$j('#iframeBible').show().jScrollPane({autoReinitialise: true});
	$j('.live_tabs').tabify();
	$j('.note_options').tabify();
	$j('.elastic').elastic();
	$j('.infield').inFieldLabels();
	$j('#alphabet').listnav();
}

function setupSearch(){
  // This script is to clear the search input field for searches
  $j('.search_clear').click(function() {
    return;
    if (this.value == this.defaultValue) {
      this.value = '';
    }
  });

  $j('.search_clear').blur(function() {
    return;
    if (this.value == '') {
      this.value = this.defaultValue;
    }
  });
}


function setupShareLink(){
  //Media items
  //Hide the link input field
  $('.video_permalink').hide();
  //When the link button is pressed show/hide the input box to copy and paste
  //the video URL
  $('.link_input_toggle').click(function(){
    //hide the social share box
    $('.sharethis_box').hide();
    //toggle the input section
    $('.video_permalink').toggle('fast');

  });

  $('.video_permalink_close').click(function(){
    $('.video_permalink').slideUp('fast');
  });

  //click outside the share box, hide it
  //todo implement
}

/**
 * Add click handles to buttons that need to display the Share This popup div
 * and handle click for closing that popup, etc.
 */
function setupShareThisPopup() {
  //Social Elements
  $j('.sharethis_box').hide();
  $j('.sharethis_email').hide();
  $j('.divConfirm').hide();

  //Share this dialog
  $j('#social_share, #vs_share, #footerShare').click(function(e){
    e.preventDefault();

    //display the Share This div as a modal dialog with a darkened overlay above the rest of the page
    //to make the div stand out a bit more
    $j('#cmgShareThis').modal({
      opacity: 70,
      overlayCss: { backgroundColor:"#000" },
      onOpen: function(dialog) {
        dialog.overlay.fadeIn('fast', function() {
          dialog.data.hide();
          dialog.container.show();
          dialog.data.slideDown('fast');
        });
      }
    });
  });

  //Close button
  $j('#btn_sharethis_close').click(function(e){
    e.preventDefault();

    //close/hide the Share This div
    $.modal.close();
  });
}

/**
 * Setup the action that loads the page requested from the dropdown select menu
 */
function setupSelectUrlChange(){
  $('.url-select').change(function() {
    document.location.href = $(this).val();
  });
}

/**
 * Setup the jCarousel that is used on the media landing page to show the
 * various series items.
 */
function setupSermonSeriesCarousel() {
  $j('#seriesCarousel').jcarousel({
    scroll: 4,
    wrap: "both",
    initCallback: function(carousel) {
      $j('.series_carousel_btn_next').bind('click', function() {
        carousel.next();
        return false;
      });
      $j('.series_carousel_btn_prev').bind('click', function() {
        carousel.prev();
        return false;
      });
    },
    buttonNextHTML: null,
    buttonPrevHTML: null
  });
}

/**
 * Setup click handlers and such for the search input that is used on listing pages
 * that lets the user click the (X) to clear out the input
 */
function setupSearchListingInput() {
  //If there's an "Advanced Search" anchor then hook up the click event so it
  //will slide down the div with advanced search inputs
  $j('#jsAdvSearchToggle').click(function(e) {
    e.preventDefault();
    $j('#divAdvanced').slideToggle();
  });

  //After a key is pressed if the input is empty remove the (X) image link that's
  //used to clear out the input's contents since it's not needed.
  $j('#keyword').keyup(function() {
    $j('a.btn_search_clear').toggle(this.value != '');
  });

  //Show or hide the <a> that has the (X) close icon when the page first loads
  if ($j('#keyword').val() == '') {
    $j('.btn_search_clear').hide();
  }
  else {
    $j('.btn_search_clear').show();
  }
}
/**
 * Setup the click event for requesting a new captcha image
 */
function setupNewCaptchaImage(){
   //Load a different captcha image
  $('#refresh-captcha').click(function() {
    var image = $("#captcha_image");
    var d = new Date();
    //need to append a new time as a parameter to the end of the URL so we
    //can ensure it will not try to load a cached image
    var tokenDeCacher = d.getTime();
    //create the base url and parameters respectively
    var urlTokens = image.attr("src").split('?');
    var urlString = ""
    if (urlTokens.length == 1){
      urlString = urlTokens[0] + '?' + tokenDeCacher;
      alert(urlString);
      image.attr("src", urlTokens[0] + '?' + tokenDeCacher);
      return false;
    }
    //create an array of all the url parameters
    var urlParameters = urlTokens[1].split('&');
    //replace the last parameter with the new time token
    urlParameters[urlParameters.length-1] = tokenDeCacher;
    //create the parameter string
    var urlParams = "";
    //loop through each element in the parameter array building the string
    $.each( urlParameters,
        function( intIndex, objValue ){
          //Make sure there is a valid key=value item
          if (objValue != ""){
            urlParams = urlParams + "&" + objValue;
          }
        }
       );
    //put it all together to create the url string for the captcha.php file
    urlString = urlTokens[0] + '?' + urlParams;
    image.attr("src", urlString);

    return false;
  })
}

