if(typeof window.IGN === "undefined" || !window.IGN){ IGN = {}; }

IGN.HeroUnit = function(){
	var AUTOSCROLL_DELAY = 			4000,	// autoscroll delay before switching

		FADE_IN_SPEED = 			800,	// speed at which text whill hide
		FADE_OUT_SPEED = 			800,	// speed at which text whill display
		THUMB_HOVER_DELAY = 		25,

		selectedThumb,				// points to current selected thumb in dom
		selectedContent,			// points to current selected content in dom
		selectedIntervalThumb,		// setInterval ID for thumb

		lastVidNum,

		thumbHoverDelayId,

		FADE_OVERLAY = 'fade-overlay';		// classname for fade overlay
		
	// hide and show related text box.
	var show = function(target, anim){
		if(anim){
			$j(target).fadeIn(anim);
		}else{
			$j(target).fadeIn(FADE_IN_SPEED);
		}
	}

	// will transition from curr selected element to next element
	var showNext = function(next, curr, anim){

		if(curr){
			if(anim){
				$j(curr).fadeOut(anim);
			}else{
				$j(curr).fadeOut(FADE_OUT_SPEED);
			}
		}
		show(next, anim);

		selectedContent = next;
	}

	/* 
	 * swaps the current displayed image and text to next
	 */
	var swapContent = function(next, curr, anim){
		// do not swap if next and curr are the same element
		if(!curr || next.attr('id') !== curr.attr('id')){
			showNext(next, curr, anim);
		}
	}
	var resetView = function(el){
		$j(el).css('display', 'none');
	}
	var autoScroll = {
		// pointer to interval id for setInterval()
		intervalId : null,
		resumeLast : 0,
		_list : $j('#top-stories > .wrapper-thumbs > .thumbs > li'),
		start : function(num, noDelay){
			num = (num && num < autoScroll.length()) ? num : 0;
			var list = autoScroll._list,
				length = autoScroll.length();
			var initStart = function(){
				if(length > 0){
					num = num % length;
					next($j('a > img', $j(list[num])), false);
					num++;
					autoScroll.resumeLast = num;
				}
			}
			if(!autoScroll.intervalId){
				if(noDelay){
					initStart();
				}
				autoScroll.intervalId = setInterval(initStart, AUTOSCROLL_DELAY);
			}
		},
		stop : function(){
			clearInterval(autoScroll.intervalId);
			autoScroll.intervalId = null;
	    },
		pause : function(){
			autoScroll.stop();	
		},
		resume : function(){
			autoScroll.start(autoScroll.resumeLast || 0);	
		},
		reset : function(){
			autoScroll.stop();	
			autoScroll.start();	
		},
		length : function(){
			return this._list.length;
		}
	};

	// adds selected class to thumbnail
	var selectThumb = function(el){
		if(!selectedThumb || $j(el).attr('id') !== $j(selectedThumb).attr('id')){
			$j(selectedThumb).parent().parent().removeClass('selected');
			$j(el).parent().parent().addClass('selected');
			selectedThumb = el;
		}
	}

	//
	var next = function(aId, anim){
		selectThumb(aId);
		var nextSelectedContent = $j("#"+decodeIdValue($j(aId).parent('a').attr('id')));
		swapContent(nextSelectedContent, selectedContent, anim);
	}

	var decodeIdValue = function(id){
		if(id){
			return id+"l";
		}
	}
	
	// creates the overlay used for doign fake fade
	var createFadeOverlay = function(){
		var fade = document.createElement('div');
		fade.className = FADE_OVERLAY;	
		$j('#top-stories > .content').prepend($j(fade));
	}

function hideVideoPlayer(){
	$j("#hul-video, #hul-video-age, .hul-video-back").hide();
	$j('a > img', $j("#hu"+lastVidNum+"l")).show();
	$j(".wrapper-thumbs > .thumbs .item-thumb").show();		
	$j("#hu"+lastVidNum+"l").removeClass('selected');
	if (typeof($f())!='undefined'&&typeof($f().pause())!='undefined') {$f().pause();}
	}
	
function showVideoPlayer(vidNum,params,minAge){
	IGN.HeroUnit.pause();
	lastVidNum=vidNum;
	$j("#hu"+vidNum+"l").addClass('selected');
	$j('a > img', $j("#hu"+vidNum+"l")).hide();
	userAge = csReadCookie("VPage");
	if (minAge == 0 || (userAge != null && userAge >= minAge)) {
		$j("#hul-video-age").hide();
		$j(".wrapper-thumbs > .thumbs .item-thumb").hide();
		$j("#hul-video").html("");
		$j("#hul-video,#hu"+vidNum+"l-video-back").show();

		$j.getJSON("http://api.ign.com/tt/global_embed_config.t?"+params+"&pagetype=mediavideo_embed_channel&content-type=application%2Fx-javascript&callback=?",function(config){
			$f("hul-video",{src:"http://media.ign.com/ev/embed.swf",wmode:"transparent"},config);
			});

	} else {
		$j("#hul-video-age,#hu"+vidNum+"l-video-back").show();
		$j(".wrapper-thumbs > .thumbs .item-thumb").hide();	
		$j("#agFormAgeGate").attr("value", minAge); 
		$j("#agFormvidNum").attr("value", vidNum); 
		$j("#agFormparams").attr("value", params); 
		if (userAge != null && userAge < minAge){
			$j('#ageGateText').attr('style','color: red').html('You have entered a restricted birth date.<br/><br/>');
			$j('#ageGateOptions').attr('style','display:none;');
		}
	}
}

function getAge(userBirthday){
		var bd = new Date(userBirthday);
		var today = new Date();

		var yeardiff = today.getFullYear() - bd.getFullYear();
		var monthdiff = today.getMonth() - bd.getMonth();
		var daydiff = today.getDate() -  bd.getDate();

		if (yeardiff < 0){return -1} //born in the future. come with me if you want to live.
		if (monthdiff < 0){
			return yeardiff-=1;
		}
		else if((monthdiff == 0) && (daydiff < 0)){
			yeardiff-=1;
		}
		return yeardiff;
	}

function csReadCookie(name){
 		var nameEQ = name + "=";
		var val = document.cookie.split(';');
		for(var i=0;i < val.length;i++) {
			var c = val[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return parseInt(c.substring(nameEQ.length,c.length));
		}
		return null;
 }

function csSetCookie(name, value, days){
	 	var v = value;
		var expires =new Date();
        expires.setDate(expires.getDate()+days);
		if (days !=null){
			document.cookie = name +"=" +escape(v)+"; expires="+expires.toGMTString() +"; domain=ign.com; path=/";
		}else{
			document.cookie = name +"=" +escape(v)+"; domain=ign.com; path=/";
		}
 } 
 
	
	$j(document).ready(function(){
	$j('#vidSubmitAge').click(function(){
	    var chk = /^\d+$/;
		var mm = $j(".agemm").val();
		var dd = $j(".agedd").val()
		var yyyy = $j(".ageyyyy").val();
		var age = getAge(mm+'/'+dd+'/'+yyyy);
		var ageGate = $j("#agFormAgeGate").val();
		if(mm > 12 || dd > 31 || yyyy < 1910 || mm == '' || dd =='' || yyyy == ''|| !chk.test(mm) || !chk.test(dd)|| !chk.test(yyyy)){
			$j('#ageGateText').attr('style','color: red').html('Please enter a valid birth date (MM-DD-YYYY).<br/><br/>')
		}else{
			csSetCookie("VPage",age,null);
			if (age < ageGate){
				$j('#ageGateText').attr('style','color: red').html('You have entered a restricted birth date.<br/><br/>')
				$j('#ageGateOptions').attr('style','display:none;')
			}else{
				showVideoPlayer($j("#agFormvidNum").val(),$j("#agFormparams").val(),0);
			}
	  	}
	});	
	});

	return {
		autoScroll : autoScroll,
		pause : autoScroll.pause,
		resume : autoScroll.resume,
		reset : autoScroll.reset,
		showPlayer : showVideoPlayer,
		hidePlayer : hideVideoPlayer,
		
				   /*
		config : {
			set : function(o, v){
				if(o == "INACTIVE_THRESHOLD"){
					INACTIVE_THRESHOLD = v;
				}else if(o == "IMAGE_GROW_WIDTH"){
					IMAGE_GROW_WIDTH = v;
				}else if(o == "IMAGE_GROW_HEIGHT"){
					IMAGE_GROW_HEIGHT = v;
				}else if(o == "IMAGE_SHRINK_WIDTH"){
					IMAGE_SHRINK_WIDTH = v;
				}else if(o == "IMAGE_SHRINK_HEIGHT"){
					IMAGE_SHRINK_HEIGHT = v;
				}else if(o == "IMAGE_SHRINK_STEP_SIZE"){
					IMAGE_SHRINK_STEP_SIZE = v;
				}else if(o == "IMAGE_GROW_STEP_SIZE"){
					IMAGE_GROW_STEP_SIZE = v;
				}else if(o == "TEXT_HIDE_SPEED"){
					TEXT_HIDE_SPEED = v;
				}else if(o == "TEXT_SHOW_SPEED"){
					TEXT_SHOW_SPEED = v;
				}else if(o == "AUTOSCROLL_DELAY"){
					AUTOSCROLL_DELAY = v;
				}
			},
			get : function(o){
				if(o == "INACTIVE_THRESHOLD"){
					return INACTIVE_THRESHOLD;
				}else if(o == "IMAGE_GROW_WIDTH"){
					return IMAGE_GROW_WIDTH;
				}else if(o == "IMAGE_GROW_HEIGHT"){
					return IMAGE_GROW_HEIGHT;
				}else if(o == "IMAGE_SHRINK_WIDTH"){
					return IMAGE_SHRINK_WIDTH;
				}else if(o == "IMAGE_SHRINK_HEIGHT"){
					return IMAGE_SHRINK_HEIGHT;
				}else if(o == "IMAGE_SHRINK_STEP_SIZE"){
					return IMAGE_SHRINK_STEP_SIZE;
				}else if(o == "IMAGE_GROW_STEP_SIZE"){
					return IMAGE_GROW_STEP_SIZE;
				}else if(o == "TEXT_HIDE_SPEED"){
					return TEXT_HIDE_SPEED;
				}else if(o == "TEXT_SHOW_SPEED"){
					return TEXT_SHOW_SPEED;
				}else if(o == "AUTOSCROLL_DELAY"){
					return AUTOSCROLL_DELAY;
				}
			},
			create : function(id){
				function getValue(id){
					return parseInt(document.getElementById(id).value);
				}
				var click = function(name){
					return function(){
						IGN.HeroUnit.config.set(name, getValue(name));
					}
				}
				var createOne = function(name){
					var b = document.createElement('input');
					b.type = "button";
					b.value = name;
					b.onclick = click(name);
					var i = document.createElement('input');
					i.type = "text";
					i.maxlength = 5;
					i.id = name; 
					i.value = IGN.HeroUnit.config.get(name);
					return [b, i];
				}
				var names = ["AUTOSCROLL_DELAY", "IMAGE_GROW_WIDTH", "IMAGE_GROW_HEIGHT", "IMAGE_SHRINK_WIDTH", "IMAGE_SHRINK_HEIGHT", "IMAGE_SHRINK_STEP_SIZE", "IMAGE_GROW_STEP_SIZE", "TEXT_HIDE_SPEED", "TEXT_SHOW_SPEED"];
				var container = document.getElementById(id);
				for(var i = 0; i < names.length; i++){
					var one = createOne(names[i]);
					container.appendChild(one[0]);
					container.appendChild(one[1]);
					container.appendChild(document.createElement('br'));
				}
			}
		},
	   */
		/*
		// todo: START remove after demmo
		init2 : function(startThumb){
			var show = startThumb || 0;
			var stories = $j('#top-stories > .wrapper-thumbs > .thumbs > li > a')
			for(var i = 0, len = $j(stories).length; i < len; i++){
				var dataId = $j("#"+$j(stories[i]).attr('title'));
				if(i !== show){
					resetView(dataId);
				}else{
					//resetView(dataId);
					next($j('img', stories[i]), true);
					//IGN.HeroUnit.autoScroll.start(i);
				}
			}
	    },
		*/
		// todo: END remove after demmo
		init : function(startThumb){
			if(!$j('#top-stories').length){
				return false;
			}
			//createFadeOverlay();
			var show = startThumb || 0;
			var stories = $j('#top-stories > .wrapper-thumbs > .thumbs > li > a')
			for(var i = 0, len = $j(stories).length; i < len; i++){
				var value = decodeIdValue($j(stories[i]).attr('id'));
				var dataId = $j("#"+value);
				resetView(dataId);
			}
			IGN.HeroUnit.autoScroll.start(show, true);

			/*
			$j('#fe1, #fe2, #fe3, #fe4, #fe5, #fe6').mouseover(function(e){
				autoScroll.stop();
				next(this, false);
			});
			*/
			$j('#top-stories > .wrapper-thumbs > .thumbs > li').mouseover(function(e){
				var that = this;
				thumbHoverDelayId =	setTimeout(
					function(){
						autoScroll.stop();
						next($j('a > img', that), 400);
					}, THUMB_HOVER_DELAY);
			});
			$j('#top-stories > .wrapper-thumbs > .thumbs > li').mouseout(function(e){
					clearTimeout(thumbHoverDelayId);
			});
			
	    }
	};
}();
IGN.HeroUnit.init();

function updateCompanionAd(HTMLResource,clickThrough)
{
                var aleft = '<a href=';
                var aright = ' target="_blank"><img src="'+HTMLResource+'" ></a>';
                document.getElementById('medRecContainer').innerHTML = aleft+clickThrough+aright;
}
function update300x250(HTMLResource,clickThrough,width,height)
{
var elementId = "ADIframe";
var iframe = document.getElementById(elementId);
iframe.src = clickThrough;
iframe.width = width;
iframe.height = height;
}
function updateTrackerFromPlayer(HTMLResource,ww,hh)
{
                document.getElementById('tracker').innerHTML = HTMLResource;
}
function updateUrlFromPlayer( url )
{
                var newUrl = 'URL: '+url;
                document.getElementById('trackerUrl').innerHTML = newUrl;
}
function fetchReferrer()
{
                return document.referrer;
}
function fetchDocumentUrl()
{
                return document.location.href;
}
function prerollClick(url) {
                newwindow=window.open(url,'_blank');
                if (window.focus) {newwindow.focus()}
}
function RUTest() {
                return false;
}
function isNewVideoSession() {
                if ( csReadIGNVideoCookie("newIGNVideoSession") == null ) {
                                csSetIGNVideoCookie("newIGNVideoSession","1");
                                return true;
                }
                return false;
}
function csReadIGNVideoCookie(name) {
                var nameEQ = name + "=";
                var val = document.cookie.split(';');
                for(var i=0;i < val.length;i++) {
                                var c = val[i];
                                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                                if (c.indexOf(nameEQ) == 0) return parseInt(c.substring(nameEQ.length,c.length));
                }
                return null;
}
function csSetIGNVideoCookie(name, value) {
                document.cookie = name +"=" +escape(value)+"; domain=ign.com; path=/";
}

//IGN.HeroUnit.config.create('config');

