
function trueX(i) {
	iPos = 0
	while (i!=null) {
		iPos += i["offsetLeft"]
		i = i.offsetParent;
	}
	return iPos
}

function trueY(i){
	iPos = 0
	while (i!=null) {
		iPos += i["offsetTop"]
		i = i.offsetParent;
	}
	return iPos
}


function getEl(el) {
	return document.getElementById(el);	
}


// FIND THE TRUE POSITION OF AN ELEMENT
function getRealPos(i,which) {
	iPos = 0
	while (i!=null) {
		iPos += i["offset" + which]
		i = i.offsetParent;
	}
	return iPos
}
isMacIE = (navigator.userAgent.toLowerCase().indexOf('mac') != -1 && navigator.userAgent.toLowerCase().indexOf('msie') != -1);
dragElement = null;

function ibsPlaylist(orientation) {
	if(document.getElementById && document.createElement) {	
		myPlaylist = this;
		this.orientation = (arguments.length > 0 && arguments[0] != '')?arguments[0]:'horizontal';
		this.dragonid = '';
		this.dragonid = 0;
		this.insertAt = 0;
		this.nextVideoID = 0;
		this.previousVideoID = 0;
		this.idList = new Array();
		this.crumbs = new Array();
		this.entries = new Array();
		this.pairs = document.cookie.split('; ');
		if(this.pairs){
			for (c in this.pairs) {
				cookieHolder = this.pairs[c].split('=');
				this.crumbs[cookieHolder[0]] = unescape(cookieHolder[1]);
			}
		}
		this.idList = (this.crumbs['ibsPlaylist'])?this.crumbs['ibsPlaylist']:''
		
		dply = document.createElement('div');
		dply.setAttribute('id', 'playlistDIV');
		if(window.ActiveXObject) dply.setAttribute('className', 'playlistDIV');
		else dply.setAttribute('class', 'playlistDIV');
		if(getEl('playlist')) this.displayElement = getEl('playlist').appendChild(dply);
		else this.displayElement = document.body.appendChild(dply);
		myPlaylist.displayElement.onmouseover = function(e){
			thelist = getEl('playlist');
			if (window.event) e = window.event;
			if(navigator.userAgent.toLowerCase().indexOf('gecko') == -1) {
				pageLeft = e.clientX;
			} else {
				pageLeft = e.pageX;
			}
			mousePosition = pageLeft - getRealPos(thelist,'Left');
			if(mousePosition < 100 && dragElement){
				//scrollLeft
				thelist.scrollLeft = thelist.scrollLeft - 50; 
			} else if(mousePosition > 450 && dragElement){
				//scrollRight
				thelist.scrollLeft = thelist.scrollLeft + 50; 
			};
		}
		myPlaylist.displayElement.onmouseout = function(){
			window.status = '';
		}
		this.setOrientation = function(o) {
			this.orientation = o;
			this.refreshPlaylist();
		}
		this.currentList = '';
		// fetchXML function gets the XML from the site MIGHT HAVE TO ENSURE THAT I CAN DO THIS WITHIN THE DOMAIN
		this.fetchXML = function() {
			if (window.ActiveXObject) {
				// WINDOWS
				myPlaylist.xmldata = new ActiveXObject("Microsoft.XMLHTTP");
			} else if (document.implementation && document.implementation.createDocument) {
				// MOZILLA
				myPlaylist.xmldata = new XMLHttpRequest();
			}
			myPlaylist.xmldata.onreadystatechange = myPlaylist.writePlaylist;
			myPlaylist.xmldata.open("GET", '/_objectxml/' + this.idList + '/detail.html', true);
			myPlaylist.xmldata.send(null);		
		}
		this.writePlaylist = function() {
			if (myPlaylist.xmldata.readyState == 4){
				if(typeof myPlaylist.xmldata.responseXML == 'undefined') {
					thedata = myPlaylist.xmldata;
				} else {
					thedata = myPlaylist.xmldata.responseXML;
				}
				myPlaylist.displayElement.innerHTML = '';
				cos = thedata.getElementsByTagName("video");
				for(a=0; a<cos.length; a++) {
					imagesrc = 'http://images.ibsys.com/sh/images/videoplayer/genericvideo_8060.jpg';
					if(cos[a].getElementsByTagName("ibs_image").length != 0) {
						imagesrcs = cos[a].getElementsByTagName("ibs_image")[0].getElementsByTagName("src");
						for(i=0; i<imagesrcs.length; i++) {
							if (imagesrcs[i].getAttribute('width') == '60' && imagesrcs[i].childNodes[0].nodeValue != '') imagesrc = 'http://images.ibsys.com'+imagesrcs[i].childNodes[0].nodeValue;
						}
					}
					myPlaylist.entries[a] = new entry(cos[a].getAttribute('id'), cos[a].getElementsByTagName('headline')[0].childNodes[0].nodeValue,1,imagesrc);
					if(getEl('playlistlink'+cos[a].getAttribute('id'))) getEl('playlistlink'+cos[a].getAttribute('id')).style.visibility = 'hidden';
					myPlaylist.displayElement.appendChild(myPlaylist.entries[a].getDisplayElement(a))
				}
				myPlaylist.updateCookie();
				myPlaylist.setNextEntry();
				myPlaylist.highlight('current');
				if(myPlaylist.orientation == 'horizontal') myPlaylist.displayElement.style.width = myPlaylist.entries.length*160;
			}
		}
		this.refreshPlaylist = function() {
			myPlaylist.displayElement.innerHTML = '';
			for(a=0; a<myPlaylist.entries.length; a++) {
				myPlaylist.displayElement.appendChild(myPlaylist.entries[a].getDisplayElement(a))
				if(getEl('playlistlink'+myPlaylist.entries[a].id)) getEl('playlistlink'+myPlaylist.entries[a].id).style.visibility = 'hidden';
			}
			//myPlaylist.updateCookie();
			//myPlaylist.setNextEntry();
			//myPlaylist.highlight('current');
			if(myPlaylist.orientation == 'horizontal') myPlaylist.displayElement.style.width = myPlaylist.entries.length*160;
		}
		this.insert = function(id,rank) {
			if(typeof rank != 'undefined' && rank <= myPlaylist.entries.length) myPlaylist.insertAt = rank;
			else myPlaylist.insertAt = myPlaylist.entries.length;
			if(myPlaylist.idList.indexOf(id) == -1) {
				if (window.ActiveXObject) {
					// WINDOWS
					myPlaylist.entryXML = new ActiveXObject("Microsoft.XMLHTTP");
				} else if (document.implementation && document.implementation.createDocument) {
					// MOZILLA
					myPlaylist.entryXML = new XMLHttpRequest();
				}
				myPlaylist.entryXML.onreadystatechange = myPlaylist.addNewEntry;
				myPlaylist.entryXML.open("GET", '/_objectxml/' + id + '/detail.html', true);
				myPlaylist.entryXML.send(null);
			} else {
				//myPlaylist.highlight('last');
				//myPlaylist.setNextEntry();
			}
		}
		this.addNewEntry = function(){
			if (myPlaylist.entryXML.readyState == 4) {
				if(typeof myPlaylist.entryXML.responseXML == 'undefined') {
					theentry = myPlaylist.entryXML;
				} else {
					theentry = myPlaylist.entryXML.responseXML;
				}
				co = theentry.getElementsByTagName("video");
				imagesrc = 'http://images.ibsys.com/sh/images/videoplayer/genericvideo_8060.jpg';
				if(co[0].getElementsByTagName("ibs_image").length != 0) {
					imagesrcs = co[0].getElementsByTagName("ibs_image")[0].getElementsByTagName("src");
					for(i=0; i<imagesrcs.length; i++) {
						if (imagesrcs[i].getAttribute('width') == '60' && imagesrcs[i].childNodes[0].nodeValue != '') imagesrc = 'http://images.ibsys.com'+imagesrcs[i].childNodes[0].nodeValue;
					}
				}
				listlength = myPlaylist.entries.length;
				thisvideo = new entry(co[0].getAttribute('id'), co[0].getElementsByTagName('headline')[0].childNodes[0].nodeValue,1,imagesrc);	
				myPlaylist.entries.splice(myPlaylist.insertAt, 0, thisvideo);
				myPlaylist.updateCookie();
				myPlaylist.refreshPlaylist();
				myPlaylist.highlight('last');
				myPlaylist.setNextEntry();
				if(typeof updateChannelList != 'undefined') updateChannelList('current');
			}
		}

		this.setNextEntry = function() {
			if(typeof videoplayer != 'undefined') {
				for(a=0; a<myPlaylist.entries.length; a++) {
					if(myPlaylist.entries[a].id == videoplayer.videoid) {
						if(myPlaylist.entries[a+1]) myPlaylist.nextVideoID =  myPlaylist.entries[a+1].id;
						else myPlaylist.nextVideoID = 0;
						if(myPlaylist.entries[a-1])myPlaylist.previousVideoID =  myPlaylist.entries[a-1].id;
						else myPlaylist.previousVideoID = 0;
					}
				}
			}
		}
		this.getNextEntry = function() {
			return myPlaylist.nextVideoID;
		}
		this.move = function(from, to){
			pickup = myPlaylist.entries.splice(from, 1);
			myPlaylist.entries.splice(to, 0, pickup[0]);
			myPlaylist.dragonid = '';
			dragElement = null;
			getEl('dragon').style.display = 'none';
			getEl('dragon').innerHTML = '';
			myPlaylist.refreshPlaylist();
			myPlaylist.highlight(false);
			myPlaylist.updateCookie();
			myPlaylist.setNextEntry();
		}
		this.deleteID = function(id) {
			for(a=0; a<myPlaylist.entries.length; a++) {
				if(myPlaylist.entries[a].id == id) {
					myPlaylist.entries.splice(a, 1);
					//el = getEl('entry'+id);
					//myPlaylist.displayElement.removeChild(el);
				}
			}
			if(getEl('playlistlink'+id)) getEl('playlistlink'+id).style.visibility = 'visible';
			if(typeof videoplayer != 'undefined' && id == videoplayer.videoid) nextVideo();
			myPlaylist.refreshPlaylist();
			myPlaylist.highlight(false);
			myPlaylist.updateCookie();
			myPlaylist.setNextEntry();
			if(typeof videoplayer != 'undefined') updateChannelList('current');
		}
		this.getCurrentVideo = function() {
			currEntry == -1;
			for(a=0; a<myPlaylist.entries.length; a++) {
				if(myPlaylist.entries[a].id == videoPlayer.videoid) currEntry = a
			}
			if (currEntry > -1) return myPlaylist.entries[currEntry];
			
		}
		this.setCurrentVideo = function(id) {
			if(myPlaylist.idList.indexOf(id) == -1) {
				//myPlaylist.insert(id, 0);
			}
			if (window.ActiveXObject) {
				// WINDOWS
				myPlaylist.playEntry = new ActiveXObject("Microsoft.XMLHTTP");
			} else if (document.implementation && document.implementation.createDocument) {
				// MOZILLA
				myPlaylist.playEntry = new XMLHttpRequest();
			}
			myPlaylist.playEntry.onreadystatechange = myPlaylist.updatePlayer;
			myPlaylist.playEntry.open("GET", '/_objectxml/' + id + '/detail.html', true);
			myPlaylist.playEntry.send(null);
			videoplayer.videoid = id;
			myPlaylist.highlight('current');
			myPlaylist.setNextEntry();
			myPlaylist.updateCookie();
		}
		this.updatePlayer = function() {
			if(myPlaylist.playEntry.readyState == 4){
				if(typeof myPlaylist.playEntry.responseXML == 'undefined') {
					playentry = myPlaylist.playEntry;
				} else {
					playentry = myPlaylist.playEntry.responseXML;
				}
				co = playentry.getElementsByTagName("video");
				var id = co[0].getAttribute('id');
				var streams = co[0].getElementsByTagName('videostream');
				var videowmv = false;
				var videoflv = false;
				var videorm = false;
				var videormspeed = 0;
				for(var s=0; s<streams.length; s++) {
					if(streams[s].getAttribute('source') == 'ext_stream') {
						videowmv = true;
					} else if(streams[s].getAttribute('extension') == 'rm') {
						videorm = true;
						if(parseInt(streams[s].getAttribute('speed')) > videormspeed) {
							videormspeed = parseInt(streams[s].getAttribute('speed'));
							videormlocation = streams[s].getAttribute('location');
						}
					} else if (streams[s].getAttribute('extension') == 'wmv') {
						videowmv = true;
					} else if(streams[s].getAttribute('extension') == 'flv') {
						videoflv = true;
					}				
				}
				///
				if(streams.length == 0) {
					alert('No Video for This entry');
					return;
				} else if(activexVideo && videowmv) { // USE WINDOWS MEDIA PLAYER IF THEY HAVE IT AND THE VIDEO HAS IT
					if(typeof videoplug != 'undefined' && getEl('videoplug')){
						videoplug.URL = '../' + id + '/playlist.asx?qs=speed='+currentspeed;
					} else {
						out = '';
						out +='<OBJECT ID="videoplug"';
						out +=' CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"';
						out +=' CODEBASE="http://www.microsoft.com/netshow/download/en/nsmp2inf.cab#Version=5,1,51,415"';
						out +=' standby="Loading Microsoft Windows Media Player components..."';
						out +=' WIDTH="100%" HEIGHT="100%"';
						out +=' type="application/x-oleobject">';
						out +='<PARAM NAME="autoStart" VALUE="1" />';
						out +='<PARAM NAME="invokeURLs" VALUE="1" />';
						out +='<PARAM NAME="windowlessVideo " VALUE="1" />';
						out +='<PARAM NAME="mute" VALUE="0" />';
						out +='<PARAM NAME="URL" VALUE="../' + id + '/playlist.asx?qs=speed=' + currentspeed + '" />';
						out +='<PARAM NAME="uiMode" VALUE="none" />';
						out +='<PARAM NAME="stretchToFit" VALUE="true" />';
						out +='</OBJECT>';
						getEl('player').innerHTML = out;
						checkStatus();
					}
				} else if (embedVideo && videowmv) {
					//if(id != videoplayer.videoid) document.location = '../' + id + '/detail.html';
					// TO DO: USE DOM INSERTION
					getEl('player').innerHTML = '<embed id="videoplug" src="../' + id + '/playlist.asx?qs=speed=' + currentspeed + '" filename="../' + id + '/playlist.asx?qs=speed=' + currentspeed + '" width="320" height="283" type="application/x-mplayer2" autostart="1" showcontrols="1" transparentstart="1" showstatusbar="0" showtracker="1"></embed>';
				} else if (flashVideo && videoflv && flashPlayer) {
					// TO DO: USE DOM INSERTION
					//WRITE FLASH VIDEO PLUGIN ???
					out='';
					out +='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="320" height="285" id="scroller_videoplayer" align="middle">';
					out +='<param name="allowScriptAccess" value="sameDomain" />';
					out +='<param name="movie" value="/download/sh/images/flash/videoplayer_320x285.swf?sitekey=' + sitekey + '&cpcode=' + flashcpcode + '&coid=' + id + '" />';
					out +='<param name="quality" value="high" />';
					out +='<param name="bgcolor" value="#62649c" />';
					out +='<embed src="/download/sh/images/flash/videoplayer_320x285.swf?sitekey=' + sitekey + '&cpcode=' + flashcpcode + '&coid=' + id + '" quality="high" bgcolor="#62649c" width="320" height="285" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
					out +='</object>';
					getEl('player').innerHTML = out;
				} else if (haveRMP && videorm) {
					akamaiprefix = 'http://mfile.akamai.com/' + sitecpcode + '/rm/vod.ibsys.com/';
					url = videormlocation;
					urlend = url.indexOf('.rm');
					urlstart = url.indexOf('554//')+5;
					urllength = (urlend-urlstart);
					filelocation = url.substr(urlstart, urllength);
					realsrc = akamaiprefix + filelocation + '.ram';
					// TO DO: USE DOM INSERTION
					//WRITE FLASH VIDEO PLUGIN ???
					out='';
					out += '<div id="realplayer" style="width:320"><EMBED '
					+ 'SRC="' + realsrc + '" '
					+ 'CONSOLE="Clip1" '
					+ 'WIDTH="320" '
					+ 'HEIGHT="240" '
					+ 'LOOP="0" '
					+ 'CONTROLS="imagewindow" '
					+ 'TYPE="audio/x-pn-realaudio-plugin" '
					+ 'NAME="daPlaya" '
					+ 'ID="daPlaya" '
					+ 'AUTOSTART="true">'
					+ '</EMBED><br></div>'
					+ '<div style="position:absolute; display:block; left:0px; top:240px;"><OBJECT ID="RMConsole" HEIGHT="40" WIDTH="320" CLASSID="clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA">'
					+ '<PARAM NAME="controls" VALUE="ControlPanel">'
					+ '<PARAM NAME="console" VALUE="Clip1">'
					+ '<EMBED type="audio/x-pn-realaudio-plugin" id="RMConsole" width="320" height="40" controls="ControlPanel" console="Clip1"></embed></OBJECT></div>';
					getEl('player').innerHTML = out;	
				}		
				
				///
			
			
				
				//IF EITHER OF THESE ARE NULL I GET AN ERRROR ?????
				getEl('videoheadline').innerHTML = '';
				getEl('videoteaser').innerHTML = '';
				getEl('videoheadline').innerHTML = co[0].getElementsByTagName('headline')[0].childNodes[0].nodeValue;
				document.title = co[0].getElementsByTagName('headline')[0].childNodes[0].nodeValue;
				// put an 'if' around this because it was causing an error and my WebTrends code wasn't executing on videos with no teaser --crambo
				if ((co[0].getElementsByTagName('teaser').length > 0) && (co[0].getElementsByTagName('teaser')[0].childNodes.length > 0)) getEl('videoteaser').innerHTML = co[0].getElementsByTagName('teaser')[0].childNodes[0].nodeValue;
				adtracked = false;
				leaderboard = false;
				// TRACK THIS EVENT WITH WEBTRENDS
				var cgs = co[0].getAttribute('topic_path');
				if (cgs != null)  {
					var pattern = /\/([^\/]*)\//g;
					cgs = cgs.replace(pattern, "$1");
				} else {
					cgs = co[0].getAttribute('categoryname');
				}
				var coid = co[0].getAttribute('id');
				var pool = co[0].getAttribute('owner');
				var vtype = co[0].getAttribute('livestream');
				if (vtype != null && vtype == 'true') {
					vtype = 'Livestream';
				} else {
					vtype = 'Clickplay';
				}
				dcsMultiTrack('WT.ti',document.title,'DCSext.mtype','Video','DCSext.vtype',vtype,'WT.cg_s',cgs,'DCSext.ib_coid',coid,'DCSext.ib_pool',pool);
				/*var pattern=/\/([^\/]*)\//g;
				var cgs = cgs.replace(pattern, "$1");
				//if (cgs.charAt(0)=='/') cgs=cgs.substring(1);
				//if (cgs.charAt(cgs.length-1)=='/') cgs=cgs.substring(0, cgs.length-1);
				dcsMultiTrack('WT.ti',document.title,'WT.cg_s',cgs,'DCSext.ib_pool','','DCSext.ib_coid','');*/
			}
		}
		this.highlight = function(show) {
			if(typeof videoplayer != 'undefined') {
				for(a=0; a<myPlaylist.entries.length; a++) {
					if(myPlaylist.entries[a].id == videoplayer.videoid ) {
						getEl('entry'+myPlaylist.entries[a].id).className = 'entryon';
						if(show && show == 'current') getEl('playlist').scrollLeft = a*150;
					} else {
						getEl('entry'+myPlaylist.entries[a].id).className = 'entry';
					}
				}
				if(show && show == 'last') getEl('playlist').scrollLeft = a*150;
			}
		}
		this.updateCookie = function() {
			myPlaylist.idList = '';
			for(a=0; a<myPlaylist.entries.length; a++) {
				if(a!=0) myPlaylist.idList += ',';
				myPlaylist.idList += myPlaylist.entries[a].id;
			}
			path = '/';
			domain = document.domain;
			secure = false;
			var expires = new Date();
			expires.setTime(expires.getTime() + (240 * 3600000)); // 10 days in the future
			var curCookie =  "ibsPlaylist=" + escape(myPlaylist.idList) +
				((expires) ? "; expires=" + expires.toGMTString() : "") +
				((path) ? "; path=" + path : "") +
				((domain) ? "; domain=" + domain : "") +
				((secure) ? "; secure" : "");
				document.cookie = curCookie;
		}
	} else {
		return false;	
	}
}

function entry(id, h, t, i) {
	this.id = id;
	this.teaser = t;
	this.headline = h;
	this.image = i;
	this.getDisplayElement = function(p) {
		this.displayElement = document.createElement('div');
		this.displayElement.setAttribute('id', 'entry'+id);
		this.displayElement.setAttribute('className', 'entry');
		this.displayElement.setAttribute('class', 'entry');
		this.displayElement.onmouseover = function() {
			if(dragElement && dragElement == getEl('dragon') && this.className != 'entryon' && this.className != 'selectedentry') {
				this.className = 'entryover';
			} else if(!dragElement && this.className == 'entry') {
				this.className = 'entryhover';
			}
		}
		this.displayElement.onmouseup = function() {
			if(dragElement && dragElement == getEl('dragon')) {
				myPlaylist.move(myPlaylist.dragonpos, p);
			}
		}
		this.displayElement.onmouseout = function() {
			if(this.className != 'selectedentry' && this.className != 'entryon') {
				this.className = 'entry';	
			}
		}
		del = document.createElement('a');
		del.setAttribute('class', 'delete');
		del.setAttribute('className', 'delete');
		del.setAttribute('videoid', id);
		del.appendChild(document.createTextNode('Remove'));
		del.onclick = function() {
			myPlaylist.deleteID(this.getAttribute('videoid'));
		}
		play = document.createElement('a');
		play.setAttribute('class', 'play');
		play.setAttribute('className', 'play');
		play.setAttribute('videoid', id);
		play.appendChild(document.createTextNode('Play'));
		play.onclick = function() {
			if(typeof videoplayer != 'undefined') myPlaylist.setCurrentVideo(this.getAttribute('videoid'));
			else window.open('/dayportvideo/' + this.getAttribute('videoid') + '/detail.html', 'videoplayer', 'width=200,height=200');
		}
		handle = document.createElement('div');
		handle.setAttribute('class', 'handle');
		handle.setAttribute('className', 'handle');		
		handle.setAttribute('drag','slide');
		handle.setAttribute('videoid', id);
		handle.appendChild(document.createTextNode(' '))
		handle.onmousedown = function() {
			myParent = getEl('entry'+this.getAttribute('videoid'));
			getEl('dragon').innerHTML = myParent.innerHTML;
			getEl('dragon').style.display = 'block';
			myParent.className= 'selectedentry';
			myPlaylist.dragonpos = p;
			myPlaylist.dragonid = this.getAttribute('videoid');
		}
		this.displayElement.appendChild(handle);
		img = document.createElement('img');
		img.setAttribute('src', i);
		img.setAttribute('alt', h);
		img.setAttribute('width', 60);
		img.setAttribute('height', 45);
		br = document.createElement('br');
		this.displayElement.appendChild(img);
		this.displayElement.appendChild(br);
		hdln = document.createElement('div');
		hdln.setAttribute('class', 'headline');
		hdln.setAttribute('className', 'headline');
		hdln.appendChild(document.createTextNode(this.headline))
		this.displayElement.appendChild(hdln);
		this.deleteButton = this.displayElement.appendChild(del);
		this.playButton = this.displayElement.appendChild(play);
		return this.displayElement
	}

}
function getEl(id){
	return document.getElementById(id);
}

