$(document).ready(function(){
	
	// goal_value = 5;
	// update_goal(dare_id, goal_value);
	
	// Toggles showing and hiding of the application.
	$("#show_app").click(function(){
		$("#goal_application").show();
        $.get('/ajax/clist/?action=remove&list=daretrackers&id='+dare_id);
        get_graph_data(dare_id);

	});
	$("#hide_app").click(function(){
		$("#goal_application").hide();
        $.get('/ajax/clist/?action=add&list=daretrackers&id='+dare_id);
	});

	// Toggles showing and hiding of the application.
	$("#show_graph").click(function(){
		$("#user_graph").show();
        $.get('/ajax/clist/?action=remove&list=daregraphs&id='+dare_id);
	});

	$("#hide_graph").click(function(){
		$("#user_graph").hide();
        $.get('/ajax/clist/?action=add&list=daregraphs&id='+dare_id);
	});

	// Sets the date picker to show up
	$("#current_selected_date").datepicker({ 
		onSelect: setDateFromDialog,
		dateFormat: "M d, yy",
		maxDate: '+0m +0w',
		showOn: "both", 
		buttonImage: "/ui/images/dares/calendar.gif", 
		buttonImageOnly: true 
	});

	// The save button, to update your progress.
	$("#save_dare_data").click(function(){

		$("#dare_notice .text").html("");

		var dare_is_complete_checked = $("#dare_is_complete").attr("checked");
		var dare_post_to_group_checked = $("#dare_post_to_group").attr("checked");
		var post_anonymous = $("#post_anonymous").val();
		var diary_notes = $("#diary_notes").val();
		if (diary_notes == 'Add Notes to your diary...')
		{
			diary_notes = '';
		}
		var calendar_value = $("#hidden_calendar_value").attr("value");

		var ogga = $("input[name=data_progress]").length;
		var data_progress = null;
		if(ogga >= 2) {
			data_progress = $("input:checked[name=data_progress]").val();
		} else {
			data_progress = $("#data_progress").attr("value");
		}		
		
		if(data_progress == null || (jQuery.trim(data_progress) == "" && dare_is_complete_checked != true)) {
			if (confirm('Would you like to delete your progress for ' + calendar_value + '?')) {
				var url = "/ajax/dare/tracker/";
				$.post(url, { dare_id: dare_id, date: calendar_value, clear: true }, function(data){ });
			}
			return;
		}

		if(dare_is_complete_checked == true) {
			var tracker_complete = 1;
		} else {
			var tracker_complete = 0;
		}

		if(dare_post_to_group_checked == true) {
			var post_to_group = 1;
		} else {
			var post_to_group = 0;
		}

		var url = "/ajax/dare/tracker/";
		$.post(url, {dare_id: dare_id, progress: data_progress, date: calendar_value, message: diary_notes, complete: tracker_complete, posttogroup: post_to_group, anonymous: post_anonymous}, function(data){
			if(data.response) {
				show_notice(data.response);
 				get_graph_data(dare_id);
			}
			if(data.error) {
				show_notice(data.error, "#FF0000");
			}

			if(data.post) {
				var dare_post_id = data.post.dare_post_id;
				//var dare_id = data.post.dare_id;
				var user_id = data.post.user_id;
				var title = data.post.title;
				var post = data.post.post;
				var anonymous = data.post.anonymous;
				var create_date = data.post.create_date;			
				window.location = document.location;
			}

		}, "json");
	});

	$("#my_goal_action").click(function(){
		var date_today = new Date();

		var foo = $("#hidden_calendar_value").attr("value");
		var date_parsed = foo.split("-");
		var date_current = new Date();
		date_current.setFullYear(date_parsed[0], date_parsed[1]-1, date_parsed[2]);

		// Are you in the past?
		if (date_current < date_today) {
			// If you are, tell the user this might not be a good idea.
			if(!confirm('Are you sure you want to update your goal for a date in the past?')) {
				return false;
			} 
		}

		if($("#my_goal_action").html() == "Edit Goal") {
			var current_goal_value = $(".my_goal .value span").html();
			$(".my_goal .value span").html("<input type=\"text\" value=\""+current_goal_value+"\" />");
			$(".my_goal .value span input").focus();
			$("#my_goal_action").html("Save Goal");
		} else {
			var current_goal_value = $(".my_goal .value span input").val();
			$(".my_goal .value span").html(current_goal_value);
			update_goal(dare_id, current_goal_value);
			$("#my_goal_action").html("Edit Goal");
		}
	});

	// If there is no default value for the textarea
	// signal the user to edit it.
	if($("#diary_notes").val() == "") {
		$("#diary_notes").val("Add Notes to your diary...");
		$("#diary_notes").css("color", "#999999");
	}

	$("#diary_notes").click(function(){
		if($("#diary_notes").val() == "Add Notes to your diary...") {
			$("#diary_notes").val("");
			$("#diary_notes").css("color", "#000000");
		} 
	});

	$("#diary_notes").blur(function(){
		if($("#diary_notes").val() == "") {
			$("#diary_notes").val("Add Notes to your diary...");
			$("#diary_notes").css("color", "#999999");
		} 
	});

});

function confirm_stop_taking(obj) {
	if (confirm('Are you sure you want to stop taking this dare? You can always retake the dare and continue where you left off (your history is never deleted).')) {
		window.location = obj.href;
	} 

	return(false);
}

// Update goal
function update_goal(dare_id, goal_value) {
	var calendar_value = $("#hidden_calendar_value").attr("value");
	var url = "/ajax/dare/goals/";
	$.getJSON(url, {dare_id: dare_id, goal: goal_value, date: calendar_value}, function(data){
		// printd(data);
	});
	get_graph_data(dare_id);
}

// Get the data for the graph, and then calls render_graph 
function get_graph_data(dare_id) {
	var progress_data = [];
	var goal_data = [];
	var url = "/ajax/dare/progress/?dare_id="+dare_id;

	$.getJSON(url,function(data){
		for (var i=0; i<data.progress.length; i++) {
			progress_data.push([data.progress[i][0], data.progress[i][1]]);
		}
		for (var i=0; i<data.goals.length; i++) {
			goal_data.push([data.goals[i][0], data.goals[i][1]]);
		}
		render_graph("graph", progress_data, goal_data);
	});
}

// Creates the graph based on the data
function render_graph(container_id, progress_data, goal_data) {
	var ele = document.getElementById(container_id);
	if(ele) {
		$.plot($("#"+container_id), 
			[{
				data: progress_data,
				label: "My Progress",
				lines: { show: true, fill: true, fillColor: "rgba(230, 230, 230, 0.6)" },
				points: { show: true, fillColor: "#FFCF43" }
			}, 
			{
				data: goal_data,
				label: "My Goal",
				lines: { show: true }
			}],
			{ 
				xaxis: { 
					mode: "time",
					timeformat: "%b %d" 
				},
				grid: {
					backgroundColor: "#FFFFFF"
				},
				legend: {
					position: 'sw' 
				}
			}
		);
	}
}

// Gets the data and updates the fields for a specific date && dare.
function get_progress(dare_id, date) {
	
	$("#dare_notice .text").html("");

	var url = "/ajax/dare/progress/?dare_id="+dare_id+"&date="+date;
	$.getJSON(url,function(data){
		if (tracker_type == 'bool')
		{
			$("#data_progress_yes").attr('checked', false);
			$("#data_progress_no").attr('checked', false);
			if (data.progress.progress == 1)
			{
				$("#data_progress_yes").attr('checked', true);
			}
			else if (data.progress.progress == 0)
			{
				$("#data_progress_no").attr('checked', true);
			}
		}
		else
		{
			if(data.progress.progress) {
				$("#data_progress").attr("value", data.progress.progress);
			} else {
				$("#data_progress").attr("value", "");
			}
		}

		if(data.progress.progress) {
			$("#diary_notes").val(data.progress.message);
		} else {
			$("#diary_notes").val("");
		}

		if(data.progress.progress) {
			$(".value span").html(data.goal);
		} else {
			$(".value span").html("");
		}

		$(".my_goal .value span").html(data.goal);

		if(data.response) {
			show_notice(data.response);
		}
		if(data.error) {
			show_notice(data.error, "#FF0000");
		}
	});
}

// Array of months so it can be translated to numbrs
var month_names = new Array();
month_names["Jan"] = "01";
month_names["Feb"] = "02";
month_names["Mar"] = "03";
month_names["Apr"] = "04";
month_names["May"] = "05";
month_names["Jun"] = "06";
month_names["Jul"] = "07"; 
month_names["Aug"] = "08"; 
month_names["Sep"] = "09"; 
month_names["Oct"] = "10"; 
month_names["Nov"] = "11"; 
month_names["Dec"] = "12";

// Date call back function - parses the date and then sets a hidden value
// with the date in a YYYY-MM-DD format so it can be passed to "get_progress"
function setDateFromDialog(date) {
	var reg_ex = /([A-Za-z]{3}) ([0-9]{1,2}), ([0-9]{4})/;
	var date_parts = date.match(reg_ex);
	if(date_parts) {
		var month = month_names[date_parts[1]];
		var day = date_parts[2];
		var year = date_parts[3];
		var date_string = year + "-" + month + "-" + day;
		$("#hidden_calendar_value").attr("value",date_string);
		get_progress(dare_id, date_string);
	}
} 

function show_notice(message, color) {
	if(color) {	
		$("#dare_notice .text").append("<span>"+message+"</span>");
	} else {
		$("#dare_notice .text").append(message);
	}
	if($("#dare_notice:visible").length != 1) {
		$("#dare_notice").show();
	}
}


// /////////////////////////////////////////////////////////////////////////////


$(document).ready(function(){
		$('.show-post-form').click(function() { 
				$('#post-form').fadeIn();
				return false;
			});

		$('.show-comment-form').click(function() {
				$(this).parent().siblings().children('.comment-form').fadeIn();
				return false;
			});

		$('.comment-form').ajaxForm({ 
				dataType:  'json', 
				success:   processForm 
			});
});

function processForm(data, statusText, el) {
	if ('pass' == data.status)
	{
		var target = '#'+data.dare_post_id+'-comment';
		$(target).fadeIn();
		$(target).append(data.comment);
		$(el).children('.error').empty();
		$(el).empty();
	}
	else
	{
		$(el).children('.error').html(data.error);
	}
}

function flag_dare(el) {
	$.getJSON(el.href, processFlag);
}

function processFlag(data, statusText, el)
{
	if ('pass' == data.status)
	{
		$('#dare-flag').fadeOut();
		$('#dare-flag').parent().html(data.msg);
	}
	else
	{
		$('#dare-flag').siblings('.error').children('li').html(data.msg);
		$('#dare-flag').siblings('.error').fadeIn();
	}
}