var debug = false;

/*
 *
 * before DOM ready
 *
 */

/*-----top nav-----*/
function highlightLink(body_id) {
 var $headerLinks = $('.header .nav a');
 $headerLinks.each(function() {
  if (body_id == "case-study") body_id = "gallery"; /* fixme - ugly */
  if ($(this).text().toLowerCase() == body_id && $headerLinks.filter('.active').text().toLowerCase() != body_id) {
   $headerLinks.removeClass('active');
   $(this).addClass('active');
   var $inner = $(this).find('.inner');
   $inner.animate({'top': -parseInt($inner.css('padding-top'))},'fast','easeOutQuad',function() {
    $(this).animate({'top': 0},1000,'easeOutBounce');
   });
  }
 });
}

/*-----loading cursor-----*/
function showLoading() {
 $(this).css('visibility','hidden');
 $body.mousemove(followCursor);
 loading.css({'display': 'block'}).fadeIn();
 /*
 TODO:
 setTimeout(function() {
  $('#still-loading').remove();
  $('#content').before('<div id="still-loading"><p>Loading ...</p></div>');
  $('#still-loading').hide().fadeIn(fixClearType);
  }, 500);
 setTimeout(function() {
  $('#still-loading').append('<p>This is taking longer than expected. Check your internet connection,<br /> then <a href="">click here to try again</a>.</p>');
  $('#still-loading p:last').hide().fadeIn(fixClearType);
  }, 4000);
  */
}

function followCursor(event) {
 loading.css({'top': (event.pageY + 16) + 'px', 'left': (event.pageX + 16) + 'px'});
}

function hideLoading() {
 /*
 $('#still-loading').stop().fadeOut(function() {
  $(this).remove();
 });
 */
 loading.fadeOut(function() {
  $body.unbind('mousemove', followCursor);
  $(this).css('display','none');
 });
}

/*-----after fade in-----*/
function fixClearType(param) {
 var el = param || this;
 if ($.browser.msie) el.style.removeAttribute('filter'); // fix IE7 font rendering
}

/*-----ajax-----*/
// PageLoad function
// This function is called when:
// 1. after calling $.historyInit();
// 2. after calling $.historyLoad();
// 3. after pushing "Go Back" button of a browser
function pageload(hash) {
 if (Shadowbox.isActive()) {
  Shadowbox.close();
 }
 if (debug) $('body').prepend("<br />pageload called: testing for hash" + "(" + hash + ")");
 if (hash == "") hash = "/";

 var content = $('#content');
 content.after('<div id="content2"></div>').animate({'opacity': 0}, 'normal', showLoading);
 var content2 = $('#content2');

 // different pages are served based on load method so ?ajax=true is added to URI prevent browser caching
 content2.css('display','none').load(hash + '?ajax=true', function() {
  $(this).css('visibility','hidden');
  $('body').attr({'id': body_id, 'class': body_class}); // comes from inline js in ajax loaded doc
  highlightLink(body_id);
  hideLoading();
  var oldHeight = content.innerHeight();
  var newHeight = content2.innerHeight();
  content.stop().html(content2.html()).css({'visibility': 'visible', 'opacity': 0, 'height': oldHeight});
  content2.remove();
  if (debug) $('body').prepend("<br />Cufon.refresh();");
  Cufon.refresh();
  
  content
   .stop()
   .animate({'opacity': 1, 'height': newHeight}, 'slow', function() {
    pageTracker._trackPageview(hash); // track Google analytics
    fixClearType(this);
    $(this).css('height','auto').attr('id','content');
   });
   
 });

 if (debug) $('body').prepend('<br />hash exists: load(' + hash +')');
}

/*-----shadowbox-----*/
Shadowbox.init({
 animateFade: false,
 ease: function(x){
  return 1 + Math.pow(x - 1, 3);//default cubic polynomial
  //return x; //linear?
 },
 resizeDuration: .2,
 skipSetup: true,
 players: ['img','swf','html','iframe'],
 handleOversize: "drag", //"none", "drag" or "resize"
 viewportPadding: 20,
 overlayOpacity: 0.4,
 enableKeys: false //true breaks browser keys
});

/*-----tooltip-----*/
$.tooltip = {
 defaults: {
  delay: 0,
  fade: 200,
  showURL: false,
  extraClass: "",
  top: 15,
  left: 15,
  id: "tooltip",
  showBody: " - ",
  track: true
 }
};

var loading; // required for IE

/*
 *
 * on DOM ready
 *
 */
$(function() {
 Cufon.set('hover','true');
 Cufon.replace('h1', { fontFamily: 'Kievit Medium' });
 Cufon.replace('h2', { fontFamily: 'Kievit Book' });
 Cufon.replace('h3', { fontFamily: 'Kievit Medium' });
 Cufon.replace('h4', { fontFamily: 'Kievit Medium' });
 Cufon.replace('.button', { fontFamily: 'Kievit Medium', textShadow: '#000 1px 1px'});
 Cufon.replace('.nav a', { fontFamily: 'Helvetica Neue Roman' });

 $body = $('body');
 $body.append('<span id="loading"></span>');
 loading = $('#loading');

 // Initialize history plugin. The callback pageload is called only when hash exists
 $.historyInit(pageload, ""); //jquery_history.html
 
 /*-----inkreel logo-----*/
 $('a.ink-logo').hover(
  function() {
   $(this).addClass('hover').stop().css({'opacity': 0}).animate({'opacity': 1}, {queue: false, duration: 400});
  },
  function() {
   $(this).css({'display': 'block'}).animate({'opacity': 0}, {queue: false, duration: 800});
  }
 );

 $.easing.def = "easeOutCubic";

 /* -----top nav snake----- */
 var $headerLinks = $('.header .nav a');
 var navMargin = parseInt($headerLinks.css('margin-left'));
 var $unders = $headerLinks.find('.under');
 var $last = $([]); // empty jquery object
 var $lastUnder = $([]); // empty jquery object
 var lastText = "";
 if($unders.css('display') == 'none') { // if underlines are divs
  $unders.css({'opacity': 0, 'display': 'block'});
  $headerLinks.hover(
   function(event) {
    var $next = $(this).next();
    var $prev = $(this).prev();
    var $under = $(this).find('.under');
    var thisWidth = $(this).outerWidth() + navMargin;
    var nextWidth = $next.outerWidth();
    var prevWidth = $prev.outerWidth();
    if (lastText == $next.text() && $lastUnder.is(':animated') && $lastUnder.css('opacity') > .1) { // if moving left
     $unders.not($under).not($lastUnder).css('opacity',0);
     $next.find('.under').stop(true).animate({'left': -nextWidth}, // stops fadeOut, slides next left
      function() { // when done sliding left
       $(this).css({'left': 0, 'opacity': 0});
      }
     );
     $under.css({'opacity': 1, 'left': thisWidth}).stop().animate({'left': 0}); // slides current left
    }
    else if (lastText == $prev.text() && $lastUnder.is(':animated') && $lastUnder.css('opacity') > .1) { // if moving right
     $unders.not($under).not($lastUnder).css('opacity',0);
     $prev.find('.under').stop(true).animate({'left': prevWidth}, // stops fadeOut, slides prev right
      function() { // when done sliding right
       $(this).css({'left': 0, 'opacity': 0});
      }
     );
     $under.css({'opacity': 1, 'left': -thisWidth}).stop().animate({'left': 0}); // slides current right
    }
    else { // if not moving
     $under.stop(true).animate({'opacity': 1}, 'fast');
    }
   },
   function(event) {
    $last = $(this);
    $lastUnder = $last.find('.under');
    lastText = $last.text();
    $(this).find('.under').animate({'opacity': 0}, 'slow' );
   }
  );  
 }
 
 /*-----sliding >> arrows (livequery)-----*/
 // TODO: Fix fade out in IE8
 $('.feature h1 a, .feature h2 a').livequery(
  function() {
   $(this).hover(function() {
    $(this).find('span.arrow').css({'display': 'inline'}); // to allow fade out animation
    $(this).find('span.arrow').css({'left': '-8px'});
    $(this).find('span.arrow').stop().animate({
     'opacity': 1,
     'left': '2px'
    }, {
     queue: false,
     duration: 200
    });
   },
   function() {
    $(this).find('span.arrow').animate({
     'opacity': 'toggle'
    }, {
     queue: false,
     duration: 400
    });
   });
  },
  function() {
   $(this).unbind('mouseover').unbind('mouseout');
  }
 );

 /*-----thumb control for feature handler-----*/
 function thumbLighten($el) {
  if ($el.length == undefined) $el = $(this);
  $el.find('img').css({'opacity': .75}).stop().animate({'opacity': 1}, {queue: false, duration: 400});
  $el.find('.icon').css({'display': 'block', 'opacity': 0}).stop().animate({'opacity': 1}, {queue: false, duration: 400});
 }

 function thumbDarken($el) {
  if ($el.length == undefined) $el = $(this);
  $el.find('img').animate({'opacity': .75}, {queue: false, duration: 800});
  $el.find('.icon').animate({'opacity': 0}, {queue: false, duration: 800});
 }

 /*-----feature handler w/ link sets (livequery)-----*/
 function linkHandler() {
  $(this).toggleClass('hover');
  if ($(this).find('span.cufon').length > 0) {
   Cufon.refresh($(this).parent()[0].tagName.toLowerCase());
  }
 }

 function linkSetHandler() {
  var $linkSet = $(this);
   var $links = $linkSet.find('a.linked');
   $links.each(function() {
    $(this).hover(function() {
     //alert('over a link set');
     thumbLighten($linkSet.find('.thumb a'));
     $links.each(linkHandler);
    }, function() {
     //alert('leaving a link set');
     thumbDarken($linkSet.find('.thumb a'));
     $links.each(linkHandler);
    });
   });
 }

 function featureHandler() {
  var $linkSet = $(this).find('.links').andSelf().filter('.links'); //TODO: cleaner?
  if ($linkSet.length > 0) {
   $linkSet.each(linkSetHandler);
  }
  else {
   $(this).find('.thumb a').hover(thumbLighten, thumbDarken);
  }
 }

 function unHover() {
  $(this).unbind('mouseover').unbind('mouseout');
 }

 $('.feature').livequery(featureHandler, unHover);

 /*-----buttons-----*/
 function buttonHandler() {
  $(this).hover(
   function(event) {
    $(this).addClass('unhover');
    if ($(this).find('span.inner span.top').length == 0) { // once
     $(this).find('span.inner').wrapInner('<span class="top"></span>'); // IE6 text hack
    }
    var hoverOpacity = $(this).find('.hover').css('opacity') || 0;
    $(this).find('.hover').remove();
    var $buttonHoverLeft = $(this).prepend('<span class="hover"></span>').find('span.hover');
    var $buttonHoverRight = $buttonHoverLeft.prepend('<span class="hover"></span>');
    $buttonHoverLeft.css({
     'width': $buttonHoverLeft.parent().innerWidth(),
     'height': $buttonHoverLeft.parent().innerHeight(),
     'opacity': hoverOpacity /* needed for IE */
    });
    $buttonHoverLeft.animate({'opacity': 1}, 400*(1-hoverOpacity), function() {$(this).css('cursor','hand');});
   },
   function(event) {
    $(this).children('span.hover').animate({'opacity': 0}, 600, function() {
     $(this).parent().removeClass('unhover');
     $(this).remove();
    });
   }
  );
 }
 $('.button').livequery(buttonHandler, unHover);

 /* -----footer form----- */
 $('.feature .contact form').RSV({
  displayType: "display-html",
  onCompleteHandler: submitFooterForm,
  errorFieldClass: "required",
  rules: [
   "equals_original,name,Please provide your name.",
   "valid_email,email,Please enter a valid e-mail address."
  ]
 });

 function submitFooterError(f, errorInfo) {
  if (errorInfo.length == 0) {
   submitFooterForm();
  }
  else {
   $('.feature .contact .error').animate({
    'height': 'toggle',
    'opacity': 'toggle'
   }, 'slow');
  }
  return false;
 }

 function submitFooterForm() {
  //$.ajax({ url: "process-form.asp", type: 'post', data: $('form:first').serialize(), async: false });
  
  $('.feature .contact .error').fadeOut('fast');
  $('form:first').fadeOut('fast', function(){
   $('.feature .contact .sending').fadeIn('fast',function(){
    var act = $('form:first').attr('action');
    var vars = $('form:first').serialize();
    $.post(
     act,
     vars,
     function(){
      $('.feature .contact .sending').fadeOut('fast',function(){
       $('.feature .contact .thanks').fadeIn('slow');
      });
     }
    );
   });
  });

  return false;
 }

 /* -----clear form fields on focus----- */
 $('form input:text, form textarea')
 .focus(function() {
  $(this).addClass('focus'); // add focus class for IE6
  if ($(this).val() == $(this).attr('title')) {
   $(this).val('');
  }
 })
 .blur(function() {
  $(this).removeClass('focus');
  if ($(this).val() == '') {
   $(this).val($(this).attr('title'));
  }
 });
 
 /*-----regular popup window (livequery)-----*/
 $('a.popup').livequery('click', function(event) {
  event.preventDefault();
  var params = $(this).data("popup") || {}; // Grab parameters using jQuery's data() method
  if ($(this).attr("target")) { // Use the target attribute as the window name
   params.windowName = $(this).attr("target");
  }
  var windowObject = popup.open(this.href, params); // Pop up the window
  $(this).data("windowObject", windowObject); // Save the window object for other code to use
 });
  
 
 /*-----history (livequery)-----*/
 // Create custom :external selector (from http://custom-drupal.com/jquery-demo/external-links/)
 $.expr[':'].external = function(obj) {
  return (obj.hostname != location.hostname);
 };
 
 // add ajax listeners
 $('a:not(.popup,.zoom,.play,#sb-container a,[href$=.pdf],[href^=mailto],:external)').livequery('click', function(event) {
  if (debug) $('body').prepend('<br/>ajax link clicked!');
  loading.css({'top': (event.pageY + 10) + 'px', 'left': (event.pageX + 10) + 'px'})
  var path = parseUri(this.href).path;
  //var query = parseUri(this.href).query; // part after ?
  // moves to a new page - pageload is called
  $('div#tooltip').hide();
  $.historyLoad(path);
  return false;
 });

 $('#sb-container').livequery(
  function() {
   $(this).tooltip({
    extraClass: "close-tip",
    bodyHandler: function() {
     return ("Close");
    }
   });
  }
 );
 
 $('div.more a').livequery(
  function() {
   $(this).tooltip({
    bodyHandler: function() {
     return ('<span class="title">' + $(this).attr('rel') + "</span>");
    }
   });
  }
 );

 /* -----gallery client panel slide (livequery)----- */
 $('.feature.mini-slice .thumb a').livequery(
  function() {
   var label = $(this).find('.label.top');
   label.stop().css({'top': '-' + label.outerHeight() + 'px'});
   $(this).hover(
    function(event) {
     label.stop().animate({'top': '0'});
    },
    function(event) {
     label.stop().animate({'top': '-' + label.outerHeight() + 'px'});
    }
   );
  }
 );

 /*-----shadowbox (livequery)-----*/
 $('.zoom, .play, .iframe').livequery(
  function() {
   Shadowbox.setup($(this));
  }
 );
 // close on non-draggable click
 $('#sb-container #sb-content').livequery('click', function(event) {
   //event.preventDefault();
   Shadowbox.close();
  }
 )

});
