/* global nav hover
/*-------------------------------------------------------------------------------*/

$(document).ready(function() {
	$('a#gnavWork').hover(function() { //mouse in
		$('a#gnavWork span').animate({ paddingTop: '11px' }, 300);
	}, function() { //mouse out
		$('a#gnavWork span').animate({ paddingTop: 0 }, 200);
	});
	
	$('a#gnavAgency').hover(function() { //mouse in
		$('a#gnavAgency span').animate({ paddingTop: '11px' }, 300);
	}, function() { //mouse out
		$('a#gnavAgency span').animate({ paddingTop: 0 }, 200);
	});
	
	$('a#gnavContact').hover(function() { //mouse in
		$('a#gnavContact span').animate({ paddingTop: '11px' }, 300);
	}, function() { //mouse out
		$('a#gnavContact span').animate({ paddingTop: 0 }, 200);
	});
	
	$('a#gnavBlog').hover(function() { //mouse in
		$('a#gnavBlog span').animate({ paddingTop: '11px' }, 300);
	}, function() { //mouse out
		$('a#gnavBlog span').animate({ paddingTop: 0 }, 200);
	});
});


/* image grayscale
/*-------------------------------------------------------------------------------*/

function initDesaturatedImage(imgObj){
	if ($.browser.msie){
		imgObj.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayScale=1)';
		$(imgObj).parent().hover(function(){
			if ($(this).get(0).tagName.toLowerCase() == "a")
				imgObj.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayScale=0)';
		}, function(){
			imgObj.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayScale=1)';
		});
	}else{
		var canvas = document.createElement('canvas');

		var canvasContext = canvas.getContext('2d');

		var imgW = imgObj.width;

		var imgH = imgObj.height;
		canvas.width = imgW;
		canvas.height = imgH;
		canvasContext.drawImage(imgObj, 0, 0);

		try{
		var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);

		for(var y = 0; y < imgPixels.height; y++){
		     for(var x = 0; x < imgPixels.width; x++){
		          var i = (y * 4) * imgPixels.width + x * 4;
		          var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
		          imgPixels.data[i] = avg;
		          imgPixels.data[i + 1] = avg;
		          imgPixels.data[i + 2] = avg;
		     }
		}
		canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);

		$(canvas).insertAfter($(imgObj));
		$(imgObj).hide();
		$(canvas).show();
		$(imgObj).parent().hover(function(){
			if ($(this).get(0).tagName.toLowerCase() == "a"){
				$(imgObj).show();
				$(canvas).hide();
			}
		}, function(){
			$(canvas).show();
			$(imgObj).hide();
		});
		}catch(e){
			//console.log('Error with desaturating:', e);
		}
	};
};


/* jQuery accordian
/*-------------------------------------------------------------------------------*/

function initMenu(options) {
	$('ul.menu div').hide();
	$.each($('ul.menu'), function(){
		$('#' + this.id + '.expandfirst div:first').show();
		if (options.onExpand && $('#' + this.id + '.expandfirst div:first').length > 0)
			options.onExpand($('#' + this.id + '.expandfirst div:first').siblings('a'));
	});
	$('ul.menu li.expand div').show();
	var currentOpen;
	$('ul.menu li a').click(
		function() {
			var checkElement = $(this).next();
			var parent = this.parentNode.parentNode.id;
			if((checkElement.is('div')) && (checkElement.is(':visible'))) {
				if($('#' + parent).hasClass('collapsible')) {
					if (currentOpen && options.onCollapse) options.onCollapse(currentOpen.prev('a'), currentOpen);
					if (currentOpen && options.onAllCollapse) options.onAllCollapse(currentOpen.prev('a'), currentOpen);
					$('#' + parent + ' div.menuItem:visible').slideUp('fast');
					currentOpen = null;
				}
				return false;
			}
			if((checkElement.is('div')) && (!checkElement.is(':visible'))) {
				if (currentOpen && options.onCollapse) options.onCollapse(currentOpen.prev('a'), currentOpen);
				if (options.onExpand) options.onExpand($(this), checkElement);
				checkElement.slideDown('fast', function(){
				var called = false;
				$('#' + parent + ' div.menuItem:visible').each(function(){
					if ($(checkElement).get(0) != $(this).get(0)){
						called = true;
						if (options.onExpandComplete){
							$(this).slideUp('fast', function(){
								options.onExpandComplete($(checkElement).parent());
							});
						}else{
							$(this).slideUp('fast');
						}
					}
				});
				if (!called && options.onExpandComplete)
					options.onExpandComplete($(checkElement).parent());
				});
				currentOpen = checkElement;
				return false;
			}
		}
	);
}
       
function resizeProjectRollover(emElement) {
	var img = $(emElement).parent().find('a img')[0];
	var w = $(img).width() - 37; // this seems to be the magic padding
	//console.log("setting em to width: " + w);
	$(emElement).css('width', w);	
} 


/* jQuery project image hover
/*-------------------------------------------------------------------------------*/
$(document).ready(function(){
	//$('div.projectRow > div > span > em').each(function(index, em) {
		//resizeProjectRollover(em);
	//});
	
	$('div.projectRow img').each(function(index, el) {
		var src = $(el).attr('src');
		src = src.replace('http://www.thinkinc.com', '');
		$(el).attr('src', src);
	});
	$('div.projectRow span').hover(
		function(){                  
			var em = $(this).find('em');    
			
			resizeProjectRollover(em);
			
			$(em).slideDown('fast');
		},
		function(){
			$(this).find('em').slideUp('fast');
		}
	);       
	$('input[placeholder],textarea[placeholder]').placeholder();
});


/* jQuery project image get details
/*-------------------------------------------------------------------------------*/ 
var animSpeed = 200;
$(document).ready(function(){
	$('div.projectRow a').click(function(){
		transReady = false;
		var href = $(this).attr('href');
		$('div#mover').animate(
			{
				'margin-left':'-670px'
			}, 
			{
				duration: animSpeed, 
		        easing: 'swing',
				complete : function(){
					if (transReady) showDetail();
					transReady = true;
				}
			}
		);
		$.ajax({
			url : href + "?ajax=true",
			success : function(data){
				$('div.detailHolder').html(data);
				if (transReady) showDetail();
				transReady = true;
			}
		});
		return false;
	});
	if (getUrlVars().d != null){
		$('div.projectRow a[data-slug=' + getUrlVars().d + ']').click();
	}
});
function hideDetail(){
	$(this).unbind('click', hideDetail);
	$(this).animate(
		{
			'margin-left':'-670px'
		}, 
		{
			duration: animSpeed, 
	        easing: 'swing',
			complete : function(){
				//$(this).html('');
				$('div#mover').show().animate(
					{
						'margin-left':'0px'
					}, 
					{
						duration: animSpeed, 
				        easing: 'swing',
						complete: function(){
							$('div.detailHolder').html('');
						}
					}
				);
				$('div#detailContent').fadeOut(function(){
					$(this).html('');
				});
			}
		}
	);
}
function showDetail(){
	$('div#mover').hide();
	$('div.detailHolder').animate(
		{
			'margin-left':'0px'
		}, 
		{
			duration: animSpeed, 
	        easing: 'swing',
			complete : function(){
				$('div.detailHolder').bind('click', hideDetail);
			}
		}
	);
	$('div.#detailContent').html($('div.detailHolder').find('.projectSummary'));
	$('div.#detailContent').fadeIn();
}


/* jQuery ajax expand featured
/*-------------------------------------------------------------------------------*/

$(document).ready(function() {
	if ($('body.home').length > 0){
		initMenu({
			onExpand : function(opener, element){
				//$('#feedToggle').trigger('click', [true]);
				$('ul.menu li a.featuredTab').each(function(){
					if ($(this).get(0) == $(opener).get(0)){
						$(this).animate({opacity: 1}, 200, function(){
							//$(this).addClass($(this).data('origClass'));
						});
					}else{
						//if ($(this).attr('class') != "")
							//$(this).data('origClass', $(this).attr('class'));
						//$(this).removeClass();
						$(this).animate({opacity: .2/*, backgroundColor: '#6F7375'*/});
					}
				});
				opener.addClass('opened');
				opener.children().last().rotate({animateTo: 45});
				if (opener.siblings('div.homeFeatured').children().length > 0) return false;
				var href = opener.attr('href');
				$.ajax({
					url : href + '?ajax=true',
					context : element,
					success : function(data){
						$(this).html(data);
						setupSlider($(this));
					}
				});
			},
			onExpandComplete : function(current){
				//console.log($(current));
				if ($.browser.msie)
					$('html').animate({'scrollTop': $(current).offset().top}, 1000);
				else
					$('body').animate({'scrollTop': $(current).offset().top}, 1000);
				//$('body').scrollTop($(this).parent().offset().top);
			},
			onCollapse : function(opener, element){
				opener.children().last().rotate({animateTo: 0});
				opener.removeClass('opened');
			},
			onAllCollapse : function(opener, element){
				$('ul.menu li a.featuredTab').each(function(){
					//$(this).addClass($(this).data('origClass'));
					$(this).animate({opacity: 1}, 1000);
				});
			}
		});
		
		$('a.featuredTab').mouseover(function(idx){
			if ($(this).siblings('div.homeFeatured').children().length > 0) return false;
			var href = $(this).attr('href');
			var element = $(this).siblings('div.homeFeatured');
			$.ajax({
				url : href + '?ajax=true',
				context : element,
				success : function(data){
					$(this).html(data);
					setupSlider($(this));
				}
			});
		});
		$('a.featuredTab').each(function(){
			if ($(this).siblings('div.homeFeatured').children().length > 0){
				$(this).children().last().rotate({animateTo: 45});
				setupSlider($(this).siblings('div.homeFeatured'));
			}
		})
	}else if ($('body.single-agency').length > 0){
		initMenu({
			onCollapse : function(opener, element){
				opener.parent().removeClass('selected');
				opener.children().first().rotate({animateTo: 0});
			},
			onExpand : function(opener, element){
				opener.parent().addClass('selected');
				opener.children().first().rotate({animateTo: 45});
			}
		});
    //loadMediaAssets();
	}
});

function loadMediaAssets() {
  $('p[data-type]').each(function(index, el) {
    //if (index > 3) { continue; };      
                                               
		var mediaList = $('<ul class="media"/>');
    var mediaType = $(this).attr('data-type');  
		var searchType = $(this).attr('data-search');
    var terms = $(el).text();
    var termsArray =  terms.split(",");
		var count = termsArray.length
    for (var i = 0; i < count; i++) {          
			var searchTerm = termsArray[i].replace(/^\s+|\s+$/g,"");
      fetchMediaAsset(searchTerm, searchType, mediaType, mediaList); 
    };    
		$(this).after(mediaList);
  });

}
            
function q(str) { return str.replace('\'', ' ').replace('"', ' '); }
function fetchMediaAsset(term, searchType, mediaType, appendToElement) {
  var wsURL = '/wp-content/themes/THINK/medialookup.php?type=' + searchType + '&search=' + searchType + '&term=' + escape(term);

	$.getJSON(wsURL, function(data) {
		//console.log('got data!');     
		if (searchType == 'movie')
			console.log(data.results);                  
		                           
		var li = $('<li/>');
                          
		var title = term;
		if (data.results == null || data.resultCount == 0 || data.results[0] == null) { 
			console.log(data);
			$(li).append('<img src="/wp-content/themes/THINK/img/no-' + mediaType + '-icon.png" alt="' + title + '"/>');
		} else {

			var href = data.results[0].artistViewUrl;
			var thumb = data.results[0].artworkUrl60;
			title = q(data.results[0].artistName);
			if (data.results[0].trackName) { 
				title += ": " + q(data.results[0].trackName); 
			} else if (data.results[0].collectionName) {
				title += ": " + q(data.results[0].collectionName); 
			}
			$(li).append("<a target='_blank' title='" + title + "' href='" + href  + "'><img width='60' alt='" + title + "' src='" + thumb  + "'/></a>");
		}               
		$(appendToElement).append(li);
	
		return data;
	});
}

function updateFeedDots(count) {
  var sel = $('#feedDots > span');
  var total = sel.size();
  sel.removeClass('on').addClass('off');
  limit = total - count;
  sel.each(function(index, el) {
    //console.log(index); console.log(el);
    if (index >= limit) { 
      $(el).removeClass('off').addClass('on');
    }
  });
  updateFeedBar();
}

var barHeight;
var pages;
function updateFeedBar(first){
	$('#mashup ul.main').show();
	$('#mashup ul.page').remove();
	var wh = $(window).height();
	var allowed_height = wh - barHeight - $('#mashup div.pager:not(.bottom)').outerHeight(true) - $('#mashup div.pager.bottom').outerHeight(true);
	$("#mashup #interior").height(allowed_height);
	var pageNum = 0;
	var height_checker = allowed_height/* - $('#mashup div.pager').outerHeight(true)*/;
	pages = [];
	$('#mashup #interior ul.main li:not(.hidden)').each(function(idx) {
		//$(this).show().css('opacity', 1);
		if (pages[pageNum] == null) pages[pageNum] = [];
		height_checker -= ($(this).outerHeight());
		//check to see if we can display it
		if (height_checker <= 0){
			height_checker = allowed_height;
			height_checker -= ($(this).outerHeight());
			//start the next page
			pageNum ++;
			if (pages[pageNum] == null) pages[pageNum] = [];
			pages[pageNum].push($(this));
			first ? $(this).hide() : $(this).fadeOut('fast');
		}else if (pageNum == 0){
			pages[pageNum].push($(this));
			$(this).fadeIn();
		}else{
			pages[pageNum].push($(this));
			first ? $(this).hide() : $(this).fadeOut('fast');
		}
	});
	//if (pageNum > 0) 
	build_pager();
	//else{
	//	$('#mashup div.pager').animate({'opacity': 0}, function(){ $(this).html('&nbsp;')});
		//$('#mashup div.pager').fadeOut();
	//}
}

function build_pager(){
	var inter = $('#mashup #interior');
	var content = $("<ul class='pageList'></ul>");
	//$('#mashup div.pager').slideDown();
	$('#mashup div.pager').animate({'opacity': 1});
	$(pages).each(function(idx, page){
		content.append('<li class="' + (idx == 0 ? 'active' : '') + ' page' + (idx+1) + '"><a href="page' + (idx+1) + '">' + (idx+1) + '</a></li>');
		var page_content = $("<ul class='page' id='page" + (idx+1) + "'></ul>");
		$(page).each(function(j, item){
			var newItem = item.clone();
			page_content.append(newItem);
		});
		inter.append(page_content);
//		page_content.insertBefore($('#mashup div.pager').last());
	});
	$('#mashup div.pager').children().remove();
	content.prepend('<li class="movers"><a class="prev inactive">prev</a></li>');
	content.append('<li class="movers"><a class="next ' + (pages.length == 1 ? 'inactive' : '') + '">next</a></li>');
	$('#mashup div.pager').html(content);
	//$('#mashup div.pager').last().css('position', 'absolute').css('bottom', 2);
	if (pages.length > 12){
		for(i = 13; i <= pages.length; i++){
			//this hides the extra pages
			$('.page' + i).hide();
		}
	}
}

$(document).ready(function() {
	$('#mashup div.pager a').live('click', function(e){
		var a = $(this);
		if (a.hasClass('inactive')) return false;
		
		//get the parent of the currect active element
		var p = $('#mashup div.pager li.active');
		if ($(this).hasClass('next')){
			p = p.next();
			a = p.children('a');
		}else if ($(this).hasClass('prev')){
			p = p.prev();
			a = p.children('a');
		}else{
			//get the parent of the clicked element
			p = a.parent();
		}
		if (p.index() == 1){
			$('#mashup div.pager a.prev').addClass('inactive');
			$('#mashup div.pager a.next').removeClass('inactive');
		}else if (p.index() >= $('#mashup div.pager a.next').parent().index() - 1){
			$('#mashup div.pager a.next').addClass('inactive');
			$('#mashup div.pager a.prev').removeClass('inactive');
		}else{
			$('#mashup div.pager a.prev').removeClass('inactive');
			$('#mashup div.pager a.next').removeClass('inactive');
		}
		if (!$(p).first().is(":visible")){
			var obj = $(this);
			$(p).each(function(){
				var pObj = $(this);
				//console.log($(this).siblings(':visible:not(.movers)'));
				if (obj.hasClass('next')){
					$(this).siblings(':visible:not(.movers)').first().hide();//.fadeOut('fast', function(){pObj.fadeIn();});
					pObj.show();
				}
				else if (obj.hasClass('prev')){
					$(this).siblings(':visible:not(.movers)').last().hide();//.fadeOut('fast', function(){pObj.fadeIn();});
					pObj.show();
				}
			});
			
				
		}
		$('#mashup div.pager li').removeClass('active');
		$('#mashup ul.main, #mashup ul.page').css('position', 'absolute').hide().css('position', 'static');//.fadeOut('medium', function(){$(this).css('position', 'static')})
		$('#mashup div.pager li:nth-child(' + (p.index() + 1) + ')').addClass('active');
		$('#' + a.attr('href')).css('position', 'static').show().children().show();
		return false;
	});
	barHeight = 61;
	//
	$(window).resize(function(){
		updateFeedBar();
	});

  updateFeedDots($('#mashup .main li').length); // default

  $('#controlBar li a').click(function() {
  	var feedData = $('div#mashup');
	var isOpen = feedData.css('margin-left') == '0px';
	if (!isOpen)
	  	$('#controlBar a#feedToggle').click();
    var filterVal = $(this).attr('data-type');
    $('#controlBar li').removeClass('active');
    $(this).parent().addClass('active');

    var typeCount = 0;
    $('#mashup .main li').each(function() {
      //console.log('checking if ' + $(this) + ' has filter: ' + filterVal);
      if ($(this).hasClass(filterVal) || filterVal == 'all') {
          $(this).removeClass('hidden'); 
			typeCount++;
      } else {
        //console.log('no');
        $(this).fadeOut('slow').addClass('hidden'); 
      }
    });
    updateFeedDots(typeCount);
  });
	setTimeout('updateFeedBar(true)', 100);
});


/*  just for the confetti ---
	there are way to many document readys!
	someone needs to optimize this messy code
/*-------------------------------------------------------------------------------*/
$(function(){
	if(Modernizr.canvas) {
		// pass in canvas id
		THINKINC.Confetti.init('#confetti', 'div#mashup');
		
	}
});

/* jQuery feed toggle
/*-------------------------------------------------------------------------------*/

/* notes

 Need to add in functions move push and pull confetti
 Change css to start confetti pushed out?
 
 div#mashup = feed container
 
*/
var feedCanAnimate = true;

$(document).ready(function () {
    if ($('a#feedToggle').length > 0) {
        $('#controlBar a#feedToggle').click(function (event, shouldStayClosed) {

            if (feedCanAnimate) {

                feedCanAnimate = false;

                var feedData = $('div#mashup');
                var self = $(this);
                var isOpen = feedData.css('margin-left') == '0px';
                var w = !isOpen ? 0 : $(this).closest('aside').outerWidth();
                if (!isOpen && shouldStayClosed) {
                    return false;
                } else {
                    feedData.show();
                }
                /**
                 * Feed open
                 */
                !isOpen ? $(this).children().last().rotate({
                    animateTo: 0
                }) : $(this).children().last().rotate({
                    animateTo: 45
                });

                // Confetti shit
                feedData.trigger('feedBarAnimate', isOpen);

                feedData.animate({
                    'margin-left': w
                }, 500, function () {
                    if (isOpen) {
                        $(this).hide();
                    } else {
                        //$(this).hide();
                    }
                    //if it was open now it should be closed so set the cookie
                    $.cookie('feedToggle', !isOpen ? null : true, {
                        path: '/'
                    });

                    feedCanAnimate = true;
                });
                return false;

            }
        });
        //if ($.cookie('feedToggle'))
        //$('#controlBar a#feedToggle').click();
        $(window).resize(function () {
            var feedData = $('div#mashup');
            if (feedData.css('margin-left') != '0px') {
                feedData.css('margin-left', feedData.closest('aside').outerWidth());
            }
        });
        if ($('div#mashup.closed').length > 0) {
            $('#controlBar a#feedToggle').children().last().rotate(45);
        }
    }
});

/* jQuery featured scroller
/*-------------------------------------------------------------------------------*/
$(function(){
	if ($('body.single-featured').length > 0){
		setupSlider($('.homeFeatured'));
	}
});


function setupSlider(parent){
	var w = 0;
	var t = parent.children('ul.featuredContentData');
	var s = parent.children('div.scroller');
	var b = s.children('ul.scrollBar');
	var h = s.children('div.scrollHandle');
	//set the width of the parent container
	t.children().each(function(){
		w += $(this).outerWidth();
	});
	t.css('width', w);
	var next = b.find('.featured-next');
	var prev = b.find('.featured-prev');
	if (parent.parent().index() == 0){
		prev.addClass('inactiveButton');
	}
	prev.data('canClick', false);
	
	s.find('ul.scrollBar li:not(".featured-prev, .featured-next")').click(function(){
		s.find('li.featured-prev').data('canClick', null);
		s.find('li.featured-next').data('canClick', null);
		var i = $(this).index() - 1; //need to account for the previous button
		var move = 0;
		var moveHandle = 0;
		moveHandle += 2*i; //to account for the margin on the left and right of the items in the scroll bar
		t.children().each(function(index, element){
			if (i > index){
				move += $(element).outerWidth();
				var temp = b.find(':nth-child(' + (index + 2) + ')');
				moveHandle += temp.outerWidth();
				
			}else{
				return false;
			}
		});
		t.animate({'margin-left' : -move}, 500);
		h.animate({'left' : moveHandle}, 500);
		if (parent.parent().index() == 0){
			i > 0 ?  prev.removeClass('inactiveButton') : prev.addClass('inactiveButton');
		}else if (parent.parent().index() == parent.parent().siblings().length){
			i < $(this).siblings().length - 2 ? next.removeClass('inactiveButton') : next.addClass('inactiveButton');
		}
		if (i == 0){
			s.find('li.featured-prev').data('canClick', false);
		}else if (i == $(this).siblings().length - 2){
			s.find('li.featured-next').data('canClick', false);
		}
	});
	s.find('li.featured-prev, li.featured-next').click(function(){
		if ($(this).data('canClick') == false){
			var p = $(this).parents('div.homeFeatured').parent();
			if ($(this).hasClass('featured-next')){
				//goto next cases study
				
				if (p.next().children('a').length == 0){
					p.parent().children().first().children('a').click();
				}else{
					p.next().children('a').click();
				}
			}else{
				//goto prev case study
				p.prev().children('a').click();
			}
			return false;
		}
		var current = parseInt(t.css('margin-left').replace('px', '')) * -1;
		var moveTo = 0;
		var isNext = $(this).hasClass('featured-next');
		//go through each child and see how far we are to get the current index
		t.children().each(function(index, element){
			current -= $(element).outerWidth();
			if (current < 0){
				if (isNext && index < t.children().length){//this goes to the next item
					moveTo = 2;
				}else if (!isNext && $(element).outerWidth() == -current){ //this is for when the user is exactly at one item
					moveTo = 0;
				}else if (!isNext && index > 0){ //this is for when the user is slightly off an item
					moveTo = 1;
				}
				if (moveTo >= 0){
					b.find(':nth-child(' + (index + 1 + moveTo) + ')').click();
					s.find('li.featured-next').removeClass('inactiveButton');
					s.find('li.featured-prev').removeClass('inactiveButton');
					if ((index + 1 + moveTo) == 2){
						s.find('li.featured-prev').data('canClick', false);
						if (parent.parent().index() == 0){
							s.find('li.featured-prev').addClass('inactiveButton');
						}
					}else if ((index + 1 + moveTo) == b.children().length - 1){
						s.find('li.featured-next').data('canClick', false);
						if (parent.parent().index() == parent.parent().siblings().length){
							s.find('li.featured-next').addClass('inactiveButton');
						}
					}else{
						s.find('li.featured-prev').data('canClick', null);
						s.find('li.featured-next').data('canClick', null);
					}
				}
				return false;
			}
		});
	});
	h.draggable({
		axis:	'x',
		opacity: .75,
		containment : 'parent',
		drag : function(event, ui){
			var sp = parseInt(prev.css('margin-left').replace('px', '')) + parseInt(prev.css('margin-right').replace('px', ''));
			var sn = parseInt(next.css('margin-left').replace('px', '')) + parseInt(next.css('margin-right').replace('px', ''));
			var r = (t.outerWidth()/* - s.outerWidth()*/) / ((s.outerWidth() - next.outerWidth() - prev.outerWidth() - sp - sn - 10));//the extra 10 is to account for the margin on the left and right of the items in the scroll bar
			t.css('margin-left', -ui.position.left*r);
		}
	});
	$('.introSteps a').click(function(){
		var i = parseInt($(this).attr('href')) + 2;
		b.find(':nth-child(' + i + ')').click();
		return false;
	});
}


/* jQuery agency mouseover
/*-------------------------------------------------------------------------------*/
// Custom sorting plugin
(function($) {
  $.fn.sorted = function(customOptions) {
    var options = {
      reversed: false,
      by: function(a) { return a.text(); }
    };
    $.extend(options, customOptions);
    $data = $(this);
    arr = $data.get();
    arr.sort(function(a, b) {
      var valA = options.by($(a));
      var valB = options.by($(b));
      if (options.reversed) {
        return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;				
      } else {		
        return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;	
      }
    });
    return $(arr);
  };
})(jQuery);

// DOMContentLoaded
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
$(function() {
	
	// TODO: chain with quicksand
	/*$('.post-type-archive-work #filter a.tag').click(function() {
		//$('.description h3').text($(this).text());
		//$('.description p').text($(this).attr('data-description'));		
	});*/
	
	$filterMe = $('#people, #work');
	//get the tags
	var $filterType = $('body.post-type-archive #filter a.tag');
	// clone elements to filter
	var $data = $filterMe.clone();
	var $filteredData = $([]);
	// bind the tags to click for quicksand
	$filterType.click(function(){
		$filterType.not($(this)).removeClass('selected');
		$(this).toggleClass('selected');
		var tags = $filterType.not(function(){return !$(this).hasClass('selected')}).map(function(n,i){return 'li.' + $(i).attr('data-type')});
		if (tags.length > 0)
				$filteredData = $data.find(tags.toArray().join());
		else
			$filteredData = $data.find('li');

	      var $sortedData = $filteredData.sorted({
	        by: function(v) {
	          return $(v).find('span[data-type=name]').text().toLowerCase();
	        }
	      });

	    // finally, call quicksand
	    $filterMe.quicksand($sortedData, 
			{
				duration: 500,
	      		easing: 'easeInOutQuad'
	    	},
			function(){
				setupHover();
			}
		);
		//ios remove highlight
		$('body').focus();
		return false;
 	});
	if (getUrlVars().t != null){
		$filterType.each(function(){
			if ($(this).attr('data-type') == getUrlVars().t){
				$(this).click();
			}
		})
	}
	var setupHover = function(){
		$('#people li a').mousemove(function(){
			$(this).parent().prev().css('z-index', 0);
			$(this).parent().next().css('z-index', 0);
			$(this).parent().css('z-index', 1);
		});
		$('.userInfo').mouseenter(function(){
			$(this).stop().animate({opacity:1,left: 0}, 100, function(){
				$(this).css('visibility', 'hidden');
			});
			$(this).parent().prev().css('z-index', 1);
			$(this).parent().next().css('z-index', 1);
		});
		$('#people li a').hover(
			function(event){
				var e = jQuery.Event('showOnlyColor');
				myColor = $(this).parent().children('.userInfo').attr('class').replace('userInfo ', '');
				if (canvas)
					$(canvas).trigger(e, [myColor, false]);
				var i = 1;
				var d = $(this).outerWidth();
				if (($(this).parent().index() + 1)%6 == 0){
					i = -1;
					$(this).parent().children('.userInfo').css('margin-left', '-12px');
				}
					
				$(this).parent().prev().css('z-index', 0);
				$(this).parent().next().css('z-index', 0);
				$(this).parent().children('.userInfo').css('visibility', 'visible').show().stop().animate({opacity:1,left: i*d + 0}, 250);
			},
			function(event){
				var e = jQuery.Event('resetShow');
				if (canvas)
					$(canvas).trigger(e);
				$(this).parent().children('.userInfo').stop().animate({opacity:1,left: 0}, 100, function(){
					$(this).css('visibility', 'hidden');
					$(this).parent().prev().css('z-index', 1);
					$(this).parent().next().css('z-index', 1);
				});
			}
		);
	};

	setupHover();
});


/* jQuery dots
/*-------------------------------------------------------------------------------*/

var ctx;
var canvas;
var dots = [];
$(function(){
	canvas = $('#mainCanvas')[0];
	if (Modernizr.canvas && canvas) {
		//G_vmlCanvasManager.initElement(canvas);
		ctx = canvas.getContext("2d");
		ctx.globalAlpha = .3;
		if (ctx != null){
			canvas.height = $(window).height() - 75;
			$(window).resize(function(){
				canvas.height = $(this).height() - 75;
			});
			$('nav a, a.featuredTab').mouseover(function(){
				var e = jQuery.Event('showOnlyColor');
				var myColor;
				if ($(this).closest('nav').length > 0){
					needsConvert = true;
					myColor = $(this).css('border-top-color');
				}else{
					needsConvert = false;
					myColor = $(this).parent().attr('class').replace('Tab', '');
				}
				$(canvas).trigger(e, [myColor, needsConvert]);
			});
			$('nav a, a.featuredTab').mouseout(function(){
				var e = jQuery.Event('resetShow');
				$(canvas).trigger(e);
			});
	
			$(canvas).bind('showOnlyColor', null, showOnlyColor);
			$(canvas).bind('resetShow', null, showOnlyColor);
			createDots();
			redraw();
			setInterval("moveAndRedraw()", 33);
		}
	}
});

function showOnlyColor(event, color, needsConvert){
	var hexString;
	if (needsConvert){
		var rgbString = color; // get this in whatever way.
		if (rgbString != null){
			var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
			delete (parts[0]);
			for (var i = 1; i <= 3; ++i) {
			    parts[i] = parseInt(parts[i]).toString(16);
			    if (parts[i].length == 1) parts[i] = '0' + parts[i];
			}
			hexString = parts.join('');
		}
	}else{
		hexString = colorsHash[color];
	}
	for (i=0; i < dots.length; i++){
		if (event.type != 'resetShow' && dots[i].color != hexString){
			dots[i].setExtraColor(hexString);
		}else{
			dots[i].setExtraColor(null);
		}
		
	}
}

function moveAndRedraw(){
	moveDots();
	redraw();
}

function moveDots(){
	var dot;
	for (i=0; i < dots.length; i++){
		dot = dots[i];
		$(['x', 'y']).each(function(){
			var factor = 1;
			if (randomFromTo(0,100) %2 == 0){
				//move in the negative direction
				factor *= -1;
			}else{
				//move in the positive direction
				factor *= 1;
			}
			var maxWidth = $(canvas).width()-5;
			var feedData = $('div#mashup');
			var isOpen = feedData.css('margin-left') == '0px';
			if (isOpen){
				maxWidth = $(canvas).width() - 15 - feedData.outerWidth();
			}
			//var val = (this == 'x') ? dot['vX'] : dot['vY'];//randomFromTo(0, 100);
			var val = .1;
			var newVal = dot[this] + (val * factor);
			if (newVal < 5){
				dot[this] = 5;
			}else if ((this == 'x' && newVal > maxWidth) || (this == 'y' && newVal > $(canvas).height()-5)){
				dot[this] = (this == 'x') ? maxWidth : $(canvas).height()-5;
			}else{
				dot[this] = newVal;
			}
		})
	}
}

function redraw(){
	//ctx.globalCompositeOperation = "source-over";
	//ctx.fillStyle = "rgba(255,255,255,.1)";
	//ctx.fillRect( 0 , 0 , $(canvas).width() , $(canvas).height() );
	//ctx.globalCompositeOperation = "lighter";
	ctx.clearRect ( 0 , 0 , $(canvas).width() , $(canvas).height() );
	var dot;
	
	for (i=0; i < dots.length; i++){
		ctx.save();
		dot = dots[i];
		ctx.drawImage(dot.getCanvas(), dot.x, dot.y);
		ctx.restore();
	}
	
}

function createDots(){
	var dot;
	for (i=0; i < 50; i++){
		dot = new Dot();
		dot.x = randX();
		dot.y = randY();
		dot.vX = randomFromTo(1,2);
		dot.vY = randomFromTo(1,2);
		dot.color = randColor();
		dot.size = randRadius();
		dot.setCanvasSize();
		dots[i] = dot;
	}
}

var colors = ["6f7375", "0064a6", "db2d25", "f9d443"];
var colorsHash = {
	"gray":"6f7375", 
	"blue":"0064a6", 
	"red":"db2d25", 
	"yellow":"f9d443"
}
function randColor(){
	return colors[Math.floor(Math.random()*colors.length)];
}

function randRadius(){
	return randomFromTo(2, 5);
}

function randX(){
	return randomFromTo(5, $(canvas).width() - 5);
	//return randomFromTo(0, 2);
}
	
function randY(){
	return randomFromTo(5, $(canvas).height() - 5);
	//return randomFromTo(0, 2);
}

function randomFromTo(from, to){
	return Math.floor(Math.random() * (to - from + 1) + from);
}

function Dot(){
	this.color = "rgb(" + Math.floor( Math.random()*255 ) + "," + Math.floor( Math.random()*255 ) + "," + Math.floor( Math.random()*255 ) + ")";
	this.y     = 0;
	this.x     = 0;
	this.vX    = 0;
	this.vY    = 0;
	this.size  = 1;
	this.extraColor = null;
	this.isVisible = true;
	this.canvas = document.createElement('canvas');
	//G_vmlCanvasManager.initElement(this.canvas);
	this.canvas.width = this.canvas.height = 100;
	this.context = this.canvas.getContext('2d');
	this.context.save();
	
	this.setCanvasSize = function(){
		this.canvas.width = this.canvas.height = this.size * this.size * Math.PI;
		this.redraw();
	}
	this.setExtraColor = function(c){
		this.extraColor = c;
		this.redraw();
	}
	this.getCanvas = function() {
		return this.canvas;
	}
	this.redraw = function() {
		var size = this.size * this.size * Math.PI;
		var startX = startY = size / 2;
		this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
		this.context.beginPath();
		if (this.extraColor != null)
			this.context.fillStyle = this.extraColor;
		else
			this.context.fillStyle = this.color;
		this.context.arc(startX, startY, this.size, 0, Math.PI*2, true); 
		this.context.closePath();
		this.context.fill();
	};
	
}

if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPad/i)) {
	$(document).ready(function () {
		$('label[for]').click(function () {
			var el = $(this).attr('for');
			if ($('#' + el + '[type=radio], #' + el + '[type=checkbox]').attr('selected', !$('#' + el).attr('selected'))) {
				return;
			} else {
				$('#' + el)[0].focus();
			}
		});
	});
}

if (typeof(window["console"]) == "undefined") {
	console = {
		log : function(msg){
			if ($('link[rel="pingback"]').attr('href').indexOf('thinkinc.com') < 0 || document.URL.indexOf('showConsole=true') >= 0){
				if ($('.consoleArea').length == 0)
					$('body').prepend('<p class="consoleArea" style="position:absolute;bottom:0;right:0;width:200px;height:150px;overflow-y:scroll;z-index:99999;background-color:#000;color:#FFF;">');
				$('.consoleArea').append('console.log: ' + msg + '<br>');
				$('.consoleArea').scrollTop(9999999999999);
			}
		}
	}
}


/* ie cleartext
/*-------------------------------------------------------------------------------*/

$(document).ready(function(){
	$("h2, h2, h3, h4, h5, h6, .red a, .blue a, .yellow a, .grey a,div.introRight dt, div.leftCol a, div.leftCol dt, ul#accordion a, .entry-title, .entry-utility, #archive li, form input, form textarea, .sectionHeader, form label.placeholder")
	.ieffembedfix();
});


/* fixed footer
/*-------------------------------------------------------------------------------*/
var fixFooter = function(){
	var win = $(window);
	var h = 0;
    $('#container').children().not('footer').each(function(){h += $(this).outerHeight(true)});
	h += parseInt($('footer').css('padding-top'));
	if (win.height() > h){
		$('footer').css('position', 'fixed').css('bottom', 0);
	}else{
		$('footer').css('position', 'relative');
	}
}

$(function(){
	$(window).resize(fixFooter);
    $('#container section').resize(fixFooter);
	fixFooter();
});

function checkMousePosition(obj){
	bub.each( function() {
 		if( mouseX < $(this).offset().left || mouseX > $ (this).offset().left + $(this).width() || mouseY < $(this).offset().top || mouseY > $(this).offset().top + $(this).height() ) { 
			$('#bubbleMapArea').trigger( 'mouseleave' );
		}
	});
}
var mouseX, mouseY, bub, timer; 
$(function(){
	bub = $('#bubbleHolder');
	var bubImg = bub.children('img#bubble');
	var bhHalf = bubImg.height() / 2;
	var bwHalf = bubImg.width() / 2;
	var mapImg = $('#mapImage');
	var holder = bub.children('#contentHolder');
	$('#bubbleMapArea').mouseleave(function(e){
		if (e.relatedTarget == holder.get(0) || $(e.relatedTarget).parents("#contentHolder").length > 0) return;
		bub.css('visibility', 'hidden');
		clearInterval(timer);
		timer = null;
	});
	$('*').mousemove(function(e) { 
		mouseX = e.pageX;
		mouseY = e.pageY; 
	});
	$('area:not(#bubbleMapArea)').mouseover(function(){
		var content = $('#' + $(this).attr('alt'))
		var coords = $(this).attr('coords').split(',');
		var off = mapImg.offset();
		var newX = coords[0] - bwHalf;
		var newY = coords[1] - bhHalf;
		bub.offset({'top':newY + off.top, 'left': newX + off.left});
		
		holder.html(content.children().clone());
		holder.css('top', -bhHalf - holder.height() / 2);
		holder.hide();
		bub.css('visibility', 'visible').children('img').show('scale', {percent: 100}, 150, function(){
			holder.fadeIn('fast');
		});
		if (timer == null)
			timer = setInterval(checkMousePosition, 100, bub);
	});
});

/* services content switcher
/*-------------------------------------------------------------------------------*/
$(function(){
	$('body.page div.leftCol#filter a').click(function(){
		$('body.page div.leftCol#filter a').not($(this)).removeClass('selected');
		$(this).toggleClass('selected');
		var id = $(this).attr('data-type')
		$('.serviceItem:visible').fadeOut('fast', function(){
			$('.serviceItem#' + id).fadeIn('fast');
		});
		$('#peopleThumbs').children().fadeOut('fast', function(){
			$('#peopleThumbs').html($('.serviceItem#' + id + ' .peopleTagged').html()).hide().fadeIn('fast');
		});
		$('#projectThumbs').children().fadeOut('fast', function(){
			$('#projectThumbs').html($('.serviceItem#' + id + ' .projectsTagged').html()).hide().fadeIn('fast');
		});
	});
});


             
/* begin cornify fun *********************************************************/
/* courtesy Paul Irish ... */

function loadRemoteScript(url, callback) {
	var head = document.documentElement;
	script = document.createElement('script');

	script.src = url;

	var done = false;

	script.onload = script.onreadystatechange = function() {
		if( !done && (!this.readyState ||
			this.readyState === 'loaded' || this.readyState === 'complete') ) {
				done = true;

				callback();
		}
	};

	head.insertBefore( script, head.firstChild );

	return true;
}
            
function cornifyLocal(json) {
	//alert(json.ip); // alerts the ip address     
	if (json.ip == '67.211.17.2' || json.ip == '65.13.8.201') {  
		var chance = Math.floor(Math.random() * 3);
		if (chance == 0) {
			loadRemoteScript('http://www.cornify.com/js/cornify.js', function(){
				var times = [42, 28,75, 50, 62];
				times = times[Math.floor(Math.random() * times.length)];

				while(--times)
				cornify_add();
			});		
		}
	}
}

$(function () {	        
	if (window.location.pathname.toLowerCase().match(/agency\/team\/timothy/)) {
		try {               
			$.get('http://jsonip.appspot.com/?callback=cornifyLocal', function(data) {     
				//alert(data);
			});  
		} catch (err) { }
	} 
}) 

/* end cornify fun ***********************************************************/

	

