//
// - 4.00 - ForRent Package
//


init = function(){
	var _thisScript;
	var thisScript = function(){
		if(!_thisScript){
			var scripts = document.getElementsByTagName("script");
			for (var i = 0; i < scripts.length; i++) {
				if(/mds/.test(scripts[i].src)) _thisScript = scripts[i];
			}
		}
		return _thisScript;
	}

	var lastScript = function(){
		var s = document.getElementsByTagName("script");
		return s[s.length-1];
	}

	var getServerRoot = function(){
		var sroot = "";
		if(/mds/.test(thisScript().src)){
			sroot = thisScript().src.substring(0, thisScript().src.lastIndexOf("/")+1);
		}
		return sroot;
	}

	var isDebug = window.isDebug || /debug=true/.test(document.location.href) || false;
	var cacheBust = window.cacheBust || false;
	var serverRoot = window.serverRoot || getServerRoot();
	var multipleSkins = false;
	var w = window;
	var ua = navigator.userAgent.toLowerCase();
	var isNewIE = (/Trident/.test(window.navigator.userAgent));
	var isIE = ua.indexOf('msie') != -1  &&  ua.indexOf( 'opera' ) == -1;
	if(!isDebug || !w.console){
		try{
			w.console = {};
			var m = ("log,info,warn,error,dir,debug").split(",");
			for(var i=0; i<m.length;i++){
				w.console[m[i]] = function(){}
			}
		}catch(e){ /*ignore*/}
	}
	if (  isIE  ) {
		// 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);
		}
	};

	w.mds = {
		// library of common methods
		//
		isDebug:isDebug,
		root: serverRoot,
		flashArgs:{
			// defaults for player initialization
			// these may be edited.
			//
			swf: serverRoot + "mds_player.swf",
			width: '220',
			height: '240',
			bgcolor:"#ffffff",
			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:{},
		winLoaded:false,
		mdsDialogStyle:{},
		players: {},
		refNodes:{},
		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){
			if(!str) return {};
			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;
		},

		hashToObject: function(){ // not used?
			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*$/, '');
		},

		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){
				if(o[nm] !== "")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]; // FF, Saf
			}else if(doc[name]){
				swfs[name] = doc[name]; // IE 6, 7, 8
			}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){
			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();
		},

		launchAvailability: function(){
			if(!this.current){ return; }
			this.swf(this.current.id) && this.swf(this.current.id).launchAvailability();
		},

		setPlaylistIndex: function(idx){
			this.swf(this.current.id).setPlaylistIndex(idx);
		},

		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;

			for(var nm in this.players){
				if(this.players[nm].type == "inserted"){
					id = nm;
				}else{
					this.close(this.players[nm]);
				}
			}
			var plst = buildDynamicXml(videoId);
			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);
				}
			}
		},

		getScriptParams: function(){
			var player, dupe = false;
			// find where this script is attached in the dom
			var scr = thisScript();
			var id = scr.id || scr.getAttribute("videoId");
			var cfg = this.strToObj(scr.getAttribute("config"));
			var cid = scr.getAttribute("clientId") || cfg.clientId;
			var lid = scr.getAttribute("locationId") || cfg.locationId;

			if (id || /^file|,file/.test(cfg)) {
				var videoId = id || "";
				id = id || this.uid();
				id = /swf/.test(id) ? id : "swf_"+id;
				if(!mds.players[id]){
					dupe = false;
					player = mds.players[id] = {
						type:		"embedded",
						script: 	scr,
						id:			id,
						args: 		mds.mix(mds.flashArgs, cfg),
						flashVars: 	mds.mix(mds.flashVars, cfg),
						node:		scr.parentNode
					};
					player.flashVars.videoId = videoId;
				}else{
					dupe = scripts[i].id
				}
			}else if(/mds/.test(scr.src)){
				if(scr.parentNode.tagName == "HEAD") return null; // we're not embedded
				var id = this.uid();
				player = mds.players[id] = {
					id:			id,
					type:		"embedded",
					script: 	scr,
					args: 		mds.mix(mds.flashArgs, cfg),
					flashVars: 	mds.mix(mds.flashVars, cfg),
					node:		scr.parentNode
				};
			}
			if(lid){
				player.args.locationId = lid;
			}

			if(dupe){
				log("***** A duplicate ID was detected: ", dupe);
			}
			this.current = player;

			// mixinParams gets called next
			return player;
		},

		mixinParams: function(p, resizeNode){
			var fv = p.flashVars;
			p.args.id = fv.pId = p.id;

			if(resizeNode){
				p.node.style.width = p.args.width;
				p.node.style.height = p.args.height;
			}
			if(p.args.width=="220" && p.args.height=="240"){
				p.args.width = this.style(p.node, "width");
				p.args.height = this.style(p.node, "height");
			}
			p.args.movie = p.args.src = p.args.swf + (/\.swf/.test(p.args.swf) ? "" : ".swf");

			if(this.cacheBust) fv.cacheBust = true;
			//console.log("mixinParams player:", p)
			return p;
		},

		getInsertParams: function(videoId, nodeId, params){
			params = params || {};
			var id = typeof(nodeId)=="string" ? "swf_"+nodeId : "swf_"+this.uid();

			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
			var player, dfd = new Deferred(), ieTimer;
			var whenReady = function(){
				player = mds.getInsertParams(videoId, nodeId, params);
				mds.embed(player);
				dfd.fire(player);
				clearTimeout(ieTimer)
			}
			if(mds.byId(nodeId)){
				whenReady();
			}else{
				mds.connect(window, "load", function(){
					whenReady();
				});
				// if a lot of DOM activity, IE foobars
				ieTimer = setTimeout(function(){
					whenReady();
				},100)
			}
			return dfd;
		},

		insert: function(o){
			console.warn("INSERT!")
			n = lastScript().parentNode;
			var id = o.videoId || o.id || o.siteId || o.siteID;
			this.insertPlayer(id, n, o);
		},

		cacheBust:cacheBust,
		embed: function(params){
			if(!this.minVersion(params)) return false;
			var a = params.args;
			var v = params.flashVars;
			var br = "";//"\n";
			var tb = "";//"\t";

			if(this.cacheBust){
				var c = "?cache=CB_" + (new Date()).getTime();
				params.args.src   += c;
				params.args.movie += c;
				v.cacheBust = true;
			}

			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,swf".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;
		},

		minVersion: function(params){
			// not checking IE, that happens in the embed
			if(isIE) return true;
			fVersion=(function(){
				var plugin = navigator.plugins["Shockwave Flash"];
				if(plugin && plugin.description){
					var v = plugin.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split(".");
					return (v[0]!=null) ? parseInt(v[0]) : 0;
				}
				return 0;
			})();
			console.log("fVersion:", fVersion)
			if(fVersion > 8) return true; // Player will catch 9
			params.node.innerHTML = "To play this video you need the latest version of the Adobe Flash Player.<br/><a href='http://www.adobe.com/products/flashplayer/' style='font-weight:bold;'>Get Adobe Flash Player</a>";
			return false;
		}
	};

	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[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){
				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();
	if(!player) return;
	player = mds.mixinParams(player);
	//console.log("embed player:::", player)
	mds.embed(player);

}
initEmbededScripts();
