/**
 * 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 isIE =  $.browser.msie; 
	var isIE6 = ($.browser.version == "6.0" && isIE); 
	var isIE7 = ($.browser.version == "7.0" && isIE); 
	jQuery(".america .top").wrap("<a href='http://www.thefoxnation.com/'></a>");
	
	$('.tabbed .tabs li a').click(function(){ 
        var parent_id = '#' + $(this).parent().parent().parent().attr('id'); 
        $(parent_id + ' .tabs li').removeClass('active'); 
        $(parent_id + ' .pane').hide(); 
        $(this).parent().addClass('active'); 
        $('#pane-browse-' + $(this).attr('title')).show(); 
        return false; 
	}); 
	
	$('.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'));
	    }
	    }

	});
	
	
	$(".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();	
	
	$('.generic-list.link-list .popup')
	.each( function(){
		if(isIE){	    
		   $(this).hide();
		}
	})
	.end();
	
	jQuery('.channel-bar.sub-navigation .generic-list.link-list.b ul li')
	.each( function(){
		if(isIE6){
			var ie6Class = ($(this).attr('class'));		    
	       $(this).addClass('channel-bar-sub-navigation-generic-list-link-list-b-ie6');
		}
	})
	.end();
	//story.initDetailPanel( $('div.story-container:first') );

    //do stuff to generic list elements in first pass
	$('.generic-list, .feature-item, .composite, .accordion')
	
		//remove rounded bottom corners
		.find('ul.ui-accordion li').removeClass('ui-corner-bottom').end() 
	
		.find('h1').each(function(){
			genericlist.wrapHeadlinesFirstWord($(this));
		}).end()
		
		//add popup to video links in generic list
		.find('li.video h2 a, li.video .img a, ul.ui-accordion a').each(function(){

		    var href = $(this).attr('href');

		    if(href != null && href.indexOf("http://www.foxnews.com/video2/video08.html") === 0 ){
		
		    	$(this).click(function() {
		    		// pop up window
		    	    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()
		
		
		//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()
		
		.find('li').find('.more:visible:first').addClass('first').end().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();
	
	try { 
		var pageTracker = _gat._getTracker("UA-3128154-2"); pageTracker._setDomainName(".foxnews.com"); pageTracker._trackPageview(); 
	} 
	catch(err) {}
	
	if(isIE6){
		//we aren't going to support png hacks in IE6
		$('.png-template').remove();
	}
	
 });

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){
		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>";
             }
		}
		$container.html((temp.join(" ")).replace(/\^/g,' ')); // Clean up 
	} else {
		$container.html( "<strong>" + str + "</strong>" );
	}
}

//javascript for section headers
var is_ie='v'=='v';
function slide_u(id, ele, max, ofs){
	//var ele = document.getElementById(id);
	var top = ele.offsetTop;
	check(top, id, ofs);
	if (max>0) {
		ele.style.top = (top + 13) + "px";
		var fn = function(){slide_u(id, ele, max-13, ofs);};
		setTimeout(fn,0.5);
	}
}
function slide_d(id, ele, max, ofs){
	//var ele = document.getElementById(id);
	var top = ele.offsetTop;
	check(top, id, ofs);
	if (max>0) {
		ele.style.top = (top - 13) + "px";
		var fn = function(){slide_d(id, ele, max-13, ofs);};
		setTimeout(fn,0.5);
	}
}
function slide(dir, id){
	var ele = document.getElementById(id);
	var hgt = ele.offsetHeight;
	var how = 5;//how many items #5
	var unt = 26;//height of item #41 
	var ofs = 1-(hgt-(how*unt));
	if (is_ie) ofs+=1;//ie calcs 1 extra pixel
	var scr = 5;//scroll by #5, #10
	var top = ele.offsetTop;
	//alert('old top: '+top);
	if (dir=='down') {
		if (top < 0) {
			slide_u(id, ele, (scr*unt), ofs);
		}
	}
	if (dir=='up') {
		if (top > ofs) {
			slide_d(id, ele, (scr*unt), ofs);
		}
	}
	}
function check(top, id, ofs) {
	 if (top >= ofs) {
		document.getElementById('down_'+id).className="down";
	} else {
		document.getElementById('down_'+id).className="inactive-down";
	}
	if (top >= 0) {
		document.getElementById('up_'+id).className="inactive-up";
	} else {
		document.getElementById('up_'+id).className="up";
	}
}





