// V7 SITE JAVASCRIPT

// DOCUMENT.READY
// 	This function must be kept neat and clean, not to be crowded with assorted functions and triggers.
$(document).ready( function() {
	
	fox.site.loadDocReadyVars(); // store global variables only available on document.ready
	fox.site.fnChannelBar.init(); // main and sub nav bar hover
	fox.site.genericItems(); // generic triggers
	fox.site.rpx(); // trigger RPX
	fox.site.videoPlayer(); // video player embedding
	
	//renderWeather();
	weather_service.displayHeader();
	
	fox.widgets.tabs.init();
	
});

// SITE VARIABLES: Use this object to store global variables
window.siteVars = {
	isIE: function(){ return $.browser.msie; },
	isIE6: ($.browser.version==="6.0" && $.browser.msie) ? true : false,
	siteMeta: (pagedescriptor) ? pagedescriptor.getSiteMeta() : false
};

// SITE PRE-LOADER: loadEvent function
fox.site.loadEvent = function(componentId) {
	
	$(componentId).each(function(){
		// accordion
		if ($(this).hasClass(".accordia")) {
			fox.widgets.accordion.init();
		} 
		// carousel
		if ($(this).hasClass(".q-and-a")) {
			fox.widgets.carousel.initQandACarousel();
		}
		else if ($(this).hasClass(".features-f")) {
			fox.widgets.carousel.initFeatureCarousel();
		}
		// loomia
		$("#link_list_most_read",this).each(function(){
			fox.site.loomiaFeed.parseFeed(this);
		});
	});
	
}

// DOC.READY VARIABLES: site defined variables only available on document.ready
fox.site.loadDocReadyVars = function() {
	/*
	var newVars = {
		sample: "sample"
	};
	for (i in newVars) { siteVars[i] = newVars[i]; }
	*/
};

// GENERIC ITEMS: General site specific jQuery triggered items
fox.site.genericItems = function() {
	
	// accordion
	$("#fb-vp").each(function(){
		$("ul li.content:first",this).show();
		var elHeight = $(this).height()+"px";
		$(this).css("height",elHeight);
	});
	
	$.get("/inc/whatshot.inc",  function(data){
	    $('#header-container').append(data);
	});
    
	//login top links
	$('#right-head ul').append(createLoginLogout($.cookie('p_ThirdParty') != null));
	accountInfo.init();

	$(".generic-list, .composite").each(function(){
		$("h2 span.icon.newfreeform",this).replaceWith('<img alt="newfreeform" class="icon newfreeform" src="'+pagedescriptor.getSiteMeta().static_asset_all_img+'/interactive.jpg"/>');
		
		$("h1",this).each(function(){ 
			fox.site.styleSingleWordHeadlines($(this));
		});
		
	});
	
	$(".link-list-c").each(function(){
		$("li p.more-set a",this).each(function(){
			$(this).html('<img alt="&#187;" src="'+pagedescriptor.getSiteMeta().static_asset_img+'/blue-arrow.jpg"/>');
		});
	});
	
	// Registration overlay
	$("#top-register-link a, .sign_up_registration").each(function(){
		fox.widgets.overlay.init($(this));
		$(this).click(function(){
			vcs_service.registrationOverlay(this);
			return false;
		});
	});
	
	fox.site.pollCarousel(); // poll carousel
   
};

//general styling for single word headlines
fox.site.styleSingleWordHeadlines = 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
	for (n=0;n<nodeValue.length;n++) {
		if (nodeValue.charCodeAt(n)===160) { return false; }
	}
	
	if (headline.find("strong,span").size()<1) {
		headline.html('<strong>'+headline.html()+'</strong>');
	}
}

//man and sub nav bar hover
fox.site.fnChannelBar = {
	init: function() {
		this.nav.root = this;
		this.nav.main();
		this.nav.sub();
	},
	nav: {
		main: function() { // top nav channel bar
			var meta = this.root.get.meta();
			var reference = (meta) ? meta : this.root.get.path('folder');
			if (reference) { $("#top ul.nav li a[href*='/"+reference+"']").addClass('on'); }
		},
		sub: function() { // sub nav
			var path = this.root.get.siteMetaPath();
			var navItems = $(".channel-bar-sub-navigation .generic-list ul li");
			
			if (!path) { 
				path = '/' + this.root.get.path(); 
				navItems.each(function(){
					var aTag = $("a:first-child",this);
					if (aTag.attr("href").toLowerCase().indexOf(path)>-1) { aTag.addClass("active"); return false; }
				});
			} else {
				path = $.trim(path).split("/").reverse();
				var found = false;
				for (var x=0;x<path.length;x++) {
					navItems.each(function(){
						var aTag = $("a:first-child",this);
						if (aTag.attr("href").toLowerCase().indexOf('/'+path[x])>-1) { aTag.addClass("active"); found = true; return false; }
					});
					if (found) { return false; }
				}
			}
			
		}
	},
	get: {
		meta: function() { // get site name from pagedescriptor
			if (typeof pagedescriptor!=='undefined') { return pagedescriptor.getSiteMeta().top_site_name; }
			return false;
		},
		siteMetaPath: function() {
			return (siteVars.siteMeta) ? siteVars.siteMeta.breadcrumb : false;
		},
		path: function(type) {
			type = type || null;
			var path = window.location.pathname.toLowerCase();
			switch(type) {
				case 'folder':
					path = path.substr(1);
					var folder = path.substring(0,path.indexOf('/'));
					return (folder.length>0) ? folder : false; break;
					
				default:
					return (path.length>0) ? path : false; break;
			}
		}
	}
};

//loomia feed parser
fox.site.loomiaFeed = {
	feedCallback: function(data) {
		var items = [];
		$.each(data.recs, function(i,item){
			items.push(createLinklistItem(i,item));
			if (i==4) { return false; }
		});
		$(this.holder).html(items.join(''));
		
		function createLinklistItem(i, item){
			var content = [];
			var pubdate = (typeof item.pubdate!=='undefined') ? (item.pubdate!==null) ? fox.utils.datetime.format(eval(item.pubdate)) : '-' : '-';
			content.push('<li'+((i==0) ? ' class="first"' : '')+'>');	
			content.push('<div class="primary set primary-set"><a href="' + item.link + '">' + item.title + '</a>');
		    content.push('<p><span class="publish-date">' +  pubdate + '</span></p></div>');
		    content.push('<p class="more set more-set"><a href="' + item.link + '">&#187;</a></p></li>');
		    return content.join('');
		}
	},
	parseFeed: function(holder) {
		if (holder) {
			this.holder = holder;
			fox.site.tracking.loomia.getFeed("fox.site.loomiaFeed.feedCallback"); // pass callback function
		}
		
	}
};

//poll carousels
fox.site.pollCarousel = function() {
	$(".section-mod-poll-results .content").each(function(){
		var carousel = $(this);
		var maxBatch = 0;
		
		var control = carousel.children().filter(".controls");
		var firstBtn = control.find("> .first-page");
		var lastBtn = control.find("> .last-page");
		var prevBtn = control.find("> .prev");
		var nextBtn = control.find("> .next");
		var pageElm = carousel.find("#page");
		
		var config = {
			auto: { set:false,speed:3000 }, // auto scroll
			slide: 'horizontal', // horizontal or vertical
			scroll: 1, // number of items to scroll per event
			show: 1, // items shown
			speed: "fast", // scroll speed
			rotate: false, // rotate back to star if end
			eventCallback: function(obj) {
				var current = obj.batch.current;
				var max = obj.batch.max;
				
				pageElm.html("Page "+current+" of "+max);
				
				if (obj.event==='init') {
					maxBatch = max; // set max batches
				}
				
				if (current===1) {
					firstBtn.addClass("inactive-first");
					prevBtn.addClass("inactive-prev");
				} else {
					firstBtn.removeClass("inactive-first");
					prevBtn.removeClass("inactive-prev");
				}
				
				if (current===max) {
					lastBtn.addClass("inactive-last");
					nextBtn.addClass("inactive-next");
				} else {
					lastBtn.removeClass("inactive-last");
					nextBtn.removeClass("inactive-next");
				}
			},
			controlsCallback: function(control) {
				firstBtn.click(function(){
					control.stopAutoScroll();
					control.scrollToItem(1);
					return false;
				});
				
				lastBtn.click(function(){
					control.stopAutoScroll();
					control.scrollToItem(maxBatch);
					return false;
				});
				
				prevBtn.click(function(){
					control.stopAutoScroll();
					control.slide('prev');
					return false;
				});
				
				nextBtn.click(function(){
					control.stopAutoScroll();
					control.slide('next');
					return false;
				});
			}
		};
		
		carousel.jfoxCarousel(config);
		
	});
	
};

fox.site.rpx = function() {
	// RPX Social Publishing initializer
	if (typeof(RPXNOW)!=='undefined' && typeof(RPXMiddleWare)!=='undefined') { // check if RPX API exists
		window.rpxSMCall = new RPXMiddleWare();
		rpxSMCall.init({
			RPX: {
				appId:'niojnfniceodpipmhkao', // account id
				xdReceiver:'\/static/all/html/rpx/rpx_xdcomm.html' // Cross-domain receiver
			},
			config: {
				FNCLogo: 'http://'+window.location.hostname+pagedescriptor.getSiteMeta().static_asset_all_img+'/fnc_logo05.gif'
			}

			/* Advanced: adding custom triggers
			,customTrigger: {
				opinionLink: { // share_display,action,userContent are REQUIRED fields
					'share_display': 'Share myComment',
					'action': 'Commented on this page %PAGE_TITLE%',
					'userContent': 'Check out this page! Yo!',
					'imgSources': [{ <path to image>,<link for the image> }, { <path to image>,<link for the image> } ] // imgSources is OPTIONAL
				}
			}
			*/

		});

		/*
		// Calling the Social Publishing Trigger
		<namespace>.publish("<trigger name>");

		// Sample: Trigger publishing on comment submission
		$("form[id='new-comment-form'] fieldset input[type='submit']").click(function(){
			rpxSMCall.publish("comment"); // call comment trigger
		});
		*/

		// comment: submit & share button
		$("form[id='new-comment-form']").each(function(){
			var form = $(this);
			form.find(".submit-share").click(function(){
				var textArea = form.find("#discussion-comment").val();
				if ($.cookie("p_UN") && textArea.length>0) {
					rpxSMCall.publish("comment",textArea); // call comment trigger
				}
			});
		});

	} else {
		if (typeof window.console == 'object') { console.log('RPX Social Media not initialized!'); }
	}
};

//RPX on bottomInit
fox.site.bottomInitOrig = fox.site.bottomInit;
fox.site.bottomInit = function() {
	fox.site.bottomInitOrig();
	RPXMiddleWare();
	
	function RPXMiddleWare() { // RPX Call
		var middleWare = window.location.protocol+'//'+window.location.hostname+'/static/all/js/rpx-middleware.js';
		document.write(unescape("%3Cscript src='"+middleWare+"' type='text/javascript'%3E%3C/script%3E"));
	}
};

// In-page Video Player
fox.site.videoPlayer = function() {
	// flash embed properties for SWFObject
	var config = {
			player: {
				location: 'http://interactive.foxnews.com/projects/video-player/video-player.swf',
				flashVersion: '9.0.115',
				expressInstall: 'http://interactive.foxnews.com/swf/swfobject/expressInstall.swf',
				params: {
					bgcolor: '#000000',
					wmode: 'opaque',
					scale: 'noScale',
					menu: 'false',
					allowScriptAccess: 'always',
					allowFullScreen: 'true'
				},
				flashVars: {
					core_ads_enabled: 'true',
					core_swf_url: 'http://interactive.foxnews.com/projects/mmcore/mmcore.swf',
					core_omniture_player_name: 'FOX News',
					core_omniture_account: 'foxnewsmaven',
					core_yume_ad_domain_code: '109RXfmeHtS',
					core_yume_ad_server_domain: 'pl.yumenetworks.com',
					core_ad_player_name: 'inpage',
					core_yume_ad_library_url:'http://interactive.foxnews.com/swf/yume/yume_ad_library.swf',
					core_yume_player_url:'http://interactive.foxnews.com/swf/yume/yume_player_4x3.swf', 
					auto_play:'false'
				}
			},
			display: {
				allow: { // class declared attribute
					'format-9': [604,341],
					'format-6': [397,224]
				},
				clickThruImage: false
			}
		};
		
		// Instantiate player globally
		var videoPlayer = window.videoPlayer = new MvPlayer();
		videoPlayer.init({
			namespace: 'videoPlayer',
			config: config
		});
};


// SITE WIDGETS
fox.widgets.overlay = {
	init: function(action,target) {
		target = target||"#registration-overlay";
		var thisObj = this;
		$(action).each(function() {
			$(action).unbind("click").click(function() {
				thisObj.show(target);
			});	
		});
	},
	show: function(target) {
		var thisObj = this;
		if (typeof(increaseRefresh)!=='undefined') { increaseRefresh(); }
		$(target+" .validate a.sprites").unbind("click");
		if ($(".overlay-layer").size() < 1) {
			$("body").prepend('<div class="overlay-layer"></div>');
		}
		$(".overlay-layer").show();
		$(target).each(function(){
			$(this).show().fixedBox();
			if ($(window).height() < $(this).height()) {
				var scrollTop = $(document).scrollTop();
				var overlayTop = ($(this).css("top")).replace(/[a-z]/g,'');
				var abs = Math.abs(overlayTop)+scrollTop;
				$(this).css({
					top: abs+"px",
					position: "absolute"
				});
			}
			
			// reset items
			$(".field input",this).removeClass("error").attr("value","");
			$(".validate a.sprites,.error-tip",this).hide();
			
			var usr = $("#reg_user_name",this);
			var usrParent = $(usr).parent();
			if ($("span.req-text",usrParent).size()<1) {
				$(usr).after('<span class="req-text req-user">5-15 characters, cannot be changed</span>');
				$(usrParent).focus(function(){ $(".req-user",this).remove(); });
			}
			var pwd = $("#reg_password",this);
			var pwdParent = $(pwd).parent();
			if ($("span.req-text",pwdParent).size()<1) {
				$(pwd).after('<span class="req-text req-password">5-12 characters, no space, case-insensitive</span>');
				$(pwdParent).focus(function(){ $(".req-password",this).remove(); });
			}
		});

		var close = $(target+" .close").parent();
		$(close).unbind("click").attr("onclick","").click(function(){ thisObj.hide(target); });
		$(target+" .buttons input[type='reset']").click(function() { thisObj.hide(target); });
	},
	hide: function(target) {
		if (typeof(decreaseRefresh)!=='undefined') { decreaseRefresh(); }
		$(".overlay-layer").hide(); 
		$(target).hide();
	}
};

fox.widgets.tabs = {
     init: function() {
		$(".composite.tabbed").each(function(){
			var body = $(".composite-body",this);
			var tabs = $(".tabs li",this);
			if (typeof(body)=='object' && typeof(tabs)=='object') {
				$(tabs).each(function(i){
					var tab = this;
					$("a",this).bind("click",function(){
						$(tabs).each(function(){ $(this).removeClass("active"); }); // Remove active from tabs
						$(tab).addClass("active"); // Activate selected tab
						// Activate tab content body
						$(".composite-item",body).each(function(){ $(this).removeClass("active"); });
						$(".composite-item:nth-child("+(i+1)+")",body).addClass("active");
						return false;
					});
				});
			}
		});
    }               
};

fox.widgets.accordion = {
	init: function(){
		$("#video-main").accordion({
	        event: "mouseover",
	        header: "li.title",
	        active: 0,
	        change: function(event, ui) {
	          	var target = $(ui.newContent);            
	        }
	    });
	}
};

fox.widgets.carousel = {
	initFeatureCarousel: function() {
		var thisObj = this;
		$("#sbc-feature-carousel").jcarousel({
	    	visible: 1,
	    	scroll: 1,
	    	initCallback: thisObj.initCallback,
	    	buttonNextHTML: null,
	        buttonPrevHTML: null
	    });
	},
	initQandACarousel: function() {
		var thisObj = this;
		sbcQACarouselHiHeightFirst("#sbcqacarousel");
	    $("#sbcqacarousel").jcarousel({
	    	scroll: 1
	    });
	},
	initCallback: function(carousel) {
		$(".jcarousel-control-dot-slider a").bind("click",function(){
			carousel.scroll(jQuery.jcarousel.intval(jQuery(this).attr("id")));
			return false;
		});

		$("#jcarousel-control-dot-slider-next").bind("click",function() {
			carousel.next();
			changeCarouselImage(carousel.first-1);
			return false;
		});

		$("#jcarousel-control-dot-slider-prev").bind("click",function() {
			carousel.prev();
			changeCarouselImage(carousel.first-1);
			return false;
		});
	}
};

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

function increasefont() {
	if(story.fontState < 2) {
		var ptext = $('div.bodytext');
		$(ptext).removeClass(story.fontArray[story.fontState]);
		story.fontState++;
		$(ptext).addClass(story.fontArray[story.fontState]);
		return false;	
	}
}
function decreasefont() {
	if(story.fontState > 0) {
		var ptext = $('div.bodytext');
		$(ptext).removeClass(story.fontArray[story.fontState]);
		story.fontState--;
		$(ptext).addClass(story.fontArray[story.fontState]);
		return false;	
	}
}


// ----- DEFINE SITE OBJECTS -----
// These objects are used site-wide
var comment = {};
/*
 * The function will keep a ref to the jQuery Container that should be filled when the ajax call is returned.
 * This is like an Ajax event that includes a ref to the original jQuery container.
 */
comment.getCount = function(vcmId, jQueryContainer){
	
	 var event = new AjaxGetEvent({jQueryContainer:jQueryContainer}, 
			 
			 function(data, eventdata){
		 
			        var doc = ParseXML(data);   
				   	var status = $(doc).find('status').attr('code'); 
					if (status != 'error'){  
						var count = $(doc).find('collab-object').attr('totalCommentCount');  
						count = formatNumber(count,0,',','','','','-','');
						var href = eventdata.jQueryContainer.attr('href');	
					    if(href != null){	        		
					      href = href+"\/?storytab=story-comments";
					      eventdata.jQueryContainer.attr('href', href);	
					    }
				      	eventdata.jQueryContainer.html('<span class="result">' + count + '</span> <span class="label">Comments</span> ');			
		            }else{               
		            	eventdata.jQueryContainer.remove(); 
	                }  
					eventdata.jQueryContainer.removeClass("loading");
			 }
	 );
	 
	 event.get("/vcs/read/getNumberOfComments",{object:vcmId},'text');

};


/*Story*/
var story = {};
story.init = function(){
	var imagePath =pagedescriptor.getSiteMeta().static_asset_img;
	var site = pagedescriptor.getSiteMeta().top_site_name;
	if (site == 'opinion') {
		site = 'Opinion';
	}
	var channel = pagedescriptor.getSiteMeta().channel;
	var imgAllPath = $('#img-all-path').text();
	var vcmId = $('#story-vcmId').text();
	var storyTitle = $('#story-title').text();
	var storyDek = $('#story-dek').text();
	var storyUrl = $('#story-url').text();
	var objectType = "STORY";
	this.perpage= '10';
	this.pagenum='1';
	this.sort ='DESC'; //DESC - ASCN  (DESC for newest first).
	vcs_service.init({
		imgAllPath: $('#img-all-path').text(),
		imagePath: pagedescriptor.getSiteMeta().static_asset_img,
		site: ((pagedescriptor.getSiteMeta().top_site_name==='opinion')?'Opinion':pagedescriptor.getSiteMeta().top_site_name),
		channel: pagedescriptor.getSiteMeta().channel,
		vcmId: $('#story-vcmId').text(),
		storyTitle: $('#story-title').text(),
		storyDek: $('#story-dek').text(),
		storyUrl: $('#story-url').text(),
		objectType: "STORY"
	});
	if($(".story-container").length > 0){
		story.initDetailPanel();
		story.initCommenting();
	}
	story.fontArray = new Array('smalltext','mediumtext','largertext');
	story.fontState = 0; // index to fontArray
	createShareThisMultiLink($("#up-share-share"));
    createShareThisMultiLink($("#down-share-share"));
    createShareThisMultiLink($("#up-share-email"), 'email');
    createShareThisMultiLink($("#down-share-email"), 'email');
};

story.initDetailPanel = function(){
	var container = $('#pane-browse-story-detail .bodytext');
	if($('#otherMedia').children().length > 0 && container.find('p').text().length > 3200){
		var otherMedia = '<div class="related vertical">'+$('#otherMedia').html()+'</div>';
		container.find('p:nth-child(5)').after(otherMedia);
		$('#otherMedia').remove();
	}
	
	$('.story-container .tabbed .tabs li a').click(function(){		
		var tabTitle = $(this).attr('title');		
		var tabLink = $('.story-container .tabs li a[title*='+tabTitle+']');
	    story.switchTab(tabLink);
		if (tabTitle=='story-comments') {
			vcs_service.getComments(story.perpage, story.pagenum, story.sort);
		}
		return false;
	});
	$(".recomended-count").click(function () { 
	  vcs_service.recommend(this);
	  return false; 
    });
	if($('.recomended-count').length > 0){
		vcs_service.getRecommendCount();  
	}	
};

story.initCommenting = function(){
	var obj = this;
	
	if($("#pane-browse-story-comments").length > 0){
		
	    //deep link to comments tab
		tabIndex = story.getQuery('storytab');
		if (tabIndex=='story-comments'){
			story.switchToCommentTab();
			vcs_service.getComments(story.perpage, story.pagenum, story.sort);			
		}

	    $(".join-discussion, .leave-a-comment").click(function () {
	    	story.switchToCommentTab(); 
	    	$.scrollTo('#begin-comment-form'); 
	       	if (tabIndex!='story-comments'){			
				vcs_service.getComments(story.perpage, story.pagenum, story.sort);			
			}
	    	var timeoutListener = new Object();	    	
	    	function checkCommentsLoaded() {
	    		if ($(".comments-left .discussion").size() > 0) {
	    			$.scrollTo('#begin-comment-form'); 	
	    				
	    			clearTimeout(timeoutListener);
	    			return false;
	    		}
	    		else { timeoutListener = setTimeout(function() { checkCommentsLoaded(); }, 100 );}
	    	}
	    	checkCommentsLoaded();	    	
	    	
	    });
        $("#start-new-discussion").click(function () { 
          $.scrollTo('#begin-comment-form');
          return false;  
        });
	    if($("#commentCount").length > 0){
	    	vcs_service.getCommentsCount();  	
	    }
	    $(".oldest-first").click(function () { 
	    	obj.sort = 'ASCN';
		  vcs_service.getComments(obj.perpage, obj.pagenum, obj.sort);
		  $.scrollTo('#commentsHolder');
		  return false;  
	    });
	    $(".newest-first").click(function () { 
	    	obj.sort = 'DESC';
		  vcs_service.getComments(obj.perpage, obj.pagenum, obj.sort);
		  $.scrollTo('#commentsHolder');
		  return false;  
	    });
    	$('#new-comment-form').validate({
	    	onkeyup: false,
	    	errorPlacement: function(error, element) {
			},
			invalidHandler: function(form, validator) {
				$(this).find('input[type*=submit]').attr("disabled", "disabled");
				var errors = validator.numberOfInvalids();
				if (errors) {
					$(".com-required").show();
				} else {
					$(".com-required").hide();
				}
				$(this).find('input[type*=submit]').removeAttr("disabled"); 
			},
			submitHandler: function(form) {
				$(form).find('input[type*=submit]').attr("disabled", "disabled");
				$(".com-required").hide();
				return false;
			}
    	});
	}
};

story.switchTab = function(tabLink){
	var parent_id = '#' + tabLink.parent().parent().parent().attr('id');
	$(parent_id + ' .tabs li').removeClass('active');
	$(parent_id + ' .pane').hide();
	tabLink.parent().addClass('active');
	$('#pane-browse-' + tabLink.attr('title')).show();
	return false;
};

story.switchToCommentTab = function(){
		
	var tabTitle = 'story-comments';		
	var tabLink = $('.story-container .tabs li a[title*='+tabTitle+']');
    story.switchTab(tabLink);
	return false;
};

story.getQuery = function(q) {
	if(window.location.search) {
		var query = window.location.search.substr(1);
		var pairs = query.split("&");
		for(var i = 0; i < pairs.length; i++) {
  		var pair = pairs[i].split("=");
  		if(unescape(pair[0]) == q)
  			return unescape(pair[1]);
  		}
	}
};

//Slider Tab Switching. 11/27/2009
//Dependencies: jquery
function TabSwitcher() {
	// defaults;
	this._currentTab = 1;
	this._turnTimeout = null;
	this._hover = true;
	this._autoplay = true;
	this._transitionSpeed = 5000;
	this._size = 0;
	this._checkedVideo = false;
}

TabSwitcher.prototype = {
	init: function(properties) {
		if (typeof properties === 'undefined') { this.showToConsole('No properties passed');return; }
		for (i in properties) {
			if (properties.hasOwnProperty(i)) {
				this["_"+i] = properties[i]; 
			}
		}
		this._autoplay = (this._autoplay==='false')?false:this._autoplay;
		this._obj = $("#"+this._id);
		this._size = $("ul li",this._obj).size();
		if (this._size===0) { this.showToConsole('No tab component for id:' + this._id);return; }
		$("ul li",this._obj).each(function(i){ // initialize show first item
			if (i===0) { $("h2",this).addClass("selected"); $("img",this).css("display","block"); }
		});
		this.autoPlay.init(this);
		this.initVideo();
		this.listener();
	},
	initAndRun: function(properties) {
		this.init(properties);
	},
	listener: function() {
		var thisObj = this;
		var tabs = $("ul li",this._obj);
		var hover = this._hover;
		$(this._obj).hover(function(){ (thisObj._autoplay==='persistent')?thisObj.autoPlay.pause():thisObj.autoPlay.stop(); },function(){ thisObj.autoPlay.play(); });
		$("h2",tabs).each(function(i){
			var li = $(this).parent();
			$(li).hover(function(){ $(this).addClass("hover"); }, function(){ $(this).removeClass("hover"); }); // add a hover class control
			if (hover) { // hover
				$(this).hover(function(){ selectItem(li,i); },function(){ });
			} else { // click
				$(this).unbind("click").click(function(){ selectItem(li,i);return false; });
				$("a",this).unbind("click").click(function(){ selectItem(li,i);return false; });
			}
		});
		function selectItem(item,i) {
			thisObj._currentTab = i+1;
			thisObj.switchItem.trigger(thisObj._obj,tabs,item);
		}
		thisObj.autoPlay.play();
	},
	initVideo: function() {
		var thisObj = this;
		var tabs = $("ul li",this._obj);
		var videoObj = $("object[id^='videoid:']",tabs);
		if (!this._checkedVideo) {
			$(tabs).each(function(i){
				$("object",this).each(function(){ 
					if (i===0) { $(this).removeClass("swf-hidden"); } 
					else { $(this).addClass("swf-hidden").css("visibility","hidden"); }
				});
			});
		} else { setTimeout(function(){ thisObj.initVideo(); },100); this._checkedVideo=true; }
	},
	showToConsole: function(str) {
		if (typeof window.console == 'object') { console.log(str); }
	}
};

TabSwitcher.prototype.switchItem = {
	select: function(item) {
		$(item).each(function(){
			$("h2",this).addClass("selected");
			$(".media-holder object",this).removeClass("swf-hidden").css("visibility","visible");
			$("img:first",this).fadeIn(200);
		});
	},
	unselect: function(item) {
		$(item).each(function(){
			$("h2",this).removeClass("selected");
			$(".video object",this).addClass("swf-hidden").hide();
			$("img:first",this).hide();
		});
	},
	deck: function(item,holder) {
		$("> p",holder).each(function(){
			$("a",this).attr("href",$("a",item).attr("href"));
			$("a span",this).html($(".deck",item).html());
		});
	},
	trigger: function(holder,tabs,item) {
		this.unselect(tabs);
		this.select(item);
		this.deck(item,holder);
	}
};

TabSwitcher.prototype.autoPlay = {
	init: function(obj) {
		this.thisObj = obj;
	},
	play: function() {
		var thisObj = this.thisObj;
		thisObj._turnTimeout = (thisObj._autoplay)?(setTimeout(function(){ thisObj.autoPlay.turn(); },thisObj._transitionSpeed)):null;
	},
	stop: function() {
		var thisObj = this.thisObj;
		this.clear();
		thisObj._autoplay = false;
	},
	pause: function() {
		this.clear();
	},
	clear: function() {
		var thisObj = this.thisObj;
		clearTimeout(thisObj._turnTimeout);
	},
	turn: function() {
		var thisObj = this.thisObj;
		var next = thisObj._currentTab+1;
		var current = (next>thisObj._size)?1:next;
		thisObj._currentTab = current;
		var tabs = $("ul li",thisObj._obj);
		var ul = $("ul",thisObj._obj);
		$("li:nth-child("+current+")",ul).each(function(){
			thisObj.switchItem.trigger(thisObj._obj,tabs,this);
		});
		if (thisObj._autoplay) { thisObj._turnTimeout = setTimeout(function(){ thisObj.autoPlay.turn(); },thisObj._transitionSpeed)}
	}
}; // Tab Switcher End

//List Type Dropdown: updated 12/16/2009
//Dependencies: jQuery
function ListDropdown() {
	this._target = ".list-type-dropdown"; // default 
	this._trigger;
	this.elementObj; 
}

ListDropdown.prototype = {
	init: function(config) {
		config = config||{};
		for (i in config) {
			this["_"+i] = config[i];
		}
		this.targetObj = $(this._target);
		this.set();
	},
	set: function() {
		var thisObj = this;
		$(this.targetObj).each(function(){
			var pTag = $("p.current-value",this);
			var list = $("ul",this);
			//$(".holder",this).css("height",$(".holder",this).height()); // set height
			$("ul",this).hide(); // hide list
			if (!pTag.hasClass("disabled")) { // check if disabled
				pTag.unbind("click").click(function(){ setTimeout(function(){ thisObj.show(list,pTag); },50); });
			}
			thisObj.listener(this);
			$(document).click(function(){ // global click listener per list dropdown
				if (list.css("display")!='none') { thisObj.show(pTag,list); }
			});
		});
	},
	listener: function(obj) {
		var thisObj = this;
		var pTag = $("p.current-value",obj);
		var list = $("ul",obj);
		$("ul li",obj).each(function(){ // set list listeners
			$(this).unbind("hover").hover(function(){ $(this).addClass("hover"); }, 
				function(){
					$(this).removeClass("hover");
					//setTimeout(function(){ thisObj.show(pTag,list); },1000); // close after 1 second
				})
				.unbind("click")
				.click(function(){
					var value = ($(this).attr("lang")!=-1)?$(this).attr("lang"):$(this).text(); // value search
					$("input",obj).attr("value",value);
					pTag.html($(this).text());	
					thisObj.show(pTag,list);
					if (typeof(thisObj._trigger)==='function') { thisObj._trigger(obj); }
				});
		});
	},
	show: function(showObj,hideObj) {
		$(hideObj).hide();
		$(showObj).show();
	}
}; /* end list type dropdown */

//Multiple Video Player - Minimum Version. Last Updated: 02/25/2010
//Dependencies: swfobject, jquery
(function($){

window.MvPlayer = function() {
	this._namespace = null;
	this._config = {};

	this.holder = {}; // jquery object holder 
	this.playerIds = []; // player id holder
	
	this.idSeparator = ":"; // customizable separator
	this.instanceId = ['videoid','videolink']; // default instances
	this.videoTypeId = ['videoid','playlistid']; // video types
	
	this.videoTypeLinks = {
		videoid: "http:\/\/video.foxnews.com/v/feed/video/",
		playlistid: "http:\/\/video.foxnews.com/v/feed/playlist/"
	};

	this.playTimeout = {};
	this.dataObj = {};
	this.holderObj = {};
};

MvPlayer.prototype = {
	init: function(config) {
		for (i in config) { this['_'+i] = config[i]; }
		this.embed.root = this.feed.root = this.video.root = this;

		this.holder.videoObj = $(".video");
		this.embed.players();
	}
};

MvPlayer.prototype.embed = {
	players: function() {
		var thisObj = this;
		var root = this.root;
		var clickthru = (typeof root._config.display.clickThruImage==='undefined') ? false : root._config.display.clickThruImage;
		var separator = root.idSeparator;
		
		root.holder.videoObj.each(function(){ // for all video holder items
			var holder = $(this);
			var videoExists = false;
			for (var x=0;x<root.instanceId.length;x++) {
				var prefix = root.instanceId[x];
				holder.find("div[id^='"+prefix+separator+"']").each(function(){
					var videoDiv = $(this);
					var dimensions = root._config.display.allow;
					for (d in dimensions) {
						if (videoDiv.hasClass(d)) {
							videoExists = true;
							var vId = root.format[prefix](videoDiv,prefix,separator);
							var dim = dimensions[d];
							
							root.holderObj[vId] = { id: vId, elm: videoDiv, dim: dimensions[d] }; // create holder
							if (clickthru) { root.feed.get(vId); } else { thisObj.player(vId); }
						}
					}
				});
			}
			// remove additional image if video exists
			if (videoExists) {
				holder.children().filter("div.img").hide();
			}
			
		});
	},
	player: function(id) {
		var thisObj = this;
		var root = this.root;
		if (!id) { return false; }
		if (typeof swfobject!=='undefined') {
			root.playerIds.push(id); // store id's
			// Build Embed swfobject
			var info  = root._config.player;
			var holder = root.holderObj[id];
			
			if (!root.holderObj[id].swfLoaded) {
				swfobject.embedSWF(info.location,id,holder.dim[0],holder.dim[1],info.flashVersion,info.expressInstall,root._config.player.flashVars,root._config.player.params);
				root.holderObj[id].swfLoaded = true;
			}
			root.video.load(id);
		}
		
	},
	clickthru: function(data,id) {
		var thisObj = this;
		var root = this.root;
		var holder = root.holderObj[id];
		holder.elm.html('<a style="display:block;visibility:visible" href="#" onclick="javascript:return false;"><img src="'+data.thumbnail+'" /></a>');
		
		holder.elm.find("a")
			.click(function(){ thisObj.player(id); return false; })
			.hover(function(){ $("img",this).addClass("hover"); }, function(){ $("img",this).removeClass("hover"); });
		
	}
};

MvPlayer.prototype.video = {
	load: function(id) {
		var thisObj = this;
		var root = this.root;
		if (document.getElementById(id).playFile) {
			var clickthru = (typeof root._config.display.clickThruImage==='undefined') ? false : root._config.display.clickThruImage;
			if (root.dataObj[id]) {
				var autoplay = (clickthru) ? true : false;
				document.getElementById(id).playFile(root.dataObj[id],autoplay);
			} else { root.feed.get(id); }
			clearTimeout(root.playTimeout[id]);
		} else {
			root.playTimeout[id] = setTimeout(function(){ thisObj.load(id); },100);
		}
	}
};

MvPlayer.prototype.feed = {
	get: function(id) {
		var thisObj = this;
		var root = this.root;
		var separator = root.idSeparator;
		
		var feedFn = 'parse_' + root._helper.formatVideoId(id,true,true);
		var callbackFn = root._namespace + '.feed.' + feedFn;
		
		var linkObj = false;
		function getFeedLink() {
			for (i in root.videoTypeLinks) {
				if (id.indexOf(i)>-1) { 
					return { prefix:root.videoTypeLinks[i],type:i };
				}
			}
			return false;
		}
		
		linkObj = getFeedLink();
		if (!linkObj) { showToConsole("[feed] Error: no feed link: " + type + " | " + id); return false; }
		
		var videoId = id.substr(linkObj.type.length + separator.length);
		var linkPrefix = linkObj.prefix;
		
		if (videoId.charAt(0).toLowerCase()!=='g') {  // for legacy maven id's
			if (linkObj.type==='videoid') {
				linkPrefix = linkPrefix.replace("/v/","/");
			}
		} else {
			videoId = videoId.substr(1);
		}
		
		var url = linkPrefix + videoId + ".js";
		var query = "?callback="+callbackFn+"&jsonp=?";
		
		// create arbitrary function for feed
		if (!this.root.feed[feedFn]) {
			this.root.feed[feedFn] = function(data) {
				var clickthru = (typeof root._config.display.clickThruImage==='undefined') ? false : root._config.display.clickThruImage;
				var dataObj = root._helper.videoObjectJSON(data);
				root.dataObj[id] = dataObj; // store video data
				if (dataObj) {
					if (clickthru) {
						root.embed.clickthru(dataObj,id);
					} else {
						root.embed.player(id);
					}
				} else {
					showToConsole("[parse] Warning: no data found!");
				}
			};
		}
		$.getJSON(url+query);
	}
};

MvPlayer.prototype.format = {
	videoid: function(obj,prefix,separator) { // legacy video id
		var id = obj.attr("id").substr(prefix.length+1);
		return 'videoid' + separator + id;
	},
	videolink: function(obj,prefix,separator) { // full link on the id
		var id = obj.attr("id");
		var searchStr = "playlist";
		var prefixId = "playlistid" + separator;
		
		function replaceDivId(id) { obj.attr("id",id); } // replace linked id
		
		if (id.indexOf('?'+searchStr)>-1) {
			// playlist id via passed string variable
			// sample: http://video.foxbusiness.com/?playlist_id=87447
			
			var query = id.substr(id.indexOf('?')+1);
			var items = query.split('&');
			for (var x=0;x<items.length;x++) {
				var pair = items[x].split('=');
				if (pair[0].toLowerCase()==='playlist_id') {
					var returnId = prefixId + pair[1];
					replaceDivId(returnId);
					return returnId;
				}
			}
		} else {
			return false;
		}
		
	}
};

MvPlayer.prototype._helper = {
	formatVideoId: function(id,uriFriendly,callback) {
		uriFriendly = uriFriendly || false;
		callback = callback || false;
		if (callback) { id = id.split("").reverse().join(""); } // to avoid global replace of legacy mavenid's to new id's
		
		if (uriFriendly) {
			return id.replace(/\:/gi,"_");
		} else {
			return id.replace(/\_/gi,":");
		}
	},
	convertDate: function(d) {
		if (typeof d!=="undefined") {
			var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
			var date = d.toString().split('T');
			date = date[0].split('-');
			date = new Date(date[0],(date[1]-1),date[2]);
			return months[date.getMonth()]+' '+date.getDate()+', '+date.getFullYear();
		} else {
			return '';
		}
	},
	extractVideoId: function(str) {
		var s = str.replace(/^(http:\/\/)?[a-zA-Z0-9\.]+/,'');
		s = (s.indexOf('#')===0) ? s.substring(2) : s.substring(1);
		return s.substring(0,s.indexOf('/'));
	},
	extractCategoryId: function(str) {
		return str.split('category_id=')[1];
	},
	cleanTitle: function(title) {
		title = title.replace(/ /g,'-').toLowerCase();
		return title.replace(/[^a-z0-9\-]/g,'');
	},
	cleanHref: function(href) { // necessary for ie 6 link cleanup
		return href.replace(/^(http:\/\/)?[a-zA-Z0-9\.]+/,'');
	},
	cleanImageUrl: function(url) {
		return url.replace('http://media2.foxnews.com','');
	},
	convertTime: function(sec) {
		var minutes = Math.floor(sec/60);
		var seconds = Math.floor(sec%60);
		if (seconds.toString().length==1) { seconds = '0'+seconds; }
		return minutes+':'+seconds;
	},
	videoObjectJSON: function(json) {
		if (typeof json.channel.item==='undefined') { return false; }
		
		var item = json.channel.item;
		var details = item['media-content'];
		var credits = details['media-credit'];
		
		var obj = {
			url: details['@attributes'].url,
			title: item.title,
			description: details['media-description'],
			keywords: details['media-keywords'],
			thumbnail: details['media-thumbnail'],
			guid: details['mvn-assetUUID'],
			mavenid: details['mvn-mavenId'],
			channel: (details['mvn-fnc_channel'])?details['mvn-fnc_channel']:details['mvn-fbn_channel'],
			playlist: details["mvn-fnc_default_playlist"],
			personality: (details['mvn-fnc_personality'])?details['mvn-fnc_personality']:details['mvn-fbn_personality'],
			format: (details['mvn-fnc_format'])?details['mvn-fnc_format']:details['mvn-fbn_format'],
			show: (details['mvn-fnc_show'])?details['mvn-fnc_show']:details['mvn-fbn_show'],
			category: (details['mvn-fnc_category']) ? details['mvn-fnc_category'] : details['mvn-fbn_category'],
			creationDate: this.convertDate(details['mvn-creationDate']),
			shortDescription: details['mvn-shortDescription'],
			loc: 'http://'+window.location.host+window.location.pathname
		};

		return obj;
	}
};

//console log for firebug
function showToConsole(str) {
	if (typeof window.console==='object') { console.log(str); }
}

})(jQuery); /* end - video player */