// from NICK.com min/base
var NICK = NICK || {};
NICK.utils = {};

NICK.utils.hideSwfs=function(a){
	if(a){
			a=a+" ";
		}
	else{
			a="";
		}
	$(a+".swf").not(".swfnohide").find("> *").each(function(){
		obj=$(this);
		obj.css("visibility","hidden");
	})
};


NICK.utils.showSwfs=function(a){
	if(a){
			a=a+" ";
		}
	else{
			a="";
		}
	$(a+".swf > *").each(function(){
		obj=$(this);
		obj.css("visibility","visible");
	})
};



// from NICK.com - homepage-promo.js
var hppItemCount = 0, hppCurrentItem = 0;
var hppStarted = false;
var hppContainer, hppNavigation, hppNavigationScroller, hppNavigationBullets, hppNavigationBar;
var hppNavigationWhiteout, hppNavigationFiller, hppNavigationItems;
var hppTimer = 0, hppAutoPlayedFirst = false, hppFirstVideoRef = null;
var hppVidIsPlaying = false, hppPlayingFlash = false;

// Don't start the homepage promo unit until the page is fully ready
window.onload = function() {
	hppStart();
}

$(document).ready(function() {
	// jQuery Shortcuts
	hppContainer          = $(".homepage-promo-container");
	hppNavigation         = hppContainer.children(".homepage-promo-navigation");
	hppNavigationScroller = hppNavigation.children(".homepage-promo-scroller");
	hppNavigationHover    = hppNavigation.children(".homepage-promo-hover");
	hppNavigationBullets  = hppNavigation.children(".homepage-promo-bullets");
	hppNavigationBar      = hppNavigation.children(".homepage-promo-bar");
	hppNavigationBarFade  = hppNavigation.children(".homepage-promo-barfade");
	hppNavigationFillers  = hppNavigation.children(".homepage-promo-fillers");
	hppNavigationWhiteout = hppContainer.find(".homepage-promo-whiteout");
	hppNavigationItems    = hppContainer.find(".homepage-promo-item");
	hppLoader             = hppContainer.find(".homepage-promo-loader");

	// Determine the item count
	hppItemCount = hppNavigationItems.size();

	// Replace Fonts
	/* DA - KCA -  don't do font replacement if we can't control string length + need support for other characters */
	/*
	NickLog.info("Homepage Promo: Replacing default fonts with the FontGenerator");
	$(".NickPromoFont", hppContainer).each(function() {
		size = $(this).parent().is(".font-medium") ? 36 : 30;
		$(this).replaceWith($((new FontGenerator()).create($(this).text(), size)));
	});
	*/
	if ( hppItemCount == 0 ) {
		hppContainer.remove();
	} else if ( hppItemCount == 1 ) {
		hppNavigation.remove();
	} else {
		// Create events to stop timer when hovering over the promo area
		$(hppContainer).hover(hppStopTimer, hppStartTimer);
		
		// Create Navigation Based on total items
		var bulletContainerWidth = (hppItemCount * hppNavigationScroller.width());
		hppNavigationBullets.css( "width", bulletContainerWidth );
		hppNavigationFillers.width(bulletContainerWidth);
		hppNavigationBar.css({
			left: bulletContainerWidth,
			width: hppContainer.width() - bulletContainerWidth - hppNavigationBarFade.width()
		});

		// Apply click event to navigation items
		hppNavigationBullets.bind("mousemove mouseleave click", function(e) {
			var position = e.pageX - $(this).offset().left;
			var item = Math.ceil(position / (hppNavigationBullets.width() / hppItemCount));
	
			switch( e.type ) {
				case "click":
					hppScrollTo( item );
					hppStartTimer();
					break;
				case "mousemove":
					if ( hppCurrentItem != item ) {
						hppNavigationHover.css("left", ((item - 1) * hppNavigationHover.width()) + 5);
						break;
					}
				case "mouseleave":
					hppNavigationHover.css("left", -999999);
					break;
			}
		});

		// Hide white out
		hppNavigationWhiteout.css("opacity", 0);
	}
	
	hppContainer.find(".homepage-related-links span").click(function(e) {
		e.preventDefault();
		document.location = $(this).attr("href");
	});
	
	// Apply Video Click Events
	$(".homepage-promo-video-thumb").click(hppInitVideo);

	// Never let Thumbnail or Video hit the anchor tag
	$("#homepage-promo-video-wrapper").live("click", function(e) {
		e.stopImmediatePropagation();
		return false;
	});

	// If it hasn't loaded within 3.5 seconds, load it anyway.
	setTimeout(function() {
		hppStart();
	}, 3500);
	
	
	$(document).bind("PlayerEvent.ON_MEDIA_ENDED", hppVideoEnd);
	$(document).bind("PlayerEvent.ON_READY", hppPlayFirstVideo);
});

function hppStart() {
	if ( hppStarted == false ) {
		hppLoader.remove();
	
		if ( hppItemCount > 1 ) {
			// Begin timer
			hppStartTimer();
		}
	
		// Scroll to first item
		hppScrollTo(1);
		hppStarted = true;
	}
}

function hppScrollTo( i ) {
	$("#homepage-promo-video-wrapper").html("");
	if ( i > hppItemCount || i < 1 || hppCurrentItem == i ) {
		return false;
	}

	// Hide flash elements
	NICK.utils.hideSwfs(".homepage-promo-container");
	$(".homepage-promo-flash-wrapper", hppNavigationItems).empty();

	hppCurrentItem = i;
	hppNavigationWhiteout.css("display", "block").animate( { opacity: 1	}, "fast");
	hppNavigation.addClass("homepage-promo-animating");
	/*hppNavigationBar.css("opacity",1);*/
	hppNavigationScroller.stop().animate({
		left: ((i - 1) * hppNavigationScroller.width()) + 5
	}, "slow", function() {
		hppNavigation.removeClass("homepage-promo-animating");
		/*hppNavigationBar.css("opacity", 0.6);*/
		hppNavigationItems.addClass("homepage-promo-item-hidden")
		hppNavigationItems.eq(i - 1).removeClass("homepage-promo-item-hidden");
		hppNavigationWhiteout.animate( { opacity : 0 }, "fast", function() {
			$(this).css("display", "none");
			NICK.utils.showSwfs(".homepage-promo-container");
		});
		
		var item = hppNavigationItems.eq(hppCurrentItem - 1);

		if ( item.is(".homepage-promo-item-flash") ) {
			var link = item.find(".homepage-promo-flash-link").text();
			var wrap = item.find(".homepage-promo-flash-wrapper");
			var id   = wrap.attr("id") + "-object";
			var newc = $("<div />").attr("id", id).appendTo(wrap);
			swfobject.embedSWF(link, id, "772", "288", "9.0.0","expressInstall.swf", {}, { wmode: "transparent", allowScriptAccess: "always" }, {});
			hppPlayingFlash = true;
			hppStopTimer();
		}

		// If this is the first video in the list, auto play it
		if ( hppNavigationItems.eq(hppCurrentItem - 1).is(".homepage-promo-item-video:first") && hppAutoPlayedFirst == false ) {
			hppNavigationItems.eq(hppCurrentItem - 1).find(".homepage-promo-video-thumb").click();
			hppAutoPlayedFirst = true;
		} else {
			$(".homepage-promo-video-thumb").show();
		}
	});
}

function hppFlashPromoEnd() {
	hppPlayingFlash = false;
	hppNextItem();
	hppStartTimer();
}

function hppPlayFirstVideo() {
	if ( hppFirstVideoRef != null ) {
		hppFirstVideoRef.hide();
		$("#homepage-promo-video-wrapper").css("opacity", 1);
	}
}

function hppStartTimer() {
	// If a video is playing, don't ever start the timer
	if ( hppPlayingFlash || ($("#homepage-promo-video-wrapper").html() != null && $("#homepage-promo-video-wrapper").html() != "") ) {
		return false;
	}

	hppStopTimer();
	hppTimer = setInterval( function() { hppNextItem(); }, 5000);
}

function hppNextItem() {
	if ( hppCurrentItem == hppItemCount ) {
		hppScrollTo(1);
	} else {
		hppScrollTo(hppCurrentItem + 1);
	}
}

function hppStopTimer() {
	clearInterval( hppTimer );
	hppTimer = null;
}

function hppInitVideo(e) {
	// Stop Propagation & Timer (Both of these are EXTREMELY important)
	e.stopImmediatePropagation();
	hppStopTimer();

	// Move Video Wrapper to current Item
	$("#homepage-promo-video-wrapper").remove();
	$("<div />").attr("id", "homepage-promo-video-wrapper").insertAfter( $(this) );

	var timg = $(this).find("img");
	var vid = $(this).attr("id").substring(21);
	var pid = "homepage-promo-video";

	//run the player off the proper stage environment
	var hostName = window.location.toString();
	var hostPathName = window.location.pathname.toString();
	//var feedHub = "home";
	//var playerEnvironment = "media.nick.com";	
	/*if ((hostName.indexOf("localhost") > 0) || (hostName.indexOf("-d") > 0) || (hostName.indexOf("-jd") > 0)) {
		playerEnvironment = "media.nick-d.mtvi.com";
	}	
	if ((hostName.indexOf("-q") > 0) || (hostName.indexOf("-jq") > 0)) {
		playerEnvironment = "media.nick-q.mtvi.com";
	}*/
	
	/*player hub reporting value
	if (hostPathName.indexOf("/videos") > 0) {
		feedHub = "videos";
	}
	if (hostPathName.indexOf("/shows") > 0) {
		feedHub = "shows";
	}	
	if (hostPathName.indexOf("/music") > 0) {
		feedHub = "music";
	}	
	if (hostPathName.indexOf("/games") > 0) {
		feedHub = "games";
	}	*/
	
	//adfree is now handled in the PMT
	//if(KIDS.get("adfree") === 'true') {
	//	doRegisterSwf(pid ,'http://' + playerEnvironment + '/mgid:cms:item:nick.com:' + vid,'homepage-promo-video-wrapper','10','256px','342px',{sid:'Nick__Homepage',configParams:'site%3Dnick%26playerName%3DtoutPlayerNormal%26adRuleSet%3DnoAds%26demo%3Dnull%26clickableVideoScreen%3Dfalse%26feedHub%3D' + feedHub},'false','false','/dynamo/javascript/swfobject/expressinstall.swf','/common/detect/get_flash.jhtml',{wmode:"opaque",salign:"TL",allowScriptAccess:"always",swliveconnect:"false"},{name:pid,id:pid});
	//} else {
		doRegisterSwf(pid ,'http://media.nick.com/mgid:cms:video:nick.com:' + vid,'homepage-promo-video-wrapper','10',timg.height() + 'px',timg.width() + 'px',{sid:'Nick__Homepage'},'false','false','/dynamo/javascript/swfobject/expressinstall.swf','/common/detect/get_flash.jhtml',{wmode:"opaque",salign:"TL",allowScriptAccess:"always",allowFullScreen:"true",swliveconnect:"false"},{name:pid,id:pid});
	//}	
		
	NICK.videoPlayer.init(pid);

	// Never let Thumbnail or Video hit the anchor tag
	$("#homepage-promo-video-wrapper *").click(function(e) {
		e.preventDefault();
		e.stopImmediatePropagation();
	});

	if ( hppAutoPlayedFirst == true ) {
		$(this).hide();
	} else {
		$("#homepage-promo-video-wrapper").css("opacity", 0);
		hppFirstVideoRef = $(this);
	}

	return false;
}

function hppVideoEnd() {
	$("#homepage-promo-video-wrapper").remove();
	$(".homepage-promo-video-thumb").show();
	hppStartTimer();
	hppNextItem();
}
