//Parse the parts of the url. Currently only gets last directory and anchor
function ParseUrl(url)
{
  return url.replace(/.*?\/[^#]+/, "").replace(/\//g, "").split("#");
}

function ChangePage(page)
{
  $("#pages").children().hide();    
    
  var parts = ParseUrl(page);
  
  //Fade in the page
  $("#p_" + parts[0]).fadeIn("slow");
  
  //Remove any currently active items in the menu, and activate the new one
  $("#t_menu a").removeClass("active");
  $("#t_menu_" + parts[0]).addClass("active");
  
  //If there is an anchor in the url, scroll to it.
  if (parts[1]) {
    var targetOffset = $("a[name=" + parts[1] + "]").offset().top;
    $('html,body').animate({scrollTop: targetOffset}, 1000);
  }
}

$(function() {  
  $textareas = $("textarea");
  $textareas.textlimit($textareas.siblings("span.counter:first"), 500);
  
  $("#pages").children().hide();  
  $("#p_home").show();
  /*var initial = ParseUrl(location.href);
  
  //Show the default page
  if (initial != "") {
    $("#p_" + initial).show();
  } else {
     $("#p_home").show();
  }*/
  
  $("a.internal, area.internal").click(function() {
    //Don't do the animation if this is already active
    if ($(this).is(".active"))
      return false;
      
    ChangePage($(this).attr("href"));    

    return false;
  });
  
  $("#p_contact form").submit(function() {
    var $form = $(this);
    //Clear previous errors
    $("#p_contact .error").text("");
    
    /*$.ajaxError(function (event, XMLHttpRequest, ajaxOptions, thrownError) {
      $("body").html(thrownError);
    });*/
    
    $.post($form.attr("action"), $form.serialize(), function(data, textStatus) {      
      var errors = data.split("\n");
      if (errors != "success") {
        for (var x = 0; x < errors.length; x++) {
          var parts = errors[x].split(": ");
          $(".contact_" + parts[0] + " .error").text(parts[1]); 
        }
      } else {
        $("#p_status .section h2").text("Successfully sent");
        $("#p_status .section p").text("Your message was successfully sent. Thank you for your input.");
        ChangePage("status/");
        $form[0].reset();
      }
    });
    
    return false;
  });
});
