/*
 * jquery.tools 1.0.2 - The missing UI library
 *
 * [tools.overlay-1.0.4]
 *
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 *
 * -----
 *
 * Build: Fri Jun 12 13:35:46 GMT+00:00 2009
 */
(function(b){b.tools=b.tools||{version:{}};b.tools.version.overlay="1.0.4";var c=[];function a(h,d){var r=this,q=b(window),f,n,s,i,k,m,l;var e=d.expose&&b.tools.version.expose;function p(o,t){b(r).bind(o,function(v,u){if(t&&t.call(this)===false&&u){u.proceed=false}});return r}b.each(d,function(o,t){if(b.isFunction(t)){p(o,t)}});var j=d.target||h.attr("rel");var g=j?b(j):null;if(!g){g=h}else{k=h}q.load(function(){m=g.attr("overlay");if(!m){m=g.css("backgroundImage");if(!m){throw"background-image CSS property not set for overlay element: "+j}m=m.substring(m.indexOf("(")+1,m.indexOf(")")).replace(/\"/g,"");g.css("backgroundImage","none");g.attr("overlay",m)}s=g.outerWidth({margin:true});i=g.outerHeight({margin:true});n=b('<img src="'+m+'"/>');n.css({border:0,position:"absolute",display:"none"}).width(s).attr("overlay",true);b("body").append(n);if(k){k.bind("click.overlay",function(o){r.load(o.pageY-q.scrollTop(),o.pageX-q.scrollLeft());return o.preventDefault()})}d.close=d.close||".close";if(!g.find(d.close).length){g.prepend('<div class="close"></div>')}f=g.find(d.close);f.bind("click.overlay",function(){r.close()});if(d.preload){setTimeout(function(){var o=new Image();o.src=m},2000)}});b.extend(r,{load:function(w,v){if(!n){q.load(function(){r.load(w,v)});return r}if(r.isOpened()){return r}if(d.oneInstance){b.each(c,function(){this.close()})}var u={proceed:true};b(r).trigger("onBeforeLoad",u);if(!u.proceed){return r}if(e){n.expose(d.expose);l=n.expose().load()}w=w||d.start.top;v=v||d.start.left;var o=d.finish.top;var t=d.finish.left;if(o=="center"){o=Math.max((q.height()-i)/2,0)}if(t=="center"){t=Math.max((q.width()-s)/2,0)}if(!d.start.absolute){w+=q.scrollTop();v+=q.scrollLeft()}if(!d.finish.absolute){o+=q.scrollTop();t+=q.scrollLeft()}n.css({top:w,left:v,width:d.start.width,zIndex:d.zIndex}).show();n.animate({top:o,left:t,width:s},d.speed,function(){g.css({position:"absolute",top:o,left:t});var x=n.css("zIndex");f.add(g).css("zIndex",++x);g.fadeIn(d.fadeInSpeed,function(){b(r).trigger("onLoad")})});return r},close:function(){if(!r.isOpened()){return r}var u={proceed:true};b(r).trigger("onBeforeClose",u);if(!u.proceed){return r}if(l){l.close()}if(n.is(":visible")){g.hide();var t=d.start.top;var o=d.start.left;if(k){u=k.offset();t=u.top+k.height()/2;o=u.left+k.width()/2}n.animate({top:t,left:o,width:0},d.closeSpeed,function(){b(r).trigger("onClose",u)})}return r},getBackgroundImage:function(){return n},getContent:function(){return g},getTrigger:function(){return k},isOpened:function(){return g.is(":visible")},getConf:function(){return d},onBeforeLoad:function(o){return p("onBeforeLoad",o)},onLoad:function(o){return p("onLoad",o)},onBeforeClose:function(o){return p("onBeforeClose",o)},onClose:function(o){return p("onClose",o)}});b(document).keydown(function(o){if(o.keyCode==27){r.close()}});if(d.closeOnClick){b(document).bind("click.overlay",function(o){if(!g.is(":visible, :animated")){return}var t=b(o.target);if(t.attr("overlay")){return}if(t.parents("[overlay]").length){return}r.close()})}}b.fn.overlay=function(e){var f=this.eq(typeof e=="number"?e:0).data("overlay");if(f){return f}var d=b(window);var g={start:{top:Math.round(d.height()/2),left:Math.round(d.width()/2),width:0,absolute:false},finish:{top:80,left:"center",absolute:false},speed:"normal",fadeInSpeed:"fast",closeSpeed:"fast",close:null,oneInstance:true,closeOnClick:true,preload:true,zIndex:9999,api:false,expose:null,target:null};if(b.isFunction(e)){e={onBeforeLoad:e}}b.extend(true,g,e);this.each(function(){f=new a(b(this),g);c.push(f);b(this).data("overlay",f)});return g.api?f:this}})(jQuery);


/*
 * jquery.tools 1.0.2 - The missing UI library
 *
 * [tools.expose-1.0.3]
 *
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 *
 * -----
 *
 * Build: Fri Jun 12 13:02:03 GMT+00:00 2009
 */
(function(b){b.tools=b.tools||{version:{}};b.tools.version.expose="1.0.3";function a(){var e=b(window).width();if(b.browser.mozilla){return e}var d;if(window.innerHeight&&window.scrollMaxY){d=window.innerWidth+window.scrollMaxX}else{if(document.body.scrollHeight>document.body.offsetHeight){d=document.body.scrollWidth}else{d=document.body.offsetWidth}}return d<e?d+20:e}function c(g,h){var e=this,d=null,f=false,i=0;function j(k,l){b(e).bind(k,function(n,m){if(l&&l.call(this)===false&&m){m.proceed=false}});return e}b.each(h,function(k,l){if(b.isFunction(l)){j(k,l)}});b(window).bind("resize.expose",function(){if(d){d.css({width:a(),height:b(document).height()})}});b.extend(this,{getMask:function(){return d},getExposed:function(){return g},getConf:function(){return h},isLoaded:function(){return f},load:function(){if(f){return e}i=g.eq(0).css("zIndex");if(h.maskId){d=b("#"+h.maskId)}if(!d||!d.length){d=b("<div/>").css({position:"absolute",top:0,left:0,width:a(),height:b(document).height(),display:"none",opacity:0,zIndex:h.zIndex});if(h.maskId){d.attr("id",h.maskId)}b("body").append(d);var k=d.css("backgroundColor");if(!k||k=="transparent"||k=="rgba(0, 0, 0, 0)"){d.css("backgroundColor",h.color)}if(h.closeOnEsc){b(document).bind("keydown.unexpose",function(n){if(n.keyCode==27){e.close()}})}if(h.closeOnClick){d.bind("click.unexpose",function(){e.close()})}}var m={proceed:true};b(e).trigger("onBeforeLoad",m);if(!m.proceed){return e}b.each(g,function(){var n=b(this);if(!/relative|absolute|fixed/i.test(n.css("position"))){n.css("position","relative")}});g.css({zIndex:h.zIndex+1});var l=d.height();if(!this.isLoaded()){d.css({opacity:0,display:"block"}).fadeTo(h.loadSpeed,h.opacity,function(){if(d.height()!=l){d.css("height",l)}b(e).trigger("onLoad")})}f=true;return e},close:function(){if(!f){return e}var k={proceed:true};b(e).trigger("onBeforeClose",k);if(k.proceed===false){return e}d.fadeOut(h.closeSpeed,function(){b(e).trigger("onClose");g.css({zIndex:b.browser.msie?i:null})});f=false;return e},onBeforeLoad:function(k){return j("onBeforeLoad",k)},onLoad:function(k){return j("onLoad",k)},onBeforeClose:function(k){return j("onBeforeClose",k)},onClose:function(k){return j("onClose",k)}})}b.fn.expose=function(d){var e=this.eq(typeof d=="number"?d:0).data("expose");if(e){return e}var f={maskId:null,loadSpeed:"slow",closeSpeed:"fast",closeOnClick:true,closeOnEsc:true,zIndex:9998,opacity:0.8,color:"#456",api:false};if(typeof d=="string"){d={color:d}}b.extend(f,d);this.each(function(){e=new c(b(this),f);b(this).data("expose",e)});return f.api?e:this}})(jQuery);


/* Twitter
 * --------------------- */
function twitterLatest(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'" target="_blank">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'" target="_blank">'+reply.substring(1)+'</a>';
    });
    //statusHTML.push('<p>&ldquo;'+status+'&rdquo; &ndash; <small>'+relative_time(twitters[i].created_at)+'</small></p>');
    statusHTML.push('<span class="latest">'+status+'</span>');
  }

  $('#latest-tweet').prepend($(statusHTML.join('')));

  //document.getElementById('latest_tweet').innerHTML = statusHTML.join('');
}

function twitterCallback2(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'" target="_blank">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'" target="_blank">'+reply.substring(1)+'</a>';
    });
    //statusHTML.push('<p>&ldquo;'+status+'&rdquo; &ndash; <small>'+relative_time(twitters[i].created_at)+'</small></p>');
    statusHTML.push('<p>'+status+'</p>');
  }

  $('.loading').fadeOut(750, function() {
     $('#latest_tweet').append($(statusHTML.join('')).hide().fadeIn(750));
  });

  //document.getElementById('latest_tweet').innerHTML = statusHTML.join('');
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}

$(document).ready(function() {
  var excol = '<span class="collapse trigger">collapse (<b>-</b>)</span><span class="expand trigger">expand (<b>+</b>)</span>';
  $('#work li h3').append(excol);
  var tweets = $('#tweets');
  $('#work > li > ul').hide();
  //$('#work .collapse').hide();
  $.getScript('http://twitter.com/statuses/user_timeline/numethod.json?callback=twitterLatest&count=1');


  $('#work li h3').hover(
    function(){
      var theParent = $(this).parent();
      var collapse = $('.collapse', this);
      var expand = $('.expand', this);

      if(theParent.hasClass('active')) {
        $('.collapse', this).show();
      } else {
        $('.expand', this).show();
      }
    },
    function(){
      $('span', this).hide();
    });

  $('#work li h3 .trigger').click(function() {
    var checkElement = $(this).parent().next();
    var $target = $(this).parent().parent();
    if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
      $target.removeClass('active');
      checkElement.slideUp('slow');
      return false;
    }
    if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
      $('#work > li > ul:visible').slideUp('slow');
      checkElement.slideDown('slow',function() {
        $target.addClass('active');
        var target = $target.length && $target;
        if ($target.length) {
          var targetOffset = $target.offset().top;
          $('html,body').animate({scrollTop: targetOffset}, 1000);
        }
      });
      return false;
    }
  });

  $('.backtop a').click(function() {
    var $target = $(this).parent().parent();
    $target = $target.length && $target;
    if ($target.length) {
      var targetOffset = ($target.offset().top - 28);
      $('html,body').animate({scrollTop: targetOffset}, 1000);
      return false;
    }
  });

  $('#latest-tweet .expand a').click(function() {
    if ((tweets.is(':hidden'))) {
      tweets.fadeIn('slow', function() {
        if (!$("#latest_tweet p").length) {
          $.getScript('http://twitter.com/statuses/user_timeline/numethod.json?callback=twitterCallback2&count=5');
        }
      });
      return false;
    }
    if (!tweets.is(':hidden')) {
      tweets.fadeOut('slow');
      return false;
    }
  });

  $("#tweets .close a").click(function() {
    tweets.fadeOut('slow');
    return false;
  });

  // Overlay
  $(function() {
    var api = $("#contact").overlay({
      api:true,
      close: '.close a',
      closeOnClick: false,
      expose: {
        closeOnClick: false,
        color: '#222',
        opacity:.9
      },
      finish: {top: 40}
    });
    // define function that opens the overlay
    window.openOverlay = function() {
      api.load();
    }
    window.closeOverlay = function() {
      api.close();
    }
  });

  // Open Contact Form Overlay
  $("a.contact-trigger").click(function() {
    $('#contact form .error').remove();
    openOverlay();
    return false;
  });

  // Close Contact Form Overlay
  $("#contact .close a").click(function() {
    closeOverlay();
    return false;
  });


  /* Contact Form
   * http://trevordavis.net/blog/tutorial/wordpress-jquery-contact-form-without-a-plugin/
   * ------------------------------------------------------------------------------------- */
  $('#contact form').submit(function() {
    $('#contact form .error').remove();
    var hasError = false;
    $('.required').each(function() {
      if(jQuery.trim($(this).val()) == '') {
        var labelText = $(this).attr('name');
        $(this).parent().append('<span class="error">You forgot to enter your '+labelText+'</span>');
        hasError = true;
      } else if($(this).hasClass('email')) {
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
        if(!emailReg.test(jQuery.trim($(this).val()))) {
          var labelText = $(this).attr('name');
          var errMssg = $(this).next();
          $(this).parent().append('<span class="error">You entered an invalid '+labelText+'.</span>');
          hasError = true;
        }
      }
    });
    if(!hasError) {
      $('#contact form button').fadeOut('normal', function() {
        $(this).parent().addClass('active');
      });
      var formInput = $('#contact form').serialize();
      /*$.post($(this).attr('action'), formInput, function(data){
        $('#contact form').slideUp("slow", function() {
          $(this).before('<p class="thanks"><strong>Thanks!</strong> Your email was successfully sent. I will get back to you as soon as possible.</p>');
        });
      });*/
      $.ajax({
        type: "POST",
        url: "mail.php",
        data: formInput,
        success: function(data) {
          $('#contact form').slideUp(1000, function() {
            $('#contact').html('<div class="success"></div>');
            if (data == 'fail') {
              $('.success').html('<h3>Thank You!</h3>');
            }
            else {
              $('.success').html('<h3>Thank You!</h3>')
                .append('<p>Your message was successfully sent. I will get back to you as soon as possible.</p>')
            }
          }),
          setTimeout(function(){closeOverlay();}, 3500);
        }
      });
    }

    return false;

  });

});

