//================================================================================
// Detect iPhone
//================================================================================
var isIPhone = Boolean(navigator.userAgent.match(/iPhone/i));

//================================================================================
// Preload images
//================================================================================
function preloadImage(url)
{
  var preload = new Image;
  preload.src = url;
}

//================================================================================
// Initialise event handlers
//================================================================================
function init(target, isDocument)
{
  var $target = $(target);
  
  //================================================================================
  // Preload mouseover images
  //================================================================================
  preloadImage("/images/top-nav-on.gif");
  preloadImage("/images/top-nav-menu-on.gif");
  preloadImage("/images/ajax-loader.gif");
  
  //==============================================================================
  // Email links
  //==============================================================================
  $("span.email", $target).each(function()
  {
    var email = $(this).text().replace(/ at /, "@");
    var html = '<a href="mailto:' + email + '" class="email">' + email + '</a>';
    $(this)
      .html(html)
      .removeClass("email");
  });
  
  //==============================================================================
  // Forms
  //==============================================================================
  $(".set-focus", $target).focus();
  
  if (!isIPhone)
  {
    $(".form-checkbox input", $target).each(function()
    {
      var $input = $(this);
      var $label = $("label[for='" + this.id + "']");
      var $span = $("<span />");
      
      // Add .checked or .unchecked to the label as appropriate
      function updateLabelClass()
      {
        $label.removeClass("checked unchecked");
        if ($input.attr("checked"))
          $label.addClass("checked");
        else
          $label.addClass("unchecked");
      }
      $input.bind("click", updateLabelClass);
      updateLabelClass();
      
      // Add .focus to the span when the original input is focussed
      $input
        .bind("focus", function()
        {
          $label.addClass("focus");
        })
        .bind("blur", function()
        {
          $label.removeClass("focus");
        });
      
      // Replace the checkbox
      $input.wrap("<span class='fake-checkbox'></span>").after($span);
    });
  }
  
  //==============================================================================
  // Antispam
  //==============================================================================
  $(".antispam input", $target).val(unescape("Z6FZ72Z61Z6EZ67Z65".replace(/Z/g, "%")));
  $(".antispam", $target).hide();
  
  //==============================================================================
  // Ajax forms
  //==============================================================================
  $("form.ajax-form", $target).bind("submit", function()
  {
    var $form = $(this);
    var $indicator = $form.find(".ajax-indicator-off");
    var $buttons = $form.find("button[type=submit]");
    
    // Show indicator
    if ($indicator.length == 0)
    {
      $indicator = $form.parents(".content-box").find(".ajax-indicator-off");
    }
    
    $indicator.addClass("ajax-indicator");
    
    // Disable buttons
    $buttons.attr("disabled", "disabled").addClass("disabled-button");
    $buttons.filter(".send-button").html("Please wait...");
    
    // Submit form by ajax
    $.ajax({
      type: $form.attr("method"),
      url: $form.attr("action"),
      data: $form.serializeArray(),
      success: function(data, textStatus)
      {
        // Remove the indicator
        $indicator.removeClass("ajax-indicator");
        
        // Replace form with new HTML
        $form.html(data);
        
        // Re-run the init() function on the contents
        init($form);
      },
      error: function(XMLHttpRequest, textStatus, errorThrown)
      {
        // Remove the indicator
        $indicator.removeClass("ajax-indicator");
        
        // Re-enable the buttons
        $buttons.attr("disabled", false).removeClass("disabled-button");
        $buttons.filter(".send-button").html("Send");
        
        // Show an error message
        alert("ERROR: Could not send message. Please try again.");
      }
    });
    
    // Prevent the standard form submission
    return false;
  });
  
  //==============================================================================
  // NyroModal
  //==============================================================================
  
  // Preload next/prev mouseover images
  if (isDocument)
  {
    preloadImage("/images/lightbox-next-on.png");
    preloadImage("/images/lightbox-prev-on.png");
  }
  
  // Remove the "close" title attribute
  $.fn.nyroModal.settings.closeButton = '<a href="#" class="nyroModalClose" id="closeBut">Close</a>';
  
  // Gallery of links
  $(".gallery", $target).each(function(index)
  {
    $(this).find("a")
      .attr("rel", "lightbox-" + index)
      .nyroModal();
  });
  
  // Single popup links, or manual "rel" attributes
  $("a.popup, a.image-border-popup").nyroModal();
  
  //==============================================================================
  // End init()
}

$(function()
{
  init(document, true);
});

//================================================================================
// Handle click on Pi symbol in footer
// http://en.wikipedia.org/wiki/The_Net_%281995_film%29#Plot
//================================================================================
function redirectIfCtrlShift(event, url, target)
{
  if (event.ctrlKey && event.shiftKey)
  {
    if (target)
      window.open(url, target);
    else
      window.location = url;
    return false;
  }
}

//================================================================================
// iPhone
//================================================================================
// http://www.engageinteractive.co.uk/blog/2008/06/19/tutorial-building-a-website-for-the-iphone/
if (isIPhone)
{
  var orientation;
  function updateOrientation()
  {
    if (window.orientation != orientation)
    {
      orientation = window.orientation;
      
      // Set orientation so the CSS can access it using body[orientation="landscape"]
      switch (orientation) {
        
        case 0:
          document.body.setAttribute("orientation", "portrait");
          break;
          
        case 90:
        case -90:
          document.body.setAttribute("orientation", "landscape");
          break;
          
        default:
          console.error("Invalid orientation: " + orientation);
          
      }
      
      // Hide the address bar
      /*if (window.pageXOffset == 0 && window.pageYOffset == 0)
      {
        setTimeout("window.scrollTo(0, 0);", 1);
      }*/
    }
  }
  
  addEventListener("orientationchange", updateOrientation);
  addEventListener("load", updateOrientation);
}

