if ( typeof(console) === 'undefined' ) {
	var console = {}
	console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};
}

// script injector

mvpInjectScript = function(url, scriptId, lookFor, callback, replace) {
	var head = document.getElementsByTagName('head')[0];
	var prevScript = document.getElementById(scriptId);
	
	if ( replace == undefined ) 
		replace = true;	
		
	if ( prevScript && replace ) {
		console.log('previous script is: ' + prevScript + ' and head is ' + head)
		head.removeChild( prevScript );
		prevScript = null;
	}
	if ( !prevScript || !(url == prevScript.src) ) {
		var oScript = document.createElement("script"); 
		oScript.setAttribute("src", url); 
		oScript.setAttribute("id", scriptId); 
		if ( callback ) {
			mvpWaitForLoad(lookFor, callback);
		}
		
		head.appendChild(oScript);
	} else {
		callback();
	}
}

mvpWaitForLoad = function(lookFor, callback) {
	var interval = setInterval(function() {
		if ( eval("typeof " + lookFor) != 'undefined') {
			clearInterval(interval);
			callback();
		}
	}, 50);					
}


// ###################################################################### //
// YuMe companion ads

var companionIds = ['mvp_ad300', 'magnify_video_ad', 'magnify_widget_rect_content', 'mvp_ad_module_item_rect', 'mvp_tool_panel_about_ad300', 'cb_medrect1_div', 'adCompanionBanner'];

locateAdModules = function() {
	var adModuleClasses = ['.mvp_ad_module_item_rect'];
	var candidateAds = new Array();
	adModuleClasses.each( function(className, i) {
		var divs = $$(className);
		if ( divs.length ) {
			var candidate = divs[0];
			candidate.id = "mvp_dynamic_ad_module_" + i;
			candidate.width = "300";
			candidate.height = "250";
			companionIds.push( candidate.id );
		}
	});
	return companionIds;
}
			
buildYumeIframe = function(el) {
	el.style.width = "300px";
	el.style.height = "250px";
	if ( $('magnify_player_continuous_ad') ) {
		$('magnify_player_continuous_ad').style.height = "262px";	
	}
	el.id = 'cb_medrect1_div';
	el.innerHTML = '<iframe name="' + el.id + '_frame" id="cb_medrect1_frame" src="/decor/yume/empty.html" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" topmargin="0" leftmargin="0" allowtransparency="true" width="300" height="250"></iframe>';
}

callYumeAd = function(domainId, adUrl) {
	var yumeCbAdObject1 = new yumeStaticCbAd(); 
	yumeCbAdObject1.setPlayerMediumRectangleCompanionBannerDivSource("cb_medrect1_div"); 
	yumeCbAdObject1.setPlayerAdDomainUrl(adUrl);
	yumeCbAdObject1.setPlayerIframeBannerPlaylist("dynamic_banner_iframe.html?domain=" + domainId);
}
					
loadYumeCompanions = function(domainId, adUrl) {
	locateAdModules().each( function( el, i ) {
		if ( $(el) ) {
			buildYumeIframe($(el));
			callYumeAd(domainId, adUrl);
			throw $break;
		}
	});
}

// ###################################################################### //
// Acudeo companion ads

function displayCompanionBanners(banners) { 
   tmDisplayBanner(banners, "adCompanionBanner", 300, 250); 
   try {
		$f().getPlugin('logoContent').hide();
   } catch(e) {}
} 

function hideCompanionBanners(banners) { 
	if ( standalonePreroll ) {
		try {
			swapClips();
		} catch(e) { return; }
	}
	try {
		$f().getPlugin('logoContent').show();
	} catch(e) {}
	try {
		hideAd();
		//tmHideBanner("adCompanionBanner"); 
	} catch(e) {}
} 
			
buildAcudeoDiv = function(el) {
	el.style.width = "300px";
	el.style.height = "250px";
	el.style.position = "relative";
	if ( $('magnify_player_continuous_ad') ) {
		$('magnify_player_continuous_ad').style.height = "262px";	
	}
	el.update('<img src="/decor/live/indicator.gif" width="16" height="16" border="0" style="position: absolute; top: 117px; left: 142px;" />');
	el.id = 'adCompanionBanner';
	//el.style.visibility = "hidden";
}

loadAcudeoCompanions = function() {
	locateAdModules().each( function( el, i ) {
		if ( $(el) ) {
			buildAcudeoDiv($(el));
			throw $break;
		}
	});
}


 // ###################################################################### //
// Adsense companion ads

buildAdSenseDiv = function(el, publisherId) {


	var adSlot1 = googletag.defineUnit(
		publisherId,
		[300, 250],
		el.id
	);
  	adSlot1.set("backfill", "true");

	// Attach the slot to the companion ads service.
	adSlot1.addService(googletag.companionAds())
	// Attach to the publisher ads service in order to preload the ads.
	adSlot1.addService(googletag.pubads());
	// Enable the ads services.
	googletag.enableServices();
	
	googletag.display(el.id);
}

loadAdsenseCompanions = function(publisherId) {
	locateAdModules().each( function( el, i ) {
		if ( $(el) ) {
			buildAdSenseDiv($(el), publisherId);
			throw $break;
		}
	});
}

// ###################################################################### //
// DART companion ads

buildDartDiv = function(el) {	
	//console.log("displaying companion " + adId + " in " + el.id);
	var adSlot1 = googletag.defineSlot(
		"/nym.video/vvideoplayer",
		[300, 250],
		el.id
	);
  	//adSlot1.set("backfill", "true");

	// Attach the slot to the companion ads service.
	adSlot1.addService(googletag.companionAds())
	// Attach to the publisher ads service in order to preload the ads.
	adSlot1.addService(googletag.pubads());
	// Enable the ads services.
	googletag.enableServices();
	googletag.display(
		"/nym.video/vvideoplayer",
		[300, 250],
		el.id
	);
}
		
buildDartAdFrame = function(el, companionURL) {
	el.style.width = "300px";
	el.style.height = "250px";
	if ( $('magnify_player_continuous_ad') ) {
		$('magnify_player_continuous_ad').style.height = "262px";	
	}
	el.innerHTML = '<iframe name="' + el.id + '_frame" id="dartAdFrame" src="' + companionURL + '" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" topmargin="0" leftmargin="0" allowtransparency="true" width="300" height="250"></iframe>';
}

syncRoadBlock = function(adTag, companionAds) {	
	console.log("calling sync roadblock for tag " + adTag);
	
	if ( companionAds.length > 0 ) {
		locateAdModules().each( function( el, i ) {
			if ( $(el) ) {
				ova.writeCompanion(el, companionAds[0].content);
				throw $break;
			}
		});
	}
}

// ###################################################################### //
// OVA companion ad helper

var ova = new function() {
	this.readHTML = function(companion) {
		return jQuery('#' + companion).html();
	}
	
	this.writeCompanion = function(companion, src) {
		jQuery('#' + companion).writeCompanion(src);
	}
	
	this.writeHTML = function(companion, src) {
		jQuery('#' + companion).writeOriginal(src);
	}
}

// These jQuery functions are trigged from ova class
jQuery.fn.writeCompanion = function(src) {
	// Store jQuery(this) in a variable otherwise it will be out of scope in document.write
	var companionElem = jQuery(this);
	var tmpDocWrite = document.write;
	var tmpDocWriteln = document.writeln;
	document.write = function(arg) { jQuery(companionElem).append(arg); };
	document.writeln = function(arg) { jQuery(companionElem).append(arg) + '\n'; };
	
	// Function to retrieve a new advert from the server.
	jQuery(companionElem).html(jQuery(src));
};

jQuery.fn.writeOriginal = function(src) {
	var companionElem = jQuery(this);
	jQuery(companionElem).html(src);
};


// ###################################################################### //
// Magnify default companion fill
controlDefaultOverlay = function() {
	try {
		hideAd();
	} catch(e) {}
}

buildDefaultIframe = function(el, cid) {
	el.style.width = "300px";
	el.style.height = "250px";
	if ( $('magnify_player_continuous_ad') ) {
		$('magnify_player_continuous_ad').style.height = "262px";	
	}
	el.id = 'magnify_widget_rect_content';
	el.innerHTML = '<iframe name="magnify_widget_rect_frame" id="magnify_widget_rect" src="/embed/player/modules/ad.mason?content_item_cid=' + cid + '&preroll_disabled=1&autoplay=1&loc=magnify_widget_rect_frame" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" topmargin="0" leftmargin="0" allowtransparency="true" width="300" height="250"></iframe>';
	setTimeout(controlDefaultOverlay, 7000);
}

loadDefaultCompanion = function(cid) {
	locateAdModules().each( function( el, i ) {
		if ( $(el) ) {
			buildDefaultIframe($(el), cid);
			throw $break;
		}
	});
}


// ###################################################################### //
// javascript player helpers

var jsHelper = new function() {	
	this.writePlayer = function(id, src) {
		var companionElem = document.getElementById(id);
		var script = document.createElement('script');
		script.src = src;
		companionElem.insert({'after': script});
		var tmpDocWrite = document.write;
		var tmpDocWriteln = document.writeln;
		document.write = function(arg) { document.getElementById(id).innerHTML = arg; };
		document.writeln = function(arg) { document.getElementById(id).innerHTML = arg + '\n'; };
	}
}

// ###################################################################### //

setCookie = function(name, value, expiration) {
	var expirationDate = new Date();
	expirationDate.setTime(expirationDate.getTime() + expiration);
	document.cookie = name + "=" + escape(value) + ( (expiration == null) ? "" : ";path=/;expires=" + expirationDate.toGMTString() );
}
	
getCookie = function(name) {
	if ( document.cookie.length > 0 ) {
		c_start = document.cookie.indexOf(name + "=");
		if ( c_start != -1 )  { 
			c_start = c_start + name.length + 1; 
			c_end = document.cookie.indexOf(";", c_start);
			
			if ( c_end == -1 ) 
				c_end = document.cookie.length;
				
			return unescape( document.cookie.substring(c_start, c_end) );
		} 
	}
	return;
}


// ###################################################################### //

function set_one_different( parent_id, tag_name, active_id, active_class, inactive_class ) {
  var tablist = $( parent_id ).getElementsByTagName( tag_name );
  var nodes = $A( tablist );

  nodes.each( function(node) {
	  node.className = ( node.id == active_id ) ? active_class : inactive_class;
   } );
}

// ###################################################################### //

function tab_activate( tab_id, pane_id ) {
  tabselect( $( tab_id ) ); 
  paneselect( $( pane_id ) );
}

function tabselect(tab) {
  set_one_different( 'tabcontrol1', 'li', tab.id, 'tab-selected', 'tab-unselected' ) 
}

function paneselect(pane) {
  set_one_different( 'panecontrol1', 'li', pane.id, 'pane-selected', 'pane-unselected' ) 
}

// ###################################################################### //

function help_show_tip ( q_el, a_el ) {
	// q_el.src = '/decor/live/help_dark_info.gif';
	var q_pos = Position.cumulativeOffset( q_el );
	var answer_div = $( a_el );
	answer_div.style.left = q_pos[0] - 346 + "px";
	answer_div.style.top = q_pos[1] + 15 + "px";
	answer_div.visualEffect('Appear', { duration: 0.25, queue: 'end' } );
}

function help_hide_tip ( q_el, a_el ) {
	var answer_div = $( a_el );
	answer_div.visualEffect('Fade', { 
		duration: 0.25, queue: 'end'
	} );
	
	// afterFinish: function () { q_el.src = '/decor/live/help_gray_info.gif'; } 
	
}

// ###################################################################### //

var mvp_popup_menu_is_open;

var mvp_moved_popup = [];

function mvp_popup_menu_hide_open () {
	if ( mvp_popup_menu_is_open ) {
		mvp_popup_menu_hideshow( mvp_popup_menu_is_open, 0 );
	}
}

function mvp_popup_menu_hideshow ( menu_id, visible ) {
	var menu_div = $('mvp_popup_menu_area_' + menu_id );
	if ( visible == '-' ) {
		visible = ! menu_div.hasClassName( 'mvp_active' );
	}
	if ( visible ) {
		mvp_popup_menu_hide_open();

		if ( ! mvp_moved_popup[ menu_id ] ) {
			mvp_moved_popup[ menu_id ] = 1;
			document.body.appendChild( menu_div );
			Position.absolutize( menu_div ); 
		}
		var menu_btn = $('mvp_popup_menu_buttton_' + menu_id );
		Position.clone( menu_btn, menu_div, { setWidth: false, setHeight: false, offsetLeft: 10 } ); 
		menu_div.style.width = '140px';
		menu_div.style.height = 'auto';
		
		menu_div.addClassName( 'mvp_active' );
		mvp_popup_menu_is_open = menu_id;
	} else {
		menu_div.removeClassName( 'mvp_active' );
		mvp_popup_menu_is_open = 0;
	}
}

function mvp_popup_menu_add_playlist ( el, cid, title ) {
	if ( el.innerHTML.substring(0, 9) == 'Added to ' ) { 
		window.location.assign( '/account/playlist/view/' + cid );
	} else { 
		new Ajax.Request( el.href, { 
			onSuccess: function (t) { el.innerHTML = 'Added to ' + title }, 
			onFailure: function (t) { el.innerHTML = 'Could not be added' } 
		} ); 
		new Effect.Highlight(el, { 
			duration: 0.5, 
			afterFinish: function() { 
				mvp_popup_menu_hide_open();
			} 
		} ) ; 
		
	} 
}

