$(function() {
  // Google Analytics
  $.getScript((("https:" == document.location.protocol) ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js", function() {
    var pageTracker = _gat._getTracker("UA-15043353-1");
    pageTracker._initData();
    pageTracker._trackPageview();
  });
	
	// Block UI (AJAX Processing)
	$.blockUI.defaults.overlayCSS.opacity = 0;

	$("#page").ajaxStart(function() {
	  $.blockUI({
			theme: true,
			title: "Processing Request",
	    message: $("#ajax")
	  });
	});

	$("#page").ajaxStop(function() {
	  $.unblockUI();
	});
	
	// REST
  $.rest();

	// Tools
	$("a.show, a.new, a.edit, a.destroy").tooltip();
	
	// Buttons
	$(".button").button();

	// MarkItUp
	$(".textile").markItUp(markItUpSettings);
	
	// Single position move and sorting.
	function movePosition(element, position) {
		var tr = $(element).closest("tr");
		var id = tr.attr("id");
		$.post($(".sortable").attr("data-url"), "id=" + id.slice(id.lastIndexOf('_') + 1) + "&" + "position=" + position + "&_method=put");
		tr.fadeOut(500, function() {
			switch (position) {
				case "top": $(".sortable").prepend(tr); break;
				case "higher": $(tr).prevAll("tr:first").before(tr); break;
				case "lower": $(tr).nextAll("tr:first").after(tr); break;
				case "bottom": $(".sortable").append(tr); break;
			}
			$(this).fadeIn(500);
		});
	}

	// Drag and drop sorting.
	$(".sortable").sortable({
		handle: ".move",
		cursor: "move",
		placeholder: "ui-state-highlight",
		revert: true,
		forceHelperSize: true,
		forcePlaceholderSize: true,
		helper: function(event, tr) {
	    var $originals = tr.children();
	    var $helper = tr.clone();
	    $helper.children().each(function(index) {
	      $(this).width($originals.eq(index).width()) // Set helper cell sizes to match the original sizes.
	    });
	    return $helper;
	  },
		update: function(event, ui) {$.post($(".sortable").attr("data-url"), $(".sortable").sortable("serialize") + "&_method=put");}
	});
	$(".sortable").disableSelection();

	// Move to top position.
	$(".top").mouseup(function(){
		movePosition(this, "top");
	});

	// Move one position higher.
	$(".higher").mouseup(function(){
		movePosition(this, "higher");
	});

  // Move one position lower.
	$(".lower").mouseup(function(){
		movePosition(this, "lower");
	});

	// Move to bottom position.
	$(".bottom").mouseup(function(){
		movePosition(this, "bottom");
	});
});
