/**
 * H2 Support
 */
var H2 = {
	initLinks: function() {
		$("a[rel='external']").click(function(e) {
			window.open(this.href);
			e.preventDefault();
		});
		$("a[rel='internal']").click(function(e) {
			window.open(this.href);
			e.preventDefault();
		});
		$("a[rel='popup']").click(function(e) {
			H2.openPopupWindow(this.href);
			e.preventDefault();
		});
	},

	addFormValidation: function($form) {
		var noFieldValidation = false;
		$form.find("input[name='_noFieldValidation']").each(function() {
			noFieldValidation = true;
		});
		if (!noFieldValidation) {
			$form.find(':input').blur(function() {
				var data = {'_action': $form.attr('action')};
				data[$(this).attr('name')] = $(this).val();

				var $input = $(this);
				$.post($form.attr('action') + "/fieldvalidation", data, function(result) {
					if (!result.errors || !result.errors[$input.attr('name')]) {
						$input.removeClass('error');
						$input.attr('title', "");
						$('#' + $input.attr('id') + "-error").remove();
						$("label[for='" + $input.attr('id') + "']").removeClass('error');
					}

					if (result.errors) {
						$.each(result.errors, function(key, fieldErrors) {
							$.each(fieldErrors, function(idx, error) {
								$form.find("*[name='" + key + "']").each(function(idx, item) {
									if (!$(item).hasClass('error')) {
										$(item).addClass('error');
									}

									$("label[for='" + $(this).attr('id') + "']").each(function() {
										if (!$(this).hasClass('error')) {
											$(this).addClass('error');
										}

										var errorMessage = error.replace("{label." + key + "}", $(this).text().replace(/(.+):([ *]+)?/, "$1")).replace("&nbsp;", " ");
										$(item).attr('title', errorMessage);
										var $errorMsg = $('<div class="input-error-message" id="' + $(item).attr('id') + '-error" />')
															.html($('<img />').attr({
																alt: errorMessage,
																src: "/img/icons/exclamation_mark.gif",
																width: 15,
																height: 15
															}))
															.append(errorMessage);

										if ($("#" + $(item).attr('id') + "-error").length) {
											$("#" + $(item).attr('id') + "-error").replaceWith($errorMsg);
										} else {
											$(item).after($errorMsg);
										}
									});

									// Disable form submiting
									$form.find("input[type='submit']").attr('disabled', 'disabled');
								});
							});
						});
					} else {
						// Enable form submiting if no other errors found
						if ($form.find(".input-error-message").length == 0) {
							$form.find("input[type='submit']").removeAttr('disabled');
						}
					}
				}, "json");
			});
		}
	},

	initFormsValidation: function() {
		$("form").each(function(idx, form) {
			H2.addFormValidation($(form));
		});
	},

	openPopupWindow: function(url, resizable, width, height, left, top) {
	  if (typeof resizable == 'undefined') resizable = true;
	  if (typeof width == 'undefined') width = 1024;
	  if (typeof height == 'undefined') height = 600;

	  var _width = screen.availWidth, _height = screen.availHeight;
	  if (typeof left == 'undefined') {
		  if (_width > width)
		  	left = (_width-width)/2;
		  else
		  	left = 0;
	  }
	  if (typeof top == 'undefined') {
		  if (_height > height)
		  	top = (_height-height)/2;
		  else
		  	top = 0;
	  }

	  if (typeof left == 'undefined') left = 0;

	  return !open(url, "", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars="+(resizable?"yes":"no")+",resizable="+(resizable?"yes":"no")+",copyhistory=no,top="+top+",left="+left+",width="+width+",height="+height);
	}
};


$(window).load(function () {
	H2.initLinks();
	H2.initFormsValidation();

	if ($('.answer-options a').length > 0) {
		$('.answer-options a').each(function() {
			var b = $('<input type="button" value="' + this.text() + '" />');
			b.click(function(e) {
				window.location = button.href;
				e.preventDefault();
			});
			this.after(b);
			this.hide();
		});
	}

	if ($('.method').length) {
		if (window.location.hash) {
			$$(window.location.hash).each(function() {
				this.parentNode.addClassName('selected');
			});
		}
	}

	// Test tasks with common answer options
	$('.task').each(function(idx, task) {
		$(task).find('select.shared-options').each(function() {
			$(this).data('oldVal', $(this).val());
			$(this).change(function() {
				$(task).find('select.shared-options[name!="' + $(this).attr("name") + '"] option[value="' + $(this).val() + '"]').hide();
				$(task).find('div.shared-options[id$="-answer-' + $(this).val() + '-container"]').hide();

				$(task).find('select.shared-options[name!="' + $(this).attr("name") + '"] option[value="' + $(this).data('oldVal') + '"]').show();
				$(task).find('div.shared-options[id$="-answer-' + $(this).data('oldVal') + '-container"]').show();

				$(this).data('oldVal', $(this).val());
			});
		});

		$(task).find('div.shared-options').each(function(idx, div) {
			$(div).parent().data('oldVal', $(div).find("input").val());
			$(div).find("input").change(function() {
				var el = /question\[([0-9]+)\]/;
				var els = el.exec($(this).attr("name"));
				var questionId = els[1];

				$(task).find('div.shared-options[id$="-answer-' + $(this).val() + '-container"]:not([id^="question-' + questionId + '-answer-"])').hide();
				$(task).find('select.shared-options option[value="' + $(this).val() + '"]').hide();

				$(task).find('div.shared-options[id$="-answer-' + $(div).parent().data('oldVal') + '-container"]:not([id^="question-' + questionId + '-answer-"])').show();
				$(task).find('select.shared-options option[value="' + $(div).parent().data('oldVal') + '"]').show();

				$(div).parent().data('oldVal', $(this).val());
			});
		});
	});

	$("a[rel='lightbox-gallery']").lightBox();
	$("a[rel='lightbox']").lightBox();
});

