
try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

function PageManager() { }
PageManager.prototype = {
	setLoginMessage: function(message,el) {	
		jq(el).find('p.login_error').each(function() {
			jq(this).attr("innerHTML",message);
			jq(this).addClass("show");
		});
	},
	
	showLoginWindow: function(message, el) {
		var loginWin = jq('#INPAGELOGIN').get(0);
		if(loginWin) {
			jq(loginWin).removeClass("loading");
			message = message || ""; 
			var atEl = el || IFILM.lastNodeClicked;
			IFILM.lastNodeClicked = atEl;
			atEl = atEl || jq('#USER').get(0);
			if(atEl) {
				try { 
					safelog("login panel at: " + atEl, "info", "PageManager.showLoginWindow");
					xy = {};
					jq(atEl).offset({scroll: false},xy);
					xy.left = (xy.left-140)+(jq(atEl).outerWidth()/2);
					xy.top = xy.top+jq(atEl).outerHeight();
				} catch(e) {
					safelog(e, "ERROR", "showLoginWindow");
				}
			}
			jq("#LOGIN_MESSAGE").html(message);
			jq(loginWin).css({top: xy.top, left: xy.left});
			jq(loginWin).fadeIn("normal");
			jq('#INPAGE_LOGIN').get(0).focus();
			IFILM.focusSet = true;
		}
		else { alert("Cannot find login window"); }
	  },
	removeLoginWindow: function(autoClosed) {
		var clearRequest = true;
		if(!!autoClosed) {
			clearRequest = false;
		}
		var loginWin = jq('#INPAGELOGIN').get(0);
		jq(loginWin).fadeOut("normal");
		if(clearRequest) {
			this.incompleteAjaxRequest = null;
		}
	},
	displayPersonalization: function(xmlobj) {
		var user = xmlobj.getElementsByTagName("user")[0];
		if(user) {
			try {
			var userid = getTag(user, "id");
			var username = getTag(user, "login");
			var pEls = {
				USER: jq('#USER').get(0),
				LOGOUT: jq('#LOGOUT').get(0),
				MYIFILM: jq('#loginform').get(0)
			}
			jq("#USER,#LOGOUT,#loginform").empty();
			
			var logoutNa = new NodeAssembly(pEls.LOGOUT);
			logoutNa.createEl("a", { href: "/control/logout" }, "Log-out");
			var userNa = new NodeAssembly(pEls.USER);
			userNa.createEl("a", { href:"/myifilm", id: "USER_ID"}, StringUtils.truncate(username,7) + "'s page");

			var myIfilmNa = new NodeAssembly(pEls.MYIFILM);
			var ul = myIfilmNa.createElWithAssembly("ul", { id: "MYSPIKE_FEATURES" });
			var li  = ul.createElWithAssembly("li", { "class": "myifilmfeatures" });
			li.createEl("a", {href: "/upload"}, "Upload a Video");
			li = ul.createElWithAssembly("li", { "class":"myifilmfeatures"});
			li.createEl("a", {href: "/myifilm?sublisting=favorites"}, "My Favorites");

			ul.createEl("li", { "class": "myifilmfeatures sharing"}, "Share Your SPIKE Favorites");

			li = ul.createElWithAssembly("li");
			li.createEl("label", {"for": "share_favorites"}, "Embed");
			li.createEl("input", {type: "text", name:"share_favorites", id: "share_favorites", onclick: "this.select()", value: '<embed width="448" height="365" src="http://www.spike.com/efp" quality="high" bgcolor="000000" name="efp" align="middle" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="playlisttype=favorites&playlistid='+username+'"></embed>'});

			li = ul.createElWithAssembly("li", {"class": "usernav"});
			li.createEl("a", {href: "/myifilm"}, username+"'s page");
			li.createTextEl(" | ");
			li.createEl("a", {href: "/control/logout"}, "Log-out");
			logoutNa.insertIn();
			userNa.insertIn();
			myIfilmNa.insertIn();
			
			if( jq(pEls.LOGOUT).is('.triggered') ) {
				TaskbarManager.toggleState(pEls.LOGOUT,'SIGNIN');
			}
			
			jq('#MAINCONTENT a.tool-send').each(function() {
				jq(this).removeClass('not-logged-in');
			});
		} catch(e) { safelog("error writing personalization: " + e,"error","PageManager.displayPersonalization"); }

		}
	},
	triggers: {},
	dynForms: {},
	dynMenus: {},
	incompleteAjaxRequest: null
}

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;
				}
				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);
		
		return IFILM.user.authenticated;
	} catch(e) {
		safelog(e,"error", "checkAuthenticationDWR");
		return false;
	}
}
function checkAuthenticationVoteDWR(return_vote_object) {
	try {
		IFILM.user.authenticated = (return_vote_object != null);
		
		return IFILM.user.authenticated;
	} catch(e) {
		safelog(e,"error", "checkAuthenticationVoteDWR");
		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) {
			UserManager.onAuthenticate(o);
			IFILM.loadingManager.removeLoading();
		}
		else { alert("document isn't xml"); }
	},
	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);
		}
	},
	
	onAuthSpecial: null,

	onAuthenticationFailure: function(o) {
		var submittedForm = this.submitted_form;
		IFILM.loadingManager.removeLoading();
		var funcName = (this.submitted_form.id == "INPAGELOGIN") ? "showLoginWindow" : "setLoginMessage";
		var thisNode = IFILM.lastNodeClicked || submittedForm;
		IFILM.pageManager[funcName](loginErrorMessage, thisNode);
	},

	checkAuthentication: checkAuthentication
}

var LoginAutoCheck = {
	connections: {},
	success: function(o) {
		var xml = o.responseXML;
		if(xml) {
			if(IFILM.user.checkAuthentication(xml)) {
				IFILM.pageManager.displayPersonalization(xml);
			}
		} else { this.failure(o); }
	},
	failure: function(o) { safelog("LoginAutoCheck: Error retrieving login status", "error", "loginAutoCheck"); },
	tryCheckLogin: function() {
		if(!jq('#USER_ID').get(0)) {
			var ipf = IFILM.cookieManager.get("ipfreely");
			var returnURLEl = jq('returnURL').get(0);
			if(returnURLEl && returnURLEl.value) {
				fetchFromAjax("/ajaxlogin?returnURL=" + encodeURIComponent(returnURLEl.value), LoginAutoCheck);
				return;
			}
			if(ipf) { fetchFromAjax("/ajaxlogin", LoginAutoCheck); }
		}
	},
	addTriggers: function() {
		jq("#MYIFILM").load(IFILM.loginAutoCheck.tryCheckLogin);
	}
}


function ageAlert() {
	var alert_box = jq('#no_registration').get();
	var height = jq(alert_box).css('height').replace(/px/,'');
	var width = jq(alert_box).css('height').replace(/px/,'');
	var window_height = getViewportHeight();
	var window_width = getViewportWidth();
	alert_top = Math.round((window_height/2) - (height/2));
	alert_left = Math.round((window_width/2) - (width/2));
	jq(alert_box).css('top', alert_top + 'px');
	jq(alert_box).css('left', alert_left + 'px');
	jq(alert_box).css('display', 'block');
}

function validEmbed() {}

validEmbed.prototype = {
	connections: {},
	success: function(o) {
		var xml = o.responseXML;
		var responseError = xml.getElementsByTagName("error")[0];
		var statusCode = getTag(responseError, "code");
		return (statusCode == 0);
	}
}

embedValidation = new validEmbed();

var ValidationManager = {
	allowPPT: false,
	forms: {},
	counters: {},
	reporters: {},
	isValidEmbed: null,
	currentEl: null,
	validators: { 
		required: function(el) { 
			if(el.type == "checkbox") {
				return el.checked;
			}
			if(el.value) { return true; }
			else { 
				if(el.type.indexOf("select") >= 0) {
					return ValidationManager.validators.selected(el);
				}
			}
			return false;
		},
		
		selected: function(el) {
			if(el.type.indexOf("select") >= 0) {
				return Boolean(el.selectedIndex);
			}
		},
		age: function(el) {
         if(el.value == 'Under' || IFILM.cookieManager.getSessionCookie("underAge")!=null) {
                IFILM.cookieManager.setSessionCookie("underAge", "true");
            ageAlert();
            Validationmanager.removeFieldError(ValidationManager.currentEl.label);
            return false;
         } else {
            return true;
         }
      },
		validembed: function(el) {
			var quick_add = jq('#quick_add').get(0);
			var file = jq('#file').get(0);
			
			if(!quick_add.value.match(/Embed codes supported/) && file.value == '') {
				fetchFromAjax('/validateThirdPartyEmbedCode?embedCodeOriginal=' + quick_add.value,embedValidation,null, true);
				
				return ValidationManager.isValidEmbed;
				
			} else { return true; }
		},
		videoincluded: function(el) {
			var quick_add = jq('#quick_add').get(0);
			var file = jq('#file').get(0);
			
			if(!quick_add) { return true; }
			
			if(quick_add.value.match(/Embed Codes Supported/) && file.value=='') {
				return false;
			} else { return true; }
		},
		genre: function(el) {
			var genre = jq('#genre_area').get(0) || jq('#genres').get(0);
			var platform = jq('#platform_area').get(0) || jq('platforms').get(0);
			var channel = jq('#video_channel').val();
			var genre_checked = false;
			var platform_checked = false;
			var total_genres = 0;
			var total_platform = 0;
			
			if(genre) {
				var genre_inputs = genre.getElementsByTagName('input');
				if(genre_inputs) {
					for(i = 0; i < genre_inputs.length; i++) {
						if(genre_inputs[i].checked) {
							genre_checked = true;
							total_genres = total_genres+1;
						}
					}
				}
			} else {
				return false;
			}
			
			if(platform) {
				var platform_inputs = platform.getElementsByTagName('input');
				if(platform_inputs) {
					for(i = 0; i < platform_inputs.length; i++) {
						if(platform_inputs[i].checked) {
							platform_checked = true;
							total_platform = total_platform+1;
						}
					}
				} else if(channel == 'videogames') {
					return false;
				}
			}
			if((channel == 'videogames' && !platform_checked) || !genre_checked) {
				return false;
			} else if ( !IFILM.user.isAdmin && (total_genres > 3 || total_platform > 3)) {
				return false;
			} else {
				return true;
			}
		},
		email: function(el) {
			var val = this.getElVal(el);
			if(val) { 
				var emailre = /^[\w''.-]+@[a-zA-Z][\w.-]+\.[a-zA-Z]{2,7}$/;
				return emailre.test(val);
			}
			else { return true; }
		},
		
		url: function(el) {
			var val = this.getElVal(el);
			if(val && val != '') {
				var urlre = /^https?:\/\/[\w.-]+\.[a-zA-Z]{2,7}(\/[\S]*)?$/i;
				return urlre.test(val)
			} else { return true; }
		},
		
		urlprefix: function(el) {
			var val = this.getElVal(el);
			var re = /^http:\/\/(.*)/;
			if(val.length && !re.test(val)) {
				el.value = 'http://' + val;
			}
			
			return true;
		},
		date: function(el) {
			
		},
		
		numeric: function(el, lowerBound, upperBound) {
			var val = this.getElVal(el);
			var numVal = parseFloat(StringUtils.trim(val));
			var isNumeric = false;
			if(numVal || val == "0") {
				isNumeric = true;
				if(lowerBound != undefined && numVal < lowerBound) {
					isNumeric = false;
				}
				if(upperBound != undefined && numVal > upperBound) {
					isNumeric = false;
				}
			}
			return isNumeric;
		},
		
		length: function(el, length) {
			var val = this.getElVal(el, true);
			safelog("Testing length " + parseInt(length) + " against: " + val, "vaildation", "ValidationMananger.validator.length");
			return val.length <= parseInt(length);
		},
		
		bounds: function(el, bounds) {
			var val = this.getElVal(el, true);
			var boundsAr = bounds.split("~");
			safelog("Bounds Checking: " + bounds + " = " + boundsAr, "validation", "ValidationMananger.validator.bounds");
			var lowerBound = parseInt(boundsAr[0]);
			var upperBound = parseInt(boundsAr[1]);
			return (val.length <= upperBound && val.length >= lowerBound);
			
		},
		
		matches: function(el, el1) {
			var val1 = this.getElVal(el, true);
			var val2 = this.getElVal(jq("#" + el1).get(0), true);
			return val1 == val2;
		},
		
		charfilter: function(el) {
			var val = this.getElVal(el);
			var charfilterRe = /[\w][\w&-\. ]+/g;
			var tags = val.match(charfilterRe);
			el.value = (tags) ? tags.join(", ") : "";
			return true;
			
		},
		
		checked: function(el, bounds) {
			safelog("raw bounds: " + bounds, "validation","ValidationManager.validator.checked");
			var elAr = el;
			var boundsAr = (bounds) ? bounds.split("~") : [];
			var iMin = parseInt(boundsAr[0]) || 0;
			var iMax = parseInt(boundsAr[1]) || 1000;
			var checkCount = 0;
			var elLim = elAr.length;
			for(var x=0; x<elLim; x++) {
				if(elAr[x].checked) { ++checkCount; }
			}
			safelog(elAr[0].name + " should have between " + iMin+  " and " + iMax + " checked", "validation", "ValidationManager.validator.checked"); 
			return (checkCount >= iMin && checkCount <= iMax);
			
		},
		
		custom: function(el, customFunc) {
			return customFunc(el);
		},
		videoformat: function(el) {
			var arValidFormats = new Array("xvid", "dat", "gvi", "avi","wmv","asf","mp4","mpg","mpeg","mov","qt","3gp","flv","dv");
			if(ValidationManager.allowPPT) {
				arValidFormats.push("pptx","ppt");
			}
			var val = this.getElVal(el);
			var formatRe = new RegExp("\\.(" + arValidFormats.join("|") + ")$", "i");
			var quick_add = jq('#quick_add').get(0);
			if(!quick_add || quick_add.value.match(/Embed Codes Supported/i)) {
				return formatRe.test(val);
			} else {
				return true;
			}
		},
		
		photoformat: function(el) {
			var arValidFormats = ["jpg", "jpeg"];
			var val = this.getElVal(el);
			var formatRe = new RegExp("\\.(" + arValidFormats.join("|") + ")$", "i");
			return val != ''?formatRe.test(val):true;
		},
		
		
		getElVal: function(el, notrim) {
			return ValidationManager.getElVal(el, notrim); 
		}
		
	},
	
	validatorErrorMessages: {
		email: "Email is misformatted (ex: yourname@email.com)",
		url: "Website address is misformatted (ex: http://www.spike.com)",
		numeric: "{fieldname} must be numeric",
		length: "{fieldname} must be a maximum of {param1} characters",
		bounds: "{fieldname} must be between {param1} and {param2} characters",
		matches: "Password fields don't match",
		videoformat: "Video is not an accepted file format",
		photoformat: "Image is not an accepted file format",
		videoincluded: "A video file or third party embed code must be included"
	},
	
	getElVal: function(el, notrim) {
		var dotrim = !notrim; 
		var val = (typeof el == "string") ? el : el.value;
		if(dotrim) { val = StringUtils.trim(val); }
		return val;
	},
	autoValidate: function(form) { 
		try { jq('#no_registration').css('display', 'none'); } catch(e) { }
		var tFields = this.getTestableFields(form);
		safelog(tFields, "info", "ValidationManager.autoValidate");
		var formValidated = true;
		var validationErrs = [];
		for(var elRef in tFields) { 
			var elObj = tFields[elRef];
			var fieldValidated = true; 
			if(!this.validate_field(elObj)) {
				this.currentEl = elObj;
				formValidated = false;
				validationErrs.push(elObj);
				jq(elObj.label).addClass("error");
				if(elObj.el.className)
					jq(elObj.el).addClass("error");
					
				if(elObj.el.id == 'tag_group_genre_tags_1')
					jq('#platform_label label').addClass('error');
			}
			else {
				safelog(elRef + " validated against: " + elObj.tests, "info", "ValidationManager.autoValidate");
				if(elObj.el.className)
					jq(elObj.el).removeClass("error");
				
				if(elObj.el.id == 'tag_group_genre_tags_1')
					jq('#platform_label label').removeClass('error');
					
				jq(elObj.label).removeClass("error");
			}
		}
		

		if(!formValidated) {
			this.alertValidationErrors(form, validationErrs);
		} else { 
			this.removeValidationErrors(form, validationErrs); 
			var quick_add = jq('#quick_add').get(0);
			var file = jq('#file').get(0);
			
			if(quick_add && file) {
				if(file.value != '' && quick_add.value != '') {
					quick_add.value = '';
				}
			}
		}
		return formValidated;
	},
	
	alertValidationErrors: function(form, validationErrs) {
		jq(form).addClass("error");
		for(var x=0; x<validationErrs.length; x++) {
			var curEl = validationErrs[x];
			for(var i=0; i<curEl.failures.length; i++) {
				var curFailure = curEl.failures[i];
				if(this.validatorErrorMessages[curFailure.test]) {
					var fieldname = getNodeText(curEl.label).replace(/:/, "");
					var msg = this.validatorErrorMessages[curFailure.test].replace(/{fieldname}/, '"'+fieldname+'"');
					if(curFailure.testParams) {
						if(curFailure.testParams.length) {
							msg = msg.replace(/{param1}/, curFailure.testParams[0]);
						}
							
						if(curFailure.testParams.length >= 2) {
							msg = msg.replace(/{param2}/, curFailure.testParams[1]);
						}
	
						if(curFailure.testParams.length >= 3) {
							msg = msg.replace(/{param3}/, curFailure.testParams[2]);
						}
					}
					safelog(msg, "validation", "alertValidationErrors");
				}
			}
		}
	},
	removeValidationErrors: function(form, validationErrs) {
		jq(form).removeClass("error");
	},
	removeFieldError: function(el) {
		jq(el).removeClass("error");
	},
	getTestableFields: function(form) { 
		var tFields = {};
		var labels = form.getElementsByTagName("label");
		var labelLim = labels.length;
		var vClassTestRe = /(vv_|required)/;
		var vClassRe = /^(vv_[\w-~]+|required)$/;
		for(var x=0; x<labelLim; x++) {
			var curLabel = labels[x];
			if(curLabel.htmlFor) { 
				var curEl    = jq('#' + curLabel.htmlFor).get(0);
			}
			else { 
				if(curLabel.getElementsByTagName("input").length) {
					var curEl = curLabel.getElementsByTagName("input")[0];
				}
				else if(curLabel.getElementsByTagName("select").length) {
					var curEl = curLabel.getElementsByTagName("select")[0];
				}
				else if(curLabel.getElementsByTagName("textarea").length) {
					var curEl = curLabel.getElementsByTagName("textarea")[0];
				}
			}
			if(curEl) { 
				safelog("Checking field " + curLabel.htmlFor + " (" + curLabel.className + ")", "validation", "ValidationMananger.getTestableFields");
				if(vClassTestRe.test(curLabel.className)) {
					safelog("ClassName may be testable", "validation", "ValidationMananger.getTestableFields");
					var classes = curLabel.className.split(/[^\w-~]+/);
					for(var y=0; y<classes.length; y++) {
						var curClass = classes[y];
						safelog(" - checking className: " + curClass, "validation", "ValidationManager.getTestableFields");
						if(vClassRe.test(curClass)) {
							tFields[curEl.id] = tFields[curEl.id] || {el: curEl, label: curLabel, tests: [], failures:[]};
							tFields[curEl.id].tests.push(curClass);
						}
					}
				}
			}
			else { safelog("Cannot find element for " + curLabel.htmlFor, "error", "ValidationManager.getTestableFields"); }
		}
		
		var groupLabels = jq(form).find("span.label").get();
		var gLabelForRe = /\bfor-([\w~-]+)\b/;
		for(var x=0; x<groupLabels.length; x++) {
			var gLabel = groupLabels[x];
			if(gLabelForRe.test(gLabel.className)) {
				var elNameMatch = gLabelForRe.exec(gLabel.className);
				if(elNameMatch && elNameMatch.length >= 2) {
					var elName = elNameMatch[1];
					var elAr = form.elements[elName];
					if(elAr && vClassTestRe.test(gLabel.className)) {
						var classes = gLabel.className.split(/[^\w-~]+/);
						for(var y=0; y<classes.length; y++) {
							var curClass = classes[y];
							safelog("Checking span className:" + curClass, "validation", "ValidationManager.getTestableFields");
							if(vClassRe.test(curClass)) {
								tFields[elName] = tFields[elName] || { el: elAr, label: gLabel, tests: [], failures: []};
								tFields[elName].tests.push(curClass);
							}
						}
					}
				}
			}
		}
		return tFields;
	},
	validate_field: function(elObj) {
		var field = elObj.el;
		var tests = elObj.tests; 
		var fieldErrs = []
		var validField = true;
		for(var x=0; x<tests.length; x++) {
			var curTest = tests[x];
			curTest = curTest.replace("vv_", "");
			testParams = curTest.split("-");
			var test = testParams[0];
			safelog("Test field " + field.id + " with test: " + test, "validation", "ValidationManager.validate_field");
			if(this.validators[test]) {
				if(!this.validators[test](field, testParams[1])) {
					var errParams = (testParams[1]) ? testParams[1].split("~") : [];
					fieldErrs.push({"test": test, "testParams": errParams} );
					validField = false;
				}
			}	
		}	
		
		elObj.failures = fieldErrs;	
		return validField;
	},
	
	triggerFunc: function(e) {
		try {
			if(!ValidationManager.autoValidate(this)) {
				if(e) { preventDefault(e); }
				return false;
			}
		} catch(err) { preventDefault(e); safelog(err, "error", "ValidationManager.triggerFunc"); }
	},
	
	autocount: function(e) {
		if(!ValidationManager.reporters[this.id]) {
			ValidationManager.reporters[this.id] = jq('#' + this.id + "_counter").get(0);
		}
		var reporter = ValidationManager.reporters[this.id];
		if(reporter) {
			var myLen = this.value.length;
			var maxLen = ValidationManager.counters[this.id];
			if(myLen) {
				if(maxLen >= myLen) {
					reporter.innerHTML = (maxLen - myLen) + " characters remaining";
					if(reporter.className.indexOf("error") >= 0) { jq(reporter).removeClass("error") }
				} else { 
					reporter.innerHTML = "Exceeded limit of " + maxLen + " characters"; 
					this.value = this.value.substring(0, maxLen);
					if(reporter.className.indexOf("error") == -1) { jq(reporter).addClass("error") }
				}
			} else { reporter.innerHTML = ""; jq(reporter).removeClass("error"); }
		}		
	},
	
	addTriggers: function() {	
		jq('form.autovalidate').each(function(i) {
			jq(this).submit(ValidationManager.triggerFunc);
			var curForm = this;
			ValidationManager.forms[this.id] = curForm;
			
			safelog("autovalidation added to " + curForm.id, "validation", "ValidationManger.addTriggers");
			jq(curForm).find('label.autocount').each(function() {
				var maxVal = parseInt(this.className.replace(/^.*vv_length-([0-9]+).*$/, "$1"));
				safelog(this.htmlFor + " max length: " + maxVal, "validation", "ValidationManager.addTriggers");
				
				ValidationManager.counters[this.htmlFor] = maxVal;
				jq('#' + jq(this).attr('for')).keyup(ValidationManager.autocount);
			});
		});
		
	}
}


var IFILM = {
	suppressLogging: (QueryManager.getAsBoolean("jsdebug")) ? false : true,
	user: UserManager,
	pageManager: new PageManager(),
	cookieManager: new CookieManager(),
	loginAutoCheck: LoginAutoCheck,
	queryManager: QueryManager,
	focusSet: false,
	lastNodeClicked: null,
	constants: {
		OPENSCRIPT: "<script type=\"text/javascript\" ",
		CLOSESCRIPT: "</script>",
		DASHES: "--",
		AMP: "&",
		Q: '"',
		SQ: "'"
	}
};

IFILM.loginAutoCheck.addTriggers();

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) {
		this.removeLoading();
				
		if(el.id == "INPAGELOGIN")
			this.curLoadingEl = el.getElementsByTagName('fieldset')[0];	
		else
			this.curLoadingEl = el;
		
		jq(this.curLoadingEl).addClass(this.loadClassName);
		
		if(this.curLoadingEl.tagName == 'UL') {
			jq(el).empty();
			var na = new NodeAssembly(el);
			var li = na.createElWithAssembly('li', {'class':'loadingEl'});
			li.createEl('img', {'src':'http://dyn.ifilm.com/website/loadingAnimation.gif'});
			na.insertIn();
		}
	},
	removeLoading: function(el) {
		var loadingEl = el || this.curLoadingEl;
		if(loadingEl) {
			jq(this.curLoadingEl).removeClass(this.loadClassName);
		}
	}
}


/* FAVORITES */
function favoriteTrigger(ev) {
	try {
		if(ev) { preventDefault(ev) }
		FavoriteManager.triggered[this.id] = this;
		var href = this.href;
		IFILM.loadingManager.setLoading(this);
		blurel(this);
		whatWasClicked(ev);
		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;
	}
}

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() { alert("An error occurred while modifying your favorites"); },
	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) ? "Remove from Playlist" : "Save to Playlist";
			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
	}
}

/* MENUS */
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) }
	IFILM.pageManager.removeLoginWindow();
	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' && me.className.indexOf("not-logged-in") >= 0) {
			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;
			var tWidth = Math.min(oWidth, 420);
			jq(form).css("display", "block");

			if(CUSTOMTOOLFUNCS[formtype]) { CUSTOMTOOLFUNCS[formtype](formparam, form, formparamtype) }
			jq(form).css("width", tWidth + "px");
			var rightBound = (jq(me).offset().left + jq(me).outerWidth()) + 5;
			var leftBound = jq(tContainer).offset().left;
			var formX = Math.max(rightBound - tWidth, leftBound);
			jq(form).css('left', formX + 'px');
			
			var offset = jq(me).offset();
			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" }
		}
	}
}

var CUSTOMTOOLFUNCS = {
	SEND: function(id, form, typeid) {
		jq(form).find("p.tempstatus").html("").removeClass("show");
	},
	SHARE: function(id, form) {
		var re = /(flvbaseclip=)[0-9]+/g;
		var ta = form[0].getElementsByTagName("textarea")[0];
		ta.value = ta.value.replace(re, "$1" + id);
		ta.select();
		window.setTimeout(CUSTOMTOOLFUNCS.SHAREFOCUS, 50);
	},
	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");
}

function openRssMenu(e, obj) {
	if(e) { preventDefault(e) };
	if(this.className.indexOf("opened") >=0) {
		jq("#RSSREADERS").slideUp();
		jq(this).removeClass("opened");
	}
	else {
		jq("#RSSREADERS").slideDown();
		jq(this).addClass("opened");
	}
}


pageLoadFuncs.push(function() {
	try {
		window.readers = window.readers || {};
		
		jq("#RSSMODULE a.subscribelink").click(openRssMenu);
	} catch(e) { safelog("Error adding rssreader litener", "Error", "pageLoadFuncs"); }	
});
pageLoadFuncs.push(function() {
	MenuManager.init();
	jq("#SEASONMENU,#GENREMENU,#CHANNELMENU,#SENDFORM,#DOWNLOADSFORM").prependTo(".container");
	
	jq("#CHANNELNAV a.menutrigger").each(function() {
		MenuManager.addMenuWithTrigger(this, "CHANNELMENU");
	});
	
	jq("#GENRENAV a.menutrigger").each(function() {
		MenuManager.addMenuWithTrigger(this, "GENREMENU");
	});
	
	jq("#combo_header a.menutrigger").each(function() {
		MenuManager.addMenuWithTrigger(this,"SEASONMENU");
	});
	
	jq("#featured_playlists a.menutrigger").each(function() {
		MenuManager.addMenuFromEl(this);
	});
});
pageLoadFuncs.push(function() {
	

	jq("#MAINCONTENT a.tool-send,#MAINCONTENT a.tool-share,#MAINCONTENT a.tool-downloads").click(openMenu);
	jq("#MAINCONTENT a.tool-favorites").click(favoriteTrigger);
	var loginTriggers    = [];
	if(jq('#LOGINLINK').get(0)) { loginTriggers.push(jq('#LOGINLINK').get(0)); }
	if(jq('#COMMENTLOGINBOTTOM').get(0)) { loginTriggers.push(jq('#COMMENTLOGINBOTTOM').get(0)); }
	var registerLink = jq('#REGISTERLINK').get(0);
	var curUrl = document.location.href;
	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() {
	EmailManager.addTriggers();
});

jq(document).ready(function() {
	pageLoadHandler();
});

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

function whatWasClicked(e) {
	IFILM.lastNodeClicked = getTarget(e, true);
}

IFILM.AdObj = function(targ, scriptSrc, confObj, disableRefresh) {
	this.targ = targ;
	this.scriptSrc = scriptSrc;
	this.disableRefresh = disableRefresh || 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)
	}
	IFILM.adManager.addAd(this);
	safelog("Ad Object created with scriptSrc:" + scriptSrc, "info", "IFILM.AdObj");	
}

IFILM.AdObj.prototype = {
	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);
				var iframe = na.createElWithReturn("iframe", this.config)
				na.insertIn();
			} else {
				var iframe = displayAt;
			}
			
			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;
					safelog("Ad height: " + docSize, "info", "IFILM.AdObj.adjustHeight");
					var rawSize = targetFrame.height;
					
					if(Math.abs(docSize - rawSize) > 20 && docSize < 700)
						targetFrame.height = docSize;
				}
			}
		} 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() {
		safelog('refreshing ad ' + this.targ);
		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,
	revealAds: function() {
		var adLim = IFILM.adManager.ads.length;
		for(i = 0; i < adLim; i++)
			jq('#' + IFILM.adManager.ads[i].targ).css('visibility', 'visible');

		jq('iframe').css('visibility', 'visible');
	},
	obscureAds: function() {
		var adLim = IFILM.adManager.ads.length;
		jq('iframe').css('visibility', 'hidden');
		for(i = 0; i < adLim; i++)
			jq('#' + IFILM.adManager.ads[i].targ).css('visibility', 'hidden');
	},
	displayAds: function() {
		var adlim = this.ads.length;
		for(var x=0; x<adlim; x++)  {
			try {
				safelog("Displaying ad " + (x+1) + " of " + adlim, "info", "IFILM.adManager.displayAds");
				if(this.ads[x]) { this.ads[x].display(); }
			} catch(e) { safelog(e, "ERROR", "IFILM.adManager.displayAds"); }
			//this.ads[x] = null;
		}
	},
	refreshAds: function() {
		jq('#HEADER').removeClass('ad-fullheader');
		jq("#IFILM iframe").remove();
		var adlim = this.ads.length;
		for(var x=0; x<adlim; x++) {
			if(this.ads[x] && !this.ads[x].disableRefresh) { 
				safelog("reloading ad " + (x+1) + " of " + adlim, "info", "IFILM.adManager");
				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) {
		safelog("Hiding: " + hideEl, "info", "adManager.hideAds");
		
		if(hideEl) { 
			hideEl.style.display = "none";
			if(hideEl.parentNode) {
				hideEl.parentNode.style.display="none";
			}
		}
	},
	makeFullheader: function() {
		try {
			var HEADER = document.getElementById("HEADER");
			var HEADERAD = document.getElementById("HEADERAD");
			jq(HEADER).addClass("ad-fullheader");
			
			if(document.all) {
				var na = new NodeAssembly(jq('#IFILM').get(0));
				var conf = { 
					width: "246", 
					height: "92",
					FRAMEBORDER: "0",
					border: "0",
					marginwidth: "0",
					marginheight: "0",
					hspace: "0",
					vspace: "0",
					scrolling: "no",
					style: "border: none",
					src: '/ui/jsp/global/shim.jsp',
					id: 'iframeshim' 
				}
				na.createEl('iframe', conf,'');
				na.insertIn();
			}
		} catch (e) { }
	}
}

pageLoadFuncs.push(function() {
	window.setTimeout(IFILM.adManager.displayAdsGeneric, 1000);
})


/* 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 = "";

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;
}

var MiniPlayerManager = {
	getRegion: function() {
		var footerEl = jq('#footer').get(0);
		var readerTop = jq(footerEl).offset().top;
		var cn = footerEl.childNodes;
		var targetBottom = readerTop;
		for(var x=0; x<cn.length; x++) {
			if(cn[x].tagName) {
				var newBottom = (jq(cn[x]).offset() + jq(cn[x]).outerHeight());
				targetBottom = (newBottom > targetBottom) ? newBottom : targetBottom;						
			}
		}
		var targetHeight = Math.abs(targetBottom - readerTop);
		footer_xy = jq(footerEl).offset();
		return footer_xy.top + targetHeight;
	},
	positionFooter: function() {
		var footer_position = MiniPlayerManager.getRegion();
		var cur_width = document.documentElement.clientWidth;
		var cur_height = document.documentElement.clientHeight;
		
		playlist = jq('#playList').get(0);
		var playlist_height = jq(playlist).css('height').replace(/px/,'');
		playlist_height = parseInt(playlist_height);
		var diff = cur_height - footer_position;
		playlistTargetHeight = (footer_position <= cur_height)?(playlist_height + diff):Math.max(playlist_height + diff,140);
		jq(playlist).animate({height: playlistTargetHeight}, "normal");
	},
	triggerFunc: function(e) {
		if(e)
			preventDefault(e);
		var options = this.target.split("_");
		window.open(this.href,options[0] + '_' + options[1].replace('-',''),'width='+options[2]+',height='+options[3]+',location=0,status=0,scrollbars=0,resizable=1');
	},
	addTriggers: function() {
		jq("#PRIMARY a.miniplayer,#NAV a.miniplayer").click(this.triggerFunc);
	},
	init: function() {
		this.addTriggers();
	}
}

pageLoadFuncs.push(function() {
	MiniPlayerManager.init();
});

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;
}

function gotoGallerySWF(e) {
	if(e) { preventDefault(e); }
	if(jq('#SpikeTV_Framework').get(0)) {
		gotoGallery(this.id.replace(/link_/, ''));
		safelog('Calling flash refresh for the babelizer link ' + this.id, "INFO", "gotoGallerySWF");
	} else {
		safelog('Calling document.location for babelizer link ' + this.id, "INFO", "gotoGallerySWF");
		document.location = this.href;	
	}
}

pageLoadFuncs.push(function() { 
	jq("#babealizer_links a.gallery_link").click(gotoGallerySWF);
});

// NOTE: This is only in place to support flash.
// Do not remove without first speaking with Sr. Flash Developer.
function getLocation () {
	return document.location.href;
}

function TickerObj(el) {
	this.ticker = jq('#' + el).get(0);
	if(this.ticker) {
		this.elements = this.ticker.getElementsByTagName('li');
		var offset = jq(this.elements[this.curElementIndex]).offset();
		this.leftPosition = offset.left;
		this.topPosition = jq(this.ticker).offset().top;
		safelog(jq(this.ticker).offset().top, 'INFO', 'TickerObj.init');
		this.addTriggers();
		this.scrollNext();
		this.inited = true;
	}
}

TickerObj.prototype = {
	ticker: null,
	elements: null,
	curElement: null,
	curElementIndex: 0,
	leftPosition: null,
	topPosition: null,
	interval: null,
	inited: false,
	scrollPrev: function(e) {
		if(e) { preventDefault(e); }
		if(this.curElement) {
			//move current element out of the way
			safelog(this.topPosition, 'INFO', 'scrollPrev');
			jq(this.curElement).animate({top: -100}, "normal");
			jq(this.curElement).fadeOut("normal");
			
			this.curElementIndex = (this.curElementIndex-1)>=0?this.curElementIndex-1:this.elements.length-1;
		}

		this.curElement = this.elements[this.curElementIndex];
		this.curElement.style.top = '40px';
		
		jq(this.curElement).animate({top: 2}, "normal");
		jq(this.curElement).fadeIn("normal");
		this_ticker = this;
		clearTimeout(this_ticker.interval);
		this.interval = setTimeout('this_ticker.scrollNext()',10000);
	},
	scrollNext: function(e) {
		safelog('Scrolling to next ticker item ' + this.ticker.id, 'INFO', 'TickerObj');
		if(e) { preventDefault(e); }
		if(this.curElement) {
			//move current element out of the way
			jq(this.curElement).animate({top: 100}, "normal");
			jq(this.curElement).fadeOut("normal");
			
			this.curElementIndex = this.curElementIndex+1<this.elements.length?this.curElementIndex+1:0;
		}

		this.curElement = this.elements[this.curElementIndex];
		this.curElement.style.top = '-140px';
		
		jq(this.curElement).animate({top: 2}, "normal");
		jq(this.curElement).fadeIn("normal");
		if(this.inited) {
			this_ticker = this;
			clearTimeout(this_ticker.interval);
			this.interval = setTimeout('this_ticker.scrollNext()',10000);
		}
	},
	addTriggers: function() {
		jq("#" + this.ticker.id + '-up').click(this.scrollPrev.bind(this));
		jq("#" + this.ticker.id + '-down').click(this.scrollNext.bind(this));
	}
}

function textAd(msg) {
	if(StringUtils.trim(jq("#globaltxtad").html()) != '')
		jq("#globaltxtad").fadeOut("normal", function() { jq("#globaltxtad").html(msg).fadeIn("normal"); });
	else
		jq("#globaltxtad").html(msg).fadeIn("normal");
	jq("#HEADER").css("height", "118px");
}

function setMaturityCookie(name,value) {
	IFILM.cookieManager.setSessionCookie(name,value);             
}

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 {
			AnimateManager.reserveTitle = AnimateManager.curThumb.title;
			AnimateManager.curThumb.title = 'No Preview Available.';
		}
	},
	stopAnimation: function(e) {
		clearTimeout(AnimateManager.interval);
		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', 'block');
	},
	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('display', 'none');
		jq('#FEATURELIST a.tn_frame').hover(AnimateManager.animateThumb, AnimateManager.stopAnimation);
	}
}


function adjustThumbnails() {
	//jq('#FEATURELIST a.tn_frame img').each(function() {
		var height = jq(this).height();
		var parent_height = jq(this).parent().height();
		if(height > parent_height) {
			var multiplier = -1;
			jq(this).css('margin-top', ((height-parent_height)/2)*multiplier +'px');
		} else if(height < parent_height) {
			jq(this).css('margin-top', ((parent_height-height)/2) +'px');
		}
	//});
}

pageLoadFuncs.push(function() {
	var z;
	AnimateManager.addTriggers();
	jq('#SIMILARLIST a.tn_frame img, #FEATURELIST a.tn_frame img').load(adjustThumbnails);
	//adjustThumbnails();
});
