/**
 * Compact labels plugin
 */
(function($){$.fn.compactize=function(){return this.each(function(){var label=$(this),input=$('#'+label.attr('for'));input.focus(function(){label.hide();}).blur(function(){if(input.val()===''){label.show();}});window.setTimeout(function(){if(input.val()!==''){label.hide();}},50);});};})(jQuery);

/*
 * hrefID jQuery extention - returns a valid #hash string from link href attribute in Internet Explorer
 */
(function($){$.fn.extend({hrefId:function(){return $(this).attr('href').substr($(this).attr('href').indexOf('#'));}});})(jQuery);

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 * Open source under the BSD License. 
 * 
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
*/
jQuery.easing['jswing']=jQuery.easing['swing'];jQuery.extend(jQuery.easing,{def:'easeOutQuad',swing:function(x,t,b,c,d){return jQuery.easing[jQuery.easing.def](x,t,b,c,d);},easeInQuad:function(x,t,b,c,d){return c*(t/=d)*t+b;},easeOutQuad:function(x,t,b,c,d){return-c*(t/=d)*(t-2)+b;},easeInOutQuad:function(x,t,b,c,d){if((t/=d/2)<1)return c/2*t*t+b;return-c/2*((--t)*(t-2)-1)+b;},easeInCubic:function(x,t,b,c,d){return c*(t/=d)*t*t+b;},easeOutCubic:function(x,t,b,c,d){return c*((t=t/d-1)*t*t+1)+b;},easeInOutCubic:function(x,t,b,c,d){if((t/=d/2)<1)return c/2*t*t*t+b;return c/2*((t-=2)*t*t+2)+b;},easeInQuart:function(x,t,b,c,d){return c*(t/=d)*t*t*t+b;},easeOutQuart:function(x,t,b,c,d){return-c*((t=t/d-1)*t*t*t-1)+b;},easeInOutQuart:function(x,t,b,c,d){if((t/=d/2)<1)return c/2*t*t*t*t+b;return-c/2*((t-=2)*t*t*t-2)+b;},easeInQuint:function(x,t,b,c,d){return c*(t/=d)*t*t*t*t+b;},easeOutQuint:function(x,t,b,c,d){return c*((t=t/d-1)*t*t*t*t+1)+b;},easeInOutQuint:function(x,t,b,c,d){if((t/=d/2)<1)return c/2*t*t*t*t*t+b;return c/2*((t-=2)*t*t*t*t+2)+b;},easeInSine:function(x,t,b,c,d){return-c*Math.cos(t/d*(Math.PI/2))+c+b;},easeOutSine:function(x,t,b,c,d){return c*Math.sin(t/d*(Math.PI/2))+b;},easeInOutSine:function(x,t,b,c,d){return-c/2*(Math.cos(Math.PI*t/d)-1)+b;},easeInExpo:function(x,t,b,c,d){return(t==0)?b:c*Math.pow(2,10*(t/d-1))+b;},easeOutExpo:function(x,t,b,c,d){return(t==d)?b+c:c*(-Math.pow(2,-10*t/d)+1)+b;},easeInOutExpo:function(x,t,b,c,d){if(t==0)return b;if(t==d)return b+c;if((t/=d/2)<1)return c/2*Math.pow(2,10*(t-1))+b;return c/2*(-Math.pow(2,-10*--t)+2)+b;},easeInCirc:function(x,t,b,c,d){return-c*(Math.sqrt(1-(t/=d)*t)-1)+b;},easeOutCirc:function(x,t,b,c,d){return c*Math.sqrt(1-(t=t/d-1)*t)+b;},easeInOutCirc:function(x,t,b,c,d){if((t/=d/2)<1)return-c/2*(Math.sqrt(1-t*t)-1)+b;return c/2*(Math.sqrt(1-(t-=2)*t)+1)+b;},easeInElastic:function(x,t,b,c,d){var s=1.70158;var p=0;var a=c;if(t==0)return b;if((t/=d)==1)return b+c;if(!p)p=d*.3;if(a<Math.abs(c)){a=c;var s=p/4;}else{var s=p/(2*Math.PI)*Math.asin(c/a);}return-(a*Math.pow(2,10*(t-=1))*Math.sin((t*d-s)*(2*Math.PI)/p))+b;},easeOutElastic:function(x,t,b,c,d){var s=1.70158;var p=0;var a=c;if(t==0)return b;if((t/=d)==1)return b+c;if(!p)p=d*.3;if(a<Math.abs(c)){a=c;var s=p/4;}else{var s=p/(2*Math.PI)*Math.asin(c/a);}return a*Math.pow(2,-10*t)*Math.sin((t*d-s)*(2*Math.PI)/p)+c+b;},easeInOutElastic:function(x,t,b,c,d){var s=1.70158;var p=0;var a=c;if(t==0)return b;if((t/=d/2)==2)return b+c;if(!p)p=d*(.3*1.5);if(a<Math.abs(c)){a=c;var s=p/4;}else{var s=p/(2*Math.PI)*Math.asin(c/a);}if(t<1)return-.5*(a*Math.pow(2,10*(t-=1))*Math.sin((t*d-s)*(2*Math.PI)/p))+b;return a*Math.pow(2,-10*(t-=1))*Math.sin((t*d-s)*(2*Math.PI)/p)*.5+c+b;},easeInBack:function(x,t,b,c,d,s){if(s==undefined)s=1.70158;return c*(t/=d)*t*((s+1)*t-s)+b;},easeOutBack:function(x,t,b,c,d,s){if(s==undefined)s=1.70158;return c*((t=t/d-1)*t*((s+1)*t+s)+1)+b;},easeInOutBack:function(x,t,b,c,d,s){if(s==undefined)s=1.70158;if((t/=d/2)<1)return c/2*(t*t*(((s*=(1.525))+1)*t-s))+b;return c/2*((t-=2)*t*(((s*=(1.525))+1)*t+s)+2)+b;},easeInBounce:function(x,t,b,c,d){return c-jQuery.easing.easeOutBounce(x,d-t,0,c,d)+b;},easeOutBounce:function(x,t,b,c,d){if((t/=d)<(1/2.75)){return c*(7.5625*t*t)+b;}else if(t<(2/2.75)){return c*(7.5625*(t-=(1.5/2.75))*t+.75)+b;}else if(t<(2.5/2.75)){return c*(7.5625*(t-=(2.25/2.75))*t+.9375)+b;}else{return c*(7.5625*(t-=(2.625/2.75))*t+.984375)+b;}},easeInOutBounce:function(x,t,b,c,d){if(t<d/2)return jQuery.easing.easeInBounce(x,t*2,0,c,d)*.5+b;return jQuery.easing.easeOutBounce(x,t*2-d,0,c,d)*.5+c*.5+b;}});

/* 
 * jquery.tweet.js
 */
(function($) {
 
  $.fn.tweet = function(o){
    var s = {
      username: ["seaofclouds"],              // [string]   required, unless you want to display our tweets. :) it can be an array, just do ["username1","username2","etc"]
      avatar_size: null,                      // [integer]  height and width of avatar if displayed (48px max)
      count: 3,                               // [integer]  how many tweets to display?
      intro_text: null,                       // [string]   do you want text BEFORE your your tweets?
      outro_text: null,                       // [string]   do you want text AFTER your tweets?
      join_text:  null,                       // [string]   optional text in between date and tweet, try setting to "auto"
      auto_join_text_default: "i said,",      // [string]   auto text for non verb: "i said" bullocks
      auto_join_text_ed: "i",                 // [string]   auto text for past tense: "i" surfed
      auto_join_text_ing: "i am",             // [string]   auto tense for present tense: "i was" surfing
      auto_join_text_reply: "i replied to",   // [string]   auto tense for replies: "i replied to" @someone "with"
      auto_join_text_url: "i was looking at", // [string]   auto tense for urls: "i was looking at" http:...
      loading_text: null,                     // [string]   optional loading text, displayed while tweets load
      query: null                             // [string]   optional search query
    };

    $.fn.extend({
      linkUrl: function() {
        var returning = [];
        var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
        this.each(function() {
          returning.push(this.replace(regexp,"<a href=\"$1\">$1</a>"))
        });
        return $(returning);
      },
      linkUser: function() {
        var returning = [];
        var regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
        this.each(function() {
          returning.push(this.replace(regexp,"<a href=\"http://twitter.com/$1\">@$1</a>"))
        });
        return $(returning);
      },
      linkHash: function() {
        var returning = [];
        var regexp = / [\#]+([A-Za-z0-9-_]+)/gi;
        this.each(function() {
          returning.push(this.replace(regexp, ' <a href="http://search.twitter.com/search?q=&tag=$1&lang=all&from='+s.username.join("%2BOR%2B")+'">#$1</a>'))
        });
        return $(returning);
      },
      capAwesome: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/(a|A)wesome/gi, 'AWESOME'))
        });
        return $(returning);
      },
      capEpic: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/(e|E)pic/gi, 'EPIC'))
        });
        return $(returning);
      },
      makeHeart: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/[&lt;]+[3]/gi, "<tt class='heart'>&#x2665;</tt>"))
        });
        return $(returning);
      }
    });

    function relative_time(time_value) {
      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);
      if(delta < 60) {
      return 'less than a minute ago';
      } else if(delta < 120) {
      return 'about a minute ago';
      } else if(delta < (45*60)) {
      return (parseInt(delta / 60)).toString() + ' minutes ago';
      } else if(delta < (90*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';
      }
    }

    if(o) $.extend(s, o);
    return this.each(function(){
      var list = $('<ul class="tweet_list">').appendTo(this);
      var intro = '<p class="tweet_intro">'+s.intro_text+'</p>'
      var outro = '<p class="tweet_outro">'+s.outro_text+'</p>'
      var loading = $('<p class="loading">'+s.loading_text+'</p>');
      if(typeof(s.username) == "string"){
        s.username = [s.username];
      }
      var query = '';
      if(s.query) {
        query += 'q='+s.query;
      }
      query += '&q=from:'+s.username.join('%20OR%20from:');
      var url = 'http://search.twitter.com/search.json?&'+query+'&rpp='+s.count+'&callback=?';
      if (s.loading_text) $(this).append(loading);
      $.getJSON(url, function(data){
        if (s.loading_text) loading.remove();
        if (s.intro_text) list.before(intro);
        $.each(data.results, function(i,item){
          // auto join text based on verb tense and content
          if (s.join_text == "auto") {
            if (item.text.match(/^(@([A-Za-z0-9-_]+)) .*/i)) {
              var join_text = s.auto_join_text_reply;
            } else if (item.text.match(/(^\w+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+) .*/i)) {
              var join_text = s.auto_join_text_url;
            } else if (item.text.match(/^((\w+ed)|just) .*/im)) {
              var join_text = s.auto_join_text_ed;
            } else if (item.text.match(/^(\w*ing) .*/i)) {
              var join_text = s.auto_join_text_ing;
            } else {
              var join_text = s.auto_join_text_default;
            }
          } else {
            var join_text = s.join_text;
          };

          var join_template = '<span class="tweet_join"> '+join_text+' </span>';
          var join = ((s.join_text) ? join_template : ' ')
          var avatar_template = '<a class="tweet_avatar" href="http://twitter.com/'+ item.from_user+'"><img src="'+item.profile_image_url+'" height="'+s.avatar_size+'" width="'+s.avatar_size+'" alt="'+item.from_user+'\'s avatar" border="0"/></a>';
          var avatar = (s.avatar_size ? avatar_template : '')
          var date = '<a href="http://twitter.com/'+item.from_user+'/statuses/'+item.id+'" title="view tweet on twitter">'+relative_time(item.created_at)+'</a>';
          var text = '<span class="tweet_text">' +$([item.text]).linkUrl().linkUser().linkHash().makeHeart().capAwesome().capEpic()[0]+ '</span>';
          
          // until we create a template option, arrange the items below to alter a tweet's display.
          list.append('<li>' + avatar + date + join + text + '</li>');

          list.children('li:first').addClass('tweet_first');
          list.children('li:odd').addClass('tweet_even');
          list.children('li:even').addClass('tweet_odd');
        });
        if (s.outro_text) list.after(outro);
      });

    });
  };
})(jQuery);

/* 
 * Promos 
 */
(function($){
	var HRPromos= function(el,data){
		if (typeof data[0] === 'undefined') {
			throw "missing datasource";
		}
		var src = data[0];
		
		if ($.cookie('firstView') == 1) {
			return;			
		}
		$.cookie('firstView',1);
		
		var $overlay = $('<div id="overlay"/>').css('opacity','0.8').hide();
		
		if ($.browser.msie === true && $.browser.version === '6.0'){
			$(window).resize(function(){
				$overlay.height($(document).height());				
			}).triggerHandler('resize');
		}
		
		var $lightbox = $('<div id="lightbox-d"><div class="inner"/></div>').hide();	
		var $content = $('div.inner', $lightbox);
		
		var 
			keydown, close;
			
		close = function(){
			$(document).unbind('keydown',keydown);			

			var speed = $.browser.msie ? 0 : 'fast';
			$lightbox.add($overlay).fadeOut(speed,function(){
				$(this).hide();
			});			
		};
				
		//close on ESC
		keydown = function(e){
			if (e.keyCode === 27){
				close();
			}			
		};
						
		var $closeTrigger = $('<a href="#" class="close">Close</a>').click(function(e){
			e.preventDefault();
			close();
		});				
						
		$overlay.click(function(e){
			close();
		});
		
		$lightbox.append($closeTrigger);		
				
		$('body').append($overlay, $lightbox);
		$(document).bind('keydown',keydown);
				
		$content.load(src,this,function(){
			var speed = $.browser.msie ? 0 : 'fast';
			$lightbox.add($overlay).fadeIn(speed);			
		});
	};

	$.fn.hrpromos = function(){
		var options = arguments;
		return $(this).each(function(){			
			var lb = new HRPromos(this,options);
		});
	};		
})(jQuery);

/* 
 * Personality Scale
 */
(function($){
	var HRScale = function(el, data){
				
		var $overlay = $('<div id="overlay"/>').css('opacity','0.8').hide();
		
		if ($.browser.msie === true && $.browser.version === '6.0'){
			$(window).resize(function(){
				$overlay.height($(document).height());				
			}).triggerHandler('resize');
		}
		
		var $lightbox = $('<div id="lightbox-c"><div class="wrapper"/><p class="copyright">Copyright &copy; 2010 HandyRandy Communications Inc.</p><div class="nav"><p class="close"/></div><p class="art10"></span></div>').hide();	
		var $content = $('div.wrapper', $lightbox);
		
		var 
			keydown, close;
			
		close = function(){
			$(document).unbind('keydown',keydown);			

			var speed = $.browser.msie ? 0 : 'fast';
			$lightbox.add($overlay).fadeOut(speed,function(){
				$(this).hide();
			});			
			
			$content.find('.section-b, .section-b .step, .section-c').hide();
			$content.find('.section-a a.active').removeClass('active');
			$content.find('input').val('');
			$content.find('label').show();			
		};
				
		//close on ESC
		keydown = function(e){
			if (e.keyCode === 27){
				close();
			}			
		};
						
		var $closeTrigger = $('<a href="#">Close</a>').click(function(e){
			e.preventDefault();
			close();
		});				
						
		$overlay.click(function(e){
			close();
		});
		
		$lightbox.find('p.close').append($closeTrigger);				
		$content.append($('#scale .scale-inner'));
		

				
		var validateEmail = function(field) {
			var val = $.trim($(field).val());
			return (/^[A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,6}$/i).test(val);					
		};

		var validateRequired = function(field) {
			var val = $.trim($(field).val());					
			return (val !== '');
		};

		var addError = function(msg) {
			var $errors = $content.find('form ul.errors');
			if ($errors.length === 0) {
				$content.find('form').prepend('<ul class="errors" />');
				$errors = $content.find('form ul.errors');
			}
			
			$errors.append('<li>'+msg+'</li>');
		};

		$content.find('form').submit(function(e){
			e.preventDefault();
			$(this).find('ul.errors').remove();

			var flag = true;
				
			var $email = $('#f-scale-email');
			if (validateRequired($email) === false) {
				addError('Please provide an email address.');
				flag = false;
			}
			else if (validateEmail($email) === false) {
				addError('Provided email address is invalid.');
				flag = false;
			}
			
			var $name = $('#f-scale-name');
			if (validateRequired($name) === false) {
				addError('Please provide your name.');
				flag = false;
			}
			
			if (flag === true){
				$.post(
					$(this).attr('action'), 
					$(this).serialize(),
					function(data){
						$content.find('.section-c form').replaceWith('<p class="send-ok">Thank you for getting in touch. We will get back to you on our next business day or sooner.</p>');
					}
				);
			}
		});				

		
		var $stepField = $content.find('#f-scale-step');
		
		var $steps = $content.find('.section-a ul.steps a');
		$steps.click(function(e){
			e.preventDefault();
			$steps.removeClass('active');
			$(this).addClass('active');
			$content.find('.section-b, .section-c').show();
			$content.find('.section-b .step').hide();
			$($(this).hrefId()).show();
			
			$stepField.val($(this).hrefId());
		});
				
		$('body').append($overlay, $lightbox);		
		$content.find('label').compactize();		
				
		$(el).click(function(e){
			e.preventDefault();
			$(document).bind('keydown',keydown);							
			
			var speed = $.browser.msie ? 0 : 'fast';
			$lightbox.add($overlay).fadeIn(speed);			
		});
	};

	$.fn.hrscale = function(){
		var options = arguments;
		return $(this).each(function(){			
			var lb = new HRScale(this,options);
		});
	};		
})(jQuery);

/* 
 * Portfolio lightbox
 */
(function($){
	
	var HRPortfolio = function(el){
		this.current = 0;
				
		this.fetchData('#portfolio');
		
		this.build();

		var self = this;
		$(el).click(function(e){
			e.preventDefault();
			self.open();
		});
	};
	
	HRPortfolio.prototype.fetchData = function(el){
		var items = [];
		$(el).find('.item').each(function(){
			items[items.length] = {
				media : $(this).find('.media').html(),
				description : $(this).find('.description').html()
			};
		});
		this.items = items;
	};
	
	HRPortfolio.prototype.build = function(){
		var self = this;
		this.$overlay = $('<div id="overlay"/>').css('opacity','0.8').hide();
		
		if ($.browser.msie === true && $.browser.version === '6.0'){
			$(window).resize(function(){
				self.$overlay.height($(document).height());				
			}).triggerHandler('resize');
		}
		
		this.$lightbox = $('<div id="lightbox"><div class="wrapper"><div class="nav"><p class="a"/><p class="b"/></div><p class="anniversary"><a href="/about/notables">Notables</a></p></div></div>').hide();
		this.$media = $('<p class="media"/>');
		this.$lightbox.find('.wrapper').append(this.$media);
		this.$description = $('<p class="description"/>');		
		this.$lightbox.find('.wrapper').append(this.$description);		
				
		var $close = $('<a href="#">Close</a>').click(function(e){
			e.preventDefault();
			self.close();
		});								
		this.$lightbox.find('p.b').append($close);		
		
		this.$prev = $('<a href="#" class="prev inactive">Previous</a>').click(function(e){
			e.preventDefault();
			self.activate(self.current - 1);
		});
		
		this.$next = $('<a href="#" class="next">Next</a>').click(function(e){
			e.preventDefault();
			self.activate(self.current + 1);
		});
		
		this.$lightbox.find('p.a').append(this.$prev, this.$next);
		
		this.activate(this.current);
		
		$('body').append(this.$overlay, this.$lightbox);
	};
	
	HRPortfolio.prototype.activate = function(pos){
		var self = this;
		if (pos < 0 || pos >= this.items.length) {
			return;
		}
		this.current = pos;
		
		this.$prev.add(this.$next).removeClass('inactive');		
		if (this.current === 0){
			this.$prev.addClass('inactive');
		}		
		if (this.current === parseInt(this.items.length - 1, 10)){
			this.$next.addClass('inactive');
		}
		
		this.$media.fadeOut('fast',function(){
			$(this).html(self.items[self.current].media);
			$(this).fadeIn('fast');
		});
		
		this.$description.fadeOut('fast',function(){
			$(this).html(self.items[self.current].description);
			$(this).fadeIn('fast');
		});
			
	};

	//close lightbox on ESC press
	HRPortfolio.prototype.keydown = function(e){
		if (e.keyCode === 27 && e.data[0] && e.data[0] instanceof HRPortfolio){
			e.data[0].close();
		}
	};

	HRPortfolio.prototype.open = function(){
		if (this.$lightbox.is(':visible')) {
			return false;
		}										
		$(document).bind('keydown',[this],this.keydown);
		
		var speed = $.browser.msie ? 0 : 'fast';
		this.$lightbox.add(this.$overlay).fadeIn(speed);
	};
						
	HRPortfolio.prototype.close = function(){
		$(document).unbind('keydown',this.keydown);			
				
		var speed = $.browser.msie ? 0 : 'fast';
		this.$lightbox.add(this.$overlay).fadeOut(speed,function(){
			$(this).hide();
		});		
	};
	
	$.fn.hrportfolio = function(){
		var options = arguments;
		return $(this).each(function(){
			var lb = new HRPortfolio(this,options);
		});
	};
	
})(jQuery);

/*
 * Slider
 */
(function($){
	
	var HRSlider = function(el){
		this.$slider = $(el);
		this.$slides = this.$slider.find('.slide');
		this.$wrapper = this.$slider.find('.wrapper');
		this.current = 0;
		this.sliderWidth = this.$slider.width();
		
		//don't do anything if there's only one slide
		if (this.$slides.length < 2) {
			return;
		}
		
		this.$wrapper.css({
			'width' : parseInt(this.sliderWidth * this.$slides.length, 10)
		});
		
		this.build();
		
		this.autorotate();

	};
	
	HRSlider.prototype.autorotate = function(){
		window.clearTimeout(this.timeout);
		this.timeout = window.setTimeout($.proxy(function(){
			var pos = this.current + 1;
			if (pos === this.$slides.length) {
				pos = 0;
			}
			this.slide(pos);
		},this), 10000);		
	};
	
	HRSlider.prototype.click = function(trigger){
		this.slide($(trigger).data('position'));	
	};
	
	HRSlider.prototype.slide = function(pos){
		var speed = Math.abs(pos - this.current) * 300;
		
		this.$wrapper.stop().animate({
			'left' : parseInt(- this.sliderWidth * pos, 10)
		}, speed, 'easeInOutQuad');
		
		this.current = pos;		
		
		//change active state on all triggers
		this.$slider.find('ul.nav a').removeClass('active').eq(pos).addClass('active');
		
		this.autorotate();
	};
			
	HRSlider.prototype.build = function(){
		var 
			$nav = $('<ul class="nav"/>'),
			self = this;
		
		this.$slides.each(function(index, item){
			var 
				$li = $('<li />'),
				$trigger = $('<a href="#'+$(item).attr('id')+'">' + parseInt( index + 1, 10) + '</a>');
			
			$trigger.data('position',index);
			$trigger.click(function(e){
				e.preventDefault();
				self.click(this);
			});
			$nav.append($li.append($trigger));
		});
		
		this.$wrapper.after($nav);			
		$nav.find('a:eq('+this.current+')').triggerHandler('click');		
	};
	
	$.fn.hrslider = function(){
		return $(this).each(function(){
			var sl = new HRSlider(this);
		});
	};		
})(jQuery);

/*
 * Scripts
 *
 */
jQuery(function($) {

	var Engine = {
		utils : {
			links : function(){
				$('a[rel*=external]').click(function(e){
					e.preventDefault();
					window.open($(this).attr('href'));					  
				});
			},
			mails : function(){
				$('a[href^=mailto:]').each(function(){
					var mail = $(this).attr('href').replace('mailto:','');
					var replaced = mail.replace('/at/','@');
					$(this).attr('href','mailto:'+replaced);
					if($(this).text() == mail) {
						$(this).text(replaced);
					}
				});
			}
		},
		enhancements : {
			tweets : function(){
				$(".twitter-a .wrapper").tweet({
					username: "handyrandycom",
					count: 1
				});				
			},
			slideshow : function(){
				$('.slideshow-a').hrslider();
			},
			portfolio : function(){
				$('a.portfolioTrigger').hrportfolio();
			},
			promos : function(src) {
				$(document).hrpromos(src);
			},
			scale : function(){
				$('a.scale-trigger').hrscale();
			}
		}
	};

	Engine.utils.links();
	Engine.utils.mails();
	Engine.enhancements.slideshow();
	Engine.enhancements.portfolio();
	Engine.enhancements.tweets();
	Engine.enhancements.promos('/promo-06.html'); 
	Engine.enhancements.scale();
});
