$(document).ready(function() {
	
	
	/*** Homepage ***/
	/* Update ticker */
	if($("body").hasClass("home")){
		interval = setInterval(removeFirst, 7000);	
	}
	function removeFirst(){
		var first = $('ul#snippets-list li:eq(0)').html();
		$('ul#snippets-list li:first').animate({opacity: 0}, 700).fadeOut('slow', function() {$(this).remove();}).fadeIn();
		addLast(first);
	}
	function addLast(first){
		last = '<li>'+first+'</li>';
		$('ul#snippets-list').append(last);
		$('ul#snippets-list li:last').animate({opacity: 1}, 700).fadeIn('slow');
	}
	
	/*** Home carousel ***/
	if($("body").hasClass("home")){
		$('#carousel').cycle({
			fx:    'fade',
			timeout: 4000,
			speed: 500,
			pager: '#carouselthumbs',
			pause: true,
			pagerAnchorBuilder: function(idx, slide) {
				return '#carouselthumbs li:eq(' + idx + ') a'; 
			},
			delay: -1000
		});
	}
	
	/*** Events carousel ***/
	if($("body").hasClass("events")){
		$.fn.cycle.updateActivePagerLink = function(pager, currSlideIndex) { 
			$(pager).find('li').removeClass('activetab') 
			.filter('li:eq('+currSlideIndex+')').addClass('activetab'); 
		};
		
		$('#tab-content').cycle({
		    fx: 'fade',
		    timeout: 0,
		    speed: 500,
		    pager: '#tabs',
		    pagerAnchorBuilder: function(idx, slide) {
		        return '#tabs li:eq(' + idx + ')';
		    }
		});
	}
	

	/*** 404 ***/
	$("#error-previous a", $("body#error")).click(function(e){
		e.preventDefault();
		history.go(-1);
	});

	
	
	/*** News Archive ***/
	if($("body").hasClass("newsarchive")){
		$("#archivedates li ul").css({display:"block" });
		$('#archivedates li').live('click', function() {
			if ($(this).hasClass('expandeddate')) {
				return false;
			}
		
			$('#archivedates li ul').slideUp('fast');
			$('.expandeddate').removeClass('expandeddate');
			$(this).children('ul').slideDown('fast');
			$(this).addClass('expandeddate');
			return false;
		});
		$('#archivedates li#currentactive').click();
		
		$('#archivedates li ul').click(function(event) {
			event.stopPropagation();
		});
	}
	
	
	
	$('#commentformcomment').submit(function() {
		if ($('#commentformcomment-content').val() == '') {
			alert('Please enter a comment');
			$('#commentformcomment-content').focus();
			return false;
		}
	
	});
	

	/*** Sitewide ***/
	$("a[href^='http'], a.external").attr('target','_blank');
	
	
	
	 $('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').removeClass('activetopitem');
			} else {
				$(this).children('.submenu').fadeIn('fast').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;
	});
	
	
	
	
	
	$("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 + "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").fadeOut("slow");
				$(this).addClass("active_tab").siblings("ul").fadeIn("slow");
			
				tabHeight = $("#" + tabId + " a").outerHeight();
				contentHeight = $(this).siblings("ul").outerHeight();
				if(tabId == "app_shop"){
					$("#" + tabId).css({height:(tabHeight+contentHeight) + "px" });
				} else {
					$("#" + tabId).animate({height:(tabHeight+contentHeight) + "px" });
				}
			}
		});
	});
	
	
	
	
		
	
	
	$('.relatize').relatizeDate();
	
	// Advert code
	// If hijack ad unit is present, grab the image and set it as background
    if ($('div[id*="Hijack_1400x1400"]').length > 0) {
		var image = $('div[id*="Hijack_1400x1400"]').find('iframe').contents().find('img');
        $('div[id*="Hijack_1400x1400"]').hide();
        $('#wrapper').css('background-image', 'url('+image.attr('src')+')');
        $("#wrapper").css({"background-color":"#f5f4f5","background-position":"50% -22px","background-repeat":"no-repeat","margin":"0px auto 0","width":"1400px"});
        var sidebarHeight = $("#sidebar").height();
        $("#main").css({"height":sidebarHeight})
        $('#wrapper-liner').css('background', 'url(/assets/images/wrapper-liner-bg.gif) repeat-x');
	}
	
	// we have to duplicate this code thanks to Googles random div naming conventions....
	if ($('div[id*="Hijack_1400x1400"]').length > 0) {	
        var image = $('div[id*="Hijack_1400x1400"]').find('iframe').contents().find('img');
		$('div[id*="Hijack_1400x1400"]').hide();
        $('#wrapper').css('background-image', 'url('+image.attr('src')+')');
		$("#wrapper").css({"background-color":"#f5f4f5","background-position":"50% -22px","background-repeat":"no-repeat","margin":"0px auto 0","width":"1400px"});
        $('#wrapper-liner').css('background-color', 'transparent');	
        var sidebarHeight = $("#sidebar").height();
        $("#main").css({"height":sidebarHeight})
        $('#wrapper-liner').css('background', 'url(/assets/images/wrapper-liner-bg.gif) repeat-x');
	}
	
});


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