(function($){
	$.fn.phraseCuePreview = function(options) {
		var opts = $.extend({
			phraseCue: " / ",
			sentenceCue: " // ",
			originalBefore: '<span style="display: none;">',
			originalAfter: '</span>'
		}, options);
		var base = $(this);

		base.find(".nonalphanum").each(function() {
			var nonalphanum = $(this);
			
			nonalphanum.after(
				opts.originalBefore + nonalphanum.text() + opts.originalAfter
			).hover(
				function() {
					nonalphanum.addClass("hover");
				},
				function() {
					nonalphanum.removeClass("hover");
				}
			).click(function() {
				if (nonalphanum.hasClass("phrase")) {
					nonalphanum.removeClass("phrase");
					nonalphanum.addClass("sentence");
					nonalphanum.text(opts.sentenceCue);
					
				} else if (nonalphanum.hasClass("sentence")) {
					nonalphanum.removeClass("sentence");
					nonalphanum.text(
							nonalphanum.next().text()
					);
					
				} else {
					nonalphanum.addClass("phrase");
					nonalphanum.text(opts.phraseCue);
				}
			});		
		});
		
		base.find(".period").click().click();
		
		
		base.submit(function() {
			base.find(".nonalphanum").each(function() {
				$(this).next().remove();
			});
			
			base.find("textarea[id='PhraseCuePdf']").val(
				base.find("div.passage").html()
			);
		});
		
		
	};
	
	$.fn.phraseCuePdf = function(option) {
		$(".confirmNewDialog").click(function(e) {
			e.preventDefault();
			$('#confirmNewDialog').modal();
		});
	};
	
	$.fn.navBack = function() {
		$(this).click(function() {
			window.history.back();
		});
	};
	
	$.fn.flash = function() {
		setTimeout(
			function() {
				$("#flashMessage.message").fadeOut(1000, function() {
					$("#flashMessage.message").remove();
				});	
			},
			5000
		);
	};
})(jQuery);


function isNonAlphanumericKey(event) {
	if (event == null)
		return false;

	var char = null;
	
	if (event.which == null) {
		char = String.fromCharCode(event.keyCode);    // IE
	} else if (event.which > 0) {
		char = String.fromCharCode(event.which);	  // All others
	} else {
	}

	if (char == null || char.match(/\w/))
		return false;

	return true;
}

function getWordCount(text) {
	if (text == null || text.length == 0) 
		return 0;	

	// Replace non-alpha with single space and then remove trailing/leading spaces
	// Then split and return number of words
	return text.replace(/[^\w']+/g, " ")
				.replace(/\ $/, "")
				.replace(/^\ /, "")
				.split(" ").length;
}

function updateWordCount(count) {
	$(".maze .wordCount .count").text(count);
	
	var max = $(".maze .wordCount .maximum").text();
	var min = $(".maze .wordCount .minimum").text();
	
	if (count > max || count < min) {
		$(".maze .wordCount .count").addClass("mazeError");
	} else {
		$(".maze .wordCount .count").removeClass("mazeError");
	}
}

function computeReadability() {
	
	var data = {
		"data[Maze][passage]":$(".maze .passage").val(),
		"data[Maze][options][]": []
	};
	
	$(".readability .options input:checked").each(function() {
		data["data[Maze][options][]"].push($(this).val());
	});
	
	var estimate = $(".readability input[name='estimateUrl']");
	
	if (estimate.length > 0) {
		$.post(
			estimate.val(),
			data,
			function(data, textstatus) {
				$(".readability .score").text("   ");
				
				for (var name in data) {
					var key = name.replace(/[\W\s]+/g, "");
					// console.log(key);
					$("#" + key).text(data[name]);
				}
			},
			"json"
		);
	}
}

function unbindDistractorRandomizer() {
	$(".maze .distractors").unbind('click').unbind('mouseover').unbind('mouseout');
}

function bindDistractorRandomizer() {
	// Populate from form for browser back button compatibility
	$(".maze .distractors").each(function() {
		var distractors = $(this).next().val().split(/\ /);
		var html = "";
		for (var i in distractors) {
			html += '<span class="distractor">' + distractors[i] + '</span>'; 
		}
		$(this).html(html);
	});
	
	$(".maze .distractors").click(function() {
		var distractors = this;
		var pos = $(this).prev().val();
	
		var target = $(this).prev().prev().text();
		if (! $(this).prev().prev().prev().hasClass("start")) {
			target = "";
		}

		$.post(
			$(".maze input[name='wordRandomizeUrl']").val() 
				+ "/pos:" + pos 
				+ "/target:" + target,
			{
				'data[Maze][distractorList]': $(".maze textarea[name='sample']").text()
			},
			function(data, textstatus) {
				var distractorsHtml = "";
				var d = "";
				for (var name in data) {
					distractorsHtml += "<span class=\"distractor\">" + data[name] + "</span>";
					d += data[name];
					if (name != (data.length - 1))  {
						d += " ";
					}
				}
				
				$(distractors).html(distractorsHtml)
				$(distractors).next().val(d);
			},
			"json"
		);
	});
	
	$(".maze .distractors").mouseover(function() {
		$(this).addClass("mouseOverDistractors");
	});
	
	$(".maze .distractors").mouseout(function() {
		$(this).removeClass("mouseOverDistractors");
	});
}

$(document).ready(function() {

	$("a.help").each(function() {
		$(this).tooltip();
	});
	
	$(".tooltip").tooltip({
		fade: 500,
		showURL: false 
	});
	

	if ($(this).find("#distractorEditor").length == 0) {
		$(".navigator input[value='Next']").click(function(e) {

			var wordCount = getWordCount($(".maze .passage").val());

			var max = $(".maze .wordCount .maximum").text();
			var min = $(".maze .wordCount .minimum").text();
			
			if ( wordCount > max) {
				e.preventDefault();
				alert("The passage word count cannot exceed " + max + " words. Please trim the passage by " + (wordCount - max) + " words.");
			} else if ( wordCount < min ) {
				e.preventDefault();
				alert("The passage word count must be at least " + min + " words. Please add " + (min - wordCount) + " words to the passage.");
			} else {
				return true;
			}
		});
		
		$(".maze .passage").keyup(function(event) {
	
			var wordCount = getWordCount($(this).val());
	
			updateWordCount(wordCount);
	
			/*
			if ( wordCount > $(".maze .wordCount .maximum").text() || wordCount < $(".maze .wordCount .minimum").text() ) {
				$(".navigator input[value='Next']").attr("disabled", "disabled");
			} else {
				$(".navigator input[value='Next']").removeAttr("disabled");
			}
	 		*/
			
			if (wordCount < $(".readability .wordCount .minimum").text()) {
				$(".readability .score").text("");
				$(".readability .compute").attr("disabled", "disabled");
				
				return;
			}
			
			$(".readability .compute").attr("disabled", "");
			
			if (! isNonAlphanumericKey(event) ) {
				return; 
			}
	
			computeReadability();	
		});
	
		$(".maze .passage").keyup();
	}
	
	$(".readability .compute").click(function() {
		var spinnerGifUrl = $(".readability input[name='spinnerGifUrl']").val();
	
		$(".readability .score").html("<img src=\"" + spinnerGifUrl + "\" />");
		
		computeReadability();
	});


	updateWordCount(getWordCount($(".maze .passage").val()));
	computeReadability();

	bindDistractorRandomizer();
	
	$(".toggleAnswers").toggle(
		function() {
			$(".maze div.answer").hide();
			$(".maze div.passage").show();
			$(this).text("Show Examiner's Copy");
		},
		function() {
			$(".maze div.answer").show();
			$(".maze div.passage").hide();
			$(this).text("Show Students' Copy");
		}
	);
	
	$(".toggleAnswers").click();
	
	// Page Preview
	$(".emailPdfDialog").click(function(e) {
		e.preventDefault();
		try {
			$('#emailPdfDialog').modal();
		} catch(ex) {
			// ie6 hack
			$('#emailPdfDialog').modal();
		}
	});


	$(".confirmNewMazeDialog").click(function(e) {
		e.preventDefault();
		$('#confirmNewMazeDialog').modal();
		//.bindSimpleButtons();
	});
	
	$("#emailPdfDialog input[type='submit']").click(function() {
		var data = {
			'data[emailPdf]':'Send PDF',
			'data[Message][from]': $("#emailPdfDialog input[name='data[Message][from]']").val(),
			'data[Message][to]': $("#emailPdfDialog input[name='data[Message][to]']").val(),
			'data[code]': $("#emailPdfDialog input[name='data[code]']").val()
		};
	
		// This calls cancel to close the form
		$("#emailPdfDialog input[type='button']").click();
		
		$("#emailPdfDialog input[name='data[Message][from]']").val(data['data[Message][from]']);
		$("#emailPdfDialog input[name='data[Message][to]']").val(data['data[Message][to]']);
		$("#emailPdfDialog input[name='data[code]']").val(data['data[code]']);
		
		$("#emailPdfDialog input[type='submit']").parents("form").ajaxSubmit(
			{
				'beforeSubmit': function() {
					var spinnerGifUrl = $(".readability input[name='spinnerGifUrl']").val();
					$("#emailPdfResponse").html("<div class='navigator'><img src=\"" + spinnerGifUrl + "\" /> Sending...</div>").modal();
				},
				'data': {
					'data[emailPdf]':'Send PDF'
				},
				'success': function(responseText) {
					$(".simplemodal-close").click();
					$("#container").prepend(responseText);
					$("#flashMessage.message").flash();
				}
			}
		);
	});
	
	
	$("#MazeDistractorSourceInternal").click(function() {
		$("#specifyDistractors").hide();
	});
	
	$("#MazeDistractorSourcePassage").click(function() {
		$("#specifyDistractors").hide();
	});
	
	$("#MazeDistractorSourceSpecify").click(function() {
		$("#specifyDistractors").show();
	});
	
	$("input[name='data[Maze][distractorSource]']:checked").each(function() {
		if ($(this).val() == "specify") {
			$("#specifyDistractors").show();
		}
	});
	
	$("#distractorEditor").show().ready(function() {
		var parent = $(this);
		
		var edit = $(this).find(".edit");
		var save = $(this).find(".save");
		var cancel = $(this).find(".cancel");
		var help = $("#mazeAlert");
		help.html("Remember to save or cancel your changes before proceeding");
		save.hide();
		cancel.hide();
		help.hide();
		
		var distractors = parent.find(".distractors");
		edit.show().click(function() {
			edit.hide();
			save.show();
			cancel.show();
			help.fadeIn(750);
			distractors.find(".distractor").each(function(i) {
				var value = $(this).html();
				var length = value.length;
				if (length < 5) {
					length = 5;
				}
				$(this).html('<input class="editDistractor" value="' + value + '" style="width: ' + length + 'em;" />');
			});

			$(".navigator input").attr("disabled", "disabled");
			unbindDistractorRandomizer();
			
		});
		
		$(this).find(".edit, .save, .cancel").each(function() {
			$(this).hover(function() {
				$(this).addClass("distractorEditorHover");
			}, 
			function() {
				$(this).removeClass("distractorEditorHover");
			});
		});
		
		save.hide().click(function() {
			edit.show();
			save.hide();
			cancel.hide();
			help.fadeOut(500);
			
			distractors.each(function(i) {
				var value = "";
				$(this).find(".distractor input").each(function() {
					value += $(this).val() + " ";
				});
				
				var trimmed = value.substr(0, value.length - 1);
				$(this).next("input[type='hidden']").val(trimmed);
			});
			
			$(".navigator input").removeAttr("disabled");
			bindDistractorRandomizer()
		});
		
		cancel.hide().click(function() {
			edit.show();
			save.hide();
			cancel.hide();
			help.fadeOut(500);
			
			$(".navigator input").removeAttr("disabled");
			bindDistractorRandomizer();
		});

	});
	
	$("#PhraseCuePreviewForm").phraseCuePreview();
	$("#PhraseCuePdfForm").phraseCuePdf();
	
	$(".navigator input[type='button'][value='Previous']").navBack();
});
