// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  arguments.callee = arguments.callee.caller;
  if(this.console) console.log( Array.prototype.slice.call(arguments) );
};
// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();)b[a]=b[a]||c})(window.console=window.console||{});

window.requestAnimFrame = (function() {
    return  window.requestAnimationFrame   ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame    ||
            window.oRequestAnimationFrame      ||
            window.msRequestAnimationFrame     ||
            function(/* function */ callback, /* DOMElement */ element){
                window.setTimeout(callback, 1000 / 60);
            };
})();
window.requestInterval = function(fn, delay) {
    if( !window.requestAnimationFrame     &&
        !window.webkitRequestAnimationFrame &&
        !window.mozRequestAnimationFrame    &&
        !window.oRequestAnimationFrame      &&
        !window.msRequestAnimationFrame)
            return window.setInterval(fn, delay);
    var start = new Date().getTime(),
        handle = new Object();
    function loop() {
        var current = new Date().getTime(),
            delta = current - start;
        if(delta >= delay) {
            fn.call();
            start = new Date().getTime();
        }
        handle.value = requestAnimFrame(loop);
    };
    handle.value = requestAnimFrame(loop);
    return handle;
}
window.clearRequestInterval = function(handle) {
    window.cancelAnimationFrame ? window.cancelAnimationFrame(handle.value) :
    window.webkitCancelRequestAnimationFrame ? window.webkitCancelRequestAnimationFrame(handle.value):
    window.mozCancelRequestAnimationFrame ? window.mozCancelRequestAnimationFrame(handle.value):
    window.oCancelRequestAnimationFrame ? window.oCancelRequestAnimationFrame(handle.value):
    window.msCancelRequestAnimationFrame ? msCancelRequestAnimationFrame(handle.value):
    clearInterval(handle);
};

/* Custom Select plugin */
(function($){
  $.fn.extend({
    customSelect: function(opts) {
      if(!$.browser.msie || ($.browser.msie&&$.browser.version > 6)){
        return this.each(function() {
          var $el = $(this), cur = $el.find(':selected');
          $el.after('<span class="' + $el.attr('class') + '"><span class="inner">' + cur.text() + '</span></span>')
          .css({ position:'absolute', opacity:0, fontSize:$el.css('font-size') });
          var span = $el.next(), inner = span.find(':first-child');
          $el.change(function(){
            inner.text($(this).find(':selected').text()).parent();
          });
        });
      }
    }
  });
})(jQuery);

var APP = (function($) {
  var app = {}, $el, $search = $('#search-form'), on = 'on';
  app.ie7 = ($.browser.msie && parseInt($.browser.version, 10) == 7);
  // Public functions
  app.init = function() {
    $('a[href=#]').attr('href', 'javascript:;');
    // Set up the global ajax
    $.ajaxSetup({ cache: false, error: function errorLog(x, e) { log(x, e); }, type: 'POST' });
    contactFormSetup();
    if (!Modernizr.input.placeholder) { placeholder(); }
    yepnope([{
      test: Modernizr.borderradius,
      nope: [STATIC_ROOT + 'js/libs/jquery.corner.js'],
      complete: onCornerLoad
    }]);
    $search.mouseenter(onSearchOver).mouseleave(onSearchOut);
    $('input[type="text"], input[type="email"], input[type="search"], input[type="password"], textarea').live('focus', onInputFocus).live('blur', onInputBlur);
    $('li:last-child').addClass('last'); // IE fix
    emails();
    slim();
    praise_accolades();
    ios_fixes();
    $('form.sugar').submit(onSugarSubmit);
  };
  // Private functions
  function emails() {
    $el = $('.e');
    var e = $el.text().split('//').join('.com').split('/').join('@');
    $el.after('<a href="mailto:' + e + '">' + e + '</a>');
    $el.remove();
  }
  function contactFormSetup() {
    // style the select
    $('.select').customSelect();
    // manually set placeholders
    $el = $('.wpcf7-form');
    $el.find('input[name="first-name"]').attr('placeholder', 'First Name');
    $el.find('input[name="last-name"]').attr('placeholder', 'Last Name');
    $el.find('input[name="email"]').attr('placeholder', 'Business Email');
    $el.find('textarea').attr('placeholder', 'Enter your query');
    // swap the input submit with a button
    $('.wpcf7-form input[type="submit"]').replaceWith('<button class="button" type="submit" title="Submit">Submit</Button>');
  }
  function placeholder() {
    var attr = 'placeholder';
    $('input[' + attr + '!=""]').each(function(idx, el){
      $el = $(el);
      var d = $el.attr(attr);
      if (d === undefined) { return; }
      $el.focus(function onFocus() {
        if (this.value === d) { this.value = ''; }
      }).blur(function onBlur() {
        if ($.trim(this.value) === '') { this.value = d; }
      });
      $el.blur();
    });
  }
  function onCornerLoad() {
      if (!Modernizr.borderradius) {
          $('#main').corner('20px');
          $('.round6:not(.no-radius),.button:not(.no-radius)').corner('6px');
          $('.round9:not(.no-radius)').corner('9px');
          $('.round10:not(.no-radius)').corner('10px');
          $('.round18:not(.no-radius),.testimonials .testimonial,.sidebar li.widget-container').corner('18px');
          $('.round26:not(.no-radius)').corner('26px');
      }
  }
  function onSugarSubmit(e) {
	    $el = $(e.currentTarget);
	    var msg = 'All fields are required.',
	    filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
	    $email = $el.find('.email');
	    if ($el.find('.first').val() === '' || $el.find('.last').val() === '' || $email.val() === '') {
		    alert(msg);
		    return false;
	    }
	    if (!filter.test($email.val())) {
	        alert('Please provide a valid email');
		    $email.focus();
		    return false;
	    }
	    $el.find('button').attr('disabled', 'disabled').css({ opacity : 0.6 });
	    return true;
  }
  function praise_accolades() {
    // todo: convert this to a plugin
    var $wrap, $inner, $nav, a_w, inner_w, wrap_w, orig_offset, new_offset;

    $('.praise-accolades').each(function() {
      $el = $(this);
      $wrap = $el.find('.wrap');
      $inner = $wrap.find('> div');

      // explicitly set the width
      // * assumes all children have the same width
      inner_w = $inner.find('>:first-child').outerWidth(true) * $inner.children().length;
      $inner.width(inner_w);

      wrap_w = $wrap.width();
      offset = wrap_w + 20;
      orig_offset = parseInt($inner.css('left'), 10);

      if (inner_w > offset) {
        $nav = $el.find('.praise-nav');
        $nav.fadeIn();
        $nav.find('.l-button').click(function() {
          if ($inner.is(':animated')) return false;

          new_offset = parseInt($inner.css('left'), 10) + offset;
          if (new_offset <= orig_offset) {
            $inner.animate({left: new_offset});
          } else {
            return false;
          }
        });
        $nav.find('.r-button').click(function() {
          if ($inner.is(':animated')) return false;

          new_offset = parseInt($inner.css('left'), 10) - offset;
          if (-(new_offset) + 20 < inner_w) {
            $inner.animate({left: new_offset});
          } else {
            return false;
          }
        });
      }
    });
  }

  function ios_fixes() {
    if (navigator.userAgent.match(/like Mac OS X/i)) {
      // hide the search button
      $('header .icon .icon').hide();
    }
  }

  function slim() {
    if ($("a[rel^='lightbox']").length <= 0) { return; }
    if (!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
      $("a[rel^='lightbox']").slimbox({
        captionAnimationDuration:100,
        loop:true,
        overlayFadeDuration:200,
        overlayOpacity:0.45,
        resizeDuration:200
      },
      null,
      function(el) {
        return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
      });
    }
  }

  function onInputFocus(e) {
    $(e.currentTarget).addClass(on);
  }
  function onInputBlur(e) {
    $(e.currentTarget).removeClass(on);
  }
  function onSearchOver(e) {
    $search.addClass(on);
  }
  function onSearchOut(e) {
    $search.removeClass(on);
  }
  // Call the init function on load
  $(app.init);
  return app;
} (jQuery));

