
/************************************************************/
/************************************************************/
/************************************************************/

/* iPhone sniff */

var isiphone = false;
if ((navigator.userAgent.indexOf('AppleWebKit') != -1) && (navigator.userAgent.indexOf('Mobile') != -1)){
	var isiphone = true;
}

/* end sniff */


/****** get a random image ********/
var curPix;

var theImage, seenIt, chosenImage, imageLibrary, numberOfImages, newNumberOfImages;

/*****************
Get Some Pix
*****************/
/*if (!isiphone){
	var imageLibrary = new Array(
		"/images/spacer.gif"
	);
} else {
	*/var imageLibrary = new Array(
		"/images/splash/alberta_train_tall.jpg",
		"/images/splash/snow_road.jpg",
		"/images/splash/palm_shoot.jpg"
	);
/*}*/

var preloadImgs = function(){
	imagetoload1 = new Image();	
	imagetoload1.src = "images/tray_labelbg.png";
	imagetoload2 = new Image();	
	imagetoload2.src = "images/tray_bgright.png";	
	imagetoload3 = new Image();	
	imagetoload3.src = "images/tray_bgleft.png";	
	imagetoload4 = new Image();	
	imagetoload4.src = "images/beige_bg.png";
	imagetoload5 = new Image();	
	imagetoload5.src = "images/timeline.png";
}

/*****************
Let's Bake Some Cookies!
*****************/

function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	var ck = name+"="+value+expires+"; path=/";
	document.cookie = ck;
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i<ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name)
{
	createCookie(name,"",-1);
}

var seenIt = readCookie("justindamerimagesseen");

/**********
Pick Images
**********/

var pickAnImage = function(){
	if (seenIt.indexOf(imageLibrary.length+"t") != -1){
		seenIt = "0t,";
	}
	var chosenImage = Math.round(Math.random()*(imageLibrary.length-1));
	while (seenIt.indexOf(","+chosenImage) != -1){
		chosenImage = Math.round(Math.random()*(imageLibrary.length-1));
	}
	seenIt += ","+chosenImage;
	numberOfImages = parseInt(seenIt.slice(0,seenIt.indexOf("t")));
	newNumberOfImages = numberOfImages+1;
	seenIt = newNumberOfImages + seenIt.slice(seenIt.indexOf("t"));
	createCookie("justindamerimagesseen",seenIt,300);
	theImage = imageLibrary[chosenImage];
}


/******************************/
/*****detects and init*********/
//
var isIE = (navigator.appName.indexOf("Microsoft")!=-1);
var isMac = (navigator.userAgent.indexOf("Mac") != -1);
if (isIE && isMac){alert("The web browser you are using, Microsoft Internet Explorer Mac, is no longer supported by Microsoft. They recommend that you use Safari, which is already on your computer, or that you use Firefox. If you continue to use Internet Explorer Mac, you may experience technical difficulties on this website, among others.");}
var isFirefox = ((navigator.userAgent.indexOf("Firefox") != -1) || (navigator.userAgent.indexOf("Camino") != -1));
var winW, winH,theImgs,scrollContent;
var theImgsXList = new Array();
var currentImg = 0;
var dragging = false;
/**/
//IE 6 Flickering Image Fix
try {document.execCommand('BackgroundImageCache', false, true);} catch(e) {}

/*******/
var contentUrl = "";
var sourceP = "home";
var destP = "home";
var persistentCurrentProject = 0;

/********resize**********/
function winResize() {
	if (document.body){
		if (destP == "portfolio"){
			winW = (isIE) ? document.body.clientWidth : window.innerWidth;
			winH = (isIE) ? document.body.clientHeight : window.innerHeight;
			if (winH<=440){
				winH=440;
				document.getElementById("content").getElementsByTagName("h2")[0].style.bottom = "auto";
				document.getElementById("content").getElementsByTagName("h2")[0].style.top = "284px";
			} else {
				document.getElementById("content").getElementsByTagName("h2")[0].style.bottom = "138px";
				document.getElementById("content").getElementsByTagName("h2")[0].style.top = "auto";
			}
		
			if (theImgs && $("content").getElementsByTagName("div")[0]){
				var theW = 10;
				for (i=0;i<theImgs.length;i++){
					var curImg = theImgs[i];
					var imgW = curImg.name.slice(1,curImg.name.indexOf("y"));
					var imgH = curImg.name.slice(curImg.name.indexOf("y")+1);
					var centerAlignImg = function(){
						curImg.parentNode.style.verticalAlign = "middle";
						if (isIE) {
							curImg.parentNode.parentNode.style.top = "50%";
							curImg.parentNode.parentNode.style.height = "20px";
							curImg.parentNode.style.position = "absolute";
							curImg.parentNode.style.paddingLeft = 0;
							curImg.parentNode.style.paddingRight = 0;
							curImg.parentNode.style.left = 0;
							curImg.parentNode.style.top = (-1*(curImg.parentNode.clientHeight/2))-20+"px";
							$("content").style.overflowY = "hidden";
						}
					}
					var topAlignImg = function(){
						curImg.parentNode.style.verticalAlign = "top";
						if (isIE) {
							curImg.parentNode.parentNode.style.top = "auto";
							curImg.parentNode.parentNode.style.height = "auto";
							curImg.parentNode.style.position = "relative";
							curImg.parentNode.style.paddingLeft = "10px";
							curImg.parentNode.style.paddingRight = "10px";
							curImg.parentNode.style.left = "auto";
							curImg.parentNode.style.top = "auto";
						}	
					}
					if (imgW >= (winW-30)){
						curImg.style.width = winW-30+"px";
						curImg.style.height = (((winW-30)/imgW)*imgH)+"px";
						curImg.lowsrc = curImg.src;
						centerAlignImg();
					} else if (imgH > (winH-269)){
						//curImg.style.height = "92%";
						curImg.style.height = (winH-269)+"px"
						curImg.style.width = "auto";
						topAlignImg();
					} else {
						curImg.style.width = imgW+"px";
						curImg.style.height = imgH+"px";
						centerAlignImg();
					}
					if (curImg.clientWidth >= (winW-30)){
						curImg.style.width = winW-30+"px";
						curImg.style.height = (((winW-30)/imgW)*imgH)+"px";
						centerAlignImg();
					}
					if (curImg.clientHeight > (winH-269)){
						//curImg.style.height = "92%";
						curImg.style.height = (winH-269)+"px"
						curImg.style.width = "auto";
						topAlignImg();
					}
					if (curImg.parentNode.id == "noyscale"){
						curImg.style.width = imgW+"px";
						curImg.style.height = imgH+"px";
						if (imgW >= (winW-30)){
							curImg.style.width = winW-30+"px";
							curImg.style.height = (((winW-30)/imgW)*imgH)+"px";
							curImg.lowsrc = curImg.src;
							centerAlignImg();
						}
						if (curImg.clientWidth >= (winW-30)){
							curImg.style.width = winW-30+"px";
							curImg.style.height = (((winW-30)/imgW)*imgH)+"px";
							centerAlignImg();
						}
					} else if (curImg.parentNode.id == "noxscale"){
						curImg.style.width = imgW+"px";
						curImg.style.height = imgH+"px";
						if (imgH > (winH-269)){
							curImg.style.height = (winH-269)+"px"
							curImg.style.width = "auto";
							topAlignImg();
						}
						if (curImg.clientHeight > (winH-269)){
							curImg.style.height = (winH-269)+"px"
							curImg.style.width = "auto";
							topAlignImg();
						}
					} 
					theImgsXList[i]=curImg.clientWidth+20;
					theW+=curImg.clientWidth+15;
					if ($("content").getElementsByTagName("div")[0]){
						if (theW > $("content").getElementsByTagName("div")[0].clientWidth){
							$("content").getElementsByTagName("div")[0].style.width = theW+"px";
						} else {
							$("content").getElementsByTagName("div")[0].style.width = "100%";
						}
					}
				}
				if ($("content").getElementsByTagName("div")[0]){
					if ($("content").getElementsByTagName("div")[0].clientWidth > winW){
						document.getElementsBySelector("#scrollcontent div")[0].style.display = "block";
						$("content").style.textalign = "left";
					} else {
						document.getElementsBySelector("#scrollcontent div")[0].style.display = "none";
						$("content").style.textalign = "center";
					}
				}
			} else {
				try{document.getElementsBySelector("#scrollcontent div")[0].style.display = "none";} catch(e){}
			}
			updateScrollBars();
		} else {
			if (document.body.id == "homepage"){
				winW = (isIE) ? document.body.clientWidth : window.innerWidth;
				winH = (isIE) ? document.body.clientHeight : window.innerHeight;
				var imgRatio = $("bgimage").width/$("bgimage").height;
				var winRatio = winW/(winH-70);
				if (winRatio > imgRatio){
					$("bgimage").style.left = "0px";
					if ($("bgimage").style.width!="100%"){
						$("bgimage").style.width="100%";
						$("bgimage").style.height="auto";
					}
				} else {
					$("bgimage").style.height = winH-70+"px";
					$("bgimage").style.width="auto";
					$("bgimage").style.left=((winW-$("bgimage").width)/2)+"px";
				}
			}
		}
	}
}
window.onresize = function() {
	winResize();
}

/****************
Modify links to make them work w/ Ajax calls instead of going places
*****************/
/*function fixLinks(){
	for (i=0;i<document.links.length;i++){
		document.links[i].href = "#"+document.links[i].href;
	}
}*/


/*******onload**********/
Behaviour.addLoadEvent(function() {
	if(destP == "portfolio"){
		if (isFirefox){
			$("content").style.paddingBottom = "131px";
		}
		getPageFromAnchor();
		new Ajax.Updater('menucontent', "work.html", { method:'get', onComplete:generateLists});
		if (isFirefox){
			$("menupane").style.bottom = "-20px";
			$("menupane").style.height = "131px";
		}
	} else {
		if (document.body.id == "homepage"){
			bgImageLoader = new Image();
			bgImageLoader.onload = function(){
				var completed = 0;
				var onloadComplete = function(){
					if (completed < 1) {
						if (isIE){
							$("bgimage").src = bgImageLoader.lowsrc;
							$("bgimage").style.filter += "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+bgImageLoader.src+"', sizingMethod='scale')";
						} else {
							$("bgimage").src = bgImageLoader.src;
						}
						winResize();
						$("splashbox").style.visibility = "visible";
						completed++;
						getPageFromAnchor();
					}
				}
				var showcontentbox = function(){
					$("contentbox").style.visibility = "visible";
				}
				if (document.body.id == "homepage"){
					Element.hide('splashbox');
					new Effect.Appear('splashbox',{duration:2,afterUpdate:onloadComplete,afterFinish:preloadImgs});
					new Effect.Appear('contentbox',{duration:2,delay:2.5,afterUpdate:showcontentbox});
				} else {
					onloadComplete();
				}
			}
			//
			if (!seenIt){
				seenIt = "0t,";
			} else if (seenIt.indexOf(imageLibrary.length+"t") != -1){
				seenIt = "0t,";
			}
			pickAnImage();
			//
			bgImageLoader.src = theImage;
			bgImageLoader.lowsrc = bgImageLoader.src.slice(0,bgImageLoader.src.lastIndexOf("."))+"_clear.gif";
			//
		}
	}
});

var getPageFromAnchor = function(){
	var locString = String(document.location);
	if (locString.indexOf("#") != -1){
		var sectionId = locString.slice(locString.indexOf("#")+1);
		if (sectionId != ""){
			StateManager.setState(sectionId);	
		}
	}
}

var hideSplash = function(){
	if ((destP == "portfolio") || (destP == "bio")) {
		$("splashbox").style.visibility = "hidden";
	}
	sourceP = destP;
}

var showContent = function(){
	if(destP == "portfolio"){
		if (isFirefox){
			$("content").style.paddingBottom = "131px";
		}
		//getPageFromAnchor();
		new Ajax.Updater('menucontent', "work.html", { method:'get', onComplete:generateLists});
		if (isFirefox){
			$("menupane").style.bottom = "-20px";
			$("menupane").style.height = "131px";
		}
	} else if(destP == "bio"){
		/*var d = new Date();
		//get number of years since March 2010
		var startYear = 2010;
		var curYear = d.getFullYear();
		var totalYears = curYear-startYear;
		//get number of months in curYear
		var curMonth = d.getMonth()+1;
		//calculate total months at current job (-2 because started in March)
		var totalMonths = (totalYears*12)-2+curMonth;
		//on timeline, one month = 5px
		$("currentjob").style.width = 1+totalMonths*5+"px";*/
	}
	new Effect.Appear('contentbox', {duration:1, afterFinish:hideSplash});
}

var insertContent = function(){
	new Ajax.Updater('contentbox', contentUrl, { method:'get', onComplete:showContent });
}

var insertBlank = function(){
	new Ajax.Updater('contentbox', "blank.html", { method:'get', onComplete:showContent });
}

/*******/
var topLink = true;
/*****************
State Manager for Ajax event history tracking
******************/
// "Import" the StateManager so we don't have to keep typing
// "EXANIMO.managers.StateManager".
window.StateManager = EXANIMO.managers.StateManager;

// Define what happens when the state changes.
StateManager.stateChangeHandler = function(e){
	if (topLink){
		var theObjId = String(e.id);
		destP = theObjId;
		
		if ((destP == "home") || (destP == "blank") || (destP == "contact") || (sourceP == "contact") || (sourceP == "home") || (sourceP == "blank") || (sourceP == "contact")) {
			$("splashbox").style.visibility = "visible";
		}
		if (theObjId.indexOf("/") == -1){
		
			contentUrl = $(theObjId).href;
			if ((theObjId != "home") && (theObjId != "homepage")){
				new Effect.Fade('contentbox', {duration:0.5, afterFinish:insertContent});
				new Effect.Fade(theObjId, {duration:0.5});
				StateManager.setTitle('Justin Damer : ' + $(theObjId).title);
			} else {	
				theObjId = "home";
				new Effect.Fade('contentbox', {duration:0.5, afterFinish:insertBlank});
				StateManager.setTitle('Justin Damer');
			}
			for (i=0;i<3;i++){
				var theLink = $("topnav").getElementsByTagName("li")[i].firstChild;
				if (theLink.id != theObjId){
					theLink.style.backgroundImage = "url(images/textreplace/"+theLink.id+"_a.png)";
					theLink.onmouseover = function(){
						this.style.backgroundImage = "url(images/textreplace/"+this.id+"_hover.png)";
					}
					theLink.onmouseout = function(){
						this.style.backgroundImage = "url(images/textreplace/"+this.id+"_a.png)";
					}
						new Effect.Appear(theLink);
				}
			}
		}
	} else {
		if (loadCount < 1){
			oldString = urlString;
			urlString = String(e.id);
			if (urlString.indexOf("/") == -1){
				urlString = oldString;
			}
			var docLocation = String(document.location);
			contentUrl = docLocation.slice(0,docLocation.indexOf("#"))+"clients/"+urlString;
			new Effect.Fade('contentpane', {duration:0.5, afterFinish:pInsertContent});
			new Effect.Fade('scrollcontent', {duration:0.5});
			currentImg = 0;
			loadCount++;
		}
	}
} 

/*****************
Element Behaviours
******************/

var myrules = {
	'#topnav ul li a' : function(el){
		el.onclick = function(){
			topLink = true;
			StateManager.setState(this.id);
			return false;
		}
		el.onfocus = function(){
			this.blur();
		}
	}/*,
	'#home' : function(el){
		el.onclick = function(){
			topLink = true;
			StateManager.setState(this.id);
			return false;
		}
		el.onfocus = function(){
			this.blur();
		}
	} */
};
Behaviour.register(myrules);


/***************************************
****************************************
Ugly hack to make sure Behaviour rules
get applied after Ajax content updates
****************************************/

Ajax.Responders.register({ 
	onComplete: function() { 
		if(Ajax.activeRequestCount==0) { 
			Behaviour.apply(); 
		} 
	} 
}); 

// CSS Browser Selector   v0.2.5
// Documentation:         http://rafael.adm.br/css_browser_selector
// License:               http://creativecommons.org/licenses/by/2.5/
// Author:                Rafael Lima (http://rafael.adm.br)
// Contributors:          http://rafael.adm.br/css_browser_selector#contributors
var css_browser_selector = function() {
	var 
		ua=navigator.userAgent.toLowerCase(),
		is=function(t){ return ua.indexOf(t) != -1; },
		h=document.getElementsByTagName('html')[0],
		b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('gecko/')? 'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',
		os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';
	var c=b+os+' js';
	h.className += h.className?' '+c:c;
}();