/*
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);

/*
 * Tiny Scrollbar
 * http://baijs.nl/tinyscrollbar/
 */
(function($){$.tiny=$.tiny||{};$.tiny.scrollbar={options:{axis:'y',wheel:40,scroll:true,size:'auto',sizethumb:'auto'}};$.fn.tinyscrollbar=function(options){var options=$.extend({},$.tiny.scrollbar.options,options);this.each(function(){$(this).data('tsb',new Scrollbar($(this),options));});return this;};$.fn.tinyscrollbar_update=function(sScroll){return $(this).data('tsb').update(sScroll);};function Scrollbar(root,options){var oSelf=this;var oWrapper=root;var oViewport={obj:$('.viewport',root)};var oContent={obj:$('.overview',root)};var oScrollbar={obj:$('.scrollbar',root)};var oTrack={obj:$('.track',oScrollbar.obj)};var oThumb={obj:$('.thumb',oScrollbar.obj)};var sAxis=options.axis=='x',sDirection=sAxis?'left':'top',sSize=sAxis?'Width':'Height';var iScroll,iPosition={start:0,now:0},iMouse={};function initialize(){oSelf.update();setEvents();return oSelf;}
this.update=function(sScroll){oViewport[options.axis]=oViewport.obj[0]['offset'+sSize];oContent[options.axis]=oContent.obj[0]['scroll'+sSize];oContent.ratio=oViewport[options.axis]/oContent[options.axis];oScrollbar.obj.toggleClass('disable',oContent.ratio>=1);oTrack[options.axis]=options.size=='auto'?oViewport[options.axis]:options.size;oThumb[options.axis]=Math.min(oTrack[options.axis],Math.max(0,(options.sizethumb=='auto'?(oTrack[options.axis]*oContent.ratio):options.sizethumb)));oScrollbar.ratio=options.sizethumb=='auto'?(oContent[options.axis]/oTrack[options.axis]):(oContent[options.axis]-oViewport[options.axis])/(oTrack[options.axis]-oThumb[options.axis]);iScroll=(sScroll=='relative'&&oContent.ratio<=1)?Math.min((oContent[options.axis]-oViewport[options.axis]),Math.max(0,iScroll)):0;iScroll=(sScroll=='bottom'&&oContent.ratio<=1)?(oContent[options.axis]-oViewport[options.axis]):isNaN(parseInt(sScroll))?iScroll:parseInt(sScroll);setSize();};function setSize(){oThumb.obj.css(sDirection,iScroll/oScrollbar.ratio);oContent.obj.css(sDirection,-iScroll);iMouse['start']=oThumb.obj.offset()[sDirection];var sCssSize=sSize.toLowerCase();oScrollbar.obj.css(sCssSize,oTrack[options.axis]);oTrack.obj.css(sCssSize,oTrack[options.axis]);oThumb.obj.css(sCssSize,oThumb[options.axis]);};function setEvents(){oThumb.obj.bind('mousedown',start);oThumb.obj[0].ontouchstart=function(oEvent){oEvent.preventDefault();oThumb.obj.unbind('mousedown');start(oEvent.touches[0]);return false;};oTrack.obj.bind('mouseup',drag);if(options.scroll&&this.addEventListener){oWrapper[0].addEventListener('DOMMouseScroll',wheel,false);oWrapper[0].addEventListener('mousewheel',wheel,false);}
else if(options.scroll){oWrapper[0].onmousewheel=wheel;}};function start(oEvent){iMouse.start=sAxis?oEvent.pageX:oEvent.pageY;var oThumbDir=parseInt(oThumb.obj.css(sDirection));iPosition.start=oThumbDir=='auto'?0:oThumbDir;$(document).bind('mousemove',drag);document.ontouchmove=function(oEvent){$(document).unbind('mousemove');drag(oEvent.touches[0]);};$(document).bind('mouseup',end);oThumb.obj.bind('mouseup',end);oThumb.obj[0].ontouchend=document.ontouchend=function(oEvent){$(document).unbind('mouseup');oThumb.obj.unbind('mouseup');end(oEvent.touches[0]);};return false;};function wheel(oEvent){if(!(oContent.ratio>=1)){oEvent=$.event.fix(oEvent||window.event);var iDelta=oEvent.wheelDelta?oEvent.wheelDelta/120:-oEvent.detail/3;iScroll-=iDelta*options.wheel;iScroll=Math.min((oContent[options.axis]-oViewport[options.axis]),Math.max(0,iScroll));oThumb.obj.css(sDirection,iScroll/oScrollbar.ratio);oContent.obj.css(sDirection,-iScroll);oEvent.preventDefault();};};function end(oEvent){$(document).unbind('mousemove',drag);$(document).unbind('mouseup',end);oThumb.obj.unbind('mouseup',end);document.ontouchmove=oThumb.obj[0].ontouchend=document.ontouchend=null;return false;};function drag(oEvent){if(!(oContent.ratio>=1)){iPosition.now=Math.min((oTrack[options.axis]-oThumb[options.axis]),Math.max(0,(iPosition.start+((sAxis?oEvent.pageX:oEvent.pageY)-iMouse.start))));iScroll=iPosition.now*oScrollbar.ratio;oContent.obj.css(sDirection,-iScroll);oThumb.obj.css(sDirection,iPosition.now);}
return false;};return initialize();};})(jQuery);

$(function() {
	
	$.fn.getTwitter = function(username, num_posts, columns) {
		var elem = $(this);
		var is_ul = elem.is('ul');

		if (!columns || !columns.length) { 
			columns = ['content', 'date'];
		}

		$.getJSON('http://twitter.com/statuses/user_timeline/'+username+'.json?count='+num_posts+'&callback=?', function(data) {
			var html = '';

			for (var i=0; i<data.length; i++) {
				if (is_ul) { html += '<li>'; }
				for (var j=0; j<columns.length; j++) {
					switch (columns[j]) {
						case 'content':
							html += '<span class="twitter_content">'+atReplace(urlReplace(data[i].text))+'</span>';
						break;
						case 'date':
							html += '<span class="twitter_date">'+dateFormat(data[i].created_at)+'</span>';
						break;
						case 'followers':
							html += '<span class="twitter_followers">'+dateFormat(data[i].user.followers_count)+'</span>';
						break;
						case 'friends':
							html += '<span class="twitter_friends">'+dateFormat(data[i].user.friends_count)+'</span>';
						break;
						case 'count':
							html += '<span class="twitter_count">'+dateFormat(data[i].user.statuses_count)+'</span>';
						break;
					}
				}
				if (is_ul) { html += '</li>'; }
			}

			elem.html(html);
		});

		function urlReplace(string) {
		  var exp = /(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
		  return string.replace(exp,'<a href="$1" target="_blank">$1</a>'); 
		}
		
		function atReplace(string) {
			var exp = /@([^\s]*)/ig;
			return string.replace(exp,'<a href="http://www.twitter.com/$1" target="_blank">@$1</a>');
		}

		var dateFormat = function(a) {
			var b = new Date();
			var c = new Date(a);
			if ($.browser.msie) {
				c = Date.parse(a.replace(/( \+)/, ' UTC$1'))
			}
			var d = b - c;
			var e = 1000,
				minute = e * 60,
				hour = minute * 60,
				day = hour * 24,
				week = day * 7;
			if (isNaN(d) || d < 0) {
				return ""
			}
			if (d < e * 7) { return "right now" }
			if (d < minute) { return Math.floor(d / e) + " seconds ago" }
			if (d < minute * 2) { return "about 1 minute ago" }
			if (d < hour) { return Math.floor(d / minute) + " minutes ago" }
			if (d < hour * 2) { return "about 1 hour ago" }
			if (d < day) { return Math.floor(d / hour) + " hours ago" }
			if (d > day && d < day * 2) { return "yesterday" }
			if (d < day * 365) { return Math.floor(d / day) + " days ago" } else { return "over a year ago" }
		}
	}
	
	// Input toggle
	$.fn.toggle = function() {
		var $this = $(this);
		
		if (typeof(this[0].value) !== 'undefined' && typeof(this[0].defaultValue) !== 'undefined') {
			$this.live('focus', function() {
				if (this.defaultValue == this.value) {
					this.value = '';
					$this.addClass('active');
				}
			}).live('blur', function() {
				if (this.value == '') {
					this.value = this.defaultValue;
					$this.removeClass('active');
				}
			});
		}
	}
	
	$('input.toggle').toggle();
	
	// Change Page Effect
	function changePage(page) {
		var pages = page.replace(SITE_URL, '').replace(/-/g, '_').split('/');
		var count = $('#'+pages[0]).prevAll().length;
		var margin = 0 - (1040 * count);
		if (margin+'px' != $('#content').css('marginLeft')) {
			$('#content').animate({
				marginLeft: margin+'px'
			}, 800, function() {
				if (pages.length == 2) {
					changeSubPage(pages[0], pages[1]);
				}
			});
		} else {
			if (pages.length == 2) {
				changeSubPage(pages[0], pages[1]);
			}
		}
	}
	
	function changeSubPage(parent, page) {
		if (parent == 'case_studies') {
			var count = $('#case_studies #'+page).prevAll().length;
			var margin = 0 - (312 * count);
			$('#case_studies_nav li a').removeClass('active');
			$('#case_studies_nav li a.'+page).addClass('active');
			$('#case_studies_inner').animate({
				marginTop: margin+'px'
			}, 400, function() {
				
			});
		} else if (parent == 'services') {
			$('#services_nav a.active').removeClass('active');
			$('#services_nav a[data-ref="'+page+'"]').addClass('active');
			var count = $('#services #services_'+page).prevAll().length;
			var margin = 0 - (326 * count);
			$('#services_inner').animate({
				marginTop: margin+'px'
			}, 400, function() {
				
			});
		}
	}
	
	// Add slide effect to links
	$('a').click(function() {
		var $this = $(this);
		var href = $this.attr('href');
		changePage(href);
		if ("pushState" in history) {
			history.pushState({page: href.replace('-', '_')}, href, href);
		} else {
			window.location.hash = 'ie-'+href.replace(SITE_URL, '');
		}
		return false;
	});
	
	if ("pushState" in history) {
		window.onpopstate = function(e) {
			if (e.state) {
				changePage(e.state['page']);
			}
		}
	} else {
		$(window).hashchange(function() {
			changePage(location.hash.replace('#ie-', '').replace('-', '_'));
		});
	}
	
	if (window.location.hash.length) {
		changePage(window.location.hash.replace('#ie-', '').replace('-', '_'));
	}
	
	// Services
	$('.scrollbar_wrapper').tinyscrollbar();
	
	/** //Old 
	
	// Banners
	var $banner  = $('.banner');
	$('.banner').each(function() {
		var gallery = $(this);
		
		setTimeout(function() {
			nextBannerImage(gallery);
		}, 3000);		
	});
	
	
	function nextBannerImage(gallery) {		
		var visible = gallery.children('img:visible');
		var next = visible.next('img');
		if (next.length) {
			visible.fadeOut(600);
			next.fadeIn(600);
		} else {
			visible.fadeOut(600);
			gallery.children('img:first').fadeIn(600);
		}
		setTimeout(function() {
			nextBannerImage(gallery);
		}, 3000);
	}
	
	/**/
	
	var nextBannerImage = function() {	
		$('.banner').each(function() {	
			var gallery = $(this);
			var images = $(this).children('img');
			var current = 0;
			images.each(function(i) {
				if($(this).is(':visible')) {
					current = i;
					return false;
				}
			});		
			var next = current + 1;			
			if (next != images.length) {
				$(images[current]).fadeOut(600);
				$(images[next]).fadeIn(600);
			} else {
				$(images[current]).fadeOut(600);
				$(images[0]).fadeIn(600);
			}
		});
		setTimeout(function() {
			nextBannerImage();
		}, 3000);
	}	
	nextBannerImage();
	
	// Case Study Gallery
	function nextGalleryImage(gallery) {
		var visible = gallery.children('img:visible');
		var next = visible.next('img');
		if (next.length) {
			visible.fadeOut(300);
			next.fadeIn(300);
		} else {
			visible.fadeOut(300);
			gallery.children('img:first').fadeIn(300);
		}
		
		var active = gallery.children('.icons').children('li.active');
		var next = active.next();
		active.removeClass('active');
		if (next.length) {
			next.addClass('active');
		} else {
			gallery.children('.icons').children('li:first').addClass('active');
		}
	}
	
	function prevGalleryImage(gallery) {
		var visible = gallery.children('img:visible');
		var prev = visible.prev('img');
		if (prev.length) {
			visible.fadeOut(300);
			prev.fadeIn(300);
		} else {
			visible.fadeOut(300);
			gallery.children('img:last').fadeIn(300);
		}
		
		var active = gallery.children('.icons').children('li.active');
		var prev = active.prev();
		active.removeClass('active');
		if (prev.length) {
			prev.addClass('active');
		} else {
			gallery.children('.icons').children('li:last').addClass('active');
		}
	}
	
	$('.gallery img, .gallery .next').click(function() {
		nextGalleryImage($(this).parent('.gallery'));
	});
	
	$('.gallery .prev').click(function() {
		prevGalleryImage($(this).parent('.gallery'));
	});
	
	$('#contact_us .twitter').getTwitter('ATandCLoewe', 1);
	
});
