﻿$(function () {

	$("select").fancify();

	$(".field-container .help").each(function () {

		var $help = $(this);
		var $container = $help.closest(".field-container");

		$help.append('<span class="tip"/>');

		var timeout = -1;

		$container.mouseenter(function () {

			clearTimeout(timeout);
			timeout = setTimeout(function () {
				$help.stop().fadeIn(300);
			}, 500);

		}).mouseleave(function (evt) {

			if (!$container.is(".focused")) {

				clearTimeout(timeout);
				$help.stop().fadeOut(100);

			}

		}).focusin(function () {

			$container.addClass("focused");

			clearTimeout(timeout);
			timeout = setTimeout(function () {
				$help.stop().fadeIn(300);
			}, 500);

		}).focusout(function (evt) {

			$container.removeClass("focused");

			clearTimeout(timeout);
			$help.stop().fadeOut(100);

		});

	});

	$(".date-container input[maxlength]").keyup(function (evt) {

		if (evt.which != 9) {

			var $input = $(this);

			if ($input.nextAll("input").length > 0 && $input.val().length == $input.attr("maxlength")) {

				var $nextInput = $input.nextAll("input").first();

				if ($nextInput.val().length > 0)
					$nextInput.select();

				$nextInput.focus();

			}

		}

	});

	$("textarea[data-maxlength]").each(function (idx) {

		var $textarea = $(this);
		var $charCount = $textarea.parent().find(".chars-left");
		var maxLength = parseInt($textarea.data("maxlength"));

		$charCount.text(maxLength);

		$textarea.keydown(function (evt) {

			var isPlus = (

					evt.which == 13 ||
					evt.which == 32 ||
					(evt.which >= 48 && evt.which <= 90) ||
					(evt.which >= 186 && evt.which <= 192) ||
					(evt.which >= 219 && evt.which <= 222)

				) && !(evt.ctrlKey || evt.altKey);

			var left = maxLength - $textarea.val().length + (isPlus ? -1 : 0);

			if (isPlus && left < 0) {

				return false;

			}

		}).keyup(function (evt) {

			var isPlus = evt.which > 48 && evt.which < 91;

			if ($textarea.val().length > maxLength)
				$textarea.val($textarea.val().substr(0, maxLength));

			var left = maxLength - $textarea.val().length;

			$charCount.text(left);

		});

	});

	var $uploadContainer = $(".upload-container .editor");
	$uploadContainer.each(function (idx) {

		var $container = $(this);
		var $form = $container.closest("form");
		var $submitButtons = $form.find("input[type=submit]");
		var $valueField = $container.find(".file");
		var $originalValueField = $container.find(".original-file");

		var fileTypes = $container.find(".file-types").val();

		var $button = $("<div class='button-placeholder'><div class='button'/></div>");
		$container.append($button);

		var $progress = $("<div class='progress-container'><div class='progress' /></div>");
		$progress.hide();
		$container.append($progress);

		var $message = $("<div class='message'/>");
		$message.hide();
		$container.append($message);

		var paramWidth = $container.find(".width").val();
		var paramHeight = $container.find(".height").val();

		var retryUpload = function () {

			$progress.hide();
			$message.hide();
			$button.removeClass("button-hidden");

			swfu.setButtonDisabled(false);
			$submitButtons.removeAttr("disabled");

			$valueField.val("");
			$originalValueField.val("");

			return false;

		};

		var generateButtons = function (useView, useRetry) {

			var $options = $('<span class="options"/>');

			if (useView) {

				$options.append('<a href="' + __TEMP_STORAGE_URL + $valueField.val() + '" class="view">View</a>');
				$options.children(".view").fancybox({

					padding: 0,
					centerOnScroll: true

				});

			}

			if (useRetry) {

				$options.append('<a href="javascript:;" class="retry">Retry</a>');
				$options.children(".retry").click(retryUpload);

			}

			$message.append($options);

		};

		if ($originalValueField.val().length > 0) {

			$button.addClass("button-hidden");
			$message.empty().text($originalValueField.val()).show();
			generateButtons(true, true);

		}

		var swfu = new SWFUpload({

			upload_url: __BASE_URL + "handlers/image-upload.ashx",

			file_post_name: 'upload',

			post_params: {
				width: paramWidth,
				height: paramHeight
			},

			file_size_limit: "5120", // 5MB
			file_types: fileTypes && fileTypes.length > 0 ? fileTypes : "*.*",
			file_queue_limit: 1,
			file_upload_limit: 0,
			begin_upload_on_queue: true,
			use_server_data_event: true,
			button_placeholder: $button.children(".button")[0],
			button_width: 170,
			button_height: 37,
			button_image_url: __BASE_URL + 'img/ui/buttons/choose-image.png',
			button_cursor: SWFUpload.CURSOR.HAND,
			button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,

			// Event Handler Settings
			upload_success_handler: function (file, data) {

				var swfu = this;

				data = data.split(";");

				var valid = data[0] != -1 ? true : false;

				var $options = $('<span class="options"/>');

				if (valid) {

					$valueField.val(data[2]);
					$originalValueField.val(data[1]);

				}

				$message.empty().text(data[1]);
				generateButtons(valid, true);

				$progress.hide();
				$message.show();
				$submitButtons.removeAttr("disabled");

			},

			upload_error_handler: function (file, code, message) {

				var swfu = this;

				$valueField.val("");
				$originalValueField.val("");

				$message.empty().text(message);
				generateButtons(false, true);

				$progress.hide();
				$message.show();
				$submitButtons.removeAttr("disabled");

			},

			upload_start_handler: function (file) {

				var swfu = this;

				$submitButtons.attr("disabled", true);
				swfu.setButtonDisabled(true);

				$button.addClass("button-hidden");

				$progress.show().children(".progress").width(0);

			},

			upload_progress_handler: function (file, bytes, totalBytes) {

				var swfu = this;

				var percent = Math.round(bytes / totalBytes * 100.0);

				$progress.children(".progress").width(percent + "%").text(percent + "%");

			},

			file_queued_handler: function (file) {

				var swfu = this;

				swfu.startUpload();

				$valueField.val("");
				$originalValueField.val("");

				swfu.startUpload();

			},

			// Flash Settings
			flash_url: __BASE_URL + "scripts/swfupload/swfupload.swf", // Relative to this file

			// UI Settings
			ui_container_id: "swfu_container",
			degraded_container_id: "degraded_container",

			// Debug Settings
			debug: false
		});

	});

});
