﻿var showTestIsComplete = true;

$(window).load(function() {
	resizeMe();
	checkReportStatus();
	computePercentage();
	//	submitViewportForm();
});

$(document).ready(function() {
	initialize();
});

function initialize() {
	resizeMe();

	$(window).resize(function() {
		resizeMe();
	});

	$("input:radio").hide();

	setupQuestionDropdown();
	loadNextQuestion();
	enableSaveNote();
	initNotes();
	setNextPrevButtons();
//	opacify();
//	checkReportStatus();
//	computePercentage();
	enableHelpClose();
	enabledCloseLiteTest();

	$("#logo").click(function() {
		location.href = "/Test.aspx/All";
	});
}

function submitViewportForm() {
	$("#viewportForm").ajaxSubmit({ dataType: 'json',
		success: function(data) {
			//alert("viewport data submitted");
		}
	});
}

/* Set the next and previous buttons
************************************/
function setNextPrevButtons() {
	$("#nextQuestionAction").click(function() {
		loadNextQuestion();
		return false;
	});

	$("#prevQuestionAction").click(function() {
		loadPrevQuestion();
		return false;
	});
}

/* Initialise the slider
************************/
function opacify() {
	$("#slider").css('opacity', .5);
	$("#slider").hover(function() {
		$("#slider").css('opacity', 1);
	}, function() {
		$("#slider").css('opacity', .5);
	});

	$("#addNoteAction").css('opacity', .5);
	$("#addNoteAction").hover(function() {
		$("#addNoteAction").css('opacity', 1);
	}, function() {
		$("#addNoteAction").css('opacity', .5);
	});
}

/*
Setup the dropdown for questions 
********************************/
function setupQuestionDropdown() {
	$("#questionForms .answer").each(function() {
		var option = $("<li></li>").html($(this).find("h1").text())
			.attr("title", $(this).find("input[name=fieldResult.ReportField.ReportFieldId]").val());

		var type = $("<span></span>").addClass("type");
		if ($(this).find(".slider").length > 0) {
			option.append(type.addClass("rating"));
		} else if ($(this).find(".binarySelector").length > 0) {
			option.append(type.addClass("bin"));
		}

		$("#questionSelect").append(option);

		// Set prepop values
		var value = $(this).find("input[name=fieldResult.Result]:checked").val();
		if (value > 0)
			setDropdownValue(option.attr("title"), value);
	});

	$("#questionSelect li:first").addClass("selected");
	/*
	$("#questionSelect").hover(function() {
		$(this).css("background-color", "#323232");
		$("#questionSelect li").show();
		$("#questionSelect .selected").addClass("highlight");
	}, function() {
		$(this).css("background-color", "");
		$("#questionSelect li").not(".selected").hide();
		$("#questionSelect li").removeClass("highlight");
	});
	*/
	
	$("#questionSelect li").not(":first").hide();
	//$("#questionSelect li").hover(function() { $(this).addClass("highlightItem"); }, function() { $(this).removeClass("highlightItem"); });
//	$("#questionSelect li").click(function() {
//		loadQuestion($(this).attr("title"));
//		$(this).parent().find("li").removeClass("selected");
//		$(this).addClass("selected");
//		$("#questionSelect li").not($(this)).hide();
//	});
}

function setDropdownValue(fieldId, value) {
	var menuItem = $("#questionSelect li[title=" + fieldId + "] .type");
	if (menuItem.hasClass("rating")) {
		menuItem.html("(" + value + "/5)");
	} else if (menuItem.hasClass("bin")) {
		if (value == 2)
			menuItem.html("(yes)");
		else if (value == 1)
			menuItem.html("(no)");
	}
}

/************************
   Load next question 
************************/
function loadNextQuestion() {
	var form = $("#questionForms .reportFieldId[value=" + $("#actionPanel .reportFieldId").val() + "]").parent(".answer").next().clone(true);
	if (form.html() == null) {
		form = $("#questionForms .answer:first").clone(true);
	}
	bindQuestionForm(form);
}

/***************************
   Load previous question 
***************************/
function loadPrevQuestion() {
	var form = $("#questionForms .reportFieldId[value=" + $("#actionPanel .reportFieldId").val() + "]").parent(".answer").prev().clone(true);
	if (form.html() == null) {
		form = $("#questionForms .answer:last").clone(true);
	}
	bindQuestionForm(form);
}

/**********************
    Load question 
**********************/
function loadQuestion(reportFieldId) {
	var form = $("#questionForms .reportFieldId[value=" + reportFieldId + "]").parent(".answer").clone(true);
	bindQuestionForm(form);
}

/**********************************
   Bind the question to form  
**********************************/
function bindQuestionForm(form) {
	var target;
	if (form.find(".slider").length > 0) {
		target = $("#currentSlider");
		$("#binary").hide();
		$("#text").hide();
		$("#slider").show();
		animateResizePanel(34);
	} else if (form.find(".binarySelector").length > 0) {
		target = $("#binary");
		$("#binary").show();
		$("#slider").hide();
		$("#text").hide();
		animateResizePanel(34);
	} else if (form.find(".textAnswer").length > 0) {
		target = $("#text");
		$("#binary").hide();
		$("#slider").hide();
		$("#text").show();
		animateResizePanel(80);
	}

	// Reset the content
	$("#currentSlider").html("");
	$("#binary").html("");
	$("#text").html("");
	target.append(form);

	var reportFieldId = target.find("input[name=fieldResult.ReportField.ReportFieldId]").val();

	// set the dropdown to have the selected question selected
	$("#questionSelect li").slideUp();
	$("#questionSelect li[title=" + reportFieldId + "]").slideDown();

	var currentValue = form.find("input:checked").val();
	
	if (target.find(".slider").length > 0) { // We have a slider
		var sliderValue;
		if (currentValue) {
			sliderValue = currentValue;
		} else {
			sliderValue = 3;
		}

		target.find(".slider").gradable(function(value, x) {
			var selectedCheckbox = x.find("input[value=" + value + "]");
			submitAnswer(form, selectedCheckbox);
		}, { inactiveClass: "lt_gradable_inactive" });
	}

	if (target.find(".binarySelector").length > 0) { // We have a binary selector
		target.find(".binarySelector").append($("<li></li>").attr({ title: "yes", id: "yesAnswer" })).append($("<li></li>").attr({ title: "no", id: "noAnswer" }));
		target.find(".binarySelector li")
			.hover(function() {
				if (!$(this).attr("checked")) {
					$(this).css({ backgroundPosition: "-31px center" });
				}
			}, function() {
				if (!$(this).attr("checked")) {
					$(this).css({ backgroundPosition: "0 center" });
				}
			})
			.click(function() {
				$(this).parent().find("li").css({ backgroundPosition: "0 center" }).removeAttr("checked");
				$(this).attr("checked", "checked");
				$(this).css({ backgroundPosition: "-62px center" });
				if ($(this).attr("title") == "yes") {
					var selectedCheckbox = $(this).parent().find("input[value=2]");
				} else {
					var selectedCheckbox = $(this).parent().find("input[value=1]");
				}
				submitAnswer(form, selectedCheckbox);
			});

		if (currentValue == 2) {
			target.find(".binarySelector li[title=yes]").css({ backgroundPosition: "-62px center" }).attr("checked", "checked");
		}
		if (currentValue == 1) {
			target.find(".binarySelector li[title=no]").css({ backgroundPosition: "-62px center" }).attr("checked", "checked");
		}
	}

	if (target.find(".textAnswer").length > 0) { // We have textual input
		target.find("a").click(function() {
			submitAnswer(form, $(".textAnswer .textQuestionAnswer"));
			return false;
		});
	}
}

function animateResizePanel(size) {
	var frameSize = $(window).height() - size;
	$("#liteTestPanel").animate({
		height:size
	}, 300);

	$("#theFrame").animate({ height: frameSize, top: size }, 300);
}

/********************
    Save answer
********************/
function submitAnswer(form, selectedInput) {
	var localnonsense = $("#questionForms ." + selectedInput.attr("class"));

	if (selectedInput.attr("type") == "radio") {
		selectedInput.attr("checked", "checked");
	} else {
	var iddy = selectedInput.attr("id");
		$(".textAnswer #" + iddy).val(selectedInput.val());
	}
	
	if ($("#viewportWidth").val() == "" && $("#viewportHeight").val() == "") {
		$("#viewportWidth").val($(window).width());
		$("#viewportHeight").val($(window).height());
	}

	$("#loader").show();
	form.ajaxSubmit({
		dataType: 'json',
		success: function(data) {
			if (data.Success == true) {
				computePercentage();
				setDropdownValue($(form).find("input[name=fieldResult.ReportField.ReportFieldId]").val(), selectedInput.val());
				setReportStatus(data.ReportStatus);
				loadNextQuestion();
			} else {
				alert("failed to save");
				for (var i = 0; i < data.length; i++) {
				}
			}
			$("#loader").hide();
		}
	});
}

/***********************
   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>").css("display", "inline-block").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;
		})
	);
}


/********************
    Resize iframe
********************/
function resizeMe() {
	var frameSize = $(window).height() - $("#liteTestPanel").height();
	$("#theFrame").css("height", frameSize + "px");
	$("#theFrame").css("top", $("#liteTestPanel").css("height"));
}


/************************* 
   Bind reportfields  (Not in use)
*************************/
function enableReportFields() {
	$("#questionForms .answer").each(function() {
		$(this).find("input[type=radio]").change(function() {
			alert("saving" + $(this).val());
			$(this).parent(".answer").ajaxSubmit({
				dataType: 'json',
				success: function(data) {
					if (data.Success == true) {
						computePercentage();
						alert("saved");
					} else {
						for (var i = 0; i < data.length; i++) {
							form.append($("<p></p>").html(data[i].Message));
						}
					}
				}
			});
		});

		/*********************************
		Clear report result value
		*********************************/
		/*
		form.find(".clearResultAction").click(function() {
		var reportFieldId = form.find("input[name=fieldResult.ReportField.ReportFieldId]").val();
		var releaseId = form.find("input[name=fieldResult.ReleaseId]").val();
		var requestId = form.find("input[name=requestId]").val();
		$.getJSON("/Report/Actions/RemoveResult.aspx", { rfid: reportFieldId, release: releaseId, requestId: requestId }, function(data) {
		if (data.success == true) {
		form.find("input[type=radio]").removeAttr("checked");
		} else {
		alert("fail");
		}
		});
		return false;
		});
		*/
	});
}

function checkReportStatus() {
	$.getJSON("/Report.aspx/CheckReportStatus/" + $("#reportId").val(), function(data) {
		setReportStatus(data.ReportStatus);
	});
}

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() {
	$(".clickaway").click(function() {
		$(this).remove();
	});
}

function enabledCloseLiteTest() {
	$("#closeLiteTest").click(function() {
		$("#liteTestPanel").slideUp(300, function() {
			location.href = $("#closeLiteTest").attr("href");
		});
		return false;
	});
}