$(document).ready(function(){
	
	var valid = /^([a-zA-Z0-9\ ]+)$/;
	
	$(window).resize(function(){
		updateBody();
	});
	
	/**
	 * GLOBALS
	**/
	
	//checks url for unknown country notices
	checkLocale();
	//fixes layout bugs
	updateBody();
	
	$("#btn-change-location a").click(function(){
		$(this).html("loading...");
		$(this).addClass("hide");
		$(this).parent().find("img").addClass("hide");
		$.ajax({
			url: "/ajax/get-countries.do",
			data: {
				locale: window.ph_locale
			},
			success: function(data) {
				$("#country-list").removeClass("hide").html(data).focus().click();
				//bind event
				$("#country-list").change(function(){
					//change location
					ar = document.location.href.split("/");
					loc = ar[ar.length-1];
					document.location = "/" + $("#country-list").val() + "/" + loc;
				});
			}
		});		
		return false;
	});
	
	/**
	 * Homepage
	**/
	
	$("#txt-search").click(function(){
		if ($(this).val() == 'search...') {
			$(this).val('');
		}
	});
	
	$("#btn-txt-search").click(function(){		
		var reg = $("#txt-search").val();
		if (reg == "") {
			showError("Number plate cannot be empty!");
		} else if (reg == "search...") {
			showError("Number plate is unchanged from the default.");
		} else if (!valid.test(reg)) {
			showError("Number plate should only contain numbers and letters.");
		} else {
			hideError();
			$.ajax({
				url: "/ajax/search-plate.do",
				data: {
					plate: reg,
					locale: window.ph_locale
				},
				beforeSend: function () {
					$("#btn-txt-search").attr("disabled", "disabled");
				},
				success: function (data) {
					$("#results").empty().html(data);
					$("#btn-txt-search").removeAttr("disabled");
				},
				complete: function() {
					updateBody();
				}
			});
		}
		return false;
	});
	
	$("#txt-search").keyup(function(e){
		var code = (e.keyCode ? e.keyCode : e.which);
		if(code == 13) {
			$("#btn-txt-search").click();
		}	
	});
	
	$("#txt-search").keydown(function(e){
		//apply case force after user clicked field!
		if ($(this).val() != "search...") {
			$(this).css("text-transform", "uppercase");
		}
	});
	
	/**
	 * Plate page
	**/
		
	//images
	$("a.lightbox").click(function(){
		var url = $(this).attr("href");
		var lb = document.createElement("div");
		var im = document.createElement("img");
		//
		$(lb).addClass("lightbox");
		$(lb).css({'min-height':$(document).height()}).click(function(){$(this).remove();$(im).remove()});
		//
		$(im).addClass("lightboxItem");		
		$("body").append(lb);
		$("body").append(im);
		$(im).attr("src", url).css({
			"top": ($(window).height() / 2) - ($(im).outerHeight() / 2),
			"left": ($(window).width() / 2) - ($(im).outerWidth() / 2)
		});
		return false;
	});
	
	//comments
	$(".plateBtnComment").click(function(){
		var commentID = $(this).attr("id").replace(/\D/g, "");
		//delete other boxes
		if ($(".commentBox").length > 0) {
			$(".commentBox").remove();			
		}
		//remove previous alerts
		$(".error").remove();
		$(".ok").remove();
		//
		$("#plate-comment-" + commentID).after("<div class='commentBox'><textarea class='commentText'></textarea><p><button class='addComment'>Add comment</button></p></div>");
		//focus
		$(".commentText").focus();
		//bind to button
		$("button.addComment").click(function(){
			if ($(".commentText").val().length > 0) {
				$.ajax({
					type: "post",
					url: "/ajax/add-comment.do",
					data: {
						id: commentID,
						comment: $(".commentText").val()
					},
					success: function(data) {
						//remove previous alerts
						$(".error, .ok").remove();
						//get rid of comment box
						$(".commentBox").remove();
						//remove previous comments
						$("div.entry_" + commentID).remove();
						//reload the lot
						$("#plate-comment-" + commentID).after(data);
					},
					complete: function() {
						updateBody();
					}
				});
			}
		});
		return false;
	});
	
	/**
	 * RSS builder
	**/
	
	$("#rss-plate").keyup(function(e){		
		var plates = $(this).val().split(",");
		var str = "";
		for (var i = 0; i < plates.length; i++) {
			var plate = trim(plates[i]).replace(/([ ]+)/ig, "+");
			plate = plate.replace(/([^A-Z0-9\+]+)/ig, "");
			if (plate.length > 0) {
				str += "/" + plate.toUpperCase()
			}
		}
		$("#rss").val("http://" + document.location.hostname + "/feeds/" + window.ph_locale + "/rss/plate" + (str.split("/").length > 2 ? "s" : "") + str + (str.length > 0 ? ".xml" : ""));
	});
	
	$("#rss").click(function(){
		$(this).focus().select();
	});
	
	/**
	 * Submission page
	**/
	
	
	// don't show the plate field if user says they didn't get it
	$("input.plate_capture").change(function(){
		if ($(this).val() == 0) {
			$("#plate_container").fadeOut();
		} else {
			$("#plate_container").fadeIn();
		}
	});
	
	// attempts some very basic locality matching based off DVLA memory tags
	$("input#plate").keyup(function(e){
		var plate = $(this).val().replace(/ /ig, '').toUpperCase();
		if (plate.match(/^([A-Z]){2}([0-9]){2}([A-Z]){3}$/)) {
			$.ajax({
				type: "GET",
				url: "/ajax/find-location.do",
				data:{
					plate: plate
				},
				success: function(data) {
					$("input#location").val(data.toString());
				},
				error: function() {
				}
			});
		}
	});
	
	$("#frm-new").submit(function() {
		var safe = true;
		$(".req").each(function(){			
			// special check for plate - if user selected rant only, we ignore the plate field. hacky but fuck it.
			if ($("input[name='plate_capture']:checked").val() == "0" && $(this).attr("name") == "plate") {
				// do nothing
			} else {
				$(this).removeClass("error");
				if ($(this).val() == "") {
					$(this).addClass("error");
					$("div.error").removeClass("hide");
					safe = false;
				}
			}
		});
		//
		updateBody();
		return safe;
	});
	
	/**
	 * Site-wide rules
	**/
	
	$("a.external").attr("target", "_blank");
	
	/**
	 * Helper functions
	**/
	
	
	//if a locale is passed in the querystring, alert the user to tell them it's not supported yet.
	function checkLocale() {
		var l = document.location.toString().split("?c=");
		if (l.length == 1) return;
		if (l.length > 1) {
			if (l[1] == "unknown") {
				msg = "Hello! We tried to detect the country you're visiting from but failed. Sorry. Try selecting a supported country from the menu in the top right!"
			} else {
				msg = "Hello! We've noticed you're visiting from " + titleCase(l[1].replace(/\+/, " ")) + ", but we don't support your country yet. We've logged your visit and will add support if enough visitors come along! Happy driving in the meantime :)"
			}
			var msgDiv = document.createElement("div");
			$(msgDiv).html(msg).addClass("msg").insertBefore("#search");
		}
	}
	
	function titleCase (str) {
		return str.toLowerCase().replace(/\b[a-z]/g, strToUpper);
		function strToUpper() {
			return arguments[0].toUpperCase();
		}
	}
	
	function updateBody() {
		var minHeight = $(document).height() - $("#header").outerHeight();
		$("#body").css({"min-height": minHeight, "height": minHeight});
	}
	
	function trim(str) {
		return str.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
	}
	
	function showError(msg) {
		$(".error").html(msg).fadeIn("normal");
	}
	
	function hideError(msg) {
		$(".error").fadeOut("fast").empty();
	}	
	//
	updateBody();
});
