IFILM.AdObj = function(targ, scriptSrc, confObj, disableRefresh, showCallout) {
	this.targ = targ;
	this.scriptSrc = scriptSrc;
	this.disableRefresh = disableRefresh || false;
	this.showCallout = showCallout || false;
	this.config = confObj || {
		width: '300',
		height: '251',
		FRAMEBORDER: "0",
		border: "0",
		marginwidth: "0",
		marginheight: "0",
		hspace: "0",
		vspace: "0",
		scrolling: "no", 
		style: "border: none",
		src: "/iframe/vciframesrc.jsp?advurl=" + encodeURIComponent(scriptSrc),
		allowtransparency: 'true'
	}
	IFILM.adManager.addAd(this);
	safelog("Ad Object created with scriptSrc:" + scriptSrc, "info", "IFILM.AdObj");	
}

IFILM.AdObj.prototype = {
	previouslyHidden: false,
	display: function() {
		var displayAt = jq('#' + this.targ).get(0);
		if(displayAt && displayAt.tagName) {
			var iframe;
			if(displayAt.tagName.toLowerCase() != "iframe") {
				var na = new NodeAssembly(displayAt);
				if(this.showCallout)
					na.createEl('p', {'class':'ad_callout'}, 'ADVERTISEMENT');
				var iframe = na.createElWithReturn("iframe", this.config);
				na.insertIn();
			} else {
				var iframe = displayAt;
			}
			
			safelog(this.scriptSrc);
			
			this.targetFrame = iframe;
			this.addHeightAdjustTrigger();
			
			var scriptTag= this.createAdString();
			this.dispatchAd(scriptTag);
		}
	},
	
	adjustHeight: function(targetFrame) {
		var cw = targetFrame.contentDocument || targetFrame.contentWindow.document;
		try {
			if(cw) {
				var atHTML = cw.getElementsByTagName("html")[0];
				if(atHTML) {
					var docSize = cw.body.scrollHeight || atHTML.offsetHeight;
					var rawSize = targetFrame.height;
					
					if(Math.abs(docSize - rawSize) > 20 && docSize < 700)
						targetFrame.height = docSize;
				}
				
				if(jq("img[src='http://m1.2mdn.net/viewad/817-grey.gif']", cw).get(0))
					jq(targetFrame).parent().hide();
			}
		} catch(e) {
			safelog("Error auto-resizing ad " + e, "Error", "IFILM.AdObj.adjustHeight");
		}
	},
	
	addHeightAdjustTrigger: function() {
		var adjustHeight = this.adjustHeight;
		if(this.targ != 'globalTextAdUnit') {
			jq(this.targetFrame).load(function(e) {
				adjustHeight(this);
			});
		}
	},
	
	createAdString: function() {
		var scriptTag = "/iframe/vciframesrc.jsp?advurl=" + encodeURIComponent(this.scriptSrc);
		scriptTag +=  "&ifilmrnd=" + Math.round(Math.random() * 1000000) + '-' + Math.round(Math.random() * 1000000);
		return scriptTag;
	
	},
	dispatchAd: function(adString) {
		if(this.targetFrame ) {
			var dispatcher = this.targetFrame.contentDocument || this.targetFrame.contentWindow.document; 
			var adLoc = adString || this.createAdString();
			this.adDisplayed = true;
		}
		
	},
	targetFrame: null,
	adDisplayed: false,
	refresh: function() {
		jq('#' + this.targ).empty();
		this.display();
	},
	styleref: [
		'<style type="text/css">',
		'body {margin:0; padding: 0; border: none; }',
		'</style><style type="text/css">',
		'a img { border: none; }',
		'</style>'
	]

}

IFILM.adManager = {
	ads: [],
	banner: null,
	ad_refresh_rate: null,
	timer: 10,
	textAd: function(msg) {
		if(StringUtils.trim(jq("#globaltxtad").html()) != '')
			jq("#globaltxtad").fadeOut("normal", function() { jq("#globaltxtad").html(msg); });
		else
			jq("#globaltxtad").html(msg);
			
		jq('#globaltxtad a').html(StringUtils.truncate(jq("#globaltxtad a").html(),60));
		jq('#globaltxtad').fadeIn("normal");
		
		//if(document.location.toString().indexOf('show') != -1)
			//jq('body').css('background-position', 'center 14px');
	},
	hideChannelPlayer: function() {
		jq('#SUPPLEMENT embed,#SUPPLEMENT object').css('display', 'none');
	},
	revealAds: function() {
		var adLim = IFILM.adManager.ads.length;
		for(i = 0; i < adLim; i++) {
			if(!IFILM.adManager.ads[i].previouslyHidden)
				jq('#' + IFILM.adManager.ads[i].targ + ' *').css('visibility', 'visible');
		}

		jq('body>iframe').not('#dsHistoryFrame').css('visibility','visible');
	},
	obscureAds: function() {
		var adLim = IFILM.adManager.ads.length;
		for(i = 0; i < adLim; i++) {
			if(jq('#' + IFILM.adManager.ads[i].targ).css('visibility') == 'hidden' || jq('#' + IFILM.adManager.ads[i].targ).css('display') == 'none')
				IFILM.adManager.ads[i].previouslyHidden = true;
				
			jq('#' + IFILM.adManager.ads[i].targ + ' *').css('visibility', 'hidden');
		}
		
		
		jq('body>iframe').not('dsFrame').css('visibility','hidden');
	},
	displayAds: function() {
		var adlim = this.ads.length;
		for(var x=0; x<adlim; x++)  {
			try {
				if(this.ads[x]) { this.ads[x].display(); }
			} catch(e) { safelog(e, "ERROR", "IFILM.adManager.displayAds"); }
			//this.ads[x] = null;
		}
	},
	refreshAds: function() {
		
		var adlim = this.ads.length;
		for(var x=0; x<adlim; x++) {
			if(this.ads[x].targ == 'HEADERAD') { 
				//jq('#HEADER').removeClass('ad-fullheader').css('background-image', 'url(http://dyn.ifilm.com/website/ver2/header_bg.png)') ;
				jq("#IFILM iframe").remove();
				jq('#HEADER .click_through').remove();
			}
			
			//jq('body iframe:last').remove();
			
			if(this.ads[x] && !this.ads[x].disableRefresh) { 
				this.ads[x].refresh(); 
			} else {
				safelog("reloading ad disabled for " + (x+1) + " of " + adlim, "info", "IFILM.adManager");
			}
		}
	},
	addAd: function(adObj) {
		if(adObj.display) {
			this.ads.push(adObj);
		}
	},
	displayAdsGeneric: function() {
		IFILM.adManager.displayAds();
	},
	displaySkin: function(frame) {
	},
	attachSkin: function(style_src) {
		var stylesheets = document.getElementsByTagName('link');
		var has_stylesheet = false;
		stylesheetLim = stylesheets.length;
		
		for(i = 0; i < stylesheetLim; i++) {
			if(style_src == stylesheets[i].href) {
				has_stylesheet = true;
			}
		}
		
		if(!has_stylesheet) {
			var parent_head = document.getElementsByTagName('head')[0];
			var e = document.createElement('link');
			e.type = 'text/css';
			e.href = style_src;
			e.rel = 'stylesheet';
			e.media = 'screen';
			parent_head.appendChild(e);
		}
	},
	hideAds: function(hideEl) {
		if(hideEl) { 
			hideEl.style.display = "none";
			if(hideEl.parentNode) {
				hideEl.parentNode.style.display="none";
				jq('#' + hideEl.parentNode.id + '_top, #' + hideEl.parentNode.id + '_bottom').css('display','none');
			}
		}
	},
	makeFullheader: function(url, clickThrough) {
		
		
		//if(jq.browser.msie && jq.browser.version < 7) {
		//	url = url.replace(/\.png/,'.jpg');
		//}
		
		//jq('#HEADER').css({'background-image': 'url('+url+')', 'background-repeat': 'no-repeat', 'background-position': 'top left'}).addClass('ad-fullheader').end();
		jq("#HEADERAD").css({'visibility': 'hidden', 'border':'0'});
		
		if(clickThrough)
			jq('#HEADER').prepend('<a href="' + clickThrough + '" target="_blank" class="click_through clearfix">&nbsp;</a>');
	
		if(jq.browser.msie && jq.browser.version < 7)
			jq('#HEADER a.click_through').css('z-index', '2000');
			
		jq('#LOGO a').css({position: 'relative', 'z-index': '2000'});
		
		jq('#HEADER .click_through').css({ 'top': '94px', 'left': jq('#BODYCONTENT').offset().left + 'px'});
		
			
			
	}, 
	createInterstitial: function(width) {
		if(!width) width = 600;
		try {
			tbGenerateOverlay();		
			jq('#INTERSTITIAL').before('<div id="timer">SPIKE.com will appear in <span id="timercount">:0' + IFILM.adManager.timer + '</span> seconds</div>');
			jq("#INTERSTITIAL").before('<div id="closead"><a href="#" id="closeadlink">Continue to SPIKE.com</a>');
			
			jq('#TB_window').remove();
			jq("#TB_overlay,#closeadlink").click(IFILM.adManager.removeInterstitial);
		} catch(e) { safelog(e); }
		
		jq(document).keyup(function(e) {
			if (e == null) // ie
				keycode = event.keyCode;
			else // mozilla
				keycode = e.which;
				
			if(keycode == 27) // close
				IFILM.adManager.removeInterstitial();
		});
		
		if(ie)
			 jq('html').css('overflow', 'hidden');
		
		if(width == 300) {
			jq('#INTERSTITIAL iframe,#INTERSTITIAL').css({ "width":"300px", "height":"250px"});
			jq('#timer').css('margin-top','75px');
		}
		
				 
		jq('#INTERSTITIAL').css({'margin-left':'-' + width/2 + 'px', 'margin-top':'-200px'}).show();
		
		jq("body>iframe,body>embed,body>object,#BODYCONTENT iframe, #BODYCONTENT embed, #BODYCONTENT object").css('visibility', 'hidden');
		IFILM.adManager.obscureAds();
		setTimeout(IFILM.adManager.incrementTimer, '1000');	
		IFILM.cookieManager.setSessionCookie('prestitial', true);
		
		if ( !(jQuery.browser.msie && jQuery.browser.version < 7) ) // take away IE6
			jq("#INTERSTITAL").css({marginTop: '-' + parseInt((200 / 2),10) + 'px'});
		
	},
	removeInterstitial: function(e) {
		if(e) { preventDefault(e); }
		
		jq("#TB_overlay").fadeOut("fast",function(){jq('#closead,#gt_link,#timer,#INTERSTITIAL,#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
		jq(document).unbind("keyup");
		jq("#closeadlink").unbind()
		
		jq("body>iframe,body>embed,body>object,#BODYCONTENT iframe,#BODYCONTENT embed,#BODYCONTENT object").css('visibility', 'visible');
		IFILM.adManager.revealAds();
				
		if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
			jq("body","html").css({height: "auto", width: "auto"});
			jq("html").css("overflow","");
		}
	},
	incrementTimer: function() {
		IFILM.adManager.timer--;
		
		jq('#timercount').html(':0' + IFILM.adManager.timer);
		if(IFILM.adManager.timer != 0)
			setTimeout(IFILM.adManager.incrementTimer,'1000');
		else
			IFILM.adManager.removeInterstitial();
	},
	reskinningUnit: function(imageUrl, bgColor) {
		IFILM.adManager.reskinPage(imageUrl, bgColor);
		jq("#BODYCONTENT").css('background-color', 'transparent');
		jq('#ad1div iframe').css({'position': 'relative', 'width':'330px', 'height': '270px', 'background': 'transparent none'});
		jq('#ad1div').css({'background': 'transparent none', 'border': 0, 'padding': 0, 'margin-bottom': '20px'});
		jq("#ad1div_top, #ad1div_bottom").remove();
		
		setTimeout(IFILM.adManager.removeTopBottom, 250)
	},
	reskinPage: function(imageUrl, bgColor) {
		jq('body').css('background', bgColor + ' url(' + imageUrl + ') no-repeat top center');
	},
	removeTopBottom: function() {
		if(jq('#ad1div_top').get(0))
			jq("#ad1div_top,#ad1div_bottom").remove();
		else
			setTimeout(IFILM.adManager.removeTopBottom, 250)
	}
}

function textAd(msg) {
	IFILM.adManager.textAd(msg);
}

/* GLOBAL AD STUFF FROM FRAME 0 */

var adid = "";
var query = window.location.search.substring(1);
var queryparams = query.split("&");
/*  Global Adv Vars for Dart */
ord=Math.random()*10000000000000000;
var dartRef, hbxRef, refsiteSession, reftypeSession;
/* Global Analytics Vars and Refsite Session Cookie for HBX */
refsiteid = "";
referralType = "";

pageLoadFuncs.push(function() {	
	//ad refresh rate and displaying the ads, handled as the last function of global functions
	window.setTimeout(IFILM.adManager.displayAdsGeneric, 1000);
	try {
		var min = 10000;
		
		if(!IFILM.adManager.ad_refresh_rate || IFILM.adManager.ad_refresh_rate == '') 
			return;		
			
		ad_refresh_rate = IFILM.adManager.ad_refresh_rate;			
		var valInSeconds = parseInt(ad_refresh_rate)*1000;
		
		if(isNaN(valInSeconds) || valInSeconds < min) {
			valInSeconds = min;
		}
		safelog("reload interval: " + valInSeconds, "INFO", "ad refresh interval");
		
		var z = window.setInterval('IFILM.adManager.refreshAds()', valInSeconds);
	} catch(e) {
		safelog("problem reloading " + e.message, "ERROR", "ad refresh interval");
	}
});

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Javascript function for Flash tagging
function resolveLink(args){

//alert(args);
  var string=document.location.href; 
 

  if  ( string.indexOf("http://surveys.relevantview.com/sbox/asandboxdev.sbt/")  != -1)
  {
	  var getrev= new Array();
	  var getrev=string.split("http://surveys.relevantview.com/sbox/asandboxdev.sbt/");
	  var result=getrev[1];
	  var filename=result.split("/"); 
	   
	  var filenamefinal=filename[0];
	  var filenamefinal=result.split(",");
	  var respondentid = filenamefinal[0];
	  var surveyid = filenamefinal[1];
	  var questionid = filenamefinal[2];
	  var url1 = filename[1];
	  var url2 = filename[2]; 
	
	
		//alert("http://surveys.relevantview.com/sbox/asandboxdev.sbt/" + respondentid + "," + surveyid  + "," + questionid+",1,0/http/www.tvland.com/" + args);
	
		if (args.indexOf("http://") != -1)
	
			{
	
				args = args.replace(new RegExp(/^http:\/\//i),"http/");
	  
	  			document.location.href = "http://surveys.relevantview.com/sbox/asandboxdev.sbt/" + respondentid + "," + surveyid  + "," + questionid  +",1,0/" + args;
			}
	
		else
		{
	
			document.location.href = "http://surveys.relevantview.com/sbox/asandboxdev.sbt/" + respondentid + "," + surveyid  + "," + questionid  +",1,0/" + url1 + "/" + url2  + args;
		}
  }
  else
  {
	  document.location.href =  args;
  } 
}

 
 
// Javascript function for Flash tagging
function getLocation() { 

	var string=document.location.href; 
	if  ( string.indexOf("http://surveys.relevantview.com/sbox/asandboxdev.sbt/")  != -1)
	{
		var getrev= new Array(); 
		var getrev=string.split("http://surveys.relevantview.com/sbox/asandboxdev.sbt/"); 
		var result=getrev[1]; 
		var filename=result.split("/"); 
		     
		var filenamefinal=filename[0];
		var filenamefinal=result.split(","); 
		var respondentid = filenamefinal[0];
		var surveyid = filenamefinal[1];
		var questionid = filenamefinal[2];
		var url1 = filename[1];
		var url2 = filename[2];
		var url;
		if (args.indexOf("http://") != -1)

		{
			args = args.replace(new RegExp(/^http:\/\//i),"http/");
  
  			url = "http://surveys.relevantview.com/sbox/asandboxdev.sbt/" + respondentid + "," + surveyid  + "," + questionid  +",1,0/" + args;
		}

		else
		{
			url = "http://surveys.relevantview.com/sbox/asandboxdev.sbt/" + respondentid + "," + surveyid  + "," + questionid  +",1,0/" + url1 + "/" + url2  + args;
		}
		
	}  
	else
	{  
		var url = document.domain;
	}
	 return url;
}





// Relevant View Java Script - END!!!!!!
// Fix for Norton preventing playback
var advurl = "";
	
var IFILMPlayer = {
	playerObj:null, 
	playerFrame:null, 
	init: function() {
		try {
			var atProduct = jq("#PRODUCT_FRAME").get(0);
			var atProductObj = jq("#PRODUCT_OBJECT").get(0);
			var atSupp = jq("#SUPPLEMENT").get(0);
			if (atProductObj) {
				this.playerObj = atProductObj;
				this.playerFrame = atProduct;
			}
		}
		catch (e) {
			safelog("error setting anims: " + e.message, "error", "IFILMPlayer.init");
		}
	}
	
};


var AutoPlayManager = {
	index: 0,
	videoList: null,
	turnOff: function() {
		IFILM.cookieManager.setSessionCookie("playNext", "0");
		jq("#autoplay").hide();
		jq("#SIMILARLIST li").removeClass('active')
	},
	turnOn: function() {
		IFILM.cookieManager.setSessionCookie("playNext", "1");
		
		jq("#autoplay").show();
		jq(AutoPlayManager.videoList.get(AutoPlayManager.index)).addClass('active');
	},
	playNext: function() {
		var metadata = player.getMetadata();
		
		if(metadata.isAd)
			return false;
		
		if(jq("#SIMILARLIST").get(0) && parseInt(IFILM.cookieManager.getSessionCookie("playNext")))
			document.location = jq(AutoPlayManager.videoList.get(AutoPlayManager.index)).find("a.tn_frame").attr('href');
	},
	highlight: function() {
		if(parseInt(IFILM.cookieManager.getSessionCookie("playNext")))
			jq('#autoplay strong').css('color', '#333');
		else
			jq('#autoplay strong').css('color', '#999');
	},
	changeNext: function(dir) {
		if(dir == 'next')
			AutoPlayManager.index++;
		else
			AutoPlayManager.index--;
			
		if(AutoPlayManager.index >= AutoPlayManager.videoList.size())
			AutoPlayManager.index = 0;
		else if (AutoPlayManager.index < 0)
			AutoPlayManager.index = AutoPlayManager.videoList.size()-1;
		
		AutoPlayManager.videoList.removeClass('active');
		jq(AutoPlayManager.videoList.get(AutoPlayManager.index)).addClass('active');
		
		title = jq(AutoPlayManager.videoList.get(AutoPlayManager.index)).find('.tn_frame').attr('title');
		vid_link = jq(AutoPlayManager.videoList.get(AutoPlayManager.index)).find('.tn_frame').attr('href');
		jq('#autoplay p span').html('<a class="link_title" href="' + vid_link + '">' + StringUtils.truncate(title, 42) + '</a>');
	},
	init: function() {
		AutoPlayManager.videoList = jq("#SIMILARLIST ol li");
		
		if(IFILM.cookieManager.getSessionCookie("playNext") == null)
			IFILM.cookieManager.setSessionCookie("playNext", "1");
			
		if(parseInt(IFILM.cookieManager.getSessionCookie("playNext"))) {
			jq('#continuous_play').attr('checked', 'checked');
		} else {  jq('#autoplay').hide(); }
		
		jq("#continuous_play").click(function(e) {
			if(this.checked)
				AutoPlayManager.turnOn();
			else
				AutoPlayManager.turnOff();
			
			AutoPlayManager.highlight();
		});
		
		jq('#autoplay a').click(function(e) {
			if(e) preventDefault(e);
			
			id_parts = jq(this).attr('id').split('_');
			
			AutoPlayManager.changeNext(id_parts[1]);
		});
		
		AutoPlayManager.highlight();
	}
};

var PlaylistManager = {
	listEl:null, 
	listItems:[], 
	listTriggers:[], 
	listIndex:{}, 
	current:null, 
	player:null, 
	scrollUpAnim:null, 
	scrollDownAnim:null, 
	scrollToAnim:null, 
	listElHeight:0, 
	listItemHeight:0, 
	autoRefresh:false, 
	isMiniPlayer:false, 
	loaded:false, 
	getPlayer:function () {
		this.player = jq("#PRODUCT_OBJECT").get(0);
	}, 
	getPlaylist:function () {
		this.listEl = jq("#more_clips").get(0);
		if (this.listEl) {
			this.autoRefresh = jq(this.listEl).is('.pagerefresh');
			
			var testRe = /popupplayer/;
			this.isMiniPlayer = testRe.test(window.location.pathname);
			jq("#more_clips td.songName a.play_video").each(function(e) {
				try {
					PlaylistManager.listTriggers.push(this);
					if(jq(this).parent('td.songName').is('.active') || jq(this).parents('tr').is('.active')) {
						PlaylistManager.current = jq(this).parent('td.songName').parents('tr').get(0);
					}
				} catch(e) { safelog(e); }
			});
			return true;
		}
		return false;
	}, addTriggers:function () {
//		jq(this.listTriggers).click(this.autoPlayOnClick);
	}, getFidFromEl:function (el) {
		var myId = el.id;
		return myId.split("_")[1];
	}, getElIdFromFid:function (fid) {
		return "pl_" + fid;
	}, hilightCurrent: function (el, historyObject) {	
		
		jq('#pl_' + el).each(function(i) {	
			try { 
				jq(PlaylistManager.current).removeClass('active');
				PlaylistManager.current = this.parentNode;
				jq(PlaylistManager.current).addClass('active');
				jq('#playList').get(0).scrollTop = PlaylistManager.current.offsetTop;
				var el_id = jq("a", this).attr("id");
				if(el_id)
					var type_id = el_id.split("_")[2];
				
				PlaylistManager.refreshMetaData(el, type_id);
				
				
			} catch(e) {
				safelog(e, "ERROR", hilightCurrent);
			}
		});
		
	}, refreshMetaData:function (id, type_id) {
		CollectionVideoManager.switchVideo(id);
		VoteManager.changeVote(id, type_id);
	}, autoPlay: function (el, historyObject) {
		safelog(el.id, "info", "argument");
		
		if (isNaN(el)) {
			if(!el || el == undefined)
				el = jq('#more_clips tr').get(1);
				
			var myId = el.id;
			safelog("autoplaying: " + myId, "info", "PlaylistManager.autoplay");
			if (PlaylistManager.autoRefresh) {
				var atags = el.getElementsByTagName("a");
				if (atags) {
					document.location.href = atags[0].href;
					return;
				}
			}
			var fid = myId.split("_")[1];
		
		} else {
			var fid = el;
		}
		if (!PlaylistManager.player) {
			PlaylistManager.getPlayer();
		}
		if (PlaylistManager.player && PlaylistManager.player.callMethod) {
			PlaylistManager.player.callMethod("[ \"gotoCommand\", \"" + fid + "\"]");
		}
		
		//if(!isNaN(fid))
			//CollectionVideoManager.switchVideo(fid);
	}, autoPlayOnClick:function (e) {
		PlaylistManager.getPlayer();
		if (PlaylistManager.player) {
			if (e) { preventDefault(e); }
			var line = this.parentNode.parentNode;
			PlaylistManager.autoPlay(line);
			blurel(this);
		}
	}, setPlayNext:function (is_active) {
		if (!PlaylistManager.player) {
			PlaylistManager.getPlayer();
		}
		PlaylistManager.player.callMethod("[ \"setGlobalVariables\", false, { \"shouldPlayNext\" : " + is_active + "} ]");
	}, togglePlayNext:function (e) {
		if (e) {
			var is_active = jq(this).is('.active');
			preventDefault(e);
			if (is_active) {
				jq(this).removeClass('active');
			} else {
				jq(this).addClass('active');
			}
		}
		if (!PlaylistManager.player) {
			PlaylistManager.getPlayer();
		}
		PlaylistManager.player.callMethod("[ \"setGlobalVariables\", false, { \"shouldPlayNext\" : " + !is_active + "} ]");
	}, stopAutoPlay:function () {
		if (!PlaylistManager.player) {
			PlaylistManager.getPlayer();
		}
		PlaylistManager.player.callMethod("[ \"setGlobalVariables\", false, { \"shouldPlayNext\" : " + false + "} ]");
	}, playNext:function (last) {
		var el = null;
		if (last == undefined || last == "") {
			el = this.current;
		} else {
			el = jq(this.getElIdFromFid(last)).get(0);
		}
		if (el) {
			var idx = this.listIndex[el.id];
			if (this.listItems[idx + 1]) {
				this.autoPlay(this.listItems[idx + 1]);
					//IFILM.adManager.refreshAds();
			}
		}
	},
	init:function () {
		window.getMedia = function (a) {
			PlaylistManager.playNext(a);
		};
		if (this.getPlaylist()) {
			this.getPlayer();
			this.addTriggers();
			if (!this.isMiniPlayer) {
				this.resetScrolls();
			}
			window.setTimeout(function () {
				PlaylistManager.tryStartPlay();
			}, 2 * 1000);
			var playlist_height = parseInt(jq("#playList").css("height"));
			var table_region = jq("#more_clips").offset();
			var table_height = (jq("#more_clips").outerHeight()+table_region.top) - table_region.top;
			if (table_height < playlist_height) {
				jq("#playList").css("height", table_height + "px");
			}
		}
		
		
	}, tryStartPlay:function () {
		if (!this.current) {
			this.autoPlay(this.listItems[0]);
		}
	}
};

var CollectionVideoManager = {
	realtimeServer: null,
	curEntity:null, 
	curEntityType:null, 
	collectionTable:null, 
	collectionContainer:null, 
	collectionTrigger:null, 
	curObj: null,
	openEntities:function (e) {
		if (e) { preventDefault(e); }
		var lower = false;
		if (this.id == "commenttriggerlower") {
			lower = true;
		}
		if (lower) {
			CollectionVideoManager.collectionTable = jq("#collection_comments_lower").get(0);
			CollectionVideoManager.collectionContainer = jq("#commentsExpLower").get(0);
		} else {
			CollectionVideoManager.collectionTable = jq("#collection_comments").get(0);
			CollectionVideoManager.collectionContainer = jq("#commentsExp").get(0);
		}
		CollectionVideoManager.toggle(this);
		CollectionVideoManager.collectionTrigger = this;
	}, updateForm:function(is_commentable) {

		if(is_commentable) {
			var form = jq("#leavecomment");
			var form_el = form.get(0);
			jq('#current_comment').hide();
			if(!jq('.newcomment').get(0)) {
				jq('#comment_IFILMEntityId').val(CollectionVideoManager.curEntity);
				jq('#comment_IFILMEntityTypeId').val(CollectionVideoManager.curEntityType);
				jq('#current_comment').html('You are commenting on: <strong>' + CollectionVideoManager.curObj.titleParts[CollectionVideoManager.curObj.titleParts.length-1].label + '</strong>');
			} else {
				form.empty();
				var na = new NodeAssembly(form_el);
				var loading = na.createElWithAssembly('div', {'id':'comment_loading'});
				loading.createEl('h3', {}, 'Saving your comment...');
				loading.createEl('img', {'src':'http://dyn.ifilm.com/website/loadingAnimation.gif'});
				
				var fieldset = na.createElWithAssembly('fieldset');
				fieldset.createEl('legend', {}, 'Leave a Comment');
				fieldset.createEl('div', {'id':'current_comment'}, { htmlStr: 'You are commenting on: <strong>' + CollectionVideoManager.curObj.titleParts[CollectionVideoManager.curObj.titleParts.length-1].label + '</strong>' });
				fieldset.createEl('textarea', { 'rows': 10, 'cols': 45, 'name': 'body', 'id': 'commentfield' });
				fieldset.createEl('input', {'type': 'hidden', 'name':'IFILMEntityId', 'id':'comment_IFILMEntityId', 'value':CollectionVideoManager.curEntity});
				fieldset.createEl('input', {'type': 'hidden', 'name': 'IFILMEntityTypeId', 'id':'comment_IFILMEntityTypeId', 'value': CollectionVideoManager.curEntityType});
				fieldset.createEl('input', {'type':'submit', 'name':'addComment', 'value': 'Leave A Comment', 'id': 'submit_comment_btn', 'class': 'submit_comment_btn'});
				na.insertIn();
			}
			jq('#current_comment').fadeIn("slow");
		    jq('#comment_container').fadeIn("slow");
		    jq('#comment_box').fadeIn("slow");
		    jq('#submitcomment').fadeIn("slow");
		} else {
		    jq('#comment_container').hide();
		    jq('#comment_box').hide();
		    jq('#submitcomment').hide();
            jq('#comment_count').hide();
			
		}
		
	}, switchVideo:function (id) {
		CollectionVideoManager.curEntity = id;
		CollectionVideoManager.curEntityType = 1;
		
		var url = document.location.toString().split("?");
		LoadEntityDWR.getEntityForDWR(CollectionVideoManager.curEntity, CollectionVideoManager.curEntityType, 1, 10, url[0] + "?st=" + this.curEntityId, {callback:CollectionVideoManager.success, errorHandler:CollectionVideoManager.failure, httpMethod: 'GET'});
	}, updateIdsAndTitles:function (o) {
		jq("#send_ifilmentityid").val(o.id);
		jq("#send_ifilmentitytypeid").val(o.entityTypeId);
		jq("send_contentid").val(o.id);
		jq("#EMAIL_SUBJECT").val(o.title);
		
		jq('.tool-favorites').attr({'id':'favorites_' + o.id, 'href': jq('.tool-favorites').attr('href').replace(/favoritesSelection=[0-9]*/, 'favoritesSelection=' + o.id)});
		jq('#embed_code').val(jq('#embed_code').val().replace(/flvbaseclip=[0-9]*/, 'flvbaseclip=' + o.id));
		var embed_link = jq('#embed_link');
		jq('#clip_embed_code').empty();
		
		var na = new NodeAssembly(jq('#clip_embed_code').get(0));
		na.createEl('label', {'for': 'url'}, 'URL');
		na.createEl('input', {'type': 'text', 'name': 'url', 'id': 'url', 'onclick': 'this.select()', 'value': 'http://www.spike.com' + o.URL});
		if (o.embeddable) {
			na.createEl('label', {'for':'embed_link'}, 'Clip Embed Code:');
			na.createEl('input', {'type':'text', 'name':'embed', 'id':'embed_link', 'onclick':'this.select()', 'value':jq('#embed_code').val(), 'class':'embed_text'});
		}
		na.insertIn();
	}, success:function (commentList) {
		safelog("comments successfully retrieved", "INFO", "CollectionVideoManager");
		CollectionVideoManager.curObj = commentList;
		try {			
			jq("#CLIP_DESCRIPTION h1").html(commentList.title);
			jq("#CLIP_DESCRIPTION h2").remove();
			jq("#CLIP_DESCRIPTION h1").after('<h2><a href="' + commentList.show.url + '">' + commentList.show.title + "</a></h2>");
			
			
			jq("#CLIP_DESCRIPTION a.tool-share").each(function(i) {
				this.id = this.id.replace(/share_[0-9]*|([0-9])/, "share_" + commentList.id + "|$1");
			});
		}
		catch (e) {
			safelog(e, "ERROR", "CollectionVideoManager.success");
		}
		
		var desc = jq("#this_description");
		if (desc.get(0)) {
			desc.empty();
			var na = new NodeAssembly(desc.get(0));
			na.createEl("a", {"href":"/channel/" + commentList.primaryChannel, "class":"primarytype"}, commentList.primaryDisplayChannel);
			na.createEl("span", {}, {htmlStr:" - " + commentList.description});
			na.insertIn();
		}
		jq("#date_posted").html("Posted " + commentList.createFormatted);
		var stats = jq("#viewscomm");
		stats.empty();
		na = new NodeAssembly(stats.get(0));
		na.createEl("strong", {"class":"first-child"}, "Views:");
		na.createEl("span", {"id": "viewCountText"}, StringUtils.numberFormat(commentList.viewsTotal));
		na.createEl("strong", {}, "Comments:");
		na.createTextEl(StringUtils.numberFormat(commentList.commentsTotal));
		na.insertIn();
			
		CollectionVideoManager.updateIdsAndTitles(commentList);

		var tagsLen = commentList.tags.length;
		var clip_tags = jq("#clip_tags").each(function(i) {
			jq(this).empty();
			na = new NodeAssembly(this);
			na.createEl('strong', {}, 'Tags: ');
			for (i = 0; i < tagsLen; i++) {
				
				na.createEl("a", {"href":"/tag/" + commentList.tags[i].replace(/\s/, "-")}, StringUtils.truncate(commentList.tags[i], 12));
				if (i + 1 != tagsLen) {
					na.createTextEl(" \u2022 ");
				}
			}
			na.insertIn();
		});
		
		if(jq("#release_year").get(0)) {
			jq("#release_year").html((commentList.origReleaseYear == "" || commentList.origReleaseYear == null)?"":"Release Year: " + commentList.origReleaseYear);
		} else {
			if (commentList.origReleaseYear != "" && commentList.origReleaseYear != null) {
				na = new NodeAssembly(jq("#CLIP_DESCRIPTION").get(0));
				na.createEl("p", {"id":"release_year"}, "Release Year: " + commentList.origReleaseYear);
				na.insertIn();
			}
		}
		
		var credits = jq("#credits");
		if (credits.get(0) && commentList.crewList.length || commentList.castList.length) {
			if (credits.size()) {
				credits.empty();
				na = new NodeAssembly(credits.get(0));
				ul = na;
			} else {
				na = new NodeAssembly(jq("#clip_details").get(0));
				var ul = na.createElWithAssembly("ul", {"id":"credits", "class":"credits"});
				na.insertIn();
				na = new NodeAssembly(jq("#credits").get(0));
			}
			if (commentList.castList.length) {
				for (i = 0; i < commentList.castList.length; i++) {
					li = na.createElWithAssembly("li");
					li.createTextEl(commentList.castList[i][1] + ": ");
					header = li.createElWithAssembly("h5");
					name = (commentList.castList[i][2] != null) ? commentList.castList[i][2] : "";
					name += " ";
					name += (commentList.castList[i][3] != null) ? commentList.castList[i][3] : "";
					header.createEl("a", {"href":"/artist/" + commentList.castList[i][0]}, name);
				}
			}
			if (commentList.crewList.length) {
				for (i = 0; i < commentList.crewList.length; i++) {
					var li = na.createElWithAssembly("li");
					li.createTextEl(commentList.crewList[i][1] + ": ");
					var header = li.createElWithAssembly("h5");
					name = (commentList.crewList[i][2] != null) ? commentList.crewList[i][2] : "";
					name += " ";
					name += (commentList.crewList[i][3] != null) ? commentList.crewList[i][3] : "";
					header.createEl("a", {"href":"/artist/" + commentList.crewList[i][0]}, name);
				}
			}
			na.insertIn();
		} else {
			credits.empty();
		}
		var all_comments = jq("#video").get(0);
		if (all_comments) {
			jq("#comment_count").html(commentList.commentsTotal + " Comment" + ((commentList.commentsTotal != 1)?'s':''));
			
			generateCommentHTML(all_comments, commentList.members, commentList.commentsTotal, commentList.paginationString);
			
			try { CollectionVideoManager.updateForm(commentList.commentable); } catch(e) {  safelog(e, "ERROR", "CollectionVideoManager.updateForm"); }
		}
		var title_parts = document.title.toString().split(" - ");
		title_parts[1] = commentList.title;
		document.title = title_parts.join(" - ");
		
		attachJs(CollectionVideoManager.realtimeServer + "/realtime/video/viewcounts/id.js?id=" + commentList.id);
	}, failure:function (e) {
		safelog("comments were not retrieved " + e, "ERROR", "CollectionVideoManager");
	}
};

pageLoadFuncs.push(function () {
	IFILMPlayer.init();
	PlaylistManager.init();
});

var GenreManager = {
	connections: {},
	success: function(o) {
		var prop_list = [];
		for(var prop in o) {
			tagLim = o[prop].length;  
			prop_list.push(prop);
			if(prop == 4) {
	    		var division = jq('#genres');
	    	} else {
	    		var division = jq('#platforms');
	    	}
	    	var prop_label = (prop == 4)?'genre':'platform';
	    	division.empty();
	    	
	    	var na = new NodeAssembly(division.get(0));
		    for(i = 0; i < tagLim; i++) {
		    	safelog(prop + ' ' + o[prop][i].label);
		    	var list_item = na.createElWithAssembly('li');
	    		list_item.createEl('input', {'id':'tag_group_' + prop_label + '_tags_' + i,'name':prop==4?'tag_group_genre_tags':'tag_group_platform_tags','type': 'checkbox','value':o[prop][i].keywordId});
	    		list_item.createEl('label', {'for':'tag_group_' + prop_label + '_tags_' + i}, o[prop][i].label);
		    }  
		    na.insertIn();
		} 
		
		if(prop_list.length == 1) {
			jq('#platform_area').css('display','none');
			jq('#platform_label').css('display','none');
		} else {
			jq('#platform_area').css('display','block');
			jq('#platform_label').css('display', 'block');
		}
	},
	failure: function(o) {
	
	},
	getGenres: function() {
		channelBox = jq('#video_channel');
		var g_division = jq('#genres');
   		var p_division = jq('#platforms');
   		
   		g_division.empty();
   		p_division.empty();
   		
		if(channelBox.value != '') {
			RetrieveChannelTagGroupTagsDWR.getChannelTagGroupTags(channelBox.val(), GenreManager.success);
			//fetchFromAjax('/channeltaggrouptags/?channel=' + channelBox.value,GenreManager,this,false);
		}
	}
};	

var ThumbnailManager = {
	triggers: null,
	trigger: function(e) {
		if(e) { preventDefault(e); }
		jq('#thumb_extract a').removeClass('chosen');
		jq(this).addClass('chosen');
		jq('#chooseNewImageIndex').val(this.id.replace(/status_/, ''));
	},
	addTriggers: function() {
		jq('#thumb_extract a').click(this.trigger);
	}
};

var FavoriteManager = {
	connections: {},
	triggered: {},
	lastAttempted: null,
	idIndex: {},
	success: function(o) {
		if(o) {
			var xml = o;
			if(IFILM.user.checkAuthentication(xml)) {
				this.lastAttempted = null;
				var entities = xml.getElementsByTagName("ifilmentity");
				var enLim = entities.length;
				for(var x=0; x<enLim; x++) {
					var entity = entities[x];
					var id = getTag(entity, "entityid");
					var type = getTag(entity, "entitytypeid");
					var favorite = parseInt(getTag(entity, "favorite"));
					var favRef = IFILM.lastNodeClicked;
					var altRef = "favorites_" + id;
					var altRefs = [altRef, altRef + "-1", altRef +"-2", altRef + "-3"]
					safelog("Entity " + id + " is favorite: " + favorite, "info", "FavoriteManager.success");
					var favRefInAr = false;
					if(favRef) {
						for(var y=0; y<altRefs.length; y++) {
							favRefInAr = (altRefs[y] == favRef.id) ? true : favRefInAr;
						}
						if(!favRefInAr) {
							altRefs.push(favRef);
						}
						
						FavoriteManager.updateFavElAr(altRefs, favorite, id);
					}
				}
			} else {
				IFILM.loadingManager.removeLoading();
				IFILM.user.requestAuthentication(IFILM.lastNodeClicked);
		    }
		}
	},
	failure: function() { 
		jq.prompt("An error occurred while modifying your favorites", { buttons: { Ok: true, Cancel: false } }); 
	},
	updateFavEl: function(favRef, favorite, entityid) {
		thisFavRef = jq(favRef).get(0);
		if(thisFavRef) {
			safelog(thisFavRef.id + " classNames before alteration: " + thisFavRef.className, "info", "FavoriteManager.updateFavEl");
			IFILM.loadingManager.removeLoading();
			jq(thisFavRef).removeClass((favorite)?"add":"remove");
			jq(thisFavRef).addClass((favorite)?"remove":"add");
			var newhref = "/favorites?fxn=";
			newhref += (favorite) ? "remove" : "add";
			newhref += "&favoritesSelection=" + entityid;
		
			var newtext = "Favorite";
			thisFavRef.href = newhref;
			thisFavRef.innerHTML = newtext; 
			safelog(favRef.id + " classNames after alteration: " + thisFavRef.className, "info", "FavoriteManager.updateFavEl");
		}
	
	},
	updateFavElAr: function(favElAr, favorite, entityid) {
		var favElArLim = favElAr.length;
		
		for(i = 0; i < favElArLim; i++)
			favElAr[i] = "#" + favElAr[i];
			
		jq(favElAr).each(function(i) {
			FavoriteManager.updateFavEl(this.toString(), favorite, entityid);
		});
	},
	createFavoriteEl: function(entityid, favorite, useTrigger) {
		var tempna = new NodeAssembly();
		var favEl = tempna.createAnonEl("a", {
				"class": "tool-favorites " + (favorite?"remove":"add"), 
				"id": "favorites_" + entityid + "-2",
				"href": "/favorites?fxn=" + (favorite?"remove":"add") + "&favoritesSelection=" + entityid
			}, (favorite ? "Remove from Playlist" : "Save to Playlist" ))

		var triggerFunc = (useTrigger && useTrigger instanceof Function) ? useTrigger : favoriteTrigger;
		
		jq(favEl).click(triggerFunc);
		return favEl
	}
};

/* FAVORITES */
function favoriteTrigger(e) {
	try {
		if(e) preventDefault(e);
		FavoriteManager.triggered[this.id] = this;
		var href = this.href;
		//IFILM.loadingManager.setLoading(this);
		blurel(this);
		whatWasClicked(e);
		FavoriteManager.lastAttempted = this;
		IFILM.pageManager.incompleteAjaxRequest = function() {
			if(FavoriteManager.lastAttempted) {
				IFILM.loadingManager.setLoading(FavoriteManager.lastAttempted);
				fetchFromAjax(FavoriteManager.lastAttempted.href, FavoriteManager, FavoriteManager.lastAttempted);
			}
		}
		
		return fetchFromAjax(this.href, FavoriteManager, this);
	} catch(e) {
		safelog(e, "Error", "favoriteTrigger");
		return true;
	}
}

pageLoadFuncs.push(function() {
	jq("#interaction a.tool-favorites").click(favoriteTrigger);
	
	jq("#show_less,#show_more").click(function(e) {
		if(e) preventDefault(e);
		if(jq("#this_description").is(":visible")) {
			jq("#this_description").hide();
			jq("#this_description_trun").show();
		} else {
			jq("#this_description").show();
			jq("#this_description_trun").hide();
		}
	});
	
	jq("#morefromusertrigger").toggle(function() {
		jq(this).addClass('triggered');
		jq('#more_from_user').slideDown();
	}, function() {
		jq(this).removeClass('triggered');
		jq('#more_from_user').slideUp();
	});
	
	var flyoutZ = null;
	jq('#SIMILARLIST .more_info,#RECOMMENDEDLIST .more_info').hover(function() {
			var el = this;
			jq(this).css('cursor','pointer');
			flyoutZ = setTimeout(function() {
				if(jq(el).parent().parent().parent().is('.bottom')) {
					flyout = jq(el).parent().parent().find('.description-flyout');
					flyout.css('top', '-' + (jq(flyout).height()-30) + 'px');
				} 
				
				if(jq.browser.msie) {
					jq(el).parent().parent().css('z-index', '20000000');
				}
				
				jq(el).parent().parent().find('.description-flyout').fadeIn();
			}, 250);
	}, function() {
		var el = this;
		jq(this).parent().parent().find('.description-flyout').fadeOut();
		clearTimeout(flyoutZ);
		if(jq.browser.msie) {
			jq(el).parent().parent().css('z-index', 'auto');
		}
	});
	
	jq('#similarlisttabs li').click(function(e) {
		if(e) preventDefault(e);
		 
		jq(".similarlist").hide();
		
		jq("#similarlisttabs li").removeClass('active');
		
		el = this;
		
		if(el.tagName != 'LI')
			el = jq(this).parent().get(0);
		
		jq(el).addClass('active');
		jq("#" + jq(el).attr('id') + "LIST").show();
	});
	AutoPlayManager.init();
});
RatingManager = {
	ifilmEntity: null,
	ifilmEntityTypeId: null,
	voteType: null,
	success: function(o) {
		jq('.likeit').removeClass('likeit').addClass('likedit').unbind('click');
		
		jq('#rating strong').html(jq('#rating strong').html().replace(/\d+/g, (parseInt(o.totalVotes)+1)));
	},
	failure: function(o) {
		safelog('fail:' + o);
	},
	trigger: function(e) {
		try {
			if(e) preventDefault(e);
			var item_id = jq(this).attr('id').split("-");
		
			if(IFILM.user.id == null) {
				IFILM.pageManager.incompleteAjaxRequest = function() {
					jq('.likeit').trigger("click");
				}
				
				IFILM.pageManager.showLoginWindow();
				return;
			}
			
			RatingManager.ifilmEntityId = item_id[2];
			RatingManager.ifilmEntityTypeId = item_id[3];
			
			VoteProcessor.addVoteToEntity(RatingManager.ifilmEntityId, RatingManager.ifilmEntityTypeId, 10, {callback:RatingManager.success, failure: RatingManager.failure, httpMethod: 'GET'});
		} catch(err) { safelog(err); }
	},
	addTriggers: function() {
		jq('.likeit').click(RatingManager.trigger);
		jq('.likedit').click(function(e) { if(e) preventDefault(e); });
	}
}

pageLoadFuncs.push(function() {
	RatingManager.addTriggers();
});
var barelisting = new Array();

var LineListingManager = {
	connections: {},
	sort: null,
	is_filter: false,
	success: function(o) {
		var respxml = o;
		var items = respxml.getElementsByTagName("ifilmentity");
		var sublisting = getTag(respxml,"sublisting");
		
		var clipview_header = jq('#clipview_options').get(0);
		if(clipview_header) {
			jq(clipview_header).removeClass("mostRecent");
			jq(clipview_header).removeClass("mostPopular");
			jq(clipview_header).removeClass("newStuff");
			jq(clipview_header).removeClass("mostViewed");
			jq(clipview_header).addClass(sublisting);
		}
		
		
		if(items) {
			var featurelist = jq('#FEATURELIST').get(0);
			jq(featurelist).empty();
			IFILM.loadingManager.removeLoading();
			IFILM.suppressLogging = true;
			var itemLim = items.length;
			var na = new NodeAssembly(featurelist); 
			var is_thumb = false;
			var last_child = 0;
			is_thumb = jq('#clipview_options').is(".thumb");
			var thumbnail = jq('#thumbnail').get(0);
			if(thumbnail) 
				last_child = thumbnail.className.match(/children_[0-9]*/).toString().replace(/children_/,'');
			if(itemLim > 0) {
				for(var x=0; x<itemLim; x++) {
	
					var curItem = items[x];
					var curChannel = getTag(curItem,"channel");
					var curChannelName = getTag(curItem,"channelname");
					var channelUrl = '';
					var curItemId = getTag(curItem, "entityid");
					if(curChannelName != '') {
						var channelUrl = '/channel/' + curChannelName;
					}
					var contrib = getTag(curItem,"contrib").split("|");
					var contriburl_arr = getTag(curItem, "contriburl").split("|");
					
					// so we don't have to replicate the generation of html
					// in bloglinelisting tag files, I just dumped it into an xml node
					// we parse that node and insert it.
					var entityHtml = curItem.getElementsByTagName('entityHtml')[0].text || curItem.getElementsByTagName('entityHtml')[0].textContent;

					entityHtml = StringUtils.trim(entityHtml);
					
					var matches = entityHtml.match(/(clearfix) ([a-zA-Z0-9_\-\s]*)/i);
					
					entityHtml = entityHtml.replace(/^<[\/]?li([^>]*)>/gi,'');
					entityHtml = entityHtml.replace(/<[\/]?li([^>]*$)>/gi,'');
					
					var curItemObj = { doc: curItem, entityid: getTag(curItem, "entityid"), imgsrc: getTag(curItem, "imgsrc"), url: getTag(curItem, "url") }
					var attrs = {
						"id": "E_" + curItemObj.entityid + '_' + getTag(curItem, "entitytypeid"),
						"class": "clearfix " + matches[2] + "" + (x?"": " first-child")
					}

					var li = na.createEl("li", attrs, { htmlStr: entityHtml });
				}
			} else {
				na.createEl('li', { 'class' : 'no-results' }, 'No results found.');
			}
			na.insertIn();
			
			// a fun little piece of hackery to account for ripping out the li, it's simpler to do it
			// this way.
			jq('#FEATURELIST li ol a').wrap('<li class="clearfix"></li>');
			
			jq("#VIDEOLIST ul.pager").html(getTag(respxml, "paging"));
			
			IFILM.suppressLogging = false;
			
			jq("#SIMILARLIST a.tn_frame img, #FEATURELIST a.tn_frame img").load(adjustThumbnails);
			
			jq('#VIDEOLIST .pager a').each(function() {
				if(LineListingManager.type) {
					var matches = jq(this).attr("href").match(/type=([a-zA-Z]*)/);
					if(matches && matches.length)
						jq(this).attr("href", jq(this).attr("href").replace(/type=[a-zA-Z]*/,"type=" +  LineListingManager.type[1]));
					else
						jq(this).attr("href", jq(this).attr("href") + "&type=" + LineListingManager.type[1]);
				}
			});
			LineListingManager.type = null;
			
			
			jq("#MAINCONTENT a.tool-send,#MAINCONTENT a.tool-share,#MAINCONTENT a.tool-downloads,#MAINCONTENT a.tool-url").click(openMenu);
			
			if(jq('#FEATURELIST .delete').get(0))
				deleteManager.addTriggers();
				
			if(editVideo)
				editVideo();
				
			jq('#FEATURELIST').css('visibility', 'visible');
			
			jq('.collection_wrapper ol,.photo_album').jcarousel({
				visible: 4,
				scrollInc: 1,
				wrap: "both",
				buttonNextHTML: '<a href="#"><img src="http://dyn.ifilm.com/website/ver2/next_arrow.png"  alt="" /></a>',
				buttonPrevHTML: '<a href="#"><img src="http://dyn.ifilm.com/website/ver2/prev_arrow.png"  alt="" /></a>'
			});
		}
	},
	failure: function(o) {
		jq.prompt("Sorry, there was a problem loading the list you requested.  Please try again.",{ buttons: { Ok: true } });
	},
	trigger: function(e, obj, onload) {
		if(e) preventDefault(e);
		
		var el = obj || this;
		
		if(!onload)
			onload = false;
		
		var loadingItem = jq('#FEATURELIST').get(0);
		IFILM.loadingManager.setLoading(loadingItem);
				
		is_sort = (jq(el).parent().parent().attr('id') == 'clipview_options');
		is_nested =  jq(el).parent().attr('id') == 'listing_links';
		var my = !is_nested?jq(el).parent():jq(el).parent().parent();
		
		is_filter = jq(el).parent().parent().attr("id") == 'sort_by_type_list';
		
		var type = jq(el).attr("href").match(/type=([a-zA-Z]*)/);
		
		if(type == undefined)
			type = '';
		
		LineListingManager.type = type;

		if(LineListingManager.type == null) {
			LineListingManager.type = new Array();
			LineListingManager.type[0] ='';
		}
		
		
		if(obj && is_filter) 
			SortByType.triggerFunc();
		
		if(el.href.indexOf('gtgirls') == -1 && (el.href.indexOf('mostviewed') != -1 || el.href.indexOf('newstuff') != -1) && !realtimeListing.scriptAttached) {
			realtimeListing.attachScript(el.href);
			setTimeout(function() {
				realtimeListing.checkAttachment(el.href, is_filter, el);
			}, 2000);
			return;
		}
		
		if( el.href.indexOf('gtgirls') == -1 && (el.href.indexOf('mostviewed') != -1 || el.href.indexOf('newstuff') != -1) && realtimeListing.trigger(el.href)) {
			var sent = false;
			IFILM.loadingManager.removeLoading();
		} else {
			var link = el.href;
			if(!e) {
				page = QueryManager.get('page');
				
				if(page == undefined || !page)
					page = 1
				
				if(link.indexOf('page=') != -1)
					link = link.replace(/page=[0-9]*/, 'page=' + page);
				else
					link = link + '&page=' + page;
			}
			
			var sent = !fetchFromAjax(link, LineListingManager, this, true);
		}
		
		if(!is_filter) {
			jq("#combo_header a").removeClass('active');
			jq(el).addClass('active');
			var sublisting = jq(el).attr('href').match(/sublisting=([a-zA-Z]*)/);
			jq("#sort_by_type_list a").each(function() {
				jq(this).attr("href", jq(this).attr("href").replace(/sublisting=[a-zA-Z]*/,"sublisting=" + sublisting[1]));
			});
		} else {
			jq("#sort_by_type").html(jq(el).html());
			
			
			jq("#combo_header a").not("#sort_by_type_list a").each(function() {
				
				if(jq(el).attr("href").indexOf("type=") )
					jq(this).attr("href", jq(this).attr("href").replace(/type=[a-zA-Z]*/,"type=" + type[1]));
				else
					jq(this).attr("href", jq(this).attr("href") + "&type=" + type[1]);
			});
		}
		
		
	},
	addTriggers: function() {
		if(jq('#VIDEOLIST').get(0)) { 			
			jq("#combo_header a").not(".miniplayer").click(this.trigger);
		}
		
		jq('#clipview_options span.sort_options a,#sort_by_type_list a').click(this.trigger);
		
	}
}
	var deleteManager = {
		connections: {},
		triggered: {},
		lastAttempted: null,
		idIndex: {},
		triggerFunc: function(e) {
			if(e) { preventDefault(e); }

			var click_el = this;
			blurel(this);
					
			var isFavorite = this.id.match(/favorites/) == 'favorites';
			delete_id = this.id.replace(/delete_/,'').replace(/-[0-9]*/,'').replace(/favorites_/,'');
			delete_id = delete_id.split("_");		
			var list_element = jq('#E_' + delete_id[0] + "_" + delete_id[1]);
				
			jq("#FEATURELIST li.tn_frame").each(function(i) {
				jq(this).css("opacity","1");
			});
			
			var pos = list_element.offset();
			//pos.top -= 10;
			
			deleteManager.overlayListing(list_element,pos);
			//TODO: Add onclick calls to the confirm
			
			jq("#confirm_delete").unbind();
			jq("#confirm_delete").click(function(e) {
				deleteManager.confirmDelete(e,click_el);
			});
			jq("#cancel_delete").click(function(e) {
				deleteManager.hideOverlay(e,list_element);
			});
			
		},
		addTriggers: function() {
			jq('#FEATURELIST a.delete').click(this.triggerFunc);
		},
		overlayListing: function(list_element,position) {
			jq(list_element).css('opacity',.1);
			jq('#video_delete_confirm').css('opacity',.8);
			jq('#video_delete_confirm').css('display','block');
			jq('#video_delete_confirm').css('top',position.top);
			jq('#video_delete_confirm').css('left',position.left);
			
			var top_el = list_element.find("a");
			top_pos = jq(top_el.get(0)).offset();
			bot_pos = jq(top_el.get(top_el.length-1)).offset();
			this_height = bot_pos.top - top_pos.top;
			
			this_height = this_height < 77?77:this_height;
			jq('#video_delete_confirm').css('height', (parseInt(this_height) + 15) + 'px');
			jq('#video_delete_confirm').css('width', jq(list_element).width() + 'px');
		},
		loading: function(id) {
			
		},
		success: function(o) {	
			window.lastConn = o;
			if( o ) {
				var xml = o
				
				id = getTag(xml,"entityid");
				var list_element = jq('#E_' + id);
				deleteManager.hideOverlay(null, id);
				if(list_element) {
					list_element.addClass("deleted");
					list_element.css('opacity', .1);

				}
			}
		},	
		failure: function(o) {
			jq.prompt("An error occurred while trying to remove your video.");
		},
		confirmDelete: function(e,obj) {
			jq("#confirm_delete").unbind();
			return fetchFromAjax(obj.href, deleteManager, obj, true);
		},
		hideOverlay: function(e,el) {
			jq("#video_delete_confirm").css('display', 'none');
			jq(el).css('opacity', 1);
		}
	}

function truncateLink(view) {
	try {
		jq('#BODYCONTENT a.title_link').each(function(i) {
			link_text = this.innerHTML;
			full_link_text = this.title;
			if(view == 'list') {
				this.innerHTML = full_link_text;
			} else {
				this.innerHTML = StringUtils.truncate(link_text, 20, '...', true);
			}
		});
	} catch(e) { 
		safelog('error truncating links: ' + e, 'error', 'truncateLink');
	}
}

var max_thumb_height = 0;
var thumb_row = [];
function appendLastChild(list,view,last_child) {
	if(list == 'feature') {
		els = jq('#VIDEOLIST ul.feature' + view + ' li');
	} else if(list == 'similar') {
		els = jq('div.similar' + view + ' ul:first li');
	} else {
		els = jq('ul#video_tn_list li');
	}
	
	els.each(function(i) {
		max_thumb_height = Math.max(max_thumb_height, jq(this).innerHeight());
		thumb_row.push(this);
		if((i % last_child) == (last_child - 1) && view == 'thumb') {
			jq(this).addClass('last-child');
			jq(thumb_row).css('height', max_thumb_height+'px');
			thumb_row = new Array();
			max_thumb_height = 0;
		} else if ( i == (els.length - 1) && view == 'thumb') {
			max_thumb_height = 0;
			thumb_row = new Array();
		} else {
			jq(this).removeClass('last-child');
		}
	});
	
	if(view == 'list') { 
		jq(thumb_row).css('height', 'auto');
		max_thumb_height = 0;
		thumb_row = new Array();
	}
	
}

function switchView(e, obj) {
	try {
		if(!jq('#thumbnail').get(0)) {
			safelog('Disable view switching', 'info', 'switchView');
			jq(body_element).removeClass('hide_videos');
			return false;
		}
		
		if(obj) {
			var which_list = obj.id;
			var listEl     = obj;
			var optionEl   = jq('#clipview_options').get(0) || jq('#recommended_header').get(0) || jq('#combo_header').get(0);
		} else {
			var which_list = jq('#FEATURELIST').get(0)?'FEATURELIST':'SIMILARLIST';
			var listEl     = (which_list == 'FEATURELIST') ? jq('#FEATURELIST').get(0) : jq('#SIMILARLIST').get(0);
			var optionEl   = (which_list == 'FEATURELIST') ? jq('#clipview_options').get(0) : jq('combo_header').get(0)||jq('#recommended_header').get(0);
		}
		
		if(listEl) {
			var flag = IFILM.viewPrefMap[which_list];
			safelog(which_list + " using flag " + flag, "info", "switchView");
			var prefixes = { 'FEATURELIST' : 'feature', 'SIMILARLIST' : 'similar', 'video_tn_list': '' };
			var prefix = prefixes[which_list] || "";
			
			if(e && this.id) {
				if(this.id == "thumbnail") { IFILM.user.view |= flag; }		
				else if(this.id == "linelist") { IFILM.user.view = IFILM.user.view & ~flag; }
				else { IFILM.user.view ^= flag; }
			} else if(view_loaded) {
				IFILM.user.view ^= flag;
			}
			
			var old_view  = (IFILM.user.view & flag) ? "list" : "thumb";
			var this_view = (IFILM.user.view & flag) ? "thumb" : "list";
			
			jq(listEl).removeClass(prefix+old_view);
			jq(listEl).addClass(prefix + this_view);
			jq(optionEl).removeClass(old_view);
			jq(optionEl).addClass(this_view);

			thumbnail_icon = jq('#thumbnail').get(0);
			last_children = thumbnail_icon.className.match(/children_[0-9]*/).toString().replace(/children_/,'');
			switch(which_list) {
				case 'FEATURELIST':
					truncateLink(this_view);
					appendLastChild('feature', this_view, last_children);
					break;
				case 'SIMILARLIST':
					truncateLink(this_view);
					appendLastChild('similar', this_view, last_children);
				case 'video_tn_list':
					truncateLink(this_view);
					appendLastChild('video_tn_list', this_view, last_children);
			}
			
			if(view_loaded) {
				IFILM.cookieManager.set("userPref",IFILM.user.view);
			}
			view_loaded = true;
		}
		
		if(e) { 
			//blurel(this);
			preventDefault(e); 
		}
		
		
	} catch(e) {
		safelog("No thumbnail view to switch: " + e, "error", "switchView");
	}
	
	return false;
}

IFILM.viewPrefMap = {
	FEATURELIST: 0x1,
	SIMILARLIST: 0x2,
	video_tn_list: 0x4
}


body_element = document.body?document.body:document.documentElement;
var view_loaded = false;

pageLoadFuncs.push(function() {
	var default_view = 0;
	var clipview_header = jq('#clipview_options').get(0) || jq('#combo_header').get(0);
	if( clipview_header && jq(clipview_header).is('thumb') ) {
		default_view = IFILM.viewPrefMap['FEATURELIST'];
	}
	IFILM.user.view = IFILM.cookieManager.get("userPref")||default_view;
	
	var obj = jq('#FEATURELIST').get(0) || jq('#SIMILARLIST').get(0) || jq('#video_tn_list').get(0);
	jq("#thumbnail, #linelist").click(function(e) {
		switchView(e,obj);
	});
	switchView(null, obj);
});
/* END THUMBNAIL/LISTING SWITCHING */


relatedVideoWallManager = {
	connections: {},
	relatedPage: 1,
	maxPage: 20,
	header: null,
	videos: null,
	loadingHeader: null,
	success: function(o) {
		try {
	 		var items = o.getElementsByTagName('ifilmentity');
	 		var item_html = '';
	 		
	 		start_point = 0;
	 		end_point = items.length;
	 		safelog(items.length);
	 		if(items.length > 10) {
	 			relatedVideoWallManager.maxPage = Math.ceil(items.length/10);
	 			start_point = (relatedVideoWallManager.relatedPage-1)*10;
	 			end_point = Math.min(items.length, start_point + 10);
	 		}
	 		j = 0;
	 		for(i = start_point; i < end_point; i++) {
	 			var el = jq('#SIMILARLIST ol li').get(j);
	 			if(el) {
		 			jq(el).attr('id', 'E_' + getTag(items[i],'entityid') + '_' + getTag(items[i],'entitytypeid'));
		 			jq('a.tn_frame,h3 a', el).attr({'href': getTag(items[i], 'url'), 'title': getTag(items[i], 'title')});
		 			jq('h3 a', el).html(StringUtils.truncate(getTag(items[i], 'title'), 50));
		 			jq('img', el).not('.more_info').attr('src', getTag(items[i], 'imagesrc') + '?width=116');
		 			jq('.description-flyout h5', el).html(getTag(items[i], 'title'));
		 			jq('.description-flyout p', el).html(StringUtils.truncate(getTag(items[i], 'description'), 100));
		 			jq(el).show();
		 		}
		 		j++;
	 		}
	 		
	 		safelog("end point: " + end_point + "  start point: " + start_point);
	 		if(end_point - start_point < 10) {
	 			for(x = (end_point - start_point); x < 10; x++) {
	 				var el = jq('#SIMILARLIST ol li').get(x);
	 				jq(el).hide();
	 			}
	 		}
	 				
	 		jq('#SIMILARLIST').removeClass('loading');
	 		
 		} catch(e) { safelog(e, "ERROR", "printRelated.success"); }	
	},
	failure: function(o) {
		jq.prompt("Sorry, there was a problem loading the list you requested.  Please try again.",{ buttons: { Ok: true } });
	},
	triggerFunc: function(e) {
	
		if(e) preventDefault(e);
		
		if(jq(this).parent().is('.prevbutton'))
			relatedVideoWallManager.relatedPage--;
		else
			relatedVideoWallManager.relatedPage++;
		
		if(relatedVideoWallManager.relatedPage > relatedVideoWallManager.maxPage)
			relatedVideoWallManager.relatedPage = 1;
		else if (relatedVideoWallManager.relatedPage < 1)
			relatedVideoWallManager.relatedPage = relatedVideoWallManager.maxPage;
		
		jq('#SIMILARLIST li img').not('.more_info').unbind('load').attr('src','http://dyn.ifilm.com/website/ver2/x.gif').css('margin', '0');
		jq("#SIMILARLIST").addClass('loading');
		
		fetchFromAjax(document.location + '?usingAjax=true&ajaxTargetData=relatedVideo&numPerPage=10&relatedPage=' + relatedVideoWallManager.relatedPage, relatedVideoWallManager, null, true);
	},
	addTriggers: function() {
		jq('#SIMILARLIST .nextbutton a,#SIMILARLIST .prevbutton a').click(relatedVideoWallManager.triggerFunc);	
	}
}

pageLoadFuncs.push(function() { 
	relatedVideoWallManager.addTriggers();
});

function editVideo() {
	jq('.edit_this_video').click(function(e) {
		preventDefault(e);
		tb_show('',this.href, null, {success: function() {
			jq('#returnURL').val(document.location.toString());
			ValidationManager.addTriggers();	
			genreTriggerFunc = GenreManager.getGenres;
			jq('#video_channel').change(genreTriggerFunc);
			
			channelBox = jq('#video_channel').get(0);
			if(channelBox) {
				if(channelBox.value == 'videogames') {
					jq('#platform_area').css("display", 'block');
					jq('#platform_label').css("display", 'block');
				} else {
					jq('#platform_area').css("display", 'none');
					jq('#platform_label').css("display", 'none');
				}
			}
			
			ThumbnailManager.addTriggers();
			var cur_thumbnail = jq('#cur_thumbnail').get(0);
			if(cur_thumbnail) {
				cur_thumbnail.src = cur_thumbnail.src + '&rnd=' + Math.round(Math.random()*9999999) + '-' + Math.round(Math.random()*9999999);
			}
		}, failure: null});
	});
};

pageLoadFuncs.push(function() {
	editVideo();
});

realtimeListing = {
	channelId: null,
	page: 1,
	scriptAttached: false,
	scriptTimeout: false,
	checkAttachment: function(url, is_filter, el) {
		try {
			if(barelisting)
				this.scriptTimeout = false;
		} catch(e) { this.scriptTimeout = true; }
		
		if(!is_filter) {
			if(url.indexOf('mostviewed') != -1)
				LineListingManager.trigger(null,jq("#mostviewed").get(0));
			else
				LineListingManager.trigger(null,jq("#newstuff").get(0));
		} else {
			if(url.indexOf('mostviewed') != -1)
				LineListingManager.trigger(null,el);
			else
				LineListingManager.trigger(null,el);
		}
	},
	attachScript: function(url) {
		var url_parts = StringUtils.parseUrl(url);
		
		if(url.indexOf("mostviewed") != -1) {
			if(url_parts.length == 4)
				attachJs(realtimeListing.server + '/realtime/genrelisting/mostpopular/?bucketId=' + this.channelId + '&page=' + this.page + '&' + LineListingManager.type[0]);
			else if(this.channelId != 1) 
				attachJs(realtimeListing.server + '/realtime/channellisting/mostpopular/?bucketId=' + this.channelId + '&page=' + this.page + '&' + LineListingManager.type[0]);
			else
				attachJs(realtimeListing.server + '/realtime/homepage/mostpopular/?bucketId=' + this.channelId + '&page=' + this.page  + '&' + LineListingManager.type[0]);
		} else if(url.indexOf("newstuff") != -1) {
			if(this.channelId != 1) 
				attachJs(realtimeListing.server + '/realtime/channellisting/newstuff/?bucketId=' + this.channelId + '&page=' + this.page + '&' + LineListingManager.type[0]);
			else
				attachJs(realtimeListing.server + '/realtime/homepage/newstuff/?bucketId=' + this.channelId + '&page=' + this.page + '&' + LineListingManager.type[0]);
		} else if(url_parts[0] == 'network' && url_parts[1] == 'spike') {
			attachJs(realtimeListing.server + '/realtime/networklisting/mostpopular/?bucketId=' + this.channelId + '&page=' + this.page + '&' + LineListingManager.type[0]);
		}
	
		realtimeListing.scriptAttached = true;
	},
	trigger: function(url) {
		realtimeListing.scriptTimeout = false;
		realtimeListing.scriptAttached = false;
		try {
			if(barelisting.length && (url.indexOf('newstuff') != -1 || url.indexOf("mostviewed") != -1)) {
				jq("#FEATURELIST").empty().html(barelisting.join(" "));
				jq("#VIDEOLIST .pager").html(jq("#FEATURELIST .hidden_paging .pager").html());
				
				if(url.indexOf('newstuff') != -1) {
					jq('#VIDEOLIST .pager a').each(function() {
						var link = jq(this).attr('href');
						link = link.replace(/sublisting=[a-z]*/, 'sublisting=newstuff');
						jq(this).attr('href', link);
					});
				}
				
				jq('#FEATURELIST li:first').addClass('first-child');
				barelisting = new Array();
				jq("#MAINCONTENT a.tool-send,#MAINCONTENT a.tool-share,#MAINCONTENT a.tool-downloads,#MAINCONTENT a.tool-url").click(openMenu);
				jq('#FEATURELIST').css('visibility', 'visible');
				jq('.collection_wrapper ol,.photo_album').jcarousel({
					visible: 4,
					scrollInc: 1,
					wrap: "both",
					buttonNextHTML: '<a href="#"><img src="http://dyn.ifilm.com/website/ver2/next_arrow.png"  alt="" /></a>',
					buttonPrevHTML: '<a href="#"><img src="http://dyn.ifilm.com/website/ver2/prev_arrow.png"  alt="" /></a>'
				});
				return true;
			}
		} catch(e) { safelog(e, "ERROR", "Realtime trigger"); return false; }
		
		return false;
	}
};

pageLoadFuncs.push(function() {
	deleteManager.addTriggers();
	
	if(jq.browser.msie) {
		jq("#FEATURELIST li a.tn_frame span").click(function() {
			document.location = jq(this).parent().attr('href');
		});
	}
});
var CommentManager = {
	formref:null, 
	userform:null, 
	position:null, 
	connections:{}, 
	getLoginLink:function () {
		var loginlink = jq("#COMMENTLOGIN").get(0);
		if (!loginlink) {
			loginlink = this.userform.getElementsByTagName("h3")[0];
		}
		IFILM.lastNodeClicked = loginlink;
		return loginlink;
	}, generateCode:function (node, commentel, commentbody) {
		var cdiv = new NodeAssembly(node);
		var commentBox = cdiv.createElWithAssembly("div", {"class":"newcomment"});
		commentBox.createEl("h3", {"class":"posted_header"}, "Your comment has been added");
		var cmeta = commentBox.createElWithAssembly("p", {"class":"commentmeta"});
		cmeta.createEl("a", {"class":"topic", href:getTag(commentel, "authorurl")}, getTag(commentel, "author"));
		cmeta.createTextEl(" - ");
		cmeta.createTextEl(getTag(commentel, "date"));
		commentBox.createEl("p", null, { htmlStr: commentbody });
		jq(node).empty();
		cdiv.insertIn();
		var atDiv = commentBox.baseEl;
		jq(atDiv).fadeIn("normal");
	}, success:function (o) {
		var xml = o;
		if (IFILM.user.checkAuthentication(xml)) {
			IFILM.pageManager.incompleteAjaxRequest = null;
			var errXml = xml.getElementsByTagName('error')[0];
			var err = {
				code: getTag(errXml, "code"),
				description: getTag(errXml, "description")
			}
			if(err.code == 0) {
				IFILM.loadingManager.removeLoading();
				var commentel = xml.getElementsByTagName("comment")[0];
				var commentbody = getTag(commentel, "commentbody");
				if (commentbody != "") {
					CommentManager.generateCode(CommentManager.formref.get(0), commentel, commentbody);
				}
			} else {
				safelog(err.description, "ERROR", "CommentManager.Success");
			}
		} else {
			IFILM.pageManager.incompleteAjaxRequest = function () {
				submitToAjax(IFILM.commentManager.formref.get(0), IFILM.commentManager);
			};
			IFILM.loadingManager.removeLoading();
			IFILM.pageManager.showLoginWindow(null, CommentManager.getLoginLink());
		}
	}, failure:function (o) {
		jq.prompt("There was an error adding this comment");
		safelog("There was an error: " + o, "ERROR", "CommentManager");
		IFILM.loadingManager.removeLoading();
	}, addTriggers:function () {
		this.formref = jq("#leavecomment");
		this.formref.submit(IFILM.commentManager.triggerFunc);
		
		jq('#comment_box h6 select').change(function(e) {
			try {
				if(jq(this).val() == 'oldest')
					oldest_first = true;
				else
					oldest_first = false;
				
				var url = document.location.toString().split("?");
				
				jq('#video').empty();
				LoadEntityDWR.getEntityForDWR(jq('#comment_IFILMEntityId').val(), jq('#comment_IFILMEntityTypeId').val(), 1, CommentPagingManager.maxPerPage, url[0], oldest_first, {callback: CommentPagingManager.success, errorHandler: CommentPagingManager.failure, httpMethod: 'POST'});
			} catch(err) { safelog(err); } 
		});
	}, triggerFunc:function (e) {
		if (e) { preventDefault(e); }
		loadingEl = this.parentNode;
		IFILM.loadingManager.setLoading(loadingEl);
		IFILM.commentManager.position = this.id.replace(/leavecomment/, "");
		submitToAjax(this, IFILM.commentManager, IFILM.commentManager.validate);
	}, validate:function() {
		return (jq.trim(jq('#commentfield').val())!='');
	},	resetCommentForm: function(commentable,curEntity,curEntityType) {
		if(commentable) {
		    jq('#comment_container').fadeIn("slow");
		    jq('#comment_box').fadeIn("slow");
		    jq('#submitcomment').fadeIn("slow");
			var re = new RegExp(/disabled/);
			if(jq("#leavecomment .newcomment").get(0)) {
				var leave_comment = jq("#leavecomment");
				leave_comment.empty();
				var na = new NodeAssembly(leave_comment.get(0));
				var fieldset = na.createElWithAssembly("fieldset");
				fieldset.createEl("legend", {}, "Leave A Comment");
				fieldset.createEl("textarea", {"cols":45, "name": "body", "id":"commentfield"}, "");
				fieldset.createEl("input", {"type":"hidden", "value":curEntity, "name": "IFILMEntityId"});
				fieldset.createEl("input", {"type":"hidden", "value":curEntityType, "name": "IFILMEntityTypeId"});
				fieldset.createEl("input", {"type":"submit", "value": "Leave A Comment", "name": "addComment", "class": "submit_comment_btn", "id":"submit_comment_btn"});
					
				na.insertIn();
				
			}
		} else {
		    jq('#comment_box,#comment_box_top,#comment_box_bottom').hide();
		}
	}
};

IFILM.commentManager = CommentManager;

pageLoadFuncs.push(function() {
	IFILM.commentManager.addTriggers();
});


var CommentPagingManager = {
	page: 1,
	totalPages: 1,
	maxPerPage: 50,
	curLink: null,
	failure: function(comments) {
		jq.prompt("There was an error loading next page of comments.");
		safelog(comments, "ERROR", "CommentPagingManager");
		if(CommentPagingManager.curLink)
			return;
			//document.location = CommentPagingManager.curLink;
	},
	success: function(comments) {
		var all_comments = jq("#video").get(0);
		CommentPagingManager.totalPages = Math.ceil(parseInt(comments.commentsTotal)/CommentPagingManager.maxPerPage);
		
		
		jq('#comment_box li').removeClass('last-child');
		if (all_comments) {
			generateCommentHTML(all_comments, comments.members, comments.commentsTotal, comments.paginationString, QueryManager.get("cmtPage"));
		}
				
		var paging_link = jq("#comment-pagination a").attr('href');
		
		if(paging_link == null)
			paging_link = '';
			
		paging_link = paging_link.replace(/(cmtPage=)[0-9]*/, 'cmtPage=' + (CommentPagingManager.page+1));
		jq("#comment-pagination a").attr('href', paging_link).html('Read ' + ((CommentPagingManager.page)*CommentPagingManager.maxPerPage+1) + '-' + Math.min(comments.commentsTotal, (((CommentPagingManager.page)*CommentPagingManager.maxPerPage)+CommentPagingManager.maxPerPage)) + ' of ' + comments.commentsTotal + ' comments');
		
		if(CommentPagingManager.page+1 > CommentPagingManager.totalPages)
			jq('#comment-pagination').remove();
		
		CommentPagingManager.addTriggers();
		commentReplyManager.addTriggers();
		IFILM.loadingManager.removeLoading(jq('#video').get(0));
		jq('#comment-pagination').removeClass('loading');
		document.location = '#comment_' + comments.members[0].id;
	},
	trigger: function(e) {
		if(e) preventDefault(e);
			
		CommentPagingManager.curLink = this;
		
		var url = this.href.split("?");
		QueryManager.curQuery = url[1];
		CommentPagingManager.page = parseInt(QueryManager.get("cmtPage"));
		
		IFILM.loadingManager.setLoading(jq('#video').get(0));
		
		jq('#comment-pagination').addClass('loading');
		LoadEntityDWR.getEntityForDWR(jq('#comment_IFILMEntityId').val(), jq('#comment_IFILMEntityTypeId').val(), CommentPagingManager.page, CommentPagingManager.maxPerPage, url[0], {callback: CommentPagingManager.success, errorHandler: CommentPagingManager.failure, httpMethod: 'POST'});
	}, addTriggers: function() {
		jq('#comment-pagination a').click(this.trigger);
	}
};

pageLoadFuncs.push(function() { CommentPagingManager.addTriggers(); });

function generateCommentHTML(all_comments, comments, total, paging, page) {
	na = new NodeAssembly(all_comments);
	
	if(!page)
		page = 1;
	var memberLen = comments.length;
	for (i = 0; i < memberLen; i++) {
		var member = comments[i];
		var member_user = member.user;
		
		var total_votes = member.totalVotes;
		var up_votes = member.totalUpVotes;
		var down_votes = member.totalDownVotes;
		var vote_calc = up_votes-down_votes;
		
		var child_class = '';
		if(i == 0) {
			child_class = 'first-child';
		} else if ( i == (memberLen-1)) {
			child_class = 'last-child';
		}
				
		var buried_status = '';
		
		if(vote_calc < 3 && (member.vote && member.vote.voteType == 1)) {
			buried_status = '';
		} else if(vote_calc <= -5 || (member.vote && member.vote.voteType == -1)) {
			buried_status = 'buried';
		} else if(vote_calc >= 5) {
			buried_status = 'hot';
		} 
		
		var li = na.createElWithAssembly("li", {"class": "clearfix " + child_class + " "  + buried_status, "id":"comment_" + member.id});
		li.createEl("a", {"name": "comment_" + member.id});
		var avatar_div = li.createElWithAssembly("div", { "class":"avatar_frame " + (member_user.userIsAFriend?'is-a-friend':'not-a-friend')});
		var avatar_link = avatar_div.createElWithAssembly("a", {"class":"tn_frame", "href":member_user.URL, 'class':'avatar'});
		if (member_user.imageURL == "") {
			avatar_link.createEl("img", {"src":"http://dyn.ifilm.com/image/website/standard-avatar-80.gif", "alt":member_user.login, "class":"avatar"});
		} else {
			avatar_link.createEl("img", {"src":member_user.imageURL + "?width=80", "alt":member_user.title, "class":"avatar"});
		}
		//avatar_div.createEl('a', {'href':'#', 'class':'tool-friend-trigger', 'id': 'friendid-' + member_user.id + '-' + i}, '^');

		var vote = li.createElWithAssembly('div', {'class':'comment_vote'});
		
		prefix = (vote_calc > 0)?'+':'';
		vote.createEl('strong', {}, prefix + vote_calc );
		if(member.vote && member.vote.hasVote) {
			vote.createEl('img', {'src': 'http://dyn.ifilm.com/website/ver2/comment_vote_up_off.gif'});
			vote.createEl('img', {'src': 'http://dyn.ifilm.com/website/ver2/comment_vote_down_off.gif'});
		} else {
			var up_link = vote.createElWithAssembly('a', {'href':'#', 'id': 'commentvote_' + member.id + '_' + member.entityTypeId + '_up'});
			up_link.createEl('img', {'src': 'http://dyn.ifilm.com/website/ver2/comment_vote_up.gif'});
			var down_link = vote.createElWithAssembly('a', {'href':'#', 'id': 'commentvote_' + member.id + '_' + member.entityTypeId + '_down'});
			down_link.createEl('img', {'src': 'http://dyn.ifilm.com/website/ver2/comment_vote_down.gif'});
		}
		
		var comment_meta = li.createElWithAssembly("p", {"class":"commentmeta"});

		var this_page = (i+1)+(CommentPagingManager.maxPerPage*(page-1));				
		comment_meta.createEl("span", {"class":"number"}, this_page + ". ");
		comment_meta.createEl("a", {"href":member_user.URL, "title":"comments", "class":""}, member_user.title);
		comment_meta.createEl("span", {"class":"date"}, "Posted on " + member.createFormatted);
		li.createEl("p", {"class":"comment_text"}, {htmlStr:member.description});
		var tools = li.createElWithAssembly("p", {"class":"actions"});
		tools.createEl('a', { 'href': "#", 'class': "comment_reply", 'id': "comment_replies_" + member.id + "_" + member.entityTypeId }, member.commentsTotal + ' ' + ((member.commentsTotal != 1)?'replies':'reply'));
		tools.createEl('a', { 'href': "#", 'class': "reply_to_comment", 'id': "reply_to_comment_" + member.id + "_" + member.entityTypeId }, 'Reply');
		tools.createEl("a", {"href":"#", "class":"flag", "id":"flagcomment_" + member.id}, "Flag as inappropriate");
                if(IFILM.user.isAdmin) {
		tools.createEl("a", {"href":"/offlinecomment?IFILMEntityId=" + member.id + "&IFILMEntityTypeId=" + member.entityTypeId, "class":"offline", "id":"offline_comment_" + member.id}, "Make it offline");
                }
		var buried = li.createElWithAssembly("p", {"class":"buried_comment_control"}, "This comment has been buried by our users.");
		buried.createEl("a", {"href":"#", "class":"show_comment", "id":"buried_" + member.id}, "Reveal Comment");
		
	}
	na.insertIn();
	jq("#commentspager").html((total > 10)?paging:"");
	
	CommentPagingManager.addTriggers();
	jq("#comment_box a.flag").click(openMenu);
	OfflineManager.addTriggers();
	CommentVotingManager.addTriggers();
	//FriendManager.addTriggers();
}

CommentVotingManager = {
	curVoteMod: null,
	entity_id: null,
	entity_type_id: null,
	vote_type: null,
	writeVote: function(o) {
		jq(CommentVotingManager.curVoteMod).empty();
		var na = new NodeAssembly(CommentVotingManager.curVoteMod);
		var total_votes = o.totalVotes;
		var up_votes = Math.floor(total_votes*(o.upVotePercent/100));
		var down_votes = Math.floor(total_votes*(o.downVotePercent/100));
		var vote_calc = parseInt(up_votes)-parseInt(down_votes);
		
		prefix = (vote_calc > 0)?'+':'';
		
		na.createEl('strong', {}, prefix + vote_calc.toString());
		
		na.createEl('img', {'src': 'http://dyn.ifilm.com/website/ver2/comment_vote_up_off.gif'});
		na.createEl('img', {'src': 'http://dyn.ifilm.com/website/ver2/comment_vote_down_off.gif'});
		na.insertIn();
		
		if(CommentVotingManager.vote_type == -1)
			jq('#comment_' + o.voteForIFILMEntityId).addClass('buried');
		
	},
	success: function(o) {
		if (checkAuthenticationDWR(o)) {
			if (o != null) {
				CommentVotingManager.writeVote(o);
			}
		} else {
			IFILM.pageManager.incompleteAjaxRequest = function () {
				VoteProcessor.addVoteToEntity(CommentVotingManager.entity_id, CommentVotingManager.entity_type_id, CommentVotingManager.vote_type, CommentVotingManager.success);
			};
			IFILM.loadingManager.removeLoading();
			IFILM.pageManager.showLoginWindow(null, IFILM.lastNodeClicked);
		}
	},
	failure: function(o) {
		safelog(o);
	},
	trigger: function(e) {
		if(e) {
			preventDefault(e);
			whatWasClicked(e);
		}
		
		
		CommentVotingManager.curVoteMod = jq(this).parent().get(0);
		el_parts = this.id.split("_");
		
		CommentVotingManager.entity_id = el_parts[1];
		CommentVotingManager.entity_type_id = el_parts[2];
		CommentVotingManager.vote_type = el_parts[3];
		
		if(CommentVotingManager.vote_type == 'up')
			CommentVotingManager.vote_type = 1;
		else
			CommentVotingManager.vote_type = -1;
		 
		 VoteProcessor.addVoteToEntity(CommentVotingManager.entity_id, CommentVotingManager.entity_type_id, CommentVotingManager.vote_type, {callback: CommentVotingManager.success, failure: CommentVotingManager.failure, httpMethod: 'GET'});
		
	},
	addTriggers: function() {
		jq('#comment_box .comment_vote a').click(CommentVotingManager.trigger);
		
		jq('#comment_box .buried_comment_control a').click(function(e) {
			preventDefault(e);
			
			id_parts = this.id.split('_');
			
			jq(this).parent().hide();
			jq('#comment_' + id_parts[1] + ' p.actions,#comment_' + id_parts[1] + ' p.comment_text').css("margin-left","0px").fadeIn("normal", function() { jq(this).css("margin-left", "90px"); });
			jq('#comment_' + id_parts[1]).removeClass('buried');
		});
	}
}

commentReplyManager = {
	comment_reply: 0,
	is_reply: false,
	formref: null,
	success: function(o) {
		var xml = o;
	
		if (IFILM.user.checkAuthentication(xml)) {
			IFILM.pageManager.incompleteAjaxRequest = null;
			var errXml = xml.getElementsByTagName('error')[0];
			var err = {
				code: getTag(errXml, "code"),
				description: getTag(errXml, "description")
			}
			
			if(err.code == 0) {
				user = o.getElementsByTagName('user')[0];
				comment = o.getElementsByTagName('comment')[0];
				
				var comment_line = jq("#comment_replies_" +  getTag(comment, 'IFILMEntityId') + "_" + getTag(comment, 'IFILMEntityTypeId')).html();
				comment_arr = comment_line.split(" ");
				comment_number = parseInt(comment_arr[0]);
				comment_number++;
				
				comment_qualifier = ' replies';
				if(comment_number == 1)
					comment_qualifier = ' reply';
								
				jq('#comment_replies_' +  getTag(comment, 'IFILMEntityId') + '_' +  getTag(comment, 'IFILMEntityTypeId')).html(comment_number + " " + comment_qualifier).trigger('click');
			} else {
				safelog(err.description, "ERROR", "CommentManager.Success");
			}
		} else {
			IFILM.pageManager.incompleteAjaxRequest = function () {
				submitToAjax(commentReplyManager.formref.get(0), commentReplyManager);
			};
			IFILM.loadingManager.removeLoading();
			IFILM.pageManager.showLoginWindow(null, CommentManager.getLoginLink());
		}	
	},
	failure: function(o) {
		jq.prompt('There was a problem adding your reply to this comment');		
	},
	revealRepliesSuccess: function(comments) {
		try {
			
			jq('#comment_replies_' + commentReplyManager.comment_reply).remove();
			jq('#comment_' + commentReplyManager.comment_reply).after('<li id="comment_replies_' + commentReplyManager.comment_reply + '" class="comment_replies"><ul></ul></li>');
			
			jq('#comment_replies_' + commentReplyManager.comment_reply).removeClass('load_comments');
			na = new NodeAssembly(jq('#comment_replies_' + commentReplyManager.comment_reply + ' ul').get(0));
			
			page = 1;
		
			var memberLen = comments.members.length;
			
			for (i = 0; i < memberLen; i++) {
				
				var member = comments.members[i];
				if(i == 0)
					first_item = comments.members[i].id;
				
				var member_user = member.user;
				
				var total_votes = member.totalVotes;
				var up_votes = member.totalUpVotes;
				var down_votes = member.totalDownVotes;
				var vote_calc = up_votes-down_votes;
				
				var child_class = '';
				if(i == 0) {
					child_class = 'first-child';
				} else if ( i == (memberLen-1)) {
					child_class = 'last-child';
				}
						
				var buried_status = '';
				
				if(vote_calc < 3 && (member.vote && member.vote.voteType == 1)) {
					buried_status = '';
				} else if(vote_calc <= -2 || (member.vote && member.vote.voteType == -1)) {
					buried_status = 'buried';
				} else if(vote_calc >= 3) {
					buried_status = 'hot';
				} 
				
				var li = na.createElWithAssembly("li", {"class": "clearfix " + child_class + " "  + buried_status, "id":"comment_" + member.id});
				li.createEl("a", {"name": "comment_" + member.id});
				var avatar_div = li.createElWithAssembly("div", { "class":"avatar_frame " + (member_user.userIsAFriend?'is-a-friend':'not-a-friend')});
				var avatar_link = avatar_div.createElWithAssembly("a", {"class":"tn_frame", "href":member_user.URL, 'class':'avatar'});
				if (member_user.imageURL == "") {
					avatar_link.createEl("img", {"src":"http://dyn.ifilm.com/image/website/standard-avatar-80.gif", "alt":member_user.login, "class":"avatar"});
				} else {
					avatar_link.createEl("img", {"src":member_user.imageURL + "?width=80", "alt":member_user.title, "class":"avatar"});
				}
				//avatar_div.createEl('a', {'href':'#', 'class':'tool-friend-trigger', 'id': 'friendid-' + member_user.id + '-' + i}, '^');
		
				var vote = li.createElWithAssembly('div', {'class':'comment_vote'});
				
				prefix = (vote_calc > 0)?'+':'';
				vote.createEl('strong', {}, prefix + vote_calc );
				if(member.vote && member.vote.hasVote) {
					vote.createEl('img', {'src': 'http://dyn.ifilm.com/website/ver2/comment_vote_up_off.gif'});
					vote.createEl('img', {'src': 'http://dyn.ifilm.com/website/ver2/comment_vote_down_off.gif'});
				} else {
					var up_link = vote.createElWithAssembly('a', {'href':'#', 'id': 'commentvote_' + member.id + '_' + member.entityTypeId + '_up'});
					up_link.createEl('img', {'src': 'http://dyn.ifilm.com/website/ver2/comment_vote_up.gif'});
					var down_link = vote.createElWithAssembly('a', {'href':'#', 'id': 'commentvote_' + member.id + '_' + member.entityTypeId + '_down'});
					down_link.createEl('img', {'src': 'http://dyn.ifilm.com/website/ver2/comment_vote_down.gif'});
				}
				
				var comment_meta = li.createElWithAssembly("p", {"class":"commentmeta"});
		
				var this_page = (i+1)+(CommentPagingManager.maxPerPage*(page-1));				
				comment_meta.createEl("span", {"class":"number"}, this_page + ". ");
				comment_meta.createEl("a", {"href":member_user.URL, "title":"comments", "class":""}, member_user.title);
				comment_meta.createEl("span", {"class":"date"}, "Posted on " + member.createFormatted);
				li.createEl("p", {"class":"comment_text"}, {htmlStr:member.description});
				var tools = li.createElWithAssembly("p", {"class":"actions"});
				tools.createEl("a", {"href":"#", "class":"flag", "id":"flagcomment_" + member.id}, "Flag as inappropriate");
		                if(IFILM.user.isAdmin) {
				tools.createEl("a", {"href":"/offlinecomment?IFILMEntityId=" + member.id + "&IFILMEntityTypeId=" + member.entityTypeId, "class":"offline", "id":"offline_comment_" + member.id}, "Make it offline");
		                }
				var buried = li.createElWithAssembly("p", {"class":"buried_comment_control"}, "This comment has been buried by our users.");
				buried.createEl("a", {"href":"#", "class":"show_comment", "id":"buried_" + member.id}, "Reveal Comment");
			}
			na.insertIn();
			
			OfflineManager.addTriggers();
			if(jq('#leavecomment_' + comments.id).get(0))
				jq('#leavecomment_' + comments.id).remove();
			
			
				//document.location = '#comment_' + first_item;			//else
			if(commentReplyManager.is_reply)
				document.location = '#comment_' + comments.members[memberLen-1].id;
			
			IFILM.loadingManager.removeLoading();
			
			commentReplyManager.is_reply = false;
		} catch(e) { alert(e) }
	}, revealRepliesTrigger: function(e) {
		if(e) preventDefault(e);
		
		if(jq.trim(jq(this).html()) == '0 replies')
			return false;
		
		id_parts = jq(this).attr('id').split('_');
			
		comment_id = id_parts[2];
		type_id = id_parts[3];
		
		
		commentReplyManager.comment_reply = comment_id;
		
		jq('#comment_replies_' + commentReplyManager.comment_reply).remove();
		jq('#comment_' + commentReplyManager.comment_reply).after('<li id="comment_replies_' + commentReplyManager.comment_reply + '" class="comment_replies load_comments"><ul><li>Loading Comments</li></ul></li>');
				
		LoadEntityDWR.getEntityForDWR(comment_id, type_id, 1, 100, '#', {callback: commentReplyManager.revealRepliesSuccess, errorHandler: commentReplyManager.failure, httpMethod: 'POST'});
	}, replyTrigger: function(e) {
		if(e) preventDefault(e);
		try {
			id_parts = jq(this).attr('id').split('_');
			
			comment_id = id_parts[3];
			type_id = id_parts[4];
			
			commentReplyManager.comment_reply = comment_id;
			
			var comment_form = '';
			comment_form += '<form name="leavecomment" class="leavecomment" id="leavecomment_' + comment_id + '" action="/stripesAction/comments/addComment" method="get">';
			comment_form += '<div id="comment_loading">';
			comment_form += '<h3>Saving your comment...</h3>';
			comment_form += '<img alt="Loading..." src="http://dyn.ifilm.com/website/loadingAnimation.gif"/>';
			comment_form += '</div>';
			comment_form += '<fieldset>';
			comment_form += '<textarea id="commentfield" name="body" cols="45" rows="10"/>';
			comment_form += '<input type="hidden" value="/video/guilty-as-charged/3073423" name="returnURL"/>';
			comment_form += '<script type="text/javascript">document.leavecomment.returnURL.value=document.location;</script>';
			comment_form += '<input type="hidden" value="' + comment_id + '" id="comment_IFILMEntityId_' + comment_id + '" name="IFILMEntityId"/>';
			comment_form += '<input type="hidden" value="' + type_id + '" id="comment_IFILMEntityTypeId_' + comment_id + '" name="IFILMEntityTypeId"/>';
			comment_form += '<input type="submit" class="submit_comment_btn btn" id="submit_comment_btn" value="Leave A Comment" name="addComment"/>';
			comment_form += '</fieldset>';
			comment_form += '</form>';
			
			jq(this).parent().after(comment_form);
			
			jq('#leavecomment_' + comment_id).submit(function(e) {
				if(e) preventDefault(e);
				commentReplyManager.formref = jq(this);
				commentReplyManager.is_reply = true;
				loadingEl = jq("#comment_" + comment_id).get(0);
				IFILM.loadingManager.setLoading(loadingEl);
				IFILM.commentManager.position = this.id.replace(/leavecomment_/, "");
				submitToAjax(this, commentReplyManager, IFILM.commentManager.validate);
			});
		} catch(e) { alert(e); }
	},
	addTriggers: function() {
		jq('#comment_box a.reply_to_comment').unbind("click").click(commentReplyManager.replyTrigger);
		jq('#comment_box a.comment_reply').unbind("click").click(commentReplyManager.revealRepliesTrigger);
	}
};

pageLoadFuncs.push(function() {
	CommentVotingManager.addTriggers();
	commentReplyManager.addTriggers();
});



pageLoadFuncs.push(function() {
	FriendManager.addTriggers();
});

var FriendManager = {
	friend: null,
	friendTrigger: function(e) {
		if(e) { preventDefault(e); }
		
		var url = this.href;
		
		var url_parts = url.match(/friendId=([0-9]*)/);
		FriendManager.friend = url_parts[1];
		
		if(UserFriendDWR) {
			if(jq(this).html() == 'Add Friend') {
				UserFriendDWR.addFriend(FriendManager.friend, {callback: FriendManager.success, errorHandler: FriendManager.failure});
			} else {
				if( confirm('Do you really want to remove this person as your friend?') )
					UserFriendDWR.removeFriend(FriendManager.friend, {callback: FriendManager.success, errorHandler: FriendManager.failure});
			}
		}
		whatWasClicked(e);
		//fetchFromAjax(this.href, FriendManager, "GET");
	},
	success: function(o) {
		if(IFILM.user.id || checkAuthenticationDWR(o)) {
			FriendManager.closeTrigger();
			
			if(document.location.toString().match(/friends/) == 'friends' && o.match && o.match(/Remove/) == 'Remove' && FriendManager.friend) {
				jq('#friend_' + FriendManager.friend).remove();
				jq('#friends ul:first li').each(function(i) {
					jq(this).removeClass('alt_friend');
					if(i%4 == 3)
						jq(this).addClass('alt_friend');
				});
			}
			
			if(o.match && o.match(/Remove/) == 'Remove')
				jq.prompt("Your friend has been removed.");
			
			if(o.description)
				jq.prompt('Friend request has been sent.');
		} else {
			IFILM.pageManager.showLoginWindow();
			
			IFILM.pageManager.incompleteAjaxRequest = function() {
				UserFriendDWR.addFriend(FriendManager.friend, {callback: FriendManager.success, errorHandler: FriendManager.failure});
			}
		}
	},
	failure: function(o) {
		safelog(o, 'error adding friend');
	},
	closeTrigger: function(e) {
		if(e) { preventDefault(e); }
		var parent_menu = jq('#friends-panel').parent();
		
		parent_menu.removeClass('triggered');
		
		jq('#friends-panel').slideUp("fast", function() { jq('#friends-panel').remove(); });
		
		
		parent_menu.parent().css('overflow', 'hidden');
		
		avatar_link = jq('a.avatar', parent_menu);
		avatar = jq('a.avatar img', parent_menu);
		jq(document).unbind('click',FriendManager.closeTrigger);
		
	},
	trigger: function(e) {
		if(e) { 
			preventDefault(e);
			stopPropagation(e); 
		}
		
		jq(this).parent().addClass('triggered');
		
		if(jq('#friends-panel', jq(this).parent()).get(0)) {
			FriendManager.closeTrigger();
			return;
		}
		
		var parent_menu = jq(this).parent();
		parent_menu.parent().css('overflow', 'visible');
		avatar_link = jq('a.avatar', parent_menu);
		avatar = jq('a.avatar img', parent_menu);
		user_name = avatar_link.attr('title');
		link = avatar_link.attr('href');
		
		avatar_link.next().after('<div id="friends-panel"></div>');
		var na = new NodeAssembly(jq('#friends-panel').get(0));
		
		var friend = jq(this).parent().is('.is-a-friend');
				
		var ul = na.createElWithAssembly('ul');
		 
		var li_1 = ul.createElWithAssembly('li');
		li_1.createEl('a', {'class':'view_profile', 'href': link}, 'View Profile');
		var li_2 = ul.createElWithAssembly('li');
		
		if(friend)
			li_2.createEl('a', {'class':'add_friends', 'href':'/friends?fxn=deny&friendId=' + this.id.split('-')[1]}, 'Remove Friend');
		else
			li_2.createEl('a', {'class':'add_friends', 'href':'/friends?fxn=addFriend&friendId=' + this.id.split('-')[1]}, 'Add Friend');
			
		var li_3 = ul.createElWithAssembly('li', { 'class':'message_user' });
		li_3.createEl('a', {'class':'message', 'href':'/message?fxn=write&width=600&height=400&userId=' + this.id.split('-')[1] + '&recipients='+user_name}, 'Message User');
		na.insertIn();
		
		jq('.close-panel').click(FriendManager.closeTrigger);
		jq('#friends-panel').slideDown("fast");
		
		jq('.add_friends').click(FriendManager.friendTrigger);
		jq(document).bind('click',FriendManager.closeTrigger);
		jq('#friends-panel a').click(function(e) { stopPropagation(e); });
		
		jq('#friends-panel a.message').click(messageUser);
		
	},
	addTriggers: function() {
		jq('.tool-friend-trigger').click(FriendManager.trigger);
		var preload = new Image();
		preload.src = "http://dyn.ifilm.com/website/friends-panel.gif";
	}
};

FriendApprovalManager = {
	friendId: null,
	action: null,
	messages: {
		approve: "Friend Approved.",
		deny: "Friend Rejected.",
		block: "Friend Blocked."
	},
	success: function(o) {
		var na = new NodeAssembly(jq('#friend_' + FriendApprovalManager.friendId).get(0));
		na.createEl('p', {'class':'action_taken'}, FriendApprovalManager.messages[FriendApprovalManager.action]);
		na.insertIn();
	},
	failure: function(o) {
		safelog(o, "ERROR", "FriendApprovalManager");
	},
	trigger: function(e) {
		if(e) preventDefault(e);
		
		var id_parts = this.id.split("-");
		var friend_id = this.href.match(/friendId=([0-9]*)/);
		
		FriendApprovalManager.friendId = friend_id[1];
		FriendApprovalManager.action = id_parts[2];
		if(id_parts[2] == 'approve') {
			UserFriendDWR.approveFriend(friend_id[1], null, FriendApprovalManager.success);
		} else if(id_parts[2] == 'deny') {
			UserFriendDWR.removeFriend(friend_id[1], FriendApprovalManager.success);
		} else if(id_parts[2] == 'block') {
			UserFriendDWR.blockFriend(friend_id[1], FriendApprovalManager.success);
		}
	},
	addTriggers: function() {
		jq('.tools-friend-actions').click(this.trigger);
	}
};

pageLoadFuncs.push(function() {
	FriendApprovalManager.addTriggers();
});
