﻿var showTestIsComplete = true;

$(window).load(function() {
	if ($("#offsiteTestHome").length == 0)
		return;
	checkReportStatus();
	computePercentage();
});

$(document).ready(function() {
	if ($("#offsiteTestHome").length == 0)
		return;

	$(".loader").hide();
	initialize();
});

function initialize() {
	enableSaveNote();
	initNotes();
	enableAnswerSubmit();
	//enableBinaryAnswer();
}

function enableAnswerSubmit() {
	$(".answer").each(function() {
		var form = $(this);

		// Rating
		if (form.find(".grady").length > 0) {
			form.find(".grady").gradable(function(value, x) {
				var selectedCheckbox = x.find("input[value=" + value + "]");
				selectedCheckbox.attr("checked", true);
				submitAnswerForm(form);
			}, { range: 5 });
		}

		// Binary
		if (form.find(".binary").length > 0) {
			form.find(".binary").binary(function(value) {
				submitAnswerForm(form);
			});
		}
	});
}

/* Submit answer
****************/
function submitAnswerForm(form) {
	form.find(".loader").show();
	form.ajaxSubmit({
		dataType: 'json',
		success: function(data) {
			form.find(".loader").hide();
			computePercentage();
			setReportStatus(data.ReportStatus);
		}
	});
}

/***********************
Compute percentage
***********************/
function computePercentage() {
	var questionCount = $("#questionForms .answer").length;
	var questionsComplete = $("#questionForms .answer input:checked").length;
	var percentage = (questionsComplete / questionCount) * 129;

	var noteCount = $("#noteList ul li").length;
	if (noteCount > 0) {
		percentage += 10;
	} else {
		if (questionCount == questionsComplete) {
			flashNoteIcon();
			$("#noteHelp").fadeIn();
		}
	}

	if ($("#progress").is(":hidden")) {
		$("#progress").show();
		$("#progress").css({ width: percentage + "px" }, 200);
	} else {
		$("#progress").animate({ width: percentage + "px" }, 200);
	}
}


/********************
   Flash note icon
*********************/
function flashNoteIcon() {
	$("#addNoteAction").css({ backgroundPosition: "0 center" });
	$("#addNoteAction").fadeOut(500);
	$("#addNoteAction").fadeIn(500);
	$("#addNoteAction").fadeOut(500);
	$("#addNoteAction").fadeIn(500, function() {
		$("#addNoteAction").css({ backgroundPosition: "-21px center" });
	});
	$("#addNoteAction").hover(function() { $(this).css({ backgroundPosition: "0 center" }); }, function() { $(this).css({ backgroundPosition: "-21px center" }); });
}

/****************
	Init notes
****************/
function initNotes() {
	$(".noteContainer").each(function() {
		var htmlNote = $(this).find(".htmlNote").html();
		var plainNote = $(this).find(".plainNote").html();
		var noteId = $(this).find(".noteId").html();
		addNoteToList(htmlNote, plainNote, noteId);
	});
	$(".noteContainer").remove();
}

/****************
    Save Notes
****************/
function enableSaveNote() {
	$("#addNote").draggable({ handle: "#feedbackNoteHeader" });
	$("#closeNotes").click(function() {
		$("#addNote").hide();
		$("#addNote input[name=note.ReportNoteId]").val("");
		$("#addNote #noteInput").val("");
		return false;
	});
	
	$("#addNoteAction").click(function() {
		if ($("#addNote").is(":visible")) {
			$("#addNote").hide();
		} else {
			$("#addNote").show();
			if ($("#noteList ul").length == 0) {
				getNotes();
			}
		}
		return false;
	});

	$("#saveNote").click(function() {
		if ($('#noteForm .error').length > 0) {
			$('#noteForm .error').remove();
		}
		$('#noteForm').ajaxSubmit({
			dataType: 'json',
			success: function(data) {
			if (data) {
					if (data.Success == true) {
						setReportStatus(data.ReportStatus);
						$("#noteInput").val("");
						addNoteToList(data.HtmlNote, data.Note, data.NoteId);
						computePercentage();
					} else {
						$('#noteForm').append($("<div></div>").attr("class", "error").append($("<ul></ul>")));
						for (var i = 0; i < data.length; i++) {
							$('#noteForm .error ul').append($("<li></li>").hide().html(data[i].Message).show());
						}
					}
				}
			}
		});
		return false;
	});
}

/****************
    View Notes
****************/
function getNotes() {
	$("#getNotesForm").ajaxSubmit({
		dataType: 'json',
		success: function(data) {
			if (data.Success == false) {
			} else if (data.length > 0) {
				$("#noteList").html("");
				$("#noteList").append($("<ul></ul>"));
				for (var i = 0; i < data.length; i++) {
					addNoteToList(data[i].HtmlNote, data[i].Note, data[i].ReportNoteId);
				}
			}
		}
	});
	return false;
}

/**********************
	Add note to list
**********************/
var truncationLength = 40;
function addNoteToList(htmlNote, plainTextNote, noteId) {
	var existingNote = $("#noteList ul #note_" + noteId);
	if (existingNote.length > 0) {
		existingNote.find(".truncatedNote").html(plainTextNote.substring(0, truncationLength) + "...");
		existingNote.find(".htmlNote").html(htmlNote);
		existingNote.find(".plainNote").html(plainTextNote);
		return;
	}

	var noteItem = $("<li></li>").attr("id", "note_" + noteId).hide();

	if ($("#noteList ul").length == 0) {
		$("#noteList").append($("<ul></ul>"));
	}

	$("#noteList ul").append(noteItem);
	noteItem.show();

	var truncateContainer = $("<span></span>").addClass("truncatedNote").html(plainTextNote.substring(0, truncationLength) + "...");
	var htmlNoteContainer = $("<span></span>").addClass("htmlNote").addClass("hidden").html(htmlNote);
	var plainNoteContainer = $("<span></span>").addClass("plainNote").addClass("hidden").html(plainTextNote);

	noteItem.append(truncateContainer).append(htmlNoteContainer).append(plainNoteContainer).append(
				$("<a></a>").html("").attr("href", "#").addClass("remove").click(function() {
					var sender = $(this);
					$.getJSON("/Report.aspx/RemoveNote", { noteId: noteId, reportId: $("#reportId").val() }, function(data) { // Remove note
						if (data.Success) {
							sender.parent("li").slideUp(200, function() {
								sender.parent("li").remove();
								computePercentage();
								setReportStatus(data.ReportStatus);
							});
						} else {
							alert("fail");
						}
					});
					return false;
				}
			)
		).append($("<a></a>").html("").addClass("edit").attr("href", "#").click(function() { // Edit note
			$("#addNote input[name=note.ReportNoteId]").val(noteId);
			$("#noteInput").val($(this).parent().find(".plainNote").text());
			$("#addNote").show();
			return false;
		})
	);
}

function checkReportStatus() {
	$.getJSON("/Report.aspx/CheckReportStatus/" + $("#reportId").val(), function(data) {
		setReportStatus(data.ReportStatus);
	});
}

//function setReportStatus(isComplete) {
//	if (isComplete && showTestIsComplete) {
//		showTestIsComplete = false;
//		$("#testComplete").fadeIn();
//		$("#closeTestAction").click(function() {
//			$("#testComplete").fadeOut();
//			return false;
//		});
//	}
//}

function setReportStatus(reportStatus) {
	if (reportStatus.IsComplete && showTestIsComplete) {
		if (reportStatus.IsSignedIn) {
			if (reportStatus.IsEligible) {
				$("#testsRequired").text("You can now submit your own site to be tested!");
			} else {
				$("#testsRequired").text("Only " + reportStatus.TestTokensRequired + " more tests and you can add your own site!");
			}
		}
		showTestIsComplete = false;
		$("#testComplete").fadeIn();
		$("#closeTestAction").click(function() {
			$("#testComplete").fadeOut();
			return false;
		});
	}
}


function enableHelpClose() {
	$("#firstTimeHelp .helpInfo").click(function() {
		$(this).remove();
	});
}
