/**
 * VideoEgg Player JavaScript
 *
 * Functions for including the VideoEgg Flash player in HTML pages.
 *
 * @version 1.4
 * @changelog
 *	API 1.4 (3/12/07)
 * 		- changed input params to use object instead of growing parameters list
 *      - added skin, config, allowGrabcode, allowEmailShare, allowRecommendations, permalink, clickurl and clickurl_openinnewwindow  params
 *	API 1.1 (4/27/06)
 *		- added object wrappers for API
 *		- removed download authentication support
 *		- added autoPlay, width, height, and wmode params
 *		- changed Flash param allowScriptAccess to always to support fullscreen mode
 *		- changed Flash param scale to noscale
 *		- changed DOM ID of player object from Player to VE_Player
 *		- changed embed name of player from Player to VE_Player
 *		- added VE_embedPlayerHTML_1_1
 * @usage
 *		var api = VE_getPlayerAPI("1.1");
 *		api.embedPlayer("/gid328/cid1096/2T/60/11428306632vWNmMJIrwZ2Gf0rlPU3", 640, 505, false, "", "", "", "", "");
 **/

// current API version
var VE_curAPIVer = "1.4";



//
// Helpers
//

var VE_Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

/* declare dynamic function in case function is already defined */
var VE_isset = function(v) {
	// define undefined for older browsers
	var undefined;
	if ((v == undefined) || (v == null) || (v === "")) {
		return false;
	} else {
		return true;
	}
}



//
// Object API
//

var VE_getPlayerAPI = function(ver) {
	ver = ver.replace(".", "_");
	var ret = eval("new VE_PlayerAPI_" + ver);
	return ret;
}

var VE_PlayerAPI_1_0 = VE_Class.create();
VE_PlayerAPI_1_0.prototype = {
	version: "1.0",
	
	initialize: function() {	
	},
	
	embedPlayer: function (clientId, path, appearance, bgcolor, auth1, auth2, auth3) {
		document.write(this.getPlayerHTML(clientId, path, appearance, bgcolor, auth1, auth2, auth3));
	},
	
	getPlayerHTML: function (clientId, path, appearance, bgcolor, auth1, auth2, auth3) {
		return VE_JSEmbedPlayer_Flash7_8(clientId, path, appearance, bgcolor, auth1, auth2, auth3);
	}
	
};

var VE_PlayerAPI_1_1 = VE_Class.create();
VE_PlayerAPI_1_1.prototype = {
	version: "1.1",

	initialize: function() {
	},
	
	embedPlayer: function (path, mWidth, mHeight, autoPlay, logo, bgcolor, showAd, wMode) {
		var api = VE_getPlayerAPI("1.3");
		return api.embedPlayer(path, mWidth, autoPlay, "", "", showAd, "", wMode);
	},

	getPlayerHTML: function (path, mWidth, mHeight, autoPlay, logo, bgcolor, showAd, wMode) {
		var api = VE_getPlayerAPI("1.3");
		return api.getPlayerHTML(path, mWidth, autoPlay, "", "", showAd, "", wMode);
	}
};


var VE_PlayerAPI_1_2 = VE_Class.create();
VE_PlayerAPI_1_2.prototype = {
	version: "1.2",

	initialize: function() {
	},
	
	embedPlayer: function (path, mWidth, mHeight, autoPlay, logo, bgcolor, showAd, adVars, wMode) {
		var api = VE_getPlayerAPI("1.3");
		return api.embedPlayer(path, mWidth, autoPlay, "", "", showAd, adVars, wMode);
	},

	getPlayerHTML: function (path, mWidth, mHeight, autoPlay, logo, bgcolor, showAd, adVars, wMode) {
		var api = VE_getPlayerAPI("1.3");
		return api.getPlayerHTML(path, mWidth, autoPlay, "", "", showAd, adVars, wMode);
	},

	getThumbnailURL: function (path) {
		var api = VE_getPlayerAPI("1.3");
		return api.getThumbnailURL(path);
	}
};

var VE_PlayerAPI_1_3 = VE_Class.create();
VE_PlayerAPI_1_3.prototype = {
	version: "1.3",

	initialize: function() {
	},
	
	embedPlayer: function (path, width, autoPlay, watermark, watermarkLocation, showAd, adVars, wMode, extraFlashVars) {
		document.write(this.getPlayerHTML(path, width, autoPlay, watermark, watermarkLocation, showAd, adVars, wMode, extraFlashVars));
	},

	getPlayerHTML: function (path, width, autoPlay, watermark, watermarkLocation, showAd, adVars, wMode, extraFlashVars) {
		return VE_getPlayerHTML_1_4({
			file:path,
			width:width,
			autoPlay:autoPlay,
			watermark:watermark,
			watermarkLocation:watermarkLocation,
			showAd:showAd,
			adVars:adVars,
			wmode:wMode,
			extraFlashVars:extraFlashVars});
	},

	getGrabcodeHTML: function (path, width, autoPlay, watermark, watermarkLocation, showAd, adVars, wMode, extraFlashVars) {
		return VE_getPlayerHTML_1_4({
			file:path,
			width:width,
			autoPlay:autoPlay,
			watermark:watermark,
			watermarkLocation:watermarkLocation,
			showAd:showAd,
			adVars:adVars,
			isGrabcode:true,
			wmode:wMode,
			extraFlashVars:extraFlashVars});
	},

	getThumbnailURL: function (path) {
		return VE_getThumbnailURL_1_4({file:path});
	}
};

var VE_PlayerAPI_1_4 = VE_Class.create();
VE_PlayerAPI_1_4.prototype = {
	version: "1.4",

	initialize: function() {
	},
	
	embedPlayer: function (pObj) {
		document.write(this.getPlayerHTML(pObj));
	},

	getPlayerHTML: function (pObj) {
		return VE_getPlayerHTML_1_4(pObj);
	},

	getGrabcodeHTML: function (pObj) {
		pObj.isGrabcode = true;
		return VE_getPlayerHTML_1_4(pObj);
	},

	getThumbnailURL: function (pObj) {
		return VE_getThumbnailURL_1_4(pObj);
	}
};



//
// API 1.0 Functions (legacy)
// 

var VE_JSEmbedPlayer_Flash7_8 = function (clientId, path, appearance, bgcolor, auth1, auth2, auth3) {
	document.write(VE_getPlayerHTML(clientId, path, appearance, bgcolor, auth1, auth2, auth3));
}

var VE_getPlayerHTML = function (clientId, path, appearance, bgcolor, auth1, auth2, auth3) {
	return VE_getPlayerHTML_1_1(path, "", "", false, "", bgcolor, "", "");
}

var EmbedPlayer = function (bgcolor, dbid) {
	VE_embedPlayerHTML_1_1("/gid325/cid1093/timestamp/" + dbid, 334, 330, false, "", bgcolor, "", "");
}

var EmbedPlayer2 = function (bgcolor, dbid) {
	VE_embedPlayerHTML_1_1("/gid328/cid1096/" + dbid, 334, 330, false, "", bgcolor, "", "");
}

var VE_embedPlayerHTML_1_1 = function (path, mWidth, mHeight, autoPlay, logo, bgcolor, showAd, wMode) {
        document.write(VE_getPlayerHTML_1_1(path, mWidth, mHeight, autoPlay, logo, bgcolor, showAd, wMode));
}

var VE_getPlayerHTML_1_1 = function (path, mWidth, mHeight, autoPlay, logo, bgcolor, showAd, wMode) {
	var api = VE_getPlayerAPI("1.3");
        return api.getPlayerHTML(path, mWidth, autoPlay, "", "", showAd, "", wMode);
}




//
// API 1.4 Functions (current)
//

var VE_getThumbnailURL_1_4 = function (pObj) {
	var path = pObj.file;
	if (path.substr(0, 4) == "/gid") {
		path = "http://download.videoegg.com" + path;
	}
	else {
		path = "http://" + path;
	}

	return path + "_thumbnail.jpg";
}

var VE_getPlayerHTML_1_4 = function (pObj) {
	var path = pObj.file;
	// Figure out the path.  For legacy reasons, we still support paths
	// without hostnames, which just default to download.videoegg.com.
	if (path.substr(0, 4) == "/gid") {
		path = "http://download.videoegg.com" + path;
	}
	else if(path.substr(0, 4) != "http") {
		path = "http://" + path;
	}

	// Temporary enable features for specific sites
	var tmpurl = document.URL;
	if (tmpurl.indexOf("hi5.com") != -1 ||
		tmpurl.indexOf("bebo.com") != -1 ||
		tmpurl.indexOf("ringo.com") != -1 ||
		tmpurl.indexOf("tagged.com") != -1)
	{
		if (! VE_isset(pObj.allowGrabcode))
			pObj.allowGrabcode = true;

		if (! VE_isset(pObj.allowRecommendations))
			pObj.allowRecommendations = true;
	}
	// end temporary
	
	// Figure out adVars - if it's an object, collapse it into a string.
	var adVarsString = "";

	if (typeof(pObj.adVars) == 'string') {
		adVarsString = pObj.adVars;
	}

	else if (typeof(pObj.adVars) == 'object') {
		for (var name in pObj.adVars) {
			adVarsString += name + "=" + pObj.adVars[name] + "&";
		}
	}

	adVarsString = adVarsString.toLowerCase();
	
	if (adVarsString.indexOf("site=") == -1)
	{
		// Pull the 'site' var from the doc URL
		adVarsString = VE_forceSite(adVarsString);
	}

	if (! VE_isset(pObj.autoPlay)) pObj.autoPlay = false;
	if (! VE_isset(pObj.showAd)) pObj.showAd = true;
	if (! VE_isset(pObj.showAdPrimary)) pObj.showAdPrimary = true;
	if (! VE_isset(pObj.width)) pObj.width = 440;
	if (! VE_isset(pObj.wmode)) pObj.wmode = "window";
	if (! VE_isset(pObj.watermark)) pObj.watermark = "";
	if (! VE_isset(pObj.watermarkLocation)) pObj.watermarkLocation = "bottomleft";
	if (! VE_isset(pObj.extraFlashVars)) pObj.extraFlashVars = "";
	if (! VE_isset(pObj.isGrabcode)) pObj.isGrabcode = false;
	if (! VE_isset(pObj.allowGrabcode)) pObj.allowGrabcode = false;
	if (! VE_isset(pObj.allowEmailShare)) pObj.allowEmailShare = false;
	if (! VE_isset(pObj.allowRecommendations)) pObj.allowRecommendations = false;
	if (VE_isset(pObj.skin)) pObj.skin = (pObj.skin.indexOf("skins/") > -1 ? "" : "skins/") + pObj.skin;
	if (! VE_isset(pObj.aspect)) pObj.aspect = 3/4;

	adVarsString = VE_siteShowAd(adVarsString, pObj.showAd);
	
	// Figure out the flash version to load.
	var VE_flashVersion = 0;
	
	if (VE_DetectFlashVer(8, 0, 0)) {
		VE_flashVersion = 8;
	} else if (VE_DetectFlashVer(7, 0, 19)) {
		VE_flashVersion = 7;
	} else {
		return '<a href="http://www.macromedia.com/go/getflashplayer"><img src="http://update.videoegg.com/client/upgrade_flash.gif" border=0></a>';
	}
	
	var VE_playerLocation = "http://update.videoegg.com/flash/proxy.swf?jsver=" + VE_curAPIVer;

	// For testing, we can pass in an alternate player location.
	if (typeof(VE_USE_ALTERNATE_PLAYER_LOCATION) == "string") {
		VE_playerLocation = VE_USE_ALTERNATE_PLAYER_LOCATION;
	}

	// Figure out the height based on the width.
	var height = Math.ceil(pObj.width * pObj.aspect)+32;

	// Write out the flash vars.
	var flashVars = 'file=' + escape(path) +
		'&swfpath=' + VE_playerLocation +
		'&autoPlay=' + pObj.autoPlay +
		'&showAd=' + pObj.showAd +
		'&showAdPrimary=' + pObj.showAdPrimary +
		'&wmode=' + pObj.wmode + 
		'&adVars=' + escape(adVarsString) +
		'&allowGrabcode=' + (pObj.allowGrabcode ? "true" : "false") +
		'&allowEmailShare=' + (pObj.allowEmailShare ? "true" : "false") +
		'&allowRecommendations=' + (pObj.allowRecommendations ? "true" : "false") +
		(VE_isset(pObj.permalink) ? '&permalink=' + pObj.permalink : "") +
		(VE_isset(pObj.pid) ? '&pid=' + pObj.pid : "") +
		(VE_isset(pObj.skin) ? '&skin=' + pObj.skin : "") + 
		(VE_isset(pObj.clickurl) ? '&clickurl=' + pObj.clickurl : "") + 
		(VE_isset(pObj.clickurl_openinnewwindow) ? '&clickurl_openinnewwindow=' + pObj.clickurl_openinnewwindow : "") + 
		(VE_isset(pObj.grabcode_clickurl) ? '&grabcode_clickurl=' + pObj.grabcode_clickurl : "") + 
		(VE_isset(pObj.grabcode_clickurl_openinnewwindow) ? '&grabcode_clickurl_openinnewwindow=' + pObj.grabcode_clickurl_openinnewwindow : "") + 
		'&MMredirectURL=' + escape(window.location.href) +
		'&MMplayerType=' + ((navigator.appVersion.indexOf("MSIE") != -1) ? 'ActiveX' : 'PlugIn') +
		'&MMdoctitle=' + escape(document.title.slice(0, 47));		
		// Watermark - the param looks like "watermark_bottomleft=URL"
	if (pObj.watermark != "") {
		flashVars += '&watermark_' + pObj.watermarkLocation + '=' + pObj.watermark;
	}

	// Extra flash vars - for testing, we can pass additional vars like playlistURL.
	if (pObj.extraFlashVars != "") {
		flashVars += "&" + pObj.extraFlashVars;
	}

	// Legacy embeds will not contain the allowFullScreen flag, so we pass a FlashVar param
	// to the Player so it knows that this embed contains allowFullScreen so we can enable
	// the fullscreen button.  Fullscreen doesn't work in windowsless or transparent mode
	// (Flash limitation) so we disable the button in that case as well.
	if (pObj.wmode == "window") {
		flashVars += '&allowFlash9Fullscreen=true';
	}

	// Finally, we build the HTML
	var playerObject = 
		'<embed src="' + VE_playerLocation + '" '
		+ 'FlashVars="' + flashVars + '" '
		+ 'quality="high" '
		+ 'allowFullScreen="true" '
		+ 'allowScriptAccess="always" '
		+ 'scale="noscale" '
		+ 'wmode="' + pObj.wmode + '" '
		+ 'width="' + pObj.width + '" '
		+ 'height="' + height + '" '
		+ 'name="VE_Player" id="VE_Player" align="middle" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>';
		
	return playerObject;
}

var VE_parseURI = function(uri_string)
{
	var parts = ['uri', 'proto', 'domain', 'port', 'path'];
	var regx = /^([^:\/?#]+)(?::\/\/)([^:/?#]+)(?::([\d]+)?)?(?:[^/?#]*)(\/.*)/;
	var uri = new Object();
		
	uri_string = uri_string + "";
	var parse = uri_string.match(regx);
	
	if (parse == null)
		return uri;

	for (var i = 0; i < parts.length; i++)
	{
		uri[parts[i]] = parse[i];
	}
	return uri;
}

// fuzzy heuristic to get the primary domain
var VE_getSite = function()
{
	var uri = VE_parseURI(document.URL);
	var site = (typeof(uri.domain) != "string" ? "unknown" : uri.domain);
	var parts = site.split(".");

	if (parts.length > 1)
	{
		// remove TLD
		parts.pop();

		// strip www
		if (parts[0] == "www")
			parts.shift();
		
		while (parts.length > 1 && parts[parts.length - 1].length < 3)
			parts.pop();
	}

	site = parts.pop();

	var alts = {
		beboframe: "bebo"
		// add other alternates here.
	};
	
	if (typeof(alts[site]) == "string")
		site = alts[site];
		
	return site;
}

var VE_forceSite = function(advars)
{
	var site = VE_getSite();

	if (advars.indexOf("site=") != -1)
	{
		var replaceSite = /site=[^&]*/;
		advars = advars.replace(replaceSite, "site=" + site);
	}
	else if (advars.length > 0)
		advars += "&site=" + site;
	else
		advars = "site=" + site;

	return advars;
};

var VE_siteShowAd = function(advars, showAd)
{
    if (!showAd)
    {
        var replaceSite = /site=[^&]*/;
        var match = advars.match(replaceSite);
        if (match != null)
        {
            advars = advars.replace(replaceSite, match[0] + "_noad");
        }
    }

    return advars;
};

//
// Flash detection from Flash Detection Kit provided by Macromedia
//

var VE_writeVB = function () {
	VE_wroteVB = true;
	document.writeln('<scr' + 'ipt language="vbscript">');
	document.writeln('Function VE_VBGetSwfVer(i)');
	document.writeln('  on error resume next');
	document.writeln('  Dim swControl, swVersion');
	document.writeln('  swVersion = 0');
	document.writeln('');
	document.writeln('  set swControl = CreateObject("ShockwaveFlash.ShockwaveFlash." + CStr(i))');
	document.writeln('  if (IsObject(swControl)) then');
	document.writeln('    swVersion = swControl.GetVariable("$version")');
	document.writeln('  end if');
	document.writeln('  VE_VBGetSwfVer = swVersion');
	document.writeln('End Function');
	document.writeln('</scr' + 'ipt>');
}

// Detect Client Browser type
if (! VE_wroteVB) var VE_wroteVB = false;
var VE_isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var VE_isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var VE_isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
if (!VE_wroteVB && VE_isIE && VE_isWin && !VE_isOpera) VE_writeVB();

// JavaScript helper required to detect Flash Player PlugIn version information
var VE_JSGetSwfVer = function (i){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
      		var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			descArray = flashDescription.split(" ");
			tempArrayMajor = descArray[2].split(".");
			versionMajor = tempArrayMajor[0];
			versionMinor = tempArrayMajor[1];
			if ( descArray[3] != "" ) {
				tempArrayMinor = descArray[3].split("r");
			} else {
				tempArrayMinor = descArray[4].split("r");
			}
      		versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
            flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
      	} else {

			flashVer = -1;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	// Can't detect in all other cases
	else {
		
		flashVer = -1;
	}
	return flashVer;
} 

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
var VE_DetectFlashVer = function (reqMajorVer, reqMinorVer, reqRevision) 
{
 	reqVer = parseFloat(reqMajorVer + "." + reqRevision);
   	// loop backwards through the versions until we find the newest version	
	for (i=25;i>0;i--) {
		if (VE_isIE && VE_isWin && !VE_isOpera) {
			versionStr = VE_VBGetSwfVer(i);
		} else {
			versionStr = VE_JSGetSwfVer(i);		
		}
		if (versionStr == -1 ) { 
			return false;
		} else if (versionStr != 0) {
			if(VE_isIE && VE_isWin && !VE_isOpera) {
				tempArray         = versionStr.split(" ");
				tempString        = tempArray[1];
				versionArray      = tempString .split(",");				
			} else {
				versionArray      = versionStr.split(".");
			}
			versionMajor      = versionArray[0];
			versionMinor      = versionArray[1];
			versionRevision   = versionArray[2];
			
			versionString     = versionMajor + "." + versionRevision;   // 7.0r24 == 7.24
			versionNum        = parseFloat(versionString);

			if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
				return true;
			} else {
				return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );	
			}
		}
	}	
}


//
// Legacy Custom Player API.  Previously in PlayerCustom.js
// 
var VE_getCustomPlayerAPI = function(ver) {
	ver = ver.replace(".", "_");
	var ret = eval("new VE_CustomPlayerAPI_" + ver);
	return ret;
}

var VE_CustomPlayerAPI_1_0 = VE_Class.create();
VE_CustomPlayerAPI_1_0.prototype = {
	version: "1.0",
	
	initialize: function()
	{
	},
	
	embedPlayer: function (path, mWidth, mHeight, autoPlay, logo,
		skinID, showAd, adVars, wMode)
	{
		document.write(this.getPlayerHTML(path, mWidth, mHeight,
			autoPlay, logo, skinID, showAd, adVars, wMode));
	},
	
	getPlayerHTML: function (path, mWidth, mHeight, autoPlay, logo,
		skinID, showAd, adVars, wMode)
	{
		var settings = {
			file:path,
			width:mWidth,
			autoPlay:autoPlay,
			watermark:logo,
			watermarkLocation: "watermark_bottomright",
			skin:skinID,
			showAd:showAd,
			adVars:adVars,
			wmode:wMode
		};
		
		return VE_getPlayerHTML_1_4(settings);
	},

	getThumbnailURL: function (path)
	{
		return VE_getThumbnailURL_1_4({file:path});
	}

};
// end legacy API support
