var bc_player, bc_experience, bc_video, bc_social, bc_advertising, bc_cuepoints, bc_content, bc_tab;

var bc_currentVideo;
var experienceId;
var bc_playbackStarted = false;
var bc_playerFullScreen = false;
var bc_playerLastTick = 0; 
var bc_playerAutostart = false;
var bc_playerDefinition = '';
var BigBoxAd = {};
var BigBoxAdContainer = '';
var bc_debug = 0;
var bc_video_count = 0;
var bc_playerVolume = .5;
var bc_playerVolumeDefault = .5;
var bc_playerVolume = .5;
var bc_user_video_count = 0;
var videoList;

var stack = Array();

var count_load = -1;

var showTabs = false;

var playlistQueues;

// init
bc_playerVolume = getVolumePreference();
bc_user_video_count = getUserVideoCount();

function onTemplateLoaded( experienceId )
{
  if ( bc_debug ) 
  {
    Log('onTemplateLoaded');
  }
  
  // Setup Modules
  bc_player      = brightcove.getExperience(experienceId);
	
  bc_experience  = bc_player.getModule(APIModules.EXPERIENCE);
  bc_video       = bc_player.getModule(APIModules.VIDEO_PLAYER);
	bc_content     = bc_player.getModule(APIModules.CONTENT);
	
  bc_social      = bc_player.getModule(APIModules.SOCIAL);
  bc_advertising = bc_player.getModule(APIModules.ADVERTISING);
  bc_cuepoints   = bc_player.getModule(APIModules.CUE_POINTS);
	
  // Setup Listeners
  
  // experience related
  bc_experience.addEventListener(BCExperienceEvent.CONTENT_LOAD, onContentLoad);
  bc_experience.addEventListener(BCExperienceEvent.ENTER_FULLSCREEN, onEnterFullScreen);
  bc_experience.addEventListener(BCExperienceEvent.EXIT_FULLSCREEN, onExitFullScreen);
  bc_experience.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
  
  // video related
  bc_video.addEventListener(BCVideoEvent.VIDEO_CHANGE, onVideoChange);
  bc_video.addEventListener(BCVideoEvent.VIDEO_CONNECT, onVideoConnect);
  bc_video.addEventListener(BCVideoEvent.VIDEO_PROGRESS, onVideoProgress);
  bc_video.addEventListener(BCVideoEvent.STREAM_START, onStreamStart);
	
  // social related
  bc_social.addEventListener(BCSocialEvent.EMBED_CODE_RETRIEVED, onEmbedCodeRetrieved);
  
  // advertising related
  bc_advertising.enableExternalAds(true);
  bc_advertising.addEventListener(BCAdvertisingEvent.EXTERNAL_AD, onExternalAd);
  bc_advertising.addEventListener(BCAdvertisingEvent.AD_COMPLETE, onExternalAdComplete);

  bc_content.addEventListener(BCContentEvent.MEDIA_COLLECTION_LOAD, onMediaCollectionLoad);
  
  // check for auto start
  bc_playerDefinition = bc_video.getDefinition();
  
  if ( bc_playerDefinition.indexOf('autoStart="true"') !== -1 ) 
  {
    if ( bc_debug ) 
    {
      Log('Player is autoplay.');
    }
    
    bc_playerAutostart = true;
  } 
  else 
  {
    if ( bc_debug ) 
    {
      Log('Player is not autoplay');
    }
  }

  // set player volume
  bc_video.setVolume(bc_playerVolume);
}

function onTemplateReady(e) {

  if ( bc_debug ) 
  {
    Log('onTemplateReady');
  }
  
  videoList = bc_experience.getElementByID("videoList");

 	bc_tab = bc_experience.getElementByID("playlistTabs");
	
	if(showTabs == true) {
 	  bc_tab.setHideSingleTab(false);
	  bc_tab.setVisible(true);
	}
	
}

function onMediaCollectionLoad(e) {
	
	if(e.mediaCollection != null) {

 	  // If count_load is under 0, then the click did'nt come from us
	  if(count_load < 0) {
		  // We load the videos in the library
		  fillTab(e);
		 
		} else {

		  // while the stack is'nt full, we continue
 	    stack[stack.length] = e;

			if(count_load == stack.length) {
			  loadItems();
			}
		
		}
	}
}

function fillTab(items) {
	
  var mediaDTOs = new Array();
	
  for(var i = 0; i < items.mediaCollection.mediaCount; i++) {
    mediaDTOs[i] = bc_content.getMedia(items.mediaCollection.mediaIds[i]);
  }
	 
  videoList.setData(mediaDTOs);
		 
}

function loadItems() {
	
  var mediaDTOs = new Array();
	
	removeTabs();
	
 	for(var i = 0; i < stack.length; i++) {
	  if(stack[i].mediaCollection.displayName) {
		  bc_tab.appendTab(stack[i].mediaCollection);
		}
	}

 	fillTab(stack[0]);
	
	videoList.setSelectedIndex(0);
	
	count_load = -1;
	
	stack = new Array();
}

function onVideoChange(pEvent) 
{
  if ( bc_debug ) 
  {
    Log('onVideoChange');
  }
 
  // current video
  bc_currentVideo = bc_video.getCurrentVideo();
  
  if ( bc_debug )
  {
    Log(bc_currentVideo);
  }  
  
  bc_user_video_count = bc_user_video_count + 1;
  
  bc_advertising.resumeAfterExternalAd();
	
	BigBoxAd.redrawCount = 0;
  BigBoxAd.setSyncedBanner(false);

  if ( bc_debug )
  {
    Log('Adding Cuepoint at: '+CanoeVideoStandalone.cuepoint+' seconds');
  }
  
  bc_cuepoints.addCuePoints(bc_currentVideo.id,[{'time': CanoeVideoStandalone.cuepoint,'name': 'mid','type': 'ad'}]);   
}

function onContentLoad()
{  
  if ( bc_debug )
  {
    Log('onContentLoad');
  }

  if ( !bc_playerAutostart )
  {
    if ( $(BigBoxAd.container).is(':empty') ) 
    {
      if ( bc_debug )
      {
        Log('Loading Big Box - Not Auto Starting and Ad Container Empty');
      } 
      
      BigBoxAd.redrawAd();
    }
  }
}

function onVideoConnect(pEvent)
{
  if ( bc_debug )
  {
    Log('onVideoConnect');
  }

  bc_playerLastTick = 0;
}

function onStreamStart()
{
  if ( bc_debug )
  {
    Log('onStreamStart');
  }

  bc_video_count = bc_video_count + 1;

  // if no preroll and autoplay
  if ( bc_playerAutostart || bc_video_count > 1 )
  {
    if ( bc_debug )
    {
      Log('Loading Big Box - Auto Start and Video Count is: '+bc_video_count);
    }
    
    BigBoxAd.redrawAd();
  }
}

function onExternalAd(pAdObject)
{
	var forcepreroll = false;
	
  if ( bc_debug )
  {
    Log('onExternalAd');
  }

  if ( bc_debug == 2 )
  {
    Log(pAdObject);
  }
	
 	if ( pAdObject.ad.indexOf("forcepreroll=1") != -1 ) {
 	  forcepreroll = true;
	}
	
  // it's good.  check user video count
  if ( forcepreroll == true || (bc_user_video_count-1) % CanoeVideoStandalone.prerollfreq == 0 ) {
    if ( bc_debug )
    {
      Log('showing preroll on video number '+(bc_user_video_count-1)+' - frequency matched');
    }

    new ExternalAd(pAdObject,{expandedId: BigBoxAdContainer});  
  }
  else
  {
    if ( bc_debug )
    {
      Log('ignoring preroll on video number '+(bc_user_video_count-1)+' - frequency capped');
    }        
    
    bc_advertising.resumeAfterExternalAd();
    BigBoxAd.setSyncedBanner(false);
    
    return false;
  } 
}

function onExternalAdComplete(pEvent)
{
  if ( bc_debug )
  {
    Log('onExternalAdComplete');
  }
}

function onEnterFullScreen()
{
	bc_cuepoints.clearAdCuePoints(bc_currentVideo.id);
  BigBoxAd.setFullScreen(true);
}

function onExitFullScreen()
{
	bc_cuepoints.addCuePoints(bc_currentVideo.id,[{time: SiteParams.cue_point, name: 'mid', type: 'AD'}]);
  BigBoxAd.setFullScreen(false);
  BigBoxAd.redrawAd();
}

function onVideoProgress( pEvent )
{
  bc_playerThisTick = parseInt(pEvent.position,10);
  
  if ( bc_playerThisTick != bc_playerLastTick && bc_playerThisTick % BigBoxAd.interval == 0 )
  { 
    if ( bc_debug == 2 )
    {
      Log('Refreshing Bigbox at interval: '+BigBoxAd.interval);
    }
    
    BigBoxAd.redrawAd();
  }
  
  bc_playerLastTick = bc_playerThisTick;
}

function loadVideos(data) {
	
	loadVideosById(data);
	
}

function loadPlaylists(data, showTabs, tabAlign) {
	
	if(typeof(showTabs) == 'undefined') {
 	  showTabs = true;
	}
	
	if(typeof(tabAlign) == 'undefined') {
 	  tabAlign = 'left';
	}

	if(typeof bc_tab != 'undefined') {
  	bc_tab.setHideSingleTab(!showTabs);
		bc_tab.setVisible(showTabs);

		if(showTabs && data.length > 1) {
			bc_tab.setTabAlign(tabAlign);
		}
	
	}
	
	count_load = data.length;
	
 	for(i = 0; i < data.length; i++) {
 	  loadPlaylistById( data[i] );
	}
}

function loadPlaylistById(mediaIdToRequest) {
 	if(bc_experience != null && bc_experience.getReady()) {
 	  bc_content.getMediaCollectionAsynch(mediaIdToRequest, "id", 0, 100);
	}
}

function loadVideosById(mediaIdsToRequest) {
 	if(bc_experience != null && bc_experience.getReady()) {
 	  bc_content.getMediaInGroupAsynch(mediaIdsToRequest);
	}
}

function removeTabs() {
 	for(var i = bc_tab.getNumItems(); i > 0; i--) {
 	  bc_tab.removeTabAt(i - 1);
 	}
}

function getVolumePreference()
{
  var volume = cookie('bc_volume');
  
  if ( volume != null )
  {
    return volume;
  }
  else
  {
    return bc_playerVolumeDefault;
  }  
}

function setVolumePreference( volume )
{
  cookie('bc_volume', volume, { expires: 7, path: '/', domain: '', secure: false });
}

function setUserVideoCount( bc_user_video_count )
{
  if ( bc_debug )
  {
    Log('setUserVideoCount = '+bc_user_video_count);
  }
  
  cookie('bc_user_video_count', bc_user_video_count, { path: '/', domain: '', secure: false });
}

function getUserVideoCount()
{
  var count = cookie('bc_user_video_count');
 
  if ( bc_debug )
  {
    Log('getUserVideoCount = '+count);
  }
  
  if ( count != null )
  {
    return parseInt(count);
  }
  else
  {
    return 0;
  }  
}

function onEmbedCodeRetrieved ()
{
  // do nothing
}

function playVideo( video_id )
{
  bc_video.loadVideo(video_id);
}

function getCurrentVideo()
{
  return bc_video.getCurrentVideo();
}

var CanoeVideoStandalone = {

  experienceId: 'canoePlayer',
  style: { bgcolor: '#ffffff', width: 544, height: 455 },
  publisher: 0,
  player: 0,
  playlist: 0,
  video: 0,
  videolist: 0,
  videolistfeat: 0,
  containers : { player: '#player', ad: '#ad' },
  adtag: '',
  adserver: '',
  cuepoint: 10,
  bigboxfreq: 30,
  prerollfreq: 2,
	smoothing: false,

  Init: function ( publisher, player, video, style )
  {
    this.SetPublisher(publisher);
    this.SetPlayer(player);
    this.SetVideo(video);
    this.SetStyle(style);
  },

  SetExperienceId : function ( experienceId )
  {
    if ( typeof experienceId !== 'undefined' && experienceId )
    {
      this.experienceId = experienceId;
      experienceId = experienceId;
    }
  },

  SetStyle: function ( style )
  {
    if ( typeof style === 'object' )
    {
      if ( typeof style.width !== 'undefined' && style.width )
      {
        this.style.width = style.width;
      }
            
      if ( typeof style.height !== 'undefined' && style.height )
      {
        this.style.height = style.height;
      }
      
      if ( typeof style.bgcolor !== 'undefined' && style.bgcolor )
      {
        this.style.bgcolor = style.bgcolor;
      }
    }    
  },

  SetPublisher: function ( publisher )
  {
    if ( publisher )
    {
      this.publisher = publisher;
    }
  },

  SetPlayer: function ( player )
  {
    if ( player )
    {
      this.player = player;
    }
  },

  SetPlaylist: function ( playlist )
  {
    if ( playlist )
    {
      this.playlist = playlist;
    }
  },
  
  SetVideo: function ( video )
  {
    if ( video )
    {
      this.video = video;
    }
  },
  
  SetVideoList: function ( list )
  {
    if ( list )
    {
      this.videolist = list;
    }
  },
  
  SetVideoListFeatured: function ( video )
  {
    if ( video )
    {
      this.videolistfeat = video;
    }
  },

  SetContainers: function ( containers )
  {
    if ( typeof containers === 'object' )
    {
      if ( typeof containers.player !== 'undefined' && containers.player )
      {
        this.containers.player = containers.player;
      }

      if ( typeof containers.ad !== 'undefined' && containers.ad )
      {
        this.containers.ad = containers.ad;
      }
    }    
  },

  SetPlayerContainer: function ( container )
  {
    if ( typeof container !== 'undefined' && container )
    {
      this.containers.player = container;
    }    
  },

  SetAdContainer: function ( container )
  {
    if ( typeof container !== 'undefined' && container )
    {
      this.containers.ad = container;
    }    
  },

  SetAdServer: function ( server )
  {
    if ( server )
    {
      this.adserver = server;
    }
  },
  
  SetAdTag: function ( adtag )
  {
    if ( adtag )
    {
      this.adtag = adtag;
    }

  },
  
  SetCuePoint: function ( cuepoint )
  {
    if ( cuepoint )
    {
      this.cuepoint = cuepoint;
    }

  },
  
  SetBigboxFreq: function ( freq )
  {
    if ( freq )
    {
      this.bigboxfreq = freq;
    }

  },

  SetPrerollFreq: function ( freq )
  {
    if ( freq )
    {
      this.prerollfreq = freq;
    }

  },
	
	ActivateSmoothing: function ( ) {
    this.smoothing = 'true';
	},
	
	SetAutoStart: function ( autostart ) 
	{
    if ( typeof autostart == 'boolean' )
    {
      if ( autostart === true )
      {
        this.autostart = 'true';
      }
      else
      {
        this.autostart = 'false';
      }
    }
    else if ( typeof autostart == 'string' )
    {
      if ( autostart === 'true' )
      {
        this.autostart = 'true';
      }
      else
      {
        this.autostart = 'false';
      }     
    }
	},
  
  InitAd: function ()
  {
    if ( this.adtag )
    {
      BigBoxAd = Ad(this.containers.ad, this.adtag, this.bigboxfreq);
      BigBoxAdContainer = this.containers.ad;
    }
  },

  GeneratePlayer: function ()
  {
    if ( this.debug )
    {
      Log('Generating Player');
    }
    
    experienceId = this.experienceId; 
    var container = jQuery(this.containers.player);

    if ( container.length > 0 )
    {     
      var output =     
        '<object id="'+this.experienceId+'" class="BrightcoveExperience">'+
        '  <param name="bgcolor" value="'+this.style.bgcolor+'" />'+
        '  <param name="width" value="'+this.style.width+'" />'+
        '  <param name="height" value="'+this.style.height+'" />'+
        '  <param name="publisherID" value="'+this.publisher+'"/>'+
        '  <param name="playerID" value="'+this.player+'" />'+
        '  <param name="isVid" value="true" />'+
        '  <param name="isUI" value="true" />'+
	 			'  <param name="dynamicStreaming" value="true" />' + 
        '  <param name="wmode" value="transparent" />';

      if ( typeof this.autostart != 'undefined' )
      {
        output += '  <param name="autoStart" value="' + this.autostart + '" />';
      }
			
			if( this.smoothing ) {
        output += '<param name="videoSmoothing" value="true" />';
			}
        
      if ( this.video )
      {
        output += '  <param name="@videoPlayer" value="'+this.video+'" />';
      }
        
      if ( this.videolist )
      {
        output += '  <param name="@videoList" value="'+this.videolist+'" />';
      }
      
      if ( this.videolistfeat )
      {
        output += '  <param name="@videoList.featured" value="'+this.videolistfeat+'" />';
      }
      
      if ( this.playlist )
      {
        output += '  <param name="@playlistTabs" value="'+this.playlist+'" />';
      }
        
      if ( this.adserver )
      {
        output += '  <param name="adServerURL" value="'+this.adserver+'" />';
      }
        
      output += '</object>';

      container.empty().html(output);

      experienceId = this.experienceId;

      this.InitAd();

      return true;
    }

    return false;
  },
  
  Debug: function ( level )
  {
    if ( !level )
    {
      level = 1;
    }
    
    this.debug = level;
    bc_debug = level;
  }
  
};


/**
 * Creates a new Ad object which handles the synced banner and basic 300x250
 * unit next to the player.
 * 
 * @classDescription Creates an ad object with the basic ad tag to be used.
 *                   Redraws the iframe with that ad tag as often as the class's
 *                   interval specifies. If a synced banner exists (associated
 *                   with a video ad), then the redrawing of the iframe won't
 *                   occur.
 * @param {pString}
 *          pAdTagURL ad tag to be used when there's just a regular 300x250 (not
 *          a synced banner).
 * @return {Object} Returns the current Ad object.
 */
function Ad( container, url, interval )
{
  this.url = url;
  this.container = container;
  
  if ( interval )
  {
    this.interval = interval;
  }
  else
  {
    this.interval = 30; // seconds
  }
  
  this.fullscreen = false;
  this.syncedBanner = false;
  this.timeout;
  this.params = {size: 'sz=300x250', adkeys: ''};
	this.redrawCount = 0;

  /**
   * Creates an iFrame with the ad tag as it's source, and uses the DOM API to
   * add it to the page
   * 
   * @method
   * @param {String}
   *          pInsertionPoint The id of the HTML element where the ad should be
   *          inserted.
   * @param {String}
   *          pURL The ad tag URL to use
   */
  createAd = function( container, url )
  {  
    if ( bc_currentVideo.adKeys )
    {
      this.params.adkeys = bc_currentVideo.adKeys;
    }
    else
    {
      this.params.adkeys = '';
    }
    
    if ( bc_debug )
    {
      Log('ad keys: '+bc_currentVideo.adKeys);
    }
    
    // add params to url
    jQuery.each(this.params, function(i,val) {
      
      if ( val != '' )
      {
        url += val+';';
      }
      
    });

    // add cache bustin random number to url
    url += 'ord='+(Math.random()*10000000000000000)+'?';
    
    try
    {
      if ( bc_debug == 2 )
      {
        Log('calling bigbox ad url: '+url);  
      }
      
      var iframeElem = document.createElement('iframe');
      iframeElem.setAttribute('width', '300');
      iframeElem.setAttribute('height', '250');
      iframeElem.setAttribute('scrolling', 'no');
      iframeElem.setAttribute('frameborder', '0');
      iframeElem.setAttribute('frameBorder', '0');
      iframeElem.setAttribute('src',url);
      
      jQuery(container).empty().html(iframeElem);      
    }
    catch( e )
    {
      if ( bc_debug == 2 )
      {
        Log('Could not create the big box ad. Error: '+e);
      }
      
      return false;
    }
    
    return true;
    
  };
  
  /**
   * If the video is not in fullscreen and there's currently no synced banner,
   * the createAd() method is called again and a timeout is set to call
   * redrawAd() again after the class's interval.
   * 
   * @method
   */
  redrawAd = function()
  {
		if(bc_debug) {
			Log('Redraw Ad : Get Synched Banner : ' + this.getSyncedBanner());
		}
    if ( !this.getFullScreen() && (!this.getSyncedBanner() || this.redrawCount > 1) )
    {
      this.createAd(this.container,this.url);
		}
		
		this.redrawCount++;

  };
  
  /**
   * @method
   * @return {Boolean} Whether or not the player is currently in fullscreen mode
   */
  getFullScreen = function()
  {
    return this.fullscreen;
  };
  
  /**
   * @method
   * @param {Boolean}
   *          Sets whether or not the player is currently in fullscreen mode
   */
  setFullScreen = function(pToggle)
  {
    if(typeof pToggle == 'boolean') this.fullscreen = pToggle;
  };
  
  /**
   * @method
   * @param {Boolean}
   *          Sets whether or not a synced banner is currently on the page
   */
  setSyncedBanner = function ( pToggle )
  {  
    if ( typeof pToggle == 'boolean' ) 
    {
      this.syncedBanner = pToggle;
    }
  };
  
  /**
   * @method
   * @return {Boolean} Whether or not there's currently a synced banner on the
   *         page
   */
  getSyncedBanner = function()
  {
    return this.syncedBanner;
  };
  
  return this;
}


var _brightcoveAd = new Object();
var _BigBoxAds = new Object();

/**
 * Takes care of parsing the XML that comes back from the ad server, building
 * the ad object, and displaying the ads in both the player and on the page. It
 * should be noted that the ad XML that comes back from the ad server needs to
 * be one of the supported Rich Media templates that Brightcove distributes for
 * use with DFP and other ad serving platforms.
 * 
 * @param {String}
 *            pXML The XML string that gets returned from the ad server. Needs
 *            to be one of the templates supported by Brightcove.
 * @param {Object}
 *            pOptions An object that contains options for further
 *            customization. By default, this function will render the expanded
 *            banner (eg type: "expandedBanner") and also write out the banner
 *            to a div with the id of "expandedBanner" (eg writeTo:
 *            "expandedBanner"). For the type option, you can also choose
 *            "collapsedBanner". For the writeTo option, a user can specify the
 *            ID of any element they'd like.
 */

function ExternalAd(pAdObject, pOptions)
{  
  if (pOptions) 
  {
    _brightcoveAd.expandedId = (pOptions.expandedId) ? pOptions.expandedId : "expandedBanner";
    _brightcoveAd.collapsedId = (pOptions.collapsedId) ? pOptions.collapsedId : "collapsedBanner";
    _brightcoveAd.type = (pOptions.type) ? pOptions.type : "expandedBanner";
  }
  else
  {
    _brightcoveAd.expandedId = "expandedBanner";
    _brightcoveAd.collapsedId = "collapsedBanner";
    _brightcoveAd.type = "expandedBanner";
  }
  
  /**
   * Parses the XML from the ad server 
   * @param {Object} pXML The XML returned from the ad server.
   */
  this.parseAd = function( pAdObject )
  {
    // check for basic ad xml structure
    if ( pAdObject.ad.indexOf("<SynchedBanner") === -1 ) 
    {
      if ( bc_debug )
      {
        Log('bad preroll ad');
      }

      return false;
    }
      
    if ( window.ActiveXObject )
    {
      try
      {
        // parses the XML for IE browsers
        this.adXML = new ActiveXObject("Microsoft.XMLDOM");
        this.adXML.async = false;
        this.adXML.loadXML(pAdObject.ad);
      }
      catch ( e )
      {
        if ( bc_debug )
        {
          Log('loadXML Error');
          Log(e);
        }

        return false;
      }

    }
    else if ( window.XMLHttpRequest )
    {
      try
      {
        this.adXML = (new DOMParser()).parseFromString(pAdObject.ad, "text/xml"); 
      }
      catch ( e )
      {
        if ( bc_debug )
        {
          Log('DOMParser Error');
          Log(e);
        }

        return false;
      }
    }

    return true;
  };

  /**
   * Builds the ad object
   * 
   */
  this.buildAd = function()
  {  
    adXML = this.adXML;

    var ad = new Object();
    ad.type = "videoAd";
    
    var nodeItems = adXML.firstChild.childNodes.length;
    var currentNode = adXML.firstChild.firstChild;
    
    // get the root node attributes
    ad.duration = (adXML.firstChild.getAttribute("duration") !== "") ? Number(adXML.firstChild.getAttribute("duration")) : 15;
    if(adXML.firstChild.getAttribute("trackStartURLs") !== "") ad.trackStartURLs = adXML.firstChild.getAttribute("trackStartURLs").split(",");
    if(adXML.firstChild.getAttribute("trackMidURLs") !== "") ad.trackMidURLs = adXML.firstChild.getAttribute("trackMidURLs").split(",");
    if(adXML.firstChild.getAttribute("trackEndURLs") !== "") ad.trackEndURLs = adXML.firstChild.getAttribute("trackEndURLs").split(",");
    if(adXML.firstChild.getAttribute("trackPointURLs") && (adXML.firstChild.getAttribute("trackPointURLs") !== "")) ad.trackPointURLs = adXML.firstChild.getAttribute("trackPointURLs").split(",");
    ad.trackPointTime = (adXML.firstChild.getAttribute("trackPointTime") && (adXML.firstChild.getAttribute("trackPointTime") !== "")) ? Number(adXML.firstChild.getAttribute("trackPointTime")) : 0;
  
    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.firstChild )
      {
        if ( currentNode.nodeName == "videoURL" )
        {  
          ad.videoURL = currentNode.firstChild.nodeValue;
        }
        else if ( currentNode.nodeName == "videoClickURL" ) 
        {
          ad.videoClickURL = currentNode.firstChild.nodeValue;
        }
        else if ( currentNode.nodeName == "expandedBannerURL" )
        {
          _BigBoxAds.expandedBannerURL = currentNode.firstChild.nodeValue;
        }
        else if ( currentNode.nodeName == "expandedBannerClickURL" )
        {
          _BigBoxAds.expandedBannerClickURL = currentNode.firstChild.nodeValue;
        }
        else if ( currentNode.nodeName == "collapsedBannerURL" )
        {
          _BigBoxAds.collapsedBannerURL = currentNode.firstChild.nodeValue;
        }
        else if ( currentNode.nodeName == "collapsedBannerClickURL" )
        {
          _BigBoxAds.collapsedBannerClickURL = currentNode.firstChild.nodeValue;
        }
      }

      currentNode = currentNode.nextSibling;
    }
    
    if ( i == 0 )
    {
      return false;
    }
    else
    {
      return ad;
    }
  };
  
  this.createSwf = function(pURL, pClickThrough, pId)
  {
    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="'+pId+'" align="middle">\n';
    objectTag += '\t<param name="allowScriptAccess" value="always" />\n';
    objectTag += '\t<param name="movie" value="' + pURL + '" />\n';
    objectTag += '\t<param name="quality" value="high" />\n';
    objectTag += '\t<param name="bgcolor" value="#ffffff" />\n';
    objectTag += '\t<param name="wmode" value="transparent" />\n'; 
    objectTag += '\t<param name="FlashVars" value="clickTag=' + pClickThrough + '" />\n';
    objectTag += '\t<embed src="' + pURL + '" quality="high" bgcolor="#ffffff" width="300" height="250" name="expandedBanner" align="middle" allowScriptAccess="always" wmode="transparent" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" FlashVars="clickTag='+pClickThrough+'" />\n';
    objectTag += '</object>\n';
    
    if(document.getElementById(pId)) document.getElementById(pId).innerHTML = objectTag;
  };
  
  this.createImage = function(pURL, pClickThrough, pId)
  {
    if(document.getElementById(pId)) document.getElementById(pId).innerHTML = "<a href='" + pClickThrough + "' target='_blank' ><img src='" + pURL + "' /></a>\n";
  };
  
  /**
   * Writes the banner out to the page, and determines wheter or not it's a swf or regular image so that the correct tags are written to the page.
   * @param {Object} pAd The ad object containing all of the information to display an ad in the player and render an ad on the page.
   */
  this.createBanner = function(pAd)
  {
    var externalAds = {};
    
    if ( (_brightcoveAd.type == "expandedBanner" || _brightcoveAd.type == "both") && pAd.expandedBannerURL )
    {
      externalAds["expandedBanner"] = {clickURL: pAd.expandedBannerClickURL, srcURL: pAd.expandedBannerURL, id: _brightcoveAd.expandedId, type: "expandedBanner"};
    }
    
    if ( (_brightcoveAd.type == "collapsedBanner" || _brightcoveAd.type == "both") && pAd.collapsedBannerURL )
    {
      externalAds["collapsedBanner"] = {clickURL: pAd.collapsedBannerClickURL, srcURL: pAd.collapsedBannerURL, id: _brightcoveAd.collapsedId, type: "collapsedBanner"};
    }

    for ( var i in externalAds )
    {
      var banner = externalAds[i];

      var iframeElem = document.createElement('iframe');
      iframeElem.setAttribute('width', '300');
      iframeElem.setAttribute('height', '250');
      iframeElem.setAttribute('scrolling', 'no');
      iframeElem.setAttribute('frameborder', '0');
      iframeElem.setAttribute('frameBorder', '0');
      iframeElem.setAttribute('src', banner.srcURL);
      
      try
      {
        jQuery(banner.id).empty().html(iframeElem);
      }
      catch( e )
      {
        Log("Couldn't create the big box ad.");
        Log(e);
        return false;
      }
    }

    return true;
  };

  this.recover = function()
  {
    bc_advertising.resumeAfterExternalAd();
    BigBoxAd.setSyncedBanner(false);
  };
  
  if ( this.parseAd(pAdObject) )
  {
    var ad = this.buildAd();

    if ( typeof ad == 'object' && this.createBanner(_BigBoxAds) )
    {
      BigBoxAd.setSyncedBanner(true);
      bc_advertising.showAd(ad);
    }
    else
    {
      this.recover();
    }
  }
  else
  {
    this.recover();
  }
}

/**
* Cookie read and write function.
* @param name
* @param value
* @param options
* @return
*/

function cookie(name, value, options) 
{
  if ( typeof value != 'undefined') // name and value given, set cookie
  { 
    options = options || {};
    if ( value === null ) 
    {
      value = '';
      options.expires = -1;
    }
   
    var expires = '';
   
    if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) 
    {
      var date;
      if ( typeof options.expires == 'number' ) 
      {
        date = new Date();
        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
      } 
      else 
      {
        date = options.expires;
      }
      expires = '; expires=' + date.toUTCString(); 
    }
   
    /** 
    * CAUTION: Needed to parenthesize options.path and options.domain
    * in the following expressions, otherwise they evaluate to undefined
    * in the packed version for some reason...
    */
    var path = options.path ? '; path=' + (options.path) : '';
    var domain = options.domain ? '; domain=' + (options.domain) : '';
    var secure = options.secure ? '; secure' : '';
    document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
  } 
  else // only name given, get cookie
  { 
    var cookieValue = null;
    if (document.cookie && document.cookie != '') 
    {
      var cookies = document.cookie.split(';');
      for ( var i = 0; i < cookies.length; i++ ) 
      {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) == (name + '=')) 
        {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
   
    return cookieValue;
  }
}

function Log ( mixed )
{
  if ( typeof console !== 'undefined' )
  {
    if ( typeof mixed !== 'object' || typeof mixed !== 'boolean' )
    {
      try { console.info(mixed); } catch (e) { alert(mixed); }
    }
    else
    {
      try { console.dir(mixed); } catch (e) { }
    }
  }
  
  return true;
}

$(window).unload(function () 
{ 
  if ( typeof bc_video !== 'undefined' )
  {
    if ( bc_video.getVolume() != bc_playerVolume )
    {
      bc_playerVolume = bc_video.getVolume();
      setVolumePreference(bc_playerVolume);
    }
  }
      
  setUserVideoCount(bc_user_video_count);
});

