$(document).ready(function(){

	// MID HERO STUFF
	if($('#mid-hero').length)
		{
		$('.mid-hero-item').hover(
			function(){
				$(this).find('.top-border').show();
				$(this).find('h3').css('padding-top','6px');
				$(this).find('.picture-cover').fadeTo(0,0.15);
			},
			function(){
				$(this).find('.top-border').hide();
				$(this).find('h3').css('padding-top','0');
				$(this).find('.picture-cover').fadeTo(0,0.4);
			}
			);
		}

		// ALT HEADER STUFF
		if($('.alt-header').length) $('.alt-header .inner-padding .engadget_hdr_inner a:eq(0)').attr('href','http://alt.engadget.com');

	// COOKIE COMMENT HIDER
	if($('#comments').length)
		{
		if(getCookie('showComments'))
			{
			$('#comment-loader-wheel').fadeOut('fast',function(){
				$('.comment-hide-system').fadeIn('fast');
				$('#turn-comments-on').addClass('active');
				});
			}
		else
			{
			$('#comment-loader-wheel').fadeOut('fast',function(){
				$('#comments-are-off').fadeIn('fast');
				$('#turn-comments-off').addClass('active');
				});
			}
		}
	$('.comments-off-on a').click(function(){
		if($(this).hasClass('active')==false)
			{
			$('.comments-off-on a').removeClass('active');
			if($(this).attr('id')=='turn-comments-on')
				{
				$('#comments-are-off').fadeOut('fast',function(){
					$('.comment-hide-system').fadeIn('fast');
					$('#turn-comments-on').addClass('active');
					setCookie('showComments','Show Engadget Comments',365);
					});
				}
			else
				{
				$('.comment-hide-system').fadeOut('fast',function(){
					$('#comments-are-off').fadeIn('fast');
					$('#turn-comments-off').addClass('active');
					setCookie('showComments','',-1);
					});
				}
			}
		return false;
	});

	// CLEAR COOKIES
	$('#engadget_hdr_logout').click(function(){
		setCookie('BPLI','',-1);
		setCookie('DATA','',-1);
	});

	// GOODBYE ERIC SCHMIDT PHOTO
	$('img[src="http://www.blogsmithcdn.com/avatar/images/21/3595352_64.jpg"]')
		.attr('src','http://www.blogsmithcdn.com/avatar/images/21/3518218_64.jpg');
	
	// BREAKING NEWS BAR
	if($('#breaking-news-ticker').length)
		{
		if($('#bnt-link-jar li').length > 1) $('#bnt-tools').show();
		$('#bnt-articles').html($('#bnt-link-jar li').eq(0).html());
		$('#bnt-link-jar li').eq(0).addClass('nowShowing');
		$('#breaking-news-ticker').slideDown();
		}
	$('#bnt-next').live('click',function(){
		var nowShowing = $('#bnt-link-jar li.nowShowing').prevAll('li').length;
		var articleLen = $('#bnt-link-jar li').length-1;
		if(nowShowing !== articleLen) var nextHtml = $('#bnt-link-jar li.nowShowing').removeClass('nowShowing').next('li').addClass('nowShowing').html();
		else
			{
			$('#bnt-link-jar li.nowShowing').removeClass('nowShowing');
			var nextHtml = $('#bnt-link-jar li').eq(0).addClass('nowShowing').html();
			}
		$('#bnt-articles').fadeTo('fast',0,function(){ $('#bnt-articles').html(nextHtml).fadeTo('fast',1); });
		return false;
	});
	$('#bnt-back').live('click',function(){
		var nowShowing = $('#bnt-link-jar li.nowShowing').prevAll('li').length;
		var articleLen = $('#bnt-link-jar li').length-1;
		if(nowShowing !== 0) var nextHtml = $('#bnt-link-jar li.nowShowing').removeClass('nowShowing').prev('li').addClass('nowShowing').html();
		else
			{
			$('#bnt-link-jar li.nowShowing').removeClass('nowShowing');
			var nextHtml = $('#bnt-link-jar li').eq(articleLen).addClass('nowShowing').html();
			}
		$('#bnt-articles').fadeTo('fast',0,function(){ $('#bnt-articles').html(nextHtml).fadeTo('fast',1); });
		return false;
	});
	
	// HERO CYCLER
	var cycleTime = 60*1000;
	var heroTimer = setInterval("nextHero()", cycleTime);

	// PR HIDER
	$('div[id="pr_box_button"]').click(function(){
		var prIndex = $('div[id="pr_box_button"]').index(this);
		var prButton = $('div[id="pr_box_button"]').eq(prIndex);
		var prText = $('div[id="pr_text"]').eq(prIndex);
		if(prText.is(':visible'))
			{
			prText.fadeTo('fast',0,function(){
				prText.slideUp('fast');
				prButton.css('background-image','url(http://www.blogsmithmedia.com/www.engadget.com/media/show_full_pr_button.jpg)');
			});
			}
		else
			{
			prText.fadeTo('fast',0).slideDown('fast',function(){
				prText.fadeTo('fast',1);
				prButton.css('background-image','url(http://www.blogsmithmedia.com/www.engadget.com/media/hide_full_pr_button.jpg)');
			});
			}
	});

	// FTS NAV
	var $backBtn = $('#fts-back');
	var $nextBtn = $('#fts-next');
	var $thePort = $('#chart_port');
	var leftMargin = 0;
	var portWidth = 490;
	var barWidth = 35;
	var barAmountMove = 14;
	var movePortOnBar = 7;
	var amountMove = barWidth*barAmountMove;
	var maxMargin = (($('.follow .bar').length-8)*(barWidth*-1));
	var newMargin = 0;
	$nextBtn.click(function(){
		if(leftMargin >= maxMargin){
			$('.follow .bar .date-divider').html('<br/>');
			var newMargin = leftMargin-amountMove;
			$thePort.animate({ marginLeft: newMargin+'px' }, "normal");
			$('.follow .bar').removeClass('openBar');
			leftMargin = newMargin;
		}
		return false;
	});
	$backBtn.click(function(){
		if(leftMargin<0)
			{
			$('.follow .bar .date-divider').html('<br/>');
			var newMargin = leftMargin+amountMove;
			$thePort.animate({ marginLeft: newMargin+'px' }, "normal");
			$('.follow .bar').removeClass('openBar');
			leftMargin = newMargin;
			}
		return false;
	});
	$('.follow .bar').click(function(){
		var portMoved = 0;
		var thisIndex = $('.follow .bar').index(this);
		var hittingThisBar = ((thisIndex+1)-(barAmountMove*((leftMargin*-1)/portWidth)));
		var classes = $('.follow .bar').eq(thisIndex).attr('class');
		if (classes.indexOf('openBar') > -1)
			{
		    $('.follow .bar').eq(thisIndex).removeClass('openBar');
		   	$('.follow .bar .date-divider').html('<br/>');
		   	$('.fts-bar-close').hide();
			}
		else
			{
			if(hittingThisBar > movePortOnBar)
				{
				var moveFactor = hittingThisBar-movePortOnBar;
				var moveThisMuch = barWidth*movePortOnBar;
				newMargin = leftMargin-moveThisMuch;
				$thePort.animate({ marginLeft: newMargin+'px' }, "normal");
				leftMargin = newMargin;
				}
			$('.follow .bar').removeClass('openBar');
			$('.fts-bar-close').hide();
			$('.follow .bar .date-divider').html('<br/>');
			$('.follow .bar').eq(thisIndex).addClass('openBar').find('.fts-bar-close').show();
			$('.follow .bar .date-divider').eq(thisIndex).html(' - ')
			}
	});

	// VIDEO PAGING IN HUBS
	$('#video-hub-next').click(function(){
		changeVideoHubPlayer(1);
		return false;
	});
	$('#video-hub-prev').click(function(){
		changeVideoHubPlayer(0);
		return false;
	});
	
	// SWITCH HEROES (MANUAL)
	$('.my-little-hero .hero_menu a').live('click',function(){
		clearInterval(heroTimer);
		heroTimer = setInterval("nextHero()", cycleTime);
		var heroIndexNow = $('.my-little-hero .hero_menu').index($(this).parent().parent());
		var heroIndexNew = $('.my-little-hero .hero_menu:eq('+heroIndexNow+') a').index(this);
		if($('.my-little-hero:eq('+heroIndexNow+') .hero_bigheadline').hasClass('hero_bigheadline_open'))
			{
			$('.my-little-hero').eq(heroIndexNow).fadeOut('normal',function(){
				$('.my-little-hero').eq(heroIndexNew).fadeIn(150,function(){
					closeHeroBigHeadline(heroIndexNow);
				});
			});
			return false;
			}
		$('.my-little-hero').eq(heroIndexNow).fadeOut(150,function(){ $('.my-little-hero').eq(heroIndexNew).fadeIn(150); });
		return false;
	});

	// HIDE THE LAST COMMA ON FILED UNDER
	if($('.filed_under').length)
		{
		var filedUnderOriginal = jQuery.trim($('.filed_under').html());
		var filedUnderNew = filedUnderOriginal.slice(0,-1);
		$('.filed_under').html(filedUnderNew);
		}
	
	// COLLAPSIBLE COMMENTS
	if($('#comments').length)
		{
		var $expandLink = $('.expand_children');
		$('.child').parent().prev().find('.parent .expand_children').show();
		var commentIndex = new Array();
		var counter = 0;
		$('.expand_children a').each(function(){
			commentIndex[counter] = $('.parent .expand_children a').index(this);
			counter++
		});	
		for(i=0; i<commentIndex.length; i++)
			{
			var commentCount = 0
			$('.parent').eq(commentIndex[i]).parents('.commentlinks').nextAll().each(function() {
	    			if($(this).find('div:first').is('.child')) commentCount++;
				else return false;
			});
			$('.parent').eq(commentIndex[i]).find('.expand_children a').html(commentCount+' replies');
			}
		var $badComments = $('.level0 .container_contents_holder, .level1 .container_contents_holder');
		$('.level0, .level1').prepend('<div class="badComment_msg">This comment has been down-ranked into oblivion. <a href="">View comment</a></div>');
		$('.badComment_msg a').live('click',function(){
			if($(this).html()=='View comment') $(this).html('Hide comment').parent().next().show();
			else $(this).html('View comment').parent().next().hide();
			return false;
		});
		$expandLink.click(function(){
			if($(this).parents('.commentlinks').next().find('div:first').is(':visible')) $(this).css('background-image','url(http://www.blogsmithmedia.com/www.engadget.com/media/reply_arrow.png)');
			else $(this).css('background-image','url(http://www.blogsmithmedia.com/www.engadget.com/media/reply_arrow.png)');
			$(this).parents('.commentlinks').nextAll().each(function() {
	    			if($(this).find('div:first').is('.child')) $(this).find('div:first').toggle();
				else return false;
			});
			return false;
		});
		}

	// ARCHIVE CODE	
	var cal = $('.col2_archives_main');
	$("#archive_prev").live("click", function(){		
		rotateMonth($(this).find('a').attr('id'));		
		return false;
	});
	$("#archive_next").live("click", function(){
		rotateMonth($(this).find('a').attr('id'));		
		return false;
	});
	function rotateMonth(month){
		$.ajax({
			type : 'POST',
			url : '/index.php?a=archive-grab&svar_archive='+month+'&lPivots=svar_archive',
			type: 'html',
			success : function (data) {
				 var goodPart = data.split('<script type="text/javascript">');
				 cal.fadeTo('fast',0,function(){
				 	cal.html(goodPart[0]).fadeTo('fast',1);
				 });
			}   
		});
	}

	// DAN'S TIP US CODE
	$('#tipus_popup_holder .submit').click(function(){
		var dataStrTip = $('#tipUsForm').serialize();
		$.post('/?a=send-tip&id=tips', dataStrTip, function(data) {
			alert('Thanks for the tip!');
			location.reload(true);
			// hideTipUs();
		});
		return false;
	});
	
	// CT code start
	
	$('.faq_arrow a').click(showAnswerBody);
	$('.faq_question a').click(showAnswerBody);
	
	$('.sprite_readmore a').live('click',function(){
		var heroIndexNow = $('.my-little-hero').index($(this).parents('.my-little-hero'));
		openHeroBigHeadline(heroIndexNow);
		return false;
		});
	$('.sprite_close a').live('click',function(){
		var heroIndexNow = $('.my-little-hero').index($(this).parents('.my-little-hero'));
		closeHeroBigHeadline(heroIndexNow);
		return false;
		});
	
	$('#topstories .a_block').hover(function(){
		$(this).addClass('a_block_hover');
	},function(){
		$(this).removeClass('a_block_hover');
	});
	
	$('#anon_selector div').click(anonSelector);
	
	$('#tipus_tab, .nav_tipus, .footer_tipus').click(showTipUs);
	
	$('#tipus_cancel').click(hideTipUs);
	$('#tipus_overlay').click(hideTipUs);
	
	$('#nav_dropdown .current').click(openSearchNavDropdown);
	$('#nav_dropdown .nav_popup a').click(selectSearchNavDropdown);
	
	$('#headlink').hover(
		function() { $('a.engadget_us_hdr',this).css({'background-position':'bottom', 'border-bottom':'none'}); $('ul', this).css('display', 'block'); },
		function() { $('a.engadget_us_hdr',this).css({'background-position':'top', 'border-bottom':'none'}); $('ul', this).css('display', 'none'); });

	$('#footerlink').hover(
		function() { $('a.engadget_us_hdr',this).css({'background-position':'bottom', 'border-bottom':'none'}); $('ul', this).css('display', 'block'); },
		function() { $('a.engadget_us_hdr',this).css({'background-position':'top', 'border-bottom':'none'});  $('ul', this).css('display', 'none'); });
	
	$('#engadget_hdr_login').click(clickHeaderLogin);
	$('#engadget_hdr_register').click(clickRegisterLogin);
	
	$('#login_popup .cancel, #register_popup .cancel, #register_finish').click(function(){
			hideHeaderPopups();
			return false;
	});
	
	$('#comments .comment_report').click(function(){
		$(this).siblings('.comment_report_popup').toggle().end().parent('.comment_report_holder').toggleClass('popup_open');
		return false;
	});
	$('#comments .comment_report_popup .cancel').click(function(){
		$(this).parent().parent().hide().siblings('.comment_report').removeClass('sprite_selected').parent('.comment_report_holder').removeClass('popup_open');																
	});
	
	
	$('#tbox_gallery .thumb').hover(
		function(){ if(!$(this).parent('.thumb').hasClass('thumb_selected')) $(this).children('.hover_border').show(); },
		function(){ $(this).children('.hover_border').hide(); });	
	
	$('#podcasts .podcast_sort_dropdown .current, #recap .recap_sort_holder .current').click(function(){
		$(this).siblings('.popup').toggle();
		return false;
	});
	$('#podcasts .podcast_sort_dropdown .popup a').click(function(){
		l_sSelectedHtml = $(this).html();
		$(this).addClass('selected').siblings().removeClass('selected').end().parent('.popup').hide();
		$('#podcasts .podcast_sort_dropdown .current').html(l_sSelectedHtml);
		return false;
	});

	$('#recap .orb_center').hover(function(){
		$(this).children('.orb_tooltip').show();
		$(this).next('div').show();
	}, function(){
		$(this).children('.orb_tooltip').hide();
		$(this).next('div').hide();
	});
	$('#recap .orb_tooltip').click(function(){
		window.location = $(this).children('.article-url-jar').html();
	});
	
	$('.col2_poll .col2_poll_submit a').click(function(){
		$('.col2_poll').toggle();
		$('.col2_poll2').toggle();		
		return false;
    	});
	
	$('.col2 .archives_bottom .date_cell a').live('mouseover',function(){
		if(!$(this).parent().hasClass('gray')) $(this).siblings('.post_count').show("fast", showFix);	
	 });
	$('.col2 .archives_bottom .date_cell a').live('mouseout',function(){
		if(!$(this).parent().hasClass('gray')) $(this).siblings('.post_count').hide("fast", hideFix);
	 });
	 $('.col2 .archives_bottom .date_cell.gray a').live('click',function(){ return false; });
	
	$('.blogroll .post_content .post_body .blogroll_poll .poll_submit a').click(function(){
		$(this).parent().siblings(".blogroll_poll_selections_holder").children("li").children("input").hide();
		$(this).parent().siblings(".blogroll_poll_selections_holder").children("li").children("label").addClass("results_label");		
		$(this).parent().parent().siblings(".results").show();
		$(this).parent().hide();
		return false;
    	});
    
    	// THIS IS WHAT KILLS STUFF WHEN YOU CLICK OFF
	$(document).click(function() {
		hideHeaderPopups();
		$('#nav_dropdown .nav_popup').hide();
		$('.share_popup:visible').hide();
		$('.post_share').removeClass('sprite_selected');
	});
	$('#login_popup, #register_popup, #register_finish, .share_popup, #nav_dropdown .nav_popup').click(function(e) {
		e.stopPropagation();
	});
	
	// BREAKING and FEATURED MODULE
	$("a.swap").click(function () {
		$(".featured_posts").hide();
		$(".breaking_posts").fadeIn();
		$(".featured_on_header").hide();
		$(".breaking_on_header").show();
		return false;
	});
	$("a.swapBack").click(function () {
		$(".breaking_posts").hide();
		$(".featured_posts").fadeIn();
		$(".breaking_on_header").hide();
		$(".featured_on_header").show();
		return false;
	});
	
});  

// VIDEO HUB
function changeVideoHubPlayer(way)
	{
	var startingID = parseInt($('#numerator').text())-1;
	var videoCount = $('.video-info').length;
	var videoOn = startingID+1;
	if(way && videoOn < videoCount) startingID++;			
	else if(way && videoOn == videoCount) startingID = 0;			
	if(!way && videoOn > 1) startingID--;
	else if(!way && videoOn == 1) startingID = videoCount-1;
	var videoNowOn = startingID+1;
	var videoID = $('.video-info:eq('+startingID+')').attr('id');
	var videoTitle = $('.video-info:eq('+startingID+') .video-info-title').text();
	var videoLength = $('.video-info:eq('+startingID+') .video-info-length').text();
	var videoDate = $('.video-info:eq('+startingID+') .video-info-date').text();
	var videoHeight = $('.video-info:eq('+startingID+') .video-info-height').text();
	var $player = $('#hub-video-player-holder');
	var videoPlayer = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="313" height="[[[HEIGHT]]]" id="viddler_[[[ID]]]"><param name="movie" value="http://www.viddler.com/simple/[[[ID]]]/" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><embed src="http://www.viddler.com/simple/[[[ID]]]/" width="313" height="[[[HEIGHT]]]" type="application/x-shockwave-flash" allowScriptAccess="always" allowFullScreen="true" name="viddler_[[[ID]]]"></embed></object>';
	var newPlayer = videoPlayer.replace(/\[\[\[HEIGHT\]\]\]/gi, videoHeight).replace(/\[\[\[ID\]\]\]/gi, videoID);
	$player.empty().html(newPlayer);
	$('#numerator').text(videoNowOn);
	$('#hub-video-player-date').text(videoDate);
	$('#hub-video-player-title').text(videoTitle);
	$('#hub-video-player-length').text('('+videoLength+')');
	}


// BASIC COOKIE FUNCTIONS
function getCookie(c_name)
	{
	if (document.cookie.length>0)
		{
		c_start=document.cookie.indexOf(c_name + '=');
		if (c_start!=-1)
			{
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(';',c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
			}
		}
	return '';
	}

function setCookie(c_name,value,expiredays)
	{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ '=' +escape(value)+
	((expiredays==null) ? '' : ';expires='+exdate.toGMTString())+'; path=/';
	}

// HERO CYCLER
function nextHero(){
	if($('body').hasClass('hero-is-open') == false && location.href.match(/engadget.com/g))
		{
		var heroLength = $('.hero_menu').eq(0).find('.hero_link').length;
		var heroActive = $('.hero_link_active:visible').prevAll('.hero_link').length;
		if((heroActive+1) < heroLength) $('.hero_link_active:visible').next('.hero_link').find('a').trigger('click');
		else $('.hero_menu:visible').find('.hero_link').eq(0).find('a').trigger('click');
		}
	if(!location.href.match(/engadget.com/g)) clearInterval(heroTimer);
	}

// MAKE SURE CALENDAR POP-UPS AREN'T OVERWRITING EACH OTHER
function showFix(){
	$('.col2 .archives_bottom .date_cell .post_count').hide();
	$(this).show();	
}
function hideFix(){
	$(this).hide();	
}

function clickHeaderLogin(){
	hideHeaderPopups();
	$('#login_popup').show();
	$('#engadget_hdr_login').addClass('sprite_selected engadget_hdr_register_active');
	return false;
}

function clickRegisterLogin(){
	hideHeaderPopups();
	$('#register_popup .register_proper').show();
	$('#register_popup .register_finish').hide();
	$('#register_popup').show();
	$('#engadget_hdr_register').addClass('sprite_selected engadget_hdr_register_active');
	return false;
}

function hideHeaderPopups(){
	$('#login_popup').hide();
	$('#register_popup').hide();
	$('#engadget_hdr_register').removeClass('engadget_hdr_register_active sprite_selected');
	$('#engadget_hdr_login').removeClass('engadget_hdr_register_active sprite_selected');
}

function openSearchNavDropdown(){
	$('#nav_dropdown .nav_popup').show();
	return false;
	
}

function selectSearchNavDropdown(){
	$('#nav_dropdown .nav_popup').hide();
	$('#nav_dropdown .current').html(  $(this).html() ); 
	return false;
}

function showTipUs(){
	window.scrollTo(0,130);
	$('#tipus_overlay').height( $('body').height()+200 );
	$('#tipus_tab').hide();
	$("#tipus_popup_holder").show();
	return false;
}
function hideTipUs(){
	$('#tipus_tab').show();
	$("#tipus_popup_holder").hide();
	
	return false;
}

function anonSelector(){
	$('#anon_selector .selected').removeClass('selected');
	$(this).addClass('selected');	
}

function closeHeroBigHeadline(eqAlf){
	$('body').removeClass('hero-is-open');
	var l_nHeight = $('.my-little-hero:eq('+eqAlf+') .hero_bigheadline .top_content').css('height');
	if(!parseInt(l_nHeight)) l_nHeight = $('.my-little-hero:eq('+eqAlf+') .hero_bigheadline .top_content').height();
	$('.my-little-hero:eq('+eqAlf+') .hero_bigheadline').animate({'height':l_nHeight},100);
	$('.my-little-hero:eq('+eqAlf+') .hero_bigheadline').removeClass('hero_bigheadline_open');
	return false;
}
function openHeroBigHeadline(eqAlf){
	$('body').addClass('hero-is-open');
	var l_nHeight = $('.my-little-hero:eq('+eqAlf+') .hero_bigheadline .bottom_content').css('height');
	if(!parseInt(l_nHeight)) l_nHeight = $('.my-little-hero:eq('+eqAlf+') .hero_bigheadline .bottom_content').height();
	$('.my-little-hero:eq('+eqAlf+') .hero_bigheadline').animate({'height':l_nHeight},100, function(){
		$('.my-little-hero:eq('+eqAlf+') .hero_bigheadline').addClass('hero_bigheadline_open');
	});
	return false;
}

function showAnswerBody() {
	l_xFaqArrowSprite = $(this).parent().parent().find('.faq_arrow');
	l_xFaqArrowSprite.toggleClass("sprite_selected");
	l_xAnswerBody = $(this).parent().parent().siblings('.faq_answer');
	l_xAnswerBody.slideToggle("fast");
	return false;
}