/* Author: Jake Puffer
Ted Perez + Associates
*/


// =========== 
// ! Globals   
// =========== 

var RANDOM_NUM = Math.floor(Math.random()*1000);

var smallContainerWidths = new Array();
var largeContainerWidths = new Array();
var canvasWidth = 0;
var canvasGridsWide = 0;
var gridWidthPx = 95;
var gutterWidthPx = 15;
var extraSpace = 0; //the space leftover after the grid has been placed.  This number will always be smaller than the width of one grid cell.
var XMLObject;
var numRows = 0;
var smallContentWritten = 0;
var largeContentWritten = 0;
var staticContentWritten = 0;
var currentRow = 0;
var numSpotsLeftInRow;
var largeContentMinWidth = 4;
var largeContentMaxWidth = 6;
var itemExpandedMinWidth = 4;
var itemExpandedMaxWidth = 7;
var itemExpandedDescMinWidth = 2;
var minGridWidth = (largeContentMinWidth * (gridWidthPx + gutterWidthPx) );

var staticContentImgUrl = "media/img_thumb/static_img_all.jpg";

/* var resizeEnabled = true; */
var trayIsOut = false;
var trayIsAnimating = false;
var trayAnimSpeed = 600;

/* var sidebarMinWidth = 140; */
var sidebarMinWidth = 191;
/* var sidebarInitialMarginTop = 190; */
var colorCodeBorderWidth = 4;

var trayOpenedWidth = 405;
var trayCurrentWidth = 0;

var rowHeightPx = (3*gridWidthPx)+(2*gutterWidthPx);

var smallContentArray = new Array();
var totalNumSmallContentSpots = 0;
var largeContentArray = new Array();
var totalNumLargeContentSpots = 0;
var numSmallSpotsBetweenLarge;
var savedWindowWidth = 0;

var smallScreenModeEnabled = false;
var scrollIsEnabled = true;

var currentFilter = "all";
var userLoggedIn = false;
var userContentXmlUrl = "";

var isiPad = navigator.userAgent.match(/iPad/i) != null;
//isiPad = true; // for testing

var expandedWidthsPxArray = new Array();


function writeExpandedWidthsArray(){
	expandedWidthsPxArray = new Array();
	for (i=0; i < (itemExpandedMaxWidth - itemExpandedMinWidth + 1); i++) { 
		var theNumColumns = itemExpandedMinWidth + i;
	    expandedWidthsPxArray[i] = (gridWidthPx * theNumColumns) + ( gutterWidthPx * (theNumColumns-1) );
	    /* console.log("expandedWidthsPxArray # "+i+": "+expandedWidthsPxArray[i]); */
	}
}
writeExpandedWidthsArray();

Shadowbox.init({
    // skip the automatic setup, we do this later manually
    skipSetup:       true,
    overlayColor:    "#393938",
    overlayOpacity:  .8,
    players:         ['img', 'html', 'iframe'],
    onOpen:          fixShadowBoxForMobile,
    onClose:         enableiPadScroll
});

$(document).ready(function() {
	$("#sidebar").hide();
	init(siteXMLURL);
	/* init("site_dest_test.xml?abc"); */
	
	/* $(".subnav").hide(); */
	$(".tray-container").hide();
	$("#subnav_news").click(function(){ subNavClick(this, "tray-news"); return false;});
	$("#subnav_about").click(function(){ subNavClick(this, "tray-about"); return false;});
	$("#subnav_bav").click(function(){ subNavClick(this, "tray-bav"); return false;});
	$("#subnav_jobs").click(function(){ subNavClick(this, "tray-jobs"); return false;});
	$("#subnav_contact").click(function(){ subNavClick(this, "tray-contact"); return false;});
	onWindowResize(true);
});

function filterSpots(theCategory, theXmlUrl){
	clearCounters();
	totalNumLargeContentSpots = 0;
	totalNumSmallContentSpots = 0;
	currentFilter = theCategory;
	/*if (theCategory == "you" ){
		staticContentImgUrl = "media/img_thumb/static_img_you.jpg";
	}
	else{*/
		staticContentImgUrl = "media/img_thumb/static_img_"+theCategory+".jpg";
	/* } */

	init(theXmlUrl);
}

function init(theXmlUrl){
	clearCounters();
	totalNumLargeContentSpots = 0;
	totalNumSmallContentSpots = 0;
	$("#site-footer").hide();
  	
	$.ajax({
		type: "GET",
		url: theXmlUrl,
		dataType: "xml",
		success: XmlHandler
	});
	
	if( detectSmallScreen()==true ){
		enableSmallScreenMode();
	}
	
	$("#sidebar").css("minWidth", sidebarMinWidth+"px");
	
	
	
}



function XmlHandler(xml){
	XMLObject = xml;
	/* currentFilter = "all"; */
	parseXml();
}

function clickMainNavYou(element){
	if ( $(element).hasClass("active")){ //user is logged in and 'you' is active. clear filter, but stay logged in.
		$(element).removeClass("active");
		filterSpots("all", siteXMLURL);
	}
	else{ 
		if (userLoggedIn){ //user is logged in, but results are not filtered.  filter the results.
			/* $("#signin_menu #username, #signin_menu #password, #signin_menu #signin_cancel").hide(); */
			$(".main_nav_item").removeClass("active");
			$("#sidebar #you").addClass("active");
			$("#signin_logout").show();
			filterSpots("you", userContentXmlUrl);
		}
		else{
			if ( $("#signin_menu").is(":visible") && $("#signin_logout").is(":hidden") ){ //user is not logged in, and has opened the form already.  close the form.
				$("#signin_menu").hide();
			}else{ //user is not logged in and the tray is not yet ope.  open the login form.
				$("#signin_menu #username, #signin_menu #password, #signin_menu #signin_cancel").show();
				$("#signin_submit").show();
				$("#signin_logout").hide();
				$("#signin_menu").slideDown(100);
			}
		}
	}
}

function clickSigninMenuCancel(){
	$("#signin_menu").slideUp(300);
}
function clickSigninMenuSubmit(target){
	$("#signin_error").hide();
	var uName = $("#signin_menu #username").val();
	var pWord = $("#signin_menu #password").val();

	if(uName == '' || uName == undefined || pWord == '' || pWord == undefined){
		$("#signin_error").html("Error! Please provide a username and password.");
		$("#signin_error").show(100);
	} else {
		$.ajax({
				type: "POST",
				url: "login.php",
				data: "user=" + uName + "&password=" + pWord,
				success: function(msg){
					if(msg == "fail"){
						// fail
						$("#signin_error").html("Error! Incorrect username or password.");
						$("#signin_error").show(100);
					} else {
						// success. show "you" section.
						userContentXmlUrl = "assets/xml/"+msg+"?rand="+RANDOM_NUM
						showYouSection();
					}
				}
			});
	}
	
	function showYouSection(){
		$("#signin_menu #username, #signin_menu #password, #signin_menu #signin_cancel").hide();
		$(".main_nav_item").removeClass("active");
		$("#sidebar #you").addClass("active");
		$(target).hide();
		$("#signin_logout").show();
		userLoggedIn = true;
		filterSpots("you", userContentXmlUrl);
	}
}
function clickSignOut(target){
	$(target).hide();
	$("#sidebar #you").removeClass("active");
	filterSpots("all", siteXMLURL);
	userLoggedIn = false;
}

function mainNavClick(element, theNavItem){
	if(!userLoggedIn){$("#signin_menu").slideUp(300);}
	if ( $(element).hasClass("active")){
		$(element).removeClass("active");
		filterSpots("all", siteXMLURL);
	}
	else{
		closeTray("all");
		$(".main_nav_item").removeClass("active");
		filterSpots(theNavItem, siteXMLURL);
	$(element).addClass("active");
	}
}

function subNavClick(element, theTray){
	if (!trayIsAnimating){ //do nothing if the tray is already animating.
		if ( $(element).hasClass("active") ){
			$(element).removeClass("active");
			closeTray(theTray);
		} else{
			$(".subnav_item").removeClass("active");
			$(element).addClass("active");
			openTray(theTray);
		}
	}
}





function parseXml(){
	
	if (smallScreenModeEnabled){
		smallContainerWidths[0] = 1;
		largeContainerWidths[0] = 2;
	}else{
		$(XMLObject).find("container").each(function(index, object){
			smallContainerWidths[index] = $(this).attr("width");
		});
		$(XMLObject).find("largecontainer").each(function(index, object){
			largeContainerWidths[index] = $(this).attr("width");
		});
	}

	if (currentFilter == "all" || currentFilter == "you"){
		$(XMLObject).find("griditem").each(function(index, object){
			if ( $(this).attr("large") == 1 ){
				totalNumLargeContentSpots += 1;
			}
			else{
				totalNumSmallContentSpots += 1;
			}
		});
	}else{
		$(XMLObject).find("griditem[category='"+currentFilter+"']").each(function(index, object){
			if ( $(this).attr("large") == 1 ){
				totalNumLargeContentSpots += 1;
			}
			else{
				totalNumSmallContentSpots += 1;
			}
		});
	}
	
	
	numSmallSpotsBetweenLarge = Math.floor( totalNumSmallContentSpots / totalNumLargeContentSpots );

	if (!isiPad && !smallScreenModeEnabled){
		$(window).resize(function(){	
			onWindowResize(false);
		});
	}else{
		window.onorientationchange = function() {
			onWindowResize(true);
		}
	}
	
	$(window).scroll(function(){
		/* $("#sidebar").hide(); */
		delay2(function(){onScroll();}, 200);
	});
	
	//set custom image for first grid spot of "YOU" section
	/* console.log("about to determine new image."); */
	if (currentFilter == "you"){
		$(XMLObject).find("clientImage").each(function(index, object){
			/* console.log("$(object).text(): "+$(object).text() ); */
			staticContentImgUrl = $(object).text();
			/* console.log("new static content img: "+staticContentImgUrl); */
		});
	}else{
		/* console.log("not loading 'you' section."); */
	}
	
	buildSpots();
	onScroll();
	
	/* $('style').cssFinalize(); */
}

function onWindowResize(isOrientationChange){
	if (isOrientationChange){
/* 		console.log("is orientation change"); */
		var theOrientation = detectIPadOrientation();
		if (theOrientation == "portrait"){
			/* alert("This website was designed to be viewed in landscape mode.  Please rotate your device for an optimal viewing experience."); */
			var largeContentMinWidth = 4;
			var largeContentMaxWidth = 5;
			itemExpandedMinWidth = 3;
			itemExpandedMaxWidth = 5;
			writeExpandedWidthsArray();
		}else{
			var largeContentMinWidth = 4;
			var largeContentMaxWidth = 6;
			itemExpandedMinWidth = 4;
			itemExpandedMaxWidth = 7;
			writeExpandedWidthsArray();
		}
		$(".expanded-content").remove();
		/* alert("orientation change"); */
		enableMobileScroll();
		
		/* trayOpenedWidth = (window.innerWidth - (2*gutterWidthPx)); */
		if (trayIsOut){
			closeTray("all");
		}
	}
	
	var windowHeight;
	var newWindowWidth;
	
	var newWindowWidth;
	if (smallScreenModeEnabled){
/* 		console.log("small screen mode is enabled."); */
		windowHeight = window.innerHeight;
		newWindowWidth = window.innerWidth;
	}else{
/* 		console.log("Finding window height and width."); */
		windowHeight = $(window).height();
		newWindowWidth = $(window).width();
/* 		console.log("Window height and width found."); */
	}
	/* alert("resize handler's new window width: "+newWindowWidth); */
	
	if ( newWindowWidth != savedWindowWidth){
/* 		console.log("newWindowWidth != savedWindowWidth. hide spots and call buildSpots on a delay."); */
		$("#spots").hide();
		delay(function(){ buildSpots();	}, 100);
	}
	$(".tray-container").height( windowHeight - (2*gutterWidthPx) );
	$(".tray-container .tray-inner").height( windowHeight - (2*gutterWidthPx) );
	$(".tray-container .scroll-area").height( windowHeight - (2*gutterWidthPx) -$(".tray-container header").height() );
/* 	console.log("finished with window resize function."); */
}

function onScroll(){
	/*if (smallScreenModeEnabled){
		$("#sidebar-inner").css("marginTop",window.pageYOffset+"px"); 
	}*/
}

function clearCounters(){
	currentRow = 0;
	smallContentWritten = 0;
	largeContentWritten = 0;
	staticContentWritten = 0;
}

function buildSpots(){
	/* console.log("buildSpots function started."); */
	$("#spots").html(" ");
	$("#spots").show();
	
	var windowWidth;
	if (smallScreenModeEnabled){
		windowWidth = window.innerWidth;
	}else{
		windowWidth = $(window).width();
	}
	/* alert("build spot's window width: "+windowWidth); */

	canvasWidth = ( windowWidth - sidebarMinWidth );
	/* console.log("CANVAS WIDTH: "+canvasWidth); */
	
	if (canvasWidth < minGridWidth && !smallScreenModeEnabled){
		canvasWidth = minGridWidth;
		/* console.log("CANVAS WIDTH TOO SMALL.  MAKING IT EQUAL THE MAX."); */
		/* console.log("CANVAS WIDTH: "+canvasWidth); */
	}
	
	canvasGridsWide = Math.floor(canvasWidth / (gridWidthPx + gutterWidthPx) );
	/* console.log("canvasGridsWide: "+canvasGridsWide); */
	remainder = canvasWidth % (gridWidthPx + gutterWidthPx);
	extraSpace = remainder;

	var numRows = Math.ceil(totalNumSmallContentSpots / canvasGridsWide);
	
	/* $("#spots_wide").html(canvasWidth + ", " + canvasGridsWide + ", " + extraSpace + ", " +numRows); */
	
	clearCounters();
	
	var i=0;
	
	/* console.log("smallContentWritten: "+smallContentWritten+"totalNumSmallContentSpots: "+totalNumSmallContentSpots); */
	while (smallContentWritten < totalNumSmallContentSpots || largeContentWritten < totalNumLargeContentSpots){
		/*console.log("writing row. small content written: "+smallContentWritten);
		console.log("totalNumSmallContentSpots: "+totalNumSmallContentSpots);
		console.log("largeContentWritten: "+largeContentWritten);
		console.log("totalNumLargeContentSpots: "+totalNumLargeContentSpots);
		console.log("__");*/
		writeRow();
	}
	
	var amountPageSmallerThanMinimum = canvasWidth - ( windowWidth - sidebarMinWidth );
	var sidebarWidth = (windowWidth + amountPageSmallerThanMinimum) - ( canvasGridsWide* (gridWidthPx + gutterWidthPx) );
	/* var sidebarWidth = windowWidth - ( canvasGridsWide* (gridWidthPx + gutterWidthPx) ); */
	
	
	/* console.log("total width of grids: " + ( canvasGridsWide* (gridWidthPx + gutterWidthPx))); 
	console.log("windowWidth: " + windowWidth);
	console.log("sidebarWidth: " + sidebarWidth);*/
	
	$("#sidebar").height( "100%" );
	$("#sidebar").width( sidebarWidth );
	$("#sidebar").show();
	$("#main").width( windowWidth - (sidebarWidth + trayCurrentWidth) );
	$("#main").css("marginLeft", sidebarWidth+trayCurrentWidth);
	$('.tray-container').css("left",sidebarWidth);
	$(".tray-container").height( $(window).height() - (2*gutterWidthPx) );
	
	/* $("footer").css("marginLeft", ( windowWidth - ( canvasGridsWide* (gridWidthPx + gutterWidthPx) ) )); */
	
	addMouseEvents();
	setTimeout(function() { $("#site-footer").show(); }, 500);
	

	if (smallScreenModeEnabled){
		savedWindowWidth = window.innerWidth;
	}else{
		savedWindowWidth = $(window).width();
	}
}


function writeRow(){
	/* console.log("writeRow"); */
	
	currentRow += 1;
	
	$("#spots").append("<div class='row clearfix' id='row" + currentRow + "'"
		+ "style='height:"+ (rowHeightPx + gutterWidthPx) +"px; "
		+"width:"+((gridWidthPx + gutterWidthPx)*canvasGridsWide)+"px;'>");

	numSpotsLeftInRow = canvasGridsWide;

	//loop until there is no more room in the row
	while (numSpotsLeftInRow > 0){
		//check to make sure there's still content to be written
		if (smallContentWritten < totalNumSmallContentSpots){
			//check to see if we're due for a large content block
			if (staticContentWritten == 0){
				createStaticContainer();
			}
			else if (
				(
					smallContentWritten > (largeContentWritten * numSmallSpotsBetweenLarge) 
					|| 
					(smallContentWritten == 0 && largeContentWritten == 0)
				) 
				&& 
					largeContentWritten < totalNumLargeContentSpots
				&&
					numSpotsLeftInRow >= largeContentMinWidth
				)
			{
				createContainer(true);
			}else{
				// we aren't due for a large content container, so write a small container
				createContainer(false);
			}
		}else if((largeContentWritten < totalNumLargeContentSpots) && (numSpotsLeftInRow >= largeContentMinWidth)){
			//we are done with small content spots, but still have large ones to write. write one if there is room.
			/*console.log("largeContentWritten: "+largeContentWritten);
			console.log("smallContentWritten: "+smallContentWritten);
			console.log("done with small content, but not done with large. create large content container.");*/
			createContainer(true);
		}else{
			//there is no more content to be written.  make a filler block to finish the row.
			createRowFillerContainer();
		}
	}
	$("#spots").append("</div>");
	
}

function createStaticContainer(){

	var theContainerWidth
	if (smallScreenModeEnabled){
		theContainerWidth = 2;
	}else{
		theContainerWidth = 4;
	}
	
	$("#row"+ currentRow).append(
		"<div class='staticContainerBlock containerWidth"+theContainerWidth
		+" clearfix' style='width:"+((theContainerWidth*gridWidthPx)+((theContainerWidth-1)*gutterWidthPx))+"px; "
		+ "margin: "+ gutterWidthPx +"px " + gutterWidthPx + "px 0 0; "
		+ "left: "+ ((canvasGridsWide - numSpotsLeftInRow)*(gridWidthPx+gutterWidthPx)) +"px; " 
		+ "top: 0px;" 
		+ "'>"
		+ '<div class="static-content colorcode_'+currentFilter+'" style="left:0px; top:0px; width:'+((theContainerWidth*gridWidthPx)+((theContainerWidth-1)*gutterWidthPx)-(colorCodeBorderWidth))+'px; height:'+rowHeightPx+'px; margin-bottom:0px; margin-right:0px; background-image: url('+staticContentImgUrl+');background-repeat:no-repeat;background-position:center center; border-left-style:solid; border-left-width:'+colorCodeBorderWidth+'px; "></div>'
		+"</div>");
	staticContentWritten++;
	numSpotsLeftInRow -= theContainerWidth;
}


function createContainer(isLarge){
	var theContainerWidth = 1000;
	var theContainerNumber;
	var theContainerWidths;
	
	if (isLarge){
		theContainerWidths = largeContainerWidths;
	}else{
		theContainerWidths = smallContainerWidths;
	}
	
	
	// this loop will 'try again' until it finds a container that is not too big for the space available in the row
	do {
		theContainerNumber = Math.floor( Math.random() * theContainerWidths.length );
		theContainerWidth = theContainerWidths[theContainerNumber];
		/*console.log("finding a container. theContainerWidth: "+theContainerWidth);
		console.log("finding a container. numSpotsLeftInRow: "+numSpotsLeftInRow);
		console.log("_");*/
	} while ( theContainerWidth > numSpotsLeftInRow); 
	
	$("#row"+ currentRow).append(
		"<div class='contentContainerBlock containerWidth"+theContainerWidth
		+" clearfix' style='width:"+((theContainerWidth*gridWidthPx)+((theContainerWidth-1)*gutterWidthPx))+"px; "
		+ "margin: "+ gutterWidthPx +"px " + gutterWidthPx + "px 0 0; "
		+ "left: "+ ((canvasGridsWide - numSpotsLeftInRow)*(gridWidthPx+gutterWidthPx)) +"px; " 
		+ "top: 0px;" 
		+ "'>"
		+createChildren(isLarge, theContainerNumber)
		+"</div>");
	
	numSpotsLeftInRow -= theContainerWidth;
	
	if (numSpotsLeftInRow == 0){
		$("#row"+ currentRow).children().last().addClass("last-in-row");
	}
}


function createRowFillerContainer(){

	var theContainerWidth = numSpotsLeftInRow;
	
	$("#row"+ currentRow).append(
		"<div class='contentContainerBlock containerWidth"+theContainerWidth
		+" clearfix' style='width:"+((theContainerWidth*gridWidthPx)+((theContainerWidth-1)*gutterWidthPx))+"px; "
		+ "height: "+ rowHeightPx +"px; " 
		+ "margin: "+ gutterWidthPx +"px " + gutterWidthPx + "px 0 0; "
		+ "left: "+ ((canvasGridsWide - numSpotsLeftInRow)*(gridWidthPx+gutterWidthPx)) +"px; " 
		+ "top: 0px;" 
		+ "'>"
		+ "<div class='row-filler bg_argyle_"+currentFilter+"'></div>"
		+"</div>");
	
	numSpotsLeftInRow -= theContainerWidth;
	
	if (numSpotsLeftInRow == 0){
		$("#row"+ currentRow).children().last().addClass("last-in-row");
	}
}



function createChildren(isLarge, containerNumber){
	/* console.log("create children. "+isLarge+" "+containerNumber); */
	
	var lookingForNode;
	if (isLarge){
		if (smallScreenModeEnabled){
			lookingForNode = "largecontainer-mobile";
		}else{
			lookingForNode = "largecontainer";
		}
	}else{
		if(smallScreenModeEnabled){
			lookingForNode = "container-mobile";
		}else{
			lookingForNode = "container";		
		}
	}
	
	/* console.log(lookingForNode + ", " + containerNumber); */
	
	var theChildrenHTML = " ";
	
	var theChildren = $(XMLObject).find(lookingForNode).eq(containerNumber).find("child").each(function(index, object){
		/* console.log("starting children loop"); */
		if (smallContentWritten < totalNumSmallContentSpots || isLarge){
			//do this if there is still small content to write or the only child being created is a large child.
			var theShapeId = $(object).attr('shape-id');
			
			var theId;
			var theBgImg; 
			var theColorClass;
			var theClient;
			var theCampaign;
			var theAltTitle;
			var isLargeBinary;
			var searchFilters;
			var theContentWritten; 
			var videoNode;
			var trayOpenerNode;
			
			if (isLarge){isLargeBinary = "1"; theContentWritten = largeContentWritten;}
			else{isLargeBinary = "0"; theContentWritten = smallContentWritten}
			if (currentFilter == "all" || currentFilter == "you"){
				searchFilters = "[large='"+isLargeBinary+"']";
			}else{
				searchFilters = "[large='"+isLargeBinary+"'][category='"+currentFilter+"']";
			}
			/* console.log("searchFilters: "+searchFilters); */
			
			$(XMLObject).find("griditem"+searchFilters).eq(theContentWritten).each(function(){
				theId = $(this).attr("id");
				trayOpenerNode = $(this).attr("tray-target");
				theBgImg = $(this).find('thumb[shape-id="'+theShapeId+'"]').attr("src");
				theColorClass = "colorcode_" + $(this).attr("category");
				theClient = $(this).find('client').text();
				theCampaign = $(this).find('campaign').text();
				theAltTitle = $(this).find('alt-title').text();
				videoNode = $(this).find('video').text(); 
			});
			
			var childWidth;
			var childHeight;
			
			theChildrenHTML += "<div class='content "+theColorClass+"' style='";
			theChildrenHTML += "left:"+($(object).attr('originx')*(gridWidthPx+gutterWidthPx))+"px; ";
			theChildrenHTML += "top:"+($(object).attr('originy')*(gridWidthPx+gutterWidthPx))+"px; ";
			theChildrenHTML += "width:"+(($(object).attr('width')*gridWidthPx)+( (($(object).attr('width')-1)*gutterWidthPx) )-(colorCodeBorderWidth))+"px; ";
			theChildrenHTML += "height:"+( ($(object).attr('height')*gridWidthPx) + (($(object).attr('height')-1)*gutterWidthPx) )+"px; ";
			theChildrenHTML += "margin-bottom:"+($(object).attr('marginbottom')*gutterWidthPx)+"px; ";
			theChildrenHTML += "margin-right:"+($(object).attr('marginright')*gutterWidthPx)+"px; ";
			/* theChildrenHTML += "background-image: url(media/img/"+ PadDigits((smallContentWritten+1) , 3) +".jpg);"; */
			theChildrenHTML += "background-image: url("+theBgImg+");";
			theChildrenHTML += "background-repeat:no-repeat;";
			theChildrenHTML += "background-position:center center; ";
			theChildrenHTML += "border-left-style:solid; ";
			theChildrenHTML += "border-left-width:"+colorCodeBorderWidth+"px; ";
			theChildrenHTML += "'";
			
			theChildrenHTML += "data-id='"+ (theId) +"'";
			/* theChildrenHTML += "data-shape-id='"+($(object).attr('shape-id'); */
			theChildrenHTML += "data-column='"+ (canvasGridsWide - numSpotsLeftInRow + 1) +"'";
			theChildrenHTML += "data-spots-left-in-row='"+ (numSpotsLeftInRow - $(object).attr('originx')) +"'";
			theChildrenHTML += "data-leftpos='"+ ($(object).attr('originx')) +"'";
			
			theChildrenHTML += ">";
			
			theChildrenHTML += "<div class='hover-info'>";
				if (videoNode){theChildrenHTML += "<div class='video-hover'></div>";}
				else if (trayOpenerNode){theChildrenHTML += "<div class='trayopener-hover'></div>";}
				else{theChildrenHTML += "<div class='print-hover'></div>";}
				
				theChildrenHTML += "<div class='grid-hover-title clearfix'>";
					if (theAltTitle && theAltTitle!= "" && theAltTitle!= " "){
						theChildrenHTML += "<span class='grid-hover-client'>"+theAltTitle+"</span>";
						theChildrenHTML += "<br>"
					}else{
						if (theClient && theClient!= "" && theClient!= " "){
						theChildrenHTML += "<span class='grid-hover-client'>"+theClient+":</span>";
						theChildrenHTML += "<br>"
						}
						if (theCampaign && theCampaign!= "" && theCampaign!= " "){
						theChildrenHTML += "<span class='grid-hover-campaign'>"+theCampaign+"</span>";
						}
					}
					
					
				theChildrenHTML += "</div>";
			theChildrenHTML += "</div>";
			theChildrenHTML += "</div>";
			
			
			if (isLarge){
				largeContentWritten++;
			}
			else{
				smallContentWritten++;
			}
		}
		else{
			theChildrenHTML += "<div class='dummy-content bg_argyle_"+currentFilter+"' style='";
			theChildrenHTML += "left:"+($(object).attr('originx')*(gridWidthPx+gutterWidthPx))+"px; ";
			theChildrenHTML += "top:"+($(object).attr('originy')*(gridWidthPx+gutterWidthPx))+"px; ";
			theChildrenHTML += "width:"+(($(object).attr('width')*gridWidthPx)+( (($(object).attr('width')-1)*gutterWidthPx) ))+"px; ";
			theChildrenHTML += "height:"+( ($(object).attr('height')*gridWidthPx) + (($(object).attr('height')-1)*gutterWidthPx) )+"px; ";
			theChildrenHTML += "margin-bottom:"+($(object).attr('marginbottom')*gutterWidthPx)+"px; ";
			theChildrenHTML += "margin-right:"+($(object).attr('marginright')*gutterWidthPx)+"px; ";
			theChildrenHTML += "'"
			
			theChildrenHTML +=">";
			
			
			theChildrenHTML += "</div>";
		
		}
	});
	
	return(theChildrenHTML);
}


function addMouseEvents(){
	// remove old click handlers
	/* $("#us").unbind('click', usClickHandler); */
	if(smallScreenModeEnabled){
		$(".grid-hover-title").hide();
	}else{
		$(".content").mouseover(function() {
			var theTextWidth = $(this).find(".grid-hover-title").width();
			var theBoxWidth = $(this).width();
			var theBoxHeight = $(this).height();
			/* console.log("theTextWidth: "+theTextWidth + ", theBoxWidth: "+ theBoxWidth); */
			/* console.log("theBoxHeight: "+theBoxHeight + ", gridWidthPx: "+ gridWidthPx); */
			if (theTextWidth > theBoxWidth || theBoxHeight <= gridWidthPx){
				$(this).find(".grid-hover-title").hide();
			}
		});
	}
	
	$(".content").click(function() {
		contentClickEvent(this);
	});
	
	/*usClickHandler = function(){ console.log("clicked 'us.'"); $("#subnav-us").toggle(); return false;}
	$("#us").bind('click', usClickHandler);*/
	
}

function contentClickEvent(clickObj){
	var theSpotId = PadDigits($(clickObj).data("id"), 4);
	var theGridspotXmlNode = $(XMLObject).find("griditem[id='"+theSpotId+"']").first();
	/* console.log("theGridspotXmlNode: "+theGridspotXmlNode); */
	var trayTarget = $(theGridspotXmlNode).attr("tray-target");

	if (trayTarget){
		if( $("#"+trayTarget).is(":hidden") ){
			$(".expanded-content").remove();
			openTray(trayTarget);
		}else{
			closeTray(trayTarget);
		}
		
	}
	else{
		expandContent(clickObj, theGridspotXmlNode);
	}
}

function expandContent(clickObj, theGridspotXmlNode){
	/* console.log("expanding content.  the xml node: "+theGridspotXmlNode); */
	setTimeout(function() { closeTray("all") }, 100);
	disableMobileScroll();
	
	$(".expanded-content").remove();
		
	var expandedContent = $("<div class='expanded-content'></div>");
	
	if(smallScreenModeEnabled){
		$(clickObj).parent().parent().parent().parent().parent().append(expandedContent);
	}else{
		$(clickObj).parent().parent().append(expandedContent);
	}
	
	$(expandedContent).hide();
	
	var theSpotId = PadDigits($(clickObj).data("id"), 4);
	var rowWidth = $(clickObj).parent().parent().width();
	var galleryImgUrls = new Array();
	var galleryImgNames = new Array();
	var videoUrls = new Array();
	var videoTitles = new Array();
	var videoWidths = new Array();
	var numSpotsAfterClickObj = $(clickObj).data("spots-left-in-row");
	var unRoundedExpWidth;
	var roundedExpWidth;
	var lightBoxLinkUrl;
	var isVideo = false;
	var itemLinkoutName;
	var itemLinkoutURL;
	
	var backgroundColor = $(theGridspotXmlNode).attr("category");
	var backgroundImg = $(theGridspotXmlNode).find('expanded').attr("src");
	var expandedImgWidth = parseInt($(theGridspotXmlNode).find('expanded').attr("width"));
	/* console.log("expanded image width: "+expandedImgWidth); */
	var fullImg = $(theGridspotXmlNode).find('full').attr("src");
	var fullImgTitle = $(theGridspotXmlNode).find('full').attr("title");
	
	$(theGridspotXmlNode).find('video').each(function(i, o){
		videoUrls[i] = $(o).find('url').text(); 
		videoWidths[i] = parseInt($(o).find('width').text()); 
		videoTitles[i]=$(o).find('title').text(); 
		});
	
	 
	$(theGridspotXmlNode).find('gallery').each(function(index, object){
		if (index == 0){
			galleryImgUrls.push( fullImg ); 
			if (fullImgTitle != ""){
				galleryImgNames.push( fullImgTitle );
			}else{
				galleryImgNames.push( "Image 1" );
			}
		}
		galleryImgUrls.push( $(object).attr('src') ); 
		galleryImgNames.push( $(object).attr('title') ); 
		});

	var itemClient = $(theGridspotXmlNode).find('client').text();
	var itemCampaign = $(theGridspotXmlNode).find('campaign').text();
	var itemAltTitle = $(theGridspotXmlNode).find('alt-title').text();
	var itemDescription = $(theGridspotXmlNode).find('description').text();
	$(theGridspotXmlNode).find('linkout').each(function(i, o){
		itemLinkoutName = $(o).find('name').text();
		itemLinkoutURL = $(o).find('url').text();
		});
	
	if(smallScreenModeEnabled){	
		$(expandedContent).height(window.innerHeight - (2*gutterWidthPx)); 
		$(expandedContent).css("top",window.pageYOffset);
	}else{ 
		$(expandedContent).height(rowHeightPx); 
		$(expandedContent).css("top", 0);
	}
	
	$(expandedContent).css("borderWidth", gutterWidthPx);
	
	var expandDirection;
	var animateDirection;
	var leftPos;
	var rightPos;
	
	if (videoUrls[0]){
		isVideo = true;
	}
	
	
	$(expandedContent).css("zIndex", 11);
	$(expandedContent).addClass("colordescrip_"+backgroundColor);
	
	var imageHolder = $("<div class='exp-content-holder'></div>");
	$(expandedContent).append(imageHolder);
	
	if(!smallScreenModeEnabled){
		$(imageHolder).height(rowHeightPx);
	}
	$(imageHolder).css("float", "left");
	
	$(imageHolder).css("marginLeft", colorCodeBorderWidth+"px");
	
	var stripe = $("<div class='exp-stripe'></div>");
	$(expandedContent).append(stripe);
	
	$(stripe).addClass("color-exp-stripe"+backgroundColor); 
	$(stripe).width(colorCodeBorderWidth);
	$(stripe).height("100%"); 

	if (isVideo && !smallScreenModeEnabled){
		//this is a video item
		/* console.log("is a video item!"); */
		expandedImgWidth = parseInt(videoWidths[0]);
		/* console.log("expandedImgWidth: "+ expandedImgWidth); */
		/* console.log("itemExpandedDescMinWidth: "+ itemExpandedDescMinWidth); */
		/* console.log("gridWidthPx: "+ gridWidthPx); */
		/* console.log("gutterWidthPx: "+ gutterWidthPx); */
		unRoundedExpWidth = (expandedImgWidth)+(itemExpandedDescMinWidth*gridWidthPx)+((itemExpandedDescMinWidth-1)*gutterWidthPx);
		/* console.log("unRoundedExpWidth: "+unRoundedExpWidth); */
		roundedExpWidth = roundUp(unRoundedExpWidth);
		
		var expandedVideoWidth = (expandedWidthsPxArray[expandedWidthsPxArray.length-1-itemExpandedDescMinWidth]);
			
		if (videoWidths[0] > expandedVideoWidth ){
			/* console.log("video width was over max. has been shortened to max. vid width: "+videoWidths[0]+", expandedVideoWidth: "+expandedVideoWidth); */
			$(imageHolder).css("width", expandedVideoWidth+"px");
			$(imageHolder).append('<iframe width="'+expandedVideoWidth+'" height="315" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>');
		}else{
			$(imageHolder).css("width", videoWidths[0]+"px");
			$(imageHolder).append('<iframe width="'+videoWidths[0]+'" height="315" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>');
		}
		
		
		$(imageHolder).children().eq(0).attr('src', videoUrls[0]);
	}
	else{
		// this is a print item or viewer is on a mobile device
		
		if (expandedImgWidth > expandedWidthsPxArray[expandedWidthsPxArray.length-1-itemExpandedDescMinWidth] ){
			/* console.log("image width was over max. has been shortened to max."); */
			expandedImgWidth = (expandedWidthsPxArray[expandedWidthsPxArray.length-1-itemExpandedDescMinWidth]);
		}
		
		if(smallScreenModeEnabled){
			//on mobile, use the 'full' image for the background of an expanded post
			$(imageHolder).css("backgroundImage", "url("+fullImg+")");
			/* $(imageHolder).css("backgroundSize", "cover"); */
			//on mobile, width of the image is half of the expanded container size (which fills the screen)
			$(imageHolder).width((window.innerWidth-(gutterWidthPx*2))/2);
		}else{
			//use the 'expanded' image for the background of an expanded post
			$(imageHolder).css("backgroundImage", "url("+backgroundImg+")");
			//on desktop, the width of the expanded image's holder is equal to the correct native width of the image inside it
			$(imageHolder).width(expandedImgWidth);
		}
		
		/* console.log("expandedImgWidth: "+typeof expandedImgWidth); */
		/* console.log("itemExpandedDescMinWidth: "+typeof itemExpandedDescMinWidth); */
		/* console.log("gridWidthPx: "+typeof gridWidthPx); */
		unRoundedExpWidth = (expandedImgWidth)+(itemExpandedDescMinWidth*gridWidthPx)+((itemExpandedDescMinWidth-1)*gutterWidthPx);
		roundedExpWidth = roundUp(unRoundedExpWidth);
        
        var lightboxLink = $("<div></div>");
        $(imageHolder).append(lightboxLink);
        
        $(lightboxLink).addClass("lightbox-link");
        if(smallScreenModeEnabled){
			$(lightboxLink).css("left", (((window.innerWidth-(gutterWidthPx*2))/2)-100)/2 );
	        $(lightboxLink).css("top", ((window.innerHeight - (2*gutterWidthPx))-100)/2 );
		}else{
			$(lightboxLink).css("left", (expandedImgWidth-100)/2 );
	        $(lightboxLink).css("top", (rowHeightPx-100)/2 );
		}

        
        /* var lightboxLinkBackground; */
        $(lightboxLink).append("<div class='lightboxLinkBg colordescrip_"+backgroundColor+"' style='opacity:.8;'></div>");
        if (isVideo){
	        $(lightboxLink).append("<div class='lightboxVidLinkIcon'></div>");
        }else{
	        $(lightboxLink).append("<div class='lightboxLinkIcon'></div>");
        }
        if(smallScreenModeEnabled && isVideo){
	        lightBoxLinkUrl = videoUrls[0];
        }else{
	        lightBoxLinkUrl = fullImg;
        }
	}
	
	/* console.log("expanded content width unrounded: "+unRoundedExpWidth); */
	/* console.log("expanded content width rounded: "+roundedExpWidth); */
	
	setTimeout(function() { 
		var infoAndLinkoutArray =  buildExpandedInfo(itemClient, itemCampaign, itemAltTitle, itemDescription, itemLinkoutName, itemLinkoutURL, backgroundColor, theSpotId, galleryImgUrls, galleryImgNames, videoUrls, videoTitles, videoWidths, expandedContent);
		var expandedInfo = $(infoAndLinkoutArray[0]);
		var linkoutObject = $(infoAndLinkoutArray[1]);
		$(expandedContent).append(expandedInfo);
		$(expandedContent).append(linkoutObject);
	
		if(smallScreenModeEnabled){
			$(expandedInfo).height($(expandedContent).height() - $(linkoutObject).height());
			$(expandedInfo).width( ((window.innerWidth-(gutterWidthPx*2))/2)-5 );
			$(linkoutObject).width( ((window.innerWidth-(gutterWidthPx*2))/2)-colorCodeBorderWidth );
		}else{
			$(expandedInfo).height(rowHeightPx - 26);
			/* $(expandedInfo).width((roundedExpWidth-expandedImgWidth-colorCodeBorderWidth-2)); */
			$(expandedInfo).width(($(expandedContent).width()-$(imageHolder).width()-colorCodeBorderWidth-2));
			$(linkoutObject).width( roundedExpWidth - $(imageHolder).width() -colorCodeBorderWidth );
			/*alert("roundedExpWidth: "+roundedExpWidth);
			alert("expandedImgWidth: "+expandedImgWidth);
			alert("$(expandedInfo).width(): "+$(expandedInfo).width());*/
		}	
		
		$( "#tabs" ).tabs();
	 }, 100);
	
	

    if(smallScreenModeEnabled){
	    $(expandedContent).width(window.innerWidth-(gutterWidthPx*2));
	    
	    // INITIALIZE EXPANDED CONTENT SCROLLING FOR MOBILE DEVICES
	    setTimeout(function() { $('.item-expand-info').jScrollPane({showArrows: false, verticalGutter:0, contentWidth:((window.innerWidth-(gutterWidthPx*2))/2)-5 }); }, 500);

    }else{
	    $(expandedContent).width(roundedExpWidth);
		if (roundedExpWidth <= ((numSpotsAfterClickObj*gridWidthPx)+((numSpotsAfterClickObj-1)*gutterWidthPx)) ){
			/* expandDirection = "right"; */
			animateDirection = "left";
			leftPos = ($(clickObj).position().left + $(clickObj).parent().position().left - gutterWidthPx);
			if ((leftPos + roundedExpWidth) > rowWidth){
				leftPos = rowWidth - roundedExpWidth - (2*gutterWidthPx);
			}
			$(expandedContent).css("left", leftPos);
			/* console.log("expand left"); */
		}
		else{
			/* expandDirection = "left"; */
			animateDirection = "right";
			rightPos = ( rowWidth - ( $(clickObj).position().left + $(clickObj).width() + $(clickObj).parent().position().left + colorCodeBorderWidth) - gutterWidthPx );
			if ((rightPos + roundedExpWidth) > rowWidth){
				rightPos = rowWidth - roundedExpWidth - gutterWidthPx;
			}
			$(expandedContent).css("right", rightPos);
			/* console.log("expand right"); */
		}
	}

	
	var theCloser = $("<div class='expand-closer'></div>");
	setTimeout(function() { $(expandedContent).append(theCloser); }, 101);
	
	$(theCloser).click(function() {
		$(this).parent().remove();
		/* alert("closer click") */;
		enableMobileScroll();
	});
	
	setTimeout(function() { $(imageHolder).click(function(){ 
		closeTray("all"); 
		openLightbox(lightBoxLinkUrl, theSpotId, backgroundColor, isVideo); 
		}) 
	}, 100);
	
	
	
	$(expandedContent).show("slide", { direction: animateDirection }, 200);
}

function buildExpandedInfo(itemClient, itemCampaign, itemAltTitle, itemDescription, itemLinkoutName, itemLinkoutURL, color, theSpotId, galleryImgUrls, galleryImgNames, videoUrls, videoTitles, videoWidths, expandedContent){
	
	/* console.log("itemLinkoutName: "+itemLinkoutName); */
	
	var theContentToReturn = " "; 
	var linkoutToReturn = "";
	
	theContentToReturn += '<div class="item-expand-info">';
		theContentToReturn += '<div class="item-expand-title">';
		if (itemClient && itemClient!="" && itemClient !=" "){
			theContentToReturn += '<h3>client:</h3><h2>'+itemClient+'</h2>';
		}
		if (itemCampaign && itemCampaign!="" && itemCampaign !=" "){
			theContentToReturn += '<h3>campaign:</h3><h2>'+itemCampaign+'</h2>';
		}
		if (itemAltTitle){
			theContentToReturn += '<h2>'+itemAltTitle+'</h2>';
		}
		theContentToReturn += '</div>';
		
		//if there are several images OR several videos for this campaign
		if (galleryImgUrls[1] || videoUrls[1]){
			theContentToReturn += '<div id="tabs">';
				theContentToReturn += '<ul>';
				theContentToReturn += '	<li class="colordescrip_'+color+'"><a href="#tabs-1">Details</a></li>';
				if (videoUrls[1]){
					theContentToReturn += '	<li class="colordescrip_'+color+'"><a href="#tabs-2">All Videos</a></li>';
				}else{
					theContentToReturn += '	<li class="colordescrip_'+color+'"><a href="#tabs-2">All Images</a></li>';
				}
				
				theContentToReturn += '</ul>';
				theContentToReturn += '<div id="tabs-1">';
					theContentToReturn += '	<p>'+itemDescription+'</p>';
				theContentToReturn += '</div>';
				theContentToReturn += '<div id="tabs-2">';
					/* theContentToReturn += '<p>'; */
					for (i=0; i < (galleryImgUrls.length); i++) { 
						if (i==0){}
					    theContentToReturn += '<a href="#" class="exp-img-link" onclick="openLightbox(\''+galleryImgUrls[i]+'\', \''+theSpotId+'\', \''+color+'\', false); return false">';
					    theContentToReturn += galleryImgNames[i];
					    theContentToReturn += '</a>';
					    if( i != galleryImgUrls.length - 1){
						    theContentToReturn += '<div class="exp-link-divider"></div>';
					    }
					}
					for (i=0; i < (videoUrls.length); i++) { 
					    theContentToReturn += '<a href="#" class="exp-vid-link" onclick="swapVideo(\''+videoUrls[i]+'\', true); return false">';
					    theContentToReturn += videoTitles[i];
					    theContentToReturn += '</a>';
					    if( i != videoUrls.length - 1){
						    theContentToReturn += '<div class="exp-link-divider"></div>';
					    }
					}
					/* theContentToReturn += '</p>'; */
				theContentToReturn += '</div>';
			
			theContentToReturn += '</div>';
		} else{
			theContentToReturn += '	<div class="no-tabs">'+itemDescription+'</div>';
		}
		if  (itemLinkoutURL){
			linkoutToReturn += '<div id="linkout-container"><a href="'+itemLinkoutURL+'" target="_blank">'+itemLinkoutName+'</a></div>';
		}
	theContentToReturn += '</div>';

	return [theContentToReturn,linkoutToReturn];

}



function openLightbox(contentUrl, theSpotId, backgroundColor, isVideo){
	if (smallScreenModeEnabled && isVideo){
		window.open(contentUrl, "_blank");
	}else{
		var thePlayer;
		if (isVideo){
			thePlayer = "iframe";
		}else{
			thePlayer = "img";
		}
		
		$('.expanded-content .hidden-gallery-link').remove();
		Shadowbox.clearCache(); 
		
		if (!isVideo){
			var lightboxGalleryImgs = new Array();
			
			$(XMLObject).find("griditem[id='"+theSpotId+"']").each(function(){
				$(this).find('full').each(function(index, object){lightboxGalleryImgs.push( $(this).attr('src') ) });
				$(this).find('gallery').each(function(index, object){lightboxGalleryImgs.push( $(this).attr('src') ) });
			});
			
			
			var i=0;
			for (i=0; i < (lightboxGalleryImgs.length); i++) { 
				/* console.log("lightboxGalleryImgs[i]: "+lightboxGalleryImgs[i]); */
				/* console.log("contentUrl: "+contentUrl); */
				if (lightboxGalleryImgs[i] != contentUrl){
					$('.expanded-content').append('<a href="'+lightboxGalleryImgs[i]+'" class="hidden-gallery-link"></a>');
				} 
			} 
		}	
			Shadowbox.setup("a.hidden-gallery-link", {
		        gallery:            "campaign"+theSpotId
		    });
		
		
		$("#sb-container").removeClass();
		$("#sb-container").addClass("sb_color_"+backgroundColor);
		Shadowbox.open({
	        content:  contentUrl,
	        gallery:  "campaign"+theSpotId,
	        player:   thePlayer,
	        options:  {initialHeight:100, initialWidth:100}
	    });
	}
}

function swapVideo(theUrl){
	if (smallScreenModeEnabled){
		window.open(theUrl, "_blank");
	}else{
		$(".exp-content-holder iframe").attr("src", theUrl);
	}
}



function openTray(trayId){
	/* console.log("open tray: "+trayId); */
	disableMobileScroll();
	disableiPadScroll();
	var windowWidth;
	var windowHeight;
	if (smallScreenModeEnabled){
		windowWidth = window.innerWidth;
		windowHeight = window.innerHeight;
	}else{
		windowWidth = $(window).width();
		windowHeight = $(window).height();
	}
	
	var sidebarWidth = $("#sidebar").width();
	
	if (trayIsOut){	
		$(".tray-container").hide();
		$('#'+trayId).width(trayOpenedWidth);
	}
	
	
	$('#'+trayId).show();	
	$('#'+trayId).css("borderRightWidth", gutterWidthPx);
	$('#'+trayId).css("borderTopWidth", gutterWidthPx);
	$('#'+trayId).css("borderBottomWidth", gutterWidthPx);
	$('#'+trayId+" .tray-inner").width(trayOpenedWidth);
	$('#'+trayId).height( windowHeight - (2*gutterWidthPx) );
	$('#'+trayId+" .tray-inner").height( windowHeight - (2*gutterWidthPx) );
	$('#'+trayId+" .scroll-area").height( windowHeight - (2*gutterWidthPx) -$('#'+trayId+" header").height() );
	/* $('#'+trayId).css("marginTop",gutterWidthPx); */
	
	if(smallScreenModeEnabled){
		$('#'+trayId).width(trayOpenedWidth);
		$('#'+trayId).css("left",gutterWidthPx);
		$('#'+trayId).css("top",window.pageYOffset+"px");
		trayCurrentWidth = trayOpenedWidth+(gutterWidthPx);
		trayIsOut = true;
	}else{
		if (isiPad){
			$('#'+trayId).css("top",window.pageYOffset+"px");
		}
		$('#'+trayId).css("left",sidebarWidth);
		if (!trayIsOut){
			/* console.log("starting tray opening animation"); */
			trayIsAnimating = true;
			$('#'+trayId).width(0);
			$('#'+trayId).stop().animate({
				width: trayOpenedWidth,
				left: sidebarWidth
				}, trayAnimSpeed, function() {
				$('#'+trayId).show();
				trayCurrentWidth = trayOpenedWidth+(gutterWidthPx);
				trayIsOut = true;
				trayIsAnimating = false;
				/* console.log("tray opening animation finished."); */
			});	
	
			$('#main').stop().animate({
				marginLeft: sidebarWidth+trayOpenedWidth+gutterWidthPx,
				width: windowWidth - (sidebarWidth + trayOpenedWidth + gutterWidthPx)
				}, trayAnimSpeed, function() {
				/* console.log("grid right sliding animation finished."); */
			});
		}else{/* console.log("tray is already out!"); */}
	}
	
	/* $('.scroll-area').jScrollPane({showArrows: true}); */
	$('.scroll-area').each(
		function()		{
			$(this).jScrollPane({ showArrows: true, verticalGutter:8 } );
			var api = $(this).data('jsp');
			var throttleTimeout;
			$(window).bind(
				'resize',
				function(){
					if ($.browser.msie) {
						// IE fires multiple resize events while you are dragging the browser window which
						// causes it to crash if you try to update the scrollpane on every one. So we need
						// to throttle it to fire a maximum of once every 50 milliseconds...
						if (!throttleTimeout) {
							throttleTimeout = setTimeout(
								function(){
									api.reinitialise();
									throttleTimeout = null;
								},
								50
							);
						}
					} else {
						api.reinitialise();
					}
				}
			);
		}
	)
	
	$('#'+trayId+" .closer").click( function(){
		closeTray(trayId);
		enableMobileScroll();
	} );
	
	/* console.log("open tray function finished."); */
}


function closeTray(trayId){
	/* console.log("close tray: "+trayId); */
	/* enableMobileScroll(); */
	var sidebarWidth = $("#sidebar").width();
	
	var windowWidth;
	if (smallScreenModeEnabled){
		windowWidth = window.innerWidth;
	}else{
		windowWidth = $(window).width();
	}
	
	var whatToClose;
	$(".subnav_item").removeClass("active");
	
	if (trayId = "all"){
		whatToClose = ".tray-container";
	}else{
		whatToClose = '#'+trayId;
	}
	
	if(smallScreenModeEnabled){
		$(whatToClose).width(0);
		trayIsOut = false;
		trayCurrentWidth = 0;
		$(whatToClose).hide();
		$(whatToClose).css("left", sidebarWidth);
	}else{
		/* console.log("starting closing animation: "+whatToClose); */
		trayIsAnimating = true;
		$(whatToClose).stop().animate({
				width: 0,
				left: sidebarWidth-gutterWidthPx
				}, trayAnimSpeed, function() {
				trayIsOut = false;
				trayCurrentWidth = 0;
				$(this).hide();
				$(this).css("left", sidebarWidth);
				/* console.log("closing finished, tray hidden."); */
				trayIsAnimating = false;
			});	
			
		$('#main').stop().animate({
			marginLeft: sidebarWidth,
			width: windowWidth - (sidebarWidth)
			}, trayAnimSpeed, function() {
			/* console.log("main slide back to left finished"); */
		});
		enableiPadScroll();
	}
	/* console.log("close tray function finished."); */
}


function enableSmallScreenMode(){
	gutterWidthPx = 10;
	smallScreenModeEnabled = true;
	largeContentMinWidth = 2;
	largeContentMaxWidth = 2;
	sidebarMinWidth = 104;
	trayOpenedWidth = (window.innerWidth - (2*gutterWidthPx));
	rowHeightPx = gridWidthPx;
	$("#sidebar a").css("marginRight", gutterWidthPx);
	$("#sidebar a").css("paddingRight", gutterWidthPx);
}







var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();
var delay2 = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();


function PadDigits(n, totalDigits) { 
	n = n.toString(); 
	var pd = ''; 
	if (totalDigits > n.length) { 
		for (i=0; i < (totalDigits-n.length); i++) { 
		    pd += '0'; 
		} 
	} 
	return pd + n.toString(); 
}

function roundUp(inputNum){
	var outputNum = 0;
	var i = 0;
	while(outputNum < inputNum){
		outputNum = expandedWidthsPxArray[i];
		if (i == (expandedWidthsPxArray.length - 1)){break}
		i++;
	}
	return outputNum;
}


function detectIPadOrientation () {  
    if ( window.orientation == 0 ) {  
		return "portrait";  
    }  
    else if ( window.orientation == 90 ) {  
		return "landscape";  
    }  
    else if ( window.orientation == -90 ) {  
		return "landscape";   
    }  
    else if ( window.orientation == 180 ) {  
		return "portrait";   
    }  
 }
 
function fixShadowBoxForMobile(){ 
  if (isiPad || smallScreenModeEnabled){
  	disableMobileScroll();
  	disableiPadScroll();
    $("#sb-container").css("position","absolute"); 
    $("#sb-container").css("top",window.pageYOffset+"px"); 
  } 
} 

function enableMobileScroll(state) {
    if (smallScreenModeEnabled){
	    scrollIsEnabled = true;
	}
}
function disableMobileScroll() {
	if (smallScreenModeEnabled){
		scrollIsEnabled = false;
	}
}
function enableiPadScroll(state) {
    if (isiPad){
	    scrollIsEnabled = true;
	}
}
function disableiPadScroll() {
	if (isiPad){
		scrollIsEnabled = false;
	}
}

document.ontouchmove = function(e) {
    if(!scrollIsEnabled){
	    e.preventDefault();
	    e.stopPropagation();
    }
};



function detectSmallScreen(){
	if (Modernizr.touch == true && screen.width >= 768){
		//enable iPad mode for other tablets besides iPAd
		//console.log("enabling iPad mode because other tablet is detected.");
		isiPad = true;
	}
	
	if (isiPad == true){
		//console.log("is ipad.  removing hover class.");
		$("body").removeClass("hover-enabled");
	}
	
	if (screen.width < 768){
		//console.log("is small screen.  removing hover class.");
		loadjscssfile("css/smallscreen.css", "css") //// load and add .css file
		$("body").removeClass("hover-enabled");
		return true;
	}else{
		return screen.width;
	}
}


function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}


function loadjscssfile(filename, filetype){
	/* console.log(filename); */
	/* console.log(filetype); */
	if (filetype=="js"){ //if filename is a external JavaScript file
		var fileref=document.createElement('script');
		fileref.setAttribute("type","text/javascript");
		fileref.setAttribute("src", filename);
	}
	else if (filetype=="css"){ //if filename is an external CSS file
		var fileref=document.createElement("link");
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("href", filename);
	}
	if (typeof fileref!="undefined"){
		document.getElementsByTagName("head")[0].appendChild(fileref);
	}
}

