// Laddas sist på sidan så vi hoppar document ready för tillfället - då behöver vi inte vänta på kundo

// Laddar diagrammet om viktsidan laddas om
if(window.location.pathname.substr(0,6) == '/vikt/') {
	getGraph();
	updateDataTable();
	 $("#period option[value='"+$.cookie('period')+"']").attr("selected", true);
}


// Laddar diagrammet om den offentliga viktsidan laddas om
if(window.location.pathname.substr(0,6) == '/visa/') {
	getGraph();
	 $("#period option[value='"+$.cookie('period')+"']").attr("selected", true);
}


switchPassword();

$('#username').each(function() {
	if ($.trim($(this).val()) == '') $(this).val($(this).attr('title'));
	if ($(this).val() == $(this).attr('title')) $(this).addClass('exampleText');
}).focus(switchText).blur(switchText);

$('#header form').submit(function() {
	$(this).find('input[type=text][title!=""]').each(function() {
		if ($(this).val() == $(this).attr('title')) $(this).val('');
	});
});

// Lägger till popup-event
$("#share").colorbox({innerWidth:400, innerHeight:180});


$(".popup input:checkbox").live("click", function(){

   $("#url").toggleClass('active');
	
	var status = 'off';
	if ($(this).attr('checked')) {
		status = 'on';
	}

	$.ajax({
		type: "GET",
		url: "/delningsstatus/"+status+"/"
	});
	
});


// Hanterar datumväljare vid invägning
$("input.datepicker").datepicker({
	dateFormat: 'yy-mm-dd',
	showButtonPanel: true,
	constrainInput: true,
	duration: 'fast',
	maxDate: '+1w',
	minDate: '-1y',
	 onSelect: function(dateText, inst) {
		 $('.new input.weight').focus();
	 }
});


// Ny viktloggning
$('.new input').keypress(function(e) {
	if(e.keyCode == 13) {
		var logday = $(".new input.logday").attr('value');
		logWeight(logday);
	}
});

$(".new span").live("click", function () {
	var logday = $(".new input.logday").attr('value');
	logWeight(logday);
});


// Radera loggning
$("tr td .btn-radera").live("click", function () {
	var logday = $(this).closest('tr').attr('id').substr(5);
	deleteWeight(logday);
});


// Ändra vikt
$("tr td .btn-andra").live("click", function () {
	var weightfield = $(this).closest('tr').children().eq(2);
	var weight = $(weightfield).text().split(" ");
	var logday = $(weightfield).closest('tr').children().eq(1).text();

	$(this).closest('td').html('<span class="btn-spara">Spara</span>');
	$(weightfield).html('<input type="text" class="weight" name="weight" value="'+weight[0]+'" /> kg');
	$('input', weightfield).focus();

	$("tr td .btn-spara").bind("click", function () {
		logWeight(logday);
	});
	$('input:last').keypress(function(e) {
		if(e.keyCode == 13) {
			logWeight(logday);
		}
	});
});


$.tablesorter.addParser({
	id: "vikt",
	is: function(s) {
		return false;
	},
	format: function(s) {
		return $.tablesorter.formatFloat(parseFloat(s.slice(0,-3)));
	},
	type: "numeric"

});

$("#toplista table").tablesorter({
	headers: {
		1: {
			sorter:'vikt'
		},
		5: {
			sorter:'vikt'
		},
		6: {
			sorter:'vikt'
		},
		7: {
			sorter:'vikt'
		}
	}
});


$("#period select").bind("change", function(){
	 var period = $(':selected', this).val();
	 $.cookie('period', period, { expires: 90, path: '/' });
	 getGraph();
	 if(window.location.pathname.substr(0,6) != '/visa/') {
		 updateDataTable();
	 }
});


$("#pw_forgotten_form #submit").bind("click", function(){
	var email = $(this).prev().val();

	$.ajax({
		type: "GET",
		url: "/pw_reminder/"+email+"/",
		success: function(data){
			$("#pw_forgotten_form").html("<div>"+data+"</div>");
		}	
	});
	
	return false;
});

// Funktioner ---------------------------------------------------------

function switchText() {
	if ($(this).val() == $(this).attr('title')) {
		if ($(this).attr('id') == 'password2') $(this).attr('type', 'password');
		$(this).val('').removeClass('exampleText');
	} else if ($.trim($(this).val()) == '') {
		if ($(this).attr('type') == 'password') $(this).attr('type', 'text');
		$(this).addClass('exampleText').val($(this).attr('title'));
	}
}


function switchPassword() {
	$('#password2').hide();
	$('#password').show();

	$('#password').focus(function() {
		 $('#password').hide();
		 $('#password2').show();
		 $('#password2').focus();
	});
	$('#password2').blur(function() {
		 if($('#password2').val() == '') {
			  $('#password').show();
			  $('#password2').hide();
		 }
	});
}


function logWeight(logday) {

	var weight = $('input:last').val();
	if (weight < 1) {
		alert('Det verkar som du missat att fylla i en vikt.');
		return false;
	} else if (weight > 300) {
		alert('Det verkar som du har angivit en orimligt hög vikt.');
		return false;
	} else if (weight < 35) {
		alert('Det verkar som du har angivit en orimligt låg vikt.');
		return false;
	}

	$.ajax({
		type: "POST",
		url: "/invagning/",
		data: "logday="+logday+"&weight="+weight,
		success: function(data){
			if (data.substr(0,5) == 'error') { alert(data.substr(6)); return; }
			setSavingNotice();
			getGraph();
			getStatus();
			updateDataTable();
		}
	});
}

function deleteWeight(logday) {

	$.ajax({
		type: "POST",
		url: "/radera/",
		data: "logday="+logday,
		success: function(data){
			if (data.substr(0,5) == 'error') { alert(data.substr(6)); return; }
			getGraph();
			getStatus();
			updateDataTable();
		}
	});
}


function setSavingNotice() {
	$('.new .btn-spara').before('<span id="saving">Vikten sparad!</span>');
	setTimeout('removeSavingNotice()', 1500);
}

function removeSavingNotice() {
	$('#saving').fadeOut(500, function () {
		$('#saving').remove();
	});
}

function getStatus() {

$.ajax({
		type: "GET",
		url: "/getstatus/",
		success: function(data){
			if (data.substr(0,5) == 'error') { alert(data.substr(6)); return; }
			$("#statusbar").html(data);
		}
	});
}


function makeArray(data) {

	var arr1 = data.split("|");
	var arr = [];

	for (var i = 0; i < arr1.length; i++) {
		 var arr2 = arr1[i].split(",");
		 var x = parseFloat(arr2[0]);
		 var y = parseFloat(arr2[1]);

		 arr.push([x,y]);

	}
	return arr;
}

function updateDataTable() {
	$.ajax({
		type: "GET",
		url: "/getdataTable/"+$.cookie('period')+'/',
		success: function(string){
			$('.inner table').html(string)
		}
	});
}

function getGraph() {
	
	var status = '';
	var parts = window.location.pathname.split("/");
	if (parts[2].length > 0) {
		status = parts[2]+'/';
	}


	$.ajax({
		type: "GET",
		url: "/getdata/"+$.cookie('period')+'/'+status,
		success: function(string){

			var parts 		= string.split("#");

			var adjusted 	= makeArray(parts[0]);
			var good 		= makeArray(parts[1]);
			var goodAuto	= makeArray(parts[2]);
			var bad	 		= makeArray(parts[3]);
			var badAuto		= makeArray(parts[4]);

			var options = {
				grid: {
					show: true,
					color: "#FFFFFF",
					backgroundColor: "#5DC7DB",
					labelMargin: 12,
					tickColor: "#7DD2E2",
					aboveData: false,
					borderWidth: 0
				},
				 xaxis: {
					mode: "time",
					timeformat: "%d/%m",
					//autoscaleMargin: 1,
					minTickSize: [1, "day"]
				},
				yaxis: {
					tickDecimals: 1
					//autoscaleMargin
				}
			};


			 $.plot($("#graph"), [
				 {
						data: adjusted,
						color: "#FFFFFF",
						lines: { show: true, fill: false, lineWidth: 5 }
				  },
				  {
						data: good,
						color: "#9EC547",
						points: { show: true, radius: 5, fill: true, fillColor:"#9EC547", lineWidth:0}
				  },
				  {
						data: goodAuto,
						color: "#9EC547",
						points: { show: true, radius: 2, fill: true, fillColor:"#9EC547", lineWidth:0}
				  },
				  {
						data: bad,
						color: "#F60409",
						points: { show: true, radius: 5, fill: true, fillColor:"#F60409", lineWidth:0}
				  },
				  {
						data: badAuto,
						color: "#F60409",
						points: { show: true, radius: 2, fill: true, fillColor:"#F60409", lineWidth:0}
				  }
			 ], options);

		}
	 });
}
