MyPlayer = Player.getPlayerById("player0");


EVERYZING = EVERYZING || {};
EVERYZING.util = EVERYZING.util || {};
EVERYZING.playerControls = EVERYZING.playerControls || {};

EVERYZING.jQuery = jQuery;

jQuery(document).ready(function(){ 
	jQuery("#fullTextLink").bind("click", function(){ EVERYZING.playerControls.openTranscript(); })
});

// Collect full transcript text
var fullTranscriptText = "";
// actual clipping function
EVERYZING.clipText = function(obj,maxLen) {
	fullTranscriptText = obj.innerHTML;
	jQuery(obj).truncate(maxLen, {
        chars: / /,
        leave: false,
        trail: [true, "...\"", ""]
    });
}

EVERYZING.truncate_to = function(target, maxLen){
    maxLen = parseInt(maxLen);
    if (isNaN(maxLen) || maxLen <= 0){ return; }    
    var target = EVERYZING.jQuery(target);    
    target.each(function(){
		EVERYZING.clipText(this,maxLen);
    });
};

// display or clip full transcript on media lander
EVERYZING.displayTranscript = function(tObj, tBtn, tClipLength) {
	tObj = document.getElementById(tObj);
	tBtn = document.getElementById(tBtn);
	if (tBtn.innerHTML == "+") { // expand
		//tObj.innerHTML = fullTranscriptText;
		tObj.className = "ez-full";
		tBtn.innerHTML = "-";
	} else { // clip
		//EVERYZING.clipText(tObj, tClipLength);
		tObj.className = "ez-clipped";
		tBtn.innerHTML = "+";
	}
}

EVERYZING.util.Logger = function (message){
  if(window.console) console.log(message)
  else alert(message);
}

EVERYZING.playerControls.jumpPlayerTo = function(time){
	playerInst0.seek(time);
}

// opens up full transcript in popup
EVERYZING.playerControls.openTranscript = function(){
	var pWidth = 520; // width of popup
	var pHeight = 520; // width of popup
	var leftPos = screen.width - pWidth - 100; // 100px from right of screen
	var topPos = (screen.height - pHeight)/2; // vertically centered
	var win = window.open(location.href.replace("/m/", "/transcript/"), "Transcript", "left=" + leftPos + ",top=" + topPos + ",width=" + pWidth + ",height=" + pHeight + ",resizable,scrollbars");
}

//Overriding default pathways to objects
// Called from Flash when new media loaded (e.g., continuous play, highlights reel)
function setEzMediaTitle(value){
	jQuery(".ez-mediaMain h1").attr("title", value);
	jQuery(".ez-mediaMain h1 .ez-media-info-title").text(value);
    EVERYZING.playerMod_title_trunc(ezplayer_config.ezMaxTitleLength);
}

function setEzMediaPubDate(value){
	jQuery(".ez-mediaMain p .featured-ep-pub-date").text(value);
}

function setEzMediaDescription(value){
	jQuery(".ez-mediaMain p .ez-playerMod-episode-description").text(value);
}

// When the "lander" video is finished, remove the full transcript because it's
// no longer relevant. (We may, in future, refresh the text via Ajax or whatever.)
function removeFullTextTranscript() {
	jQuery("#fullTranscript").hide();
	jQuery("#fullTranscriptLink").hide();
}



// HTML Truncator for jQuery
// by Henrik Nyh <http://henrik.nyh.se> 2008-02-28.
// Free to modify and redistribute with credit.
// (amh: added to support maintaining markup in truncated text)
(function($) {

  var trailing_whitespace = true;

 jQuery.fn.truncateMe = function(options) {

    var opts = $.extend({}, jQuery.fn.truncateMe.defaults, options);
    
    $(this).each(function() {

      var content_length = $.trim(squeeze($(this).text())).length;
      if (content_length <= opts.max_length)
        return;  // bail early if not overlong

      var actual_max_length = opts.max_length - opts.more.length - 3;  // 3 for " ()"    
      var truncated_node = recursivelyTruncate(this, actual_max_length);
      var full_node = $(this);

      truncated_node.insertAfter(full_node);
      // This is an ugly approximation for getting the last block tag:
      // we just pick the last <p> or else the container itself.
      truncated_node.find('p:last').add(truncated_node).eq(0).
        append(' <a href="#show more content" class="ez-snippet-more">'+opts.more+'</a>');

      full_node.hide();
      full_node.find('p:last').add(full_node).eq(0).
        append(' <a href="#show less content" class="ez-snippet-less">'+opts.less+'</a>');

      truncated_node.find('a:last').click(function() {
        truncated_node.hide(); full_node.show(); return false;
      });
      full_node.find('a:last').click(function() {
        truncated_node.show(); full_node.hide(); return false;
      });

    });
  }

  // Note that the "more" link and its wrapping counts towards the max length:
  // so "more" and a max length of 10 might give "123 (more)"
  jQuery.fn.truncateMe.defaults = {
    max_length: 100,
    more: '...more',
    less: 'less'
  };

  function recursivelyTruncate(node, max_length) {
    return (node.nodeType == 3) ? truncateText(node, max_length) : truncateNode(node, max_length);
  }

  function truncateNode(node, max_length) {
    var node = $(node);
    var new_node = node.clone().html("");
    node.contents().each(function() {
      var remaining_length = max_length - new_node.text().length;
      if (remaining_length == 0) return;
      new_node.append(recursivelyTruncate(this, remaining_length));
    });
    return new_node;
  }

  function truncateText(node, max_length) {
    var text = squeeze(node.data);
    if (trailing_whitespace)  // remove initial whitespace if last text
      text = text.replace(/^ /, '');  // node had trailing whitespace.
    trailing_whitespace = !!text.match(/ $/);
    return text.slice(0, max_length);
  }

  // Collapses a sequence of whitespace into a single space.
  function squeeze(string) {
    return string.replace(/\s+/g, ' ');
  }

})(jQuery);


jQuery.fn.truncateText = function(maxLen, postfix){
    jQuery(this).each(function(){
		var target = jQuery(this);
		var content = this.innerHTML;
		var text = target.text();
		
		if (text.length > maxLen){
			text = text.slice(0,maxLen);
			
			var elemLen = 0;
			var buf = content;
			while (buf.indexOf(text) == -1) {
				var i = buf.indexOf('<');
				var j = buf.indexOf('>');
				elemLen += j - i + 1;
				
				buf = buf.slice(0,i) + buf.slice(j+1,buf.length);
			}
            
			content = content.slice(0, maxLen + elemLen);
			
			// Remove trailing word fragment
			content = content.replace(/[a-z0-9]+$/i, '');
			content = jQuery.trim(content);
			
			content = content + postfix;
			
			this.innerHTML = content;
		}
	});
};
