function ScrollTarget (selector) {
	this.selector = selector;
	this.init();
	this.active = true;
	this.pause = false;
	this.constantScroll = true;
	this.lastMsec = undefined;
	this.fastFactor = 1;
}
ScrollTarget.prototype.init = function () {
	this.window = $(this.selector);
	this.scrollPosition = this.window.scrollLeft ();
	this.adjustWidth = parseInt (this.window.parent ().css ("width"));
	this.child = this.window.children ().first ();
	this.grandchild = this.child.children ().first ();
	this.grandchildWidth = parseInt (this.grandchild.css ("width"));
	this.pixelsRemainder = 0;
}
ScrollTarget.prototype.scrollLeft = function (elapsedMsec) {
	if (this.pause) {
		this.init ()
		this.pause = false;
		return;
	}
	var nowMsec = new Date().getTime();
	if (this.lastMsec != undefined) {
		//elapsedMsec = nowMsec = this.lastMsec;
		this.lastMsec = nowMsec;
	}
	var stepMoveFloat = (this.pixelsPerMsec * this.fastFactor) * elapsedMsec;
	var stepMove = stepMoveFloat | 0;
	this.pixelsRemainder += (stepMoveFloat - stepMove);
	if (this.pixelsRemainder > 1)  {
		stepMove += 1;
		this.pixelsRemainder -= 1;
	} else if (this.pixelsRemainder < -1)  {
		stepMove -= 1;
		this.pixelsRemainder += 1;
	}
	if (stepMove == 0)
		return;

	this.scrollPosition += stepMove;
	this.window.scrollLeft (this.scrollPosition);
	if (this.scrollPosition > this.adjustWidth &&
		this.scrollPosition > this.grandchildWidth) {
		this.moveChildToEnd ();
	} else if (this.scrollPosition < 0) {
		this.moveChildToBeg ();
	}
}

ScrollTarget.prototype.moveChildToEnd = function () {
	this.grandchild.detach ().appendTo (this.child);
	this.scrollPosition -= this.grandchildWidth;
	this.window.scrollLeft (this.scrollPosition);
		
	this.grandchild = this.child.children ().first ();
	this.grandchildWidth = parseInt (this.grandchild.css ("width"));
}

ScrollTarget.prototype.moveChildToBeg = function () {
	this.grandchild = this.child.children ().last ();
	this.grandchildWidth = parseInt (this.grandchild.css ("width"));

	this.grandchild.detach ().prependTo (this.child);
	this.scrollPosition += this.grandchildWidth;
	this.window.scrollLeft (this.scrollPosition);
}

var ClientScrollDelay =8;
var ClientScrollAdj = 1;
var WordsScrollDelay = 7.5;
var WordsScrollAdj = 1;
var MaxDelay = 30;

var scrollControl = undefined;

function isiPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1) ||
        (navigator.platform.indexOf("iPad") != -1)
    );
}

function ScrollControl () {
	this.intervalDelay = ClientScrollDelay; // Align on client for smooth
	if (isiPhone ()) {
		this.intervalDelay *= 10;
		MaxDelay = 80;
	}
	
	this.target = new Array ();
	this.lastMsec = undefined;
	this.timesCalled = 0;
	this.elapsedCalled = 0;
	this.adjustment = 1.0;
	this.calibrateSpeed = true;
	this.calibrations = 0;
	this.scrollArrows = false;
	this.scrollArrowsTimeout = 0;
	this.renewScrollArrows = false;
	this.scrollArrowsVisMsec = 1000;
	this.scrollPageX = 0;
	this.scrollPageY = 0;
	this.mouseOnArrows = false;
}

ScrollControl.prototype.enableScrollArrows = function () {
	$("#clientScroll").mousemove (function (event) {
			scrollControl.showScrollArrows (event);
	});
}
ScrollControl.prototype.disableScrollArrows = function () {
	$("#clientScroll").unbind ("mousemove");
	this.hideScrollArrows ();
}


ScrollControl.prototype.setScrollArrows = function (show) {
	if (show == this.scrollArrows) {
		if (show == true) {
			this.renewScrollArrows = true;
		}
		return;
	}
	if (show == false && this.mouseOnArrows) {
		return;
	}
	
	this.scrollArrows = show;
	var visibilitySetting = show ? "visible" : "hidden";
	$("#scrollLeft, #scrollRight").css ("visibility", visibilitySetting);
	if (show == true) {
		$("#scrollLeft, #scrollRight").hover (
				function (event) {
					// mouseEnter - Keep scroll arrows enabled
					if (scrollControl.scrollArrowsTimeout) {
						clearTimeout (scrollControl.scrollArrowsTimeout);
						scrollControl.scrollArrowsTimeout = 0;
					} 
					scrollControl.renewScrollArrows = false;
					$("#scrollLeft, #scrollRight").css ("visibility", "visible");
					scrollControl.scrollArrows = true;
					scrollControl.mouseOnArrows = true;
					var direction = 1;
					if (event.target.id == "scrollLeft") {
						direction = -1;
					}
					scrollControl.target["#clientScroll"].fastFactor = 3 * direction;
				},
				function () {
					// mouseLeave - revert to timeout
					scrollControl.scrollArrowsTimeout = 
						setTimeout ("scrollControl.timeoutScrollArrows ()", scrollControl.scrollArrowsVisMsec);
					scrollControl.mouseOnArrows = false;
					scrollControl.target["#clientScroll"].fastFactor = 1;
				}
		);
		this.scrollArrowsTimeout = 
			setTimeout ("scrollControl.timeoutScrollArrows ()", this.scrollArrowsVisMsec);
	}
}

ScrollControl.prototype.timeoutScrollArrows = function () {
	if (this.renewScrollArrows) {
		this.renewScrollArrows = false;
		this.scrollArrowsTimeout = 
			setTimeout ("scrollControl.timeoutScrollArrows ()", this.scrollArrowsVisMsec);
		
	} else {
		if (this.mouseOnArrows)
			return;
		this.hideScrollArrows ();
	}
}

ScrollControl.prototype.showScrollArrows = function (event) {
	if (event != undefined) {
		if (this.scrollPageX == event.pageX &&
			this.scrollPageY == event.pageY)
			return;
		this.scrollPageX = event.pageX;
		this.scrollPageY = event.pageY;
	}
	this.setScrollArrows (true);
}

ScrollControl.prototype.hideScrollArrows = function () {
	if (this.scrollArrowsTimeout) {
		clearTimeout (this.scrollArrowsTimeout);
		this.scrollArrowsTimeout = 0;
	}
	this.setScrollArrows (false);
}

ScrollControl.prototype.addTarget = function (selector, active) {
	var target = new ScrollTarget (selector);
	target.active = active;
	if (selector == "#clientScroll") {
		target.pixelsPerMsec = ClientScrollAdj/ClientScrollDelay;
	} else {
		target.pixelsPerMsec = WordsScrollAdj/WordsScrollDelay;
	}
	this.target[selector] = target;
	this.id = undefined; 
	//this.lastMsec = undefined;
}
ScrollControl.prototype.startScroll = function () {
	if (this.id != undefined) {
		this.stopScroll ();
	}
	this.id = setInterval (function () {
		if (scrollControl.calibrateSpeed)
			scrollControl.calibrate ();
		for (selector in scrollControl.target) {
			if (scrollControl.target[selector].active)
				scrollControl.target[selector].scrollLeft (scrollControl.intervalDelay);
		}
	}, this.intervalDelay);
}
ScrollControl.prototype.calibrate = function () {
	if (this.intervalDelay == MaxDelay)
		return;
	
	this.timesCalled += 1;
	var startCalibrate = 5;
	var checkClibrate = 20;
	if (this.timesCalled == startCalibrate) {
		// Allow the first 30 calls for startup
		this.lastMsec = new Date().getTime();
		this.elapsedCalled = 0;
	} else if (this.timesCalled > startCalibrate) {
		this.elapsedCalled += 1;
	}
	if (this.elapsedCalled > checkClibrate) {
		this.calibrations += 1;
		var nowMsec = new Date().getTime();
		var elapsedMsec = nowMsec - this.lastMsec;
		var avgIntervalDelay = elapsedMsec / this.elapsedCalled;
		var lag = avgIntervalDelay / this.intervalDelay; 
		// Is it keeping up?
		this.lastMsec = undefined;
		this.timesCalled = 0;
		this.elapsedCalled = 0;

		if (lag > 1.25) {
			this.stopScroll ();
			if (!jQuery.browser.msie) 
				console.info ("avgIntervalDelay " + avgIntervalDelay + " intervalDelay " + this.intervalDelay + " lag " + lag);
			this.intervalDelay *= 1.25;// lag; //1.5;
			this.intervalDelay = Math.min(this.intervalDelay, MaxDelay);
			this.startScroll ();
		} 
		if (this.calibrations > 4)
			this.calibrateSpeed = false;
	}

}
ScrollControl.prototype.stopScroll = function () {
	clearInterval (this.id);
	this.id = undefined;
}
ScrollControl.prototype.pauseScroll = function (selector) {
	if (this.id != undefined) {
		this.stopScroll ();
	}
	if (selector == "#clientScroll") {
		this.disableScrollArrows ();
	}
	this.target[selector].active = false;
	this.target[selector].pause = true;
	this.startScroll ();
	
	if (this.target["#clientScroll"].active) {
		this.enableScrollArrows ();
	}
}
ScrollControl.prototype.contScroll = function (selector) {
	if (this.id != undefined) {
		this.stopScroll ();
	}
	this.target[selector].active = true;
	this.startScroll ();
	if (selector == "#clientScroll") {
		this.enableScrollArrows ();
	}
}

function startPage () {		
	var clientRef = 0;
	if (clientWebTag != "") {
		if (isNaN(clientWebTag)) {
			// Not a number must be a name
			for (var ii = 0; ii < clients.length; ii++) {
				var client = clients[ii];
				if (client.webTag == clientWebTag) {
					clientRef = client.clientRef;
					break;
				}
			}
		} else {
			if (clientsByRef[clientWebTag] != undefined) 
				clientRef = clientWebTag;
		}
	}
	
	scrollControl = new ScrollControl ();
	scrollControl.addTarget ("#clientScroll", clientRef == 0);
	scrollControl.addTarget ("#wordsScroll", true);
	//if (!jQuery.browser.msie) 
		scrollControl.startScroll ();
	
	if (clientRef == 0) {
		splashPage ();
	} else {
		$("#splashPanel").css ("visibility","hidden");
		showClientSpread (clientRef, true);
		$("#wordsContent").css ("opacity", 1.0);
	}
	setClientClick ();
}


function splashPage () {
	$("#dgiTagline").animate (
			{opacity: 1},
			2000,
			function () {
				$("#splashPanel").animate (
						{opacity: 0},
						1500,
						function () {
							$("#splashPanel").remove ();
							scrollControl.enableScrollArrows ();
							scrollControl.startScroll ();
						}
					);
			}
		);	
}

function getClientTagImage (client) {
	var path = "\"images/Client_Work/" + client.tag.file + "\"";
	return "<div id='clientTagSpread' class='clientTag' style='background-image: url(" + path + ")'></div>"; 
}

function basename(path) {
    return path.replace(/\\/g,'/').replace( /.*\//, '' );
}
 
function dirname(path) {
    return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');;
}

function setMenuTargets () {
	var dir = dirname (window.location.pathname);
	$("#topToolbar .topMenu").each(function(){
		toolbar = $(this).parent ();
		menu = $(this);
		var inactive = $(this).css('background-image').match(/InActive/);
		var resources = false; //$(this).css('background-image').match(/Resources/);
		var home = $(this).css('background-image').match(/Home/);
		if (inactive && !resources) {
			href = jQuery("<a href=\"./" + $(this).attr("dgiTgt") + "\"></a>").appendTo (toolbar);
			menu.detach ().appendTo (href);
		}
		if (!inactive && home) {
			$("#homeMenu").click (function () {
				if ($("#clientContent").css ("opacity") == 0)
					resumeClientScroll ();
			});
		}
	});
}

function loadInteriors (client, clientRef) {
	var clientSpread0 = $("#clientSpread0");
	for (var ii = 0; ii < client.interior.length; ii++) {
		var interior = clientSpread0.clone ().attr ("id", "clientSpread" + (ii + 1));
		interior.css({opacity: 0});
		var clientJpg = client.interior[ii];
		var path = "\"images/Client_Work/" + clientJpg.file + "\"";
		var boxWidth = clientJpg.width + 20;
		var boxHeight = clientJpg.height + 20;
		var leftWidth = (boxWidth / 2) | 0; // cast as integer bitwise OR
		var rightWidth = boxWidth - leftWidth;
		$(".clientSpreadCenter", interior).css ("width", boxWidth);
		$(".leftShadow", interior).css ("width", leftWidth);
		$(".rightShadow", interior).css ("width", rightWidth);
		$(".clientCover", interior).css ("width", clientJpg.width)
		.css ("background-image", "url(" + path + ")");
		interior.appendTo ("#clientSpread");
	}	
}

function changeClientSpread (tgtThumbId) {
	var activeThumbId = $("#clientThumbnailTray").attr("active_thumb_id");
	if (activeThumbId == undefined)
		activeThumbId = 0
	if (activeThumbId == tgtThumbId)
		return;
	var activeClientSpread = $("#clientSpread" + activeThumbId);
	var tgtClientSpread = $("#clientSpread" + tgtThumbId);
	if (activeClientSpread.css("opacity") != 1) // In transition
		return;
	
	tgtClientSpread.animate (
			{opacity: 1},
			300);
	activeClientSpread.animate (
			{opacity: 0},
			300);
	
	$("#clientThumbnailTray").attr("active_thumb_id", tgtThumbId);
}


function getCumThumbWidth () {
	var cumThumbWidth = 0;
	for (var ii = 0; ii < thumbInfo.length; ii++) 
		cumThumbWidth += thumbInfo[ii].width + thumbInfo[ii].shadow + thumbInfo[ii].margin;
	return cumThumbWidth;
}

SmallThumb = 24;
LargeThumb = 38;

function getImageThumbWithShadow (info) {
	var boxWidth = info.width + info.shadow;
	var boxHeight = info.height + info.shadow;
	var leftWidth = (boxWidth / 2) | 0; // cast as integer bitwise OR
	var rightWidth = boxWidth - leftWidth;
	var marginLeft = info.margin ? "margin-left: " + info.margin + "px;" : "";
	var largeSmallDiff = (LargeThumb - SmallThumb) / 2;
	var marginTop = boxHeight < LargeThumb + info.shadow ? "margin-top:" + largeSmallDiff + "px;" : "";
	var focused = boxHeight == LargeThumb + info.shadow ? "Focused" : "";
	var html = "<div class='clientThumbnail' style='width:" + boxWidth + "px;height:" + boxHeight + "px;" + marginLeft + marginTop + "'>";
	html += "<div class='leftShadowThumb" + focused + "' style='width:" + leftWidth + "px;height:" + boxHeight + "px;'></div>";
	html += "<div class='rightShadowThumb" + focused + "' style='width:" + rightWidth + "px;height:" + boxHeight + "px'></div>";
	html += "<div class='clientThumbnailImg' style='width:" + info.width + "px;height:" + info.height + "px;'>"+info.html+"</div>";
	html += "</div>";
	return html;
}

function adjustThumbnail (client, thumbId, size) {
	var clientJpg = thumbId == 0 ? client.cover : client.interior[thumbId-1];
	var oldThumbInfo = thumbInfo[thumbId];
	thumbInfo[thumbId] = clientJpg.getImgHeightScaled (size);
	thumbInfo[thumbId].margin = oldThumbInfo.margin;
	thumbInfo[thumbId].shadow = oldThumbInfo.shadow;
}

function setThumbnailEvents (client, clientRef) {
	$( ".clientThumbFrame" ).click(
		function( event ){
			var tgtThumbId = $(this).attr("thumb_id");
			changeClientSpread (tgtThumbId);
		}
	);
}

function loadThumbnails (client, clientRef) {
	thumbInfo = null;
	if (client.interior.length == 0)
		return;
	thumbInfo = Array (client.interior.length+1);
	thumbInfo[0] = client.cover.getImgHeightScaled (LargeThumb);
	thumbInfo[0].shadow = 4;
	thumbInfo[0].margin = 0;
	for (var ii = 0; ii < client.interior.length; ii++) { 
		thumbInfo[ii+1] = client.interior[ii].getImgHeightScaled (LargeThumb);
		thumbInfo[ii+1].shadow = 4;
		thumbInfo[ii+1].margin = 12;
	}
		
	tray = jQuery("<div id='clientThumbnailTray' style='width:" + getCumThumbWidth () +"px;'></div>")
		.appendTo ("#clientThumbnailSpread");
	tray.attr ("active_thumb_id", "0");

	for (var ii = 0; ii < thumbInfo.length; ii++) {
		var div = "<div id='thumb_" + ii + "' class='clientThumbFrame'>" +
			getImageThumbWithShadow (thumbInfo[ii]) +
			"</div>";
		jQuery(div).appendTo ("#clientThumbnailTray").attr("thumb_id",ii);
	}
}

function resumeClientScroll () {
	var clientRef = $("#clientSpread").attr ("client_ref");
	var client = clientsByRef[clientRef];
	var activeThumbId = $("#clientThumbnailTray").attr("active_thumb_id"); 
	if (activeThumbId != undefined && activeThumbId != 0)
		changeClientSpread (0);

	$( ".clientThumbFrame" ).unbind();
	$("#resume").unbind ();
	$("#resume").animate({
	    opacity: 0
  		}, 1000);

	$("#clientThumbnailSpread").animate({
	    opacity: 0
  		}, 1000, function() {
			$("#clientThumbnailSpread").html ("");
  	});
	
	$("#clientTagSpread").animate({
	    opacity: 0
	  	}, 1000, function() {
	  	$("#clientSpread").css("z-index", 19);
		$("#clientContent").animate({
		    opacity: 1.0
		  	}, 1000, function() {
		  		$("#clientSpread").css("visibility", "hidden");
		  		$("#clientSpread").html ("");
		  		$("#clientSpread").removeAttr ("client_ref");
		  		scrollControl.contScroll ("#clientScroll");
		});
	});

}

function showClientSpread (clientRef, immediate) {
	if ($("#clientSpread").attr ("client_ref"))
		return;

	$("#clientSpread").attr ("client_ref", clientRef);
	
	scrollControl.pauseScroll ("#clientScroll");
	
	var scrollingCover = $("#" + clientRef);
	var clientSpread = $("#clientSpread")
	var clientSpread0 = jQuery ("<div id ='clientSpread0' class='clientSpreadFrame'></div>").appendTo (clientSpread);
	var cover = scrollingCover.clone ().attr ("id", "").removeClass ("clientImage");
	cover.removeClass ("clientImage");
	$(".clientTagRolling", cover).remove ();
	var client = clientsByRef[clientRef];
	jQuery (getClientTagImage (client, 0)).appendTo (clientSpread).css({opacity: 0});
	cover.addClass ("clientSpreadCenter");
	cover.appendTo (clientSpread0);
	clientSpread.attr ("client_ref", clientRef);
	$("#resume").click (function () {
		if ($("#clientContent").css ("opacity") == 0)
			resumeClientScroll ();
	});
	loadInteriors (client, clientRef);
	loadThumbnails (client, clientRef);
	
	var clientScroll = $("#clientScroll")
	var leftPosition = scrollingCover.position ().left;
	var leftVisibleOffset = leftPosition - clientScroll.scrollLeft ();
		
	var targetLeftOffset = cover.offset ().left - clientSpread.offset ().left;

	var clientStrip = clientScroll.children ().first ();
	var scrollLeft = clientScroll.scrollLeft (); 
	while (scrollingCover.position ().left < targetLeftOffset) {
		var clientDiv = clientStrip.children ().last ();
		var clientWidth = parseInt (clientDiv.css ("width"));
		clientDiv.detach ().prependTo (clientStrip);
		scrollLeft += clientWidth;
		clientScroll.scrollLeft (scrollLeft);
	}

	var scrollLeft = clientScroll.scrollLeft ();
	scrollLeft += (leftVisibleOffset - targetLeftOffset);
	
	scrollSpeed = (Math.abs(leftVisibleOffset - targetLeftOffset) * ClientScrollDelay) / ClientScrollAdj;
	scrollSpeed /= 2;
	if (immediate)
		scrollSpeed = 0;
	$("#clientScroll").animate({
	    scrollLeft: scrollLeft
	  	}, scrollSpeed, function() {
	  		$("#clientSpread").css("visibility", "visible");
	  		var delay = immediate ? 0 : 1000;
			$("#clientContent").animate({
			    opacity: 0
			  	}, delay, function() {
			  		$("#clientSpread").css("z-index", 21);
			  		$("#resume").animate ({opacity: 1}, delay);
			  		setThumbnailEvents (client, clientRef);
			  		$("#clientThumbnailSpread").animate ({
			  			opacity: 1
			  			}, delay);
					$("#clientTagSpread").animate({opacity: 1.0}, delay);
			});
	  });
}

function setClientClick () {
	$("#clientScroll").click (function (e) {
		if ($("#clientSpread").attr ("client_ref"))
			return;
		var clientRef = 0;
	    var clicked = $(e.target);
	    if (clicked.hasClass ('clientCoverImg')) {
	    	clientRef = clicked.parent ().parent ().attr("id");
	    } else if (clicked.hasClass ('clientCover') ||
	    	clicked.hasClass ('leftShadow') ||
	    	clicked.hasClass ('rightShadow')) {
	    	clientRef = clicked.parent ().attr("id");
	    } else if (clicked.hasClass ('clientImage')) {
	    	clientRef = clicked.attr("id");
	    } else {
	    	console.info ('Clicked on: ' + clicked);
	    } 
	    if (clientRef != 0)
			showClientSpread (clientRef, false);
	});
	/*
	$(".clientImage").click (function () {
		if ($("#clientSpread").attr ("client_ref"))
			return;

		var clientRef = $(this).attr("id");
		showClientSpread (clientRef, false);
	});
	*/
}

function setSmallCover (clientSeq) {
	var client = clients[clientSeq];
	var info = client.small.getImgWidthScaled (SmallCoverMaxWidth);
	$("#smallCoverImg")
		.attr ("client_seq", clientSeq)
		.css ("width", info.width)
		.css ("height", info.height)
		.attr ("client_ref", client.clientRef)
		.html (info.html);
}8

function switchSmallCover (clientSeq) {
	var smallCover = $("#smallCoverImg");
	smallCover.fadeOut (100, function () {
		clientSeq += 1;
		if (clientSeq >= clients.length)
			clientSeq = 0;
		setSmallCover (clientSeq);
		smallCover.fadeIn (100, function () {
			setTimeout ("switchSmallCover ("+clientSeq+")",2000);
		});
	});
}

function loadSmallCover () {
	var div = "<div id='smallCoverFrame'>" +
		"<div id='smallCoverBottom'>" + 
		"<div id='smallCoverImg'>" + 
		"</div></div></div>"; 
	jQuery(div).appendTo ("#page");
	var startClientSeq = Math.floor(Math.random()*clients.length);
	setSmallCover (startClientSeq);
	switchSmallCover (startClientSeq);
	$("#smallCoverImg").click (
		function () {
		window.location.href = "./index.php?client=" + $(this).attr("client_ref");
	});
}


