(function ($) {
	var animationSpeed = 250,
		$filter = $("form#filter"),
		$vote = $("form#vote"),
		$suggestExercise = $("form#suggest-exercise"),
		$rating = $("img#rating"),
		$userselection = $("div.userselection");

	/**
	 * A small jQuery plugin for giving a set of elements the same height, based on the
	 * element with the largest height at invocation.
	 */
	$.fn.equalizeHeights = function (maxHeight) {
		maxHeight = maxHeight || 0;
		if (maxHeight == 0) {
			this.each(function (i, el) { maxHeight = Math.max(maxHeight, $(el).height()) });
		}
		return this.height(maxHeight);
	};

	function visMenyvalg (e) {
		$('header.site li:not(.aktiv) a')
			.each(
				function (i, el) {
					var $el = $(el),
						attrs = {
							width: $el.data('originalWidth'),
							marginTop: '0px'
						};

					$el.animate(attrs, 150, function () {
						$el.css('textIndent', '0');
						$el.children('span').animate({ opacity: 1 }, 100)
					});
				}
			);
	}

	function skjulMenyvalg (e) {
		$('header.site li:not(.aktiv) a')
			.each(
				function (i, el) {
					var $el = $(el),
						attrs = {
							width: '30px',
							marginTop: '-20px',
							textIndent: '-100em'
						};

					$el.children('span').animate({ opacity: 0 }, 100, function () {
						$el.animate(attrs, 150);
					})
				}
			);
	}

	if ($('html.sport').length == 1) {
		$('header.site ul')
			.hover(visMenyvalg, skjulMenyvalg)
			.find('li:not(.aktiv) a')
				.each(function (i, el) {
					var $el = $(el);
					$el.data('originalWidth', $el.width());
					$el.parent().addClass('skjult');
				});
	}

	/*
	 * Add JS magic to enable hide/show of filters, and automatic update when filters change.
	 */
	if ($filter.length == 1) {
		$('<span>', {
			text: 'Skjul',
			className: 'toggle hide',
			click: function (e) {
				e.preventDefault();

				var $toggle = $(e.target),
					$content = $filter.find('.content');

				if ($content.is(':animated')) return;

				if ($toggle.is('.hide')) {
					$filter.find('.content').slideUp(animationSpeed, function () {
						$toggle.removeClass('hide').addClass('show').text('Vis');
					});
				}
				else {
					$filter.find('.content').slideDown(animationSpeed, function () {
						$toggle.removeClass('show').addClass('hide').text('Skjul');
					});
				}
			}
		}).prependTo($filter);

		$filter.bind("change", function (e) {
			$(e.target.form).submit();
		});

		if ($userselection.length == 1) {
			var maxHeight = Math.max($filter.height(), $userselection.height());
			$userselection.height(maxHeight);
			// TODO: Forsøk å unngå hardkodet fratrekk på indre bokshøyde
			$filter.find('.content div').equalizeHeights(maxHeight - 30);
		}
		else {
			$filter.find('.content div').equalizeHeights();
		}
	}

	/*
	 * Add JS magic to vote by simply clicking on the rating stars.
	 */
	if ($vote.length == 1) {
		var section = $vote.attr('action').match(/^\/(\w+)/)[1],
			src = $rating.attr('src'),
			offset = $rating.offset();

		// TODO: Simplify this calculation...
		function calculateScore (e) {
			var x = e.pageX - offset.left;
			if (x < 18) {
				return 1;
			}
			else if (x < 36) {
				return 2;
			}
			else if (x < 54) {
				return 3;
			}
			else if (x < 72) {
				return 4;
			}
			else {
				return 5;
			}
			return 0;
		}

		$rating
			.data('rating.score', src.match(/(\d+)/)[1])
			.mousemove(function (e) {
				var score = calculateScore(e),
					name = score == 0 ? 0 : section + '_' + score;
				$rating.attr('src', src.replace(/([a-z]+_)?\d+/, name));
			})
			.mouseout(function (e) {
				$rating.attr('src', src);
			})
			.click(function (e) {
				var score = calculateScore(e);
				if (score > 0) {
					$vote
						.find("select[name=poeng]").val(score).end()
						.submit();
				}
			});
		$vote.hide();
	}

    if ($suggestExercise.length == 1) {
        var $blankPhoto = $suggestExercise.find(".photo:eq(0)").clone(true),
            $blankVideo = $suggestExercise.find(".video:eq(0)").clone(true),
            numPhotos = $("#id_photos-TOTAL_FORMS").val(),
            numVideos = $("#id_videos-TOTAL_FORMS").val();

        function updateAttributeName (i, val) {
            var num = val.indexOf("photos") !== -1 ? numPhotos : numVideos;
            return val.replace(/(photos|videos)-\d+/, "$1-" + num);
        }

        $suggestExercise.find("input:file").change(function (e) {
            var $input = $(e.target),
                type = $input.parent().parent().attr("class"),
                $newEntry;

            if ($input.val() != "") {
                $newEntry = type == "photo" ? $blankPhoto.clone(true) : $blankVideo.clone(true);
                // Update all relevant input and label attributes to use correct entry index
                $newEntry
                    .find("input")
                        .attr("id", updateAttributeName)
                        .attr("name", updateAttributeName)
                        .end()
                    .find("label")
                        .attr("for", updateAttributeName);

                $input.closest("fieldset").find("." + type + ":last").after($newEntry);
                if (type == "photo") {
                    $("#id_photos-TOTAL_FORMS").val(++numPhotos);
                }
                else {
                    $("#id_videos-TOTAL_FORMS").val(++numVideos);
                }
            }
        });
    }

	$("ul.photos a[rel^='ovelse']").prettyPhoto({
		animationSpeed:'fast'
	});

	$("button.print").click(function (e) {
		e.preventDefault();
		window.print();
	});
})(jQuery);
