// rails auth token enabled in jquery
$(document).ajaxSend(function(event, request, settings) {
  if (typeof(AUTH_TOKEN) == "undefined") return;
  settings.data = settings.data || "";
  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});

// add javascript request type
jQuery.ajaxSetup({
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});

jQuery.fn.exists = function(){return jQuery(this).length>0;}

var setWindowLocation = function(target_name) {
  window.location.hash = target_name;
}

$(document).ready(function() {
  $('a').css('outline', 'none');

  $(".clearable").focus(function() {
    var el = $(this);
    if (el.val() == el.attr('title')) {
      el.val('');
    }
  });

  $(".clearable").blur(function() {
    var el = $(this);
    if (el.val() === '') {
      el.val(el.attr('title'));
    }
  });

  $('input[type="hidden"]').css({ 'position' : 'absolute', 'top' : '0', 'left' : '-9999em' });

  $('#ces-slides').cycle({
    timeout: 0,
    speed: 1000,
    easing: 'easeInOutQuad',
    pager: '.menu',
    next:   '.next',
    pagerAnchorBuilder: function(idx, slide) {
      idxNUM = idx + 1;
      return '<a href="#">' + idxNUM + '</a>';
    }
  });

  // jQuery SmoothScroll | Version 09-11-02
  // http://blog.medianotions.de/en/articles/2009/smoothscroll-for-jquery
  $('a[href*=#]').click(function() {
     // duration in ms
     var duration=500;
     // easing values: swing | linear
     var easing='easeInOutQuad';
     // get / set parameters
     var newHash=this.hash;
     var target=$(this.hash).offset().top;
     var oldLocation=window.location.href.replace(window.location.hash, '');
     var newLocation=this;
     // make sure it's the same location
     if (oldLocation+newHash==newLocation) {
        // animate to target and set the hash to the window.location after the animation
        $('html:not(:animated),body:not(:animated)').animate({ scrollTop: target }, duration, easing, function() {
           // add new hash to the browser location
           window.location.href=newLocation;
        });
        // cancel default click action
        return false;
     }
  });

  // Concept borrowed from Ben Nadel.
  // http://www.bennadel.com/blog/1810-Creating-A-Sometimes-Fixed-Position-Element-With-jQuery.htm
  var subnav = $('#subnav');
  if (subnav) {
    var originalSubnavTop = subnav.offset().top;
    subnav.css({width: "196px"})
    $('h3').css('padding-top', '5px')
    var view = $( window );
    view.bind("scroll resize", function() {
      var leftOffset = $('#contact').offset().left - 10;
      var viewTop = view.scrollTop();
      if ((viewTop > originalSubnavTop)) {
        subnav.css({position: 'fixed', left: leftOffset + "px", top: "5px"});
      } else if ((viewTop <= originalSubnavTop)) {
        subnav.css({position: 'absolute', left: '10px', top: originalSubnavTop + "px"});
      }
    });
  }
});

