(function($){

$(document).ready(function(){
  navigationDropdowns.init();
  sharingWidgets.init();
  embedDrop.init();
  accordianNav.init();

  // DLA: Initialize any videoPlayers in the page.
  videoPlayers.init();

  // TK: For custom fb/tweet buttons
  if ($('.custom-social').length != 0) {
    customShareCount.init();
  }
  
});

var customShareCount = new function() {
	this.init = function () {
		var share_url = $('.custom-social a.addthis_button_facebook').attr('addthis:url');
		if (share_url.indexOf('#') != -1) {
			share_url = share_url.substr(0, share_url.indexOf('#'));
		}

		// Call to Facebook API for Share Count
		try {
			$.getJSON('http://api.facebook.com/restserver.php?format=json&method=links.getStats&urls=' + encodeURIComponent(share_url) + '&callback=?',
				function(data) {
					$('div.custom-social.facebook span.number').text(data[0].total_count);
				}
			);
		} catch(e) { }

		// Call to Twitter API for Tweet/Retweet Count
		try {
			$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + encodeURIComponent(share_url) + '&callback=?',
				function(data) {
					$('div.custom-social.twitter span.number').text(data.count);
				}
			);
		} catch(e) { }
	}
};

var navigationDropdowns = new function() {
  this.init = function() {
    $('#nav li').hover(
      function () {
        $(this).addClass('hover');
        if ($(this).find('.nav-dropdown').length) {
          $(this).find('.nav-dropdown').show();
        }
      }, 
      function () {
        $(this).removeClass('hover');
        if ($(this).find('.nav-dropdown').length) {
          $(this).find('.nav-dropdown').hide();
        }
      }
    )
  }
};

var sharingWidgets = new function() {
  this.init = function() {
    $('#tools-share, .share').live('click', function(e) {
      e.preventDefault();
      if ($(this).next($('.share-dropdown')).is(':visible')) {
        $(this).next($('.share-dropdown')).hide();
      }
      else {
        $(this).next($('.share-dropdown')).show();
      }
    });
  }
};

var embedDrop = new function() {
  this.init = function() {
    $('.embed').live('click', function(e) {
      e.preventDefault();
      if ($(this).next($('.embed-dropdown')).is(':visible')) {
        $(this).next($('.embed-dropdown')).hide();
      }
      else {
        $(this).next($('.embed-dropdown')).show();
      }
    });
  }
};

var accordianNav = new function() {
  this.init = function() {
    $('nav.accordian ul li.nav').eq(0).hide();
    $('nav.accordian ul li.description').eq(0).show();
    this.observeClicks();
  };

  this.observeClicks = function() {
    $('nav.accordian li.nav a').live('click', function(e) {
      e.preventDefault();
      var thisNav = this;

      $('nav.accordian li.description:visible').slideUp('fast', function() {
        $('nav.accordian li.nav').show();

        // open what was clicked
        $(thisNav).closest('li').hide();
        $(thisNav).closest('li').next('li.description').slideDown('fast');
      });

    });
  };
};

var overlays = new function() {
  this.init = function() {
    $(".watch").colorbox({
      returnFocus: false,
      width:"967px", 
      // height: "214px",
      // top: "156px",
      inline:true, 
      scrolling: false,
      transition: "none",
      href:"#video-overlay"
    });
    $('.overlay-close').live('click', function(e) {
      e.preventDefault();
      $.colorbox.close();
    });
  }
};

// videoPlayers uses JCarousel to initialize any video player functionality
// in the page.  
var videoPlayers = new function() {
  this.init = function() {
      
      // Each video player will have the class 'videoPlayerContainer'
      // Each video will need initialized.
      jQuery('.videoPlayerContainer').each(function(index) {
	  
	  
	    var currentPlayerId = jQuery(this).attr("id");
	    var currentUid = jQuery(this).children('input.data:first').attr("value");
	    var jqCurrentPlayerId = "#" + currentPlayerId;
	    //alert("index=" + index + " " + currentPlayerId + " " + currentUid);
	    
	    // Begin Binding individual Player items.
	    jQuery(jqCurrentPlayerId + ' a.play-video-button').click(function(event) {

		// Clear any "current" list items.
		jQuery(jqCurrentPlayerId + ' li.more-video-li').removeClass("current");
		// Make the click item current.
		jQuery(this).parent("li").addClass("current");
		// Find the data.
		var vidDataElSelector = jQuery(this).attr("href");
		var vidDataArray = jQuery(vidDataElSelector).attr("value").split("|");
		//alert(jQuery(vidDataElSelector).attr("value"));
		//alert("Playing:" + vidDataArray[0] + " " + vidDataArray[1]);
		var iFrameSrc = vidDataArray[1] + '&autoplay=1';
		jQuery(jqCurrentPlayerId + ' .videoIFrame').attr("src",iFrameSrc);

		var audioUrl = vidDataArray[2];
		var transcriptUrl = 'var'
		var downloadUrl = vidDataArray[4];
		var embedUrl = vidDataArray[5];
		var shareUrl = vidDataArray[6];

		jQuery(jqCurrentPlayerId + ' a.videoAudioUrl').attr("href",audioUrl);
		jQuery(jqCurrentPlayerId + ' a.transcriptUrl').attr("href",transcriptUrl);
		jQuery(jqCurrentPlayerId + ' a.downloadUrl').attr("href",downloadUrl);
		jQuery(jqCurrentPlayerId + ' a.embedUrl').attr("href",embedUrl);
		jQuery(jqCurrentPlayerId + ' textarea#ytembed').val('<iframe width="560" height="315" src="' + embedUrl + '" frameborder="0" allowfullscreen></iframe>');
		jQuery(jqCurrentPlayerId + ' a.shareUrl').attr("href",shareUrl);
        jQuery(jqCurrentPlayerId + ' a.addthis_button_facebook,' + jqCurrentPlayerId + ' a.addthis_button_twitter').attr("addthis:url",shareUrl);

            // Call to Facebook API for Share Count
            try {
                $.getJSON('http://api.facebook.com/restserver.php?format=json&method=links.getStats&urls=' + encodeURIComponent(shareUrl) + '&callback=?',
                    function(data) {
                        $('div.custom-social.facebook span.number').text(data[0].total_count);
                    }
                );
            } catch(e) { }

            // Call to Twitter API for Tweet/Retweet Count
            try {
                $.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + encodeURIComponent(shareUrl) + '&callback=?',
                    function(data) {
                        $('div.custom-social.twitter span.number').text(data.count);
                    }
                );
            } catch(e) { }


		// Hide any sharing links that don't have targets
		jQuery(jqCurrentPlayerId + ' div.social div.sharing a[href="#"]').each(function(i){
		    if (jQuery(this).attr("href") == "#") {
			jQuery(this).addClass("hidden");
		    }
		    else
		    {
			jQuery(this).removeClass("hidden");
		    }

		});

		event.preventDefault();
	    });

		// Hide any sharing links that don't have targets
		jQuery(jqCurrentPlayerId + ' div.social div.sharing a[href="#"]').each(function(i){
		    if (jQuery(this).attr("href") == "#") {
			jQuery(this).addClass("hidden");
		    }
		    else
		    {
			jQuery(this).removeClass("hidden");
		    }

		});


	    jQuery(jqCurrentPlayerId + ' .more-videos-carousel').jcarousel({
		scroll: 1,
		initCallback: function(carousel,state) {
		    vidcarousel_initCallback(carousel, state, 'more-videos-carousel_' + currentUid, currentPlayerId, currentUid);
		},
		// This tells jCarousel NOT to autobuild prev/next buttons
		buttonNextHTML: null,
		buttonPrevHTML: null,
		visible: 3
	    });
	
	    // End bind invididual player items.
      });
      
      // Bind all video and audio objects in any video container.
	jQuery(".videoPlayerContainer .video object").bind("click",videoClick);
	jQuery(".videoPlayerContainer .video .vid-high object").bind("click",videoClickHighlights);
	jQuery(".videoPlayerContainer .video .vid-full object").bind("click",videoClickFull);
	jQuery(".videoPlayerContainer .audio object").bind("click",audioClick);

      
  }
};

})(jQuery);

// This is a jcarousel video callback.
function vidcarousel_initCallback(carousel, state, carouselId, containerId, dataId) {
    
    jQuery('#' + containerId + ' .jcarousel-control a').bind('click', function() {
	carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
	alert('implement click');
	return false;
    });

    jQuery('#' + containerId + ' .jcarousel-scroll select').bind('change', function() {
	carousel.options.scroll = jQuery.jcarousel.intval(this.options[this.selectedIndex].value);
	alert('implement change');
	return false;
    });

    // Bind any video carousels to click.
    jQuery('#' + containerId + ' .more-videos-carousel-next').bind('click', function() {
	//alert(carousel.first + ' ' + carousel.last + ' ' + carousel.options.size);
	// Only move if the last item is not equal to the size.
	if (carousel.last < carousel.options.size) {
	    carousel.next();	
	}
	return false;
    });

    // Bind any object with an id that contains videos-carousel-prev to a previous function.
    jQuery('#' + containerId + ' .more-videos-carousel-prev').bind('click', function() {
	// Only move if the carousel is not at the beginning.
	if (carousel.first > 1) {
	    carousel.prev();
	}
	//alert(carousel.first + ' ' + carousel.last + ' ' + carousel.options.size);
	
	return false;
    });
    

};



// This is a standard jcarousel init Callback
function jcarousel_initCallback(carousel, state, carouselId) {
    
    if (carousel.first == 1) {
	jQuery('.' + carouselId + '-prev').addClass('inactive')
    }
    if (carousel.last == carousel.options.size) {
	jQuery('.' + carouselId + '-next').addClass('inactive')
    }
    
    jQuery('.' + carouselId + '-next').bind('click', function() {
	// Only move if the last item is not equal to the size.
	if (carousel.last < carousel.options.size) {
	    carousel.next();	
	}
	   
	if (carousel.last == carousel.options.size) {
	    jQuery('.' + carouselId + '-next').addClass('inactive');
	}
	else {
	    jQuery('.' + carouselId + '-next').removeClass('inactive');
	}
	if (carousel.first == 1) {
	    jQuery('.' + carouselId + '-prev').addClass('inactive');
	}
	else {
	    jQuery('.' + carouselId + '-prev').removeClass('inactive');
	}
    
	
	
	return false;
    });

    jQuery('.' + carouselId + '-prev').bind('click', function() {
	// Only move if the carousel is not at the beginning.
	if (carousel.first > 1) {
	    carousel.prev();
	}

	if (carousel.last == carousel.options.size) {
	    jQuery('.' + carouselId + '-next').addClass('inactive');
	}
	else {
	    jQuery('.' + carouselId + '-next').removeClass('inactive');
	}
	if (carousel.first == 1) {
	    jQuery('.' + carouselId + '-prev').addClass('inactive');
	}
	else {
	    jQuery('.' + carouselId + '-prev').removeClass('inactive');
	}
    

	return false;
    });
    

}

