// Channel Script: OPINION

$(document).ready( function() {
	fox.site.channel.loadDocReadyVars(); // store global variables only available on document.ready
	fox.site.channel.genericItems(); // generic triggers
	story.init();
});

// 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(){
		if ($("#video-main",this).size()>0) {
			fox.widgets.accordion.init();
		}
		// 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 = {
		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() {
	
	$(".america .top").wrap("<a href='http://www.thefoxnation.com/'></a>");
	
	$(".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];
	        if(type==="dpm") {
	        	comment.getCount(vcmid, $(this));
	        }
	    }
	});
	
	$(".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];
	        if(type === "dpm"){
	        	comment.getCount(vcmid, $(this).find('a'));
	        }
	    }
	});
	
	if (siteVars.isIE6) { // IE6 specific classes
		$(".container").each(function(){
			$(".generic-list.features-horizontal.a, .generic-list.link-list.b, .generic-list.link-list.a",this).each(function(){
				var ie6Class = ($(this).attr("class")).replace(/ +/g,'-')+'-ie6';
				$(this).addClass(ie6Class);
			});
		});
		
		
		$(".channel-bar.sub-navigation .generic-list.link-list.b ul li",this).each(function(){
			$(this).addClass("channel-bar-sub-navigation-generic-list-link-list-b-ie6");
		});
		
		//we aren't going to support png hacks in IE6
		$('.png-template').remove();
	}
	
    //do stuff to generic list elements in first pass
	$(".generic-list, .composite, .accordion").each(function(){
		//remove rounded bottom corners
		$("ul.ui-accordion li",this).removeClass('ui-corner-bottom');
		// 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"/>');
		
		//add popup to video links in generic list
		$("li.video h2 a, li.video .img a, ul.ui-accordion a",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",this).css("display","none");
		
		$(".link-list.popupdeck li > a",this).hoverIntent({
			interval: 400,
			timeout: 1300,
			over: function() {
				var popup = $(this).siblings('.popup:first');
				var parent = $(this).parent();
				
				$(popup).addClass("hovering");
				$(popup).one("mouseenter",function(){
					$(this).data('hovering','true');
				});
				$(popup).one("mouseleave", function(){
					$(this).data('hovering','false').removeClass("hovering");
					$(this).unbind();
				});
			
			},
			out: function() {
				var popup = $(this).siblings('.popup:first');
				var parent = $(this).parent();

				if(popup.data('hovering')!=='true') {
					popup.removeClass("hovering");
					popup.unbind();
				}
			}
		});
	});

	
	$(".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; 
    });
	
	try { 
		var pageTracker = _gat._getTracker("UA-3128154-2"); 
		pageTracker._setDomainName(".foxnews.com"); 
		pageTracker._trackPageview(); 
	} 
	catch(err) {
		// fail silently
	}
};

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) {
		for (x=0;x<temp.length;x++) {
			 if (x==0) {
                 temp[x] = '<strong class="word-group-1">'+temp[x]+"</strong>";
             } else if (x==1) {
                 temp[x] = '<span class="word-group-2">'+temp[x]+"</span>";
             }
		}
		headline.html((temp.join(" ")).replace(/\^/g,' ')); // Clean up
	} else {
		if ($(headline.children()).size()==0) { // pre-formatted items have children
			headline.html( "<strong>"+str+"</strong>" );
		}
	}
}

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