// NGC namespace
var NGC = {};


/*--------------------------------------------------
	Timezone
--------------------------------------------------*/

NGC.Timezone = function() {
	this.accTimezones = {"5":"et","6":"ct","7":"mt","8":"pt","9":"ak","10":"hi"};
	this.defTimezone = "5";
	
	this.init = function() {
		this.findTimezone();
		this.setupPicker();
		$("body").click(function(){
			var timezone = $("ul.timezone_list");
			if ( timezone.not(":hidden") ) {
				$("a.toggle_timezones").removeClass("on");
		    	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("ngc");
		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("ngc");
		if (!cookie_value) {
			var offset = this._getTimezoneOffset();
			if (this.accTimezones[offset]) {this.setCookie(offset);} 
			else {this.setCookie(this.defTimezone);}
		}
		this.userTimezone = $.cookie("ngc");
		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");
	    	timezone_list.slideDown("fast");
				return false;}
	    else {
	    	timezone_list_bg.removeClass("on");
				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");
			$("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;

		// ET
		if (NGC.timezone.getTimezoneString() == "et") { show = true; } else { show = false; }
		$(".tz-et").each(function() { show ? $(this).show() : $(this).hide(); });

		// CT
		if (NGC.timezone.getTimezoneString() == "ct") { show = true; } else { show = false; }
		$(".tz-ct").each(function() { show ? $(this).show() : $(this).hide(); });

		// MT
		if (NGC.timezone.getTimezoneString() == "mt") { show = true; } else { show = false; }
		$(".tz-mt").each(function() { show ? $(this).show() : $(this).hide(); });

		// PT
		if (NGC.timezone.getTimezoneString() == "pt") { show = true; } else { show = false; }
		$(".tz-pt").each(function() { show ? $(this).show() : $(this).hide(); });

		// AK
		if (NGC.timezone.getTimezoneString() == "ak") { show = true; } else { show = false; }
		$(".tz-ak").each(function() { show ? $(this).show() : $(this).hide(); });

		// HI
		if (NGC.timezone.getTimezoneString() == "hi") { show = true; } else { show = false; }
		$(".tz-hi").each(function() { show ? $(this).show() : $(this).hide(); });

		/*
		$(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("ngc", number);
	};
	
	// 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);
		}
	};
};


/*--------------------------------------------------
	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") ) {
				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();
	};
	
	// 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;
		}

		// render differently based on data (tab) type
		switch(this.dataObj.type) {
			case "overview":
				this.renderOverviewContent();
				break;
			case "videos":
				this.renderVideoContent();
				break;
			case "photos":
				this.renderPhotoContent();
				break;
			case "interactive":
				this.renderInteractiveContent();
				break;
			case "generic":
				this.renderGenericContent();
				break;
			default:
				alert("json data type not recognized");
				break;
		}

		// 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 = [];
		
		// 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">';

		// 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]);
			}
		}

		// only draw the carousel if there is more than 1 image
//		if (items.length > 1) {
			NGC.carousel = new NGC.Carousel(items, "photo", this.currentTab);
			buf += NGC.carousel.render();
//		}

		// close the main div
		buf += '</div>';
		
		// 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">';
		
		// video player
		buf += '<div id="viewer-' + this.currentTab + '" class="viewer">';
		buf += '</div>';
		
		// 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]);
			}
		}
		
		// only draw the carousel if there are more than 1 image
//		if (items.length > 1) {
			NGC.carousel = new NGC.Carousel(items, "video", this.currentTab);
			buf += NGC.carousel.render();
//		}
		
		// 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);
			// 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'
			});
		} catch (e) {
			$('div#interactive').html("Please download flash [ADD PROPER NO FLASH MESSAGE HERE]");
		}
	};
	
	// 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'
			});
		} catch (e) {
			$('#overview_flash').html("Please download flash");
		}
	};

	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) {
			buf += '<div class="next_episode_airing">';

			// display thumbnail image if it exists
			buf += '<div class="episode_preview">';
			if (obj.episode_info.image) {
				buf += '<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 + '" />';
			}
			buf += '</div>';
			
			// display the episode info
			buf += '<div class="episode_info">';
				buf += '<span class="button"><a href="javascript:NGC.remindMe.show();" class="remind_me">Remind Me</a></span>';
				buf += '<span class="title">' + obj.episode_info.name + '</span>';
				buf += '<h2 class="episode">' + obj.episode_info.title + '</h2>';
				var tz = NGC.timezone.getAllTimezones();
				for (var i=0; i < obj.episode_info.time.length; i++) {
					buf += '<span class="time_actual tz-' + tz[i] + '">' + obj.episode_info.time[i] + '</span>';
				}
				buf += '<p>' + obj.episode_info.body + '</p>';
			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;
		
		// 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>';
		}
		
		// browse episodes
		buf += '<div class="browse_episodes">';
		buf += '<span class="button"><a href="' + obj.episode_info.nextlink + '" class="next">Next</a></span>';
		buf += '<span class="button"><a href="' + obj.episode_info.prevlink + '" class="previous">Prev</a></span>';
		buf += '<label>Browse Episodes</label>';
		buf += '</div>';
		
		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);
				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.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">';
				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.updateVideo(' + i + '); 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">';
				
				// 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);
			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) {
		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;
        }

		// video player
		var viewer = 'viewer' + ((this.currentTab != '') ? '-' + this.currentTab : '');
		$('div.video #' + viewer ).html('');
		try {
			// load the satellite player
			var params ="";
			var adSite = "ngc";
			var adZone = "ngc_videos_test";
			var allowShare = "true";
			var autoPlay = "true";
			var videoRef = this.items[item].videoRef;
			var shareURL = "";
			var playerHeight = "";
			var playerWidth = "";
			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 += "&shareHeaderTextColor="+shareHeaderTextColor;

			loadSatellitePlayer(viewer,params);
			
			/*
			$('div.video #viewer').flash({
				src: "/channel/grey-headers/flash/video.swf?adSite=ngc&allowShare=true&autoPlay=true&playerHeight=" + this.items[item].height + "&playerWidth=" + this.items[item].width + "&adZone=FPO&videoRef=" + this.items[item].videoRef,
				width: this.items[item].width,
				height: this.items[item].height,
				wmode: 'transparent'
			});
			*/
		} catch (e) {
			$('div#interactive').html("Please download flash [ADD PROPER NO FLASH MESSAGE HERE]");
		}
		
		// caption
		var buf = '';
		buf += '<p>' + this.items[item].caption + '</p>';
		$('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
		if (NGC.ads)
			NGC.ads.update();
	};

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

		// 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].caption + '</p>';
		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
		if (NGC.ads)
			NGC.ads.update();
	};
	
	// 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) {
			    location.hash = url;
			    $.ajaxHistory.update(url);
			}}
		else if ($.browser.safari) {
			// 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 {
			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.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() {
			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);
		// 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);
		
		// determine the height for IE
		if ($.browser.msie) {
		    if ($.browser.version < 7) {
    			var ie_height = $('#tooltip .inner').height() + 5;
    			$('#tooltip').css({height:ie_height});
		    }
		}
	};
	
	this.hideToolTip = function() {
		$('#tooltip').css("left", -1000);
		$(".picker ul.thumbs li").each(function() {
			$(this).attr('class', '');
		});
	};
};

		
/*--------------------------------------------------
	Episode List Flyout
--------------------------------------------------*/

NGC.Episodes = function() {
	this.init = function() {
		$("body").click(function(){
	   	var episodes_list = $(".episodes_list");
	    if ( episodes_list.not(":hidden") ) {
	    	episodes_list.slideUp(150);   	
			}
		});
		
		// 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") ) {
		    	show_episodes_list.slideDown(300);
				return false;}
		    else {
		    	show_episodes_list.slideUp(150);   	
		  	    return false;}
		});
		
		$(".view_options a.all").click(function(){ 
			var upcoming_episodes = $("div.upcoming_episode_list");
	    	var all_episodes = $("div.all_episode_list");
	    	   	
		    if ( all_episodes.is(":hidden") ) {
		    	upcoming_episodes.hide();
		    	all_episodes.show();
				return false;}
		    else {
		    	all_episodes.hide();
				upcoming_episodes.show();
		  	    return false;}
		});
		
		$(".view_options a.upcoming").click(function(){ 
			var all_episodes = $("div.all_episode_list");
	    	var upcoming_episodes = $("div.upcoming_episode_list");

		    if ( upcoming_episodes.is(":hidden") ) {
		    	all_episodes.hide();
		    	upcoming_episodes.show();
				return false;}
		    else {
		    	upcoming_episodes.hide();
		    	all_episodes.show();
		  	    return false;}
		}); 
		
		$('.all_episode_list').pager('ul', {
			navClass: 'previous_next'
		});	
	};
};


/*--------------------------------------------------
	Shows List Flyout
--------------------------------------------------*/

NGC.Shows = function() {
	this.init = function() {
		// get rid of the shows list if clicking anywhere else
		$("body").click(function(){
	   	var shows_list = $(".shows_list");
			if ( shows_list.not(":hidden") ) {
	    		shows_list.hide();
			}
		});
		
		// toggle the shows list with the shows button
		$("a.toggle_shows_list").click(function(){ 
			var shows_list = $(".shows_list");
			if ( shows_list.is(":hidden") ) {
		    	shows_list.show();
				return false;
			} else {
				shows_list.hide();
				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;
	}
});


/*-----------------------------------------------
	Ad Swapping
-----------------------------------------------*/
NGC.AdClass = function() {
	this.init = function(w, h, adSite, adZone, theme, syncID, tile, adframe) {
		//frm = $('iframe#' + adframe);
		if (frm = document.getElementById("adframe0")) {
			frm.arg = {};
			frm.arg.foo = "bar";
			frm.w = w;
			frm.h = h;
			frm.adSite = adSite;
			frm.adZone = adZone;
			frm.theme = theme;
			frm.syncID = syncID;
			frm.tile = tile;
			frm.src = "/ngcweb/ad.html";
			alert(frm.arg);
		}
	};
	
	this.update = function(adZone, syncID) {
		$('div.ad iframe').each(function() {
			try {
				var temp = this.src;

				// replace the adzone if it changed
				if (adZone != undefined)
					temp = temp.replace(/\&adZone=[^\&]*\&/gi, "&adZone=" + 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;
	};
};

NGC.ads = new NGC.AdClass();
NGC.refreshAds = NGC.ads.update;		// simpler public method for updating the ads

/*--------------------------------------------------
	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 = "/channel/grey-headers/data/init.xml";
	this.startDate;
	this.startTime;
	
	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 so = new SWFObject("/channel/grey-headers/flash/grid.swf", "grid", "748", "550", "8", "#ffffff"); //width needs to be 748 instead of 750
			so.addParam("bgcolor", "#333333");
			so.addParam("wmode", "transparent");

			// add config data source
			var flashvars = "init=" + this.config;
			
			// add start date if it exists
			if (this.startDate != undefined)
				flashvars += "&startDate=" + this.startDate;
				
			// add start time if it exists
			if (this.startTime != undefined)
				flashvars += "&startTime=" + this.startTime;
			
			// add timezone
			flashvars += "&timezone=" + NGC.timezone.getTimezoneString( );
			
			//alert(flashvars);
			
			so.addParam("flashvars", flashvars);
			so.write("scheduleflash");
		}
	};
};

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() {
	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");
		});
	};
};

/*--------------------------------------------------
	Remind Me Form
--------------------------------------------------*/

$.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;
	});
};



NGC.RemindMeClass = function( ) {

	this.show = function( ) {
		$("#pop_remind_me").jqm({toTop: true}).jqmShow( );
		this.validation.validation.resetForm( );
	}
	
	this.hide = function( ) {
		$("#pop_remind_me").jqm({toTop: true}).jqmHide( );
	}
	
	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( ) {
		
		this.lacy = "lacy";
		
		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.remindMe = new NGC.RemindMeClass( );

NGC.RemindMeValidationClass = function( ) {
	this.validation;

	// initialize the validation parameters
	this.init = function( ) {
		
		this.validation = $("#signupForm").validate({
			debug: false,
			errorLabelContainer: "span.error",
			errorElement: "span",
			rules: {
				email: {
									required: function(element) { return $("#phone").val( ) == "" || $("#email").val( ) != "";},
									email: true
								},
				phone: {
									required: function(element) { return $("#email").val( ) == "" || $("#phone").val( ) != ""; }
								},
				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( );
	}
	
};

/*--------------------------------------------------
	onDomReady
--------------------------------------------------*/

$(document).ready(function(){
	// fixes mozillas incorrect font rendering, makes transparency animations not flicker.
	// if ($.browser.mozilla) $('/html/body').css({opacity:.999});
	
	// Registration Form
	if ($("form").is("#signupForm") ) {
		NGC.remindMeValidation = new NGC.RemindMeValidationClass;
		NGC.remindMeValidation.init( );
		NGC.remindMe.validation = NGC.remindMeValidation;
		NGC.remindMe.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();
	
	// On Tonight
	NGC.onTonight = new NGC.OnTonight();
	
	// Flash - NGC Home Page Dynamic Lead
	if ($("div").is("#home_dl") ) {
		fex("dl_data", "home_dl", "dataXML", { src:"/channel/grey-headers/flash/dynamic_lead.swf", width:"596", height:"368", wmode:"transparent" });
	}
	
	// Flash - Themes Dynamic Lead
	if ($("div").is("#themes_dl") ) {
		fex("dl_data", "themes_dl", "dataXML", { src:"/channel/grey-headers/flash/dynamic_lead.swf", width:"596", height:"368", wmode:"transparent" });
	}
	
	// Flash - Screen Saver
	if ($("div").is("#screensaverflash") ) {
		var so = new SWFObject("/channel/grey-headers/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("/channel/grey-headers/flash/grid.swf", "grid", "748", "550", "8", "#ffffff"); //width needs to be 748 instead of 750
		so.addParam("bgcolor", "#333333");
		so.addParam("flashvars", "init=/grey-headers/data/init.xml");
		so.write("scheduleflash");
	}
	*/
	
	// Flash - NGC Logo
	if ($("div").is("#ngc_logo") ) {
		var so = new SWFObject("/channel/grey-headers/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("/channel/grey-headers/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("/channel/grey-headers/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();
	}
	
	// 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();		
	}

	// 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;}
		});
	
	// Theme Browser
	if ($("div").is(".theme_browser")) {
		$("#theme_browser").accordion({
			active: false,
			header: '.head',
			navigation: true,
			event: 'mouseover',
			autoheight: true
		});
	}

	//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});
		$("#pop_send_to_friend").jqm({trigger: "a.pop_send_to_friend", toTop: true});
		$("#pop_send_to_friend_thanks").jqm({trigger: "a.pop_send_to_friend_thanks", toTop: true});
	} catch (e) {}
});
