 
function PageManager() { };
PageManager.prototype = {
	setLoginMessage: function(message,el) {	
		jq(el).find('p.login_error').each(function() {
			jq(this).html(message);
			jq(this).addClass("show");
		});
	},	
	showLoginWindow: function(message, el) {
		var loginWin = jq('#INPAGELOGIN').show().get(0);
		if(loginWin) {
			var vpw = getViewportWidth();
			var vph = getViewportHeight();
			var w = jq(loginWin).width();
			if(jq.browser.msie && jq.browser.version == '6.0') {
				jq(loginWin).css('left', (vpw/2-w/2) + 'px').animate({'top': (document.documentElement.scrollTop+((vph/2)-(jq(loginWin).height()/2)))+ 'px'}, 1000);
			} else {
				jq(loginWin).css('left', (vpw/2-w/2) + 'px').animate({'top':'200px'}, 1000);
			}
			/*jq(loginWin).unbind('focus').focus(function() {
				try {
					jq(document).unbind('click',FriendManager.closeTrigger);
				} catch(e) { }
			}).blur(function() {
				try {
					jq(document).bind('click',FriendManager.closeTrigger);
				} catch(e) { }
			});
			
			jq(loginWin).removeClass("loading");
			message = message || ""; 
			var atEl = el || IFILM.lastNodeClicked;
			IFILM.lastNodeClicked = atEl;
			atEl = atEl || jq('#USER').get(0);
			if(atEl) {
				try { 
					xy = {};
					var offset = jq(atEl).offset({scroll: false});
					offset.left = (offset.left-140)+(jq(atEl).outerWidth()/2);
					offset.top = offset.top+jq(atEl).outerHeight();
					
					var background_pos = -65;
					
					if(offset.left < 0) {
						background_pos = background_pos+offset.left;
						offset.left = '10px';
					}

					if(atEl.id == "LOGINLINK")
						jq('#HEADERAD,body iframe:last').css('visibility','hidden');
				} catch(e) {
					safelog(e, "ERROR", "showLoginWindow");
				}
			}
			jq("#LOGIN_MESSAGE").html(message);
			jq(loginWin).css({top: offset.top, left: offset.left, 'background-position': background_pos + 'px 0'});
			jq(loginWin).fadeIn("normal");
			jq('#INPAGE_LOGIN').get(0).focus();
			IFILM.focusSet = true; */
		} else { jq.prompt("Cannot find login window"); }
	  },
	removeLoginWindow: function(autoClosed) {
		var clearRequest = true;
		if(!!autoClosed) {
			clearRequest = false;
		}
		
		jq('#INPAGELOGIN:visible').fadeOut("normal");
		jq('#INPAGELOGIN').css('top','-500px');
		
		if(clearRequest) {
			this.incompleteAjaxRequest = null;
		}
		
		jq('#HEADERAD,body iframe:last').css('visibility','visible');
	},
	displayPersonalization: function(xmlobj) {
		var user = xmlobj.getElementsByTagName("user")[0];
		if(user) {
			try {
			var userid = getTag(user, "id");
			var username = getTag(user, "login");
			var avatar = getTag(user, "avatar");
			var firstname = getTag(user, "firstname");
			var lastname = getTag(user, "lastname");
			var pmcount = getTag(user, "pmcount");
			var requestcount = getTag(user, "requestcount");
			
			var pEls = {
				USER: jq('#USER').get(0),
				LOGOUT: jq('#LOGOUT').get(0),
				MYIFILM: jq('#myspike_login').get(0)
			}
			jq("#USER,#LOGOUT,#myspike_login").empty();
			var userNa = new NodeAssembly(pEls.USER);
			userNa.createEl("a", { href:"/myspike", id: "USER_ID"}, username);
			var logoutNa = new NodeAssembly(pEls.LOGOUT);
			logoutNa.createEl("a", { href: "/control/logout" }, "Log-out");
			logoutNa.insertIn();
			userNa.insertIn();
			
			jq("#activity_bar .loginlink").attr('href', '/myspike').unbind('click');
			jq("#activity_bar .loginlink img").attr('src', 'http://dyn.ifilm.com/website/ver2/activity-profile.png');
			
			jq('#USER').hover(function() {
				jq(this).addClass('hover');
			}, function() {
				jq(this).addClass('hover');
			});
			
			
			jq('#MAINCONTENT a.tool-send').each(function() {
				jq(this).removeClass('not-logged-in');
			});
			
			/* if(StringUtils.trim(firstname) == '' || StringUtils.trim(lastname) == '') {
				jq('#UPPERHEADER').before('<div id="prompt"></div>');
				var np = new NodeAssembly(jq('#prompt').get(0));
				var cp = np.createElWithAssembly('a', {'href':'/', id:'closeprompt'});
				cp.createEl('img', {'src':"http://dyn.ifilm.com/image/img/video_wall_delete.gif"});
				np.createEl('p',{},'SPIKE.com now has more advanced social features.  Current users are encourged to provide us with a first and last name to help you connect with other users.');
				
				var form = np.createElWithAssembly('form', {'name': 'name_update', 'id': 'update_names', 'action':'/stripesAction/useredit'});
				form.createEl('label', {'for':'firstName'}, 'First Name:');
				form.createEl('input', {'type':"text", 'class':"text", 'name':"firstName", 'id':"firstName", 'value':""});
				form.createEl('label', {'for': 'lastName'}, 'Last Name:');
				form.createEl('input', {'type':"text", 'class':"text", 'name':"lastName", 'id':"lastName", 'value':""});
				form.createEl('input', {'type':"submit", 'name':"submit_names", 'value':"UPDATE", 'class':"btn"});
				form.createEl('input', {'type':"hidden", 'name':"fxn", 'value':"updateFirstAndLastName"});
				form.createEl('input', {'type':'hidden', 'name':'userId', 'value': userid});
				
				np.insertIn();
				
				jq('#prompt').fadeIn('fast');
				IFILM.cookieManager.set('prompt', false);
				
				jq('#closeprompt').click(function(e) {
					preventDefault(e);
					jq('#prompt').fadeOut("fast");
				});
				
				jq('#update_names').submit(function(e) {
					preventDefault(e);
					if(StringUtils.trim(jq('#firstName').val()) == '' || StringUtils.trim(jq('#lastName').val()) == '') {
						jq.prompt('Please enter both your first and last name.');
						return;
					}
					submitToAjax(this, {success: function() {
						jq.prompt('Thank you!');
						jq('#prompt').fadeOut("fast");
					}, failure: function() {
						jq.prompt('There was a problem updating your information, please try again.');
					}});
				});
			} */
		} catch(e) { safelog("error writing personalization: " + e,"error","PageManager.displayPersonalization"); }

		}
	},
	triggers: {},
	dynForms: {},
	dynMenus: {},
	incompleteAjaxRequest: null
};

registrationManager = {
	success: function(o) {
		if(getTag(o, "loginresponse") != "") {
			IFILM.pageManager.removeLoginWindow();
			IFILM.pageManager.displayPersonalization(o);
			if(IFILM.pageManager.incompleteAjaxRequest) { IFILM.pageManager.incompleteAjaxRequest(); }
		} else {
			var errors = o.getElementsByTagName("registererror");
			var message = "";
			for( i = 0; i < errors.length; i++ ) {
				message += StringUtils.trim(jq(errors[i]).text()) + "\n";
			}
			
			alert(message);
			
			Recaptcha.reload();
			
			IFILM.loadingManager.removeLoading();
		}
	},
	failure: function(o) {
		safelog(o);
	},
	checkUsername: function(e) {
		if(StringUtils.trim(jq(this).val()) != '') {
			UsernameUtil.validateUserNameAvailability(StringUtils.trim(jq(this).val()),
				{callback: registrationManager.usernameSuccess});
				IFILM.loadingManager.setLoading(this);
		}
		jq('#LOGINCHECK').html('').hide();
	},
	trigger: function(e) {
		if(e) preventDefault(e);
		IFILM.loadingManager.setLoading(this);
		var isValid = ValidationManager.triggerFunc(null, this);
		if(isValid)
			submitToAjax(this, registrationManager, null, null);		
	},
	usernameSuccess: function(o) {
		message_class = '';
		if(o == 'This username is available')
			message_class = 'available';
		else
			message_class = 'unavailable';
		
		jq('#LOGINCHECK').removeClass('available').removeClass('unavailable').addClass(message_class).html(o).show();
		IFILM.loadingManager.removeLoading();
	},
	addTriggers: function() {
		jq("#INPAGEREG_LOGIN").blur(registrationManager.checkUsername);
		jq('#QUICKREG').submit(registrationManager.trigger);
	}
}

var loginErrorMessage = "";
function checkAuthentication(atxml) {
	try {
		var errXML = (atxml.getElementsByTagName('error')) ? atxml.getElementsByTagName('error')[0] : null;
        loginErrorMessage = getTag(errXML, 'description');
		if(errXML) {
			var autherr = {
				code: parseInt(getTag(errXML, 'code')),
				description: getTag(errXML, 'description')
			};
			if(autherr.code == -404) { IFILM.user.authenticated = false; }
			else {
				var user = atxml.getElementsByTagName("user")[0];
				var userid = getTag(user, "id");
				var login  = getTag(user, "login");

				if(parseInt(userid) && (login != null && login != "")) {
					IFILM.user.authenticated = true;
					IFILM.user.id = parseInt(userid);
					IFILM.user.login = login;
				}
				else { IFILM.user.authenticated = false; }
			}
			return IFILM.user.authenticated;
		}
		IFILM.user.authenticated = false;
		return IFILM.user.authenticated;
	}
	catch(e) { safelog(e,"error", "checkAuthentication"); return false; }
};

function checkAuthenticationDWR(return_code) {
	try {
		IFILM.user.authenticated = (return_code && return_code.currentUserId);
		if(IFILM.user.authenticated == null)
			IFILM.user.authenticated = false;
			
		return IFILM.user.authenticated;
	} catch(e) {
		safelog(e,"error", "checkAuthenticationDWR");
		return false;
	}
};

UserManager =  {
	id: null,
	login: null,
	authenticated: false,
	loaded: false,
	hasLoggedIn: false,
	isAdmin: false,
	submitted_form: null,
	success: function(o) {
		var xml = o;
		if(xml) {
			try {
				UserManager.onAuthenticate(xml);
				IFILM.loadingManager.removeLoading();
			} catch(e) { safelog(e); }
		}
		else { 
			jq.prompt("There was an error authenticating your account.");
			safelog("Document was not XML", "ERROR", "UserManager.success");
		
		}
	},
	loadFromXML: function(xmlobj) {
		var atXML = xmlobj.responseXML;
		if(atXML) {
			this.id				= getNodeText(atXML.getElementsByTagName("id")[0]);
			this.authenticated	= getNodeText(atXML.getElementsByTagName("authenticated")[0]);
			this.login          = '';
			this.loaded			= true;
		}
	},

	requestAuthentication: function(el) {
		IFILM.pageManager.showLoginWindow(null, el);
	},

	onAuthenticate: function(xmlobj) {
		
		var atxml = xmlobj;
		var auth = this.checkAuthentication(atxml);
		
		if(auth) {
			this.authenticated	= true;
			if(jq('#returnOnLogin').get(0)) {
				jq('#returnOnLogin').get(0).submit();
				return;
			}
			
			try {
				IFILM.pageManager.removeLoginWindow(true);
				IFILM.pageManager.displayPersonalization(atxml);
				if(IFILM.pageManager.incompleteAjaxRequest) { IFILM.pageManager.incompleteAjaxRequest(); }
			}
			catch(e) { safelog(e, "error", "UserManager.onAuthenticate"); }
		}
		else {
			this.onAuthenticationFailure(xmlobj);
		}
	},
	onAuthenticationFailure: function(o) {
		var submittedForm = this.submitted_form;
		IFILM.loadingManager.removeLoading();
		IFILM.pageManager.setLoginMessage("Your username/password is not valid.");
	},
	checkAuthentication: checkAuthentication,
	checkAuthenticationDWR: checkAuthenticationDWR
};

var IFILM = {
	suppressLogging: (QueryManager.getAsBoolean("jsdebug")) ? false : true,
	user: UserManager,
	pageManager: new PageManager(),
	cookieManager: new CookieManager(),
	queryManager: QueryManager,
	focusSet: false,
	lastNodeClicked: null,
	realtimeServer: null,
	constants: {
		OPENSCRIPT: "<script type=\"text/javascript\" ",
		CLOSESCRIPT: "</script>",
		DASHES: "--",
		AMP: "&",
		Q: '"',
		SQ: "'"
	}
};

function getIFILMCookie(name) { return IFILM.cookieManager.getIFILMCookie(name); }
function setIFILMCookie(name, value) { IFILM.cookieManager.setIFILMCookie(name, value); }

/* LOADING MANAGER */
IFILM.loadingManager = {
	curLoadingEl: null,
	loadClassName: "loading",
	setLoading: function(el,msg) {
		this.removeLoading();
				
		if(el.id == "INPAGELOGIN")
			this.curLoadingEl = el.getElementsByTagName('fieldset')[0];	
		else
			this.curLoadingEl = el;
		
		if(!msg)
			msg = 'Loading...';
		
		if(this.curLoadingEl.tagName == 'UL') {
			jq(this.curLoadingEl).before('<div id="loadingEl"><h3>' + msg + '</h3> <img src="http://dyn.ifilm.com/website/loadingAnimation.gif" /></div>')
			var height = jq(this.curLoadingEl).height();
			var width = jq(this.curLoadingEl).width()
			
			if(jq(this.curLoadingEl).attr('id') == 'FEATURELIST' && jq(this.curLoadingEl).css('visibility') == 'hidden')
				width = width/2;
			
			jq('#loadingEl').css({ 'height': height + 'px', 'width':width + 'px', 'opacity': '.8'} );
		}
		
		jq(this.curLoadingEl).addClass(this.loadClassName);
	},
	removeLoading: function(el) {
		var loadingEl = el || this.curLoadingEl;
		if(loadingEl) {
			jq(this.curLoadingEl).removeClass(this.loadClassName);
		
			if(loadingEl.tagName == 'UL')
				jq('#loadingEl').remove();
		}
	}
}

/* MENUS */
/******************************
*	Our menu system is a bit convoluted,
*	I think it was designed to handle multiple cases.
*	I tend to not mess with it much, because I don't really know
*	what everything does.
******************************/
 
var MenuManager = MenuManager || {
	menus: {},
	triggerEls: {},
	autoCloseMenus: function(e, obj) {
		for(var x in MenuManager.menus)
			MenuManager.menus[x].close();
	},
	interruptAutoClose: function(e) {
		if(e)
			stopPropagation(e);
	},
	inferMenuAction: function(e, obj) {
		if(e) { stopEvent(e); }
		var myid = this.id;
		safelog("clicked el = " + myid, "info", "MenuManager.inferMenuAction");
		var menutoopen = null;
		for(var x in MenuManager.menus) {
			var menuObj = MenuManager.menus[x];
			if(x == myid && !jq(menuObj.trigger).is(".triggered")) {
				safelog("Found menu to open: " + x, "info", "MenuManager.inferMenuAction");
				menutoopen = menuObj;
			}
			else { 
				menuObj.close(); 
				safelog("Closing menu: " + x, "info", "MenuManager.inferMenuAction");
			}
		}
		if(menutoopen) {
			safelog("Opening " + x, "info", "MenuManager.inferMenuAction");
			menutoopen.open();
		}
		if(blurel) { blurel(this) }
	},
	init: function() {
		jq(document).click(MenuManager.autoCloseMenus);
	},
	addMenu: function(menuObj) {
		this.menus[menuObj.trigger.id] = menuObj;
	},
	addMenuFromEl: function(elid) {
		var menuObj = new IFILMMenu();
		if(menuObj.init(elid)) {
			safelog("Added Menu: " + elid, "info", "MenuManager.addMenuFromEl");
		} else {
			safelog("Failed to add: " + elid, "error", "MenuManager.addMenuFromEl");
		}
	},
	addMenuWithTrigger: function(triggerid, menuid) {
		var menuObj = new IFILMMenu();
		menuObj.init(triggerid, menuid);
	},
	finalizeMenu: function() {
		jq(this.getEl()).css("display", "none");
	}
};

function IFILMMenu(trigger, menu, animOpen, animClose) {
	this.trigger   = trigger   || null;
	this.menu      = menu      || null;
	this.animOpen  = animOpen  || null;
	this.animClose = animClose || null;
}

IFILMMenu.prototype = {
	open: function() {
		jq(this.trigger).addClass("triggered");
		this.menu.style.height = "auto";
		this.menu.style.display = "block";
		this.menu.style.zIndex = "1000";
		offset = jq(this.trigger).offset();
		var menuY = (offset["top"]) + this.trigger.offsetHeight-1;
		var origX = (offset["left"] - this.menu.offsetWidth + this.trigger.offsetWidth);
		var menuX = this.menu.id != 'GENREMENU'?Math.max(origX, 5):offset["left"];
		var offsetImg = origX - menuX;
		jq(this.menu).css({'top': menuY, 'left': menuX});
		jq(this.menu).css("background-position", offsetImg + "px 0");
		safelog("Opened menu at " + menuX + " (" + origX + "), " + menuY, "info", "IFILMMenu.open");
	},
	close: function() {
		if(jq(this.trigger).is(".triggered")) {
			this.menu.style.display = "none";
			jq(this.trigger).removeClass("triggered");
			if(this.menu.id == 'GENREMENU')
				jq('#MAINCONTENT').css('position', 'relative');
		}
	},

	initTrigger: function(triggerEl) {
		var trigger = jq(triggerEl).get(0);
		if(trigger) { this.trigger = trigger; }
		if(this.trigger) {
			if(!MenuManager.triggerEls[this.trigger.id]) {
				jq(this.trigger).click(MenuManager.inferMenuAction);
				MenuManager.triggerEls[this.trigger.id] = this.trigger;
			}
		}
	},
	initMenu:    function(menuEl) {
		var menu = jq("#" + menuEl).get(0);
		if(menu) {
			if(menu) { this.menu = menu }
			if(this.menu) {
				jq(this.menu).click(MenuManager.interruptAutoClose);
			}
		}
	},
	init: function(triggerid, menu) {
		this.initTrigger(triggerid);
		var triggerel = this.trigger;
		if(triggerel) {
			try {
				if(menu) {
					this.initMenu(menu);
				}
				else {
					var idfrags = this.trigger.id.split("_");
					var menuname = idfrags[1].toUpperCase() + "MENU";
					this.initMenu(menuname);
				}
				MenuManager.addMenu(this);
				return true;
			} catch(e) {
				safelog(e, "error", "IFILMMenu.init");
				return false;
			}
		}
		else { return false; }
	}
}

function openMenu(e, obj, el) {
	if(e) { preventDefault(e); }
	if(window.autoCloseMenu) { window.clearTimeout(window.autoCloseMenu) }
	
	var me = el || this;
	if(window.curTriggeredModule && window.curTriggeredModule != me) {
	  openMenu(null, null, window.curTriggeredModule);
	}
	var adjustLayout = null;
	
	var myid = me.id;
	var myidfrags = myid.split("_");
	var formtype = myidfrags[0].toUpperCase();
	var formparam = myidfrags[1].toUpperCase();
	if(myidfrags.length == 3) {
		var formparamtype = myidfrags[2].toUpperCase();
	} else {
		var formparamtype = null;
	}
	formparam = formparam.replace(/\|.*/, "");
	var form = jq('#' + formtype + 'FORM').get(0);

	if(blurel && this!=window) { blurel(this); }
	
	if(form) {
		if(me.className.indexOf("triggered") >=0) {
			jq(form).css("display", "none");
			jq(me).removeClass("triggered");
			window.curTriggeredModule = null;
			if(adjustLayout) { adjustLayout.style.marginBottom = "0" }
		} else if (formtype == 'SEND' && !IFILM.user.id) {
			IFILM.pageManager.showLoginWindow("You must login to send this clip.", me);
		} else {
			jq(form).removeClass("result");
			jq(me).addClass("triggered");
			var tContainer = me.parentNode;
			
			var oWidth     = (tContainer.offsetWidth > 200) ? tContainer.offsetWidth : 200;
			jq(form).css("display", "block");
			
			if(CUSTOMTOOLFUNCS[formtype]) { CUSTOMTOOLFUNCS[formtype](formparam, form, formparamtype); }
			
			var offset = jq(me).offset();
			var maxLeft = getViewportWidth(); 
			var rightBound = Math.min(offset.left - (jq(me).outerWidth()/2), maxLeft);
			var leftBound = jq(tContainer).offset().left;
			var formX = Math.max(rightBound - (420/2), leftBound);
			
			if((formX + jq(form).width()) > maxLeft)
				formX = maxLeft-500;
			
			jq(form).css('left', formX + 'px');
			
			
			var myBottom = jq(me).outerHeight() + offset.top;
			jq(form).css('top', myBottom-1);
			window.curTriggeredModule = me;
			if(adjustLayout) { adjustLayout.style.marginBottom = (form.offsetHeight + 10) + "px" }
			
			diff = offset.left - jq(form).offset().left - 486;
			
			jq(form).css('background-position', diff + 'px 0px');
			
			//jq('.close-menu').remove();
			jq('.close-menu-img', form).unbind("click").click(function(e) {
				openMenu(null, null, window.curTriggeredModule);
			}).css('cursor', 'pointer');
		
		}
	}
}

var CUSTOMTOOLFUNCS = {
	SEND: function(id, form, typeid) {
		jq(form).find("p.tempstatus").html("").removeClass("show");
		jq("#send_ifilmentityid").val(id);
		jq("#send_ifilmentitytypeid").val(typeid);
		
		if(jq("#E_" + id + " h4 a").get(0))
			jq("#EMAIL_SUBJECT").val(jq("#E_" + id + " h4 a").html())
		else
			jq("#EMAIL_SUBJECT").val(document.title);
	},	
	SHARE: function(id, form) {
		var re = /(flvbaseclip=)[0-9]+/g;
		var ta = form.getElementsByTagName("textarea")[0];
		ta.value = ta.value.replace(re, "$1" + id);
		
		
		ta.select();
		window.setTimeout(CUSTOMTOOLFUNCS.SHAREFOCUS, 50);
		
	},
	URL: function(id, form,type) {
		jq(form).find("p.tempstatus").html("").removeClass("show");
		
		if(jq("#E_" + id + "_" + type + " h4 a").get(0))
			jq("#ENTITYURL").val('http://www.spike.com' + jq("#E_" + id + "_" + type + " h4 a").attr("href"))
		else
			jq("#ENTITYURL").val(document.location.toString());
	},
	SHAREFOCUS: function() {
		var ta = jq('#embed_code').get(0);
		ta.select();
	},
	FLAGCOMMENT: function(id, form) { 
		jq(form).find("p.tempstatus").html("").removeClass("show");
		form.commentId.value = id; 
	},
	OFFLINECOMMENT: function(id, form) { 
		jq(form).find("p.tempstatus").html("").removeClass("show");
	}
}

function blurel(el) { if(el && el.blur) { el.blur(); window.focus(); }}

var EmailManager = {
	formref: null,
	connections: {},
	trigger: function(e) {
		if(e) { preventDefault(e); }
		if(window.curTriggeredModule) { IFILM.loadingManager.setLoading(window.curTriggeredModule);}
		sendToAFriend.execute(this.ifilmentityid.value, this.ifilmentitytypeid.value,  this.subject.value, this.body.value, this.contentTypeId.value,this.recipients.value,null, this.sponsorHtml.value, 
			{callback: EmailManager.success,
			errorHandler: EmailManager.failure });
	},
	validate: function(form) {
		return true;
	},
	failure: function(o) {
		jq(this.formRef).find("p.tempstatus").html("There was an error sending this email, please try again.");
	},
	success: function(o) {
		try { 
			jq(EmailManager.formref).find("p.tempstatus").html("Email sent.");
			jq(EmailManager.formref).addClass("result");
			IFILM.loadingManager.removeLoading(window.curTriggeredModule);
			window.autoCloseMenu = setTimeout(function(){
				openMenu(null, null, window.curTriggeredModule)
			}, 1500);
			jq(EmailManager.formref).find("p.tempstatus").addClass("show");
		} catch(e) {
			safelog(e, "ERROR", "EmailManager.success");
		}

	},
	failure: function(o) {
		IFILM.loadingManager.removeLoading();
	},
	addTriggers: function(form) {
		var atForm = form || jq('#SENDFORM').get(0);
		this.formref = atForm;
		if(atForm)
			jq(atForm).submit(EmailManager.trigger);
	}
}

var pageLoadFuncs = [];

function pageLoadHandler() {
	for(var x=0; x<pageLoadFuncs.length; x++) {
		if(pageLoadFuncs[x] && typeof pageLoadFuncs[x] == "function") {
			try {
				
				pageLoadFuncs[x]();
				pageLoadFuncs[x] = null;
				
			} catch(e) {
				safelog("Error running page load function " + x + ": " + e.message + pageLoadFuncs[x], "error", "pageLoadHandler");
			}
		}
	}
	
	safelog("Ending pageload handler", "info", "pageLoadHandler");
}


jq(document).ready(function() {
	pageLoadHandler();
});

function whatWasClicked(e) {
	IFILM.lastNodeClicked = getTarget(e, true);
};

function IFILMEnvironmentSetup() {
	//Takeover
	try{
		window.coo = getIFILMChip("ifilm_session", "ifilm_big_ad");
		window.qs = (document.location + "").split("?");
		window.ns=false;
		if(qs.length > 1 && qs[1].indexOf("ns=") > -1){
			ns=true;
		}
		if((coo == 'undefined' || coo == null || coo == "") && document.location.hostname.indexOf("iflim")==-1 && (query.indexOf("cp&refsite=")!=-1 || query.indexOf("cpref=")!=-1 || query.indexOf("refsite=6601")!=-1 || query.indexOf("refsite=7041")!=-1)){
			setIFILMChip("ifilm_session", "ifilm_big_ad", "yes");
			if(!ns){
				window.qsBigAd;
				function _hbCookie(a,b) {
					document.cookie=a+"="+b+";path=/;"
				}
				_hbCookie("CREF",document.referrer);
				document.location.replace("/ads/asl/fullscreen/index.jsp?uri=" + document.location);
			}
		} else if (document.location.hostname.indexOf("iflim")!=-1) {
			document.location.replace("http://www.spike.com/" + document.location.search);
		}
	} catch(e) {safelog("error setting takeover params", "error", "takeover"); }
		
	if(query.indexOf("cpref=")!=-1 || query.indexOf("cp&refsite=")!=-1){
		refsiteid = QueryManager.get("refsite");
		referralType = "CPC";
		if(refsiteid!=''){
			setIFILMChip("ifilm_session", "ifilm_refsite", QueryManager.get("refsite"));
			setIFILMChip("ifilm_session", "ifilm_reftype", "CPC");
		}
	} else if(query.indexOf("cmref=")!=-1 || query.indexOf("cm&refsite=")!=-1){
		refsiteid = QueryManager.get("refsite");
		referralType = "Partner";
		if(refsiteid!=''){
			setIFILMChip("ifilm_session", "ifilm_refsite", QueryManager.get("refsite"));
			setIFILMChip("ifilm_session", "ifilm_reftype", "Partner");
		}
	} else if(query.indexOf("refsite")!=-1){
		refsiteid = QueryManager.get("refsite");
		referralType = "n-a";
		if(refsiteid!=''){
			setIFILMChip("ifilm_session", "ifilm_refsite", QueryManager.get("refsite"));
			setIFILMChip("ifilm_session", "ifilm_reftype", "n-a");
		}
	}	
	if(QueryManager.get("cmpnid")) {
		setIFILMChip("ifilm_session", "ifilm_cmpnid", QueryManager.get("cmpnid"));
	}
	if (getIFILMChip('ifilm_session', 'ifilm_cmpnid')) {
		cmpnidsession = getIFILMChip('ifilm_session', 'ifilm_cmpnid');
	} else {
		cmpnidsession = "";
	}
	if (getIFILMChip('ifilm_session','ifilm_refsite')){
		refsiteSession = getIFILMChip('ifilm_session', 'ifilm_refsite');
		reftypeSession = getIFILMChip('ifilm_session', 'ifilm_reftype');
	} else {
		refsiteSession = "default";
		reftypeSession = "none";
	}
	dartRef = "refsite=" + refsiteSession + ";reftype=" + reftypeSession;
	hbxRef = refsiteSession + "|" + reftypeSession;
};

function fetchAsImage(url) {
	var na = new NodeAssembly(document.documentElement.body);
	na.createEl("img", {"src": url, "height": "1", "width":"1", "style":"visibiility:hidden"});
	na.insertIn();
	return true;
}

var AnimateManager = {
	curIndex: 0,
	curThumb: null,
	interval: null,
	reserveTitle: null,
	animateThumb: function(e) {
		if(AnimateManager.curThumb == null && e)
				AnimateManager.curThumb = this;
				
		if(jq('img.animated_thumb',AnimateManager.curThumb).size() > 1) {	
			AnimateManager.setCurInterval();
		} else {
			if(AnimateManager.curThumb)
				AnimateManager.reserveTitle = AnimateManager.curThumb.title;
			AnimateManager.curThumb.title = 'No Preview Available.';
		}
	},
	stopAnimation: function(e) {
		clearTimeout(AnimateManager.interval);
		if(AnimateManager.curThumb && AnimateManager.curThumb.title && AnimateManager.reserveTitle)
			AnimateManager.curThumb.title = AnimateManager.reserveTitle;
	
		AnimateManager.reserveTitle = null;
		AnimateManager.curThumb = null;
		jq('.animated_thumb', AnimateManager.curThumb).css('display', 'none');
		jq('.primary_thumb', AnimateManager.curThumb).css('display', 'inline');
	},
	switchThumb: function() {
		jq('.primary_thumb',AnimateManager.curThumb).css('display', 'none');
		jq('img.animated_thumb', AnimateManager.curThumb).css('display', 'none');
		jq('img.animated_thumb', AnimateManager.curThumb).eq(AnimateManager.curIndex).css('display', 'inline');

		if(AnimateManager.curIndex < jq('img.animated_thumb',  AnimateManager.curThumb).size()-1)
			AnimateManager.curIndex++;
		else
			AnimateManager.curIndex = 0;
	
		AnimateManager.setCurInterval();
	}, 
	setCurInterval: function() {
		AnimateManager.interval = setTimeout("AnimateManager.switchThumb()", 500);
	},
	addTriggers: function() {
		jq('#PRIMARY img.animated_thumb').css('visibility', 'hidden');
		jq('#FEATURELIST .clip a.tn_frame').hover(AnimateManager.animateThumb, AnimateManager.stopAnimation);
	}
}

var PagePropertyManager = {
	formref:null, 
	title: null,
	titleHtml: null,
	editId: null,
	savedTitle: null,
	trigger:function (e) {
		if (e) { preventDefault(e); }
		if (window.curTriggeredModule) {
			IFILM.loadingManager.setLoading(window.curTriggeredModule);
		}
		submitToAjax(this, PagePropertyManager, PagePropertyManager.validate);
	}, validate:function (form) {
		return true;
	}, success:function (o) {
		var xml = o;
		var responseError = xml.getElementsByTagName("error")[0];
		var statusCode = getTag(responseError, "code");
		var atStatus = jq(this.formref).find("p.tempstatus").get(0);
		var atMessage = getTag(xml, "response");
		atStatus.innerHTML = atMessage;
		var id = getTag(xml, "pagePropertyId");
		var title = getTag(xml, "pagePropertyTitle");
		PagePropertyManager.savedTitle = title;
				
		PagePropertyManager.title.empty();
		if(PagePropertyManager.editId.indexOf('.title') != -1) {
			if(StringUtils.trim(title).length)
				PagePropertyManager.title.html(title);
			else
				PagePropertyManager.title.html('(Default Title)');
			
		} else if(PagePropertyManager.editId.indexOf('.sublisting') != 1) {
			var int_title = 'Featured';
			
			if(StringUtils.trim(title) == 'mostrecent') {
				int_title = 'Featured';
			} else if(StringUtils.trim(title) == 'mostviewed') {
				int_title = 'Popular Now';
			} else if (StringUtils.trim(title) == 'newstuff') {
				int_title = 'New Stuff';
			}
				
			PagePropertyManager.title.html('<strong>Current Default:</strong> ' + int_title);
		}
		
		PagePropertyManager.title.append('<a href="#" class="pageproperty" id="' + PagePropertyManager.editId + '">edit</a>');
		
		jq("a.pageproperty").unbind('click').click(PagePropertyManager.createTitleForm);
		
		
		PagePropertyManager.title = null;
		
	}, failure:function (o) {
		IFILM.loadingManager.removeLoading();
	}, addTriggers:function (form) {
		
		var atForm = form || jq("#savetitle").get(0);
		this.formref = atForm;
		if(atForm)
			jq(atForm).submit(this.trigger);
		
		jq('#remove_title').click(this.removeTitle);
		jq('#close_title').click(this.closeTitleForm);
	},
	removeTitle: function(e) {
		if(e) { preventDefault(e); }
		jq('#fxn').val('Remove');
		submitToAjax(jq('#savetitle').get(0), PagePropertyManager, PagePropertyManager.validate);
	}, 
	createTitleForm: function(e) {
		if(e) preventDefault(e);
		if(PagePropertyManager.title != null)
			PagePropertyManager.closeTitleForm();
			
		PagePropertyManager.title = jq(this).parent();
		
		if(PagePropertyManager.editId != this.id)
			PagePropertyManager.savedTitle = null;
			
		PagePropertyManager.editId = this.id;
		PagePropertyManager.titleHtml = PagePropertyManager.title.html();
		

		if(this.id.indexOf('.title') != -1) {
			if(!PagePropertyManager.savedTitle) {
				PagePropertyManager.savedTitle = StringUtils.trim(PagePropertyManager.titleHtml.replace(/(<[^>]*>)edit(<[^>]*>)/,""));
			}
			
			PagePropertyManager.title.empty();
			var na = new NodeAssembly(PagePropertyManager.title.get(0));
		
			var mod_id_parts = PagePropertyManager.editId.split("_");
			mod_id = mod_id_parts[1];
			
			var form = na.createElWithAssembly('form', { 'id':'savetitle' ,'action': jq("#PAGEPROPERTYFORM").attr('action') });
			form.createEl('input', {'type': 'text', 'id':'mod_title', 'name':'pagePropertyTitle', 'value':  PagePropertyManager.savedTitle});
			form.createEl('input', {'type': 'hidden', 'id':'fxn', 'name': 'fxn','value': 'Save' });
			form.createEl('input', {'type': 'hidden', 'id':'pagePropertyUri','name':'pagePropertyUri', 'value': jq('#PAGEPROPERTYFORM').get(0).pagePropertyUri.value });
			form.createEl('input', {'type': 'hidden', 'id':'pagePropertyName','name':'pagePropertyName', 'value': mod_id });
			form.createEl('input', {'type': 'submit', 'class':'btn','value': 'SAVE'});
			form.createEl('a', {'href':'#', 'id':'remove_title'}, "REMOVE");
			form.createEl('a', {'href':'#', 'id':'close_title'}, 'CLOSE');
	
			na.insertIn();
		} else if (this.id.indexOf('.sublisting') != -1) {
			if(!PagePropertyManager.savedTitle) {
				PagePropertyManager.savedTitle = StringUtils.trim(PagePropertyManager.titleHtml.replace(/(<[^>]*>)edit(<[^>]*>)/,""));
			}
			
			PagePropertyManager.title.empty();
			var na = new NodeAssembly(PagePropertyManager.title.get(0));
		
			var mod_id_parts = PagePropertyManager.editId.split("_");
			mod_id = mod_id_parts[1];
			
			
			var tab_arr = new Array();
			jq('#combo_header a').each(function(i) {
				link = jq(this).attr('href');
				matches = link.match(/sublisting=([A-Za-z]*)/);
				sublisting = matches[1];
				text = jq(this).text();
				
				tab_arr[i] = new Array();
				tab_arr[i][0] = sublisting;
				tab_arr[i][1] = text;
			});
			
						
			
			var form = na.createElWithAssembly('form', { 'id':'savetitle' ,'action': jq("#PAGEPROPERTYFORM").attr('action') });
			var select = form.createElWithAssembly('select', {'name':'pagePropertyTitle', 'id':'mod_tab'});
			for(i = 0; i < tab_arr.length; i++)
				select.createEl('option', { 'value':tab_arr[i][0]}, tab_arr[i][1]);
				
			
			form.createEl('input', {'type': 'hidden', 'id':'fxn', 'name': 'fxn','value': 'Save' });
			form.createEl('input', {'type': 'hidden', 'id':'pagePropertyUri','name':'pagePropertyUri', 'value': jq('#PAGEPROPERTYFORM').get(0).pagePropertyUri.value });
			form.createEl('input', {'type': 'hidden', 'id':'pagePropertyName','name':'pagePropertyName', 'value': mod_id });
			form.createEl('input', {'type': 'submit', 'class':'btn','value': 'SAVE'});
			form.createEl('a', {'href':'#', 'id':'remove_title'}, "REMOVE");
			form.createEl('a', {'href':'#', 'id':'close_title'}, 'CLOSE');
	
			na.insertIn();
		}
		PagePropertyManager.addTriggers();
	}, closeTitleForm: function(e) {
		if(e) preventDefault(e);
		PagePropertyManager.title.html(PagePropertyManager.titleHtml);
		jq('a.pageproperty', PagePropertyManager.title).unbind("click").click(PagePropertyManager.createTitleForm);
		PagePropertyManager.title = null;
	}
};

function adjustThumbnails(img) {
	var el = img || this;
	var hide_thumb = false;
	if(jq(el).css('display') == 'none') {
		jq(el).css({'display': 'inline', 'visibility':'hidden'});
		hide_thumb = true;	
	}
	
	var height = jq(el).height();
	
	if(hide_thumb)
		jq(el).css({'display': 'none', 'visibility':'visible'});	
	
	var parent_height = jq(el).parent().height();
	if(height > parent_height) {
		var multiplier = -1;
		jq(el).css('margin-top', ((height-parent_height)/2)*multiplier +'px');
	} else if(height < parent_height) {
		jq(el).css('margin-top', ((parent_height-height)/2) +'px');
	}
}

function adjustThumbnailTriggers() {
	jq('#SIMILARLIST a.tn_frame img, #FEATURELIST a.tn_frame img,#friends_list a.tn_frame img').load(adjustThumbnails);
}

function focusSearch() {
	if(StringUtils.trim(jq(this).val()) == 'Search')
		jq(this).val('');
}

function blurSearch() {
	if(StringUtils.trim(jq(this).val()) == '')
		jq(this).val('Search');
}

var OfflineManager = {
	connections:{},
	offlineEl: null,
	success:function (o) {
	    
		var xml = o;
		if (o) {
			var arr = OfflineManager.offlineEl.id.split("_");
			var entityId = getTag(xml, "IFILMEntityId");
			if (entityId != "") {
				if(arr[1] == 'comment')
					jq("#comment_" + entityId).addClass("offline").html("<p>This comment has been taken offline.</p>");
				else if (arr[1] == 'avatar')
					jq("#USER_PHOTO").attr("src", "http://dyn.ifilm.com/website/ver2/standard-avatar-310.gif");
			}
		} else {
			this.failure();
		}
	}, failure:function (o) {
		jq.prompt("There was an error taking this offline");
	}, addTriggers:function () {
		jq("#BODYCONTENT a.offline").unbind('click').click(OfflineManager.triggerFunc);
	}, triggerFunc:function (e) {
		if (OfflineManager.ConfirmRemoval("Are you sure you want to take this offline?")) {
			try {
				OfflineManager.offlineEl = this;
				if(this.id.split("_")[1] != 'entity') {
					fetchFromAjax(this.href, OfflineManager);
					preventDefault(e);
				}
			}
			catch (err) { }
		} else {
			if (e) { preventDefault(e); }
		}
	}, ConfirmRemoval: function(txt) {
		return confirm(txt);
	}
};

var ContentImpression = null;
var GameImpression = null;

var ImpressionManager = {
	entityId: null,
	contentTypeId: null,
	sourceCompany: null,
	primaryCollectionId: null,
	setImpression: function() {
		if(ContentImpression)
			ContentImpression.setImpression(this.entityId, this.contentTypeId, this.sourceCompany, this.primaryCollectionId);
		else if(GameImpression)
			GameImpression.setGameImpression(this.entityId);
	}	
};

var FlagManager = {
	formref:null, 
	connections:{}, 
	trigger:function (e) {
		if (e) { preventDefault(e); }
		if (window.curTriggeredModule) {
			IFILM.loadingManager.setLoading(window.curTriggeredModule);
		}
		submitToAjax(this, FlagManager, FlagManager.validate);
	}, validate:function (form) {
		return true;
	}, success:function (o) {
		var xml = o;
		var responseError = xml.getElementsByTagName("error")[0];
		var statusCode = getTag(responseError, "code");
		var atStatus = jq(FlagManager.formref).find("p.tempstatus").get(0);
		var atMessage = getTag(xml, "response");
		atStatus.innerHTML = atMessage;
		jq(atStatus).addClass("show");
		jq(FlagManager.formref).addClass("result");
		IFILM.loadingManager.removeLoading();
		window.autoCloseMenu = setTimeout(function () {
			openMenu(null, null, window.curTriggeredModule);
		}, 2000);
	}, failure:function (o) {
		IFILM.loadingManager.removeLoading();
	}, addTriggers:function (form) {
		var atForm = form || jq("#FLAGCOMMENTFORM").get(0);
		this.formref = atForm;
		if(atForm)
			jq(atForm).submit(this.trigger);
	}
};

var MailerManager = {
    sender:null,
    recipients:null,
    subject:null,
    message:null,
    format:null,
	send: function() {
		if(Mailer)
			Mailer.sendDWRMessage(this.sender,this.recipients,this.subject,this.message,this.format,
			{callback: MailerManager.success,
			errorHandler: MailerManager.failure });
	}, failure: function(o) {
		//do something here 
	}, success: function(o) {
		//do something here
	}
};

var FlagEntityManager = {
	formref:null, 
	connections:{}, 
	trigger:function (e) {
		if (e) { preventDefault(e); }
		if (window.curTriggeredModule) {
			IFILM.loadingManager.setLoading(window.curTriggeredModule);
		}
		submitToAjax(this, FlagEntityManager, FlagEntityManager.validate);
	}, validate:function (form) {
		return true;
	}, success:function (o) {
		var xml = o;
		var responseError = xml.getElementsByTagName("error")[0];
		var statusCode = getTag(responseError, "code");
		var atStatus = jq(this.formref).find("p.tempstatus").get(0);
		var atMessage = getTag(xml, "response");
		atStatus.innerHTML = atMessage;
		jq(atStatus).addClass( "show");
		jq(this.formref).addClass("result");
		IFILM.loadingManager.removeLoading();
		window.autoCloseMenu = setTimeout(function () {
			openMenu(null, null, window.curTriggeredModule);
		}, 2000);
	}, failure:function (o) {
		IFILM.loadingManager.removeLoading();
	}, addTriggers:function (form) {
		var atForm = form || jq("#FLAGENTITYFORM").get(0);
		this.formref = atForm;
		if(atForm)
			jq(atForm).submit(this.trigger);
	}
};

moduleListing = null;

var moduleListingManager = {
	type: 'videos',
	time: 'now',
	height: null,
	addTriggers: function() {
		jq('#sort_by_type_list_mod a,#most_pop_nav a').click(moduleListingManager.trigger);
	},
	trigger: function(e) {
		if(e) preventDefault(e);
		moduleListing = null;
		
		IFILM.loadingManager.setLoading(jq('#most_pop').get(0));
		
		moduleListingManager.type = jq(this).attr('href').match(/type=([a-z]*)/)[1];
		
		jq('#most_pop_nav a').removeClass('active');
		jq(this).addClass('active');
		
		if(moduleListingManager.type != 'videos') {
			attachJs(IFILM.realtimeServer + '/realtime/homepage/mostpopular?type=' + moduleListingManager.type + '&rendition=moduleListing.jsp');
		} else {
			attachJs('/top100/homepage?sublisting=mostviewednow&usingAjax=true&max=10');
		}
		
		setTimeout(function() {
			moduleListingManager.checkModuleListing();
		}, 1000);
	},
	checkModuleListing: function() {
		if(moduleListing != null) {
				moduleListingManager.renderModule();
		} else {
			setTimeout(function() {
			moduleListingManager.checkModuleListing();
			}, 1000);
		}
			
	}, 
	renderModule:function() {
		try {
			jq('#most_pop_no_results').remove();
			if(!moduleListing) {
				jq('#most_pop').append('<div id="most_pop_no_results" class="no_results">No Results</div>');
				return;
			}
			
			jq('#most_pop').removeClass();
			jq('#most_pop').empty().append('<div id="most_pop_loading"><h3>Loading...</h3></div><ul id="mod_listing"></ul>').addClass(moduleListingManager.type);
			
			if(moduleListingManager.height)
				jq("#most_pop_loading").css('height', moduleListingManager.height +'px');
			
			var na = new NodeAssembly(jq('#mod_listing').get(0));
			
			for(i = 0; i < moduleListing.length; i++) {
				items = moduleListing[i].split('~');
				
				
				if(moduleListingManager.type != 'articles') {
					var li = na.createElWithAssembly('li');
					var link = li.createElWithAssembly('a', {'href':items[0], 'class':'tn_frame', 'title': items[1]});
					link.createEl('img', {'src':items[2] + '?width=82', 'alt': items[1]});
					li.createEl('a', {'href':items[0], 'title': items[1]}, StringUtils.truncate(items[1], 27));
					li.createEl('span', {}, {htmlStr:'<strong>Views:</strong> ' + items[3]});
				} else {
					if(i < 5) {
						var li = na.createElWithAssembly('li');
						li.createTextEl(i+1 +'. ');
						li.createEl('a', {'href':items[0], 'title': items[1]}, items[1]);
						li.createEl('span', {}, {htmlStr:'<strong>Views:</strong> ' + items[3]});
					}
				}
			}
			
			na.insertIn();
			
			IFILM.loadingManager.removeLoading();
			if(moduleListingManager.type != 'articles') {
				jq('#mod_listing').jcarousel({
					visible: 3,
					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>'
				});
			}
			
			//moduleListingManager.height = jq('#mostpopular').height();
		}catch(e) { alert(e); }
	}
}

function messageUser(e) {
	if(e) 
		preventDefault(e);
	
	var href = this.href;
	href += '&usingAjax=true';
	
	tb_show('', href, null, { success: function() {
			jq('#MESSAGEFORM img').load(adjustThumbnails);
			jq('#MESSAGEFORM').submit(function(e) {
				if(e) preventDefault(e);
				if(ValidationManager.triggerFunc(e, this)) {
					submitToAjax(this, {
						success:function() {
							tb_remove();
							jq.prompt("Your message was sent successfully");
						},failure: function() {
							safelog("Sending your message did not work.");
						}
					});
				}
			});
		}, failure: function() {
	
		}
	});
};

TodayTicker = {
	interval: null,
	tickerItems: null,
	curItem: null,
	index: 0,
	switchItem: function() {
		if(TodayTicker.curItem) {
			jq(TodayTicker.curItem).fadeOut("normal", function() {
				TodayTicker.index++;
				TodayTicker.curItem = TodayTicker.tickerItems.get(TodayTicker.index);
				if(!TodayTicker.curItem) {
					TodayTicker.index = 0;
					TodayTicker.curItem = TodayTicker.tickerItems.get(TodayTicker.index);
				}
				
				jq(TodayTicker.curItem).fadeIn();
			});
		} else {
			TodayTicker.curItem = TodayTicker.tickerItems.get(TodayTicker.index);
			jq(TodayTicker.curItem).fadeIn();
		}
		
		setTimeout("TodayTicker.switchItem()", 7000);
	},
	startTicker: function() {
		this.tickerItems = jq("#nav_ticker li").not(".first-child");
		
		TodayTicker.switchItem();
	}
};

var nav_hover = null;
pageLoadFuncs.push(function() {
	
	jq("#BODYCONTENT form.inpageform").each(function(e) {
		document.body.insertBefore(this, document.body.firstChild);
	});	
	
	jq('#NAVIGATION li,#NAVIGATION li#spikenav li').hover(function() {
		el = this;
		
		if(!el) return false;
		
		jq(el).addClass('sfhover');
		
		//if(jq(el).is('#spiketv'))
			//jq('#ad1div').css('visibility','hidden');
		
		if(jq.browser.msie && jq.browser.version < 7)
			jq(el).find('ul').css({ 'left': (jq(el).offset().left)-375 + 'px' } );	
		else if(jq.browser.msie)
			jq(el).find('ul').css('left', '-110px');			
		
	}, function() {
		//clearTimeout(nav_hover);
		jq(this).removeClass('sfhover');
		//if(jq(el).is('#spiketv') || jq(el).parent().parent().is('#spiketv'))
			//jq('#ad1div').css('visibility', 'visible');
		
		if(jq.browser.msie)
			jq(this).find('ul').css('left', '-999em');
	});
});

pageLoadFuncs.push(function() {	
	//Navigation controls
	jq('#NAVIGATION li').click(function() {
			if(!jq(this).is('#nav_ticker') && !jq(this).is('.first-child'))
				document.location = jq(this).find('a').attr('href');
	});
});

pageLoadFuncs.push(function() {
	//tiny avatar fix.
	jq('#FEATURELIST .posted_by a.posted_avatar img').load(function() {
		try {
			ht = jq(this).height();
			if( ht > 20) {
				var multiplier = -1;
				jq(this).css('margin-top', ((ht-20)/2)*multiplier +'px');
			} else {
				jq(this).css('margin-top', ((20-ht)/2) +'px');
			}	
		} catch(e) { safelog(e); }
	});
});

pageLoadFuncs.push(function() {
	//Menu crap.
	MenuManager.init();
	jq("#SEASONMENU,#GENREMENU,#CHANNELMENU,#SENDFORM,#DOWNLOADSFORM").prependTo(".container");
	
	jq("#GENRENAV a.menutrigger").each(function() {
		MenuManager.addMenuWithTrigger(this, "GENREMENU");
	});
	
	jq("#combo_header a.menutrigger").each(function() {
		MenuManager.addMenuWithTrigger(this,"SEASONMENU");
	});
});

pageLoadFuncs.push(function() {
	//Login and register link manipulation
	jq("#interaction a.tool-send,#BODYCONTENT a.tool-send,#BODYCONTENT a.tool-share,#BODYCONTENT a.tool-downloads,#BODYCONTENT a.tool-url").click(openMenu);
	
	var loginTriggers = [];
	if(jq('#LOGINLINK').get(0)) { loginTriggers.push(jq('#LOGINLINK').get(0)); }
	if(jq('#COMMENTLOGIN').get(0)) { loginTriggers.push(jq('#COMMENTLOGIN').get(0)); }
	jq('#activity_bar .personal_buttons a.loginlink').each(function() {
		loginTriggers.push(this);
	});
	
	var registerLink = jq('#REGISTERLINK').get(0);
	var curUrl = document.location.href;
	if(registerLink)
		loginTriggers.push(registerLink);
	
	for(var x=0; x<loginTriggers.length; x++) { 
		var loginTrigger = loginTriggers[x];
		loginTrigger.href += "?returnURL=" + encodeURIComponent(curUrl);
		jq(loginTrigger).click(function(e) {
			preventDefault(e);
			IFILM.pageManager.showLoginWindow(null, this);
		});
	}
	
	//if(registerLink) registerLink.href += "?returnURL=" + encodeURIComponent(curUrl);
});

pageLoadFuncs.push(function() {
	//Email && validation triggers
	EmailManager.addTriggers();
	registrationManager.addTriggers();
	jq('#UPPERHEADER li.trigger').hover(function() {
		jq(this).addClass("hover");
	}, function() {
		jq(this).removeClass("hover");
	});	
});

pageLoadFuncs.push(function() {
	//search box manipulation
	jq('.search .text').focus(focusSearch).blur(blurSearch);
	jq('.search').submit(function(e) {
		if(StringUtils.trim(jq('.text',this).val()) == '' || StringUtils.trim(jq('.text',this).val()) == 'Search')
			preventDefault(e);
	});
});

pageLoadFuncs.push(function() {
	//thumbnail management.
	var z;
	AnimateManager.addTriggers();
	adjustThumbnailTriggers();
});

pageLoadFuncs.push(function() {
	//page property management and 
	jq("#BODYCONTENT a.pageproperty").click(PagePropertyManager.createTitleForm);
});

pageLoadFuncs.push(function () {
	//flagging management.  
	try {
		FlagManager.addTriggers();
		FlagEntityManager.addTriggers();
		OfflineManager.addTriggers();
		jq('#announcement p').fadeIn("slow");
	} catch(e) { safelog(e, "ERROR"); }
		
	jq("#comment_box a.flag, #avatar_box a.flag, #interaction a.flag,#SUPPLEMENT a.flag").click(openMenu);
});

pageLoadFuncs.push(function() { moduleListingManager.addTriggers(); });

ActivityFeedManager = {
	curIndex: -1,
	item: 1,
	feedTimeArr: [],
	feedArr: [],
	attaching_script: false,
	switchTimeout: null,
	switchItem: function() {
		if(ActivityFeedManager.curIndex >= ActivityFeedManager.feedArr.length-1 || !jq("#current_activity").get(0))
			return;
						
		//jq('#current_activity').fadeOut("normal", function() {
			ActivityFeedManager.curIndex++;
			jq("#current_activity").html(ActivityFeedManager.feedArr[ActivityFeedManager.curIndex]);//.fadeIn();
		//});
		
		if(ActivityFeedManager.feedArr.length - ActivityFeedManager.curIndex < 5 && ActivityFeedManager.attaching_script)
			ActivityFeedManager.attachScript();
		
		var feed_html = '<li class="first-child"><a href="#" class="close-activity-feed"><img src="http://dyn.ifilm.com/website/ver2/close-activity-btn.png"/></a></li><li class="activity-heading"><h3>What\'s happening on SPIKE.com</h3></li>';
		for(i = 6; i > 0; i--) {
			last_child = '';
			if(i == 1)
				last_child = ' class="last-child"';
			
			if(ActivityFeedManager.feedArr[ActivityFeedManager.curIndex+i] != undefined)
				feed_html += '<li' + last_child + '>' + ActivityFeedManager.feedArr[ActivityFeedManager.curIndex+i] + '</li>';
		}		
		ActivityFeedManager.switchTimeout = setTimeout("ActivityFeedManager.switchItem()", 5000);
		//jq('#activity_feed li').fadeOut('normal', function() {
			jq('#activity_feed').html(feed_html);
			jq("#activity_feed .first-child a").click(function(e) {
				if(e) preventDefault(e);
				
				jq('#activity_feed').hide();
				jq('#activity-trigger').attr('src', 'http://dyn.ifilm.com/website/ver2/activity-activity-up.png');
				
				jq('.personal_buttons a.activity').parent().toggleClass('active');
			});
			
		//});
	},
	attachScript: function() {
		ActivityFeedManager.attaching_script = true;
		if(ActivityFeedManager.item > 3)
			ActivityFeedManager.item = 1;
		
		//jq.getJSON(IFILM.realtimeServer + '/ui/js/realtime/realtime1.jsp?callback=?', ActivityFeedManager.initCompleteScript);
		
		if(!IFILM.realtimeServer || IFILM.realtimeServer == "")
			return;
			
		jq.getJSON(IFILM.realtimeServer + '/realtime/activity?callback=?', ActivityFeedManager.initCompleteScript);
		ActivityFeedManager.item++;
		
		jq('#activity_bar .activity').unbind('mouseover').mouseover(function(e) {
			if(e) preventDefault(e);
			
			if(!jq(this).parent().is('.active')) {
				jq('#activity_feed').show();
				jq('#activity-trigger').attr('src', 'http://dyn.ifilm.com/website/ver2/activity-activity-down.png');
				
				jq(this).parent().addClass('active');
			}			
		}).click(function(e) {
			if(e) preventDefault(e);
			if(jq(this).parent().is('.active')) { 
				jq("#activity_feed").hide();
				jq('#activity-trigger').attr('src', 'http://dyn.ifilm.com/website/ver2/activity-activity-up.png');
				jq(this).parent().removeClass('active');
			}
		});
	},
	initCompleteScript: function(d) {
		for(prop in d) {
			for(i = 0; i < d[prop].length; i++) {
				if(!jq.inArray(d[prop][i]["id"], ActivityFeedManager.feedTimeArr) != -1) {
					ActivityFeedManager.feedTimeArr.push(d[prop][i]["id"]);
					item_date = new Date();
					item_date.setTime(parseInt(d[prop][i]["id"]))
						
					safelog(d[prop][i]["text"]);
					ActivityFeedManager.feedArr.push(d[prop][i]["text"].replace(/Someone/,randomDescriptors[Math.round(Math.random()*(randomDescriptors.length-1))]) + ' - ' + prettyDate(item_date));
				}
			}
		}
		
		if(!ActivityFeedManager.switchTimeout)
			ActivityFeedManager.switchItem();
	}
}

pageLoadFuncs.push(function() { if(!(jq.browser.msie && jq.browser.version < 7)) ActivityFeedManager.attachScript(); });

var randomDescriptors = new Array();
randomDescriptors.push('A user');
randomDescriptors.push('A fan');
randomDescriptors.push('A new user');
randomDescriptors.push('A visitor');
randomDescriptors.push('Some guy');
randomDescriptors.push('Some dude');
randomDescriptors.push('A chick');
randomDescriptors.push('A real man');
randomDescriptors.push('A guy at work');
randomDescriptors.push('Some college kid');
randomDescriptors.push('Your mom');
randomDescriptors.push('Your ex-girlfriend');
randomDescriptors.push('Some guy cracking a beer');
randomDescriptors.push('Someone with an internet addiction');
randomDescriptors.push('The world\'s biggest Deadliest Warrior fan');
randomDescriptors.push('Someone who\'s hot for the TNA girls');
randomDescriptors.push('A fan of Spike.com\'s Top 10 lists');
randomDescriptors.push('A grease monkey');
randomDescriptors.push('The drift king');
randomDescriptors.push('A crooked politician');
randomDescriptors.push('The girl next door');
randomDescriptors.push('Your sister\'s hot friend');
randomDescriptors.push('The king of beer pong');
randomDescriptors.push('David Letterman\'s intern');
randomDescriptors.push('Balloon Boy');
randomDescriptors.push('Detective Mac Taylor');
randomDescriptors.push('A NASCAR fan');
randomDescriptors.push('A Hot Girl');
randomDescriptors.push('Your high school sweetheart');
randomDescriptors.push('Your first crush');
randomDescriptors.push('The varsity quarterback');
randomDescriptors.push('A Manswers expert');
randomDescriptors.push('A ninja warrior');
randomDescriptors.push('The competitive eating champion');
randomDescriptors.push('A Cade Courtley fan');
randomDescriptors.push('A Surviving Disaster fan');
randomDescriptors.push('The Max Geiger groupie');
randomDescriptors.push('Some douchebag');
randomDescriptors.push('A cheerleader for Blue Mountain State');
randomDescriptors.push('A kickboxing enthusiast');
randomDescriptors.push('USC\'s biggest hater');
randomDescriptors.push('Super Tramp\'s #1 fan');
randomDescriptors.push('Danny Tanner\'s stain');
randomDescriptors.push('Chuck Norris');
randomDescriptors.push('A dude with a shotgun');
randomDescriptors.push('Three hot chicks');
randomDescriptors.push('Chuck Norris');
randomDescriptors.push('Your girl on the side');
randomDescriptors.push('A soccer hooligan');
randomDescriptors.push('A fan of rugby');
randomDescriptors.push('A person of interest');
randomDescriptors.push('Master Chief');
randomDescriptors.push('Kimbo Slice');
randomDescriptors.push('Megan Fox');
randomDescriptors.push('Your booty call');
randomDescriptors.push('A fan of David Hasselhoff');


/*
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(date){

	diff = (((new Date()).getTime() - date.getTime()) / 1000);
	day_diff = Math.floor(diff / 86400);
			
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return;
			
	return day_diff == 0 && (
			diff < 60 && Math.ceil(diff) + " seconds ago" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
	jQuery.fn.prettyDate = function(){
		return this.each(function(){
			var date = prettyDate(this.title);
			if ( date )
				jQuery(this).text( date );
		});
	};
	
	
//Detects element height with padding, margin, and border

function getElementHeight(target) {
	var element = jQuery(target);
	totalHeight = element.height();
	totalHeight += parseInt(element.css("padding-top"), 10) + parseInt(element.css("padding-bottom"), 10); //Total Padding Height
	totalHeight += parseInt(element.css("margin-top"), 10) + parseInt(element.css("margin-bottom"), 10); //Total Margin Height
	totalHeight += parseInt(element.css("borderTopWidth"), 10) + parseInt(element.css("borderBottomWidth"), 10); //Total Border Height
	return totalHeight;		
}


//Code for background image offset when #announcement exists. Requires fn:getElementHeight()

function bgAnnouncementOffset() {
	if (jQuery("#announcement").get(0) != undefined){
    	//searches for string '[num]px' at end of line
    	var result = jQuery("body").css("background-position").match(/[0-9]*px$/);
    	if (result!=null){
    		yValue = parseInt(result[0].substring(0, result[0].length-2), 10);
    	}
    	else {
    		yValue = 0;
    	}
    	//grabs original x value as string (everything from beginning of line to first space)
		xValue = jQuery("body").css("background-position").match(/^.*\ /);
		jQuery("body").css("background-position",xValue + (yValue + getElementHeight("#announcement")) + "px");
	}
	return;
}

jQuery(document).ready(function() { 
		bgAnnouncementOffset();
		
		jq('.sharethispage a').click(function(e) {
			if(e) preventDefault(e);
			
			var stp_left = getViewportWidth()/2-(335/2);
			var stp_top = getViewportHeight()/2-(296/2);
			
			jq("#share_current_page").css({'left': stp_left + 'px', 'top': stp_top + 'px'});
		});
		
		jq('a.close-activity').click(function(e) {
			if(e) preventDefault(e);
			
			jq('#share_current_page').css('left', '-1000px');
		});
})// Browser Detect Lite  v2.1
// http://www.dithered.com/javascript/browser_detect/index.html
// modified by Chris Nott (chris@NOSPAMdithered.com - remove NOSPAM)
//
// modified by Michael Lovitt to include OmniWeb and Dreamcast

function BrowserDetectLite() {
	var ua = navigator.userAgent.toLowerCase(); 
	this.ua = ua;

	// browser name
	this.isGecko     = (ua.indexOf('gecko') != -1);
	this.isMozilla   = (this.isGecko && ua.indexOf("gecko/") + 14 == ua.length);
	this.isNS        = ( (this.isGecko) ? (ua.indexOf('netscape') != -1) : ( (ua.indexOf('mozilla') != -1) && (ua.indexOf('spoofer') == -1) && (ua.indexOf('compatible') == -1) && (ua.indexOf('opera') == -1) && (ua.indexOf('webtv') == -1) && (ua.indexOf('hotjava') == -1) ) );
	this.isIE        = ( (ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1) ); 
	this.isOpera     = (ua.indexOf("opera") != -1); 
	this.isKonqueror = (ua.indexOf("konqueror") != -1); 
	this.isIcab      = (ua.indexOf("icab") != -1); 
	this.isAol       = (ua.indexOf("aol") != -1); 
	this.isWebtv     = (ua.indexOf("webtv") != -1); 
	this.isOmniweb   = (ua.indexOf("omniweb") != -1);
	this.isDreamcast   = (ua.indexOf("dreamcast") != -1);
	
	// spoofing and compatible browsers
	this.isIECompatible = ( (ua.indexOf("msie") != -1) && !this.isIE);
	this.isNSCompatible = ( (ua.indexOf("mozilla") != -1) && !this.isNS && !this.isMozilla);
	
	// browser version
	this.versionMinor = parseFloat(navigator.appVersion); 
	
	// correct version number for NS6+ 
	if (this.isNS && this.isGecko) {
		this.versionMinor = parseFloat( ua.substring( ua.lastIndexOf('/') + 1 ) );
	}
	
	// correct version number for IE4+ 
	else if (this.isIE && this.versionMinor >= 4) {
		this.versionMinor = parseFloat( ua.substring( ua.indexOf('msie ') + 5 ) );
	}
	
	// correct version number for Opera 
	else if (this.isOpera) {
		if (ua.indexOf('opera/') != -1) {
			this.versionMinor = parseFloat( ua.substring( ua.indexOf('opera/') + 6 ) );
		}
		else {
			this.versionMinor = parseFloat( ua.substring( ua.indexOf('opera ') + 6 ) );
		}
	}
	
	// correct version number for Konqueror
	else if (this.isKonqueror) {
		this.versionMinor = parseFloat( ua.substring( ua.indexOf('konqueror/') + 10 ) );
	}
	
	// correct version number for iCab 
	else if (this.isIcab) {
		if (ua.indexOf('icab/') != -1) {
			this.versionMinor = parseFloat( ua.substring( ua.indexOf('icab/') + 6 ) );
		}
		else {
			this.versionMinor = parseFloat( ua.substring( ua.indexOf('icab ') + 6 ) );
		}
	}
	
	// correct version number for WebTV
	else if (this.isWebtv) {
		this.versionMinor = parseFloat( ua.substring( ua.indexOf('webtv/') + 6 ) );
	}
	
	this.versionMajor = parseInt(this.versionMinor); 
	this.geckoVersion = ( (this.isGecko) ? ua.substring( (ua.lastIndexOf('gecko/') + 6), (ua.lastIndexOf('gecko/') + 14) ) : -1 );
	
	// platform
	this.isWin   = (ua.indexOf('win') != -1);
	this.isWin32 = (this.isWin && ( ua.indexOf('95') != -1 || ua.indexOf('98') != -1 || ua.indexOf('nt') != -1 || ua.indexOf('win32') != -1 || ua.indexOf('32bit') != -1) );
	this.isMac   = (ua.indexOf('mac') != -1);
	this.isUnix  = (ua.indexOf('unix') != -1 || ua.indexOf('linux') != -1 || ua.indexOf('sunos') != -1 || ua.indexOf('bsd') != -1 || ua.indexOf('x11') != -1)
	
	// specific browser shortcuts
	this.isNS4x = (this.isNS && this.versionMajor == 4);
	this.isNS40x = (this.isNS4x && this.versionMinor < 4.5);
	this.isNS47x = (this.isNS4x && this.versionMinor >= 4.7);
	this.isNS4up = (this.isNS && this.versionMinor >= 4);
	this.isNS6x = (this.isNS && this.versionMajor == 6);
	this.isNS6up = (this.isNS && this.versionMajor >= 6);
	
	this.isIE4x = (this.isIE && this.versionMajor == 4);
	this.isIE4up = (this.isIE && this.versionMajor >= 4);
	this.isIE5x = (this.isIE && this.versionMajor == 5);
	this.isIE55 = (this.isIE && this.versionMinor == 5.5);
	this.isIE5up = (this.isIE && this.versionMajor >= 5);
	this.isIE6x = (this.isIE && this.versionMajor == 6);
	this.isIE6up = (this.isIE && this.versionMajor >= 6);
	this.isIE7 = (this.isIE && this.versionMajor == 7);
	
	this.isIE4xMac = (this.isIE4x && this.isMac);
}
var browser = new BrowserDetectLite();//---------------------------------------------------------------
// Opacity Displayer, Version 2.0
// Copyright Michael Lovitt, 6/2002.
// Modified by James Sanders
// Distribute freely, but please leave this notice intact.
//---------------------------------------------------------------
//---------------------------------------------------------------
// OPACITY OBJECT
//
// Instantiates the object, defines the properties and methods.
function OpacityObject(divObj, strPath, method) {
	this.layerObject = divObj.style;
	this.path = strPath;
	this.method = method;
	this.setBackground = od_object_setBackground;
}
// Uses AlphaImageLoader filter, or the css background property,
// as appropriate, to apply a PNG or GIF as the background of the layerObject.
function od_object_setBackground() {	
	if (pngAlpha) {
		this.layerObject.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+this.path+".png', sizingMethod='"+this.method+"')";
	} else if (pngNormal) {
		this.layerObject.backgroundImage = 'url('+this.path+'.png)';
	} else {
		this.layerObject.backgroundImage = 'url('+this.path+'.gif)';
	}
}
//---------------------------------------------------------------
//---------------------------------------------------------------
// OPACITY OBJECT FOR IMG TAGS...
//
// Instantiates the object, defines the properties and methods.
function OpacityObjectImg(divObj) {
	this.layerObject = divObj.style; 
	this.imgObj = divObj;
	this.path = divObj.src;
	this.method = 'crop';
	this.setBackground = od_object_setBackgroundImg;
}
// Uses AlphaImageLoader filter, or the css background property,
// as appropriate, to apply a PNG or GIF as the background of the layerObject.
function od_object_setBackgroundImg() {	
	if (pngAlpha) {
		this.imgObj.src = "./img/spacer.gif"
		this.layerObject.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+this.path+"', sizingMethod='"+this.method+"')";
	} else if (pngNormal) {
		//this.imgObj.src = "./img/spacer.gif"
		//this.layerObject.backgroundImage = 'url('+this.path+')';
	} else {
		
		this.layerObject.backgroundImage = 'url('+this.path+')';
	}
}
//---------------------------------------------------------------
//---------------------------------------------------------------
// OPACITY DISPLAY FUNCTION
// Outputs the image as a div with the AlphaImageLoader, or with
// a standard image tag.
function od_displayImage(strId, strPath, intWidth, intHeight, strClass, strAlt) {	
	if (pngAlpha) {
		document.write('<div style="height:'+intHeight+'px;width:'+intWidth+'px;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+strPath+'.png\', sizingMethod=\'scale\')" id="'+strId+'" class="'+strClass+'"></div>');
	} else if (pngNormal) {
		document.write('<img src="'+strPath+'.png" width="'+intWidth+'" height="'+intHeight+'" name="'+strId+'" border="0" class="'+strClass+'" alt="'+strAlt+'" />');
	} else {
		document.write('<img src="'+strPath+'.gif" width="'+intWidth+'" height="'+intHeight+'" name="'+strId+'" border="0" class="'+strClass+'" alt="'+strAlt+'" />');
	}
}
//---------------------------------------------------------------

//---------------------------------------------------------------
// OPACITY ROLL-OVER FUNCTIONS
function od_rollOver(strId, strColor) {	
	if (pngAlpha) {
		document.getElementById(strId).style.backgroundColor = strColor;
	} else {
	    if (document.images && (flag == true)) {
	        document[strId].src = eval(strId + "on.src");
	    }
	}
}
function od_rollOut(strId, strColor) {	
	if (pngAlpha) {
		document.getElementById(strId).style.backgroundColor = strColor;
	} else {
	    if (document.images) {
	        document[strId].src = eval(strId + "off.src");
	    }
	}
}
//---------------------------------------------------------------

//---------------------------------------------------------------
// global variables

// if IE5.5+ on win32, then display PNGs with AlphaImageLoader
if ((browser.isIE55 || browser.isIE5up) && browser.isWin32 && !browser.isIE7) {
	var pngAlpha = true;
	var strExt = ".png";
// else, if the browser can display PNGs normally, then do that. that list includes:
	//     -Gecko Engine: Netscape 6 or Mozilla, Mac or PC
	//     -IE5+ Mac (OpacityObject applies the background image at 100% opacity)
	//     -Opera 6+ PC
	//     -Opera 5+ Mac (Doesn't support dynamically-set background images)
	//     -Opera 6+ Linux 
	//     -Omniweb 3.1+ 
	//     -Icab 1.9+ 
	//     -WebTV 
	//     -Sega Dreamcast
} else if ((browser.isGecko) || (browser.isIE6up && browser.isMac) || (browser.isIE7 && browser.isWin32) || (browser.isOpera && browser.isWin && browser.versionMajor >= 6) || (browser.isOpera && browser.isUnix && browser.versionMajor >= 6) || (browser.isOpera && browser.isMac && browser.versionMajor >= 5) || (browser.isOmniweb && browser.versionMinor >= 3.1) || (browser.isIcab && browser.versionMinor >= 1.9) || (browser.isWebtv) || (browser.isDreamcast)) {
	var pngNormal = true;
	var strExt = ".png";
	// otherwise, we use plain old GIFs
} else {
	var strExt = ".gif";
}

var ns = (document.all)?false:true;
var browserVersion = parseFloat(navigator.appVersion );
//---------------------------------------------------------------
	var objMyImage = null;	
	var objMyImage2 = null;
	var mainHTML = null;
	function init() {
		
		mainHTML = document.getElementById('content').innerHTML;
		loadImages();
		loadTrans();
		resetStates();
		loadPageContent();
		document.getElementById('content').style.display = "block";
		//initialize();
		
		if (browser.isGecko && browser.isMac){
            var overlay = document.getElementById('overlay');
            overlay.style.opacity = "1.0";
            overlay.filter = "None";
            overlay.style.backgroundColor = "transparent";
            overlay.style.backgroundImage = "url(/promos/truedads/img/overlay2.png)";
        }

		
	}
	
	function loadPageContent(){

		var h = document.location.href; 	
	   h = h.substring(h.lastIndexOf("?")+1);
		if (h == 'events'){
			showEvents();
			jq('a.thickbox').unbind('click');
			tb_init('a.thickbox');
			
			return 1;
		}
		if (h == 'about'){
			showAbout();
			return 1;
		}
		if (h.indexOf('shoutout') == 0){
			showShout();
			return 1;
		}
		
	
	}
	
	function loadTrans(){
	
		var headers = document.getElementsByTagName('div');
		for (var h = 0; h < headers.length; h++){
			
				
			if (headers[h].className == 'header'){
				objMyImage = new OpacityObject(headers[h],'/promos/truedads/img/w-header-2','crop');
				objMyImage.setBackground();
			}
			if (headers[h].className == 'content-holder'){
				objMyImage = new OpacityObject(headers[h],'/promos/truedads/img/w-content-2','scale');
				objMyImage.setBackground();
			}
			if (headers[h].className == 'footer'){
				objMyImage = new OpacityObject(headers[h],'/promos/truedads/img/w-footer-2','crop');
				objMyImage.setBackground();
			}
			if (headers[h].className == 'l-content-holder'){
				objMyImage = new OpacityObject(headers[h],'/promos/truedads/img/w-content-1','scale');
				objMyImage.setBackground();
			}
			if (headers[h].className == 'l-header'){
				objMyImage = new OpacityObject(headers[h],'/promos/truedads/img/w-header-1','crop');
				objMyImage.setBackground();
			}
			if (headers[h].className == 'l-footer'){
				objMyImage = new OpacityObject(headers[h],'/promos/truedads/img/w-footer-1','crop');
				objMyImage.setBackground();
			}
			
			if (headers[h].className == 'robots'){
				objMyImage = new OpacityObject(headers[h],'/promos/truedads/img/robots','crop');
				objMyImage.setBackground();
			}
			
			
			/*if (headers[h].className == 'nav-menu'){
				objMyImage = new OpacityObject(headers[h],'/promos/truedads/img/nave-menu-1','crop');
				objMyImage.setBackground();
			}*/
			
		}
		
		loadTransImgs();
		
	}
	
	function loadTransImgs(){
	
		var images = document.getElementsByTagName('img');
		for (var h = 0; h < images.length; h++){
			var check = images[h].src.substring(images[h].src.lastIndexOf("."));
			if (check == ".png" || check == ".PNG"){
				objMyImage = new OpacityObjectImg(images[h]);
				objMyImage.setBackground();
			}
		
		}
	
	}

	//RLLY COMPLEX NAV SYSTEM...
	//NAV STATES in the form of (src,width,height,adjustment) (for each state)
	var navBarStates = new Array(
		//about nav states...
		new Array(
			new Array("img/nav-about.png",48,21,'-2px'),new Array("/promos/truedads/img/nav-about-selected.png",48,21,'-2px')
					),
		//events nav states...
		new Array(
			new Array("img/nav-events.png",50,22,'-3px'),new Array("/promos/truedads/img/nav-events-selected.png",50,22,'-3px')		
		),
		//shoutouts nav states...
		new Array(
			new Array("img/nav-shoutout.png",84,23,'-3px'),new Array("/promos/truedads/img/nav-shout-selected.png",84,23,'-3px')		
		)
		
	);	

	var currentState = null;

	function resetStates(){
		if (currentState != 'navShout'){
			document.getElementById('voiceThreadLogo').style.display = 'none';
		}
		var navButtons = new Array("navAbout","navEvents","navShout");
		for (var h = 0;h < navButtons.length;h++){
			if (currentState != navButtons[h]){
				var state = navBarStates[h];
				state = state[0];
				var ob = document.getElementById(navButtons[h]);
				
				ob.width = state[1];
				ob.height = state[2];
				ob.style.marginTop = state[3];
				ob.src = state[0];
			}
		}
		loadTransImgs()
	}	
	

	function highlightState(state,element){
		resetStates();
		navObj = document.getElementById(element);
		
		navObj.width = navBarStates[state][1][1];
		navObj.height = navBarStates[state][1][2];
		navObj.style.marginTop = navBarStates[state][1][3];
		navObj.src = navBarStates[state][1][0];
		//loadTransImgs();
	}	
	
	function showAbout(){
		//currentState = "navAbout";
		//resetStates();
		var aboutPage = document.getElementById('about-holder');
		var contentArea = document.getElementById('content');
		var supplement = document.getElementById('SUPPLEMENT');
		//contentArea.style.width="940px";
		supplement.style.left="800px";
		contentArea.innerHTML = aboutPage.innerHTML;
		
		//navObj = document.getElementById('navAbout');
		
		//navObj.width = navBarStates[0][1][1];
		//navObj.height = navBarStates[0][1][2];
		//navObj.style.marginTop = navBarStates[0][1][3];
		//navObj.src = navBarStates[0][1][0];

		loadTransImgs();
	
	}
	
	function showEvents(){
		//currentState = "navEvents";
		//resetStates();
		var aboutPage = document.getElementById('events-holder');
		var contentArea = document.getElementById('content');
		var supplement = document.getElementById('SUPPLEMENT');
		//contentArea.style.width="940px";
		supplement.style.left="800px";
		contentArea.innerHTML = aboutPage.innerHTML;
		jq("a.thickbox", contentArea).attr('rel', 'gallery-truedads');
		
		//navObj = document.getElementById('navEvents');
		
		//navObj.width = navBarStates[1][1][1];
		//navObj.height = navBarStates[1][1][2];
		//navObj.style.marginTop = navBarStates[1][1][3];
		//navObj.src = navBarStates[1][1][0];
		
		loadTransImgs();

	}

	function showShout(){
		currentState = "navShout";
		resetStates();
		var aboutPage = document.getElementById('shout-holder');
		var contentArea = document.getElementById('content');
		contentArea.style.width="100%";
		contentArea.innerHTML = aboutPage.innerHTML;
		
		navObj = document.getElementById('navShout');
		
		navObj.width = navBarStates[2][1][1];
		navObj.height = navBarStates[2][1][2];
		navObj.style.marginTop = navBarStates[2][1][3];
		navObj.src = navBarStates[2][1][0];
		
		document.getElementById('voiceThreadLogo').style.display = 'block';
		loadTransImgs();
		

	}	

	function showMain(){
		currentState = null;
		resetStates();
		var contentArea = document.getElementById('content');
		contentArea.innerHTML = mainHTML;
		loadTrans();
		
		
	}
	

function showFullPress(el){

	document.getElementById('extended-press').style.display = 'block';
	el.innerHTML = "Hide Full Press Release.";
	el.onclick = function(){hideFullPress(el)};
}	

function hideFullPress(el){
	document.getElementById('extended-press').style.display = 'none';
	el.innerHTML = "Show Full Press Release...";
	el.onclick = function(){showFullPress(el)};

}





/** A function that is called whenever the user
    presses the back or forward buttons. This
    function will be passed the newLocation,
    as well as any history data we associated
    with the location. */
function handleHistoryChange(newLocation,historyData) {
  // use the history data to update our UI

  updateUI(newLocation, historyData);                           
}

/** A simple method that updates our user
    interface using the new location. */
function updateUI(newLocation,historyData) {
	      
  if (newLocation == 'aboutTD'){
		showAbout();
		return 1;
  }
  if (newLocation == 'eventsTD'){
  		showEvents();
  		return 1;
  }
  if (newLocation == 'shoutTD'){
  		showShout();
  		return 1;
  }
  if (newLocation == 'mainTD'){
  		showMain();
  		return 1;
  }
 
}

function initialize() {
  // initialize RSH
  dhtmlHistory.initialize();
  
  // add ourselves as a listener for history
  // change events
  dhtmlHistory.addListener(handleHistoryChange);
  
  // determine our current location so we can
  // initialize ourselves at startup
  var initialLocation =  dhtmlHistory.getCurrentLocation();
  
  // if no location specified, use the default
  if (initialLocation == null)
    initialLocation = "initmain";
  
  // now initialize our starting UI
  updateUI(initialLocation, null);
}


function setBrowseTab(){
	btab = document.getElementById('browseTab');
	ctab = document.getElementById('createTab');
	btab.style.background = "#d3d2d0";
	ctab.style.background = "#ffc925";
}

function setCreateTab(){
	btab = document.getElementById('browseTab');
	ctab = document.getElementById('createTab');
	ctab.style.background = "#d3d2d0";
	btab.style.background = "#ffc925";
}




 
var preloadImages = new Array("/promos/truedads/img/nav-about-selected.png","/promos/truedads/img/nav-events-selected.png","/promos/truedads/img/nav-shout-selected.png")    
 
function loadImages() {   
     for (i = 0; i < preloadImages.length; i++) {   
         var preImages = new Image()  
         preImages.src = preloadImages[i]       
		 highlightState(0,'navAbout');
		 highlightState(1,'navEvents');
	     highlightState(2,'navShout');
	     resetStates();
		 }  

	highlightState(0,'navAbout');
    highlightState(1,'navEvents');
	highlightState(2,'navShout');
	resetStates();

 }  
  /**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;// embed the swf from src inside the element with id="voicethreadContainer"
function embedVoiceThread(src) {
  // add extra url parameters
  src += window.location.hash;
  // embed flash
  var so = new SWFObject(src, "voicethread", "100%", "100%", "7", "#EEEEEE");
  so.addParam("allowScriptAccess", "always");
  so.write("voicethreadContainer");
}

// called when the background is dimmed or brightened
function dim(dimmed) {
  var overlay = document.getElementById('overlay');
  if (overlay) {
    overlay.style.display = dimmed ? 'block' : 'none';
    if (dimmed) {
      overlay.onclick = function() {
        CallVoiceThread('Browse');
        return(false);
      }
    }
    else overlay.onclick = function() { return(false); }
  }
}
// called when the url should change to reflect a new location in flash
function setHash(hash, history) {
  // change the hash part of the url
  if (! history) {
    var url = window.location.href;
    var hashPos = url.lastIndexOf('#');
    if (hashPos >= 0) url = url.substr(0, hashPos);
    url += '#'+hash;
    window.location.replace(url);
  }
  else window.location.hash = '#'+hash;
}
// call a method of the VoiceThread player
function CallVoiceThread(method) {
  var elements;
  if (navigator.appName.indexOf("Microsoft") != -1)
    elements = window['voicethread'];
  else
    elements = document['voicethread'];
  if (! elements.length > 0) elements = [ elements ];
  for (var i = 0; i < elements.length; i++) {
    if (elements[i][method] != undefined) {
      elements[i][method]();
    }
  }
}