/**
 * @author 		tom.bran
 * @project		Activia
 * @date		Dec 2010 
 */

var moodMap1 = '<div id="mood-wheel-wrapper"><div id="mood-wheel"><div id="mood-wheel-inner"><img src="/images/interface/bg_wonder-wheel2.png" width="431" height="286" border="0" usemap="#wheel-map1" id="mood-wheel-img" /><map name="wheel-map1" id="wheel-map1"><area shape="poly" coords="148,258,167,228,147,200,112,211,123,237" href="javascript:;" onclick="setBelly(1)" onmouseout="hoverOut()" onmouseover="hoverBelly(1)" title="Rate as 1" /><area shape="poly" coords="145,200,140,157,103,151,101,179,110,211" href="javascript:;" onclick="setBelly(2)" onmouseout="hoverOut()" onmouseover="hoverBelly(2)" title="Rate as 2" /><area shape="poly" coords="139,156,157,122,130,97,113,122,105,151" href="javascript:;" onclick="setBelly(3)" onmouseout="hoverOut()" onmouseover="hoverBelly(3)" title="Rate as 3" /><area shape="poly" coords="156,122,192,101,182,64,154,76,131,96" href="javascript:;" onclick="setBelly(4)" onmouseout="hoverOut()" onmouseover="hoverBelly(4)" title="Rate as 4" /><area shape="poly" coords="192,102,230,101,240,65,210,60,182,65" href="javascript:;" onclick="setBelly(5)" onmouseout="hoverOut()" onmouseover="hoverBelly(5)" title="Rate as 5" /><area shape="poly" coords="229,101,266,123,292,98,270,78,240,66" href="javascript:;" onclick="setBelly(6)" onmouseout="hoverOut()" onmouseover="hoverBelly(6)" title="Rate as 6" /><area shape="poly" coords="265,123,282,157,318,150,311,124,292,97" href="javascript:;" onclick="setBelly(7)" onmouseout="hoverOut()" onmouseover="hoverBelly(7)" title="Rate as 7" /><area shape="poly" coords="282,157,278,199,311,210,320,178,318,150" href="javascript:;" onclick="setBelly(8)" onmouseout="hoverOut()" onmouseover="hoverBelly(8)" title="Rate as 8" /><area shape="poly" coords="277,199,255,227,275,257,296,237,313,211" href="javascript:;" onclick="setBelly(9)" onmouseout="hoverOut()" onmouseover="hoverBelly(9)" title="Rate as 9" /></map></div></div></div>',
	moodMap2 = '<img src="/images/interface/bg_wonder-wheel1.png" width="431" height="286" border="0" usemap="#wheel-map2" id="mood-wheel-img" /><map name="wheel-map2" id="wheel-map2"><area shape="poly" coords="112,211,38,238,54,281,127,287,148,259,124,238" href="javascript:;" onclick="setMood(1)" onmouseout="hoverOut()" onmouseover="hoverMood(1)" /><area shape="poly" coords="105,152,1,130,2,250,109,211,102,179" href="javascript:;" onclick="setMood(2)" onmouseout="hoverOut()" onmouseover="hoverMood(2)" /><area shape="poly" coords="131,96,56,35,2,130,105,151,113,121" href="javascript:;" onclick="setMood(3)" onmouseout="hoverOut()" onmouseover="hoverMood(3)" /><area shape="poly" coords="182,65,164,2,57,34,131,95,156,76" href="javascript:;" onclick="setMood(4)" onmouseout="hoverOut()" onmouseover="hoverMood(4)" /><area shape="poly" coords="240,64,259,1,165,1,182,65,210,60" href="javascript:;" onclick="setMood(5)" onmouseout="hoverOut()" onmouseover="hoverMood(5)" /><area shape="poly" coords="292,97,361,37,326,5,259,2,240,66,272,79" href="javascript:;" onclick="setMood(6)" onmouseout="hoverOut()" onmouseover="hoverMood(6)" /><area shape="poly" coords="428,132,319,150,311,123,293,97,361,38,429,73" href="javascript:;" onclick="setMood(7)" onmouseout="hoverOut()" onmouseover="hoverMood(7)" /><area shape="poly" coords="312,210,430,249,430,132,318,150,320,179" href="javascript:;" onclick="setMood(8)" onmouseout="hoverOut()" onmouseover="hoverMood(8)" /><area shape="poly" coords="276,257,295,285,419,284,428,249,313,211,298,236" href="javascript:;" onclick="setMood(9)" onmouseout="hoverOut()" onmouseover="hoverMood(9)" /></map>',
	moodMap3 = '<img src="/images/interface/bg_wonder-wheel3.png" width="431" height="286" border="0" id="mood-wheel-img" />',
	moodVals = [];

$(document).ready(function(){
	$("#header").css({ 'padding-left': $(document).width()%2 });
	
	$('#nav-tertiary li a span').bind('mousedown', function() {
		//window.location = $(this).parent('a').attr('href');
		//$(this).parent('a').trigger('click');
	});
	
	// social
	$("#nav-social li.twitter a").bind('click', function() {
		assign_points();
	});
	$("#nav-social li.facebook a").bind('click', function() {
		assign_points();
	});
	if($('div.sign-up-form .error').length>0)
	{
		$('div.sign-up-form .error').wrap('<span class="errorholder"></span>');
	}
	/* initialise placeholder fallback - http://github.com/mathiasbynens/Placeholder-jQuery-Plugin */
	$('input, textarea').placeholder();
	
	/* un-hide day view list & star-rating block (hidden with CSS on page load, to avoid FOUT) */
	$("#day-plan-list").show();
	$(".star-rating").show();
	
	/* for browsers that can't handle the css :nth-child selectors, manually alternate table row colours */
	if(!Modernizr.opacity){
		$(".content-wrapper table.banded tr:odd td").addClass("odd");
	}
	alternateCommentColours();
	
	/* IE fix */
	$(".tlc-box .expert:last").addClass("expert-last-child");
	$('.module-row>div:first-child').addClass('first-in-row');
	$('.module-row>div:last-child').addClass('last-in-row');
	
	/* transform mood-wheel form into visual representation */
	if($("#mood-wheel-form").size()){
		var $mw = $("#mood-wheel-form"),
			$class = "";
		$mw.before(moodMap1);
		$("select#mood option:gt(0)").each(function(i){moodVals[i] = $.trim($(this).text());});
		
		var bellStartScale,
			bellyEndScale;
		if($mw.hasClass("day-1")){
			$class = $mw.attr("class");
			bellyStartScale = "Bloated";
			bellyEndScale = "Great";
		}else{
			bellyStartScale = "The same";
			bellyEndScale = "Better";
		}
		
		$("#mood-wheel-wrapper").addClass($class).append('<p class="belly-1 belly-score">'+bellyStartScale+'</p>');
		$("#mood-wheel-wrapper").append('<p class="belly-9 belly-score">'+bellyEndScale+'</p>');
	}
	
	// Disable the mood wheel depending on mood & belly score.
	if ($("#belly_score").val() != '' && $("#mood").val() != '') {
		disableWheel();
		$("p.belly-score").remove();
	} else if($("#mood").val()) {
		switchToMoodWheel();
	} else if (!$('#mood').val() || !$('#belly_score').val()) {
		$('.next-button a').css('backgroundPosition', '-290px 0%');
	}
	
	/* dynamically add the login form to the header */
	var $signIn = $("#sign-in"),
		$formHolder = $signIn.after("<div id='sign-in-form' />"),
		$signInForm = $("#sign-in-form"),
		$userPanel = $("#user-panel-content");
	
	$signIn.find("#sign-in-go").click(function(e){
		var signinFormFailed = false;
		var linkHref = $(this).attr ('href');
		
		$("#sign-in").before("<button id='sign-in-cancel' title='Cancel'>Cancel</button>");
		var $cancel = $("#sign-in-cancel");
		$cancel.hide();
		$signInForm.load(
			linkHref + " #sign-in-holder", 
			function(response, status, xhr) {
				if (status == "error") {
					window.location = linkHref;
				}
				else {
					
					$signIn.fadeOut("fast");
					$userPanel.animate({"height":$signInForm.height()},400);
					setTimeout(function(){
						$signInForm.fadeIn("slow");
						$cancel.fadeIn("slow");
					},400);
				}
			}
		);
		
		e.preventDefault();
	});
	$("#sign-in-cancel").live("click",function(){
		$(this).fadeOut("fast").delay(400).remove();
		$signInForm.fadeOut("fast");
		$userPanel.animate({"height":$signIn.height()},400);
		setTimeout(function(){
			$signIn.fadeIn("slow");
		},400);
	});
	
	/* draw graph at end of plan */
	if($("table#moods").size()){
		var $m = $("table#moods"),
			$data = {},
			$rows = $m.find("tbody tr");
		
		//$m.hide();
		var $moods = ["Out of control","Tired","Stressed","Playful","Adventurous","Happy","Confident","Energetic", "On top of the world"];
		$data.mood = [];
		$data.belly = [];
		$data.bellyGraph = [];
		
		$m.before("<div id='completed-graph'><h3>Days</h3></div>");
		var $g = $("#completed-graph");
		
		for (var m = 0; m < 14; m++) 
        {
            $data.mood[m] = 0;
            $data.belly[m] = 0;
            $data.bellyGraph[m] = 0;
        }
        
        for (var i = 0, k = $rows.size(); i < k; i++)
        {
            var day = parseInt($("td:eq(0)", $rows[i]).text());
            var mood = parseInt($("td:eq(1)", $rows[i]).text());
            var belly = parseInt($("td:eq(2)", $rows[i]).text());
            
            $data.mood[day-1] = mood;
            $data.belly[day-1] = belly;
            
            if(i == (k-1))
                var maxBelly = belly;
        }
        
        
        for (var m = 0; m < 14; m++) 
        {
            if($data.belly[m] < $data.belly[m-1]) 
                $data.belly[m] = $data.belly[m-1];
            $data.bellyGraph[m] = maxBelly > 0 ? ((8/maxBelly) * $data.belly[m] >> 0) + 1 : 0;
            var tooltip = !($data.mood[m] != 0 && $data.belly[m] != 0) ? "" : "tooltip";
            $g.append('<p class="mood-'+$data.mood[m]+'"><span class="js-hide">Day</span> <b>'+(m+1)+'</b><span class="js-hide">:</span> <span class="belly-'+$data.bellyGraph[m]+" "+tooltip+'" title="'+(tooltip ? $moods[$data.mood[m]-1] : "")+'">mood '+$data.mood[m]+', belly '+$data.belly[m]+' </span></p>');
        }
	}
	
	/* custom tooltips */
	$(".tooltip").tooltip();
	
	/* pop for restart plan actions */
	$("a.restart-plan-button").attr("href","javascript:;").colorbox(
		{
			href:'/plans/restart_confirm #restart-confirm',
			width:500,
			title:false,
			opacity:0.4
		}
	);
	
	/* colorbox popup, for 'restart plan' button */
	$("#header .restart-button a").attr("href","javascript:;").colorbox(
		{
			href:'/plans/restart_confirm #restart-confirm',
			width:500,
			title:false,
			opacity:0.4
		}
	);
	/* colorbox popup, for editing/uploading a profile image */
	$("a#edit-avatar").attr("href","javascript:;").colorbox(
		{
			href:'/users/avatar #user-avatar',
			width:500,
			title:false,
			opacity:0.4
		}
	);
	
	/* colorbox popup, for user badge links */
	$("a.my-badge, a#badge-explained").attr("href","javascript:;").colorbox(
		{
			href:'/pages/badges #badge-explained',
			width:500,
			height:320,
			title:false,
			opacity:0.4
		}
	);
	$('#cboxContent .close-button').live('click', function(){
		$.fn.colorbox.close();
	});
	
	/* homepage module expansion */
	/*$(".home-wrapper .module").each(function(){
		var $this = $(this);
		$this.data(
			{
				"module-width":$this.width(),
				"margin-left":parseInt($this.css("margin-left")),
				"margin-right":parseInt($this.css("margin-right"))
			});
		$this.hover(
			function(){
				$this.stop().animate({
					"font-size": "1.05em",
					"width": $this.data("module-width")+10,
					"margin-left":$this.data("margin-left")-5,
					"margin-right":$this.data("margin-right")-5
				},200);
			},
			function(){
				$this.stop().animate({
					"font-size":"1em",
					"width":$this.data("module-width"),
					"margin-left":$this.data("margin-left"),
					"margin-right":$this.data("margin-right")
				},200);
		});
	})*/
	
	/* convert marked-up content into tabbed interface */
	$(".tab-holder").contentTabs();
	
	/* back/next nav of items within 'all activities' page */
	$(".content-slider").each(function(){
		
		var $holder = $(this),
			$slider = $holder.find(".viewport"),
			$item = $holder.find(".viewport ul"),
			$nav = $holder.find(".activity-footer .items-nav"),
			slideAmount = 950;
		
		$holder.data("current",0);
		
		function checkLimits(index){
			if(index == 0){
				$nav.find("li.prev").addClass("disabled");
			}else {
				$nav.find("li.prev").removeClass("disabled");
			}
			if(index == $item.size()-1){
				$nav.find("li.next").addClass("disabled");
			}else {
				$nav.find("li.next").removeClass("disabled");
			}
		}
		function highlightNav(index){
			index++;
			$nav.find("li").removeClass("active");
			$nav.find("> li:eq("+index+") a").parent().addClass("active");
		}
		
		if ($item.size() > 1) {
			$nav
				.prepend("<li class='prev'><a href='javascript:;'><span class='hide'>Go to previous page </span>&#9668;</a></li>")
				.append("<li class='next'><a href='javascript:;'><span class='hide'>Go to next page </span>&#9658;</a></li>")
				.find("li:eq(1)").addClass("active");
			
			$("> li a",$nav).not(".prev a, .next a").each(function(index){
				$(this)
					.attr("href","javascript:;")
					.click(function(e){
						e.preventDefault();
						$slider.stop().animate({"left":-(slideAmount * index)+5000},500);
						highlightNav(index);
						checkLimits(index);
						$holder.data("current",index);
					});
			});
			checkLimits(0);
			
			$("> li.prev",$nav).click(function(e){
				e.preventDefault();
				var current = parseInt($holder.data("current"));
				if(current-1 >= 0){
					$slider.stop().animate({"left":-(slideAmount * (current-1))+5000},500);
					$holder.data("current",current-1);
					highlightNav(current-1);
					checkLimits(current-1);
				}
			});
			$("> li.next",$nav).click(function(e){
				e.preventDefault();
				var current = parseInt($holder.data("current"));
				if(current+1 < $item.size()){
					$slider.stop().animate({"left":-(slideAmount * (current+1))+5000},500);
					$holder.data("current",current+1);
					highlightNav(current+1);
					checkLimits(current+1);
				}
			});
		}else{
			$("> li a",$nav).attr("href","javascript:;").click(function(e){
				e.preventDefault();
			})
		}
	});
	
	/* pagination for comments - ajax overlay */
	$(".comments .pagination a").live("click", function(e){
		e.preventDefault();
		
		if($("#comments-holder").size()){
			var $c = $("#comments-holder");
			var $href = $(this).attr("href");
			$c.empty().addClass("loading-comments").load($href+" #comments-holder div",function(){setTimeout(function(){$c.removeClass("loading-comments");},100)});
			$(".pagination").load($href+" .pagination:eq(0) p", function(){
				alternateCommentColours();
			});
		}
	});
	
	/* home page panel animation */
	if($(".home-wrapper #centre-piece").size() && !$(".home-wrapper .welcome-back").size()){
		var $holder = $("#centre-piece"),
			$wrapper = $holder.find(".centre-piece-wrapper")
			$panels = $holder.find(".centre-panel");
		
		/* to allow users to tab through content on the homepage */
		$("#centre-piece .centre-panel:not(#panel-more) a").live("focus",function(){ $wrapper.animate({"left":0},400); });
		$("#panel-more a").live("focus",function(){	$wrapper.animate({"left":-460},400); });
		
		$wrapper.append("<div class='centre-panel' id='panel-more' />");
		$("#panel-more").load("/pages/find_out_more #more-info",function(){
			$(this).append("<a id='cancel-button' href='javascript:;'>Cancel</a>")
			$("#cancel-button").click(function(){
				$wrapper.animate({"left":0},400);
			});
		});
		
		$("#find-out-more a").attr("href","javascript:;").click(function(e){
			e.preventDefault();
			$wrapper.animate({"left":-460},400);
		});
	}
	
	/* report comments - ajax overlay 
	$(".comments input.report").live("click", function(e)
	{
		e.preventDefault();
		
		var $f = $(this).parents("form");
		var data = { 'comment_flag[activity_comment_id]': $f.find("input[name='comment_flag[activity_comment_id]']").val(),
		             'comment_flag[return_page]': $f.find("input[name='comment_flag[return_page]']").val(),
		             'comment_flag[is_ajax]': true};
		
		$.ajax({
            type: 'POST',
            url: $f.attr("action"),
            data: data,
            dataFilter: function(response, dataType) {
                return $.parseJSON(response);
            },
            success: function(data) {
                $("form#"+data.activity_comment_id).html("Reported");
            }
        });
	});*/
	
	/* initialise Formalise CSS */
	FORMALIZE.go();
	
	$(".activity-keep-this-checkbox").live("click",function(e) {
		var isChecked = $(this).is(':checked');
		var keepThisForm = $(this).parents('form');
		var url = keepThisForm.attr('action');
		var method = keepThisForm.attr('method');
		var activityId = keepThisForm.children('input.activity-id').val();
		var day = keepThisForm.find('.rating-day').val(); 
		var data = keepThisForm.serialize();
		data += "&" + escape("keep_this[is_ajax]") + "=1";
		$.ajax({
			type: method,
			url: url,
			data: data,
			success: keepThisSuccess,
			beforeSend: function (XMLHttpRequest) {
				$("#response-message-" + day + "-" + activityId).html("Updating Plan...");
			},
			dataFilter: function(response, dataType) {
				// hide the change this box after clicking keep this.
				var keep = keepThisForm.parent('.keep');
				var changebox = keep.siblings();
				if (isChecked)
					changebox.hide();
				else
					changebox.show();
				
			}
		});
	});
	
	
	/* Social Buttons - two functions to accommodate for the different widths*/
	$("#nav-social li.facebook a").bind('click', function() {
		window.open(this.href,'Share','width=500,height=400');
		return false;
	});
	
	$("#nav-social li.twitter a").bind('click', function() {
		window.open(this.href,'Share','width=800,height=500');
		return false;
	});
	
	/* live updating of content on TLC plan */
	$(".change-this").click(function(e){
		e.preventDefault();
		e.stopPropagation();
		var $i = $(this).parents(".item");
		if($i.data('loading') != true){
			$i.data('loading', true);
			$i.append('<img src="/images/interface/icon_spinner.gif" alt="Loading new item" class="spinner" />');
			$.ajax({
				url: '/plan_activities/swap_activity',
				data: 'plan_activity_id='+$i.data("plan-activity-id"),
				type: 'POST',
				success: function(data) {
					setTimeout(function(){
						data = $.parseJSON(data);
						h3 = $i.find("h3");
						h3.text(data.activity.title);
						// toggle the video overlay.
						span = $i.find("span");
						if (data.activity.video_url)
						{
							span.addClass('icon-active');
						}
						else
						{
							span.removeClass('icon-active');
						}
						$i.find("> div > a").attr("href",data.activity.activity_url);
						$i.find("> div > a > img").attr("src",data.activity.image_url);
						var $f = $(".controls .keep form", $i);
						var $day = $f.find("input[name='keep_this[day]']").val();
						$f.find("input[name='keep_this[activity_id]']").val(data.activity.id);
						$f.find("input[name='keep_this[plan_activity_id]']").val(data.plan_activity_id);
						$f.find(".keep-button").replaceWith('<label for="keep_this_value-'+$day+'-'+data.activity.id+'" class="keep-button"><input type="checkbox" class="activity-keep-this-checkbox" name="keep_this[value]" id="keep_this_value-'+$day+'-'+data.activity.id+'" value="1"> <span>Keep this</span></label>');
						$(".spinner",$i).remove();
						$i.data('loading','false');
					},200);
				}
			});
			
		}
	});
	
	/* user setting of star ratings - used across site */ 
	$(".star-rating").stars({
		cancelShow: false,
		callback: function(ui, type, value){
			var ratingForm = ui.element.children("form");
			var url = ratingForm.attr('action');
			var method = ratingForm.attr('method');
			var activityId = ratingForm.children('input.activity-id').val();
			var day = ratingForm.children('input.rating-day').val();
			var data = { 'rating[rating]': value, 'rating[is_ajax]' : 1, 'rating[day]' : day }
			$.ajax({
				type: 'POST',
				url: url,
				data: data,
				success: ratingSuccess,
				beforeSend: function (XMLHttpRequest) {
					$("#response-message-" + day + "-" + activityId).html("Saving...");
				},
				dataFilter: function(response, dataType) {
					//dataFilter is called on success. It is passed the returned data and the value of dataType, and must return the (possibly altered) data to pass on to success.
					data = $.parseJSON(response);
					$("#response-message-" + day + "-" + activityId).html(data.message);
				}
			});
		}
	});
	$(".star-rating label").hide();
	
	function ratingSuccess(){
		ga_track_rate($('h1').text());
	}
	
	/* day list view: modify if JS is available */
	if($("#day-plan-list").size() || $("#day-plan-blocks").size()){
		// wrap and set up controls for day plan pages content
		//$("#day-plan-list, #day-plan-blocks").wrap('<div id="day-plan-wrapper" />');
		/*$("#day-plan-wrapper")
		.before('<p class="nav-slider-prev"><a href="#">Go to previous day</a></p>')
		.after('<p class="nav-slider-next"><a href="#">Go to next day</a></p>');*/
		
		/* hide ratings for non-focussed days, on day plan, list view page */
		var $daysInactive = $("#day-plan-list .day:not(.day-active)");
		$daysInactive.addClass("day-inactive").find("p").hide();
		$("ul",$daysInactive).css("margin-left","-87px");
		$("h3",$daysInactive).addClass("inactive");
		
		
		/* slideshow object - used in day plan view pages */
		var Slides = {
			animating: false,
			urlHash: null,
			viewType: $("#day-plan-list").size() ? "list" : $("#day-plan-blocks").size() ? "blocks" : "null",
			currentSlide: 0,
			initialSlide: $(".day-active").index() != -1 ? $(".day-active").index() : 0,
			count: $(".day").size(), // default to 14? Will always be - unless we load content with JS/AJAX
			
			checkForEnds: function(){
				Slides.currentSlide == 0 ? $(".nav-slider-prev a").addClass("slider-disabled") : $(".nav-slider-prev a").removeClass("slider-disabled");
				Slides.currentSlide == Slides.count - 1 ? $(".nav-slider-next a").addClass("slider-disabled") : $(".nav-slider-next a").removeClass("slider-disabled");
			},
			contentAnim: function(e,animTo,replaceUrlHash){
				if(e){e.preventDefault();}
				
				if(replaceUrlHash == null) {
					// Set this to true for it to work
					replaceUrlHash = true;
				}
				
				if(!Slides.animating && (animTo >= 0 && animTo < Slides.count)){
					if(replaceUrlHash) {
						var hash = "view-" + (animTo + 1);
						window.location.hash = hash;
						Slides.urlHash = "#" + hash;
					}
					
					Slides.animating = true;
					
					$("#title-bar ul.calendar li.viewing").removeClass("viewing");
					$("#title-bar ul.calendar li:eq(" + animTo + ")").addClass("viewing");
					
					if (Slides.viewType == "list") {
						var $da = $(".day-active");
						$("ul", $da).animate({"margin-left": "-85px"}, 300);
						$("p", $da).hide();
						$("h3", $da).switchClass("", "inactive", 300);
						$da.switchClass("day-active", "day-inactive", 300);
						$("#day-plan-list").animate({"left": ((-153 * animTo) + 306)}, 400);
						$(".rating-response").text("");
						setTimeout(function(){
							Slides.currentSlide = animTo;
							Slides.checkForEnds();
							$(".day-active p").slideDown(500);
							$(".day:eq(" + Slides.currentSlide + ")").unbind("click");
							Slides.animating = false;
						}, 500);
						
						$(".day:eq(" + animTo + ") ul").animate({"margin-left": "0"}, 400);
						$(".day:eq(" + animTo + ") h3").switchClass("inactive", "", 300);
						$(".day:eq(" + animTo + ")").switchClass("day-inactive", "day-active", 300);
					
					} else if(Slides.viewType == "blocks") {
						$(".content-wrapper h1").html("Day " + (animTo + 1));
						$("#day-plan-blocks").animate({"left": (880 * -animTo)+5000}, 800, function(){  /* +5000: this avoids jQuery -/+10000px animation bug */
							Slides.currentSlide = animTo;
							Slides.checkForEnds();
							Slides.animating = false;
						});
						
					}
				}
			},
			getIndexFromUrlHash: function() {
				var hash = window.location.hash;
				animTo = null;
				var splitHash = hash.split('-');
				var dayTemp = parseInt(splitHash[1], 10);
				if(dayTemp && typeof dayTemp == 'number') {
					animTo = dayTemp - 1;
				}
				return animTo;
			},
			setStartPosition: function() {
				this.currentSlide = $(".day-active").index() != -1 ? $(".day-active").index() : 0;
				
				if (this.viewType == 'list') {
					$("#day-plan-list").css({"left": ((-153 * Slides.currentSlide) + 306)});
				} else if(this.viewType == 'blocks') {
					$("#day-plan-blocks").css({"left": (880 * -Slides.currentSlide)+5000}); /* +5000: this avoids jQuery -/+10000px animation bug */
				}
				
			},
			init: function(){
				/* button events */
				Slides.setStartPosition();
				$(".nav-slider-prev").click(function(e){Slides.contentAnim(e,Slides.currentSlide-1);});
				$(".nav-slider-next").click(function(e){Slides.contentAnim(e,Slides.currentSlide+1);});
				$("#day-plan-list .day-inactive").live("click",function(e){Slides.contentAnim(e,$(this).index());});
				$("#title-bar ul.calendar li").live("click",function(e){Slides.contentAnim(e,$(this).index());});
				
				/* allow keyboard navigation of sliders */
				function checkKey(e){
					switch (e.keyCode) {
						case 37:
						Slides.contentAnim(null,Slides.currentSlide-1);
						break;
						case 39:
						Slides.contentAnim(null,Slides.currentSlide+1);
						break;
					}
				}
				if ($.browser.mozilla) {$(document).keypress (checkKey);} else {$(document).keydown (checkKey);	}
				
				$("#day-plan-list .day, #day-plan-blocks .day").swipe({
					swipeLeft:function(){Slides.contentAnim(null,Slides.currentSlide+1);},
					swipeRight:function(){Slides.contentAnim(null,Slides.currentSlide-1);}
				});
				Slides.checkForEnds();
			}
		}
		
		Slides.init();
		
		function watchSlideUrl() {
			var hash = window.location.hash;
			if(hash != Slides.urlHash){
				Slides.urlHash = hash;
				
				var animTo = null;
				if(hash == "") {
					animTo = Slides.initialSlide;
				} else {
					animTo = Slides.getIndexFromUrlHash();
				}
				if(animTo != null && Slides.currentSlide != animTo) {
					Slides.contentAnim(null,animTo,false);
				}
			}
			setTimeout(watchSlideUrl, 200);
		};
		watchSlideUrl();
	}
	
	
	// Makes all the on links in the description field on the activity page open in a new window  
	$(".show-item .description a").each(function (){$(this).attr('target', '_blank')});
});

function setMood(id){
	$("#mood-wheel").data("pos","0 "+(-(id)*286)+"px");
	$("#mood-wheel").css("background-position","0 "+(-(id)*286)+"px");
	$("#mood option:eq("+id+")").attr('selected','selected');
	disableWheel();
	// AJAX call
	updateMood();
	return false;
}
function setBelly(id){
	$("#mood-wheel-inner").data("pos","-430px "+(-(id)*286)+"px");
	$("#mood-wheel-inner").css("background-position","-430px "+(-(id)*286)+"px");
	$("#belly_score option:eq("+id+")").attr('selected','selected');
	switchToMoodWheel();
	// AJAX call
	updateBellyScore();
	return false;
}
function hoverMood(id){
	$("#mood-wheel").css("background-position","0 "+(-(id)*286)+"px");
}
function hoverBelly(id){
	$("#mood-wheel-inner").css("background-position","-430px "+(-(id)*286)+"px");
}
function hoverOut(){
	var $moodPos = $("#mood-wheel").data("pos") != null ? $("#mood-wheel").data("pos") : "0 0";
	var $bellyPos = $("#mood-wheel-inner").data("pos") != null ? $("#mood-wheel-inner").data("pos") : "-430px 0";
	$("#mood-wheel").css("background-position",$moodPos);
	$("#mood-wheel-inner").css("background-position",$bellyPos);
}

function keepThisSuccess(data, textStatus, XMLHttpRequest)
{
	data = $.parseJSON(data);
	object_to_update = "#response-message-" + data.day + "-" + data.activity_id;
	$(object_to_update).html(data.message);
}

function ratingSuccess(data, textStatus, XMLHttpRequest) {
	data = $.parseJSON(data);
	$("#response-message-" + data.day + "-" + data.activity_id).html(data.message);
}

function updateBellyScore() {
	var moodForm = $("#mood-form");
	var url = moodForm.attr('action');
	var method = moodForm.attr('method');
	var data = { belly_score: $("#belly_score").val(), 'is_ajax': '1'}
	
	$.ajax({
		type: method,
		url: url,
		data: data,
		success: updateBellySuccessful,
		beforeSend: function (XMLHttpRequest) {}
	});
}

function updateMood() {
	var moodForm = $("#mood-form");
	var url = moodForm.attr('action');
	var method = moodForm.attr('method');
	//show loading spinner
	$('#go-to-plan').addClass('loading');
	
	var data = { 'mood': $("#mood").val(), 'is_ajax': '1'}
	$.ajax({
		type: method,
		url: url,
		data: data,
		success: updateMoodSuccessful,
		beforeSend: function (XMLHttpRequest) {
			// deactivate link
			$(".next-button a").bind('click', function() { return false; });
		}
	});
	
	
}

function updateMoodSuccessful(data, textStatus, XMLHttpRequest) {
	if ($("#mood-wheel-wrapper").length > 0) // only happens on the moods/add page/
	{
		is_plan_population_complete();
	}
}

function switchToMoodWheel() {
	$("#mood-title").text("How are you feeling?");
	$("#mood-wheel-wrapper").css({"background-position":"left 0"});
	$("#mood-wheel-inner").html(moodMap2);
	$("#new-user-progress span").removeClass("wheel-1").addClass("wheel-2");
	
	$("p.belly-score").addClass("inactive");
	for(var i=0,k=moodVals.length;i<k;i++){
		$("#mood-wheel-wrapper").append('<p class=mood-'+(i+1)+'>'+moodVals[i]+'</p>');
		$("#wheel-map2 area:eq("+i+")").attr("title",moodVals[i]);
	}
}

function updateBellySuccessful(data, textStatus, XMLHttpRequest) {}

isComplete = 0;
function disableWheel() {
	$("#mood-title").text("Thank you!");
	$("#mood-wheel-wrapper").addClass("wheel-disabled").css({"background-position":"left bottom"});
	$("#mood-wheel-inner").html(moodMap3);
	
	$("#new-user-progress span").removeClass("wheel-2");
}

function is_plan_population_complete() {
	// check the plan controller to see if plan population is complete.
	
	var url = '/plans/is_populated';
	var method = "POST";
	var data = ({ 'is_ajax': 1})
	$.ajax({
		type: method,
		url: url,
		dataType: 'json',
		data: data,
		beforeSend: function() {
			$(".next-button a").css('backgroundPosition', '-290px 0%');
		},
		success: enable_continue_to_plan
	});
	
	isComplete = setTimeout('is_plan_population_complete()', 1500);
}

function enable_continue_to_plan(data) {
	if (data.ready_to_continue == 1)
	{
		//hide loading spinner
		$('#go-to-plan').removeClass('loading');
		$(".next-button a").css('backgroundPosition', '-90px 0%');
		// re-enable the next button
		$(".next-button a").unbind('click');
		// clear the timeout.
		clearTimeout(isComplete);
	}
}
// disable the continue to plan button on page load;


/**
 * Class to Manage the url hash on the All Activies Page
 * 
 * @TODO move all All Activies Specific function onto this class
 *
 */
function AllActivities() {
	
	this.urlHash = null;
	this.currentTabId = 0;
	this.currentPageId = 0;
	this.slideAmount = 460;
	
	this.watchUrl = function() {
		var hash = window.location.hash;
		if (hash != this.urlHash) {
			this.urlHash = hash;
			
			if(hash != "") {
				var indexes = this.getIndexFromUrlHash();
				if(indexes) {
					var animToTabId = indexes[0];
					var animToPageId = indexes[1];
				}
			} else {
				var animToTabId = 0;
				var animToPageId = 0;
			}
			
			if(animToTabId != this.currentTabId || animToPageId != this.currentPageId) {
				
				// Set the tab
				if(animToTabId != this.currentTabId) {
					this.changeTabs(animToTabId);
				}
				
				// Set the page
				var slider = $("#tab-content-" + animToTabId + " .ratings");
				this.paginateNumbers(animToPageId, slider, false);
			}
		}
		setTimeout(function(){allActivities.watchUrl();}, 500, this);
	};
	
	/**
	 * Sets the url hash to allow for back button functionality
	 * 
	 */
	this.setUrlHash = function(tabId, pageId) {
		var urlHash = "";
		
		if (tabId == null) {
			// Only the page has changed get the new tab
			tabId = this.currentTabId;
		} else {
			this.currentTabId = tabId;
		}
		
		if (pageId == null) {
			// Only the tab has changed try to pick up the current
			if($("#tab-content-" + tabId + " ul.page-numbers li.active").length){
				pageId = $("#tab-content-" + tabId + " ul.page-numbers li.active").index();
			} else {
				// Can't find page id.. use 1st page
				pageId = 0;
			}
		}
		this.currentPageId = pageId;
		
		urlHash = "Tab:" + tabId + "-Page:" + pageId
		window.location.hash = urlHash;
	};
	
	this.getIndexFromUrlHash = function() {
		var hash = window.location.hash;
		var regex = /\d+/g;
		matches = hash.match(regex);
		if(matches.length != 2) {
			// They have messed with the url.. don't return anyting
			matches = null;
		}
		return matches;
	};
	
	this.paginateNumbers = function (index, sliderObj, setHash) {
		if(index <= (sliderObj.data().max-1) && index > -1) {
		
			if(setHash == null) {
				setHash = true;
			}
			
			this.currentPageId = index;
			sliderObj.data().current = index;
			holderObj = sliderObj.find(".ratings-holder");
			holderObj.animate({"left":-(this.slideAmount * index)},500);
			$(".page-numbers li:eq("+index+")", sliderObj).addClass("active").siblings().removeClass("active");
			this.checkSliderLimits(sliderObj);
			
			if (setHash) {
				allActivities.setUrlHash(null,index);
			}
		}
	}
	
	this.changeTabs = function (tabIndex) {
		this.currentTabId = tabIndex;
		tabObject = $("#tab-" + tabIndex);
		$(tabObject).addClass("active");
		$(tabObject).siblings().removeClass("active");
		var $id = $(tabObject).parent().children("li").index(tabObject);
		$(tabObject).parents(".tab-nav").siblings(".tab-holder").children(".tab").addClass("hide").end().children(".tab:eq("+$id+")").removeClass("hide");
	} 
	
	this.checkSliderLimits = function (sliderObj){
		$(".nav-slider-prev a", sliderObj).removeClass("slider-disabled");
		$(".nav-slider-next a", sliderObj).removeClass("slider-disabled");
		
		if(sliderObj.data().current == 0)
		{
			$(".nav-slider-prev a", sliderObj).addClass("slider-disabled");
		}
		if(sliderObj.data().current == (sliderObj.data().max-1))
		{
			$(".nav-slider-next a", sliderObj).addClass("slider-disabled");
		}
	}
}
/* function to alternate comment background colours by row. Called when moving between pages of comments */
function alternateCommentColours() {
	if(!$.support.opacity){
		$(".content.wrapper table tr:odd td").addClass("odd");
		$(".content-wrapper .comments #comments-holder div:even").addClass("odd");
	}
}


var allActivities = null;

function assign_points() {
	$.ajax({
        type: 'POST',
        url: '/points/create'
    });
}


/* Google Analytics tracking */
function ga_track_signup() {
	_gaq.push(['_trackEvent', 'CTA', 'Sign up']);
}

function ga_track_comment() {
	_gaq.push(['_trackPageview', "/comment/new"]);
}


function ga_track_continue() {
	_gaq.push(['_trackPageview', "/plan/continue"]);
	_gaq.push(['_trackEvent', 'CTA', 'Continue']);
}

function ga_track_findmore() {
	_gaq.push(['_trackPageview', "/content/view/shared"]);
	_gaq.push(['_trackEvent', 'CTA', 'Find out more and join']);
} 

function ga_track_sendemail(pagename) {
	_gaq.push(['_trackPageview', "/plans/email"]);
	_gaq.push(['_trackEvent', 'CTA', 'Send email', pagename]);
}

function ga_track_print(pagename) {
	_gaq.push(['_trackPageview', "/plans/print"]);
	_gaq.push(['_trackEvent', 'CTA', 'Print', pagename]);
}

function ga_track_twitter(pagename) {
	_gaq.push(['_trackPageview', "/content/share"]);
	_gaq.push(['_trackEvent', 'Social Media Share', 'Twitter', pagename]);
}

function ga_track_fb(pagename) {
	_gaq.push(['_trackEvent', 'Social Media Share', 'Facebook', pagename]);
}

function ga_track_rate(pagename) {
	_gaq.push(['_trackPageview', "/activity/rate"]);
	_gaq.push(['_trackEvent', 'Social Media Share', 'Rate', pagename]);
}

// FUTURE FUNCTIONS to track video player actions
function ga_track_videoplay(itemname) {
	_gaq.push(['_trackEvent', 'Video', 'Play', itemname]);
}
function ga_track_videopause(itemname) {
	_gaq.push(['_trackEvent', 'Video', 'Pause', itemname]);
}
// 25%, 50%, 75%, 100%
function ga_track_videoposition(percentage) {
	_gaq.push(['_trackEvent', 'Video', percentage, percentage]);
}
function ga_track_behindthescenes() {
	_gaq.push(['_trackPageview', "/activity/behindthescenes"]);
	_gaq.push(['_trackEvent', 'Youtube', 'Behind The Scenes']);
}

/* Google Analytics custom segmentation values */
function ga_seg_registered() {
	return ["_setCustomVar", 1, "User", "registered", 1];
}

function ga_seg_auth() {
	return ["_setCustomVar", 2, "Authenticated", true, 2];
}

function ga_seg_login() {
	return ["_setCustomVar", 3, "Login", true, 3];
}
