//bitly start


if (typeof(BitlyApi) == 'undefined'){
    var BitlyApi = {}; // BitlyApi namespace. You sholdn't need to access methods here. Instead, use an instance of BitlyApiClient().
		}
if (typeof(BitlyCB) == 'undefined'){
    var BitlyCB = {}; // global namespace for your callback methods. Allows you to define callabacks from within other method calls.
		}
BitlyApi.loadScript = function(_src) { 
  var e = document.createElement('script'); 
  e.setAttribute('language','javascript'); 
  e.setAttribute('type', 'text/javascript');
  e.setAttribute('src',_src); document.body.appendChild(e); 
};

BitlyApi.loadCss = function(u) { 
  var e = document.createElement('link'); 
  e.setAttribute('type', 'text/css'); 
  e.setAttribute('href', u); 
  e.setAttribute('rel', 'stylesheet'); 
  e.setAttribute('media', 'screen');
  try {
    document.getElementsByTagName('head')[0].appendChild(e);
  } catch(z) {
    document.body.appendChild(e);
  }
};

BitlyApi.call = function(method, params, callback_method_name) {
    var s = "http://api.bit.ly/" + method;
    var url_args = [];
    if (callback_method_name) {url_args.push("callback=" + callback_method_name);}
    
    for (var name in params) {
        url_args.push(name + "=" + encodeURIComponent(params[name]));
    }
    
    s += "?" + url_args.join("&");
    BitlyApi.loadScript(s);
};

var BitlyApiClient = function(login, apiKey, version){
    this.login = login || "timedotcom";
    this.apiKey = apiKey || "R_d514a81e85b444dfbbc234f661e7c38a";
    this.version = version || "2.0.1";
};

BitlyApiClient.prototype.googleVisRequired = "This method requires the google visualization api. Please include javascript from: http://www.google.com/jsapi. More info: http://code.google.com/apis/visualization/documentation/index.html";
BitlyApiClient.prototype.availableModules = ['stats'];
BitlyApiClient.prototype.loadingModules = {};

BitlyApiClient.prototype.moduleLoaded = function(module_name, callback_method_name) {
    BitlyApiClient.prototype.loadingModules[module_name] = true;
    for (var mod in BitlyApiClient.prototype.loadingModules) {
        if (!BitlyApiClient.prototype.loadingModules[mod]) {
            return false;
        }
    }
    eval(callback_method_name + "();");
};

BitlyApiClient.prototype.loadModules = function(module_names, callback_method_name) {
    for (var i=0; i < module_names.length; i++) {
        BitlyApiClient.prototype.loadingModules[module_names[i]] = false;
    }
    for (var i=0; i < module_names.length; i++) {
        var name = module_names[i];
        var callback_name = "module_" + name + "_loaded";
        BitlyCB[callback_name] = function() {
          BitlyApiClient.prototype.moduleLoaded(name, callback_method_name);
        };
        var s = "http://bit.ly/app/modules/" + name + ".js?callback=BitlyCB." + callback_name;
        try {
            BitlyApi.loadScript(s);
        } catch(e) {
            BitlyClient.addPageLoadEvent(function(){
                BitlyApi.loadScript(s);
            });
        }
    }
    try {
        BitlyApi.loadCss("http://bit.ly/static/css/javascript-modules.css");
    } catch(e) {
        BitlyClient.addPageLoadEvent(function(){ 
            BitlyApi.loadCss("http://bit.ly/static/css/javascript-modules.css"); 
        });
    }
};

/*
# utils

*/
BitlyApiClient.prototype.addPageLoadEvent = function(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() { oldonload(); func(); };
	}
};

BitlyApiClient.prototype.extractBitlyHash = function(bitly_url_or_hash) {
    if (bitly_url_or_hash == null) {
        return null;
    } else {
        var m = bitly_url_or_hash.match(/\/([^\/]+)$/);
        if (m) {
            return m[1];
        }
        else {
            return bitly_url_or_hash;
        }
    }
};

BitlyApiClient.prototype.createElement = function(element_type, attrs) {
  var el = document.createElement(element_type);
  for (var k in attrs) {
    if (k == "text") {
      el.appendChild(document.createTextNode(attrs[k]));
    } else {
      this.setAttribute(el, k, attrs[k]);
    }
  }
  return el;
};

BitlyApiClient.prototype.setAttribute = function(element, attribute_name, attribute_value) {
  if (attribute_name == "class") {
    element.setAttribute("className", attribute_value); // set both "class" and "className"
  }
  return element.setAttribute(attribute_name, attribute_value);
};

BitlyApiClient.prototype.listen = function (elem, evnt, func) {
  if (elem.addEventListener){ // W3C DOM
    elem.addEventListener(evnt,func,false);
	}
  else if (elem.attachEvent) { // IE DOM
    var r = elem.attachEvent("on"+evnt, func);
    return r;
  }
};

BitlyApiClient.prototype.targ = function (e) {
	var targ;
	if (!e) {var e = window.event;}
	if (e.target){ targ = e.target;}
	else if (e.srcElement) {targ = e.srcElement;}
	if (targ.nodeType == 3) {// defeat Safari bug
		targ = targ.parentNode;
	}
	return targ;
};

BitlyApiClient.prototype.toggle = function(el) {
  var e;
  if (typeof(el) == 'string') {
    e = document.getElementById(el);
    if (typeof(e) == undefined) {
      throw "toggle: No DOM element with id: " + el;
      return;
    }
  } else {
    e = el;
  }
  if (e.style.display == 'none') {
    e.style.display = '';
  } else {
    e.style.display = 'none';
  }
};

/*
# API
    
Generic API caller for more advanced API usage. Allows you to specify extra params for method calls with options. Eg, you can call the /info API and ask for a subset of data using the 'keys' param.
*/
BitlyApiClient.prototype.call = function(method, params, callback_method_name) {
    params['version'] = this.version;
    params['login'] = this.login;
    params['apiKey'] = this.apiKey;
    return BitlyApi.call(method, params, callback_method_name);
};

// shorten a long url
BitlyApiClient.prototype.shorten = function(longUrl, callback_method_name) {
    return this.call('shorten', {'longUrl': longUrl}, callback_method_name);
};

// expand a bitly url
BitlyApiClient.prototype.expand = function(shortUrl, callback_method_name) {
    return this.call('expand', {'shortUrl': shortUrl}, callback_method_name);
};

// get info about one or more bitly urls or hashes
BitlyApiClient.prototype.info = function(bitly_hash, callback_method_name) {
    var arr = bitly_hash.split(',');
    var hashes = [];
    for (var i=0; i < arr.length && i < 1; i++) {// limit to 1 bitly_hash
        hashes.push(this.extractBitlyHash(arr[i]));
    }
    return this.call('info', {'hash': hashes.join(',')}, callback_method_name);
};

// get referrer data about a bilty url or hash
BitlyApiClient.prototype.stats = function(bitly_hash_or_url, callback_method_name) {
    bitly_hash_or_url = this.extractBitlyHash(bitly_hash_or_url);
    return this.call('stats', {'hash': bitly_hash_or_url}, callback_method_name);
};

/*
# TESTS
    
*/
BitlyApiClient.prototype.shortenTest = function() {
    this.shorten(document.location, 'shortenTestCB');
};
function shortenTestCB(data) {
    // this is how to get a result of shortening a single url
    var result;
    for (var r in data.results) {
        result = data.results[r];
        result['longUrl'] = r;
        break;
    }
    alert(result['longUrl'] + " shortened to " + result['shortUrl']);
}

BitlyApiClient.prototype.expandTest = function() {
    this.expand("http://bit.ly/3j4ir4", 'expandTestCB');
};
function expandTestCB(data) {
    // this is how to get a result of expanding a single url
    var result;
    for (var r in data.results) {
        result = data.results[r];
        result['hash'] = r;
        break;
    }
    alert(result['hash'] + " expanded to " + result['longUrl']);
}

BitlyApiClient.prototype.infoTest = function() {
    this.info("http://bit.ly/3j4ir4", 'infoTestCB');
};
function infoTestCB(data) {
    // this is how to get a doc of info call for a single url
    var doc;
    for (var r in data.results) {
        doc = data.results[r];
        break;
    }
    alert("got info for " + doc['hash'] + ". eg., longUrl is " + doc['longUrl'] + ", title is " + doc['htmlTitle']);
}

BitlyApiClient.prototype.statsTest = function() {
    this.stats("http://bit.ly/3j4ir4", 'statsTestCB');
};
function statsTestCB(data) {
    var stats = data.results;
    alert("stats for " + stats['hash'] + ". " + stats['clicks'] + " clicks");
}




/*
# INSTANTIATE CLIENT
    
*/
var BitlyClient = new BitlyApiClient();

/*
*/

//bitly end
var Link = {
    baseUrl : '',
    shorten : function(twitter_url) {


        var times_url = twitter_url.match(/http:\/\/www\.time.*\.html/);


        if(times_url){
          Link.baseUrl = twitter_url.replace('home?status','intent/tweet?text');
          BitlyClient.shorten(times_url[0], 'Link.response');
        }
    },
    response: function(data){
    
		var base_link = Link.baseUrl;
    
		for (var r in data.results) {
		  
			base_link = base_link.replace(/http:\/\/www\.time.*\.html/,encodeURIComponent(data.results[r]['shortUrl']));
			break;
		}
		if(typeof base_link != 'undefined'){
			$('#videoTools .twitter a').attr('href',base_link);
	}

		

	}
};


var videoFields = 'id,name,thumbnailURL,referenceId,shortDescription,longDescription,tags,length,linkURL,linkText';
var customFields = 'relatedtopics,itunesurl';

var updateVideo = function(id, data){

    var relatedVideoContent  = function(container,obj){

      container.addClass('loading');
      var ul = $('<ul class="videoList"/>') ;
      var content = generateSecondaryContent(container,obj);
      ul.append(content);
      container.append(ul);


      
      
      if(container.parent().find('.pagination li:first').hasClass('selected')){
          ul.find('img').lazyload({effect : 'fadeIn'});
      }
      
    };

    var tags = data.customFields && data.customFields.relatedtopics ? data.customFields.relatedtopics.split(',') : data.tags;
    var tagsLength = tags ? tags.length : 0;
    var title = data.name ? data.name : data.displayName;
    
    var ctid = data.referenceId ? data.referenceId : 0;
        
    var bcid = id;
    var unencodeHref = 'http://www.time.com/video/player/0,32068,'+bcid+'_'+ctid+',00.html';
    var href  = encodeURI(unencodeHref);
    var desc  = data.shortDescription ? data.shortDescription : '';    
    var relatedTopics = '';
    var linkURL = data.linkURL;    
    var linkText = data.linkText;


    document.title = title+' - Video - TIME.com';
    var $mainVideoTitle = $('#mainVideoTitle'); 
    var $videoDescription = $('#videoDescription');
    var $videoContainer = $('#videoContainer');
    var $relatedTopics = $('#relatedTopics').length ? $('#relatedTopics').show() :  $videoContainer.before('<div id="relatedTopics"/>').parent().find('#relatedTopics');
    var $relatedArticle = $('#relatedArticle').length ? $('#relatedArticle').show() : $videoDescription.after('<p id="relatedArticle"/>').parent().find('#relatedArticle');
    var $itune = $('#itunes').length ? $('#itunes').show() : $('#videoTools .emailThis').after('<li id="itunes"/>').parent().find('#itunes');
    var ituneUrl = data.customFields && data.customFields.itunesurl ? data.customFields.itunesurl : null;
    
    
    if(ituneUrl){
      $itune.html('<a href="'+ituneUrl+'" target="_blank">Download</a>');
      
    }else{
      $itune.hide();
    }

    if(!modVP){
      if(!$mainVideoTitle.text()){
        $mainVideoTitle.text(title);
      }
      if(!$videoDescription.text()){
        $videoDescription.text(desc);
      }      
    
    }else{
        $mainVideoTitle.text(title);
        $videoDescription.text(desc);
    }
    
    
    
    
      
    if(tagsLength > 0){
      var tag = '';
      var tagsli = '';
      $.each(tags,function(i,data){
        data =  $.trim(data);
        tag += data+','; 
        tagsli += '<li><a href="/time/video/search/0,,,00.html?cmd=tags&q='+data.replace(/&/,'%26')+'">'+data+'</a></li>';
      });
      
      $relatedTopics.html('<strong>RELATED TOPICS:</strong> <ul>'+tagsli+'</ul>');
      
    
    }else{
      $relatedTopics.hide();
    }
    
    
    
    if(linkURL){
      $relatedArticle.html('<strong>RELATED</strong> <a href="'+linkURL+'">'+linkText+'</a>');
    }else{
      $relatedArticle.hide();
    }
      
    
    var $videoTopic = $('#videoTopic').empty();
    $videoTopic.append('<h3>Similar Videos for: '+title+'</h3>');
    
    tag = tag ? tag.substr(0,tag.length-1) : '';
    var term = tag.replace(/&/,'%26');
  
    var cmd = 'find_videos_by_tags';
    var search = '&or_tags=';
    
    if(term.length > 0){
    var relatedVideoUrl = bcRequestUrl(cmd,search+term+'&get_item_count=true&page_size=10&page_number=0&sort_order=DESC&sort_by=plays_total&video_fields='+videoFields+'&callback=?');  	
    

    $.getJSON(relatedVideoUrl, function(data){
       
       var l = data.total_count < 100 ? data.total_count : 100;
       var outterLoop = Math.ceil(l/10);
       
       var $pagination = $('<ul class="pagination"/>');
       var paginationLi ='';
       for(var i = 0; i < outterLoop ; i++){
       var bcHref = bcRequestUrl(cmd,search+term+'&page_number='+i+'&page_size=10&sort_order=DESC&sort_by=plays_total&video_fields='+videoFields+'&callback=?');
paginationLi +='<li><a href="'+bcHref+'">'+(i+1)+'</a></li>';           

       }
      
      $pagination.append(paginationLi);
      
      var prevVideoTopicAjaxFun = function(panel){
        panel.addClass('loading');
        panel.parent().find('h3').after(panel);
      }

      var postVideoTopicAjaxFun = function(panel){
        
        panel.removeClass('loading').addClass('content');
      }

      
      
      $videoTopic.append($pagination); 
       
      var $firstContent = $('<div class="content"><ul class="videoList">'+generateSecondaryContent($('<div/>'),data)+'</ul></div>');
      
      
      var firstHerf = $pagination.find('li:first a').attr('href');
      var videoTopicPanels = {};
      videoTopicPanels[firstHerf] = $firstContent;
      
      
      $videoTopic.timeJSONTabs({panels:videoTopicPanels,generateContent:relatedVideoContent,prevAjaxFun:prevVideoTopicAjaxFun,postAjaxFun:postVideoTopicAjaxFun});
      
      $pagination.before($firstContent);
      $firstContent.find('img').lazyload({effect : 'fadeIn'});
      if(outterLoop > 1){
        $pagination.append('<li class="prev notActive"><a href="#prev">&laquo; PREV</a></li>');
        $pagination.append('<li class="next"><a href="#next">NEXT &raquo;</a></li>');
        var next = $pagination.find('.next').bind('click',nextFun);
        var prev = $pagination.find('.prev').bind('click',prevFun);
                
        $pagination.find('li').click(function(){
           $pagination.find('.notActive').removeClass('notActive');
           var offSet = -1;
           var $a = $(this).find('a');
           var aNum = parseInt($a.text(),'10');
           
           if(($a).parent().hasClass('next')){
            offSet = 1;
           }
           var pos = aNum ? aNum : parseInt($pagination.find('.selected a').text(),'10') + offSet;
           
          if(pos < 1 || aNum ==1){
            
            prev.addClass('notActive');
          }
          if(pos > outterLoop || aNum == outterLoop){
            
            next.addClass('notActive');
          }
        });
      }

      

            
    });    
    }

    

    
    if(modVP || window.location.href.match(/_0,00\.html/)){

    var $videoTools = $('#videoTools');
    $videoTools.find('a').unbind('click');
    
    


    
    $videoTools.find('.emailThis a').attr('href','http://pathfinder.com/r0/venue/partner/out?/cgi-bin/mail/mailurl2friend.cgi?path=/time/emailFriend&url='+href+'&amp;group=time&amp;title='+encodeURI(title)).timePopUp({url:this.href, height : 730, width: 750}).setPixel({tracker:'emailthis'});	
    $videoTools.find('.digg a').attr('href','http://digg.com/submit?url='+escape(href)+'&amp;title='+escape(title)+'&amp;bodytext='+escape(desc)).timePopUp({url:this.href,height : 450, width: 980}).setPixel({tracker:'sharethis'});
    $videoTools.find('.facebook a').attr('href','http://www.facebook.com/sharer.php?u='+href+'?&amp;t='+encodeURI(title)).timePopUp({url:this.href,height : 436, width: 626}).setPixel({tracker:'sharethis'});
    
    $videoTools.find('.twitter a').attr('href','http://twitter.com/home?status=Viewing @time '+escape(title)+' '+href).setPixel({tracker:'sharethis'});
		Link.shorten($('#videoTools').find('.twitter a').attr('href'));

    $videoTools.find('.yahooBuzz').html('<span id="yahooBuzzBadge-form" class="yahooBuzzBadge-form"><a href="http://buzz.yahoo.com/buzz?publisherurn=time&guid='+href+'&targetUrl=" target="_blank"><span style="cursor: pointer; position: relative; padding-left: 20px; line-height: 16px;"><span style="background: transparent url(http://l.yimg.com/ds/orion/1.0.5/img/badge-logo.png) no-repeat scroll left top; cursor: pointer; display: block; position: absolute; top: 0pt; left: 0pt; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; height: 16px; width: 16px;"/>Yahoo! Buzz</span></a></span>');
    }    
    
};
(function($){

      


      var moreVideoContent  = function(container,obj){

        container.addClass('loading');
        if(typeof(obj) != 'object'){
          container.parent().find('.selected').after(container);
          $.get(obj, function(responseText, textStatus, XMLHttpRequest){
            container.html($(responseText).find('.videoList').parent().html())
            container.removeClass('loading').addClass('content');
          });
          
     
        }else{
        
        var ul = $('<ul class="videoList"/>');
        obj.videos = obj.videos.slice(0,5);
         
        var content = generateSecondaryContent(container,obj);
        ul.append(content);
        container.append(ul);
        
        container.parent().find('.selected').after(container);

        }
        
      };

      var moreVideoHideFn  = function($content){
        $content.slideUp('slow');
      };
      var moreVideoShowFn  = function($content){
        $content.slideDown('slow');
      };

    
		var mostRecent = bcRequestUrl('find_playlist_by_id','&playlist_id=1342094282&sort_order=DESC&sort_by=publish_date&video_fields='+videoFields+'&callback=?');		

  var prevMoreVideoAjaxFun = function(panel){
  //  console.log(panel)
  panel.addClass('loading');
  }
  
  var postMoreVideoAjaxFun = function(panel){
  
  panel.removeClass('loading').addClass('content');
  } 

	$moreVideo = $('#moreVideo');
	$moreVideo.find('.moreVideoUl').append('<li id="mostRecent"><h4><a href="'+mostRecent+'">Most Recent</a></h4></li></ul>');
	var ran_unrounded=Math.random()*2;
  var ran_number=Math.floor(ran_unrounded); 
  var moreVideoTabs = $moreVideo.find('h4');
  
  $moreVideo.timeJSONTabs({generateContent:moreVideoContent,first:ran_number,tabs:moreVideoTabs,hideFn:moreVideoHideFn,showFn:moreVideoShowFn,prevAjaxFun:prevMoreVideoAjaxFun,postAjaxFun:postMoreVideoAjaxFun});
      
  var videoId = $("meta[name='videoId']").attr('content').length ? $("meta[name='videoId']").attr('content') : gup('bctid'); 
  
	var videoMainUrl = bcRequestUrl('find_video_by_id','&video_id='+videoId+'&video_fields='+videoFields+'&custom_fields='+customFields+'&callback=?');


      
  $.getJSON(videoMainUrl, function(data){
    updateVideo(videoId,data);
  });
	
	
//	$('#videoTools').find('.twitter').href() (TweetThisLink.shorten()) 



Link.shorten($('#videoTools').find('.twitter a').attr('href'));

})(jQuery);
var BC_ID_OF_BANNER_AD = 'banner-ad';
var bcExp = '';
var modVP = '';
var modExp = ''; 
var modCon = '';
var modAd = ''; 
var modCP = '';


var videoListKey = 0;

var playlist = [];

// called when template loads, this function stores a reference to the player and modules.
function onTemplateLoaded(experienceID) {
    
    bcExp = brightcove.getExperience(experienceID);
    
    modVP 	= bcExp.getModule(APIModules.VIDEO_PLAYER);
    modExp 	= bcExp.getModule(APIModules.EXPERIENCE);
    modCon 	= bcExp.getModule(APIModules.CONTENT);
    modAd 	= bcExp.getModule(APIModules.ADVERTISING);
    modAd.enableExternalAds(true);
    modCP = bcExp.getModule(APIModules.CUE_POINTS);
    
    modExp.addEventListener(BCExperienceEvent.CONTENT_LOAD, onContentLoad);
    modExp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
    
		modAd.addEventListener('adComplete',bc_adComplete); 
		modAd.addEventListener('externalAd',playAd);
		modCon.addEventListener(BCContentEvent.VIDEO_LOAD, onVideoLoad);
		modVP.addEventListener(BCMediaEvent.COMPLETE,onMediaComplete);
		modVP.addEventListener(BCMediaEvent.BEGIN,onMediaBegin);
    
    //   modCP.addEventListener(BCCuePointEvent.CUE,onCuePoint);  
    
}

function onExternalAd(evt) {
	//alert(evt);
}

function onTemplateReady(evt) {
	//alert("EVENT: TEMPLATE_READY");
  	var videoListKey = 0;
  
    var moreVideoAHerfArray = $('#moreVideo').find('.selected').next().find('li h5 a');
    var bcId;
    var currentId = modVP.getCurrentVideo().id;
    
    $.each(moreVideoAHerfArray, function(i,data){
    
      bcId = data.href.replace(/.*\,(.*)_.*/g,'$1');
   
      if (bcId !=currentId){
        playlist.push(bcId);
      }
      
      
    });
    

}

function onContentLoad(evt) {
  
	//alert("EVENT: CONTENT_LOAD");
	updateAdPolicy();
	if(!modVP.isPlaying()){
    
	 var t=setTimeout('modVP.play();',3000);
  }
	
	
}
function onMediaBegin(evt) {

  $('#bc_adOverlay,#bc_adContainer').hide();
	//alert("EVT:  MEDI  A BEGIN");
	if (videoListKey > 0){
    var currentVideo = modVP.getCurrentVideo();


    
    updateVideo(currentVideo.id,currentVideo);


    
    
    
  }  
  
	if (videoListKey < playlist.length) {
		document.getElementById('myExperience').setNextId( playlist[videoListKey]); 
	}
	else {
		document.getElementById('myExperience').setNextId( -1 );
	}
}

function onMediaComplete(evt) {
	//alert("EVT:  MEDIA COMPLETE")
	videoListKey++;
}
function onVideoLoad(evt) {
	updateAdPolicy();
}

function onCuePoint(evt){
  //  console.dir(evt)
}

function updateAdPolicy() {
//	alert('update ad policy')
  
	var currentVideo = modVP.getCurrentVideo();
		
	var tags = currentVideo.tags ? currentVideo.tags :'';
  var ctid = currentVideo.referenceId ? currentVideo.referenceId : 0;    
  var bcid = currentVideo.id;
  var unencodeHref = 'http://www.time.com/video/player/0,32068,'+bcid+'_'+ctid+',00.html';

	var referenceId = currentVideo.referenceId;
	var id = currentVideo.id;
  

	
	var adPolicy = modAd.getAdPolicy();
	//alert(adPolicy.prerollAds)
	if(adPolicy){
  	adPolicy.prerollAds = true;
  	
  	var stringTags= escape(tags.join(';cont=')).replace(/[\s]/g,'').replace(/%3b/gi,';').replace(/%3d/gi,'=');
  	
  	adPolicy.prerollAdKeys = ';cont='+stringTags+';frmt=22;frmt=0;frmt=1;frmt=2;frmt=6;frmt=14;frmt=15';
    
  	
  	modAd.setAdPolicy(adPolicy);
  }
}


	///////
	//// brightcove enclosure
	///////


	function playAd(adEvent) {
    	var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;  
       if(IE6)  
       {  
        var $overLay = $('#bc_adOverlay');
        var offSetHeight = $overLay.parent().innerHeight();
        $overLay.css('height',offSetHeight);
       }  
      //console.log(adEvent.ad);
	
	    $('#bc_adOverlay,#bc_adContainer').show();    
	    pXML = adEvent.ad;

	    try {
	        pXML = bc_replaceChars(pXML, "&", "%26");
	        bc_gAdPlaying = true;
	        if (window.ActiveXObject) {
	            //parses the XML for IE browsers
	            var adXML = new ActiveXObject("Microsoft.XMLDOM");
	            adXML.async = false;
	            adXML.loadXML(pXML);
	        } else if (window.XMLHttpRequest) {
	            //parses the XML for Mozilla browsers
	            var adXML = (new DOMParser()).parseFromString(pXML, "text/xml");
	        }

	        var ad = new Object();

	        var nodeItems = adXML.firstChild.childNodes.length; //the number of items in the XML
	        var currentNode = adXML.firstChild.firstChild; //sets the first node in the XML as the current node

	        //checks to see the duration was set and sets the variable
	        if (adXML.firstChild.getAttribute("duration") !== "") ad.duration = adXML.firstChild.getAttribute("duration");
	        if (adXML.firstChild.getAttribute("trackStartURLs") !== "") {
	            var trackStr = adXML.firstChild.getAttribute("trackStartURLs");
	            var urls = trackStr.split(",");
	            ad.trackStartURLs = urls;
	        }

	        var expandedBannerURL = null;
	        var expandedBannerClickURL = null;
	        var collapsedBannerURL = null;
	        var collapsedBannerClickURL = null;

	        for (var i = 0; i < nodeItems; i++) {
	            //checks to see if the current nodes are in our Rich Media Templates and assigns them if they exist
	            if (currentNode.nodeName == "videoURL") {
	                ad.videoURL = currentNode.firstChild.nodeValue;
	            } else if (currentNode.nodeName == "videoClickURL") {
	                ad.videoClickURL = currentNode.firstChild.nodeValue;
	            } else if (currentNode.nodeName == "expandedBannerURL") {
	                expandedBannerURL = currentNode.firstChild.nodeValue;
	            } else if (currentNode.nodeName == "expandedBannerClickURL") {
	                expandedBannerClickURL = currentNode.firstChild.nodeValue;
	            } else if (currentNode.nodeName == "collapsedBannerURL") {
	                collapsedBannerURL = currentNode.firstChild.nodeValue;
	            } else if (currentNode.nodeName == "collapsedBannerClickURL") {
	                collapsedBannerClickURL = currentNode.firstChild.nodeValue;
	            }
	            //move to the next node for the next pass of the loop
	            currentNode = currentNode.nextSibling;
	        }
	        //Call function to show 300x250 ad.
	        bc_show300Ad(expandedBannerURL, expandedBannerClickURL);

	        //call funciton to show the banner ad.
	        bc_updateBannerAd(collapsedBannerURL, collapsedBannerClickURL);

	        //force it to be of type "video ad", a type the single title can understand.
	        ad.type = "videoAd";
	        modAd.showAd(ad);

	        /** FIXME Hack, brightcove should be showing sponsor message automatically*/
	        //bc_adController.disableForExternalAd();

	        //We don't want the playing state still set for a title so if it is in that state we hide it.
	        /*if (bc_gCurrentTitleId != null) {
	            document.getElementById('bc_title_' + bc_gCurrentTitleId + '_' + bc_gCurrentPlayingLineupId).style.color = "#093B6C";
	            document.getElementById('bc_play_' + bc_gCurrentTitleId + '_' + bc_gCurrentPlayingLineupId).src = "http://brightcove.vo.llnwd.net/d2/unsecured/media/293884104/293884104_1341417403_00385e0056270c2678d9946b784868c7d65a0db4.png?pubId=293884104";
	            document.getElementById('bc_playingDiv_' + bc_gCurrentTitleId + '_' + bc_gCurrentPlayingLineupId).style.zIndex = -3;
	        }*/

	        bc_adPlayedBeforeVideo = true;
	    } catch (e) {
	        modAd.resumeAfterExternalAd();
	        bc_adComplete();
	    }
	}

	function bc_replaceChars(pString, pOut, pAdd) {
	    while (pString.indexOf(pOut) > -1) {
	        var pos = pString.indexOf(pOut);
	        pString = "" + (pString.substring(0, pos) + pAdd + pString.substring((pos + pOut.length), pString.length));
	    }
	    return pString;
	}

	function bc_adComplete(evt) {
	    /** FIXME Hack to get the brightcove overlay menu closed, it shows up after every ad */
	    /*if(bc_menuController.isOverlayMenuShowing()){
	    bc_menuController.removeOverlayMenu();
	    }*/

	    bc_gAdPlaying = false;
	    //I used zIndex instead of display:none because you cannot change element styles crossbrowser when an object is not displayed at all
	    document.getElementById('bc_adOverlay').style.zIndex = -1;
	    document.getElementById('bc_adContainer').style.zIndex = -1;
	    document.getElementById('bc_adContainer').innerHTML = "";

	    //On a Mac the scrollbars are not covered up by the overlay so we simply hide the scrollbars.  here we show them again.
	    if (navigator.platform == "Mac") {
	        for (var i = 0; i < bc_gLineUpArray.length - 1; i++) {
	            try {
	                document.getElementById(bc_gLineUpArray[i].id).style.overflow = "auto";
	            } catch (e) {
	                //gulp
	            }
	        }
	    }
	}

	function bc_show300Ad(pAdUrl, pClickUrl) {
	    //If the user is on a Mac then we want hide the scrollbars since they appear over the overlay.
	    if (navigator.platform == "Mac") {
	        for (var i = 0; i < bc_gLineUpArray.length - 1; i++) {
	            try {
	                document.getElementById(bc_gLineUpArray[i].id).style.overflow = "hidden";
	            } catch (e) {
	                //gulp
	            }

	        }
	    }

	    /*I used zIndex because setting the innerHTML of element that is not yet displayed causes problem crossbrowser issues*/
	    document.getElementById('bc_adOverlay').style.zIndex = 99;
	    document.getElementById('bc_adContainer').style.zIndex = 100;

	    var expandedBanner = document.getElementById("bc_adContainer");
	    if (pAdUrl.substr((pAdUrl.length - 3), 3) == "swf") {
	        var objectTag = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="300" height="250" id="expandedBanner" align="middle">';
	        objectTag += '<param name="allowScriptAccess" value="always" />';
	        objectTag += '<param name="movie" value="' + pAdUrl + '" />';
	        objectTag += '<param name="quality" value="high" />';
	        objectTag += '<param name="bgcolor" value="#ffffff" />';
	        objectTag += '<param name="FlashVars" value="clickTag=' + pClickUrl + '" />';
	        objectTag += '<embed src="' + pAdUrl + '" quality="high" bgcolor="#ffffff" width="300" height="250" name="expandedBanner" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" FlashVars="clickTag=' + pClickUrl + '" />';
	        objectTag += '</object>';
	        expandedBanner.innerHTML = objectTag; //writes out the object tag we just built to the expandedBanner div
	    } else {
	        expandedBanner.innerHTML = "<a href='" + pClickUrl + "' target='_blank' ><img src='" + pAdUrl + "' /></a>"; //writes out the regular anchor/tag to the expandedBanner div
	    }
	}

	function bc_updateBannerAd(pAdUrl, pClickUrl) {
	    document.getElementById(BC_ID_OF_BANNER_AD).innerHTML = "<a target='_blank' href='" + pClickUrl + "'><img border=0 src='"
	+ pAdUrl + "'/></a>";
	}
	
if (DetectIphoneOrIpodOrIPad()) {	
	BCReadAPIToken = "ytCkbxiTENhbQ9Tlyg_HmKjLkov2EduhD3NOSmXglqU."; 
	runMobileCompatibilityScript('myExperience');	
}	else if ( !FlashDetect.installed) {
  $('#videoPlayer').html('<p class="getFlash">This content requires the Adobe Flash Player. <a href="http://www.adobe.com/go/getflash/" target="_blank">Get Flash</a></p>');	
}
