/**
 * Site Code:
 */
$(document).ready( function() {
	var allImgPath = pagedescriptor.getSiteMeta().static_asset_all_img;											   
	var siteImgPath = pagedescriptor.getSiteMeta().static_asset_img;
	var vcmid=pagedescriptor.getSiteMeta().vcmid;
	var site=pagedescriptor.getSiteMeta().site;
	var channel=pagedescriptor.getSiteMeta().channel;	
	var isIE6 = ($.browser.version == "6.0" && $.browser.msie); 

	
	$('.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));
	    }

	});
	
	$('.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, $(this).find('a'));
	    }

	});
	
	//channel-logo
	$('.generic-list li.story h2 span.icon.story').each(function(){
	    var logo = $(this).parent().parent().parent('li.story').children('span.channel-logo');
	   $(this).replaceWith(logo);
	   
	});
	
	$(".widget.archive")
		.find(".calendar").each( function(index){
		
			if( index === 0 ){
				$(this).datepicker({showOn: 'both', buttonImage: siteImgPath + '/calendar.gif', buttonImageOnly: false });
				
				var startDateObj = null;
				
				var startDate = 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');
				}
				
			} 
			
			/*
			if( index === 1 ){
				$(this).datepicker({showOn: 'both', buttonImage: siteImgPath + '/calendar.gif', buttonImageOnly: false });
				$(this).datepicker('setDate', '-1d');
			}
			*/
			
		}).end()
		
		.find('.btnbox input').bind("click", function(){
			
			var calendar = $(this).closest('.archive').find(".calendar");
			
			if(calendar.length > 0){
				var date0 = $(calendar[0]).datepicker('getDate');
				
				widgets.daterange.submit(date0);
				
			}

		});

	renderWeather();
	
	$('.container .generic-list.features-horizontal.a, .container .generic-list.link-list.b, .container .generic-list.link-list.a')
	
		.each( function(){
	
			if(isIE6){
			    var ie6Class = ($(this).attr('class'));
			    ie6Class = ie6Class.replace(/ +/g, '-');
			    $(this).addClass(ie6Class + '-ie6');
			}

		})
	.end();
	
	//story.initDetailPanel( $('div.story-container:first') );

    //do stuff to generic list elements in first pass
	$('.generic-list, .composite')
	
		
	
		.find('h1').each(function(){
			genericlist.wrapHeadlinesFirstWord($(this));
		}).end()
		
		//replace the icon span markers with real icons
		.find('h2 span.icon.video').replaceWith('<img alt="video" class="icon video" src="' + siteImgPath+ '/camcorder.jpg"/>').end()
		.find('.slideshow .format-3 a').filter(function(){ return !isIE6; }).append('<span class="png-template"><img alt="slideshow" src="' + allImgPath + '/190x107_launch_slideshow.png"/></span>').wrap('<div class="img-container"></div>').end().end()
		//.find('h2 span.icon.teaser').replaceWith('<img alt="teaser" class="icon teaser" src="' + allImgPath+ '/interactive.jpg"/>').end()
		.find('li').find('.more:visible:first').addClass('first').end().end()
		
		//add popup to video links in generic list
		.find('li.video h2 a, li.video .img a, li.video a.video').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="+location.href.toString(),'videoPlayer', 'left=20,top=20,width=877,height=882,status=0,toolbar=0,resizable=0,scrollbars=0,location=0');
		    	  return false;
		    	});     
		
		    }

		}).end()
		
		.filter(function(){return $(this).is('.link-list.popupdeck'); }).find('li > a')
			.hoverIntent({ 
				
				interval:400,
				timeout:1300,
				over:function(){
					$popup = $(this).siblings('.popup:first');
			    	$parent = $(this).parent();
			    	
					$popup.addClass("hovering");
					
					$popup.one('mouseenter', function(){
						$(this).data('hovering', 'true');
					});
					
					$popup.one('mouseleave', function(){
						$(this).data('hovering', 'false');
						$popup.removeClass("hovering");
						$(this).unbind();
					});
				
				}, out:function(){
					$popup = $(this).siblings('.popup:first');
					$parent = $(this).parent();

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

				} })
		
		.end();
	
	$(".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; 
    });
	story.init();
	genericlist.featuredSliderBigTop();
	
	if(isIE6){
		//we aren't going to support png hacks in IE6
		$('.png-template').remove();
	}
	
 });



//TODO: move this into fnc namespace, fnc.widgets.daterange
var widgets = new Object();
widgets.daterange = {
		submit : function(startDate){
			
			if( location.pathname.indexOf("/start-") > 0 && location.pathname.indexOf("/category") > 0){
				
				var params = new Array();
				
				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 = location.pathname.substring(0,location.pathname.indexOf("/start-") );
				url = url + "/" + params.join("/") + "/index.html";
				//console.log(url);
				document.location = url;
			}
			else if(location.pathname.indexOf("/archive") > 0){
				
				var params = new Array();	
				
				if(startDate.getTime() > 0){
					params.push("publish_date=" + startDate.getTime());
				}
				else
				{					
					params.push("publish_date=" + (new Date().getTime()));
				}							
				
				 var url = location.pathname + "?" + params;
				document.location = url;
			}

		}
		
};




//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;
}

var genericlist = new Object();
genericlist.wrapHeadlinesFirstWord = function($container){
	var htmlObj = $container.get(0);
	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; 
	             }
			}
		}
		$container.html((temp.join(" ")).replace(/\^/g,' ')); // Clean up 
	}
};

genericlist.featuredSliderBigTop = function(){
	
	function rotateBt() {
		if( btCounter == $('#big-top ul li').size() ) {
			btCounter = 0;
			btRotate = false;
		}
		featureBtItem($('#big-top ul li:eq(' + btCounter + ') h2 a'));
		btCounter++;
		startTimeout(5000);
	}
	function startTimeout(t) {
		clearTimeout(btTimeout);
		if(btRotate) {
			btTimeout = setTimeout("rotateBt()",t);
		}
	}
	$('#big-top').mouseenter(function(){ clearTimeout(btTimeout); });
	$('#big-top ul li img:eq(0)').fadeIn(100);
	$('#big-top > p > span').html($('h2.selected').html());
	if( jQuery.browser.msie ) {
		$('#big-top ul li h2 a span.title').each(function() {
			$(this).css('display','block').css('padding-top',($(this).parent('a').height() - $(this).height()) / 2);
		});
		$('#big-top ul li h2 a span.deck').each(function() {
			$(this).css('display','none');
		});
		try { document.execCommand("BackgroundImageCache", false, true); } catch(err) {}
	}
	$('#big-top ul li h2 a').mouseover(function(){
			featureBtItem(this);
	});
	startTimeout(7000);

};

fox.site.parentBottomInit = fox.site.bottomInit;
fox.site.mediaNet = {
	
	init : function() {
		utils.runJsCodeAfterThisScriptTag("fox.site.mediaNet.mediaInit();");
		
	},
	
	mediaInit : function(){

		 // Top X
        var mndigital_widgets = new Array();
        var widget;
        widget = new Object();
        widget.mnd_widgetid = "3M5N2K5O5WOZN84D9BV3";
        widget.mnd_divid = "mndigital_topx";
        widget.mnd_max_results = "10";    //  current limit is 99; common scenarios: 5, 10, 20, 40
        widget.mnd_artistbio_url = "http://"+location.host+"/entertainment/music/media/index.html";   // for shell page; note specification of index.html
        //widget.mnd_ploginid = "";     // if user is logged in, pass in UserID here
        //widget.mnd_test = "on";    // only turn on if have developers outside US
        widget.mnd_show_explicit = "false";
        widget.mnd_width = 329; 
        widget.mnd_auto_play = "false"; 
        widget.mnd_inline_buy = "true";    // Turn on the inline (rather than overlay) buy panel, default is false
        widget.mnd_custom_CSS = "true";   // declare that you have a custom CSS in your webpage, default is false

        mndigital_widgets[0] = widget;

        // Media Explorer
         widget = new Object();
        widget.mnd_widgetid = "JRD38ABLAI4DJUL6495S";
        widget.mnd_divid = "mndigital_medx";
        //widget.mnd_ploginid = "";     
        widget.mnd_width = 600;
        widget.mnd_custom_CSS = "true";   // declare that you have a custom CSS in your webpage, default is false
        widget.mnd_show_explicit     = "false";
        mndigital_widgets[1] = widget;

        // Media Matcher - this is intended only for article pages. We believe you want it either/or the Top X
        widget = new Object();
        widget.mnd_widgetid          = "DK6OZAENEN2W9FMGWN2F";
        widget.mnd_divid             = "mndigital_medm"; // ACTION REQUIRED: place a DIVID that matches in the appropriate place on the Fox News Entertainment *Article* pages
        widget.mnd_max_results       = "10";                 // the default is 5
        widget.mnd_artistbio_url     = "http://"+location.host+"/entertainment/music/media/index.html";    // for shell page; note specification of index.html
        widget.mnd_crawl_url         = location.href;            // OPTIONAL - the crawl URL is an override and doesn't have to be passed in. This is for pages that have extra params on the querystring that you wouldn't consider as part of uniquely identifying it in our system
        widget.mnd_show_explicit     = "false";
        widget.mnd_width = 329; 
        widget.mnd_inline_buy = "true";    // Turn on the inline (rather than overlay) buy panel, default is false
        widget.mnd_custom_CSS = "true";   // declare that you have a custom CSS in your webpage, default is false
        // widget.mnd_test = "on";    // only turn on if have developers outside US
        mndigital_widgets[2] = widget;
        
        window.mndigital_widgets = mndigital_widgets;  
        utils.runJsSrcAfterThisScriptTag("http://widgets.mndigital.com/widgets/mndigital.js");
		
	}
}

fox.site.bottomInit = function(){
	fox.site.parentBottomInit();
	fox.site.mediaNet.init();
}






