/**
 * Video Controller
 * @projectDescription Methods for Brightcove Flash video player.
 * @author adam.housman@rga.com
 * @require kudos.js, jquery-1.3.2.min.js
 * @version 1.0 - Video Player v1.0 (Brightcove Production Player ID - 110154046001)
 */
var VideoController = {}, VC = VideoController;

/**
 * Reference to kudos javascript library for interacting with Brightcove Media API
 * @doc http://kudos-js.com/
 */
VC.kudos = kudos;

/**
 * Access tokens for Brightcove Media API
 * Currently using read-only token w/ URL access:
 * Read-only w/ URL Access		XW8iMHngLhlvnbRQr_72TwsKRQi_evL6EXG1eFgIikgkJ3pZ-I7Xcw..
 * Read-only					XW8iMHngLhl2_7Piu0KKMcR7DBDAK1zuy0aQ2CNeMCDy88m8muRXeQ..
 *
 * Read tokens, which provide read-only access to your Brightcove Media Library
 * Read tokens with URL access, which enable you to return the paths to the underlying media files.
 * Write tokens, which enable you to create, modify, or delete content in your Brightcove Media Library.
 * @doc http://x.brightcove.com/public/index.php/projects/124/discussions/25232
 */
VC.kudos.token = "XW8iMHngLhlvnbRQr_72TwsKRQi_evL6EXG1eFgIikgkJ3pZ-I7Xcw..";

/**
 * Default Callback method for Media API calls - overwrite this with the approprate method name
 */
VC.kudos.cb = "VideoController.log";

/**
 * NSL App ID for video player
 */
VC.appId = 'nikeosvideoplayer';

/**
 * Array to cache smart playlists. Name is comma-delimited list of tags that make up the smart playlist.
 * NOT CURRENTLY IN USE.
 */
VC.playlist = {};


/**
 * Current video being played
 */
VC.current_video = null;

/**
 * Initialize Brightcove Javascript API components
 */
VC.init = function(id){
  this.player = brightcove.getExperience(id);
  this.MOD_Video_Player = this.player.getModule(APIModules.VIDEO_PLAYER);
  this.MOD_Experience = this.player.getModule(APIModules.EXPERIENCE);
  this.MOD_Content = this.player.getModule(APIModules.CONTENT);
  this.MOD_Social = this.player.getModule(APIModules.SOCIAL);
  this.MOD_Experience.addEventListener(BCExperienceEvent.TEMPLATE_READY, VC.bc_template_ready);
  this.MOD_Experience.addEventListener(BCExperienceEvent.CONTENT_LOAD, VC.bc_content_load);
  this.MOD_Content.addEventListener(BCContentEvent.VIDEO_LOAD, VC.bc_video_load); 
  this.MOD_Video_Player.addEventListener(BCMediaEvent.CHANGE, VC.bc_media_change);
  this.MOD_Video_Player.addEventListener(BCMediaEvent.COMPLETE, onVideoComplete);
}

/**
 * Log - wrapper for console.log
 */
VC.log = function(data){
	if(typeof(console)!="undefined"){ console.log(data); }
};

/**
 * @method create_player	Create a video player SWF
 * @param options
 * @param container_id	DOM id of div to drop the player in
 */
VC.create_player = function(options){
	var HTML = [],
	container_id = options.container_id || 'brightcove_container',
	settings = JQ.extend({
		width         : "908",
		height        : "510",
		bgcolor       : '#FFFFFF',
		wmode         : 'transparent',
		publisherID   : 72451143001,
		videoId       : null,
		'@videoPlayer': null,
		playerID      : 390534381001, 
		isVid         : "true",
		isUI          : "true",
		autoStart     : "false",
		locale        : site_data.platypus_region
	}, options);

	settings.linkBaseURL = this.get_share_link(settings.videoId);

	HTML.push('\n<object id="' + container_id + '" class="BrightcoveExperience">');
	for(var i in settings){
		HTML.push('\n<param name="' + i + '" value="' + settings[i] + '"/>');
	}
 	HTML.push('\n</object>');

	document.getElementById(container_id).innerHTML = HTML.join('');
	brightcove.createExperiences('0', container_id);		
};

/**
 * Storage for tag lists, dynamically assigned to playlist cache in get_playlist
 */
VC.cache_holder = [];

/**
 * Storage for kudos callback functions
 */
VC.cache_playlist = [];

 /**
 * Fetch a playlist using kudos JSONP of all Nike videos with specified tag(s)
 * @param cb	callback method - any functions that require a playlist
 * @param tags	comma delimited list of tags
 * NOT CURRENTLY IN USE.
 */
VC.get_playlist = function(tags,cb){
	tags = tags || 'signature_moves';
	var self = this;
	var obj = {};
	obj[tags] = {};
	this.cache_holder.push(tags);
	this.cache_playlist[this.cache_holder.length-1] = function(data){
		if(data.items[0]){
			self.playlist[tags] = data;
		} else {
			self.playlist[tags] = null;
		}
		cb();
	}
	kudos_callback_index = this.cache_holder.length-1;
	if(typeof(this.playlist[tags]) == 'undefined'){
		VideoController.kudos.get("find_videos_by_tags", {'media_delivery' : 'http', 'or_tags' : tags, 'video_fields' : 'id,name,renditions', 'callback' : 'VC.cache_playlist[' + kudos_callback_index + ']'});
	} else {
		console.log('Using cached response for request for playlist with tag(s) "' + tags + '"');
		cb();
	}
};

/**
 * Create new player with first video in given playlist.
 * NOT CURRENTLY IN USE.
 */
VC.show_first_video = function(playlist){
	var self = this;
	var video_id = null;
	if(typeof(playlist) == 'string'){ //Assume comma-delimited taglist
		if(typeof(self.playlist[playlist])=='undefined'){
			return;
		}
		video_id = self.playlist[playlist].items[0].id;
	} else if(typeof(playlist) == 'object'){
		if(typeof(playlist.items[0].id)=='undefined'){
		  return;
		}
		video_id = playlist.items[0].id;
	}
	VC.create_player({
		'videoId'	: video_id,
		'@videoId'	: video_id
	});
}

/**
 * Get Ratings
 * @param {string} video_id
 * @return Rating object
 */
VC.get_rating_info = function(video_id){
  video_id = video_id || this.current_video.referenceId;
  var pluck_id = 'video:'+video_id;
  JQ.ajax({
    'url': '/nsl/services/rating/get?app=' + VC.appId + '&format=json&entityKey=' + pluck_id,
    'type': 'GET',
    'dataType': 'json',
    success: function(response){
      if(response.serviceResponse.header.success == "true"){
        var data = {
          status  : 'success',
          rating  : response.serviceResponse.body.Rating
        }
      } else {
        var data = {
          status  : 'failure',
          errors  : response.serviceResponse.header.errorCodes
        }
      }
      return data;
    }
  });
}

/**
 * Rate Video - uses NSL/Pluck Ratings service to rate video.
 * @param int rating between 1 and 5
 * @param {string} video_id (defaults to current video id)
 * @return bool
 */

VC.rate_video = function(rating, video_id){
  video_id = video_id || this.current_video.referenceId;
  if(typeof(rating) == 'undefined'){
    return false;
  }
  var pluck_id = 'video:'+video_id;
  var data = 'object={"Rating":{"entityType":"Video","entityKey":"'+pluck_id+'","currentUserRating":"'+rating+'"}}';
  JQ.ajax({
    'url': '/nsl/services/rating/create?app=' + VC.appId + '&format=json',
    'type': 'POST',
    'dataType': 'json',
    'data': data,
    success: function(response){
      if(response.serviceResponse.header.success == "true"){
        return true;
      } else {
        return false;
      }
    }
  });
}

/**
 * Get Share Link
 * @param {string} video_id
 * From BC Docs:
 * Brightcove players published using the standard JavaScript publishing code 
 * automatically listen for bclid and bctid in order to select featured items.
 * If your application is setup in another format, such as ActionScript, you can
 * choose to alter these key names to something compatible with your application.
 * Your application will be responsible for properly setting the featured content.
 */
VC.get_share_link = function(video_id){
	var video_key = "bctid",
		current_url = window.location.href,
		new_link = current_url;
	if(video_id){
		new_link += (window.location.search.length > 0 ? "&" : "?") + video_key + "=" + video_id;
	}
	return(new_link);
}

/**
 * Change the share link in the video's social sharing dialog.
 */
VC.update_share_link = function(video_id){
  var new_link = this.get_share_link(video_id);
  this.MOD_Social.newLink(new_link);
}

/**
 * Brightcove JS API onTemplateReady callback
 */
VC.bc_template_ready = function(e){
  var id = this.current_video.getCurrentVideo().id;
  this.update_share_link(id);
}

/**
 * Brightcove JS API onContentLoaded callback
 */
VC.bc_content_load = function(e){
  VC.current_video = VC.MOD_Video_Player.getCurrentVideo();
  VC.MOD_Video_Player.getMediaAsynch(VC.current_video.id);
}

/**
 * Brightcove JS API onVideoLoad callback
 */
VC.bc_video_load = function(e, ref){
	if ( typeof ref == 'undefined' )
  		this.MOD_Video_Player.loadVideo(e.video.id,'referenceId');
	else 
		this.MOD_Video_Player.loadVideo(e.video.id,'referenceId');
}

/**
 * Brightcove JS API onMediaChange callback
 * Update share link when video changes.
 */
VC.bc_media_change = function(e){
  if(this.MOD_Experience.getReady()){
    this.current_video = VC.MOD_Video_Player.getCurrentVideo();
    var id = VC.current_video.getCurrentVideo().id;
    this.update_share_link(id);
  }
}

/**
* Stop video that is currently playing 
*/
VC.bc_video_stop = function(){
	this.MOD_Video_Player.stop();
}

/**
 * Set up Brightcove Javascript API callback "onTemplateLoaded" to VC init function
 */
var kudos_callback_index;
function onTemplateLoaded(id) {
  VC.init(id);
}

