// Homepage Script
(function($){

// fox namespace declaration
if (typeof window.fox==="object") {
	window.fox.home = {}; // create home object instance
} else {
	// override any non-object fox declaration. 
	// fox is always the highest object declared namespace convention
	window.fox = { 
		home:{}
	};
}

// DOCUMENT.Ready controller
$(document).ready(function(){
	
	fox.home.initScripts = function() { // special init function to be called
		if ($(document).data("homeScriptLoaded")) { return false; }
		$(document).data("homeScriptLoaded",true);
		

		fox.home.videoIconOverlay.init(); // prioritize video icon overlay
		if (window.location.search.search(/test=/) > -1) {
			document.getElementById("board1-970x66").className = "ad dc";
			document.getElementById("board2-970x66").className = "ad dc";
		}

		fox.home.loadAds();
		fox.home.genericItems();
		fox.home.loadDocReadyVars();
		fox.home.videoPlayer();
		fox.home.onFoxVideoLinks();
		fox.home.PGALeaderBoard(); // ADDED LEADERBOARD TRIGGER CALL
		fox.home.omnitureLoad();
		$("img.unloaded_img").lazyload({ effect: "fadeIn", failurelimit: 50, threshold: 400, effectspeed: 200 });
	    setTimeout(fox.home.headlineTicker, 7000); 
	};
	
	fox.home.initScripts(); // if inline trigger fails
	fox.home.pushDown(); // ipad pushdown

	$('a[rel="external"]').click(function(){
		this.target = "_blank";
	}); 
});

// - On demand function calls
fox.home.loadEvent = function(componentId) {
	$(componentId).each(function(){
		if ($(this).hasClass(".market-snapshot")) {
			fox.widgets.marketSnapShot();
		}
		if( componentId == "#strategyroom"){
			fox.widgets.strategyRoomSchedule();
		}
		if( componentId == "#fox-spotlight"){
			fox.widgets.carousel.spotlight(); // spotlight
		}
		
	});
};

// GENERIC ITEMS: General site specific jQuery triggered items
fox.home.genericItems = function() {
	fox.home.componentTabs($(".component.tabbed-mod")); // tabs
	fox.home.timeStamp.set();
};

// DOC.READY VARIABLES: defined variables only available on document.ready
fox.home.loadDocReadyVars = function() {
	var newVars = {};
	for (i in newVars) { window.siteVars[i] = newVars[i]; }
};

fox.home.loadAds = function() {
	// ads
	if (typeof $.ad!=="undefined") {
		$.ad.init();
	} else {
		showToConsole("[fox.home.loadAds] Ad script not found.");
	}
};

//video icon image overlay
fox.home.videoIconOverlay = {
	init: function() {
		var FS = this;
		this.setBreakingVideo();
		this.setFeatures();
	},
	setBreakingVideo: function() { // Updated breaking video overlay 
		if ($(document).data("breakingVideoHover")) { return false; }
		$(document).data("breakingVideoHover",true);
		var FS = this, elm = $("#breakingVideo");
		var dim = (function(){
			var i, res = fox.home.breakingVideoParser(elm);
			for (i in res) { return res[i]; }
		}());
		
		if (dim) {
			elm.css({ height:dim[1]+"px" });
			elm.find("img").css({ width:dim[0]+"px",height:dim[1]+"px" });
		}
		
		// breaking news video - reduce image size ratio: 35%
		elm.each(function(){ 
			FS.set($(this),0.35,dim); 
		});
	},
	setFeatures: function() {
		var FS = this;
		// features & faces
		$("#features-faces ul:first").find("li.video .media, li.live .media").each(function(){
			FS.set({
				elm: $(this),
				position: "bottom right",
				size: 24,
				useAltImg: true
			});
		});
		// featured videos tab
		$(".section-9 .tabbed-mod > div:eq(1) li .media").each(function(){
			FS.set({
				elm: $(this),
				position: "bottom right",
				size: 24,
				dim: [120,68],
				useAltImg: true
			});
			
		});
	},
	
		setOverlay: function(obj) {
			var elm = obj.elm,
				ratio = obj.ratio || 0.65,
				dim = obj.dim,
				position = obj.position || "center",
				size = obj.size || 118,
				useAltImg = obj.useAltImg,
				altHover = obj.altHover || false;

			var overlaySrc = "http://www.fncstatic.com/static/all/img/vp-overlay"+((useAltImg) ? "-sm" : "")+"${hover}.png";
			function hover(over) {
				over = (altHover) ? ((over) ? false : true) : over;
				return overlaySrc.replace("${hover}",(over) ? "-hover" : ""); 
			}
			function mFloor(val) { return Math.floor(val); }

			function set() {
				var resizeVal = (dim[1] < dim[0]) ? dim[1] : dim[0], // which dimension is shorter
					resize = resizeVal * ratio;
				resize = (resize > size) ? size : resize;
				var imgW = resize, imgH = imgW, ovrL = false, ovrR = false, ovrT = false; ovrB = false, 
					edge = 0.06, edgeW = mFloor(dim[0] * edge), edgeH = mFloor(dim[1] * edge);

				switch(position) {
					case "top right": ovrR = edgeW; ovrT = edgeH; break;
					case "bottom right": ovrR = edgeW; ovrB = edgeH; break;
					case "top left": ovrL = edgeW; ovrT = edgeH; break;
					case "bottom left": ovrL = edgeW; ovrB = edgeH; break;
					default: // center 
						ovrL = Math.floor((dim[0] * 0.5) - (imgW * 0.5));
						ovrT = Math.floor((dim[1] * 0.5) - (imgH * 0.5));
				}

				var css = {};
				if (ovrR) { css.right = px(ovrR); }
				if (ovrL) { css.left = px(ovrL); }
				if (ovrT) { css.top = px(ovrT); }
				if (ovrB) { css.bottom = px(ovrB); }

				css.width = imgW;
				css.minHeight = imgH;

				var overlay = $('<span class="vid-overlay"><img style="position:absolute; display:inline;" src="'+hover()+'"/></span>'),
					titleLink = elm.parent().find("> h3:first");

				function px(val) { return val + "px"; }

				overlay.find("img").css(css);
				elm.find("a").css({ position:"relative" });
				elm.find("img").each(function(){
					var item = $(this), parent = item.parent(), isHover = false;
					parent.css({ display:"block",padding:"0" }).prepend(overlay).click(function(){
						var el = $(this), onclick = el.attr("onclick"), href = el.attr("href"); useEvent = (onclick) ? onclick : href; 
						if (onclick) { eval(onclick); } else { window.location.href = href; }
						return false;
					});
					var overlayElm = parent.find(".vid-overlay"), overlayImg = overlayElm.find("img");
					function hoverOver(over) {
						if (over && !isHover) {
							isHover = true;
							overlayImg.attr("src",hover(true));
						} else if (isHover) {
							isHover = false;
							overlayImg.attr("src",hover());
						}
					}

					titleLink.hover(function(){ hoverOver(true); },function(){ hoverOver(); });
					parent.hover(function(){ hoverOver(true); },function(){ hoverOver(); });
				});
			}

			var hoverImg = new Image();
			hoverImg.src = hover(true);
			set();
		}
};

fox.home.breakingVideoParser = function(elm) {
		var obj = false;
	
	function trigger(item) {
		var x, cname = item.attr("class"), arr = cname.split(" "), target = false;
		for (x = 0; x < arr.length; x++) {
			if (arr[x].indexOf("video-holder-")===0) { target = arr[x]; break; }
		}
		if (!target) { return false; }
		arr = ($.trim(target)).split("-");
		var dim = arr[arr.length-1].split("x");
		obj = (!obj) ? {} : obj;
		obj[target] = dim;
	}
	
	if (elm) {
		elm.find("div[class^='video-holder-']:first").each(function(){ trigger($(this)); });
	} else {
		$("div[class^='video-holder-']").each(function(){ trigger($(this)); });
	}
	return obj;
};


//start component tabs
fox.home.componentTabs = function(tabElm) {
	tabElm = tabElm || false;
	if (!tabElm) { return false; }
	
	var config = {
		show: 1, // 1st item
		controlActiveClass: "active"
	};
	
	tabElm.each(function(){
		var tab = $(this);
		if (tab.data("initialized")) { return false; } // don't initialize more than once
		
		var controller = tab.find("> ul.controller:first"), controls = controller.children(), sections = tab.children("div.section");
		config.show = (function(showDefault){
			var ret = 1;
			if (controller.attr("class").indexOf("active-tab-")>0) {
				var x, target = false, arr = controller.attr("class").split(" ");
				for (x = 0; arr.length; x++) { 
					if (arr[x].indexOf("active-tab-")>-1) { target = arr[x]; break;}
				}
				if (target) { target = target.split("-")[2]; ret = (isNaN(target)) ? ret : target; }
			}
			return parseInt(ret,10);
		}(config.show));
		
		function tabImagePreloader(target) {
			target.find("img").each(function(){
				var item = $(this), src = item.attr("pre-src"), img = new Image();
				if (src && !item.data("preloaded")) {
					img.onload = function() { item.attr("src",src); };
					img.src = src;
					item.data("preloaded",true);
				}
			});
		}
		
		controls.each(function(i){
			var item = $(this), aTag = item.find("a");

			aTag.click(function(){ // set click event
				if (typeof sections[i]!=="undefined") {
					if (tab.data("index")===i) { return false; } // don't re-trigger if it is the same tab
					
					controls.filter(function(z){ // set classes
						if (z!==i) { 
							$(this).removeClass(config.controlActiveClass);
						} else {
							$(this).addClass(config.controlActiveClass);
						}
					});
					
					sections.filter(function(z){ 
						if (z===i) { tabImagePreloader($(this)); }
						$(this).css("display",(z!==i)?"none":"block"); 
					}); // set section
					tab.data("index",i); // store current index
				} else {
					showToConsole("[fox.home.componentTabs] No associated content (index:"+(i+1)+")");
				}
				return false;
			});

			// trigger show
			if (config.show===i+1) { aTag.click(); }
		});
		tab.data("initialized",true); // set element as initialized
	});
	
};
//end component tabs

function showToConsole(str) {
	if (typeof window.console==='object') { console.log(str); }
}

})(jQuery);
