// V7 SITE JAVASCRIPT - SBC

// 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.genericItems(); // generic triggers
	fox.site.videoPlayer(); // video player embedding
	
	fox.site.tabs.init();
	fox.site.sbcChannelBar.pathName(); // Channel Bar Hover
	
});

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

// SITE PRE-LOADER: loadEvent function
fox.site.loadEvent = function(componentId) {
	
	$(componentId).each(function(){
		// tab switcher
		$("#big-top",this).each(function(){
			var tabSwitcher = new TabSwitcher();
			var tabProperties = {
				id: 'big-top',
				autoplay: true,
				transitionSpeed: 5000 // ms
			};
			tabSwitcher.initAndRun(tabProperties);
		});
		
		// carousel
		if ($(this).hasClass("q-and-a")) {
			fox.site.carousel.init('QandACarousel');
		}
		if ($(this).hasClass("features-f")) {
			fox.site.carousel.init('FeatureCarousel');
		}
		
		// 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() {
	
	$('.composite-body').each( function(){
	    $(this).children('.composite-item:last').addClass('composite-item-last');
	});
	
	accountInfo.init();
	
	fox.site.sbcRightHeaderLine();
	
	$("#top-register-link a").each(function(){
		var link = $(this);
		fox.widgets.overlay.init(link); // Registration
		link.click(function(){
			vcs_service.registrationOverlay(this,'sbc');
			return false;
		});
	});
	
    $("#reg_user_name").focus(function() { $(".req-user").remove(); });
    $("#reg_password").focus(function() { $(".req-password").remove(); });
    
    fox.site.pollCarousel(); // poll carousel
    
};

//In-page video player
fox.site.videoPlayer = function() {
	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 Business',
				core_omniture_account: 'foxnewsbusinessmaven',
				core_yume_ad_domain_code: '109sLnXEAbj',
				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-6': [397,229],
				'format-9': [605,341],
				'format-slider-tab': [397,228]
			},
			clickThruImage: false
		}
	};
	
	// Instantiate player globally
	var videoPlayer = window.videoPlayer = new MvPlayer();
	videoPlayer.init({
		namespace: 'videoPlayer',
		config: config
	});
};

// Login line header
fox.site.sbcRightHeaderLine = function() {
	
	$("#right-head ul").each(function(){
		var bLinkAppend = false;
		if (typeof(createLoginLogout)==='function') { $(this).append(createLoginLogout()); }
		$("li",this).each(function(){ 
			if (($("a",this).text()).toLowerCase()==='fox business') { bLinkAppend=true; }
		});
		if (!bLinkAppend) { $(this).append('<li><a href="http://www.foxbusiness.com">FOX Business</a></li>'); }
	})
};

//Add channel bar hover to fox.site namespace
fox.site.sbcChannelBar = {
	breadcrumb: function() {
		if (typeof pd.breadcrumb == 'undefined') { this.pathName(); } // failover to pathname if breadcrumb is not found
		else {
			var pdb = (pd.breadcrumb).split("/");
			var folder = ((pdb[3]==undefined)?'sbc':pdb[3]).toLowerCase();
			if (folder.length>0) { this.target(folder); }
		}
	},
	pathName: function() {
		var path = ((window.location.pathname).substr(1)).toLowerCase();
		var folder = (path=='index.html')?'sbc':(path.substring(0,path.indexOf('/')));
		if (folder.length>0) { this.target(folder); }
	},
	target: function(folder) {
		$(".channel-bar-sub-navigation .generic-list ul li").each(function(){
			var link = ($("a:first-child",this).attr("href")).split("/");
			if (link[1] == folder) {
				$("a:first-child",this).attr("class","selected");
			}
		});
	}
};

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

//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.tabs = {
     init: function() {
		$(".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;
					});
				});
			}
		});
    }               
};

// Carousel
fox.site.carousel = {
	init: function(type) {
		this['init'+type]();
	},
	initFeatureCarousel: function(){
		var thisObj = this;
		$("#sbc-feature-carousel").jcarousel({
	    	visible: 1,
	    	scroll: 1,
	    	initCallback: thisObj.callback,
	    	buttonNextHTML: null,
	        buttonPrevHTML: null
	    });
	},
	initQandACarousel: function(){
		this.sbcQACarouselHiHeightFirst("#sbcqacarousel");
	    $("#sbcqacarousel").jcarousel({
	    	scroll: 1
	    });
	},
	// Re-organize list to set item with the highest height first
	sbcQACarouselHiHeightFirst: function(id) {
		var target = 0;
		var temp = 0;
		var LI = new Array();
		$(id+" li").each(function(i) {
			var h = $(this).innerHeight();
			temp = (temp>h)?temp:h;
			target = (temp>h)?target:i;
			LI[i] = this;
			$(this).remove();
		});
		$(id).append(LI[target]); // Append highest height first
		$(LI).each(function(i){ // Append the rest
			if (i!=target) { $(id).append(this); }
		});
	},
	callback: function(carousel) {
		var mainHolder = $(carousel.container).parent().parent();
		$(".jcarousel-control-dot-slider a",mainHolder).click(function(){
			carousel.scroll($.jcarousel.intval($(this).attr('id')));       
		    return false;
		});
		
		$("#jcarousel-control-dot-slider-next",mainHolder).click(function(){
			carousel.next();
			changeCarouselImage(carousel.first-1);
			return false;
		});
		
		$("#jcarousel-control-dot-slider-prev",mainHolder).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;	
	}
}

// Recaptcha code for SBC Domain
function showRecaptcha(element) {
	RecaptchaSBCDomain(element);
}

// 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.html('<span class="result"></span> <span class="label">No Comments</span>');
		            	eventdata.jQueryContainer.addClass("no-comments");
	                }  
					eventdata.jQueryContainer.removeClass("loading");
			 }
	 );
	 
	 event.get("/vcs/read/getNumberOfComments",{object:vcmId},'text');

};

/**************************************/
/*            STORY DETAIL            */
/**************************************/
/*   GLOBAL */
/*Story*/
var story = new Object();
story.init = function(){
    var imagePath =pagedescriptor.getSiteMeta().static_asset_img;
    var site = pagedescriptor.getSiteMeta().top_site_name;
    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';
    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.hideCommenting();
    }
    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 > 4000){
		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.hideCommenting = function(){
	if($("#pane-browse-story-comments").length > 0){
	   $(".story-container .comment-tab").hide();	
	   $(".story-container .join-discussion").hide();
	   $(".story-container .share-links .recomended-button").hide();
	   $(".story-container div.share-links:last-child ul>li:last-child").hide();
	}
};
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();
				vcs_service.sendComment($(form));
				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]);
  		}
	}
};

//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 */

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