$(document).ready(function() {
				
	//cache nav
	
	var thumbSize = 244;
	var totalWidth;
	var galleryWidth;
	
        $.fn.touchstart = function(fn) { return this[fn ? "bind" : "trigger"]("touchstart", fn); };
	$.event.special.touchstart = {
		setup: function() {
			$.event.add(this, "mouseover", extendedClickHandler, {});                        
		},
		teardown: function() {
			$.event.remove(this, "mouseover", extendedClickHandler);
		}
	};
        
        
	function extendedClickHandler(e){
    		showPanel($(this));
	}
	
	function showPanel(that){
		
		that.addClass("noshadow");
		
		var self = that.children(":first");	
		self.addClass("navover");
		self.css("z-index", 105);
		
		var subNav = that.find("ul");
		subNav.css("z-index", 105);
		that.find("ul").stop(true, true).slideDown();
	}
	
	function hidePanel(that){
		that.removeClass("noshadow");
		var self = that.children(":first");
		self.removeClass("navover");
		self.css("z-index", 100);				
		var subNav = that.find("ul");
		subNav.css("z-index", 100);
		that.find("ul").stop(true, true).slideUp();
	}
	
	
	function initCommon(){
		//add indicator and hovers to submenu parents
		var nav = $("nav");
		nav.find("li").each(function() {
			
			if ($(this).find("ul").length > 0) {
                            if($(this).hasClass(item) && (item != undefined)) {
					showPanel($(this));
				}else{
					//show subnav on hover                                        
                                        
                                        $(this).bind('touchstart', function(event) {						
					});
                                        
					//hide submenus on exit
					$(this).mouseleave(function() {
						hidePanel($(this));
					});
				}
				
			}
            })
            .end()
    .find('ul.menu > li > a').attr({
        'href': '',
        'style': 'cursor:default'
    }).click(function() {return false;})
    .end();
		
		$("#sidebar").tabs();
	}
	/*$(window).resize(function() {
		
	});*/
	
	function resize(){
		
		if($(".video-js-box").length > 0){
			var cssObj;
			var newWidth;
			 if($(window).width() < 480){
					cssObj = {
					  'width' : 228,
					  'height' : 171
					};
					newWidth = 228;
				}else{
					cssObj = {
					  'width' : 472,
					  'height' : 354
					};
					newWidth = 472;
				}
				
				
			$(".video-js-box img").css(cssObj);
			$(".video-js-box a").css(cssObj);
			$("video").css(cssObj);
			$("video.video-js").css(cssObj);
			$(".vim-css").css("width", newWidth);
			$(".video-js-box .vjs-controls").css("width", newWidth);
		
		}
	}
	
	function showDropdown(that){
		
		var self = that.children(":first");	
		//self.addClass("dropdownover");
		self.css("z-index", 105);
		
		var subNav = that.find("ul");
		subNav.css("z-index", 105);
		that.find("ul").stop(true, true).slideDown();
	}
	
	function hideDropdown(that){
		var self = that.children(":first");
		//self.removeClass("dropdownover");
		self.css("z-index", 100);				
		var subNav = that.find("ul");
		subNav.css("z-index", 100);
		that.find("ul").stop(true, true).slideUp();
	}
	
	
	function initDropdown(){
		//add indicator and hovers to submenu parents
		var dropdown = $(".dropdown");
		//alert("here!");
		
		if(dropdown.length > 0){
			dropdown.find("li").each(function() {
				if ($(this).find("ul").length > 0) {
					//alert("$(this): " + this.id);
					$(this).click(function(){
						showDropdown($(this));
					});
					
					//hide submenus on exit
					$(this).mouseleave(function() {
						hideDropdown($(this));
						
					});
					
				}
			});
		}		
	}
	
	function initToggle(){
		///alert($(".togglelist").length);
		if($("a.togglelist").length > 0){
			
			$("a.togglelist").each(function(){ 
				$(this.rel).hide("fast");	
			}).click(function() {
				if(!$(this).hasClass("close")){
					$(this).addClass("close");
				}else{
					$(this).removeClass("close");
				}
			 	$(this.rel).slideToggle("fast");	
			});
			
			//default view. 	
			for(var i = 0; i < 2; i++){
				$($("a.togglelist")[i].rel).slideDown();
				$($("a.togglelist")[i]).addClass("close");
			}
		}		
	}
	
	function updateWidth(){
		totalWidth = $('.scrollableArea .thumb').length * thumbSize;
		galleryWidth = $('.gallery').width();	
		$('.scrollableArea').css("left", 0);
		if($(window).width() > 992){			
			$(window).load(function() {
				$(".gallery").smoothDivScroll({ 
					autoScrollStep: 10, 
					autoScrollInterval: 100
				});
			});			 
		}else{
			$(".gallery").smoothDivScroll("destroy");
			if($('.scrollableArea .thumb').length > 1){
				$(".next").show();
				$(".prev").hide();
			}
			initScroll();
		}	
		
	}
	
	
	function scrollRight(){
		var orgPt = parseInt($(".scrollableArea").css("left").substring(-2));
		
		var leftPt = orgPt - thumbSize;
		var offset = totalWidth - galleryWidth;
		if(leftPt >= -offset){				
			$('.scrollableArea').stop().animate({
				left: '-='+thumbSize
			}, 300, function(){
				var newpt = parseInt($(".scrollableArea").css("left").substring(-2));
				if(newpt - 30 <= -(totalWidth - galleryWidth)){
					$(".next").hide();
				}else{
					$(".next").show();
				}
				if(newpt < 0){
					$(".prev").show();
				}
			});	
		}
	}
	
	function scrollLeft(){
			
		var orgPt = parseInt($(".scrollableArea").css("left").substring(-2));
		var leftPt = orgPt + thumbSize;
		
		
		if(leftPt <= 0){
			$('.scrollableArea').stop().animate({
				left: '+='+thumbSize
			}, 300, function(){
				var newpt = parseInt($(".scrollableArea").css("left").substring(-2));
				if(newpt == 0){
					$(".prev").hide();
				}else{
					$(".prev").show();
				}
				
				var offset = totalWidth - galleryWidth;
				if(newpt >= -offset){		
					$(".next").show();
				}
				
			});	
		}		
	}
	
	function initScroll(){
		$(".next").click(scrollRight);	
		$(".prev").click(scrollLeft);	
		
	}
	
	function imgScroller(){		
		 
		updateWidth();
		$(window).bind('resize', updateWidth);
		
	}
	
	
	function updateEmployeeWidth(){
		var row = 0;
		var numIdx = 0;
		$("a.thumbnail").each(function(){ 
			//$(this.rel).hide("fast");	
			//alert(numIdx + ": " + row);
			var newWidth;
			var maxIdx;
			if($(window).width() < 479){
				maxIdx = 3;
				newWidth = 228;
				$(this).addClass("reduced");
			}else{
				newWidth = 472;
				maxIdx = 6;
				$(this).removeClass("reduced");
			}
			
			$("#employee").css("width", newWidth);
			if(numIdx >= maxIdx){
				numIdx = 0;	
				row++;
			}
				
			this.rowIdx = row;	
			if(numIdx == 0){
				$(this).addClass("firstitem");
			}else if(numIdx == maxIdx-1){
				$(this).addClass("lastitem");
			}else{
				$(this).removeClass("firstitem");
				$(this).removeClass("lastitem");
			}
			
			numIdx++;
					
		});
	}
	
	function initEmployee(){
		
		if($("#employee").length > 0){
			
			
			$.easing.drop = function (x, t, b, c, d) {
				return c*(t/=d)*t + b;
			};
			// loading animation
			$.tools.overlay.addEffect("drop", function(css, done) { 
			   
				// use Overlay API to gain access to crucial elements
				var conf = this.getConf(),
				overlay = this.getOverlay();        
				
			   // determine initial position for the overlay
			   if (conf.fixed)  {
				  css.position = 'fixed';
			   } else {
				  css.top = 0;
				  css.left = 0;
				  css.position = 'absolute';
			   } 
			   
			   // position the overlay and show it
			   overlay.css(css).fadeIn();
			   // begin animating with our custom easing
			  this.getTrigger().trigger('openThumbnail', [overlay, done]);
			   /* closing animation */
			   }, function(done) {
				  this.getOverlay().animate({opacity:0 }, 300, 'drop', function() {
					 $(this).hide();
						done.call();      
				  });
			   }
			);
			
			updateEmployeeWidth();
			$(window).bind('resize', updateEmployeeWidth);
			
			$("a.thumbnail").bind('close', function(){
				$(this.rel).hide();
			});
			
			//alert(thumbHeight + "  /  " + detailsHeight);
			$("a.thumbnail").bind('openThumbnail', function(event, overlay, done){
				
				var employeeHeight = $("#employee").height();
				var thumbHeight = $("a.thumbnail").first().height() + 2;
				var detailsHeight = $(".simple_overlay").first().height();
				
				var offsetTop = (this.rowIdx) * thumbHeight;
				
				if(employeeHeight <= offsetTop + detailsHeight){
					offsetTop = employeeHeight - detailsHeight - 2;
				}
				overlay.css({top: offsetTop});
				overlay.animate({opacity: 1}, 400, 'drop', done);
				
			});
			$("a.thumbnail").overlay({effect: 'drop', fixed: false});
		}
	}
	
	function refreshSlider(){
		$('.bond-touchmargin').bond({ desktopMode: 'touchMargin', mobileMode: 'touchMargin'});
	}
	
	
	function sliderTip(){	
		/* CONFIG */		
			xOffset = 10;
			yOffset = 20;		
			// these 2 variable determine popup's distance from the cursor
			// you might want to adjust to get the right result		
		/* END CONFIG */		
		$(".bond-slide").hover(function(e){											  
			//this.t = this.title;
			var contents = "drag to scroll";
			
			$("body").append("<p class='tip'>"+ contents +"</p>");
			//this.title = "";									  
			$(".tip")
				.css("top",(e.pageY - xOffset) + "px")
				.css("left",(e.pageX + yOffset) + "px")
				.fadeIn("fast");		
		},
		function(){
			//this.title = this.t;		
			$(".tip").remove();
		});	
		$(".bond-slide").mousemove(function(e){
			$(".tip")
				.css("top",(e.pageY - xOffset) + "px")
				.css("left",(e.pageX + yOffset) + "px");
		});			
	};
	
	function initSection(){
		//alert("section: "+section);
		switch(section){
			case "about":
				initToggle();
				initEmployee();
				break;
			case "work":
				initDropdown();
				if($(".bond-touchmargin").length > 0){
					$('a.thumb').fancybox({		
						'overlayColor'		: '#000',
						'overlayOpacity' 	: 0.9
					});
					
					$(window).bind('resize', refreshSlider);
					sliderTip();
					$('.bond-touchmargin').bond({ desktopMode: 'touchMargin', mobileMode: 'touchMargin'});
				}
				break;				
			case "case-studies":
				resize();
				$(window).bind('resize', resize);
				break;
		}
	}
	
		
	initCommon();
	initSection();
	
});

$(function() {
   // add last class to each last sub-menu item, to fix problem in ie 7/8
   $('li ul.sub-menu').each(function(index) {
       $('li.menu-item:last', this).addClass('last');
   });   
});

// i need to create my own unique function, jquery's $.unique() doesn't work
Array.prototype.unique = function(){
    var vals = this;
    var uniques = [];
    for(var i=vals.length;i--;){
        var val = vals[i];  
        if($.inArray( val, uniques )===-1){
            uniques.unshift(val);
        }
    }
    return uniques;
}


// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/

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