// NGC namespace
var NGC = {};
var isPageLoaded = true;

/*--------------------------------------------------
	Timezone
--------------------------------------------------*/

NGC.Timezone = function() {
	this.accTimezones = {"5":"et","6":"ct","7":"mt","8":"pt","9":"ak","10":"hi"};
	this.defTimezone = "5";
	this.cookieName = "ngctz";

	this.init = function() {
		$.cookie('all_episodes_userOption', null);
		$.cookie('upcoming_episodes_userOption', null);

		$.cookie('on_tonight_userOption', null);
		$.cookie('on_tommorow_userOption', null);
		this.findTimezone();
		this.setupPicker();
		$("body").click(function(){
			var timezone = $("ul.timezone_list");
			if ( timezone.not(":hidden") ) {
				$("a.toggle_timezones").removeClass("on");
				if ($.browser.msie && $.browser.version.substr(0, 1) == "7")
					timezone.hide();
				else
			    timezone.slideUp("fast");
			}
		});
	};

	// return the value (2 char string) part of accTimezones array
	// used both internal to this class and also to other classes
	this.getTimezoneString = function() {
		this.userTimezone = $.cookie(this.cookieName);
		return (this.accTimezones[this.userTimezone]);
	};

	// return array of 2 char strings for all existing timezones
	this.getAllTimezones = function() {
		var tz = [];
		for (var i in this.accTimezones) {
			tz.push(this.accTimezones[i]);
		}
		return tz;
	};

	// read/set timezone cookie, initiates
	this.findTimezone = function() {
		var cookie_value = $.cookie(this.cookieName);
		if (!cookie_value) {
			var offset = this._getTimezoneOffset();
			if (this.accTimezones[offset]) {this.setCookie(offset);}
			else {this.setCookie(this.defTimezone);}
		}
		this.userTimezone = $.cookie(this.cookieName);
		this.userOffset = parseInt(this.userTimezone)-parseInt(this.defTimezone);
		this.setPickerText(this.accTimezones[this.userTimezone]);
		this.updateShowTimes();
//		this.updateOnTonight();
	};

	// nav picker menu
	this.setupPicker = function() {
		// opens and closes the timezone picker
		$("a.toggle_timezones").click(function(){
			var timezone_list_bg = $("li.timezone a");
    	var timezone_list = $("ul.timezone_list");

	    if (timezone_list.is(":hidden") ) {
	    	timezone_list_bg.addClass("on");
				if ($.browser.msie && $.browser.version.substr(0, 1) == "7")
					timezone_list.show();
				else
		    	timezone_list.slideDown("fast");
				return false;}
	    else {
	    	timezone_list_bg.removeClass("on");
				if ($.browser.msie && $.browser.version.substr(0, 1) == "7")
					timezone_list.hide();
				else
					timezone_list.slideUp("fast");
	  		return false;}
		});

		// handles picker selection
		$("ul.timezone_list li a").click(function(){
			var timezone_gmt = $(this).attr("gmt");
			var timezone_text = $(this).text();
			// would like to fix scope issues here, any advice?
			NGC.timezone.setCookie(timezone_gmt);
			NGC.timezone.findTimezone();
			$("li.timezone a").removeClass("on");
			if ($.browser.msie && $.browser.version.substr(0, 1) == "7")
				$("ul.timezone_list").hide();
			else
				$("ul.timezone_list").slideUp("fast");

			// reload the schedule swf
			NGC.scheduleFlash.refresh( );

			return false;
		});
	};

	// updates show times on current page
	this.updateShowTimes = function(container) {
		if (container) { container+=" span[@time]"; }
		else { container = "span[@time]"; }

		var show = false;

		// The below code has been added for 7003 <START>

		// for all episodes
		$("div.all_episode_list_et").css("display", "none");
		$("div.all_episode_list_ct").css("display", "none");
		$("div.all_episode_list_mt").css("display", "none");
		$("div.all_episode_list_pt").css("display", "none");
		$("div.all_episode_list_ak").css("display", "none");
		$("div.all_episode_list_hi").css("display", "none");

		if ($('span').is('#episodePager-'+NGC.timezone.getTimezoneString()) ) {
			$('.all_episode_list_'+NGC.timezone.getTimezoneString()).pager('ul', { navId: 'episodePager-'+NGC.timezone.getTimezoneString(), navClass: 'previous_next', height:'' });
		}

		// for upcoming episodes

		$("div.upcoming_episode_list_et").css("display", "none");
		$("div.upcoming_episode_list_ct").css("display", "none");
		$("div.upcoming_episode_list_mt").css("display", "none");
		$("div.upcoming_episode_list_pt").css("display", "none");
		$("div.upcoming_episode_list_ak").css("display", "none");
		$("div.upcoming_episode_list_hi").css("display", "none");

		if ($('span').is('#upComingEpisodePager-'+NGC.timezone.getTimezoneString()) ) {

			$('.upcoming_episode_list_'+NGC.timezone.getTimezoneString()).pager('ul', { navId: 'upComingEpisodePager-'+NGC.timezone.getTimezoneString(), navClass: 'previous_next', height:'' });
		}

		if ($('div').is('#upcomingAndAll_list_'+NGC.timezone.getTimezoneString()) ) {
			//First time visit
			if($.cookie('upcoming_episodes_userOption')==null && $.cookie('all_episodes_userOption')==null){

				if($('.all_episode_list_'+NGC.timezone.getTimezoneString()).css('display')=="none"){

					$("div.upcoming_episode_list_"+NGC.timezone.getTimezoneString()).css("display", "block");

				}else if($('.upcoming_episode_list_'+NGC.timezone.getTimezoneString()).css('display')=="none"){

					$("div.all_episode_list_"+NGC.timezone.getTimezoneString()).css("display", "block");

				}
			}else{

				//Navigates between all episodes and up coming episodes
				if($.cookie('upcoming_episodes_userOption')=="true"){
					$("div.upcoming_episode_list_"+NGC.timezone.getTimezoneString()).css("display", "block");
					$("div.all_episode_list_"+NGC.timezone.getTimezoneString()).css("display", "none");
				}else if($.cookie('all_episodes_userOption')=="true"){
					$("div.all_episode_list_"+NGC.timezone.getTimezoneString()).css("display", "block");
					$("div.upcoming_episode_list_"+NGC.timezone.getTimezoneString()).css("display", "none");
				}
			}

		}else{

			$("div.all_episode_list_"+NGC.timezone.getTimezoneString()).css("display", "block");
		}

		// Code addition for 7003 <END>

		//SR-1312 - Start

		$("div.on_tonight_module_title").html("<div class='view_options_ontonight'><span class='tonight'><h3 class='active'>On Tonight</h3></span><div class='pipe'></div><a href='#' class='tomorrow'><h3 class='inactive'>On Tomorrow</h3></a></div><div style='clear:both;'></div>");
		$("div.on_tomorrow_module_title").html("<div class='view_options_ontonight'><a href='#' class='tonight'><h3 class='inactive'>On Tonight</h3></a><div class='pipe'></div><span class='tomorrow'><h3 class='active'>On Tomorrow</h3></div><div style='clear:both;'></div></span>");

	if ($.browser.msie && $.browser.version < 7) {
		$("div.on_tomorrow_module_title").addClass("on_tonight_module_title");
		}

		// for ontomorrow module
		$("div.on_tomorrow_module_et").css("display", "none");
		$("div.on_tomorrow_module_ct").css("display", "none");
		$("div.on_tomorrow_module_mt").css("display", "none");
		$("div.on_tomorrow_module_pt").css("display", "none");
		$("div.on_tomorrow_module_ak").css("display", "none");
		$("div.on_tomorrow_module_hi").css("display", "none");

		// for ontonight module
		$("div.on_tonight_module_et").css("display", "none");
		$("div.on_tonight_module_ct").css("display", "none");
		$("div.on_tonight_module_mt").css("display", "none");
		$("div.on_tonight_module_pt").css("display", "none");
		$("div.on_tonight_module_ak").css("display", "none");
		$("div.on_tonight_module_hi").css("display", "none");


		if ($('div').is('#ontonightAndOntomorrow_'+NGC.timezone.getTimezoneString()) ) {
			//First time visit
			if($.cookie('on_tonight_userOption')==null && $.cookie('on_tommorow_userOption')==null){

				if($('.on_tomorrow_module_'+NGC.timezone.getTimezoneString()).css('display')=="none"){

				$("div.on_tonight_module_"+NGC.timezone.getTimezoneString()).css("display", "block");

			}else if($('.on_tonight_module_'+NGC.timezone.getTimezoneString()).css('display')=="none"){

				$("div.on_tomorrow_module_"+NGC.timezone.getTimezoneString()).css("display", "block");

			}
			}else{

				//Navigates between all episodes and up coming episodes
				if($.cookie('on_tonight_userOption')=="true"){
					$("div.on_tonight_module_"+NGC.timezone.getTimezoneString()).css("display", "block");
					$("div.on_tomorrow_module_"+NGC.timezone.getTimezoneString()).css("display", "none");
				}else if($.cookie('on_tommorow_userOption')=="true"){
					$("div.on_tonight_module_"+NGC.timezone.getTimezoneString()).css("display", "none");
					$("div.on_tomorrow_module_"+NGC.timezone.getTimezoneString()).css("display", "block");
				}
			}

		}else{

			$("div.on_tonight_module_"+NGC.timezone.getTimezoneString()).css("display", "block");
		}
		// When the the user clicks on OnTomorrow module, ontonight module should be hidden and OnTomorrow module content should display
		$(".view_options_ontonight a.tomorrow").click(function(){

			var on_tonight_list = $("div.on_tonight_module_"+NGC.timezone.getTimezoneString());
			var on_tomorrow_list = $("div.on_tomorrow_module");
	    	var on_tomorrow_list_tz = $("div.on_tomorrow_module_"+NGC.timezone.getTimezoneString());

		    if ( on_tomorrow_list.is(":hidden") || on_tomorrow_list_tz.is(":hidden") ) {
			   	on_tonight_list.hide();
		    	on_tomorrow_list.show();
				on_tomorrow_list_tz.show();
				$.cookie('on_tonight_userOption', "false");
				$.cookie('on_tommorow_userOption', "true");
				return false;
			}else {
		    	on_tomorrow_list.hide();
				on_tomorrow_list_tz.hide();
				on_tonight_list.show();
		  	    return false;
			}
		});

		// When the the user clicks on OnTonight module, OnTomorrow module should be hidden and OnTonight module content should display
		$(".view_options_ontonight a.tonight").click(function(){

			var on_tomorrow_list = $("div.on_tomorrow_module");
			var on_tomorrow_list_tz = $("div.on_tomorrow_module_"+NGC.timezone.getTimezoneString());
	    	var on_tonight_list = $("div.on_tonight_module_"+NGC.timezone.getTimezoneString());

		    if ( on_tonight_list.is(":hidden")  ) {
		    	on_tomorrow_list.hide();
				on_tomorrow_list_tz.hide();
		    	on_tonight_list.show();
				$.cookie('on_tonight_userOption', "true");
				$.cookie('on_tommorow_userOption', "false");
				return false;
			}
		    else {
				on_tonight_list.hide();
		    	on_tomorrow_list.show();
				on_tomorrow_list_tz.show();
				return false;
			}
		});
		// SR-1312 - End


		// ET
		if (NGC.timezone.getTimezoneString() == "et") { show = true; } else { show = false; }
		$(".tz-et").each(function() { show ? $(this).show() : $(this).hide(); });
		$(".tz-ct").each(function() { show ? $(this).show() : $(this).hide(); });
        $(".tz-mt").each(function() { show ? $(this).show() : $(this).hide(); });
        $(".tz-pt").each(function() { show ? $(this).show() : $(this).hide(); });
        $(".tz-ak").each(function() { show ? $(this).show() : $(this).hide(); });
        $(".tz-hi").each(function() { show ? $(this).show() : $(this).hide(); });
		$("select.tz-et").each(function() {
			if ($(this).attr("name") == "date") {
				show ? $(this).attr("id", "date") : $(this).attr("id", "null");
				show ? $(this).attr("disabled", "") : $(this).attr("disabled", "disabled");
			}
		});

		// CT
		if (NGC.timezone.getTimezoneString() == "ct") {
			$(".tz-et").attr("style", "display: none;");
			show = true;
		}else{
			show = false;
		 }

		$(".tz-ct").each(function() { show ? $(this).show() : $(this).hide(); });
		$(".tz-mt").each(function() { show ? $(this).show() : $(this).hide(); });
        $(".tz-pt").each(function() { show ? $(this).show() : $(this).hide(); });
        $(".tz-ak").each(function() { show ? $(this).show() : $(this).hide(); });
        $(".tz-hi").each(function() { show ? $(this).show() : $(this).hide(); });
		$("select.tz-ct").each(function() {
			if ($(this).attr("name") == "date") {
				show ? $(this).attr("id", "date") : $(this).attr("id", "null");
				show ? $(this).attr("disabled", "") : $(this).attr("disabled", "disabled");
			}
		});

		// MT
		if (NGC.timezone.getTimezoneString() == "mt") {
			 $(".tz-et").attr("style", "display: none;");
			 $(".tz-ct").attr("style", "display: none;");
			 show = true;
		} else {
		   show = false;
		  }

		$(".tz-mt").each(function() { show ? $(this).show() : $(this).hide(); });
		$(".tz-pt").each(function() { show ? $(this).show() : $(this).hide(); });
        $(".tz-ak").each(function() { show ? $(this).show() : $(this).hide(); });
        $(".tz-hi").each(function() { show ? $(this).show() : $(this).hide(); });
		$("select.tz-mt").each(function() {
			if ($(this).attr("name") == "date") {
				show ? $(this).attr("id", "date") : $(this).attr("id", "null");
				show ? $(this).attr("disabled", "") : $(this).attr("disabled", "disabled");
			}
		});

		// PT
		if (NGC.timezone.getTimezoneString() == "pt") {
			$(".tz-et").attr("style", "display: none;");
     		$(".tz-ct").attr("style", "display: none;");
			$(".tz-mt").attr("style", "display: none;");
			show = true;
		} else {
			show = false;
		  }
		$(".tz-pt").each(function() { show ? $(this).show() : $(this).hide(); });
		$(".tz-ak").each(function() { show ? $(this).show() : $(this).hide(); });
        $(".tz-hi").each(function() { show ? $(this).show() : $(this).hide(); });
		$("select.tz-pt").each(function() {
			if ($(this).attr("name") == "date") {
				show ? $(this).attr("id", "date") : $(this).attr("id", "null");
				show ? $(this).attr("disabled", "") : $(this).attr("disabled", "disabled");
			}
		});

		// AK
		if (NGC.timezone.getTimezoneString() == "ak") {
			$(".tz-et").attr("style", "display: none;");
     		$(".tz-ct").attr("style", "display: none;");
			$(".tz-mt").attr("style", "display: none;");
			$(".tz-pt").attr("style", "display: none;");
			show = true;
		} else {
			show = false;
		  }
		$(".tz-ak").each(function() { show ? $(this).show() : $(this).hide(); });
		$(".tz-hi").each(function() { show ? $(this).show() : $(this).hide(); });
		$("select.tz-ak").each(function() {
			if ($(this).attr("name") == "date") {
				show ? $(this).attr("id", "date") : $(this).attr("id", "null");
				show ? $(this).attr("disabled", "") : $(this).attr("disabled", "disabled");
			}
		});

		// HI
		// HI


		if (NGC.timezone.getTimezoneString() == "hi") {
			$(".tz-et").attr("style", "display: none;");
     		$(".tz-ct").attr("style", "display: none;");
			$(".tz-mt").attr("style", "display: none;");
			$(".tz-pt").attr("style", "display: none;");
			$(".tz-ak").attr("style", "display: none;");
			show = true;
		} else {
			show = false;
		  }
		$(".tz-hi").each(function() { show ? $(this).show() : $(this).hide(); });
		$("select.tz-hi").each(function() {
			if ($(this).attr("name") == "date") {
				show ? $(this).attr("id", "date") : $(this).attr("id", "null");
				show ? $(this).attr("disabled", "") : $(this).attr("disabled", "disabled");
			}
		});

		/*
		$(container).each(function() {
			// offset times based on timezone
			var time_ampm = $(this).attr("time").split(" ")[0];
			var time = time_ampm.slice(0,time_ampm.length-1);
			var ampm = time_ampm.slice(time_ampm.length-1, time_ampm.length);
			var u_zone = NGC.timezone.accTimezones[NGC.timezone.userTimezone.toString()];
			var zone = $(this).attr("time").length <= 3 ? '' : u_zone;
			var offset = NGC.timezone.userOffset;
			var hour ='';

			if (time.indexOf('-') != -1) {
				times = time.split('-');
				for(i=0; i<2; i++) {
					times[i] = parseInt(times[i]) - offset;
					if (times[i]>=13){times[i]-=12; ampm=NGC.timezone.swapAMPM(ampm);}
					if (times[i]<=0) {times[i]+=12; ampm=NGC.timezone.swapAMPM(ampm);}
					if (i==0) { hour = times[i].toString() + '-'; }
					else { hour += times[i].toString(); }
				}}
			else {
				hour = parseInt(time) - offset;
				if (hour>=13){hour-=12; ampm=NGC.timezone.swapAMPM(ampm); }
				if (hour<=0) {hour+=12; ampm=NGC.timezone.swapAMPM(ampm); }
			}
			$(this).text(hour.toString() + ampm + " " + zone);
		});
		*/
	};

	// update the on tonight module, only on the home page
	// instead of changing the time span, swap out the entire timezone div of 4 show promos
	/*
	this.updateOnTonight = function() {
		if ($("#tonightET").size()) {
			this.userTimezone = $.cookie("ngc");
			var tz = this.accTimezones[this.userTimezone].toString();
			var tz = this.getTimezoneString();
			for (t in this.accTimezones) {
				if (this.accTimezones[t] == tz) {
					$("#tonight" + this.accTimezones[t].toString().toUpperCase()).show();
				} else {
					$("#tonight" + this.accTimezones[t].toString().toUpperCase()).hide();
				}
			}
		}
	};
	*/

	// changes a to p or vice versa based on timezone change
	this.swapAMPM = function(ampm) {
		return ampm == 'a' ? 'p' : 'a';
	};

	this.setCookie = function(number) {
		$.cookie(this.cookieName, number, {path: '/'});
	};

	// sets the span text for the timezone picker
	this.setPickerText = function(timezone) {
		$("li.timezone a span").text(timezone);
	};

	// returns timezone offset, taking DTS into consideration
	 this._getTimezoneOffset = function() {
	  var date = new Date();
	  var msec = date.getTime();
	  var offset = -999999;
	  for (var i = 0; i < 4; i++) {
	    date.setTime(msec + i * 7884000000);
	    offset = Math.max(offset, date.getTimezoneOffset()/60);
	  }
	  return offset.toString();
	};

};


/*--------------------------------------------------
	Clock
--------------------------------------------------*/

NGC.Clock = function() {
	this.dayNames = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");

	// update the clock each second
	this.update = function() {
		var clock_time = new Date();
		var clock_hours = clock_time.getHours();
		var clock_minutes = clock_time.getMinutes();
		var clock_nday=clock_time.getDay();
		var clock_suffix = "";

		if (clock_hours>=12) clock_suffix=" pm";
		else clock_suffix=" am";

		clock_nday = this.dayNames[clock_nday];

		if (clock_hours>=13) clock_hours-=12;
		if (clock_hours==0) clock_hours=12;
		if (clock_minutes <10) clock_minutes ="0"+clock_minutes ;

		var clock_div = document.getElementById("js_clock");
		if (clock_div) {
			var clock_str = clock_nday + " " + clock_hours + ":" + clock_minutes + clock_suffix;
			if (clock_str != clock_div.innerHTML)	clock_div.innerHTML = clock_str;

			setTimeout("NGC.clock.update()", 1000);
		}
	};
};


/*-----------------------------------------------
	Ad Swapping
-----------------------------------------------*/
NGC.AdClass = function() {
	this.lastTabFurl;

	// refresh all the ads on the page, with updated parameters
	this.update = function(adZone, syncID) {
		$('div.ad iframe').each(function() {
			try {
				var temp;
				if (this.src == "" || this.src == undefined) {
					temp = this.name;
				} else {
					temp = this.src;
				}

				// replace the adzone if it changed (adzone is called furl when passed to the jsp)
				if (adZone != undefined)
					temp = temp.replace(/\&furl=[^\&]*(\&|$)/gi, "&furl=" + adZone + "&");

				// replace the syncid if it changed
				if (syncID != undefined)
					temp = temp.replace(/\&syncID=[^\&]*(\&|$)/gi, "&syncID=" + syncID + "&");

				this.src = temp;
			} catch(e) {
			}
		});

		$('div.adheader iframe').each(function() {
			try {
				var temp;
				if (this.src == "" || this.src == undefined) {
					temp = this.name;
				} else {
					temp = this.src;
				}

				// replace the adzone if it changed (adzone is called furl when passed to the jsp)
				if (adZone != undefined)
					temp = temp.replace(/\&furl=[^\&]*(\&|$)/gi, "&furl=" + adZone + "&");

				// replace the syncid if it changed
				if (syncID != undefined)
					temp = temp.replace(/\&syncID=[^\&]*(\&|$)/gi, "&syncID=" + syncID + "&");

				this.src = temp;
			} catch(e) {
			}
		});
	};

	this.setParams = function(w, h, adZone, theme, syncID, tile) {
		this.w = w;
		this.h = h;
		this.adZone = adZone;
		this.theme = theme;
		this.syncID = syncID;
		this.tile = tile;
	};

	this.setTab = function(furl) {
		var temp = furl;
		// replace slashes with underscores (ad calls can't handle slashes
		temp = temp.split("/").join("_");
		// remove _channel if it exists to shorten the furl string
		if (temp.substr(0, 8) == "_channel")
			temp = temp.substr(8, temp.length-8);
		this.lastTabFurl = temp;
		delete temp;
	}

	this.getTab = function() {
		return this.lastTabFurl;
	}
};

NGC.ads = new NGC.AdClass();
NGC.refreshAds = NGC.ads.update;		// simpler public method for updating the ads



	// Calls Omniture for tracking tab clicks
	function loadOmniturePageView(str1, str2) {


		if (!isPageLoaded) {
			ngsPageView(str1, str2);
		} else {
			isPageLoaded = false;
		}

	};

/*--------------------------------------------------
	Tabs
--------------------------------------------------*/

// reliant on timezone object

NGC.Tabs = function() {
	this.dataObj;
	this.container;
	this.currentTab;


	this.init = function() {
		$("body").click(function(){
			$(".more_list");
			var show_more_list = $(".more_list");
			if ( show_more_list.not(":hidden") ) {
				if ($.browser.msie && $.browser.version.substr(0, 1) == "7")
					show_more_list.hide();
				else
					show_more_list.slideUp(125);
				$('li.more').removeClass('more_selected');
			}
		});
		$("#nav_tabs").tabs({
			// fxFade:true,
			// fxSlide:true,
			remote:true,
			spinner:null,
			onShow: function() {
				NGC.timezone.updateShowTimes("#nav_tabs");
			}
		});
		// un-hide the now-correct tabs
		$('ul.content_nav').show();
	};



	// allow switching of tabs from links within the page
	this.jump = function(tab) {
		$('#nav_tabs .content_nav li a').each(function() {
			if ('tab-' + $(this).attr('tabid') == tab) {
				$('#nav_tabs').triggerTab(tab);
			}
		});
	};


	// transform and render ajaxed json data for the tab content
	this.render = function(dataObj, id) {
		this.dataObj = dataObj;
		this.container = id;
		this.currentTab = this.container.replace('-container','');
		this.thumb = location.hash.split('/')[1];
		if (typeof(deeplink_asset) != 'undefined' && typeof(this.thumb) == 'undefined') {
			this.thumb = deeplink_asset;
		}



        // explicity kill any object tags that may be left in previous tabs
        // mainly to accomodate IE 6 that seems to keep playing the video when tab
        // is hidden
        $('#nav_tabs div.tabs-container object, #nav_tabs div.tabs-container embed').remove();

		// render differently based on data (tab) type
		switch(this.dataObj.type) {
			case "overview":
				this.renderOverviewContent();
				loadOmniturePageView("tab=" + this.currentTab, '');
				break;
			case "videos":
				this.renderVideoContent();
				break;
			case "photos":
				this.renderPhotoContent();
				break;
			case "interactive":
				this.renderInteractiveContent();
				loadOmniturePageView("tab=" + this.currentTab, '');
				break;
			case "generic":
				this.renderGenericContent();
				loadOmniturePageView("tab=" + this.currentTab, '');
				break;
			default:
				alert("json data type not recognized");
				break;
		}


		// for every link with class "tablink" rewrite the href to call jump method
		$("a.tablink").each(
			function() {
				var tabid = $(this).attr("href").split("#")[1];
				if (tabid != undefined)
					$(this).attr("href", "javascript:NGC.tabs.jump('" + tabid + "')");
			}
		);


		var container = $('#nav_tabs');
		var nav = $('ul.tabs-nav', container);
		nav = nav.size() && nav || $('>ul:eq(0)', container); // fallback to default structure
		var tabs = $('a', nav);

		var ct = this.currentTab;
		var furl = "";

		tabs.each(function() {
			if ("tab-" + this.tabid == ct) {
				furl = this.furl;

			}
		});

		// update the ads
		if (NGC.ads)
			NGC.ads.update(furl);

		// first try getting the thumb from the hash
		// then try getting the thumb from the deeplink variable
		// else don't change the selected thumb (use the first as default)
		/*
		******* added check for this.thumb to render*Content, so this is unnecessary. djc.

		if (typeof(this.thumb) != 'undefined' && this.thumb) {
			try { this.selectedThumb(this.thumb);} catch(e) {}
		} else if (typeof(deeplink_asset) != 'undefined') {
//			NGC.carousel.updateVideo(2);
			this.selectedThumb(deeplink_asset);
		}
		*/
	};


	// write out a (html) string to the page
	this.output = function(str) {
		$('#'+this.container).html(str);
	};

	// generate html for photos tab
	this.renderPhotoContent = function() {
		var buf = '';
		var items = [];//fix for defect 5696

		// if there are no photos, do not display content
		if (!this.dataObj.groups[0].photos || this.dataObj.groups[0].photos.length <= 0)
			return;

		// start the main div
		buf += '<div class="photo transbg">';//5696

		// big photo
		buf += '<div id="viewer-' + this.currentTab + '" class="viewer">';
		buf += '<img src="#" />';
		buf += '</div>';

		// separator
		buf += '<span class="separator"><img src="images/common/separator.png" width="512" height="1" /></span>';

		// caption and caption
		buf += '<div class="description">';
		buf += '</div>';

		// downloads
		buf += '<div class="downloads">';

		// wallpaper
		buf += '<div id="downloadwallpaper">';
		buf += '<h4>Download Wallpaper</h4>';
		buf += '<ul class="mini_options wallpaper">';
		buf += '</ul>';
		buf += '</div>';

		// screensaver
		buf += '<div>';
		buf += '<h4>Screen Savers</h4>';
		buf += '<ul class="mini_options screensaver">';
		buf += '<li class="solo"><a href="' + this.dataObj.screensaver.url + '">' + this.dataObj.screensaver.label + '</a></li>';
		buf += '</ul>';
		buf += '</div>';

		// close downloads div
		buf += '</div>';

		// flatten out the videos/groups into a single array

		for (var i=0; i < this.dataObj.groups.length; i++) {
			for (var j=0; j < this.dataObj.groups[i].photos.length; j++) {
				this.dataObj.groups[i].photos[j].group = this.dataObj.groups[i].name;
				items.push(this.dataObj.groups[i].photos[j]);

			}
		}

		// render the carousel
		NGC.carousel = new NGC.Carousel(items, "photo", this.currentTab);//
		buf += NGC.carousel.render();

		// close the main div
		//buf += '<div style="clear:both"></div></div>';//5696

		// write to the page
		this.output(buf);
		// set url's inside of tabs for msie



		if (NGC.carousel) {
			// fill in with the first photo by default, unless a specific photo is targeted
			NGC.carousel.updatePhoto(this.thumb);
			// activate tooltips
			NGC.carousel.activateToolTips();
		} else {
		}
	};

	// generate html for videos tab
	this.renderVideoContent = function() {
		var buf = '';
		var items = [];

		// if there are no videos, do not display content
		if (!this.dataObj.groups[0].videos || this.dataObj.groups[0].videos.length <= 0)
			return;

		// start the main div
		buf += '<div class="video">';//5696

		// video player
		buf += '<div id="viewer-' + this.currentTab + '" class="viewer">';
		buf += '</div>';

		// start the content div
		buf += '<div class="transbg">';//5696

		// caption
		buf += '<div class="description">';
		buf += '</div>';

		// flatten out the videos/groups into a single array
		for (var i=0; i < this.dataObj.groups.length; i++) {
			for (var j=0; j < this.dataObj.groups[i].videos.length; j++) {
				this.dataObj.groups[i].videos[j].group = this.dataObj.groups[i].name;
				items.push(this.dataObj.groups[i].videos[j]);
			}
		}

		// render the carousel
		NGC.carousel = new NGC.Carousel(items, "video", this.currentTab);
		buf += NGC.carousel.render();

		// close the content div
		//buf += '<div style="clear:both"></div></div>';//5696

		// close the main div
		buf += '</div>';

		// write to page
		this.output(buf);

		if (NGC.carousel) {
			// fill in with the first video by default, unless a specific video is targeted
			var thumb = this.thumb || 0;
			NGC.carousel.updateVideo(thumb, false);
			// activate tooltips
			NGC.carousel.activateToolTips();
		}
	};

	this.renderGenericContent = function() {
		var buf = '';

		// if there is no content, do not display
		if (!this.dataObj.content)
			return;

		this.output(this.dataObj.content);
	};

	// generate html for interactive tab
	this.renderInteractiveContent = function() {
		// determine which layout type
		switch(this.dataObj.layout) {
			case "flash":
				this.renderInteractiveContentFlash();
				break;
			default:
				break;
		}
	};

	this.renderInteractiveContentFlash = function() {
		var buf = '';

		// start main div
		buf += '<div class="interactive">';

		// flash container, also displays the no flash message
		buf += '<div id="interactive">';
		buf += '</div>';

		// close main div
		buf += '</div>';

		try {
			this.output(buf);
			$('div#interactive').flash({
				src: this.dataObj.src,
				width: this.dataObj.width,
				height: this.dataObj.height,
				wmode: 'transparent'
			}, { version: '9.0.115' });
		} catch (e) {
			$('div#interactive').html("");
		}
	};

	// generate html for overview tab
	this.renderOverviewContent = function() {
		var buffer = '';

		// start main and content divs
		buffer += '<div class="overview">';
		buffer += '<div id="viewer-' + this.currentTab + '" class="viewer">';

		// render first part based on content layout
		switch(this.dataObj.content.layout) {
			case "image":
				buffer += this.renderOverviewContentImage();
				break;
			case "flash":
				buffer += this.renderOverviewContentFlash();
				break;
			case "text_left":
				buffer += this.renderOverviewContentTextLeft();
				break;
			case "text_right":
				buffer += this.renderOverviewContentTextRight();
				break;
			default:
				break;
		}

		// close content div
		buffer += '</div>';

		// render second part based on episode_info layout
		switch(this.dataObj.episode_info.layout) {
			case "series":
				buffer += this.renderOverviewEpisodeInfoSeries();
				break;
			case "episode":
				buffer += this.renderOverviewEpisodeInfoEpisode();
				break;
			default:
				break;
		}

		// close main div
		buffer += '</div>';

		// write the buffer to the page
		this.output(buffer);

		// if this is flash content, load the actual movie
		if (this.dataObj.content.flash) {
			this.loadOverviewContentFlash();
		}

		// once all content is written, filter timedate info by timezone
		NGC.timezone.updateShowTimes();
	};

	this.renderOverviewContentImage = function() {
		var buf = '';
		var obj = this.dataObj;

		// display image, if it exists
		if (obj.content.image) {
			buf += '<img src="' + obj.content.image.src + '" width="' + obj.content.image.width + '" height="' + obj.content.image.height + '" alt="' + obj.content.image.alt + '" />';
		}

		return buf;
	};

	this.renderOverviewContentFlash = function() {
		var buf = '';
		var obj = this.dataObj;

		// display flash, if it exists
		if (obj.content.flash) {
			buf += '<div id="overview_flash" style="width:' + obj.content.flash.width + 'px; height:' + obj.content.flash.height + 'px;"></div>';
		}

		return buf;
	};

	this.loadOverviewContentFlash = function() {
		var obj = this.dataObj;

		// load actual flash movie
		try {
			w = parseInt($('#overview_flash').css('width'));
			h = parseInt($('#overview_flash').css('height'));
			$('#overview_flash').flash({
				src: obj.content.flash.src,
				width: w,
				height: h,
				wmode: 'transparent'
			}, { version: '9.0.115' });
		} catch (e) {
			$('#overview_flash').html("");
		}
	};

	this.renderOverviewContentTextLeft = function() {
		var buf = '';
		var obj = this.dataObj;

		buf += '<p class="txt_left txt_lite">' + obj.content.text + '</p>';

		// display image, if it exists
		if (obj.content.image) {
			buf += '<img src="' + obj.content.image.src + '" width="' + obj.content.image.width + '" height="' + obj.content.image.height + '" alt="' + obj.content.image.alt + '" />';
		}

		return buf;
	};

	this.renderOverviewContentTextRight = function() {
		var buf = '';
		var obj = this.dataObj;

		buf += '<p class="txt_right txt_lite">' + obj.content.text + '</p>';


		// display image, if it exists
		if (obj.content.image) {
			buf += '<img src="' + obj.content.image.src + '" width="' + obj.content.image.width + '" height="' + obj.content.image.height + '" alt="' + obj.content.image.alt + '" />';
		}

		return buf;
	};

	// series episode info
	this.renderOverviewEpisodeInfoSeries = function() {
		var buf = '';
		var obj = this.dataObj;

		// next episode info, if it exists
		if (obj.episode_info) {
			if (obj.episode_info.image && obj.episode_info.image.src)
				buf += '<div class="next_episode_airing">';
			else
				buf += '<div class="next_episode_airing_no_image">';

			// display thumbnail image if it exists
			//Updated for TT-1390 on 29-Jan-09
			//including anchor tag

			if (obj.episode_info.image && obj.episode_info.image.src) {
				buf += '<div class="episode_preview">';
				buf += '<a href="' + obj.episode_info.url +'"><img src="' + obj.episode_info.image.src + '" width="' + obj.episode_info.image.width + '" height="' + obj.episode_info.image.height + '" alt="' + obj.episode_info.image.alt + '" /></a>';
				buf += '</div>';
			}

			// display the episode info
			buf += '<div class="episode_info">';

			// show the remind me button, but only if the remind form exists
			if ($('#pop_remind_me').is("*"))
				buf += '<span class="button"><a href="javascript:NGC.remindMe.show();" class="remind_me">Remind Me</a></span>';

			var tz = NGC.timezone.getAllTimezones();

			if (obj.episode_info.name) {
				var nameTemp = "";
				for (var i=0; i < obj.episode_info.name.length; i++) {
					if (obj.episode_info.name[i])
						nameTemp += '<span class="tz-' + tz[i] + '">' + obj.episode_info.name[i] + '</span>';
				}
				buf += '<span class="title">' + nameTemp + '</span>';
				delete nameTemp;
			}

			//Updated for TT-1390 on 3-FEB-09
			//including anchor tag


			if (obj.episode_info.title)

			buf += '<h2 class="episode"><a href="' + obj.episode_info.url +'">' + obj.episode_info.title + '</a></h2>';

			for (var i=0; i < obj.episode_info.time.length; i++) {
				if (obj.episode_info.time[i])
					buf += '<span class="time_actual tz-' + tz[i] + '">' + obj.episode_info.time[i] + '</span>';
			}

			if (obj.episode_info.body && obj.episode_info.body.length>7){
				buf += '<div class="body_content">' + obj.episode_info.body + '</div>';
			}else{
				buf += '<div class="body_content">' + '&nbsp;' + '</div>';
			}

			//tt-1190-start

				if (obj.episode_info.creditlink != undefined && obj.episode_info.creditlink != "")
				{
				   buf += '<ul class="mini_options">';
				   buf += '<li class="first"><a href="' + obj.episode_info.creditlink + '">CREDITS</a></li>';
				   buf += '</ul>';
				}

              //tt-1190-end

			buf += '</div>';

			// close next_episode_airing div
			buf += '</div>';
		}

		return buf;
	}

	this.renderOverviewEpisodeInfoEpisode = function() {
		var buf = '';
		var obj = this.dataObj;

		// info
		buf += obj.episode_info.body;

		buf += '<div class="browse_episodes">';//fix for 5696

		// options
		if (obj.episode_info.creditlink != undefined && obj.episode_info.creditlink != "") {
			buf += '<ul class="mini_options">';
			buf += '<li class="first"><a href="' + obj.episode_info.creditlink + '">CREDITS</a></li>';
			buf += '</ul><BR>';//fix for 5696
		}

		// browse episodes
		if (obj.episode_info.nextlink || obj.episode_info.prevlink) {

			if (obj.episode_info.nextlink)
				buf += '<span class="button"><a href="' + obj.episode_info.nextlink + '" class="next">Next</a></span>';
			if (obj.episode_info.prevlink)
				buf += '<span class="button"><a href="' + obj.episode_info.prevlink + '" class="previous">Prev</a></span>';
			buf += '<label>Browse Episodes</label>';

		}

		buf += '</div>';//fix for 5696

		return buf;
	};

	this.selectedThumb = function(thumb) {
		if(typeof(thumb) == 'number') {
			thumb--;
		}
		switch (this.dataObj.type) {
			case "photos":
				NGC.carousel.updatePhoto(thumb);
				break;
			case "videos":
				NGC.carousel.updateVideo(thumb, true);
				break;
		}
	};
};


/*--------------------------------------------------
	Image/Video Picker/Carousel
--------------------------------------------------*/

NGC.Carousel = function(items, type, tab) {
	this.type = type;
	this.currentTab = tab || '';
	this.active = 0;
	this.items = items;
	this.thumbSpace = 64;
	this.thumbCount = 7;
	this.firstAsset = true;

	this.render = function() {
		var buf = '';

		switch(this.type) {
			case "video":
				// separator
				buf += '<span class="separator"><img src="images/common/separator.png" width="512" height="1" /></span>';

				// carousel
				buf += '<div class="picker"';
				// if only one video, then hide the carousel
				if (items.length <= 1)
					buf += ' style="display: none;"';
				buf += '>';
				buf += '<a href="#" class="arrow left">Previous</a>';
				buf += '<div class="picker_wrapper">';
				buf += '<ul class="thumbs">';

				for (var i=0; i < this.items.length; i++) {
					buf += '<li group="' + this.items[i].group + '"><a id="thumb' + i + '" onclick="NGC.carousel.startVideoPlayer(' + i + ', true); return false;"><img style="left:' + (i * this.thumbSpace) + 'px;" src="' + this.items[i].thumb + '" alt="Image Description" /></a></li>';
				}

				buf += '</ul>';
				buf += '</div>';
				buf += '<a href="#" class="arrow right">Next</a>';
				// create the tooltip
				buf += '<div id="tooltip"><div class="top"></div><div class="inner">ARG</div><div class="bottom"></div></div>';

				// close picker
				buf += '</div>';
				break;
			case "photo":
				// separator
				buf += '<span class="separator"><img src="images/common/separator.png" width="512" height="1" /></span>';

				// start picker
				buf += '<div class="picker"';
				// if only one photo, then hide the carousel
				if (items.length <= 1)
					buf += ' style="display: none;"';
				buf += '>';

				// left arrow
				buf += '<a href="#" class="arrow left">Previous</a>';

				// thumbnails
				buf += '<div class="picker_wrapper">';
				buf += '<ul class="thumbs">';

				for (var i=0; i < this.items.length; i++) {
					buf += '<li group="' + this.items[i].group + '"><a id="thumb' + i + '" onclick="NGC.carousel.updatePhoto(' + i + '); return false;"><img style="left:' + (i * this.thumbSpace) + 'px;" src="' + this.items[i].thumb + '" alt="Image Description" /></a></li>';
				}

				// close thumbnails
				buf += '</ul>';
				buf += '</div>';
				// right arrow
				buf += '<a href="#" class="arrow right">Next</a>';

				// create the tooltip
				buf += '<div id="tooltip"><div class="top"></div><div class="inner">ARG</div><div class="bottom"></div></div>';

				// close picker
				buf += '</div>';
				break;
		}

		return buf;
	};

	this.update = function(item) {
		switch(this.type) {
			case "video":
				this.updateVideo(item, true);
			break;
			case "photo":
				this.updatePhoto(item);
			break;
		}
	};

	// updates just the changing portions of the video content
	// called by the carousel, and on video tab content load
	this.updateVideo = function(item, autoPlayVideo) {
		// to resolve the http 500 error
       var itemId  = item;
        if (typeof(assetId) != 'undefined' || typeof(assetId) != 'null' || assetId!='noValue' ) {
               itemId = assetId;
              var j;
			for(j = 0; j < items.length; j++) {
				if(items[j].videoRef == itemId ) {
				    item = j;
					break;
				}

				if(j == itemId ) {
				    item = j;
					break;
				}
			}
            assetId = "null";
        }
        assetId = "null";
		// end to resolve the http 500 error
		if(typeof(item) == "string") {
			var i;
			for(i = 0; i < items.length; i++) {
				if(items[i].videoRef == item) {
				    item = i;
					break;
				}
			}
		}

        if (!this.items[item]) {
            item = 0;
        }
		loadOmniturePageView("tab=tab-Videos&itemRef=" + this.items[item].videoRef, '');

		// video player
		var viewer = 'viewer' + ((this.currentTab != '') ? '-' + this.currentTab : '');
		$('div.video #' + viewer ).html('');

		// caption
		var buf = '';
		buf += '<p>' + this.items[item].description + '</p>';//updated for SR-1402
		$('div.video .description').html(buf);

		// history
		var itemId = this.items[item].videoRef || item;
		this.updateHash(itemId);

		// toggle classes
		this.toggleClass(item, 'video');

		// update the picker
		this.updateArrows();

		// update the ads, as long as its not the initial tab video
		if (!this.firstAsset && NGC.ads)
			NGC.ads.update();
		this.firstAsset = false;
		try {
			// load the satellite player
			var params ="";
			var adSite = "ngc";
			var adZone = "";
			if (NGC.ads)
				adZone = NGC.ads.getTab();
			var allowShare = "true";
			var autoPlay = autoPlayVideo;
			var videoRef = this.items[item].videoRef;

			// Added for SR-787 - Begin
			var shareURL = window.location.href;
			var x;
			var tokens = shareURL.split("/");

			for(x in tokens)
			{
				if(tokens[x] != "Videos")
				{
					if(tokens[x].indexOf("#tab-Videos") != -1)
					{
						shareURL=shareURL.replace(shareURL.substring(shareURL.indexOf(tokens[x].substring(0))),"Videos/"+videoRef);
					}
				}
				else
				{
					shareURL=shareURL.replace(shareURL.substring(shareURL.indexOf(tokens[x].substring(0))),"Videos/"+videoRef);
					break;
				}
			}
			// Added for SR-787 - End

			var playerHeight = parseFloat(this.items[item].height);
			var playerWidth = parseFloat(this.items[item].width);
			var playerId = "";
			var overStateColor = "";
			var shareTextColor = "";
			var shareHeaderTextColor = "";

			params += "adSite="+adSite;
			params += "&adZone="+adZone;
			params += "&allowShare="+allowShare;
			params += "&autoPlay="+autoPlay;
			params += "&videoRef="+videoRef;
			params += "&shareURL="+shareURL;
			params += "&playerHeight="+playerHeight;
			params += "&playerWidth="+playerWidth;
			params += "&playerId="+playerId;
			params += "&overStateColor="+overStateColor;
			params += "&shareTextColor="+shareTextColor;
			params += "&allowScriptAccess=always";
			params += "&shareHeaderTextColor="+shareHeaderTextColor;

			loadTransparentSatellitePlayer(viewer,params);

/*
			// urlOfSatellitePlayer variable set in http://channel.nationalgeographic.com/channel/videos/satellite/js/satellite.js
			// value there is http://channel.nationalgeographic.com/channel/videos/satellite/satellite2.swf
			$('div.video #' + viewer).flash({
				src: urlOfSatellitePlayer + "?" + params,
				width: playerWidth,
				height: playerHeight,
				allowFullScreen: true,
				wmode: 'transparent'
			}, { version: '9.0.115' });
*/
		} catch (e) {
			$('div#interactive').html("");
		}
	};

	// This will not load the satelite player again, it will called from
	//  the carousel
	this.startVideoPlayer = function(item, autoPlayVideo) {
		// to resolve the http 500 error
       var itemId  = item;
        if (typeof(assetId) != 'undefined' || typeof(assetId) != 'null' || assetId!='noValue' ) {
               itemId = assetId;
              var j;
			for(j = 0; j < items.length; j++) {
				if(items[j].videoRef == itemId ) {
				    item = j;
					break;
				}

				if(j == itemId ) {
				    item = j;
					break;
				}
			}
            assetId = "null";
        }
        assetId = "null";
		// end to resolve the http 500 error
		if(typeof(item) == "string") {
			var i;
			for(i = 0; i < items.length; i++) {
				if(items[i].videoRef == item) {
				    item = i;
					break;
				}
			}
		}

        if (!this.items[item]) {
            item = 0;
        }
		loadOmniturePageView("tab=tab-Videos&itemRef=" + this.items[item].videoRef, '');

		// video player
		//var viewer = 'viewer' + ((this.currentTab != '') ? '-' + this.currentTab : '');
		//$('div.video #' + viewer ).html('');

		// caption
		var buf = '';
		buf += '<p>' + this.items[item].description + '</p>';//updated for SR-1402
		$('div.video .description').html(buf);

		// history
		var itemId = this.items[item].videoRef || item;
		this.updateHash(itemId);

		// toggle classes
		this.toggleClass(item, 'video');

		// update the picker
		this.updateArrows();

		// update the ads, as long as its not the initial tab video
		if (!this.firstAsset && NGC.ads)
			NGC.ads.update();
		this.firstAsset = false;
		try {

			var videoRef = this.items[item].videoRef;
			var shareURL = window.location.href;

			var x;
			var tokens = shareURL.split("/");

			for(x in tokens)
			{
				if(tokens[x] != "Videos")
				{
					if(tokens[x].indexOf("#tab-Videos") != -1)
					{
						shareURL=shareURL.replace(shareURL.substring(shareURL.indexOf(tokens[x].substring(0))),"Videos/"+videoRef);
					}
				}
				else
				{
					shareURL=shareURL.replace(shareURL.substring(shareURL.indexOf(tokens[x].substring(0))),"Videos/"+videoRef);
					break;
				}
			}

			// Added for SR-787 - End
			this.startVideo(videoRef, shareURL, item);


		} catch (e) {
			$('div#interactive').html("");
		}
	};

	this.startVideo = function(videoRef, shareURL, item) {
	        var player;

			if (navigator.appName.indexOf("Microsoft") != -1) {
				//player = document.getElementById("satellite2");
				player = window["satellite2"];
			}else {
				player = document["satellite2"];
			}

	        if (player != null && player != 'undefined' ) {
	        	player.startVideo(videoRef,shareURL);
			} else {
				// alert('reloading the video player');
				this.updateVideo(item, true);
			}
	}

	// updates just the changing portions of the photo content
	// called by the picker, and on tab content load
	this.updatePhoto = function(item) {
		if(typeof(item) == "string") {
			var i = 0;
			for(i = 0; i < items.length; i++) {
				if(items[i].id == item) {
			        item = i;
					break;
				}
			}
		}

        if (!this.items[item]) {
            item = 0;
        }
		loadOmniturePageView("tab=tab-Photos&itemRef=" + item, '');

		// display image with VCMID
          var itemId  = item;
        if (typeof(assetId) != 'undefined' || typeof(assetId) != 'null' || assetId!='noValue' ) {
               itemId = assetId;
              for(var z = 0; z < items.length;z++) {

                       if(items[z].VCMID == itemId) {
			        item = z;

				}

				if(z == itemId ) {

				    item = z;
					break;
				}

                        var imgPath = this.items[z].image;
			  var subStringPath = imgPath.substring(imgPath.lastIndexOf("/")+1);
			  itemId =itemId.toLowerCase();
			  subStringPath = subStringPath.toLowerCase();
			  if(subStringPath.match(itemId)!= null && itemId.match('.jpg')!= null ) {

				    item = z;
					break;
				}
			}

			assetId = "null";
        }

			assetId = "null";

// end display image with VCMID

		// large photo
		var buf = '';
		buf += '<img src="' + this.items[item].image + '" alt="'+ this.items[item].alt + '" width="' + this.items[item].width + '" height="' + this.items[item].height + '" />';
		var viewer = 'viewer' + ((this.currentTab != '') ? '-' + this.currentTab : '');
		$('div.photo #' + viewer).html(buf);
		// caption/credit
		var buf = '';
		buf += '<p>' + this.items[item].description + '</p>';//updated for SR-1402
		buf += '<span class="photo_credit">' + this.items[item].credit + '</span>';
		$('.tabs-container .description').attr('innerHTML', buf);

		// wallpaper
		var buf = '';
		if (this.items[item].wallpapers && this.items[item].wallpapers.length > 0) {
			for (var i=0; i < this.items[item].wallpapers.length; i++) {
				if (i == 0)
					buf += '<li class="first"><a href="' + this.items[item].wallpapers[i].wallpaper.url + '">' + this.items[item].wallpapers[i].wallpaper.label + '</a></li>';
				else
					buf += '<li><a href="' + this.items[item].wallpapers[i].wallpaper.url + '">' + this.items[item].wallpapers[i].wallpaper.label + '</a></li>';
			}
			$('#downloadwallpaper').show();
		} else {
			$('#downloadwallpaper').hide();
		}

		// history
		var itemId = this.items[item].id || item;
		this.updateHash(itemId);
		$('.tabs-container .wallpaper').attr('innerHTML', buf);

		// toggle classes
		this.toggleClass(item, 'photo');

		// update the picker
		// picker needs to be modified to have selected state and scroll, etc
		this.updateArrows();

		// update the ads, as long as its not the initial tab photo
		if (!this.firstAsset && NGC.ads)
			NGC.ads.update();
		this.firstAsset = false;
	};

	// toggles active classes when a picker item is clicked or back button is pressed.
	// if for some reason the selected item is outside the viewable area (back button, bookmarked) scroll to it
	this.toggleClass = function(item, tab) {
		this.links = $('div.' + tab + ' ul.thumbs li a');
		this.links.each(function(){ $(this).removeClass('selected'); });
		this.link = $(this.links[item]);
		this.link.toggleClass('selected');
		this.getDimensions(tab);
		if (this.selected_thumb_position < this.thumb_wrapper_position) {
			this.prevItem('out_of_range', tab);}
		else if (this.selected_thumb_position > (this.thumb_wrapper_position + this.thumb_container_width)) {
			this.nextItem('out_of_range');
		}

	};

	this.getDimensions = function(active_tab) {
		var tab = ' ';
		if (active_tab) tab = '.' + active_tab + ' ';
		this.selected_thumb_position = parseInt(this.link.position()['left']);
		this.thumb_wrapper_position = parseInt(Math.abs($(tab + 'ul.thumbs').position()['left']));
		this.thumb_wrapper_width = $(this.links[this.links.length-1]).position()['left'];
		this.thumb_container_width = parseInt($(tab + 'div.picker_wrapper').width());
	};

	// update the arrows, enabling or disabled each depending on the number of thumbnails and/or the current thumbnail
	this.updateArrows = function() {
		// handle left arrow
		var left_arrow = $('.tabs-container .picker .left');
		if (this.active <= 0) {
			$(left_arrow).attr("class", "arrow left disabled");
			$(left_arrow).attr("href", "javascript:void(0);");
			$(left_arrow).click(function(){});}
		else {
			$(left_arrow).removeClass("disabled");
			$(left_arrow).attr("href", "javascript:NGC.carousel.prevItem();");
		}

		// handle right arrow
		var right_arrow = $('.tabs-container .picker .right');
		if (this.items.length - this.active <= this.thumbCount) {
			$(right_arrow).attr("class", "arrow right disabled");
			$(right_arrow).attr("href", "javascript:void(0);");
			$(right_arrow).click(function(){});}
		else {
			$(right_arrow).removeClass("disabled");
			$(right_arrow).attr("href", "javascript:NGC.carousel.nextItem()");
		}
	};

	this.updateHash = function(id) {
		var hash = location.hash;
		if (hash == '') {
		    hash = '#'+this.currentTab;
		}
	  if (hash.indexOf('/') >= 0) hash = hash.split('/')[0];
		/*
		if (id != 0) {
			var url = hash.toString() + '/' + id.toString();}
		else {
			var url = hash.toString();
		}
		*/
		var url = hash.toString() + '/' + id.toString();

		if ($.browser.msie) {
			if (url) {
			    url = url.replace('#', '');
			    location.hash = url;
			    $.ajaxHistory.update(url);
			}}
		else if ($.browser.safari) {

			var version= 0;
			var valUserAgent = navigator.userAgent.toLowerCase();
			if (/safari[\/\s](\d+)/.test(valUserAgent)){
				version=new Number(RegExp.$1);
			}

			if (version < 528) {
				// Simply setting location.hash puts Safari into the eternal load state... ugh! Submit a form instead.
				var tempForm = $('<form action="' + url + '"><div><input type="submit" value="h" /></div></form>').get(0); // no need to append it to the body
				tempForm.submit(); // does not trigger the form's submit event...
				$.ajaxHistory.update(url);
			} else {
				location.hash = url.replace('#', '');
				$.ajaxHistory.update(url);
			}
		}
		else {
			if (url) {
				//location.hash = url;
				//location.hash = location.hash.replace('#', '');
				location.hash = url.replace('#', '');
				$.ajaxHistory.update(url);
			}
		}
	};

	// move to the right, by clicking on the right arrow
	this.nextItem = function(out_of_range) {
		var tile_count = this.thumbCount - 1;
		var scroll_width = (this.active + tile_count) * -this.thumbSpace;
		if (this.items.length - (this.active + this.thumbCount) <= this.thumbCount) {
			tile_count = (this.items.length) - (this.active + this.thumbCount);
			scroll_width = this.active * -this.thumbSpace;
			scroll_width = scroll_width + (tile_count * -this.thumbSpace);
		}
		this.active = this.active + tile_count;
		if (out_of_range) {
			scroll_width = $(this.link).position()['left'] - (this.thumbSpace * 3) - 9;
			scroll_width = scroll_width * -1;
			this.active = $(this.link).attr('id').split('thumb')[1] - 3;
			if (this.active + this.thumbCount-1 > this.links.length-1) {
				scroll_width = (this.selected_thumb_position * -1) + this.thumb_container_width - this.thumbSpace + 9 - 2;
				this.active = this.links.length - tile_count;
			}
		}
		$('.tabs-container ul.thumbs').animate({left: scroll_width}, 550);
		this.updateArrows();
		this.getDimensions();
	};

	// move to the left, by clicking on the left arrow
	this.prevItem = function(out_of_range) {
		var tile_count = this.thumbCount - 1;
		var scroll_width = (this.active - (this.thumbCount-1)) * -this.thumbSpace;
		if ((this.active - this.thumbCount) < 0) {
			scroll_width = 0;
		}
		this.active = this.active - tile_count;
		if (this.active < 0) this.active = 0;
		if (out_of_range) {
			scroll_width = $(this.link).position()['left'] - (this.thumbSpace * 3) - 9;
			scroll_width = scroll_width * -1;
			this.active = $(this.link).attr('id').split('thumb')[1] - 3;
			if (this.active < 0) {
				scroll_width = 0;
				this.active = 0;
			}
		}
		$('.tabs-container ul.thumbs').animate({left: scroll_width}, 550);
		this.updateArrows();
	};

	this.activateToolTips = function() {
		$('.tabs-container ul.thumbs li a').each(function() {
			this.onmouseover = function() {
				NGC.carousel.showToolTip(this); };
			this.onmouseout = function() { NGC.carousel.hideToolTip(); };
		});
	};
	this.getVisibleThumbs = function() {
		return $(".picker ul.thumbs li:gt(" + (this.active - 1) + "):lt(" + (this.active + this.thumbCount) + ")");
    }
    this.getToolTip = function() {
		return $('div.' + this.type + ' #tooltip');
    }

	this.showToolTip = function(thumb) {
		// thumb object
		var th = $("#" + thumb.id);
		// list item object
		var li = th.parent();
		// list item group attribute
		var group = li.attr('group');
		// update each list item to un/highlight
		//$(".picker ul.thumbs li").each(function() {
		this.getVisibleThumbs().each(function() {
			if ($(this).attr('group') == group)
				$(this).attr('class', 'highlight');
			else
				$(this).attr('class', '');
		});

		// extract the id number
		var id = thumb.id.substr(5, thumb.id.length - 5);

		// populate the tooltip with appropriate text
		var txt = '<strong>' + this.items[id].group + '</strong> ' + this.items[id].caption;

		//$('#tooltip .inner').html(txt);
		var toolTip = this.getToolTip();
        toolTip.find('.inner').html(txt);
		// determine the x position for the tooltip
		var x = parseInt($(thumb).children("img").css("left"));
		x += parseInt($(thumb).children("img").css("width")) / 2;
		x -= parseInt($('#tooltip').css("width")) / 2;
		x += parseInt($('.picker ul.thumbs').css("left"));
		x += parseInt($('.picker ul.thumbs li a').css("left"));
		x += 49;
		//$('#tooltip').css("left", x);
		toolTip.css("left", x);
		// determine the height for IE
		if ($.browser.msie) {
		    if ($.browser.version < 7) {
    			var ie_height = $('#tooltip .inner').height() + 5;
    			//$('#tooltip').css({height:ie_height});
				toolTip.css({height:ie_height});
		    }
		}
	};

	this.hideToolTip = function() {
		this.getToolTip().css("left", -1000);
        this.getVisibleThumbs().each(function() {
			$(this).attr('class', '');
		});
	};
};


/*--------------------------------------------------
	Episode List Flyout
--------------------------------------------------*/

NGC.Episodes = function() {
	this.init = function() {
		if( $(".upcoming_episode_list_"+NGC.timezone.getTimezoneString()+" ul").size( ) < 1 ) {
			$("div.upcoming_episode_list_"+NGC.timezone.getTimezoneString()).css("display", "none");
			$("div.all_episode_list").css("display", "block");
			$("div.all_episode_list_"+NGC.timezone.getTimezoneString()).css("display", "block");
			$("div.all_episode_list a.upcoming").css("display", "none");
		}

	//fix for defect 7042 -Start
	/*
		$("body").click(function(){
	   	var episodes_list = $(".episodes_list");
	    if ( episodes_list.not(":hidden") ) {
					if ($.browser.msie && $.browser.version.substr(0, 1) == "7")
						episodes_list.hide();
					else
						episodes_list.slideUp(150);
			}
		});
		*/
	//fix for defect 7042 -End

		// timezone content is hidden initially, but we need to make sure in this flyout they will be inline and not block when visible
		$(".episodes_list span.tz-et").each(function() { $(this).css("display", "inline"); });
		$(".episodes_list span.tz-ct").each(function() { $(this).css("display", "inline"); });
		$(".episodes_list span.tz-mt").each(function() { $(this).css("display", "inline"); });
		$(".episodes_list span.tz-pt").each(function() { $(this).css("display", "inline"); });
		$(".episodes_list span.tz-ak").each(function() { $(this).css("display", "inline"); });
		$(".episodes_list span.tz-hi").each(function() { $(this).css("display", "inline"); });

		$("a.toggle_episodes_list").click(function(){
			var show_episodes_list = $(".episodes_list");

			if ( show_episodes_list.is(":hidden") ) {
				if ($.browser.msie && $.browser.version.substr(0, 1) == "7")
					show_episodes_list.show();
				else
					show_episodes_list.slideDown(300);
				return false;
			} else {
				if ($.browser.msie && $.browser.version.substr(0, 1) == "7")
					show_episodes_list.hide();
				else
					show_episodes_list.slideUp(150);
				return false;
			}
		});

		$(".view_options a.all").click(function(){
			var upcoming_episodes = $("div.upcoming_episode_list_"+NGC.timezone.getTimezoneString());
			var all_episodes = $("div.all_episode_list");
	    	var all_episodes_tz = $("div.all_episode_list_"+NGC.timezone.getTimezoneString());

		//	$("div.all_episode_list_"+NGC.timezone.getTimezoneString()).css("display", "block");

		    if ( all_episodes.is(":hidden") || all_episodes_tz.is(":hidden") ) {

		    	upcoming_episodes.hide();
		    	all_episodes.show();
				all_episodes_tz.show();
				//Added for  7003
				$.cookie('all_episodes_userOption', "true");
				$.cookie('upcoming_episodes_userOption', "false");
				return false;
			}else {
		    	all_episodes.hide();
				all_episodes_tz.hide();
				upcoming_episodes.show();
				//Added for  7003
				$.cookie('all_episodes_userOption', "false");
				$.cookie('upcoming_episodes_userOption', "true");
		  	    return false;
			}
		});

		$(".view_options a.upcoming").click(function(){

			//alert("clicking on upcoming");

			var all_episodes = $("div.all_episode_list");
			var all_episodes_tz = $("div.all_episode_list_"+NGC.timezone.getTimezoneString());
	    	var upcoming_episodes = $("div.upcoming_episode_list_"+NGC.timezone.getTimezoneString());

		    if ( upcoming_episodes.is(":hidden")  ) {
				//alert("upcoming is hidden");
		    	all_episodes.hide();
				all_episodes_tz.hide();
		    	upcoming_episodes.show();
				//Ravinder.. 7003
				$.cookie('all_episodes_userOption', "false");
				$.cookie('upcoming_episodes_userOption', "true");
				return false;
			}
		    else {
				//alert("upcoming is not hidden");
		    	upcoming_episodes.hide();
				$.cookie('all_episodes_userOption', "true");
				$.cookie('upcoming_episodes_userOption', "false");
		    	all_episodes.show();
				all_episodes_tz.show();
		  	    return false;}
		});

		// if timezone-specific episode pagers exist, enable pager on each one
		// otherwise just enable the default pager
		/*if ($('span').is('#episodePager-et')) {
			alert("i am inside et");
			$('.all_episode_list').pager('ul', { navId: 'episodePager-et', navClass: 'previous_next', height:'' }, '');
			$('.all_episode_list').pager('ul', { navId: 'episodePager-ct', navClass: 'previous_next', height:'' });
			$('.all_episode_list').pager('ul', { navId: 'episodePager-mt', navClass: 'previous_next', height:'' });
			$('.all_episode_list').pager('ul', { navId: 'episodePager-pt', navClass: 'previous_next', height:'' });
			$('.all_episode_list').pager('ul', { navId: 'episodePager-ak', navClass: 'previous_next', height:'' });
			$('.all_episode_list').pager('ul', { navId: 'episodePager-hi', navClass: 'previous_next', height:'' });
		}*/
		if ($('span').is('#episodePager-'+NGC.timezone.getTimezoneString()) ) {
			//alert("inside if");
			$('.all_episode_list_'+NGC.timezone.getTimezoneString()).pager('ul', { navId: 'episodePager-'+NGC.timezone.getTimezoneString(), navClass: 'previous_next', height:'' });

		}else {
			//alert("inside else");
			$('.all_episode_list').pager('ul', { navClass: 'previous_next', height:'' });

		}

		if ($('span').is('#upComingEpisodePager-'+NGC.timezone.getTimezoneString()) ) {

			//alert("inside the new if");

			$('.upcoming_episode_list_'+NGC.timezone.getTimezoneString()).pager('ul', { navId: 'upComingEpisodePager-'+NGC.timezone.getTimezoneString(), navClass: 'previous_next', height:'' });
		}

	};
};


/*--------------------------------------------------
	Shows List Flyout
--------------------------------------------------*/

NGC.Shows = function() {
	this.init = function() {
		// get rid of the shows list if clicking anywhere else

		// fix for defect 7042
		/*	$("body").click(function(){
			var shows_list = $(".shows_list");
				if ( shows_list.not(":hidden") ) {
						if ($.browser.msie && $.browser.version.substr(0, 1) == "7")
							shows_list.hide();
						else
							shows_list.slideUp(150);
				}
			});
		*/


		// toggle the shows list with the shows button
		$("a.toggle_shows_list").click(function(){
			var shows_list = $(".shows_list");
			if ( shows_list.is(":hidden") ) {
				if ($.browser.msie && $.browser.version.substr(0, 1) == "7")
					shows_list.show();
				else
					shows_list.slideDown(300);
				//shows_list.show();

				// if windows media player exists, hide it
				if (NGC.wmp)
					NGC.wmp.hide();

				return false;
			} else {
				if ($.browser.msie && $.browser.version.substr(0, 1) == "7")
					shows_list.hide();
				else
					shows_list.slideUp(150);

				// if windows media player exists, show it
				if (NGC.wmp)
					NGC.wmp.show();

				return false;
			}
		});
	};
};



/*--------------------------------------------------
	Extend jQuery to load JSON data
--------------------------------------------------*/
jQuery.fn.extend({
	loadJSON: function( url, params, callback ) {
		if ( jQuery.isFunction( url ) )
			return this.bind("loadJSON", url);

		var off = url.indexOf(" ");
		if ( off >= 0 ) {
			var selector = url.slice(off, url.length);
			url = url.slice(0, off);
		}

		callback = callback || function(){};

		// Default to a GET request
		var type = "GET";

		// If the second parameter was provided
		if ( params )
			// If it's a function
			if ( jQuery.isFunction( params ) ) {
				// We assume that it's the callback
				callback = params;
				params = null;

			// Otherwise, build a param string
			} else {
				params = jQuery.param( params );
				type = "POST";
			}

		var self = this;

		// Request the remote document
		jQuery.ajax({
			url: url,
			type: type,
			data: params,
			complete: function(res, status){
				// If successful, inject the HTML into all the matched elements
				if ( status == "success" || status == "notmodified" ) {
					var obj = eval("(" + res.responseText + ")");
					NGC.tabs.render(obj, self.attr("id"));
				}
/*
					// See if a selector was specified
					self.html( selector ?
						// Create a dummy div to hold the results
						jQuery("<div/>")
							// inject the contents of the document in, removing the scripts
							// to avoid any 'Permission Denied' errors in IE
							.append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))

							// Locate the specified elements
							.find(selector) :

						// If not, just inject the full result
						res.responseText );
*/
				// Add delay to account for Safari's delay in globalEval
				setTimeout(function(){
					self.each( callback, [res.responseText, status, res] );
				}, 13);
			}
		});
		return this;
	}
});


/*
jQuery.fn.extend({
	OLDloadJSON: function( url, params, callback, ifModified ) {
		if ( jQuery.isFunction( url ) )
			return this.bind("loadJSON", url);

		callback = callback || function(){};

		// Default to a GET request
		var type = "GET";

		// If the second parameter was provided
		if ( params ) {
			// If it's a function
			if ( jQuery.isFunction( params ) ) {
				// We assume that it's the callback
				callback = params;
				params = null;

			// Otherwise, build a param string
			} else {
				params = jQuery.param( params );
				type = "POST";
			}
		}

		var self = this;
		// Request the remote document
		jQuery.ajax({
			url: url,
			type: type,
			data: params,
			ifModified: ifModified,

			complete: function(res, status){
				if ( status == "success" || !ifModified && status == "notmodified" ) {
					// Inject the HTML into all the matched elements
					try {
						var obj = eval("(" + res.responseText + ")");
						NGC.tabs.render(obj, self.attr("id"));
						// Execute all the scripts inside of the newly-injected HTML and execute callback
						self.evalScripts().each( callback, [res.responseText, status, res] );
					} catch (e) {
						// data did not load correctly or not valid json data
						alert("invalid json data");
					}
				} else {
					callback.apply( self, [res.responseText, status, res] );
				}
			}
		});
		return this;
	}
});
*/


/*--------------------------------------------------
	Newsletter Sign-Up
--------------------------------------------------*/
NGC.Newsletter = function() {
	this.address;
	this.refer;

	this.submit = function() {
		$("#newsletter_thanks").hide();
		this.address = $("#newsletter_email_address").attr('value');
		this.refer = $("#newsletter_referrer").attr('value');
		var formData = "plist_name=NG_Master_List&REFERRING_SITE=" + this.refer + "&campaign_name=NG%20Channel%20Monthly&action_type=Upload&upload_type=merge_replace&check_email_addr=Y&email_addr=" + this.address + "&profile_key=" + this.address;
		if (this.validate()) {
			try {
				// AJAX HERE
				$.ajax({
					type: "POST",
					url: "http://www.nationalgeographic.com/global/cgi-bin/epsilon.pl",
					data: formData,
					success: function(msg) {
						// do nothing for now if a response comes back
					}
				});
			} catch(e) {}
			$("#newsletter_thanks").fadeIn("slow");
			$("#newsletter_email_address").attr('value', '');
			this.address = "";
		}
	};

	// return true if the email address is valid, otherwise return false and display an error
	this.validate = function() {
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(this.address)) {
			this.error();
			return true;
		}
		this.error("Please enter a valid email address.");
		return false;
	};

	// set an error message if str exists or else remove the error message if it doesn't
	this.error = function(str) {
		var err = $("#newsletter_sign_up p.error");
		var input = $("#newsletter_email_address");

		if (str != undefined && str != "") {
			// show the error message
			err.attr("innerHTML", str);
			err.show();
			input.addClass("error");
		} else {
			// hide the error message
			err.attr("innerHTML", "");
			err.hide();
			input.removeClass("error");
		}
	};
};


/*--------------------------------------------------
	Schedule Print
--------------------------------------------------*/
NGC.PrintScheduleClass = function() {
	this.page = "/ngcweb/xmlFeed/printable.jsp";
	this.timezone = "et";
	this.week = 2;

	this.print = function() {
		var tz = NGC.timezone.getTimezoneString();
		var page = this.page + "?timezone=" + tz + "&week=" + this.week;
//		var page = this.page + tz + "/" + this.week;
		window.open(page, "print", "");
	};

	this.updateWeek = function(week) {
		if (week != undefined)
			this.week = week + 1;		// week is zero-based, so add one to make it more intuitive
	};
};

// instance
NGC.printSchedule = new NGC.PrintScheduleClass();

// reference function that is called by the schedule flash movie when the viewport changes
NGC.updateScheduleWeek = function(week) {
	try {
		if (NGC.printSchedule) {
			NGC.printSchedule.updateWeek(week);
		}
	} catch (e) {}
};


/*--------------------------------------------------
	Flash Schedule
--------------------------------------------------*/
NGC.ScheduleFlashClass = function() {
	this.config = "/staticfiles/NGC/StaticFiles/data/init.xml";
	this.startDate;
	this.startTime;

	this.getStart = function() {
		var start = location.hash.replace('#','');

		if (isNaN(start) || start < 0 || start.length < 10) {
			return false;
		}

		// expects hash to contain date time in certain format
		// 200803301800 for March 30, 2008 at 6pm.
		year = start.substr(0,4);
		month = start.substr(4,2);
		day = start.substr(6,2);
		hour = start.substr(8,2);
		min = start.substr(10,2);

		this.setStart(year+'-'+month+'-'+day, hour+':'+min);
	};

	this.setStart = function(startDate, startTime) {
		this.startDate = startDate;
		this.startTime = startTime;
	};

	this.refresh = function( ) {
		if($("div").is("#scheduleflash")) {
			$("div#scheduleflash").empty( );
			this.loadFlash( );
		}
	}

	this.loadFlash = function() {
		if ($("div").is("#scheduleflash")) {
			var flashvars = new Object();
			flashvars.init = this.config;
			if (this.startDate != undefined)
				flashvars.startDate = this.startDate;
			if (this.startTime != undefined)
				flashvars.startTime = this.startTime;
			flashvars.timezone = NGC.timezone.getTimezoneString();

			$('div#scheduleflash').flash({
				src: "/staticfiles/NGC/StaticFiles/flash/grid.swf",
				width: '748',
				height: '550',
				wmode: 'transparent',
				bgColor: '#333333',
				allowFullScreen: 'true',
				flashvars: flashvars
			}, { version: '9.0.115' });
		}
	};
};

NGC.scheduleFlash = new NGC.ScheduleFlashClass();

/*--------------------------------------------------
	Change Window Title
--------------------------------------------------*/
NGC.WindowTitleClass = function() {
	// set the window title to any string
	this.set = function(str) {
		window.document.title = str;
	}
}

NGC.windowTitle = new NGC.WindowTitleClass();

$(document).ready(function() {
//	NGC.windowTitle.set('NGC');
});


/*--------------------------------------------------
	On Tonight (Homepage)
--------------------------------------------------*/
NGC.OnTonight = function() {
//SR-1312  - start
this.init = function() {

		$("div.on_tonight_module_"+NGC.timezone.getTimezoneString()).css("display", "block");
		$("div.on_tomorrow_module_"+NGC.timezone.getTimezoneString()).css("display", "none");

	};
// SR-1312 End

	this.allShows;
	this.visibleShows;



	/*
	this.init = function() {
		try {
			if (onTonight != undefined) {
				this.allShows = onTonight.shows;
				this.findVisible();
				this.draw();
			}
		} catch(e) {}
	};

	this.findVisible = function() {
		var last = this.findLast();
		if (last >= 0) {
			var count = 0;
			this.visibleShows = [];
			for (var i = last - 3; i <= last; i++) {
				if (i >= 0) {
					this.visibleShows.push(this.allShows[i]);
				}
			}
		}
	};

	this.findLast = function() {
		for (var i=0; i < this.allShows.length; i++) {
			var start = parseFloat(this.allShows[i].start);
			var end = parseFloat(this.allShows[i].end);
			if (end == 23 || (start < 23 && end > 23)) {
				return i;
			}
		}
		return -1;
	};

	this.draw = function() {
		var buf = '';
		for (var i=0; i < this.visibleShows.length; i++) {
			var show = this.visibleShows[i];
			buf += '<div class="CAN_BE_ANY_NAME">';
			buf += '<div class="module_content">';
			buf += '<div class="promo">';
			buf += '<a href="' + show.url + '"><img src="' + show.image + '" class="image" alt="' + show.alt + '" /></a>';
			buf += '<div class="overlay">';
			buf += '<h4><a href="' + show.url + '">' + show.name + '</a></h4>';
			buf += '<span class="time" time="' + this.convertToTime(show.start) + '-' + this.convertToTime(show.end) + 'P et"></span>';
			buf += '</div>';
			buf += '</div>';
			buf += '</div>';
			buf += '</div>';
		}
		$("#ontonight").attr("innerHTML", buf);
	};

	this.convertToTime = function(time) {
		if (parseInt(time) == parseFloat(time)) {
			return parseInt(time);
		} else {
			return "" + parseInt(time) + ":30";
		}
	};
	*/
};

/*--------------------------------------------------
	Form Validation
--------------------------------------------------*/
NGC.RegistrationValidationClass = function( ) {
	this.validation;

	// initialize the validation parameters
	this.init = function() {
		var container = $('span.error');
		this.validation = $("#forum_registration").validate({
			errorContainer: container,
			errorLabelContainer: $("span.error", container),
			errorElement: "span",
			rules: {
				username: { required: true, rangeLength: [3, 10] },
				password: { required: true, rangeLength: [6, 8] },
				confirm_password: {  required: true, rangeLength: [6, 8], equalTo: "#password" },
				email:  { required: true, email: true },
				captcha: "required",
				tos: "required"
			},
			messages: {
				username: "Please enter a valid username 3 - 10 characters long.",
				password: "Please enter a valid password 6 - 8 characters long.",
				confirm_password: "We're sorry, but your passwords do not match.",
				email: "Please enter a valid email.",
				captcha: "Please check the characters you entered.",
				tos: "Please agree to the Terms of Service."
			}
		});
	};

	// submit the form if it passes all validation
	this.submit = function() {
		if (this.validation.form())
			$("#forum_registration").submit();
	}
};

NGC.ContactValidationClass = function() {
	this.validation;

	// initialize the validation parameters
	this.init = function() {
		var container = $('span.error');
		this.validation = $("#contact_us").validate({
			errorContainer: container,
			errorLabelContainer: $("span.error", container),
			errorElement: "span",
			rules: {
				first_name: "required",
				last_name: "required",
				email:  { required: true, email: true },
				department: "required",
				subject: "required",
				message: "required"
			},
			messages: {
				first_name: "Please enter your first name.",
				last_name: "Please enter your last name.",
				email: "Please enter a valid email.",
				department: "Please select a department.",
				subject: "Please enter a subject.",
				message: "Please enter your message."
			}
		});
	};

	// submit the form if it passes all validation
	this.submit = function() {
		if (this.validation.form())
			$("#contact_us").submit();
	}
};

NGC.LoginValidationClass = function() {
	this.validation;

	// initialize the validation parameters
	this.init = function() {
		$.validator.messages.required = " ";
		$.validator.messages.rangeLength = " ";
		var container = $('span.error');
		this.validation = $("#user_login").validate({
			errorContainer: container,
			errorLabelContainer: $("span.error", container),
			rules: {
				username: { required: true, rangeLength: [3, 10] },
				password: { required: true, rangeLength: [6, 8] }
			}
		});
	};

	// submit the form if it passes all validation
	this.submit = function() {
		if (this.validation.form())
			$("#user_login").submit();
	}
};

NGC.LoginBtmValidationClass = function() {
	this.validation;

	// initialize the validation parameters
	this.init = function() {
		$.validator.messages.required = " ";
		$.validator.messages.rangeLength = " ";
		var container = $('span.error');
		this.validation = $("#user_login_btm").validate({
			errorContainer: container,
			errorLabelContainer: $("span.error", container),
			rules: {
				username: { required: true, rangeLength: [3, 10] },
				password: { required: true, rangeLength: [6, 8] }
			}
		});
	};

	// submit the form if it passes all validation
	this.submit = function() {
		if (this.validation.form())
			$("#user_login_btm").submit();
	}
};

NGC.ForgotPwdValidationClass = function() {
	this.validation;

	// initialize the validation parameters
	this.init = function() {
		$.validator.messages.required = " ";
		$.validator.messages.email = " ";
		var container = $('span.error');
		this.validation = $("#forgot_password").validate({
			errorContainer: container,
			errorLabelContainer: $("span.error", container),
			rules: {
				email:  { required: true, email: true }
			}
		});
	};

	// submit the form if it passes all validation
	this.submit = function() {
		if (this.validation.form())
			$("#forgot_password").submit();
	}
};

NGC.ResetPwdValidationClass = function() {
	this.validation;

	// initialize the validation parameters
	this.init = function() {
		var container = $('span.error');
		this.validation = $("#reset_password").validate({
			errorContainer: container,
			errorLabelContainer: $("span.error", container),
			errorElement: "span",
			rules: {
				new_password: { required: true, rangeLength: [6, 8] },
				confirm_password: {  required: true, rangeLength: [6, 8], equalTo: "#password" }
			},
			messages: {
				new_password: { required: "Please provide a password", minLength: "Your password must be 6 - 8 characters long." },
				confirm_password: { required: "Please confirm your password", minLength: "Your password must be 6 - 8 characters long.", equalTo: "We're sorry, but your passwords do not match." }
			}
		});
	};

	// submit the form if it passes all validation
	this.submit = function() {
		if (this.validation.form())
			$("#reset_password").submit();
	}
};

NGC.PostValidationClass = function() {
	this.validation;

	// initialize the validation parameters
	this.init = function() {
		$.validator.messages.required = " ";
		var container = $('span.error');
		this.validation = $("#add_post").validate({
			errorContainer: container,
			errorLabelContainer: $("span.error", container),
			errorElement: "span",
			rules: {
				title: "required",
				tags: "required"
			}
		});
	};

	// submit the form if it passes all validation
	this.submit = function() {
		if (this.validation.form())
			$("#add_post").submit();
	}
};

NGC.ThreadValidationClass = function() {
	this.validation;

	// initialize the validation parameters
	this.init = function() {
		$.validator.messages.required = " ";
		var container = $('span.error');
		this.validation = $("#create_thread").validate({
			errorContainer: container,
			errorLabelContainer: $("span.error", container),
			errorElement: "span",
			rules: {
				subject: "required",
				new_thread: "required"
			}
		});
	};

	// submit the form if it passes all validation
	this.submit = function() {
		if (this.validation.form())
			$("#create_thread").submit();
	}
};

NGC.CommentValidationClass = function() {
	this.validation;

	// initialize the validation parameters
	this.init = function() {
		$.validator.messages.required = " ";
		var container = $('span.error');
		this.validation = $("#add_comment").validate({
			errorContainer: container,
			errorLabelContainer: $("span.error", container),
			rules: {
				new_comment: "required"
			}
		});
	};

	// submit the form if it passes all validation
	this.submit = function() {
		if (this.validation.form())
			$("#add_comment").submit();
	}

};

// Community Report Pop Up
NGC.Report = function() {
	this.init = function() {

		$("a.report").click(function(){
			var popup = $(".community div.pop_up");
		   	 if ( popup.not(":hidden") ) {
		         popup.slideUp("fast");
				 return false;}
			});

		$("a.report").click(function(){
		    var popup = $(this).parent().siblings(".community div.pop_up");
		    if ( popup.is(":hidden") ) {
		         popup.slideDown("fast");
				 return false;}
		    else {
				$(this).parent().slideUp("fast");
		  	    return false;}
			});

		$(".community div.pop_up span.button a").click(function(){
			$.post("dummy_url.html", function(data){
				$(this).parent().parent().parent().parent().attr("id");
			});
			$(this).parent().parent().slideUp("fast");
		});
	};
};

/*--------------------------------------------------
	Windows Media Player
--------------------------------------------------*/
NGC.WMPClass = function() {
	// show the player
	this.show = function() {
		$("#MediaPlayer").css("visibility", "visible");
	};

	// hide the player
	this.hide = function() {
		$("#MediaPlayer").css("visibility", "hidden");
	};
};

if ($("#MediaPlayer"))
	NGC.wmp = new NGC.WMPClass();




$.fn.clearForm = function() {
	return this.each(function() {
		var type = this.type, tag = this.tagName.toLowerCase();
			if (tag == 'form')
				return $(':input',this).clearForm();
			if (type == 'text' || type == 'password' || tag == 'textarea')
				this.value = '';
			else if (type == 'checkbox' || type == 'radio')
				this.checked = false;
			else if (tag == 'select')
				this.selectedIndex = -1;
	});
};

/*--------------------------------------------------
	Email Friend Form
--------------------------------------------------*/
NGC.SendToFriendClass = function() {
	this.validation;

	this.formFields;
	this.initialData;

	this.postUrl;

	this.init = function() {
		this.validation = $("#send_to_friend").validate({
			debug: false,
			errorLabelContainer: "span.error",
			errorElement: "span",
			rules: {
				your_email: {
					required: true,
					email: true
				},
				recipient_email: {
					required: true,
					email: true
				},
				message: {
					required: true
				}
			},
			messages: {
				your_email: "Please enter a valid email for your address.",
				recipient_email: "Please enter a valid email for your friend's address.",
				message: "Please enter a short message."
			}
		});

		this.formFields = {
			'your_email': $("#send_to_friend input[name='your_email']"),
			'recipient_email': $("#send_to_friend input[name='recipient_email']"),
			'message': $("#send_to_friend textarea[name='message']")
		};

		this.initialData = {
			'your_email': this.formFields.your_email.val() || '',
			'recipient_email': this.formFields.recipient_email.val() || '',
			'message': this.formFields.message.html() || ''
		};

		this.postUrl = 'http://some.url/that/handles/the/email';
	};

	// function used by jqModel to show div with form
	this.show = function() {
		$("#pop_send_to_friend").jqm({toTop: true}).jqmShow();
		$('html,body').animate({scrollTop: 0}, 100);

		return false;
	};

	this.hide = function() {
		$("#pop_send_to_friend").jqm().jqmHide();

		return false;
	};

	this.another = function() {
		$("#pop_send_to_friend").jqm({toTop: true}).jqmShow();
		$("#pop_send_to_friend_thanks").jqm().jqmHide();

		return false;
	}

	this.isValid = function() {
		return this.validation.form();
	}

	this.submit = function() {
		if (this.isValid()) {
			// put any ajax submit code here
			$.post(this.postUrl, $("#send_to_friend").serialize());

			this.hide();
			$("#pop_send_to_friend_thanks").jqm({toTop: true}).jqmShow();

			// blank out fields in case user wants to send to another friend
			this.formFields.recipient_email.val(this.initialData.recipient_email);
			this.formFields.message.val(this.initialData.message);
		}
		return false;
	};
};

/*--------------------------------------------------
	Remind Me Form
--------------------------------------------------*/
NGC.RemindMeClass = function( ) {

	this.show = function( ) {
		// reset the remind me form
		$("select#date").val("");
		$("input#email").val("");
		$("input#phone").val("");
		$("select#carrier").val("");
		$("input#termsOfUse").attr('checked', '')

		// show the remind me form
		$("#pop_remind_me").jqm({toTop: true}).jqmShow( );

		// if windows media player exists, hide it
		if (NGC.wmp)
			NGC.wmp.hide();
	}

	this.hide = function( ) {
		$("#pop_remind_me").jqm({toTop: true}).jqmHide( );

		// if windows media player exists, show it
		if (NGC.wmp)
			NGC.wmp.show();
	}

	this.display = function(id) {
			$(id + " a.send_another").attr("href",
				"javascript: NGC.remindMe.displayClose('" + id + "');"
			);
			$(id).jqm({toTop: true}).jqmShow( );
	}

	this.displayClose = function(id) {
		$(id).jqm({toTop: true}).jqmHide( );
		this.show( );
	}

	this.init = function( ) {

		var tz = $("a.toggle_timezones span").html( );
		if(tz == "pt") {
			tz = "PT";
		} else {
			tz = "ET";
		}

		$('#timezone').val(tz);

		var rm;
		var l = document.location + "";
		var urlPieces = l.split('?');
		var href = urlPieces[0];

		if(urlPieces[1]) {
			var variables = urlPieces[1].split("&");
			variables = variables[0].split("#");
			for(var i in variables) {
				var pairs = variables[i].split("=");
				if(pairs[0] == "rm") {
					rm = pairs[1];
				}
			}
		}

		if(rm == undefined) {
			rm = -1;
		}

		var h = href + "?rm=";

		$('#successUrl').val(h + "1");
		$('#errorUrl').val(h + "0");

		if(rm == 1) {
			this.display("#pop_remind_me_thanks");
		} else if(rm == 0) {
			this.display("#pop_remind_me_error");
		}
	}

};

NGC.RemindMeValidationClass = function( ) {
	this.validation;

	//added for fix 6785-Start

		$.validator.addMethod('phone', function (value) {
		    return /^[2-9]\d{2}[-.]?\d{3}[-.]?\d{4}$/.test(value);
		}, 'Please enter a valid mobile number.');
		var container = $('span.error');

   //added for fix 6785-End

	// initialize the validation parameters
	this.init = function( ) {

		this.validation = $("#signupForm").validate({
			debug: false,
			errorLabelContainer: container,
			//errorElement: "span",
			rules: {
				email: {
					required: function(element) { return $("#phone").val( ) == "" || $("#email").val( ) != "";},
					email: true
				},
				//added for fix 6785-Start
				phone: {
					required: function(element) { return $("#email").val( ) == "" || $("#phone").val( ) != ""; },
					phone: true
				},
				//added for fix 6785-End
				carrier: {
					required: function(element) { return $("#phone").val( ) != ""; }
				},
				termsOfUse: "required"
			},
			messages: {
				email: "Please enter a valid email.",
				phone: "Please enter a valid mobile number.",
				carrier: "Please select a carrier.",
				termsOfUse: "Please accept the Terms of Service."
			}
		});

	};

	// submit the form if it passes all validation
	this.submit = function( ) {
		if(this.validation.form()) {
			$("#signupForm").submit();
		}
	}

};

/*--------------------------------------------------
	Multi viewer - slideshow
--------------------------------------------------*/
NGC.MultiViewerClass = function() {
	var total = 0;
	var current = 0;
	var slides;

	this.init = function() {
		slides = $('#multiviewer .slide');
		total = slides.length;
		$(slides[0]).show();
		this.updateCount();
		this.updateArrows();
	};

	this.hideSlide = function() {
		$(slides[current]).hide();
	}

	this.showSlide = function() {
		$(slides[current]).show();
		this.updateArrows();
		this.updateCount();
	}

	this.next = function() {
		this.hideSlide();
		if(current >= total - 1)
		{
			current = 0;
		}
		else
		{
			current++;
		}
		this.showSlide();
	}

	this.prev = function() {
		this.hideSlide();
		if(current <= 0)
		{
			current = total-1;
		}
		else
		{
			current--;
		}
		this.showSlide();
	}

	this.updateArrows = function() {

		$('#multiviewer .leftarrow').css('background-position', '0px 0px');
		$('#multiviewer .leftarrow a').attr('href', 'javascript:NGC.multiViewer.prev();');

		$('#multiviewer .rightarrow').css('background-position', '0px 0px');
		$('#multiviewer .rightarrow a').attr('href', 'javascript:NGC.multiViewer.next();');

	}

	this.updateCount = function() {
		$('#multiviewer .count').text((current+1) + ' / ' + total);
	}
};

/*---------------------------------------------------
	RSS subscribe
-----------------------------------------------------*/
NGC.SubScribeClass = function() {
	this.subscribe = function() {
		var tz = NGC.timezone.getTimezoneString();

		if(tz == "ak") {
			tz = "at";
		}
		if(tz == "hi") {
			tz = "ht";
		}
		var page = "/ngcweb/rss/"+ tz + "_atomFeed.xml";
		window.open(page);
	};
	;
};

// instance
NGC.subscribe = new NGC.SubScribeClass();


/*--------------------------------------------------
	onDomReady
--------------------------------------------------*/

$(document).ready(function(){
	// fixes mozillas incorrect font rendering, makes transparency animations not flicker.
	// if ($.browser.mozilla) $('/html/body').css({opacity:.999});

	// Remind Me Form
	if ($("form").is("#signupForm") ) {
		NGC.remindMe = new NGC.RemindMeClass( );
		NGC.remindMe.init( );

		NGC.remindMeValidation = new NGC.RemindMeValidationClass;
		NGC.remindMeValidation.init( );
		NGC.remindMe.validation = NGC.remindMeValidation;
	}

	// Send to friend form
	if ($("form").is("#send_to_friend")) {
		NGC.sendToFriend = new NGC.SendToFriendClass();
		NGC.sendToFriend.init();
	}
	// Registration Form
	if ($("form").is("#forum_registration") ) {
		NGC.registrationValidation = new NGC.RegistrationValidationClass;
		NGC.registrationValidation.init();
	}

	// Contact Us Form
	if ($("form").is("#contact_us") ) {
		NGC.contactValidation = new NGC.ContactValidationClass;
		NGC.contactValidation.init();
	}

	// Login Form - Top
	if ($("form").is("#user_login") ) {
		NGC.loginValidation = new NGC.LoginValidationClass;
		NGC.loginValidation.init();
	}

	// Login Form - Bottom
	if ($("form").is("#user_login_btm") ) {
		NGC.loginBtmValidation = new NGC.LoginBtmValidationClass;
		NGC.loginBtmValidation.init();
	}

	// Forgot Password
	if ($("form").is("#forgot_password") ) {
		NGC.forgotPwdValidation = new NGC.ForgotPwdValidationClass;
		NGC.forgotPwdValidation.init();
	}

	// Reset Password
	if ($("form").is("#reset_password") ) {
		NGC.resetPwdValidation = new NGC.ResetPwdValidationClass;
		NGC.resetPwdValidation.init();
	}

	// Create New Thread
	if ($("form").is("#create_thread") ) {
		NGC.threadValidation = new NGC.ThreadValidationClass;
		NGC.threadValidation.init();
	}

	// Add Comment
	if ($("form").is("#add_comment") ) {
		NGC.commentValidation = new NGC.CommentValidationClass;
		NGC.commentValidation.init();
	}

	// Add Blog Post
	if ($("form").is("#add_post") ) {
		NGC.postValidation = new NGC.PostValidationClass;
		NGC.postValidation.init();
	}

	// Newsletter signup
	NGC.newsletter = new NGC.Newsletter();



	// Flash - NGC Home Page Dynamic Lead
	if ($("div").is("#home_dl") ) {
		fex("dl_data", "home_dl", "dataXML", { src:"/staticfiles/NGC/StaticFiles/flash/dynamic_lead.swf", width:"596", height:"368", wmode:"transparent" });
	}
	//Updated for Portal Template
	if ($("div").is("#interactive_dl") ) {
		fex("dl_data", "interactive_dl", "dataXML", { src:"/staticfiles/NGC/StaticFiles/flash/dynamic_lead_without_off_lead.swf", width:"596", height:"262", wmode:"transparent" });
	}

	// Flash - Themes Dynamic Lead
	if ($("div").is("#themes_dl") ) {
		fex("dl_data", "themes_dl", "dataXML", { src:"/staticfiles/NGC/StaticFiles/flash/dynamic_lead.swf", width:"596", height:"368", wmode:"transparent" });
	}

	// Flash - Screen Saver
	if ($("div").is("#screensaverflash") ) {
		var so = new SWFObject("/staticfiles/NGC/StaticFiles/flash/dss_home_flash_4.swf", "screensaver", "512", "240", "8", "#000000");
		so.addParam("wmode", "transparent");
		so.write("screensaverflash");
	}

	// Flash - Schedule
	/*
	if ($("div").is("#scheduleflash") ) {
		var so = new SWFObject("/staticfiles/NGC/StaticFiles/flash/grid.swf", "grid", "748", "550", "8", "#ffffff"); //width needs to be 748 instead of 750
		so.addParam("bgcolor", "#333333");
		so.addParam("flashvars", "init=/staticfiles/NGC/StaticFiles/data/init.xml");
		so.write("scheduleflash");
	}
	*/

	// Flash - NGC Logo
	if ($("div").is("#ngc_logo") ) {
		var so = new SWFObject("/staticfiles/NGC/StaticFiles/flash/ngc_logo.swf", "ngc_logo", "190", "111", "8", "#ffffff");
		so.addParam("wmode", "transparent");
		so.write("ngc_logo");
	}

	// Flash - Full Screen Interactive
	/*
	if ($("div").is("#interactive") ) {
		var so = new SWFObject("/staticfiles/NGC/StaticFiles/flash/interactive_full.swf", "interactive", "960", "535", "8", "#ffffff");
		so.write("interactive");
	}
	*/

	// Flash - Pop-Up Video
	if ($("div").is("#episode_video") ) {
		var so = new SWFObject("/staticfiles/NGC/StaticFiles/flash/popup_episode.swf", "video", "170", "100", "8", "#ffffff");
		so.addParam("wmode", "transparent");
		so.write("episode_video");
	}

	// Common Elements
	if ($("ul").is(".timezone_list")) {
		// Timezone
		NGC.timezone = new NGC.Timezone();
		NGC.timezone.init();
		NGC.timezone.updateShowTimes();

		// Clock
		//NGC.clock = new NGC.Clock();
		//NGC.clock.update();
	}

	// Schedule Flash
	if (NGC.scheduleFlash)
		NGC.scheduleFlash.loadFlash();

	// Ajax Tabs
	if ($("div").is("#nav_tabs")) {
		NGC.tabs = new NGC.Tabs();
		NGC.tabs.init();
	} else {
		if (NGC.ads)
			NGC.ads.update();
	}

	// Episode List Flyout
	if ($("div").is(".pop_up")) {
		NGC.report = new NGC.Report();
		NGC.report.init();
	}

	// Episode List Flyout
	if ($("div").is(".episodes_list")) {
		NGC.episodes = new NGC.Episodes();
		NGC.episodes.init();
	}

	// On Tonight
	// SR-1312 Start
	if ($("div").is(".on_tonight")) {
		NGC.onTonight = new NGC.OnTonight();
		NGC.onTonight.init();
	}
	// SR-1312 End

	// Shows List Flyout
	if ($("div").is(".shows_list")) {
		NGC.shows = new NGC.Shows();
		NGC.shows.init();
	}

	// PNG Hacks for IE6
	if ($.browser.msie && $.browser.version < 7) {
		$("img[@src$=.png], ul.content_nav li a, ul.content_nav li.tabs-selected a, .rate_this img, .comment_count img").pngfix();
	}

	// Hide Hidden Content
	if ($("div").is(".default_content")) {
		$(".default_content").hide();
	}

	// Show Pop Up Terms of Services
	$("a.show_terms").click(function(){
		var terms = $(".terms_of_service");

	    if (terms.is(":hidden") ) {
	    	terms.show();
			return false;}
	    else {
			terms.hide();
	  		return false;}
		});

	$('span.print_page a').click(function() {
		if (window.print) window.print();
		return false;
	});

	// Theme Browser
	if ($("div").is(".theme_browser")) {
		$("#theme_browser").accordion({
			active: false,
			header: '.head',
			navigation: true,
			event: 'mouseover',
			autoheight: true
		});
	}

	if ($("div").is("#multiviewer")) {
		NGC.multiViewer = new NGC.MultiViewerClass();
		NGC.multiViewer.init();
	}

	//Pop Ups
	try {
		$("#pop_more_info").jqm({trigger: "a.pop_more_info", toTop: true});
		$("#pop_remind_me").jqm({trigger: "a.pop_remind_me", toTop: true});
		$("#pop_remind_me_thanks").jqm({trigger: "a.pop_remind_me_thanks", toTop: true});
		if (NGC.sendToFriend) {
			$("a.pop_send_to_friend").click(function() { return NGC.sendToFriend.show(); });
			$("#send_to_friend span.button a").click(function() { return NGC.sendToFriend.submit(); });
			$("#pop_send_to_friend_thanks a.send_another").click(function() { return NGC.sendToFriend.another(); });
		}
	} catch (e) {}


});

