// Channel Script: ENTERTAINMENT

// DOCUMENT.READY
// 	This function must be kept neat and clean, not to be crowded with assorted functions and triggers.
$(document).ready(function(){
	
	fox.site.channel.loadDocReadyVars(); // store global variables only available on document.ready
	fox.site.channel.genericItems(); // generic triggers
	
	fox.site.channel.calendar.init(); // calendar
	story.init();
	
}); /* end document.ready */

// CHANNEL VARIABLES: Use this object to store global variables used in this channel only
window.channelVars = {};

// 	CHANNEL PRE-LOADER: Channel level loadEvent function
fox.site.loadEventOrig = fox.site.loadEvent;
fox.site.loadEvent = function(componentId) {
	fox.site.loadEventOrig(componentId); // existing functions
	$(componentId).each(function(){
		// main slider
		if ($("div#big-top",this).size()>0) { 
			fox.site.channel.featuredSlider();
		}
		// headlines
		if ($(this).hasClass("generic-list") || $(this).hasClass("composite")) {
			$("h1",this).each(function(){
				fox.site.channel.styleHeadlines($(this));
			});
		}
	});
};

// ----- CHANNEL SPECIFIC FUNCTIONS AND TRIGGERS -----
fox.site.channel = {}; // initialize

// DOC.READY VARIABLES: channel defined variables only available on document.ready
fox.site.channel.loadDocReadyVars = function() {
	var newVars = {
		allImgPath: pagedescriptor.getSiteMeta().static_asset_all_img,										   
		siteImgPath: pagedescriptor.getSiteMeta().static_asset_img,
		vcmid: pagedescriptor.getSiteMeta().vcmid,
		site: pagedescriptor.getSiteMeta().site,
		channel: pagedescriptor.getSiteMeta().channel
	}
	for (i in newVars) { channelVars[i] = newVars[i]; }
};

// GENERIC ITEMS - General channel specific jQuery triggered items
fox.site.channel.genericItems = function() { 
	
	// get count -  pagination
	$(".generic-list.feature-pagination .comment.count:visible").each(function(){
	    var id = $(this).attr('id');
	    var array = id.split(':');
	
	    if(array.length > 1){
	        var type = array[0];
	        var vcmid = array[1];
	        comment.getCount(vcmid, $(this));
	    }
	});
	
	// get count - story
	$(".generic-list .story .comment.count:visible").each(function(){
	    var id = $(this).attr('id');
	    var array = id.split(':');

	    if(array.length > 1){
	        var type = array[0];
	        var vcmid = array[1];
	        comment.getCount(vcmid, $("a",this));
	    }
	});
	
	//channel-logo
	$(".generic-list li.story").each(function(){
		var logo = $("p.channel-name",this).text().toLowerCase().replace(/ /g,'');
		if ($.trim(logo)!='') {
			$("h2 a:first",this).after('<span class="channel-logo channel-logo-' + logo + '"></span>');
		}
	});
	
	// IE6 specific classes
	$(".container").each(function(){
		$(".generic-list.features-horizontal.a, .generic-list.link-list.b, .generic-list.link-list.b",this).each(function(){
			if (siteVars.isIE6) {
				var ie6Class = ($(this).attr("class")).replace(/ +/g,'-')+'-ie6';
				$(this).addClass(ie6Class);
			}
		});
	});

	// Generic lists/composites
	$(".generic-list, .composite").each(function(){
		// headlines - catch headlines not caught on loadEvent
		$("h1",this).each(function(){ 
			fox.site.channel.styleHeadlines($(this));
		});
		$("li",this).find(".more:visible:first").addClass("first");
		//replace the icon span markers with real icons
		$("h2 span.icon.video",this).replaceWith('<img alt="video" class="icon video" src="'+channelVars.siteImgPath+'/camcorder.jpg"/>');
		$("h2 span.icon.freeform2",this).replaceWith('<img alt="freeform2" class="icon freeform2" src="'+channelVars.allImgPath+'/interactive.jpg"/>');
		if (!siteVars.isIE6) { 
			$(".slideshow .format-3 a",this).append('<div class="img-container"><span class="png-template"><img alt="slideshow" src="'+channelVars.allImgPath+'/190x107_launch_slideshow.png"/></span></div>')
		}

		//add popup to video links in generic list
		$("li.video h2 a, li.video .img a, li.video a.video",this).each(function(){
			var href = $(this).attr('href');
		    if(href != null && href.indexOf("http://www.foxnews.com/video2/video08.html") === 0 ){
		    	$(this).click(function(){
		    	    open(href+"&sRevUrl="+window.location.href.toString(),'videoPlayer', 'left=20,top=20,width=877,height=882,status=0,toolbar=0,resizable=0,scrollbars=0,location=0');
		    	  	return false;
		    	});     		
		    }
		});
	});
	
	$('div.feature-carousel-item img.icon').each(function(){
		$(this).css("display", "none");
	})	
	
	// share print
	$(".share-print").click(function () { 
      	var printUrl = this.hash.replace('#','');
	  	window.open(printUrl, 'storyDetailsPrint','width=668,scrollbars=yes,toolbar=no,location=no,menubar=yes,resizable=no'); 
	  	return false; 
    });

	if(siteVars.isIE6) { $('.png-template').remove(); } //we aren't going to support png hacks in IE6

}; /* end generic items */

// headline H1 styling
fox.site.channel.styleHeadlines = function(headline) {
	var htmlObj = headline.get(0);
	if (htmlObj.firstChild==null || typeof(htmlObj)==='undefined') { return; }  // ignore blank h1
	var nodeValue = $.trim(htmlObj.firstChild.nodeValue); // innerHTML will not preserve non-breaking spaces
	var str = '';
	for (n=0;n<nodeValue.length;n++) {
		str += (nodeValue.charCodeAt(n)==160)?'^':nodeValue.charAt(n); // A simple white space replacement won't work in IE
	}
	var delimiter = "^^"; // "Double white spaces"
	var temp = str.split(delimiter);
	if(temp.length > 1) {
		if( temp.length < 3){
			for (x=0;x<temp.length;x++) {
				if(x == 0){ temp[x] = '<strong>' + temp[x] + "</strong>"; } else { break; }
			}
		} else {
			for (x=0;x<temp.length;x++) { 
				if(x == 0){ 
	                 temp[x] = '<span class="initial">' + temp[x] + "</span>";
	             } else if(x == 1){
	                 temp[x] = '<strong>' + temp[x] + "</strong>";
	             } else {
	            	break; 
	             }
			}
		}
		headline.html((temp.join(" ")).replace(/\^/g,' ')); // Clean up 
	}
};

// main slider
fox.site.channel.featuredSlider = function() {
	if ($("#big-top").size() > 0) {
		var tabSwitcher = new TabSwitcher();
		tabSwitcher.initAndRun({
			id: 'big-top',
			hover: true, // This is the boolean for onHover or onClick
			autoplay: true,
			transitionSpeed: 5000 // ms
		});
	}
};

// calendar
fox.site.channel.calendar = {
	init: function() {
		var thisObj = this;
		$(".widget.archive").each(function(){
			$(".calendar",this).each(function(index){
				if(index===0) {
					$(this).datepicker({showOn: 'both', buttonImage: channelVars.siteImgPath + '/calendar.gif', buttonImageOnly: false });
					var startDateObj = null;
					var startDate = window.location.pathname.match(/start-(\d+)/);
					if(startDate!==null) {
						if(startDate.length>1){
							startDateObj = new Date();
							startDateObj.setTime(startDate[1]);
						}
					}
					if(startDateObj!==null) { //if this is a page that has a date string
						$(this).datepicker('setDate', startDateObj);
					} else {
						$(this).datepicker('setDate', 'd');
					}				
				}
			});

			$(".btnbox input").click(function(){
				var calendar = $(this).closest(".archive").find(".calendar");
				if(calendar.length>0){
					var date = $(calendar[0]).datepicker('getDate');
					thisObj.daterange.submit(date);
				}
			});
		});
	},
	daterange: {
		submit: function(startDate) {
			if (window.location.pathname.indexOf("/start-")>0 && window.location.pathname.indexOf("/category")>0) {
				var params = [];
				var upperRangeDate = new Date();
				var dayOffset = 1;

				upperRangeDate.setTime(startDate.getTime() + (dayOffset*(1000 * 60 * 60 *24) ));
				params.push("start-"+startDate.getTime());
				params.push("end-"+upperRangeDate.getTime());

				var url = window.location.pathname.substring(0,window.location.pathname.indexOf("/start-"));
				url = url + "/" + params.join("/") + "/index.html";
				window.location = url;
			} 
			else if (window.location.pathname.indexOf("/archive")>0) {
				var params = [];	
				if(startDate.getTime()>0){
					params.push("publish_date="+startDate.getTime());
				} else {					
					params.push("publish_date="+(new Date().getTime()));
				}							
				var url = window.location.pathname+"?"+params;
				window.location = url;
			}
		}
	}
};
// for daterange deprecated call (used anywhere?)
var widgets = {
	daterange: fox.site.channel.calendar.daterange
};

// ----- CHANNEL GLOBAL SCRIPTS ------
// These are scripts that do not need to be contained in the fox namespace for their simplicity

//Video Player Launch Script
function videoMPlayer(sMPID, sMPlaylistID) {
	var fnDomain = 'http://www.foxnews.com';
	var wNewWindow = window.open(fnDomain + '/video2/video08.html?maven_referralObject='+sMPID+'&maven_referralPlaylistId='+sMPlaylistID+"&sRevUrl="+window.location.href.toString(),'videoPlayer', 'left=20,top=20,width=877,height=882,status=0,toolbar=0,resizable=0,scrollbars=0,location=0'); 
  	return false;
}