var anv_mcm_objects = new Array();

function anv_pl_def()
{
}

anv_pl_def.prototype =
{
    analytics_js_url : 'http://cdn-download.mcm.univision.com/player/scripts/anvanalytics.js',
    swfobject_js_url : 'http://cdn-download.mcm.univision.com/player/scripts/swfobject.js',
	player_url : 'http://cdn-download.mcm.univision.com/player/plugins/anvatoplayer.osmf.1.5.swf',	
	skin_url : 'http://cdn-download.mcm.univision.com/player/assets/univision.xml',
	mcm_vid_url : 'http://vmscdn-download.s3.amazonaws.com/videos_mcm/',
	video : null,
	plugins : {
	   analytics : { enable : 'true', 
	                 tracker : 15, 
	                 url: 'http://cdn-download.mcm.univision.com/player/plugins/anvatoanalytics.osmf.plugin.1.5.swf', 
	                 debug : 'false',
	                 uim_channelid : null
	                },
	   mcm : { enable : 'true', 
	           url : 'http://cdn-download.mcm.univision.com/player/plugins/anvatomcm.osmf.plugin.1.5.swf',
	           id : null,
	           cdn : 'Akamai'
	         },
	   freewheel : { enable : 'true', 
	        	     account: 'univision_live', 
	        	     url: 'http://cdn-download.mcm.univision.com/player/plugins/anvatofreewheel.osmf.plugin.1.5.swf',
 	                 channelid : null,
	                 channel : null,
	                 subchannel : null,
	                 section : null,
	        	     debug : 'false'
	        	   },
	   uimads : { enable : 'true', 
	        	  url : 'http://cdn-download.mcm.univision.com/player/plugins/anvatouimads.osmf.plugin.1.5.swf' 
	        	},
	   uimtracker : { enable : 'true', 
		              url : 'http://cdn-download.mcm.univision.com/player/plugins/anvatouimtracker.osmf.plugin.1.5.swf', 
		              channelid : null,
	                  channel : null,
	                  subchannel : null,
	                  section : null,
	                  requesturl : 'http://archivo.univision.com/content/mediaTracker.jhtml',
	                  debug : 'false'
	                },
	   qos : { enable : 'true', 
	           url : 'http://cdn-download.mcm.univision.com/player/plugins/anvato.qos.plugin.1.0.swf' 
	         }, 
	   tve: { enable : 'true', 
	          url : 'http://cdn-download.mcm.univision.com/player/plugins/anvato.tve.plugin.1.0.swf' 
	        },
	   akamaihd: { enable : 'true'
	        },
       omniture: { enable: 'true',
                   url: 'http://cdn-download.mcm.univision.com/player/plugins/anvatoomniture.plugin.1.0.swf',
                   account: 'univisionglobalprod:univisionportalprod',
                   debug : 'false'
	              }
    },
    
    // Default plugin list
    plugin_list : ['analytics','freewheel', 'uimtracker','omniture'],
	cdn : "Akamai",
	player_width : 640,
    player_height : 360,
	player_div : null,
	playlist_url : null,
	
	// Always enable auto switch
	player_id : 'anvato_player',
	autoSwitchQuality : "true",
    autoHideControlBar: 'true',
    backgroundColor: "0x000000",
    autoPlay : "true",
    full_screen : 'true',
	
    //Try to load JS file only once.
    swfobject_js_tried : false,
    iOS_analytics_js_tried : false,
    
	// Display log related variables
	log_div : null,
	logs : "",
    logcnt : 0,
    
    // Parameter setting function. Assumption is that this will be only used
    // for simple parameter settings, like width, height.
    setParams : function(param_obj)
    {
		for(param in param_obj)
		{
			this[param] = param_obj[param];
		}
    },
    
    // Main player load function.
    loadPlayer : function(video_id) 
    {
    	/*
    	 * Check whether a div is provided. If not, create a new one.
    	 */
    	if (this.player_div == null)
    	{
    		/*
    		 * Create a div.
    		 */
    		this.player_div = 'anv_player_div_' + (new Date()).getTime();
    		document.write('<div id="'+this.player_div+'" width="'+this.player_width+'" height="'+this.player_height+'"></div>');
    	}
    	
    	// Is this for a specific MCM video or a generic video display?
        if (/^\d+$/.test('' + video_id))
        {
        	// Store this object in a global array
        	anv_mcm_objects[video_id] = this;
        	
        	// Initiate the player for a specific MCM video.
        	loadAnvatoJS(this.mcm_vid_url + video_id + '.js');
        	
        	return;
        }
        
        if ((typeof(video_id) == 'object') && (typeof(video_id.url) == 'string'))
        {
        	// Assume all the video information is provided as an object.
        	this.video = video_id;
        }
        else if (typeof(video_id) == 'string')
        {
        	// Assume only a url is provided.
        	this.video = { 
        		    title : '',
        		    url : video_id
        	    };
        }

        // Check whether the video object is set it up.
        if (this.video && (typeof(this.video.url) == 'string'))
        {
            if (!this.video.title)
            {
            	this.video.title = '';
            }
        	this.invokePlatformPlayer();
        }
    },
    
    /*
     * Load HTML5 vs flash player
     */
    invokePlatformPlayer: function()
    {
    	if ((navigator.userAgent.match(/iPhone/i)) || 
    	    (navigator.userAgent.match(/iPod/i)) || 
    	    (navigator.userAgent.match(/iPad/i)) )
    	{
    		this.loadiOSPlayer();
    	}
    	else
    	{
    		this.loadFlashPlayer();
    	}
    },
    
    /*
     * Load the flash player
     */
    loadFlashPlayer: function()
    {
    	/*
    	 * Check dependency for swfobject
    	 */
    	if (typeof swfobject == 'undefined')
    	{
    		if (!this.swfobject_js_tried)
    		{
    			/*
    			 * Load the swfobject.js. But do it only once.
    			 */
    			loadAnvatoJS(this.swfobject_js_url);
    			this.swfobject_js_tried = true;
    		}
    		
    		/*
    		 * Check load status of swfobject.js at every 500msec, until it is loaded.
    		 */
    		var self = this;
    		var t=setTimeout(function(){ self.loadFlashPlayer(); },100);
    		return;
    	}
    	
    	/*
    	 * Check required flash version
    	 */
    	if( !swfobject.hasFlashPlayerVersion('10.0.0') )
        {
    		var s = '<p><a href="http://get.adobe.com/flashplayer/">' +
    		        '<img src="http://u.univision.com/contentroot/uol/art/systemimages/v2/videos/video_player_alt_image.jpg" ' +
    			    'alt="Get Adobe Flash player" width="' + this.player_width + '" height="' + this.player_height + 
    			    '"/></a></p>';
            this.setAnvatoPlayerDivContent(s);
            return;
        }
    	
    	this.logs ="";
    	this.logcnt = 0;

    	// Set the flash variable defaults
    	var flashvars = this.setFlashVars();
    	var params = {
    			quality: "high",
    			allowfullscreen: this.full_screen,
    			allowscriptaccess: "always",
    			wmode : "opaque"
    	};
    	var attributes= {};

    	swfobject.embedSWF(this.player_url, this.player_div, this.player_width, this.player_height, "10.0.0.0", "player/expressInstall.swf", flashvars, params, attributes);
    },

    /*
     * Create flash player variables
     */
    setFlashVars: function()
    {
    	var fv = {
    			id : this.player_id,
    			configuration: this.skin_url,
    		    autoHideControlBar: this.autoHideControlBar,
    		    backgroundColor: this.backgroundColor,
    		    autoPlay: this.autoPlay,
    		    autoSwitchQuality: this.autoSwitchQuality
    		};

    	var p = 'name=' + this.player_div + ',callback.load=onAnvatoPlayerLoad,callback.ready=onAnvatoPlayerReady,callback.event=onAnvatoPlayerEvent,callback.switch=onAnvatoPlayerSwitch';
    		
    	if (this.playlist_url)
    	{
    		p = p +',playlist='+this.playlist_url;
    	}
    				
    	if (this.video.upload_id)
    	{
    		// For mcm plugin set the video id.
    		this.plugins.mcm.id = this.video.upload_id;
    		p = 'video_id=' + this.video.upload_id + ',cdn=' + this.cdn + ',' + p;
    		
    		// If the input is live feed coming from Akamai HD, then seamlessly load the AkamaiHD plugin.
    		if (this.video.video_type==2)
    		{
    			var load_akamai_hd = true;
    			
    			// Iterate though the url list and see whether they include 'http' protocol and includes akamaihd in the url.
    	        for ( var i=0;i<this.video.published_urls.length;i++ )
    	        {
    	        	var pub_url = this.video.published_urls[i];
    	        	if (pub_url.embed_url.indexOf('http://') == -1 || pub_url.embed_url.indexOf('akamaihd.net') == -1)
    	        	{
    	        		// This url is not for akamai hd. Hence, do not load the Akamai HD plugin.
    	        		load_akamai_hd = false;
    	        		break;
    	        	}
    	        }
    	        
    	        if (load_akamai_hd)
    	        {
    	        	this.plugin_list.push('akamaihd');
    	        }
    		}
    	}
    	else if (this.video.url)
    	{
    		var s = 'url='+this.video.url+',title='+this.video.title;
    		if (this.video.id)
    		{
    			s = s + ',id='+this.video.id;
    		}
    		
    		if (this.video.live)
    		{
    			s = s + ',live='+this.video.live;
    		}
    				
    		fv['video'] = s;
    	}
    	
    	fv['player'] = p;
    	
    	// Plugin configuration
    	for(id in this.plugin_list)
    	{
    		var plugin = this.plugin_list[id];
    		
    		var s = 'type=plugin,name=' + plugin;
    		
    		for(prop in this.plugins[plugin])
    		{
    			if (this.plugins[plugin][prop] == null)
    			{
    				continue;
    			}
    			
    			if (prop == 'debug')
    			{
    				s = s + ',debug.enable=';
    			}
    			else
    			{
    			   s = s + ',' + prop + '=';
    			}
    			
    			s = s + this.plugins[plugin][prop];
    		}
    		
    		fv[plugin] = s;
    	}
    						
    	return fv;
    },
    
    loadiOSPlayer: function() 
    {
    	var data = this.video;

    	var video_url = '';
    	var thumbnail = '';
    	var mimeType = 'video/mp4'; 

    	if (data.url && data.url.indexOf('http://') != -1)
    	{
    		// Live video player
    		video_url = data.url;

    		if (data.thumbnail)
    		{
    			thumbnail = data.thumbnail;
    		}
    	}
    	else if (data.published_urls)
    	{
    		// Set the title field
    		this.video.title = data.def_title;
    		thumbnail = data.src_image_url;

    		// Player for a specific video
    		// Check whether there is any m3u8 url, otherwise select the highest mp4 bitrate for iPad
    		var bitrate = 0;
    		for ( var i=0;i<data.published_urls.length;i++ )
    		{
    			var pub_url = data.published_urls[i];
    			if ((pub_url.embed_url.indexOf('http://') != -1) && 
    			    (pub_url.format == 'm3u8' || (pub_url.format == 'mp4' && pub_url.kbps > bitrate)))
    			{
    				video_url = pub_url.embed_url;
    				bitrate = pub_url.kbps;
    				
    				/*
    				 * If the format is m3u8, search no more.
    				 */
    				if (pub_url.format == 'm3u8')
    				{
    					mimeType = 'application/x-mpegURL';
    					break;
    				}
    				
    			}
    		}
    	}

    	if (video_url == '')
    	{
    		// No video to display
    		// TODO: Show a nice message window.
    		return;
    	}

    	var s = '<video id="'+this.player_id+'" style="width:'+this.player_width+'px;height:'+this.player_height+'px" ';

    	if (thumbnail != '')
    	{
    		s = s + 'poster="' + thumbnail + '" ';
    	}

    	s = s+ 'controls preload autoplay><source src="'+video_url+'" type="'+mimeType+'" /></video>';

    	// Insert the native player into the player div
    	this.setAnvatoPlayerDivContent(s);

    	// Now locate the player object
    	var ipad_player = document.getElementById(this.player_id);

    	// Initialize the player.
    	ipad_player.load();

    	// Start play
    	//ipad_player.play();

    	// Set the selected video url
    	this.video.url = video_url;

    	//If JS analytics is not loaded, dynamically load the JS file.
   		this.loadiOSAnalytics();
    },

    loadiOSAnalytics: function()
    {
    	if (typeof window.AnvAnalytics == 'undefined')
    	{
    		if (!this.iOS_analytics_js_tried)
    		{
    			/*
    			 * Load the Anvato iOS analytics JS file. But do it only once.
    			 */
    			loadAnvatoJS(this.analytics_js_url);
    			this.iOS_analytics_js_tried = true;
    		}
    		
    		/*
    		 * Check load status of swfobject.js at every 500msec, until it is loaded.
    		 */
    		var self = this;
    		var t=setTimeout(function(){ self.loadiOSAnalytics(); },100);
    		return;
    	}
    	
    	// JS has been loaded.
    	var ipad_analytics = new AnvAnalytics (this.player_id, this.plugins.analytics.tracker, this.video.title, this.video.url, this.log_div );
    },

    setAnvatoPlayerDivContent: function (s)
    {
        var player_div = document.getElementById(this.player_div);
        player_div.innerHTML = s;
    },
    
    // Callback functions
    player_event : function(name,event,data) { },
    player_load : function(name, video_id) { return this.video; },
    player_ready : function(name) { },
    plugin_ready : function(name,ver) { },
    display_log : function(name,data)
    {			
    	this.logcnt = this.logcnt+1;
    	var c = '['+name+'] ' + data;
    	this.logs = this.logcnt+'. ' + c + '<br>' + this.logs;
    	document.getElementById(this.log_div).innerHTML = this.logs;	
    },
    bitrate_switch : function(bitrate) { },
    
    resize : function(width,height)
    {
    	//alert(width+':'+height);

    	var p = document.getElementById(this.player_div);

    	p.resizeplayer(width,height);
    	this.player_width = width;
    	this.player_height = height;
    	p.width = width;
    	p.height = height;
    	
		if (typeof window.cb_AnvatoPlayerResize == 'function') 
		{
			// function exists, so we can now call it
			cb_AnvatoPlayerResize(this.player_id,width,height);
		}
    }    
};

/*
 * There is always one default object.
 */
var anv_pl_cfg = new anv_pl_def();

function anvatoVideoJSONLoaded ( data )
{
    var pl_cfg = anv_mcm_objects[data.upload_id];
    
	// Store the video data
	pl_cfg.video = data;

	pl_cfg.invokePlatformPlayer();
}			

function loadAnvatoJS(anv_js) 
{
	var body = document.getElementsByTagName("body")[0];         
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.src = anv_js;
	body.appendChild(newScript);
}

// Event handler functions
function onAnvatoPlayerEvent(name,event,data)
{
	anv_pl_cfg.player_event(name, event, data);
}

function onAnvatoPlayerLoad(name, video_id)
{
    var pl_cfg = anv_mcm_objects[video_id];
    
	return pl_cfg.player_load(name, video_id);
}
	
function onAnvatoPluginReady(name,ver)
{
    anv_pl_cfg.plugin_ready(name,ver);
}

function onAnvatoPlayerReady(name)
{
    anv_pl_cfg.player_ready(name);
}

function onAnvatoPlayerSwitch(bitrate)
{
	anv_pl_cfg.bitrate_switch(bitrate);
}

function onAnvatoDisplayLogs(name,data)
{			
	anv_pl_cfg.logcnt = anv_pl_cfg.logcnt+1;
	var c = '['+name+'] ' + data;
	anv_pl_cfg.logs = anv_pl_cfg.logcnt+'. ' + c + '<br>' + anv_pl_cfg.logs;
	document.getElementById(anv_pl_cfg.log_div).innerHTML = anv_pl_cfg.logs;	
}

function onAnvPlayerResize(width,height)
{
	anv_pl_cfg.resize(width,height);
}

function loadAnvatoPlayer(video_id)
{
	// Call external configuration custumization, if a function is defined.
	try
	{
		if(typeof window.setAnvatoPlayerParams == 'function') 
		{
			// function exists, so we can now call it
			setAnvatoPlayerParams();
		}
	}
	catch(e) {}

	/*
	 * Use the default object
	 */
	return anv_pl_cfg.loadPlayer(video_id);
}

