//
// - 3.20 JS - does NOT handle data.xml file
//
// calls used in this file
// These functions may need to be edited.
click2action = function(type){
	// To Edit
	//	Used for printing or bookmarking, etc.
	alert("click2action: " + type);
};

buildDynamicXml = function(videoId, clientId){
	// return XML PLAYLIST FILE
	if(!videoId || videoId == "0"){
		return false;
	}
	clientId = clientId || mds.clientId;
	locationId = mds.locationId || "2";
	if(!clientId || clientId=="0"){
		return "xml/playlist_"+videoId+".xml";
	}
	//console.warn("VIDEOID::::", videoId)
	return mds.root + "xmlwriter.aspx?videoId_clientId_locationId="+videoId+"_"+clientId+"_"+locationId;
};

getPrefsLocation = function(){
	// RETURN XML PREFS FILE
	return mds.prefs;
};


init = function(){
	var serverRoot = window.serverRoot || "http://video.bettervideo.com/videos/player/3.10/";
	var isDebug = window.isDebug || /debug=true/.test(document.location.href) || false;
	var multipleSkins = false;
	var w = window;
	var ua = navigator.userAgent.toLowerCase();
	var isNewIE = (/Trident/.test(window.navigator.userAgent));
	if(!isDebug || !w.console){
		try{
			w.console = {};
			var m = ("log,info,warn,error,dir").split(",");
			for(var i=0; i<m.length;i++){
				w.console[m[i]] = function(){}
			}
		}catch(e){ /*ignore*/}
	}
	if (  ua.indexOf('msie') != -1  &&  ua.indexOf( 'opera' ) == -1  ) {
		// catch stupid Flash code that throws IE errors onunload
		window.attachEvent('onunload', function() {
			window.__flash__removeCallback = function (instance, name) {
				try { if (instance) {	instance[name] = null; }} catch ( err ) { }
			};
		});
	}

	var _descNode;
	var _idInc = -1;
	var cons = {};
	var swfs = {};
	var _disconnect = function(object, name, handler){
		if(object.detachEvent){ //IE... good luck with this
			object.detachEvent("on"+name, handler);
		}else{
			object.removeEventListener(name, handler, false);
		}
	};

	var hitch = function(ctx, func){

		if(typeof(func) == "string"){
			if(!func){ func = ctx; ctx = window; }
			return function(){ ctx[func].apply(ctx, arguments); }
		}else{
			var method = !!func ? ctx.func || func : ctx;
			var scope = !!func ? ctx : window;
			return function(){ method.apply(ctx, arguments); }
		}
	}

	var Deferred = function(){
		_callbacks = [];
		this.addCallback = function(obj, func){
			_callbacks.push(hitch(obj, func));
		}
		this.fire = function(){
			var args = arguments;
			setTimeout(function(){
				for(var i=0;i<_callbacks.length;i++){
					var c = _callbacks[i];
					c(args);
				}
			},1)
		}
	};




	var prefMap = {
		def:"general/prefs.xml",
		"9":"white/prefs.xml",
		"9b":"white/prefsB.xml",
		"10":"white/prefs.xml",
		"19":"idearc/prefs.xml",
		"20":"skunkpost/prefs.xml",
		"21":"chron/prefs.xml"
	};

	w.mds = {
		// library of common methods
		//
		isDebug:isDebug,
		root: serverRoot,
		flashArgs:{
			// defaults for player initialization
			// these may be edited.
			//
			swf: serverRoot + "player/mds_player.swf",
			width: '220',
			height: '240',
			bgcolor:"#ffffff",
			swLiveConnect: "true",
			allowFullScreen: true,			// without this, no fullscreen ability. natch.
			allowNetworking: "all",			// Needs to be all, and needs a crossdomain.xml
			allowScriptAccess: "always", 	// Needed for ExternalInterface
			wmode:"opaque"
		},
		flashVars:{
			// defaults for variables passed into player
			// these may be edited.
			//
			isInBrowser: true,
			browserUrl:escape(document.location.href),
			referrer:document.referrer,
			prefsfile:"",
			file:""
		},
		prefs:this.root + "xml/" + prefMap.def,

		locationId:2,
		winLoaded:false,
		mdsDialogStyle:{},
		players: {},
		refNodes:{},
		hasJS: function(){
			return true;
		},
		getViewport: function(){
			var root = (document.compatMode == 'BackCompat')? document.body : document.documentElement;
			return { w: root.clientWidth, h: root.clientHeight};
		},

		coords: function(node, includeScroll){

			var db = document.body, dh = db.parentNode, ret;
			node = this.byId(node);
			if(node["getBoundingClientRect"]){
				// IE6+, FF3+, super-modern WebKit, and Opera 9.6+
				ret = node.getBoundingClientRect();
				ret = { x: ret.left, y: ret.top, w: ret.right - ret.left, h: ret.bottom - ret.top };
			}else{
				// older non-IE browsers - could go off of event
			}
			if(includeScroll){
				var n = window, d = document;
				var scroll =
					"pageXOffset" in n? { x:n.pageXOffset, y:n.pageYOffset } :
					(n=d.documentElement, n.clientHeight? { x:n.scrollLeft, y:n.scrollTop } :
					(n=d.body, { x:n.scrollLeft||0, y:n.scrollTop||0 }));
				ret.x += scroll.x;
				ret.y += scroll.y;
			}
			return ret; // Object
		},

		dom: function(tagName, className, parentNode, style){
			var n = document.createElement(tagName);
			if(className){ n.className = className; }
			if(parentNode){ parentNode.appendChild(n); }
			if(style){ n.style.cssText = style; }
			return n;
		},

		style: function(node, prop, value){
			node = this.byId(node);

			if(typeof(prop) == "string"){
				if(value !== undefined){
					node.style[prop] = value;
				}else{
					var s = node.currentStyle || node.ownerDocument.defaultView.getComputedStyle(node, null);
					return parseInt(s[prop], 10);
				}
			}else{
				for(var nm in prop){
					this.style(node, nm, prop[nm]);
				}
			}
			return true;
		},

		destroy: function(node){
			_descNode = _descNode || document.createElement("div");
			if(node.parentNode){
				node = node.parentNode.removeChild(node);
			}
			_descNode.appendChild(node);
			_descNode.innerHTML = "";
		},

		byId: function(id){
			if(typeof(id) == "string"){
				id = document.getElementById(id);
			}
			return id;
		},

		mix: function(o1, o2, leaveUndf){
			if(!o2) return this.copy(o1);
			if(typeof(o2)=="string"){
				o2 = this.strToObj(o2);
			}
			if(!o1) return o2;
			o1 = this.copy(o1);
			for(var nm in o2){
				if(leaveUndf && o1[nm]===undefined) continue;
				o1[nm] = o2[nm];
			}
			return o1;
		},

		copy: function(obj){
			var o = {};
			for(var nm in obj){
				o[nm] = obj[nm];
			}
			return o;
		},

		strToObj: function(str){
			// convert stringified object to an object
			// note: curvrently assumes all params are strings
			var delim = /&/.test(str) ? "&" : ",";
			var o = {};
			var a = str.split(delim);
			for(var i=0; i<a.length;i++){
				var pr = this.trim(a[i]).split("=");
				if (pr[0]=="file"){
					o[this.trim(pr[0])]=a[i].substring(a[i].indexOf("=")+1);
				}else{
		            o[this.trim(pr[0])] = this.trim(pr[1]);
				}
			}
			return o;
		},

		hash: function(){
			// return any hash params as an object
			if(!this._hash){
				var hash = document.location.hash.toString();
				this._hash = hash ? this.strToObj(hash.substring(1)) : {};
			}
			return this._hash;
		},

		trim: function(str){
			return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
		},

		url: function(shortUrl){
			return document.location.href;
		},

		getEmbed: function(playerId){
			console.log("LIB GET EMBED:", playerId, this.players[playerId]);
			return {
				embed:this.players[playerId].embed,
				jsembed:this.players[playerId].jsembed
			};
		},

		popup: function(url){
			this.log("popup:", url);
			var win = false;
			try{
				win = window.open(url,"MDS_Social_Connection","status=0,menubar=0,resizable=1,top=2,left=2,width=1024,height=640,scrollbars=1,addressbar=0");
				win.focus();
			}catch(e){
				mds.log("error opening popup:", e.message);
				return false;
			}
			return !!win;
		},

		bitly: function(){
			return this.shortenedUrl;
		},

		toQuery: function(o){
			var a = [];
			for(var nm in o){
				a.push(nm+'='+o[nm])
			}
			return a.join('&');
		},

		uid: function(str){
			_idInc++;
			return (str || "id") + "_" + _idInc;
		},

		swf: function (name){
			var doc = document;
			if(doc.embeds[name]){
				swfs[name] = doc.embeds[name];
			}else if(doc[name]){
				swfs[name] = doc[name];
			}else if(window[name]){
				swfs[name] = window[name];
			}else if(document[name]){
				swfs[name] = document[name];
			}
			return swfs[name];
		},

		connect: function(object, name, ctx, method){
			var handler = hitch(ctx, method);
			if(object.attachEvent){ //IE
				object.attachEvent("on"+name, handler);
			}else{
				object.addEventListener(name, handler, false);
			}
			var handle = this.uid();
			cons[handle] = [object, name, handler];
			return handle;
		},

		disconnect: function(handle){
			_disconnect(cons[handle][0], cons[handle][1], cons[handle][2]);
			delete cons[handle];
		},

		log: function(msg){
			// stub
		},

		onError: function(msg){
			// stub
		},

		onInfo: function(data){
			console.warn("onData:", data)
		},

		isPlaying: function(playerId){
			console.warn("isPlaying:", playerId)
			if(!playerId){ return; }
			this.stopOthers(playerId);
		},

		isPausing: function(playerId){
			if(!playerId){ return; }
		},

		doPlay: function(playerId){
			if(!playerId){ return; }
			this.swf(playerId) && this.swf(playerId).doPlay();
		},

		doPause: function(playerId){
			if(!playerId){ return; }
			this.swf(playerId) && this.swf(playerId).doPause();
		},

		setClientId: function(id){
			if(multipleSkins || !this.clientId){
				this.prefs = this.root + "xml/" + (prefMap[id] ? prefMap[id] : prefMap.def);
				if(/b/.test(id)){
					id = parseInt(id, 10);
					multipleSkins = true;
				}
				//console.log("setClientId:", id, "prefs:", this.prefs )
			}
			this.clientId = id;
		},

		changeVideo: function(videoId, clientId){
			console.warn("Set new video in current player:", videoId, this.current);

			if(clientId){
				this.setClientId(clientId);
			}
			var id = this.current.id;

			console.log("I THOT PLYLST:", id, this.players);
			for(var nm in this.players){
				if(this.players[nm].type == "inserted"){
					id = nm;
				}else{
					this.close(this.players[nm]);
				}
			}
			console.log("Actually is:", id);



			var plst = buildDynamicXml(videoId);
			console.log("SWF:", this.swf(id));
			this.swf(id) && this.swf(id).updatePlaylist(plst);
		},

		close: function(player){
			var ps = this.players;
			if(typeof(players)=="string"){
				id = player;
				player = ps[id];
			}else{
				id = player.id;
			}
			this.swf(id) && this.swf(id).doUnload && this.swf(id).doUnload();
			delete this.refNodes[player.refId];
			this.destroy(player.container);
			delete ps[id];
		},

		stopOthers: function(playerId){
			// all other players besides playerId will be stopped
			// if embedded, and closed if a dialog
			var ps = this.players;
			//console.log("stop the others!", ps)
			for(var nm in ps){
				//console.log("  other id", nm, playerId, ps[nm].type)
				if(nm == playerId) continue;
				if(ps[nm].type == "dialog"){
					this.close(ps[nm]);
				}else{
					// stop it
					this.doPause(nm);
				}
			}
		},

		makeThumb: function(node, openDialog){
			console.log("MAKE THUMB", node)

			var txt = this.trim(node.innerHTML);
			node.innerHTML = '<span class="b"></span><span class="c">'+txt+'<span>';


			if(!txt) node.className += " short";
			(hitch(this, function(){
				var id = node.id;
				var dialog = openDialog;
				var params = {
					title:node.getAttribute("title") || "",
					link:node.getAttribute("link") || "",
					emailLink:node.getAttribute("emailLink") || ""
				}
				console.log("NODE PARAMS:", params, node);
				this.connect(node, "click", this, function(evt){
					if(dialog){
						this.dialog(id, node, params);
					}else{
						this.changeVideo(id);
					}
				});
				this.connect(node, "mouseover", this, function(evt){
					node.className = /\s*over/.test(node.className) ? node.className : node.className + " over";
				});
				this.connect(node, "mouseout", this, function(evt){
					node.className = node.className.replace(/\s*over/g, ""); // short name may mess up existing class
				});
			}))();
			node.style.backgroundImage = "url(http://video.bettervideo.com/videos/skunkpost_thumb/"+node.id+".thumb)";
		},

		initThumbsChange: function(){
			var nodes = document.body.getElementsByTagName("div");
			for(var i=0; i<nodes.length; i++){
				if(/mdsThumbChange/.test(nodes[i].className)){
					this.makeThumb(nodes[i]);
				}
			}
		},

		initThumbsDialog: function(){
			var nodes = document.body.getElementsByTagName("div");
			for(var i=0; i<nodes.length; i++){
				if(/mdsThumbDialog/.test(nodes[i].className)){
					this.makeThumb(nodes[i], true);
				}
			}
		},

		borderStyle:"border-style:solid;border-width:1px;border-color:#f3f9ff #adc6dd #657d93 #ccdceb;",
		closeButtonStyle:"display:block;position:absolute;font-size:12px;line-height:16px;font-weight:bold;right:3px;top:4px;cursor:pointer;width:14px;height:14px;background:#FFFFFF;font-family:sans-serif;text-align:center;color:#7a94ab;",
		playerFullStyle:"padding:5px;",
		dialogPartialStyle: "position:absolute;z-index:2000;",
		dialogFullStyle: "background:#e7f2fd;position:absolute;z-index:2000;",
		titleBarFullStyle: "background:#94cbff;padding:4px;border-bottom:1px solid #657d93",

		dialog: function(videoId, refNode, params){
			if(refNode.id && this.refNodes[refNode.id]){ return; }
			if(!refNode.id){ refNode.id = this.uid();}
			this.refNodes[refNode.id] = true;
			params = this.mix(params || {}, this.mdsDialogStyle);
			this.setClientId(params.clientId || this.clientId);
			var pos = this.coords(refNode, true);
			pos.y += pos.h;

			var container = this.dom("div", "mdsDialog " + (params.className || ""));
			var titleNode = this.dom("div", "mdsTitleBar", container);
			var closeNode = this.dom("span", "mdsClose", titleNode);
			var textNode = this.dom("span", "mdsTitleText", titleNode);
			var wrap = this.dom("div", "mdsWrap", container, "width:auto;height:auto;");
			var node = this.dom("div", "mdsPlayer", wrap);
			node.id = this.uid();

			if(params.link){
				textNode.innerHTML = '<a href="'+params.link+'">'+(params.title || "Video")+'</a>';
				params.browserUrl = params.link;
			}else{
				textNode.innerHTML = params.title || "Video";
			}

			if(params.emailLink){
				params.browserUrl = params.emailLink;
			}

			console.warn("DIALOG PARMAS:", params)
			closeNode.innerHTML = params.closeText || "X";

			// need to append right away to get its size
			// if it uses a className
			document.body.appendChild(container);

			if(params.nostyle){

				container.style.cssText = this.dialogPartialStyle;
				params.width = this.style(node, "width");
				params.height = this.style(node, "height");

			}else{
				params.width = params.width || 320;
				params.height = params.height || 240;
				var s = this.dialogFullStyle;
				container.style.cssText = s + this.borderStyle;
				titleNode.style.cssText = this.titleBarFullStyle;
				//titleNode.style.width = "100px";//params.width + "px";
				closeNode.style.cssText = this.closeButtonStyle + this.borderStyle;
				node.style.cssText = this.playerFullStyle;
			}


			var box = this.coords(container);
			var vw = this.getViewport().w;
			if(pos.x + box.w > vw){
				pos.x = vw - box.w - 15; // probably need to check margins or something
			}

			if(pos.x + (box.w/2) > vw/2){
				// if past 50% center, right-align
				var rightX = vw - pos.x - box.w;
				container.style.right = rightX + "px";
			}else{
				container.style.left = pos.x + "px";
			}
			container.style.top = pos.y + "px";

			var dfd = this.insertPlayer(videoId, node.id, params);
			dfd.addCallback(this, function(player){
				player = player[0]; //arg! fixme!!
				player.type = "dialog";
				player.container = container;
				player.refId = refNode.id;
				this.current = player;

				console.log("DIALOG:", player);
				console.log("OTHERS:", this.players);

				this.stopOthers(player.id);

				this.connect(closeNode, "click", this, function(){
					delete this.players[player.id];
					delete this.refNodes[refNode.id];
					this.destroy(container);
				});
			});
		},

		getScriptParams: function(){
			// find where this script is attached in the dom
			var player, dupe = false;
			var scripts = document.getElementsByTagName("script");
			for (var i = 0; i < scripts.length; i++) {
				var scr = scripts[i];
				var id = scr.id || scr.getAttribute("videoId");
				var cfg = scr.getAttribute("config");
				if (id || /^file|,file/.test(cfg)) {
					var videoId = id || "";
					id = id || this.uid();
					id = /swf/.test(id) ? id : "swf_"+id;
					if(!mds.players[id]){
						if(scr.getAttribute("clientId")){
							this.setClientId(scr.getAttribute("clientId"));
						}
						dupe = false;
						player = mds.players[id] = {
							type:		"embedded",
							script: 	scripts[i],
							id:			id,
							args: 		mds.mix(mds.flashArgs, scr.getAttribute("config")),
							flashVars: 	mds.mix(mds.flashVars, scr.getAttribute("config")),
							node:		scripts[i].parentNode
						};
						player.flashVars.videoId = videoId;

						if(player.args.width=="220" && player.args.height=="240"){
							player.args.width = this.style(player.node, "width");
							player.args.height = this.style(player.node, "height");
						}

						// stringify the script. This will be the "get code" used in the player
						var txt = "<script ";
						for (var i = 0; i < player.script.attributes.length; i++) {
							var a = player.script.attributes[i];
							if(a.nodeValue){
								txt += a.nodeName + "='" + a.nodeValue + "' ";
							}
						}
						txt += "></script>";
						player.jsembed = txt;
						break;
					}else{
						dupe = scripts[i].id
					}
				}else if(/mds/.test(scr.src)){
					scr.getAttribute("clientId") && this.setClientId(scr.getAttribute("clientId"));
					this.flashVars = this.mix(this.flashVars, scr.getAttribute("flashVars"), true);
					this.flashArgs = this.mix(this.flashArgs, scr.getAttribute("config"), true);
				}

			}
			if(dupe){
				log("***** A duplicate ID was detected in the player scripts: ", dupe);
			}
			this.current = player;
			// mixinParams gets called next
			return player;
		},

		mixinParams: function(player, resizeNode){
			player.args.id = player.flashVars.playerId = player.id;
			//player.args = mds.mix(player.args, mds.hash(), true);
			//player.flashVars = mds.mix(player.flashVars, mds.hash(), true);

			if(resizeNode){
				player.node.style.width = player.args.width;
				player.node.style.height = player.args.height;
			}
			player.args.movie = player.args.src = player.args.swf + (/\.swf/.test(player.args.swf) ? "" : ".swf");

			if(!player.flashVars.file){
				player.flashVars.file = buildDynamicXml(player.flashVars.videoId || player.args.id);
			}
			if(!player.flashVars.prefsfile){
				player.flashVars.prefsfile = getPrefsLocation();
			}
			return player;
		},

		getInsertParams: function(videoId, nodeId, params){
			params = params || {};
			var id = typeof(nodeId)=="string" ? "swf_"+nodeId : "swf_"+this.uid();
			this.setClientId(params.clientId || this.clientId);
			//videoId = id;
			//id = "swf_"+id;
			var player = mds.players[id] = {
				type:		"inserted",
				id:			id, // not the same as node - else it picks up the style
				args: 		mds.mix(mds.flashArgs, params, true),
				flashVars: 	mds.mix(mds.flashVars, params, true),
				node:		mds.byId(nodeId)
			};

			if(params.width && params.height){
				player.args.width = params.width;
				player.node.style.width = params.width + "px";
				player.args.height = params.height;
				player.node.style.height = params.height + "px";
			}
			player.flashVars.videoId = videoId;
			player = mds.mixinParams(player, !!params.width);
			return player;
		},

		insertPlayer: function(videoId, nodeId, params){
			//this.winLoaded = true
			console.info(".....................insert:::", videoId, this.winLoaded);
			var player, dfd = new Deferred(), ieTimer;
			var whenReady = function(){
				player = mds.getInsertParams(videoId, nodeId, params);
				mds.embed(player);
				console.info("insertPlayer.player:", player);
				dfd.fire(player);
				clearTimeout(ieTimer)
			}
			if(mds.byId(nodeId)){
				whenReady();
			}else{
				mds.connect(window, "load", function(){
					whenReady();
				});
				//if(isIE){
					// if a lot of DOM activity, IE foobars
					ieTimer = setTimeout(function(){
						whenReady();
					},100)
				//}
			}
			console.info(" connected to win onload.")
			return dfd;
		},
		insert: this.insertPlayer, //alias

		cacheBust:true,
		embed: function(params){
			var a = params.args;
			var v = params.flashVars;
			var br = "";//"\n";
			var tb = "";//"\t";

			if(this.cacheBust){
				console.log()
				var c = "?cache=CB_" + (new Date()).getTime();
				params.args.swf   += c;
				params.args.src   += c;
				params.args.movie += c;
			}

			var isParam = function(str){
				// isParam: a legal param node in the object
				// note this returns a check of NOT being in the string
				return str=="id" ? true : "width,height,src".indexOf(str) == -1;
			}
			var isArg = function(str){
				// isArg: a legal embed attribute
				// note this returns a check of NOT being in the string
				return str=="id" ? true : "movie".indexOf(str) == -1;
			}

			// create object root
			var str = 	'<object id="'+a.id+'" ' + br + tb
				+ 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ' + br + tb
				+ 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" ' + br + tb
				+ 'width="'+a.width+'" height="'+a.height+'" align="middle">' + br + tb + tb;

				// add object param nodes
				for(var nm in a){
					if(isParam(nm)){
						str += '<param name="'+nm+'" value="'+a[nm]+'" />' + br + tb + tb;
					}
				}

				// add object FlashVars param
				str += '<param name="FlashVars" value="'+mds.toQuery(v)+'" />' + br + tb + tb;

				// start embed, with plugin and mime type
				str += '<embed quality="high" type="application/x-shockwave-flash" ' + br + tb + 'pluginspage="http://www.macromedia.com/go/getflashplayer" ' + br + tb

				// add embed FlashVars
				str += 'flashVars=' + mds.toQuery(v) + " " + br + tb;

				// add remaining embed attributes
				for(var nm in a){
					if(isArg(nm)){
						str += nm+"="+a[nm] + " " + br + tb + tb;
					}
				}
				// close embed, and then close object
				str += '/>' + br + '</object>';

			params.embed = str;
			params.node.innerHTML = str;
			this.current = params;
			return str;
		}
	};


	if(window.mdsDialogStyle){
		mds.mdsDialogStyle = mds.mix(mdsDialogStyle, mds.mdsDialogStyle)
	}
	if((!window.console || !window.console.dir) && !isNewIE){
		mds.log = function(){}
	}else if(isNewIE){
		// IE
		mds.log = function(msg){
			//return "disabled";
			if(msg === undefined || !isDebug) return true;
			console.log(Array.prototype.slice.call(arguments).join("  "));
			return "success";
		}
		mds.dir = function(){};
	}else{
		mds.log = isDebug ?
			function(msg){
				var m = /ERROR/.test(msg) ? "error" : "log";

				//console.info("consoleX", consoleX)
				if(consoleX){
					consoleX.log.apply(consoleX, arguments)
				}
				console[m].apply(console, arguments)
				return "success";
			}
			: function(){}
	}

	setTimeout(function(){
		// giving time for other connects so this
		// won't happen first
		mds.connect(window, "unload", function(){
			for(var nm in cons){
				mds.disconnect(nm);
			}
		});
	}, 500);

	window.log = mds.log;

	// 	call MDS player unload functions
	//	these functions give more accurate tracker readings
	//	since we know when the user closed it
	mds.connect(window, "beforeunload", function(){
		for(var id in mds.players){
			mds.swf(id).doBeforeUnload && mds.swf(id).doBeforeUnload();
		}
	});

	mds.connect(window, "unload", function(){
		for(var id in mds.players){
			mds.swf(id).doUnload && mds.swf(id).doUnload();
		}
	});

	mds.connect(window, "load", function(){
		mds.winLoaded = true;
		setTimeout(function(){
			for(var id in mds.players){
				//console.log("pid:", id);
				//console.log("player swf:", mds.swf(id))
				mds.swf(id).doOnload && mds.swf(id).doOnload();
			}
		}, 1000);
	});

}

// this block of code will be called every time
// the script is loaded on the page
initEmbededScripts = function(){
	if(!window.mds) init();
	var player = mds.getScriptParams();
	mds.connect(window, "load", mds, "initThumbsChange");
	mds.connect(window, "load", mds, "initThumbsDialog");
	if(!player) return;
	player = mds.mixinParams(player);
	mds.embed(player);
}
initEmbededScripts();


var BitlyCB;
initBitly = function(scriptSrc,longUrl){
	// scriptSrc: a derived URL that will load a JavaScript file
	// 		it includes the apiKey, which comes from XML. Because
	// 		these creds are kept in XML, we have to initialize
	// 		this from Flash.
	// longUrl: The URL we would like to be shortened. Should in
	// 		effect always be the page address.
	//
	if(/undefined/.test(scriptSrc)) return; // don't have creds
	if(!mds.bitlyUrls){
		var newScript = document.createElement('script');
		newScript.type = 'text/javascript';
		var head = document.getElementsByTagName("head");
		if(head){
			head[0].appendChild(newScript);
		}else{
			document.body.appendChild(newScript);
		}
		newScript.src = scriptSrc;
		mds.bitlyUrls = {};
	}
	if(!mds.bitlyUrls[longUrl]){
		mds.bitlyUrls[longUrl] = true;
		var v = setInterval(function(){
			if(BitlyCB){
				clearInterval(v);
				BitlyCB.shortenResponse = function(data) {
					if(data && data.results){
						for(var nm in data.results){
							mds.shortenedUrl = data.results[nm].shortUrl;
							break;
						}
					}
					//mds.log("data:",data);
					//mds.log("BITLY:", mds.shortenedUrl);
				};
				mds.log(" >>>> bitly, longUrl", longUrl)
				BitlyClient.shorten(longUrl, 'BitlyCB.shortenResponse');
			}
		},100);
	}
};

