$(document).ready(function(){
  function collect_ids(target) {
    var ids = [];
    $(target).each(function(i){
      ids.push($(this).attr("id"));
    });

    return ids.toString();
  }

  function scroll_page(amount) {
    $('html,body').stop().animate({scrollTop: amount-75}, 500);
  }

  // enable sorting for works
  $("body.admin #portfolio ul.content").sortable({
    stop: function(event, ui) {
      $.post("/works/sort",{ids: collect_ids("#portfolio ul.content li")});
    },
    scroll: false
  });

  // enable sorting for services
  $("#services").sortable({
    handle: '.handle',
    stop: function(event, ui) {
      $.post("/services/sort",{ids: collect_ids("#services li")});
    }
  });

  // the accordian for services utilized
  $("#portfolio dl").accordion({ 
    header: 'dt',
    collapsible: true,
    active: false,
    autoHeight: false
  });

  // form validation for comments
  $("#new_contact").validate({
    rules: {
      'contact[name]': {required : true, minlength: 3, maxlength: 50},
      'contact[email]': { required : true, email : true },
      'contact[body]': "required"
    }
  });

  // allows keyboard navigation for portfolio
  // left arrow (prev work) right arrow (next work)
  if($("body.portfolio").length > 0) {
    $(document).keyup(function(event) {
      if(event.keyCode == 39) {
        window.location = $("#work-navigation a.next").attr("href");
      } else if(event.keyCode == 37) {
        window.location = $("#work-navigation a.prev").attr("href");
      }
    });
  }

  // scroll navigation
  $("body.homepage #navigation a, #navigation a.contact").click(function(){
    var address = "#" + this.hash.split("#")[1],
        offset_top = $(address).offset().top;

    scroll_page(offset_top);
    
    $("#navigation a").removeClass("active");
    $(this).addClass("active");

    return false;
  });

  $("body.homepage #logo a").click(function(){
    scroll_page(0);
    return false;  
  });

  // adjust window scroll on load 
  // ex. http://www.felixflor.es/#portfolio scrolls to #portfolio
  (function(){
    var address = "#" + parseUri(document.location.href).anchor;
    if (address !== "#") {
      var offset_top = $(address).offset().top;
      scroll_page(offset_top);
    }
  })();
  
  
  // make title bars stacking
  
});
