var warnIfClosedMessage = "Your changes will be lost.";

function init(target, isDocument)
{
  var $target = $(target);
  
  //================================================================================
  // Automatic pretty table rows
  //================================================================================
  $("table.pretty-table-auto > tbody > tr:odd:not(.subheading)", $target).addClass("even"); // Swapped because jQuery is 0-based
  $("table.pretty-table-auto > tbody > tr:even:not(.subheading)", $target).addClass("odd");
  
  //================================================================================
  // Left navigation slider
  //================================================================================
  $("div.left-nav ul li.start-open", $target).addClass("is-open");
  
  $("div.left-nav ul li:has(div.submenu) > a", $target).bind("click", function()
  {
    
    // See if they clicked the currently open one
    var isOpen = $(this).parent().hasClass("is-open");
    
    // Close current menu item
    var current = $("div.left-nav ul li.is-open");
    if (current.length > 0)
    {
      current.removeClass("is-open");
      current.children("a").removeClass("open");
      current.children("div.submenu").slideUp("normal");
    }
    
    // Open new menu item (unless they clicked to close)
    if (!isOpen)
    {
      var open = $(this).parent();
      open.addClass("is-open");
      open.children("a").addClass("open");
      open.children("div.submenu").slideDown("normal");
    }
    
    // Hide the outline
    $(this).blur();
    
    return false;
    
  });
  
  //================================================================================
  // Print button
  //================================================================================
  $("a.page-action-print", $target).bind("click", function()
  {
    try
    {
      window.print();
      return false;
    }
    catch (e) {}
  });
  
  //================================================================================
  // Remove default text in form when clicked
  //================================================================================
  $("input.textbox-default", $target)
    .bind("focus", function()
    {
      if (this.value == this.defaultValue)
      {
        this.value = "";
      }
    })
    .bind("blur", function()
    {
      if (jQuery.trim(this.value) == "")
      {
        this.value = this.defaultValue;
      }
    });
  
  //================================================================================
  // Mouseover logo
  //================================================================================
  if (typeof logoOn != "undefined")
  {
    $("#logo", $target)
      .bind("mouseover", function()
      {
        this.src = logoOn;
      })
      .bind("mouseout", function()
      {
        this.src = logoOff;
      });
  }
  
  //================================================================================
  // Button bars
  //================================================================================
  $(".button-bar a, .button-bar button", $target)
    .bind("mouseover", function()
    {
      $(this).addClass("hover");
    })
    .bind("mouseout", function()
    {
      $(this).removeClass("hover");
    })
    .bind("mousedown", function()
    {
      $(this).addClass("down");
    })
    .bind("mouseup mouseout", function()
    {
      $(this).removeClass("down");
    });
  
  //================================================================================
  // Prevent clicking a label from highlighting text
  //================================================================================
  $("label", $target).bind("selectstart, mousedown", function()
  {
    return false;
  });
  
  //================================================================================
  // Prevent clicking a link inside a label from activating the control
  //================================================================================
  $("label a:not([href^=#])", $target).click(function(event)
  {
    window.open(this.href, this.target);
    return false;
  });
  
  //================================================================================
  // Deleteable rows
  //================================================================================
  $(".deleteable", $target).each(function()
  {
    var container = $(this);
    var checkbox = container.find(".delete-checkbox input[type=checkbox]")
    var inputs = container.find("input, select").not(checkbox);
    
    function update()
    {
      if (checkbox.attr("checked"))
      {
        inputs.attr("disabled", true);
      }
      else
      {
        inputs.attr("disabled", false);
      }
    }
    
    update(this);
    checkbox.bind("click", update);
    
  });
  
  //================================================================================
  // Selectable rows
  //================================================================================
  $(".selectable", $target).each(function()
  {
    var container = $(this);
    var checkbox = container.find("input.select-checkbox")
    
    function update()
    {
      if (checkbox.attr("checked"))
      {
        container.addClass("selected");
      }
      else
      {
        container.removeClass("selected");
      }
    }
    
    update(this);
    checkbox.bind("click", update);
    
  });
  
  //================================================================================
  // Select all checkbox
  //================================================================================
  $("input.select-all", $target).click(function()
  {
    var checked = $(this).attr("checked");
    $('input[name^="' + this.name + '["]')
      .attr("checked", checked)
      .each(function()
      {
        $(this).triggerHandler('click');
      });
  });
  
  //================================================================================
  // Hold shift to select multiple checkboxes
  //================================================================================
  // Based on http://stackoverflow.com/questions/659508/how-can-i-shift-select-multiple-checkboxes-like-gmail
  var lastChecked;
  var shiftSelectCheckboxes = $('input.shift-select', $target);
  var doingShiftSelect = false;
  
  shiftSelectCheckboxes.click(function(event)
  {
    // Prevent it running when called by this function
    if (doingShiftSelect)
      return;
    
    if (lastChecked && event.shiftKey)
    {
      doingShiftSelect = true;
      
      var start = shiftSelectCheckboxes.index(this);
      var end = shiftSelectCheckboxes.index(lastChecked);
      
      for (i = Math.min(start, end); i <= Math.max(start, end); i++)
      {
        shiftSelectCheckboxes[i].checked = lastChecked.checked;
        
        // Trigger click handler to update .selectable
        shiftSelectCheckboxes.eq(i).triggerHandler('click');
      }
      
      doingShiftSelect = false;
    }
    
    lastChecked = this;
  });
  
  //================================================================================
  // Warn when closing a modified form
  //================================================================================
  var warnFields = $(".warn-before-close", $target);
  if (warnFields.length > 0)
  {
    var fieldsChanged = false;
    var allowClosing = false;
    
    warnFields.change(function()
    {
      fieldsChanged = true;
    });
    
    function allowClose()
    {
      allowClosing = true;
    }
    
    $("form.allow-close", $target).bind("submit", allowClose);
    $("a.allow-close", $target).bind("click", allowClose);
    
    window.onbeforeunload = function()
    {
      if (fieldsChanged && !allowClosing)
        return warnIfClosedMessage;
    };
  }
  
  //================================================================================
  // Admin image preview
  //================================================================================
  $("img.admin-image-preview", $target)
    .click(function()
    {
      $(this).nextAll("button").click();
    })
    .css("cursor", "pointer");
  
  //================================================================================
  // Open external links in new window
  //================================================================================
  $(".content a[href*='://']", $target)
    .not("[href^='http://" + document.location.host + "']")
    .not("[href^='https://" + document.location.host + "']")
    .not(".samewin") // Use this to override it for individual links
    .attr("target", "_blank");
  
  //================================================================================
  // Lightboxes
  //================================================================================
  if ($.fn.nyroModal)
  {
    $(".popup", $target).nyroModal({
      galleryLinks: '<a href="#" class="nyroModalPrev">Prev<span></span></a><a href="#" class="nyroModalNext">Next<span></span></a>'
    });
  }
  
  //==============================================================================
  // End init()
}

$(function()
{
  init(document, true);
});

//================================================================================
// Preload mouseover logo
//================================================================================
$(window).load(function()
{
  if (typeof logoOn != "undefined")
  {
    var preload = new Image;
    preload.src = logoOn;
  }
});

//================================================================================
// Update pretty table row colours after DOM manipulation
//================================================================================
function updatePrettyTable(target)
{
  var $rows = $("> tbody > tr", target);
  $rows.removeClass("odd even");
  $rows.filter(":odd").addClass("even"); // Swapped because jQuery is 0-based
  $rows.filter(":even").addClass("odd");
}


