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

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

}

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

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

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

/* GLOBAL AD STUFF FROM FRAME 0 */

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

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

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

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

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

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

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

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

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





// Relevant View Java Script - END!!!!!!
//This page needs to be configured for each site. Each of the following values must be changed
//to the site specific values.

//**Content Match ids
//Base url for content match. Each site has a different hostname (hostname + feedpath)
var g_baseOvertureCMUrl = "http://cm.spiketvifilm.overture.com /js_flat_1_0/"
//source paramater for content match. Each site has its own source code (source)
var g_overtureCMSource = "viacom_spikeifilm_ctxt"
//Config code for each site (config)
var g_overtureCMConfig = "2901577853"

//** Search IDs
//Base url for partner search. 
var g_baseOvertureSearchUrl = "http://xml.overture.com/d/search/p/viacom/js/v2/";
//partner paramater for search. 
var g_overtureSearchPartner = "viacom_spikeifilm_search";

//This is a mapping of urls to ctxtIds. IDs are to be provided by Yahoo
//pass this into the function getMappingValue to get the value based on the current url.
//order these with the most specific urls first.
var g_contextIdMap = new Object();
g_contextIdMap["/shared/white_pages"] = "music";
g_contextIdMap["/shared/"] = "notmusic";
g_contextIdMap["/music"] = "music";
g_contextIdMap["/news"] = "news";
g_contextIdMap["/movies"] = "movies";

//Another map for type used the same way as g_contextIdMap
var g_typeIdMap = new Object();
g_typeIdMap["/shared/white_pages"] = "music";
g_typeIdMap["/news"] = "news";

//Default links to use in case we don't get results back.
zSr_dummy = new Array("Reach 80% of active Internet users with Overture.","","","List your site with Overture","http://www.overture.com/","",
"See the latest Accord offers at the Honda Official Site.",
"",
"http://ypn-100.overture.com/d/sr/?xargs=SjGTYHM2WSfAwg8ep-u2ASFl94ZiTOXSU7PrBi34b0dkMRpxIz_DgoDqDHPG_NIidq9XtjihuvhsnU-qzNGWIEpI0WYkcoPdGWF6vHcW_pmyJkWX7VREKmh2o6lFQdzPF1NYiCCDFPBMzTW1E9ywARKkbBHDxtdkScwJOM-imi-fb8Z061AriZIDa1EDdkfqf3QyaFsV2ZtTR7fzb3-6K7zuu9vXH0AppemWRteQ9SJW7Z1IuIHVxAIrOsp7BDr91kty-i4Ghjhbnh_NMBWcNKIHMwuOzg_br8ZdyL97n9w8jcEZNvfaURyWMRn97xi0YtD5kOy-QPA",
"Honda Vehicles",
"www.honda.com",
"",
"Save up to 40% JVC, Pioneer, Clarion, Alpine, Kenwood.",
"",
"http://ypn-100.overture.com/d/sr/?xargs=k-vWdwvJp78awRZ3Qhx-bNIsqKMyFJwxG5e0pmbgOXJ8w7TZD_t_g3yvErHu8Xl4I3_x8ptDV3A0LIMF7OlPTj5IkMVeVfJ7YImiuZU1-p7rVyQOV4pyMgRkXrvbW_C6knIw1bUvr88gdVHsT-HA77YeNJVDGHkfjWgmNwyqxub9CYdDO8qHDr1b2pamYZbeIy8ZdhbSa1DvmkyROP-YJHS26-bDnYiyF5Aqyi-iI6d3UaXPeWNhzBfWVqBbIRd7wn767p7eqywIgT6oNriUfKJKA9YnOYxl9msgYv75FJF4Yrr5i8pEpPbf8orxrGg5OiPTaHCp4Qw",
"Car Audio/Multimedia SALE",
"carsaudio.co.uk",
"",
"Electronics, Games, Toys, Digital Cameras, and more.",
"",
"http://ypn-100.overture.com/d/sr/?xargs=cc9OZjd2BnLDSEYSO0xFQYOLbyfpbe27TqGUg90i-jKS-gcU8lXMkhuNGMm3DJcx2oriBHlOMItEsUbii_mZooTh1ploLYXV4BBkox4A4Qm4e-UnspwI6DfPw1Y_7s2sDBsD0wcAgFkwVB-VviXebuFDhuCZJseHhCWH6u2I3yH5D1X0OIGIQdhCQIYNL7WVQvzPz69wffyUTyqnItDPX1OFjCZ3Kqnwomn_TFmZeibU291SbvoyNP4mMKIn6VmD3D4rOoid-bTxDP63P19rs3ZAqnClMlJZXOimusbL77w3hK72W7aVtG2VBll-pXPpohzEDJ2nt8A",
"Hundreds of Products at Low Prices",
"www.advancedtechtoys.com",
"");

//zSr is the array that is populated by the javacsript call to Overture
var zSr;

//Below are some example funtions to draw the acutall link boxes
//Each site can use this same pattern to define new functions that can draw the links
//in various ways.

//A function for drawing a set of sponsored links
function showLinks1(linkData, startIndex, endIndex) {
  if (startIndex == undefined) {
	startIndex = 0;
  }
  var links = linkData.getItems();
  var outString = "<table border=1>";
  var arrLength = links.length;
  if (endIndex == undefined || endIndex == 0) {
    endIndex = arrLength;
  }
  else {
    if (endIndex > arrLength) {
	endIndex = arrLength;
    }
  }

  var emptyText = "<table border=1><tr><td><b>doh! not links to show</b></td></tr></table>";
  if (endIndex <= startIndex) {
     //If there are not links to show, then return an alternative text
     return emptyText;
  }

  var i = startIndex;
  while ( i <= endIndex) {
   var currItem = links[i];
   if (!(currItem == undefined)) {
     outString += "<tr><td><a href=\"" + currItem.getClickUrl() + "\">" + currItem.getTitle() + "</a><br>" + currItem.getDescription() + "<br><a href=\"http://" + currItem.getClickUrl() + "\">" + currItem.getSitehost() + "</a></td></tr>\n";
   }
   i++;
  } 
  outString += "</table>";
  return outString;
}

//A second function for drawing a set of sponsored links
function showLinks2(linkData, startIndex, endIndex) {
  if (startIndex == undefined) {
	startIndex = 0;
  }
  var links = linkData.getItems();
  var outString = "<table border=2 bgcolor=\"tan\">";
  var arrLength = links.length;
  if (endIndex == undefined || endIndex == 0) {
    endIndex = arrLength;
  }
  else {
    if (endIndex > arrLength) {
	endIndex = arrLength;
    }
  }

  var emptyText = "<table border=1><tr><td><b>doh! not links to show</b></td></tr></table>";
  if (endIndex <= startIndex) {
     //If there are not links to show, then return an alternative text
     return emptyText;
  }

  var i = startIndex;
  while ( i <= endIndex) {
   var currItem = links[i];
     if (!(currItem == undefined)) {
      outString += "<tr><td><a href=\"" + currItem.getClickUrl() + "\">" + currItem.getTitle() + "</a><br>" + currItem.getDescription() + "<br><a href=\"http://" + currItem.getClickUrl() + "\">" + currItem.getSitehost() + "</a></td></tr>\n";
   }
   i++;
  } 
  outString += "</table>";
  return outString;
}

//This is a general library for working with Overture Content Match links
//Version: 1.0 
//Last Modified: 6-14-2007
//Author: Michael Stenzler

//This is a Javascript object to encapsulate one row of overture data
var overtureItem = function(pdescription, punused, pclickUrl, ptitle, psitehost, pbidded) {
   var description = pdescription;
   var unused   = punused;
   var clickUrl = pclickUrl;
   var title    = ptitle;
   var sitehost = psitehost;
   var bidded   = pbidded;

   this.setDescription = function(ldescription) { description = ldescription; }
   this.setUnused = function(lunused) { unused = lunused; }
   this.setClickUrl = function(lclickUrl) { clickUrl = lclickUrl; }
   this.setTitle = function(ltitle) { title = ltitle; }
   this.setSitehost = function(lsitehost) { sitehost = lsitehost; }
   this.setBidded = function(lbidded) { bidded = lbidded; }

   this.getDescription = function() { return  description; }
   this.getUnused = function() { return unused; }
   this.getClickUrl = function() { return clickUrl; }
   this.getTitle = function() { return title; }
   this.getSitehost = function() { return sitehost; }
   this.getBidded = function() { return bidded; }

   this.printItem = function() {
     var printString = "<p>description = " + description + "<br>" +
                       "unused = " +  unused + "<br>" +
                       "clickUrl = " + clickUrl + "<br>" +
                       "title = " +    title + "<br>" +
                       "sitehost = " + sitehost + "<br>" +
                       "bidded = " +   bidded + "</p>";
    document.writeln(printString);
   }
}

var overtureLinkSpotItem = function(ptitle, pkeywords) {

   var title = ptitle;
   var keywords = pkeywords.split(", ");

   this.setTitle = function(ltitle) { title = ltitle; }
   this.setKeywords = function(lkweywords) { keywords = lkeywords; }
   this.setKeywordsFromString = function (lstring) { keywords = lstring.split(", "); }

   this.getTitle = function() { return title; }
   this.getKeywords = function() { return keywords; }
   this.getKeyword = function(i) { return keywords[i]; }

   this.printItem = function() {
     var printString = "<p>title = " + title + "<br>" +
                       "keywords = ";
     for(i=0; i<keywords.length; i++) {
       if(i>0) { printString += ", " }
       printString += keywords[i];
     }
    document.writeln(printString);
   }

}


//This is a Javascript object to encapsulate an array of Overture Items 
var overtureLinks = function() {
  var listItems = new Array();
  this.addItem = function(item) {
     var i = listItems.length;
     listItems[i] = item;
  }

  this.getItems = function() { return listItems; }
  this.getItem = function(i) { return listItems[i]; }
  this.length = function() { return listItems.length; }

  this.printItems = function() {
     var i = 0;
     while (i < listItems.length) {
        var currItem = listItems[i];
        currItem.printItem();
        i++;
     }
  }
  
}

//This is a Javascript object to hold configuration data for the creation of an
//Overture Search link
var overtureSearchConf = function() {
    var baseUrl = g_baseOvertureSearchUrl;
    var partner = g_overtureSearchPartner;
    var keywords;
    var type;
    var keywordCharEnc;
    var outputCharEnc;
    var urlFilters;
    var termFilters;
    var serveUrl;
    var maxCount;

    this.setBaseUrl = function(lbaseUrl) { baseUrl = lbaseUrl; }
    this.setPartner = function(lpartner) { partner = lpartner; }
    this.setKeywords = function(lkeywords) { keywords = lkeywords; }
    this.setType = function(ltype) { type = ltype; }
    this.setKeywordCharEnc = function(lkeywordCharEnc) { keywordCharEnc = lkeywordCharEnc; } 
    this.setOutputCharEnc = function(loutputCharEnc) { outputCharEnc = loutputCharEnc; } 
    this.setUrlFilters = function(lurlFilters) { urlFilters = lurlFilters; }
    this.setTermFilters = function(ltermFilters) { termFilters = ltermFilters; }
    this.setServeUrl = function(lserveUrl) { serveUrl = lserveUrl; }
    this.setMaxCount = function(lmaxCount) { maxCount = lmaxCount; }

    this.getBaseUrl = function() { return baseUrl; }
    this.getPartner = function() { return partner; }
    this.getKeywords = function() { return keywords; }
    this.getType = function() { return type; }
    this.getKeywordCharEnc = function() { return keywordCharEnc; }
    this.getOutputCharEnc = function() { return outputCharEnc; }
    this.getUrlFilters = function() { return urlFilters; }
    this.getTermFilters = function() { return termFilters; }
    this.getServeUrl = function() { return serveUrl; }
    this.getMaxCount = function() { return maxCount; }
}

//This is a Javascript object to hold configuration data for the creation of a content
//match link
var overtureContentMatchConf = function() {
    var baseUrl = g_baseOvertureCMUrl;
    var source = g_overtureCMSource;
    var config = g_overtureCMConfig;
    var ctxtId;
    var ctxtIdMap;
    var ctxtUrl;
    var ctxtCat;
    var ctxtCatMap;
    var ctxtKeywords;
    var mkt;
    var type;
    var typeMap;
    var keywordCharEnc;
    var outputCharEnc;
    var maxCount;


    this.setBaseUrl = function(lbaseUrl) { baseUrl = lbaseUrl; }
    this.setSource = function(lsource) { partner = lsource; }
    this.setCtxtId = function(lctxtId) { ctxtId = lctxtId; }
    this.setCtxtIdMap = function(lctxtIdMap) { ctxtIdMap = lctxtIdMap; }
    this.setCtxtUrl = function(lctxtUrl) { ctxtUrl = lctxtUrl; }
    this.setCtxtCat = function(lctxtCat) { ctxtCat = lctxtCat; }
    this.setCtxtCatMap = function(lctxtCatMap) { ctxtCatMap = lctxtCatMap; }
    this.setCtxtKeywords = function(lctxtKeywords) { ctxtKeywords = lctxtKeywords; }
    this.setMkt = function(lmkt) { mkt = lmkt; }
    this.setType = function(ltype) { type = ltype; }
    this.setTypeMap = function(ltypeMap) { typeMap = ltypeMap; }
    this.setKeywordCharEnc = function(lkeywordCharEnc) {keywordCharEnc = lkeywordCharEnc; }
    this.setOutputCharEnc = function(loutputCharEnc) { outputCharEnc = loutputCharEnc; }
    this.setConfig = function(lconfig) { config = lconfig; }
    this.setMaxCount = function(lmaxCount) { maxCount = lmaxCount; }

    this.getBaseUrl = function() { return baseUrl; }
    this.getSource = function() { return source; }
    this.getCtxtId = function() { return ctxtId; }
    this.getCtxtIdMap = function() { return ctxtIdMap; }
    this.getCtxtUrl = function() { return ctxtUrl; }
    this.getCtxtCat = function() { return ctxtCat; }
    this.getCtxtCatMap = function() { return ctxtCatMap; }
    this.getCtxtKeywords = function() { return ctxtKeywords; }
    this.getMkt = function() { return mkt; }
    this.getType = function() { return type; }
    this.getTypeMap = function() { return typeMap; }
    this.getKeywordCharEnc = function() { return keywordCharEnc; }
    this.getOutputCharEnc = function() { return outputCharEnc; }
    this.getConfig = function() { return config; }
    this.getMaxCount = function() { return maxCount; }
} 

//This is a Javascript object to hold configuration data for the creation of an
//Overture Linkspot link
var overtureLinkspotConf = function() {
    var baseUrl =  g_baseOvertureLinkspotUrl;
    var source = g_overtureLinkspotSource;
    var config = g_overtureLinkspotConfig;
    var linkspotId;
    var linkspotIdMap;
    var nGrp;
    var nKw;

    this.setBaseUrl = function(lbaseUrl) { baseUrl = lbaseUrl; }
    this.setSource = function(lsource) { source = lsource; }
    this.setLinkspotId = function(llinkspotId) { linkspotId = llinkspotId; }
    this.setLinkspotIdMap = function(llinkspotIdMap) { linkspotIdMap = llinkspotIdMap; }
    this.setConfig = function(lconfig) { config = lconfig; }
    this.setNGrp = function(lnGrp) { nGrp = lnGrp; } 
    this.setNKw = function(lnKw) { nKw = lnKw; } 

    this.getBaseUrl = function() { return baseUrl; }
    this.getSource = function() { return source; }
    this.getLinkspotId = function() { return linkspotId; }
    this.getLinkspotIdMap = function() { return linkspotIdMap; }
    this.getConfig = function() { return config; }
    this.getNGrp = function() { return nGrp; }
    this.getNKw = function() { return nKw; }
}

//This function creates an overtureLinks object from the linkData passed in
//note linkData will normally be the zSr array populated by Overture
function populateOvertureLinks (linkData) {
   var i = 0;
   var rank = 0;
   var ret = new overtureLinks();

   while (i < linkData.length) {
      rank++;
      var description  = linkData[i++];
      var unused   = linkData[i++];
      var clickUrl = linkData[i++];
      var title    = linkData[i++];
      var sitehost = linkData[i++];
      var bidded   = linkData[i++];

      //skip the first returned add
      if (rank > 1) {
         var currItem = new overtureItem(description, unused, clickUrl, title, sitehost, bidded);
         ret.addItem(currItem);
      }
   }

   return ret;
}

//This function creates an overtureLinks object from the linkData passed in for linksSpots
//note linkData will normally be the mapKey array populated by Overture
function populateOvertureLinkspots (linkData) {
   var ret = new overtureLinks();

   for (var i=0; i<linkData.length; i++) {
      var currItem = new overtureLinkSpotItem(linkData[i].title, linkData[i].keywords);
      ret.addItem(currItem);
   }

   return ret;
}

//function to show all the links
function showLinkData(linkData, startIndex, endIndex) {
  if (startIndex == undefined) {
	startIndex = 0;
  }
  var links = linkData.getItems();
  var outString = "<table border=1><tr><th>Description</th><th>Unused</th><th>ClickUrl</th><th>Title</th><th>SiteHost</th><th>Bidded</th></tr>";
  var arrLength = links.length;
  if (endIndex == undefined || endIndex == 0) {
    endIndex = arrLength;
  }
  else {
    if (endIndex > arrLength) {
	endIndex = arrLength;
    }
  }
  var i = startIndex;
  while ( i < endIndex) {
   var currItem = links[i];
   outString += "<tr><td>" + checkEmpty(currItem.getDescription()) + "</td><td>" + checkEmpty(currItem.getUnused()) + "</td><td>" + checkEmpty(currItem.getClickUrl()) + "</td><td>" + checkEmpty(currItem.getTitle()) + "</td><td>" + checkEmpty(currItem.getSitehost()) +  "</td><td>" + checkEmpty(currItem.getBidded()) + "</td></tr>\n";
   i++;
  } 

  outString += "</table>";
  return outString;
}

//returns a nbsp character if a string is empty
function checkEmpty(str) {
   if ( (str == undefined) || (str == "")) {
	return "&nbsp;";
   }
   else { 
       return str;
   }
}

//This function creates a link to fetch the Content Match data from Overture
function createOvertureSearchLink(conf) {
   var baseLink = conf.getBaseUrl();
   var partner = conf.getPartner();
   var keywords = conf.getKeywords();
   var type = conf.getType();
   var keywordCharEnc = conf.getKeywordCharEnc();
   var outputCharEnc= conf.getOutputCharEnc();
   var urlFilters = conf.getUrlFilters();
   var termFilters = conf.getTermFilters();
   var serveUrl = conf.getServeUrl();
   var maxCount = conf.getMaxCount();  

   if ( isEmpty(baseLink)) {
	baseLink = g_baseOvertureSearchUrl;
   }
   if ( isEmpty(partner)) {
	partner = g_overtureSearchPartner;
   }
   
   if ( isEmpty(serveUrl)) {
	serveUrl = window.location.href;
   }
      
   var retString = baseLink + "?Partner=" + urlEncode(partner);

   if ( !isEmpty(keywordCharEnc) ) {
      retString += "&keywordCharEnc=" + urlEncode(keywordCharEnc);
   }

   if ( !isEmpty(outputCharEnc) ) {
      retString += "&outputCharEnc=" + urlEncode(outputCharEnc);
   }

   if ( !isEmpty(keywords) ) {
      retString += "&Keywords=" + urlEncode(keywords);
   }

   if ( !isEmpty(type) ) {
      retString += "&type=" + urlEncode(type);
   }

   if ( !isEmpty(urlFilters)) {
      retString += "&urlFilters=" + urlFilters;
   }

   if ( !isEmpty(termFilters)) {
      retString += "&termFilters=" + termFilters;
   }
   
   if ( !isEmpty(serveUrl)) {
      retString += "&serveUrl=" + urlEncode(serveUrl);
   }

   if ( !isEmpty(maxCount)) {
      retString += "&maxCount=" + urlEncode(maxCount);
   }

   return retString;
}

//This function creates a link to fetch the Content Match data from Overture
function createOvertureCMLink(conf) {
   var baseLink = conf.getBaseUrl();
   var source = conf.getSource();
   var ctxtUrl = conf.getCtxtUrl();
   var ctxtId = conf.getCtxtId();
   var ctxtIdMap = conf.getCtxtIdMap();
   var ctxtCat = conf.getCtxtCat();
   var ctxtCatMap = conf.getCtxtCatMap();
   var ctxtKeywords = conf.getCtxtKeywords();
   var mkt = conf.getMkt();
   var type = conf.getType();
   var typeMap = conf.getTypeMap();
   var keywordCharEnc = conf.getKeywordCharEnc();
   var outputCharEnc= conf.getOutputCharEnc();
   var config = conf.getConfig();
   var maxCount = conf.getMaxCount();

   //cb is cache buster. its a random number to prevent caching
   var cb = randomnumber=Math.floor(Math.random()*100000);

   if (ctxtUrl == undefined) {
      ctxtUrl = "http://" + window.location.hostname +  window.location.pathname;
   }

   if (isEmpty(ctxtId) && !isEmpty(ctxtIdMap)) {
        //get the ctxtId from the specified map based on the current uri
	ctxtId = getMappingValue(ctxtIdMap);
   }

   if (isEmpty(ctxtCat) && !isEmpty(ctxtCatMap)) {
        //get the ctxtCat from the specified map based on the current uri
	ctxtCat = getMappingValue(ctxtCatMap);
   }

   if (isEmpty(type) && !isEmpty(typeMap)) {
        //get the type from the specified map based on the current uri
	type = getMappingValue(typeMap);
   }

   if (isEmpty(baseLink)) {
	baseLink = g_baseOvertureCMUrl;
   }
   if (isEmpty(source)) {
       source = g_overtureCMSource;
   }

   var retString = baseLink + "?source=" + urlEncode(source);

   if (!isEmpty(keywordCharEnc)) {
      retString += "&keywordCharEnc=" + urlEncode(keywordCharEnc);
   }

   if ( !isEmpty(outputCharEnc) ) {
      retString += "&outputCharEnc=" + urlEncode(outputCharEnc);
   }

   if ( !isEmpty(ctxtId) ) {
      retString += "&ctxtId=" + urlEncode(ctxtId);
   }

   if ( !isEmpty(ctxtCat) ) {
      retString += "&ctxtCat=" + urlEncode(ctxtCat);
   }

   if ( !isEmpty(ctxtKeywords) ) {
      retString += "&ctxtKeywords=" + urlEncode(ctxtKeywords);
   }

   if (!isEmpty(ctxtUrl)) {
      retString += "&ctxtUrl=" + urlEncode(ctxtUrl);
   }

   if ( !isEmpty(type) ) {
      retString += "&type=" + urlEncode(type);
   }

   if ( !isEmpty(cb) ) {
      retString += "&cb=" + urlEncode(cb);
   }

   if ( !isEmpty(config) ) {
      retString += "&config=" + urlEncode(config);
   }

   if (!isEmpty(maxCount) ) {
      retString += "&maxCount=" + urlEncode(maxCount);
   }

   if (!isEmpty(mkt) ) {
      retString += "&mkt=" + urlEncode(mkt);
   }

   return retString;

}

//This function creates a link to fetch the linkspot data from Overture
function createOvertureLinkspotLink(conf) {
   var baseLink = conf.getBaseUrl();
   var source = conf.getSource();
   var linkspotId = conf.getLinkspotId();
   var linkspotIdMap = conf.getLinkspotIdMap();
   var config = conf.getConfig();
   var nGrp = conf.getNGrp();
   var nKw= conf.getNKw();

   if ( (baseLink == undefined) || (baseLink == "")) {
	baseLink = g_baseOvertureLinkspotUrl;
   }
   if ( (source == undefined) || (source == "")) {
	source = g_overtureLinkspotSource;
   }

   if (isEmpty(linkspotId) && !isEmpty(linkspotIdMap)) {
        //get the linkspotId from the specified map based on the current uri
	linkspotId = getMappingValue(linkspotIdMap);
   }

   var retString = baseLink + "?config=" + urlEncode(config);

   if ( !isEmpty(linkspotId) ) {
      retString += "&linkspotId=" + urlEncode(linkspotId);
   }

   if ( !isEmpty(nKw) ) {
      retString += "&NKw=" + urlEncode(nKw);
   }

   if ( !isEmpty(nGrp) ) {
      retString += "&NGrp=" + urlEncode(nGrp);
   }

   if ( !isEmpty(source) ) {
      retString += "&source=" + urlEncode(source);
   }

   return retString;
}

//load in the array
function loadOvertureLinks() {
  this.overturLinks;
  if(zSr != undefined) {
     this.overturLinks = populateOvertureLinks(zSr);
     //if (this.overturLinks == undefined) {
     //   document.writeln("<P>!!! links is undefined !!!<br>");
     //}
  }
}


//load in the array for linkspots
function loadOvertureLinkspots() {
  if(!isEmpty(mapkey)) {
     overturLinkspots = populateOvertureLinkspots(mapkey);
     //if (this.overturLinkspots == undefined) {
     //   document.writeln("<P>!!! spot links is undefined !!!<br>");
     //}
  }
}


//This function gets the first 10 keywords from the page metatag
function getMetaTagKeywords () {
   var keywords = "";
   //try to get the keywords from the metatags
   if (document.getElementsByName) {
      var metaArray = document.getElementsByName('keywords');
      var maxLength = metaArray.length;
      if (maxLength > 10) { maxLength = 10; }
      for (var i=0; i<maxLength; i++) {
         if (i>0) { keywords += " "; }
         keywords += metaArray[i].content; 
      }
   }
  return keywords;
}

//Creates and prints the javascript src= code to include the 
//Content Match links
function loadOvertureCMInclude(conf) {
  var url = createOvertureCMLink(conf);
  printSrcInclude(url);
}

//Creates and prints the javascript src= code to include the 
//Search links
function loadOvertureSearchInclude(conf) {
  var url = createOvertureSearchLink(conf);
  printSrcInclude(url)
}

//Creates and prints the javascript src= code to include the 
//Links spots
function loadOvertureLinkspotInclude(conf) {
  var url = createOvertureLinkspotLink(conf);
  printSrcInclude(url)
  
}

//Prints the javascript src= code to include the zSr array with the links
function printSrcInclude(url) {
  document.write("<script language=\"Javascript\" src=\"" + url + "\"></script>");
}

//Checks to see if a string is empty
function isEmpty(str) {
  if ( (str == undefined) || (str == "")) {
    return true;
  }
  else {
    return false;
  }
}

//HTTP Encode a url
function urlEncode(sStr) {
    return escape(sStr)
       .replace(/\+/g, '%2B')
          .replace(/\"/g,'%22')
		  	.replace(/\//g, '%2F')
             .replace(/\'/g, '%27');
  }

//This function takes a map (a hashtable) and a string. If the string is omitted the current uri is
//used. Each key of the map is compared to the string and if the key matches the begining of the 
//String (i.e. key /music would match /music/foobar/index.jhtml), then the value for the key is
//returned as the result. Used for mapping ids to sections of the site
function getMappingValue(map, str) {
  if (str == undefined) {
    //if no match string is given then use the document uri
    str = window.location.pathname;
  }

  for (var key in map) {
    var exp = "^" + key;
    var re = new RegExp(exp, "i");
    if(re.test(str)) {
      return map[key];
    }
  }
  return undefined;
}
var barelisting = new Array();

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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

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

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

pageLoadFuncs.push(function() {
	deleteManager.addTriggers();
	
	if(jq.browser.msie) {
		jq("#FEATURELIST li a.tn_frame span").click(function() {
			document.location = jq(this).parent().attr('href');
		});
	}
});var isIE=(navigator.appVersion.indexOf("MSIE")!=-1)?true:false;var isWin=(navigator.appVersion.toLowerCase().indexOf("win")!=-1)?true:false;var isOpera=(navigator.userAgent.indexOf("Opera")!=-1)?true:false;function ControlVersion(){var version;var axo;var e;try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");version=axo.GetVariable("$version")}catch(e){}if(!version){try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");version="WIN 6,0,21,0";axo.AllowScriptAccess="always";version=axo.GetVariable("$version")}catch(e){}}if(!version){try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");version=axo.GetVariable("$version")}catch(e){}}if(!version){try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");version="WIN 3,0,18,0"}catch(e){}}if(!version){try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");version="WIN 2,0,0,11"}catch(e){version=-1}}return version}function GetSwfVer(){var flashVer=-1;if(navigator.plugins!=null&&navigator.plugins.length>0){if(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"]){var swVer2=navigator.plugins["Shockwave Flash 2.0"]?" 2.0":"";var flashDescription=navigator.plugins["Shockwave Flash"+swVer2].description;var descArray=flashDescription.split(" ");var tempArrayMajor=descArray[2].split(".");var versionMajor=tempArrayMajor[0];var versionMinor=tempArrayMajor[1];if(descArray[3]!=""){tempArrayMinor=descArray[3].split("r")}else{tempArrayMinor=descArray[4].split("r")}var versionRevision=tempArrayMinor[1]>0?tempArrayMinor[1]:0;var flashVer=versionMajor+"."+versionMinor+"."+versionRevision}}else if(navigator.userAgent.toLowerCase().indexOf("webtv/2.6")!=-1)flashVer=4;else if(navigator.userAgent.toLowerCase().indexOf("webtv/2.5")!=-1)flashVer=3;else if(navigator.userAgent.toLowerCase().indexOf("webtv")!=-1)flashVer=2;else if(isIE&&isWin&&!isOpera){flashVer=ControlVersion()}return flashVer}function DetectFlashVer(reqMajorVer,reqMinorVer,reqRevision){versionStr=GetSwfVer();if(versionStr==-1){return false}else if(versionStr!=0){if(isIE&&isWin&&!isOpera){tempArray=versionStr.split(" ");tempString=tempArray[1];versionArray=tempString.split(",")}else{versionArray=versionStr.split(".")}var versionMajor=versionArray[0];var versionMinor=versionArray[1];var versionRevision=versionArray[2];if(versionMajor>parseFloat(reqMajorVer)){return true}else if(versionMajor==parseFloat(reqMajorVer)){if(versionMinor>parseFloat(reqMinorVer))return true;else if(versionMinor==parseFloat(reqMinorVer)){if(versionRevision>=parseFloat(reqRevision))return true}}return false}}function AC_AddExtension(src,ext){if(src.indexOf('?')!=-1)return src.replace(/\?/,ext+'?');else return src+ext}function AC_Generateobj(objAttrs,params,embedAttrs){var str='';if(isIE&&isWin&&!isOpera){str+='<object ';for(var i in objAttrs)str+=i+'="'+objAttrs[i]+'" ';for(var i in params)str+='><param name="'+i+'" value="'+params[i]+'" /> ';str+='></object>'}else{str+='<embed ';for(var i in embedAttrs)str+=i+'="'+embedAttrs[i]+'" ';str+='> </embed>'}document.write(str)}function AC_FL_RunContent(){var ret=AC_GetArgs(arguments,".swf","movie","clsid:d27cdb6e-ae6d-11cf-96b8-444553540000","application/x-shockwave-flash");AC_Generateobj(ret.objAttrs,ret.params,ret.embedAttrs)}function AC_GetArgs(args,ext,srcParamName,classid,mimeType){var ret=new Object();ret.embedAttrs=new Object();ret.params=new Object();ret.objAttrs=new Object();for(var i=0;i<args.length;i=i+2){var currArg=args[i].toLowerCase();switch(currArg){case"classid":break;case"pluginspage":ret.embedAttrs[args[i]]=args[i+1];break;case"src":case"movie":args[i+1]=AC_AddExtension(args[i+1],ext);ret.embedAttrs["src"]=args[i+1];ret.params[srcParamName]=args[i+1];break;case"onafterupdate":case"onbeforeupdate":case"onblur":case"oncellchange":case"onclick":case"ondblClick":case"ondrag":case"ondragend":case"ondragenter":case"ondragleave":case"ondragover":case"ondrop":case"onfinish":case"onfocus":case"onhelp":case"onmousedown":case"onmouseup":case"onmouseover":case"onmousemove":case"onmouseout":case"onkeypress":case"onkeydown":case"onkeyup":case"onload":case"onlosecapture":case"onpropertychange":case"onreadystatechange":case"onrowsdelete":case"onrowenter":case"onrowexit":case"onrowsinserted":case"onstart":case"onscroll":case"onbeforeeditfocus":case"onactivate":case"onbeforedeactivate":case"ondeactivate":case"type":case"codebase":case"id":ret.objAttrs[args[i]]=args[i+1];break;case"width":case"height":case"align":case"vspace":case"hspace":case"class":case"title":case"accesskey":case"name":case"tabindex":ret.embedAttrs[args[i]]=ret.objAttrs[args[i]]=args[i+1];break;default:ret.embedAttrs[args[i]]=ret.params[args[i]]=args[i+1]}}ret.objAttrs["classid"]=classid;if(mimeType)ret.embedAttrs["type"]=mimeType;return ret}/**
 * SWFObject v1.5.1: 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={};}if(typeof deconcept.util=="undefined"){deconcept.util={};}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil={};}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={};this.variables={};this.attributes=[];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){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(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=[];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(!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;var flatCarouselManager = {
	autoRotateCarousel: true,
	interval: null,
	start: function() {
		flatCarouselManager.interval = setTimeout("flatCarouselManager.moveToNext()", 7000);
	},
	stop: function() {
		clearTimeout(flatCarouselManager.interval);
	},
	moveToNext:function() {
		var el = jq('#carousel_items li.active').next('li');
		
		if(!el.get(0))
			el = jq('#carousel_items li').not('.first-child').get(0);
		
		var id = jq(el).attr('id').replace(/I_/, '');
		
		jq('#carousel_items li').removeClass('active');
		jq(el).addClass('active');
		jq('#carousel a.tn_frame').css('display', 'none');
		jq('#C_' + id).css('display','block');
		
		flatCarouselManager.start();
	},
	triggerFunc: function(e) {
		if(e) preventDefault(e);
		
		jq('#carousel_items li').removeClass('active');
		jq(this).addClass('active');
		
		var id = jq(this).attr('id').replace(/I_/, '');
		
		jq('#carousel a.tn_frame').css('display', 'none');
		jq('#C_' + id).css('display','block');
	},
	addTriggers: function() {
		/* jq("#carousel").hover(function(e) {
			flatCarouselManager.stopInterval();
		}, function(e) {
			flatCarouselManager.setInterval();
		}); */
		jq('#carousel_items li').not('.first-child').click(this.triggerFunc);
		jq('#carousel a.tn_frame:first').css('display','block');
		if(flatCarouselManager.autoRotateCarousel)
			flatCarouselManager.start();
			
		jq("#carousel").hover(function() {
			flatCarouselManager.stop();
		}, function() {
			flatCarouselManager.start();
		});
		
		//this.size = jq('.carousel_pane').size();
	}
}

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