$(document).ready(function() {

	 $('body').click(function() {
	 	$('#customise-stories, #filter-stories, #my-updates-list, .submenu').fadeOut('fast');
		$('#customise-trigger').removeClass('activebutton');
		$('#my-account-updates').removeClass('expanded');
		$('#topnav li').removeClass('activetopitem');
	 });
	 
	$('#customise-stories, #filter-stories, #my-updates-list, .submenu').click(function(event) {
		event.stopPropagation();
	});
	
	$('#topnav li').live('click', function(event) {
		if ($(this).children('.submenu').size() > 0) {
			event.preventDefault();
			if ($(this).children('.submenu').is(':visible')) {
				$(this).children('.submenu').fadeOut('fast');
				$(this).removeClass('activetopitem');
			} else {
				$(this).children('.submenu').fadeIn('fast');
				$(this).addClass('activetopitem');
			}
		}
	});
	
	$('#filter-trigger').live('click', function() {
		if ($('#filter-stories').is(':visible')) {
			$('#filter-stories').fadeOut('fast');
		} else {
			$('#filter-stories').fadeIn('fast');
		}
	});
	
	$('#customise-trigger').live('click', function() {
		if ($('#customise-stories').is(':visible')) {
			$('#customise-stories').fadeOut('fast');
			$('#customise-trigger').removeClass('activebutton');
		} else {
			$('#customise-stories').fadeIn('fast');
			$('#customise-trigger').addClass('activebutton');
		}
	});
	
	$('#my-account-updates').live('click', function() {
		if ($('#my-updates-list').is(':visible')) {
			$('#my-updates-list').fadeOut('fast');
			$('#my-account-updates').removeClass('expanded');
		} else {
			$('#my-updates-list').fadeIn('fast');
			$('#my-account-updates').addClass('expanded');
		}
	});
	
	$('#articlesizes button').click(function() {
		$('#articlesizes button').removeClass('selectedbutton');
		$(this).addClass('selectedbutton');
		$('#size').val($(this).val());
	});
	
	$('#frmresetbutton').click(function() {
		$('#mediumarticles').click();		
		$('#customise-stories input:checkbox').attr('checked', true);
		$('#featureToggle').attr('checked', true);
		$('#customise-stories').submit();
	});
	
	$('#frmcancelbutton').click(function() {
		$('body').click();
	});
	
	$("input.remember").focus(function(event) {
		if ($(this).val() == $(this).attr('title')) {
			$(this).val("");
			$(this).removeClass("subtle");
		}
	});
	
	$("input.remember").blur(function(event) {
		if ($(this).val() == "") {
			$(this).val($(this).attr('title'));
			$(this).addClass("subtle");
		} else {
			$(this).removeClass("subtle");
		}
	});
	
	$("input.remember").blur();
	
	$("form").submit(function() {
		$(this).find(".remember").each(function() {
			if ($(this).val() == $(this).attr('title'))
				$(this).val('');
		});
		return true;
	});
	
	$("a[href^='http'], a.external").attr('target','_blank');
	
    $('#upcoming-events').cycle({
		fx: 'fade',
		speed: 500,
		timeout: 5000,
		next: '.scroller-right',
		prev: '.scroller-left'
	});
	
	$('#top-stories').cycle({
	    fx: 'fade',
	    timeout: 0,
	    speed: 500,
	    pager: '#topstoriestabs',
	    pagerAnchorBuilder: function(idx, slide) {
	        return '#topstoriestabs li:eq(' + idx + ')'; 
	    }
	});
	
	$('#page-tabcontent').cycle({
	    fx: 'fade',
	    timeout: 0,
	    speed: 500,
	    pager: '#page-tablinks',
	    pagerAnchorBuilder: function(idx, slide) {
	        return '#page-tablinks li:eq(' + idx + ')'; 
	    }
	});	
	
	
		
		
	//used on popular sidepanel and user recent comments
	$("ul.tab_switcher").each(function(){	   
		var tabId = $(this).attr("id");
		var tabHeight = $("#" + tabId + " a").outerHeight();
		var contentHeight = $("#" + tabId + " ul").outerHeight();
		
		$("#" + tabId + " ul.tab_detail").css({marginTop:(tabHeight-1) + "px"});
		$("#" + tabId).css({height:(tabHeight+contentHeight) + "px" }).children("li").removeClass("noJs").children("a.tab_title").css({float:"left" }).siblings("ul.tab_detail").css({position:"absolute", display:"none" });
		$("#" + tabId + " a.tab_title:first").addClass("active_tab").next("ul.tab_detail").css({display:"block" });
		
		$("#" + tabId + " a.tab_title").click(function(e){
			e.preventDefault();
			
			if(!$(this).hasClass("active_tab")){
				$("#" + tabId + " a.tab_title").removeClass("active_tab").siblings("ul").stop(true,true).fadeOut("slow");
				$(this).addClass("active_tab").siblings("ul").stop(true,true).fadeIn("slow");
			
				tabHeight = $("#" + tabId + " a").outerHeight();
				contentHeight = $(this).siblings("ul").outerHeight();
				if(tabId == "app_shop"){
					$("#" + tabId).css({height:(tabHeight+contentHeight) + "px" });
				} else {
					$("#" + tabId).stop(true,true).animate({height:(tabHeight+contentHeight) + "px" });
				}
			}
		});
	});
	
	
	
	
	$('.morecontent').addClass('hidden');
	
	$('.toggle').live('click', function(e) {
		
		e.preventDefault();
	
		if ($(this).prev('.morecontent').is(':visible')) {
			$(this).prev('.morecontent').addClass('hidden');
			$(this).removeClass('less');
			$(this).addClass('more');
			$(this).html('Read more');
		} else {
			$(this).prev('.morecontent').removeClass('hidden');
			$(this).removeClass('more');
			$(this).addClass('less');
			$(this).html('Read less');
		}
	
	});
	
	$('.relatize').relatizeDate();
	
	// Advert code
	// If hijack ad unit is present, grab the image and set it as background
	if ($("#google_ads_div_BikeBiz_Home_Hijack_1400x1400").length > 0) {
		var image = $("#google_ads_div_BikeBiz_Home_Hijack_1400x1400").find('iframe').contents().find('img');
		$('#wrapper').css('background-image', 'url('+image.attr('src')+')');
		$('#wrapper-liner').css('background-color', 'transparent');
	}
	
	// If merge ad unit is present, 'merge' the leaderboard and sky
	if ($("#google_ads_div_BikeBiz_SiteWide_Merge_1x1").length > 0) {
		$('#sidebar').css('margin-top', '-13px');
	}
	
});


// All credit goes to Rick Olson.
(function($) {
	$.fn.relatizeDate = function() {
		return $(this).each(function() {
			if (newText = $.relatizeDate(this)) {
				$(this).text( newText )
			}
		})
	}

	$.relatizeDate = function(element) {
		if (relativeDate = $.relatizeDate.timeAgoInWords( new Date($(element).attr('title')), true )) {
			return relativeDate;
		} else {
			return false;
		}
	}

	// shortcut
	$r = $.relatizeDate

	$.extend($.relatizeDate, {
		shortDays: [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ],
		days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
		shortMonths: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ],
		months: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ],
	
		/**
	     * Given a formatted string, replace the necessary items and return.
	     * Example: Time.now().strftime("%B %d, %Y") => February 11, 2008
	     * @param {String} format The formatted string used to format the results
	     */
		strftime: function(date, format) {
			var day = date.getDay(), month = date.getMonth();
			var hours = date.getHours(), minutes = date.getMinutes();
	
			var pad = function(num) { 
				var string = num.toString(10);
				return new Array((2 - string.length) + 1).join('0') + string
			};
	
			return format.replace(/\%([aAbBcdHIjmMpSwyY])/g, function(part) {
				switch(part[1]) {
					case 'a': return $r.shortDays[day]; break;
					case 'A': return $r.days[day]; break;
					case 'b': return $r.shortMonths[month]; break;
					case 'B': return $r.months[month]; break;
					case 'c': return date.toString(); break;
					case 'd': return pad(date.getDate()); break;
					case 'H': return pad(hours); break;
					case 'I': return pad((hours + 12) % 12); break;
					case 'j': return date.getDate(); break;
					case 'm': return pad(month + 1); break;
					case 'M': return pad(minutes); break;
					case 'p': return hours > 12 ? 'pm' : 'am'; break;
					case 'S': return pad(date.getSeconds()); break;
					case 'w': return day; break;
					case 'y': return pad(date.getFullYear() % 100); break;
					case 'Y': return date.getFullYear().toString(); break;
				}
			})
		},
	  
		timeAgoInWords: function(targetDate, includeTime) {
			return $r.distanceOfTimeInWords(targetDate, new Date(), includeTime);
		},
	  
	    /**
	     * Return the distance of time in words between two Date's
	     * Example: '5 days ago', 'about an hour ago'
	     * @param {Date} fromTime The start date to use in the calculation
	     * @param {Date} toTime The end date to use in the calculation
	     * @param {Boolean} Include the time in the output
	     */
		distanceOfTimeInWords: function(fromTime, toTime, includeTime) {
			var delta = parseInt((toTime.getTime() - fromTime.getTime()) / 1000);
			if (delta < 60) {
				return 'less than a minute ago';
			} else if (delta < 120) {
				return 'about a minute ago';
			} else if (delta < (45*60)) {
				return (parseInt(delta / 60)).toString() + ' minutes ago';
			} else if (delta < (120*60)) {
				return 'about an hour ago';
			} else if (delta < (24*60*60)) {
				return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
			} else if (delta < (48*60*60)) {
				return '1 day ago';
			} else {
				var days = (parseInt(delta / 86400)).toString();
				if (days > 5) {
					return false;
				} else {
					return days + " days ago"
				}
			}
		}
	})
})(jQuery);
