var myGallery;
var galleryEls = null;
var galleryShuffle = [];
var curImage = 0;
var totalImages = 0;
var totalDeadBlocks = 8;
var galleryStart = true;
var curElPos = 0;
var galleryEls = null;
var elementCount = 0;

var headlineBlock = { t:158, r:420, b:244, l:12 };

var blocks = [headlineBlock]; // starts with dead zones

var galleryBlocks = // these are the permanent locations for large blocks that turn into images
	[
		{t:65,r:637,b:248,l:454},
		{t:65,r:211,b:238,l:36},
		{t:151,r:846,b:334,l:663},
		{t:151,r:428,b:334,l:245}
	];

// user adjustable
var galleryTime = 2000;
var startingTime = 1000;
var minSize = 30;
var maxSize = 80;
var minDeadBlockSize = 30;
var maxDeadBlockSize = 50;
var minDuration = 200;
var maxDuration = 1000;
var minBlockDuration = 2000;
var maxBlockDuration = 4000;
var minDistance = 100;
var maxDistance = 400;
var minOpacity = 0.17;
var hBounds = 873;
var vBounds = 378;
var boundsPadding = 10;

function addBlock() {
	
	// default vars to zero
	var myTop = 0;
	var myLeft = 0;
	var myBottom = 0;
	var myRight = 0;
	var mySize = 0
	
	// start with a location somewhere
	mySize = Math.floor(Math.random()*(maxDeadBlockSize + 1)) + minDeadBlockSize; // size
	myTop = Math.floor(Math.random()*(vBounds - (mySize + boundsPadding) + 1)) + boundsPadding; // pos
	myLeft = Math.floor(Math.random()*(hBounds - (mySize + boundsPadding) + 1)) + boundsPadding; // pos
	myRight = mySize + myLeft;
	myBottom = mySize + myTop;

	// find a location not colliding with another
	while (isColliding(myTop,myLeft,myBottom,myRight,blocks)) {
		mySize = Math.floor(Math.random()*(maxDeadBlockSize + 1)) + minDeadBlockSize; // size
		myTop = Math.floor(Math.random()*(vBounds - (mySize + boundsPadding) + 1)) + boundsPadding; // pos
		myLeft = Math.floor(Math.random()*(hBounds - (mySize + boundsPadding) + 1)) + boundsPadding; // pos
		myRight = mySize + myLeft;
		myBottom = mySize + myTop;
	}
	
	// push the object into the array of blocks
	blocks.push({t:myTop,l:myLeft,b:myBottom,r:myRight});

	// build container
	var deadBlockContainer = new Element('div', {
	    'class': 'homeGalleryDeadBlock',
	    'styles': {
	        'position': 'absolute',
			'width': mySize + "px",
			'height': mySize + "px",
			'top': myTop + "px",
			'left': myLeft + "px",
			'overflow': 'hidden'
	    }
	});
	
	// build element
	var deadBlock = new Element('div', {
		'styles': {
			'width': mySize + "px",
			'height': mySize + "px",
			'backgroundColor': '#000000',
			'opacity': 0
		}
	});

	// set up a timer for this block
	var myStart = Math.floor(Math.random()*(maxBlockDuration + 1)) + minBlockDuration; // duration
	( function() { changeBlock(deadBlockContainer); } ).delay(myStart);
	
	// set up delay for animation in
	var myDuration = Math.floor(Math.random()*(maxDuration + 1)) + minDuration; // duration
	var myNewVal = Math.floor(Math.random()*(maxDistance + 1)) + minDistance; // duration
	var myContainerTween = new Fx.Tween(deadBlockContainer,{duration:myStart + galleryTime});

	switch(Math.floor(Math.random()*4)) {
		case 1:
		myNewVal = myLeft - myNewVal;
		myContainerTween.start('left',myNewVal);
		break;

		case 2:
		myNewVal = myTop - myNewVal;
		myContainerTween.start('top',myNewVal);
		break;

		case 3:
		myNewVal += myLeft;
		myContainerTween.start('left',myNewVal);
		break;

		default:
		myNewVal += myTop;
		myContainerTween.start('top',myNewVal);
		break;
	}
	
	// set up tween
	var myTween = new Fx.Tween(deadBlock);
	myTween.start('opacity',minOpacity);

	// add black to block
	deadBlock.inject(deadBlockContainer);
	
	// add block to DOM
	deadBlockContainer.inject($('homeGallery'));
	
	/*
	myTween.start('opacity',minOpacity).chain(
		function(){ 
			this.set('tween',{duration: myStart*100});
			this.start('left',myNewLeft);
		}
	);
	*/
	
	
}

function changeBlock(el) {
	
	// fade out block
	el.getElement("div").tween('opacity',0);
	
	// fade in a new block
	addBlock();
	
	// update the block array
	( function() { 
		el.dispose(); // gets rid of the block totally
		checkBlocks();
	}).delay(600);
	
	
}

function checkBlocks() {
	
	// clear array
	blocks = new Array();
	
	// add headlineBlock
	blocks = [headlineBlock];
	
	// rebuild on current content
	$$("#homeGallery div.homeGalleryDeadBlock").each(function(el) {
	
		var w = parseInt(el.getStyle('width'));
		var t = parseInt(el.getStyle('top'));
		var r = l + w;
		var b = t + w;
		var l = parseInt(el.getStyle('left'));
		
		blocks.push({t:t,r:r,b:b,l:l});
		
	});
	
}

function galleryTimer() {
	
	// start current element immediately
	if (++curElPos == galleryEls.length) curElPos = 0;
	galleryEls[galleryShuffle[curElPos]].fireEvent("expand");
	
}

// check to see if the provided coords are intersecting with the object array of coords
function isColliding(t,l,b,r,objArr) {
	
	var collisions = objArr.length;

	// loop through object array
	for (i=0; i<objArr.length; i++) {
	
		// separating axes theorum
		if (
			(t > objArr[i].b || b < objArr[i].t) // vertical line can fit between the boxes
			||
			(l > objArr[i].r || r < objArr[i].l) // horizontal line can fit between the boxes
			) {
			collisions--;
		}
		
	}

	// return boolean
	if (collisions <= 0)
		return false;
	else 
		return true;
		
	
}

function galleryItemInit(el) {		

	// default vars
	var myTop = 0;
	var myLeft = 0;
	var myBottom = 0;
	var myRight = 0;
	
	// set the block position
	myTop = galleryBlocks[elementCount].t;	
	myRight = galleryBlocks[elementCount].r;	
	myBottom = galleryBlocks[elementCount].b;	
	myLeft = galleryBlocks[elementCount].l;	
	
	//blocks.push({t:myTop,r:myRight,b:myBottom,l:myLeft});
	
	// get a tween element
	var myTween = new Fx.Tween(el);
						
	// set the element's new clip properties
	myTween.set('clip',[myTop,myRight,myBottom,myLeft].join(' '));
	el.getElements('img').set('opacity',0);
	
	// fade the image out, and change the bg color of the div so it is faded out and black
	myTween.set('background-color','#000000');
	myTween.set('opacity',0);
	
	// now set the display to block so it actually appears in the DOM
	myTween.set('display','block');
	
	el.addEvents({
		"expand": function () {
			
			// reset set the block position
			myTop = galleryBlocks[elementCount].t;	
			myRight = galleryBlocks[elementCount].r;	
			myBottom = galleryBlocks[elementCount].b;	
			myLeft = galleryBlocks[elementCount].l;	

			var myFx = new Fx.Tween($(this));
			var myImgFx = new Fx.Tween($(this).getElements('img')[0]);

			myFx.set('clip',[myTop,myRight,myBottom,myLeft].join(' '));
			myFx.start('opacity',minOpacity).chain( function() {
				myImgFx.start('opacity',1).chain( function() {
					myFx.set('z-index',100);
					myFx.start('opacity',1).chain( function() { 
						this.start('clip', [0, 885, 390, 0].join(' ')).chain( function() {
							( function() { galleryEls[galleryShuffle[curElPos]].fireEvent("contract"); }).delay(galleryTime);
						}); 
					});
				});
			});
			
			// increment the elementCount 
			elementCount++;
			if (elementCount == galleryBlocks.length) elementCount = 0;
			
		},
		
		"contract": function () {
			var myImgFx = new Fx.Tween($(this).getElements('img')[0]);
			var myFx = new Fx.Tween($(this));							
			myFx.start('opacity',0).chain(
				
				// put it back
				function() {
					myFx.set('z-index',100);
					myFx.set('clip',[myTop,myRight,myBottom,myLeft].join(' '));
					myImgFx.start('opacity',0).chain( function() { galleryTimer(); });
				}
			);
		}
	});
	
	elementCount++;
	if (elementCount == galleryBlocks.length) elementCount = 0;
					
}

function sw(objName,onoff) {
	var e = document.getElementById(objName);
	if (onoff == 1) {
	
		if (e.overFileName == null) {
			e.myFileName = e.src;
			var extStart = 0;
			if (e.src.indexOf(".gif") > 1) {
				extStart = e.src.indexOf(".gif");
			} else if (e.src.indexOf(".jpg") > 1) {
				extStart = e.src.indexOf(".jpg");
			} else {
				extStart = e.src.indexOf(".png");
			}
			var overFileName = e.src.substr(0,extStart) + "_over" + e.src.substr(extStart,e.src.length);
			e.overFileName = overFileName;
		}

		e.src = e.overFileName;
		
	} else {
		e.src = e.myFileName;
	}
}

function openWin(url,w,h) {
	
	window.open(url,"erd","height=" + h + ",width=" + w + ",menubar=no,toolbar=no,scrollbars=yes,titlebar=no");
	
}

function showDiv(divID) {
	
	var e = document.getElementById(divID);
	e.style.display = "block";
	
}

function hideDiv(divID) {
	
	var e = document.getElementById(divID);
	if (e != undefined) e.style.display = "none";
	
}

function startGallery() {
	
	// set up navs
	// $$('[rel=gallery-next]').addEvent("click",nextImage);
	// $$('[rel=gallery-prev]').addEvent("click",prevImage);
	// $$('[rel=^gallery-goto]').addEvent("click",gotoImage);
	
	totalImages = $('myGallery').getElements('div.imageElement').length;
	myGallery = new gallery($('myGallery'), {
		timed: false,
		delay: 7000,
		showInfopane: false,
		embedLinks: false,
		showCarousel: false,
		defaultTransition: "continuoushorizontal"
	});
}

function nextImage(obj) {
	myGallery.nextItem();
	var oldImage = curImage;
	curImage++;
	if (curImage == totalImages) curImage = 0;
	setRed(oldImage,curImage);
	// return false;
}

function prevImage(obj) {
	myGallery.prevItem();
	var oldImage = curImage;
	curImage--;
	if (curImage < 0) curImage = totalImages - 1;
	setRed(oldImage,curImage);
	// return false;
}

function gotoImageNo(num) {
	myGallery.goTo(num);
	setRed(curImage,num);
	curImage = num;
	// return false;
}

function gotoImage(obj) {
	var myID = obj.get("rel");
	myID = parseInt(myID.substr(-1));
	alert(myID);
	/*
	myGallery.goTo(myID);
	setRed(curImage,myID);
	curImage = myID;
	*/
	return false;
}

function setRed(oldImage,newImage) {
	
	$('projImgNav').getElements('a')[oldImage + 1].removeClass("red");
	$('projImgNav').getElements('a')[newImage + 1].addClass("red");
	
	$('imgControls').getElements('a')[oldImage].setStyle("display","none");
	$('imgControls').getElements('a')[newImage].setStyle("display","block");

}

shuffle = function(o){ //v1.0
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};

/************ moved to index2.php script to keep JS errors from occurring on other pages ***********
window.addEvent('load', function () {
	$$("#homeGallery div").each(galleryItemInit);
	galleryEls = $$("#homeGallery div");
	for (i=0; i<galleryEls.length; i++) galleryShuffle.push(i);
	galleryShuffle = shuffle(galleryShuffle);
	galleryTimer.delay(startingTime);
});	
****************************************************************************************************/

function init_heroAnimation() {
	

}	

window.addEvent('domready',function() {

	if (pageLabel == "home") {

		// set up actual imagery
		( function() {

			$$("#homeGallery div.homeGalleryItem").each(galleryItemInit);
			galleryEls = $$("#homeGallery div");
			for (i=0; i<galleryEls.length; i++) galleryShuffle.push(i);
			galleryShuffle = shuffle(galleryShuffle);
			galleryTimer.delay(startingTime);
			
			var myFX = new Fx.Tween($("homeGalleryHead"));
			myFX.set('opacity',0);
			myFX.set('display','block');
			myFX.start('opacity',1);

			// create dead floaters
			for (i=0; i<totalDeadBlocks; i++) addBlock();

		}).delay(1000); // 1 second delay to allow page load
				
	}
	
	var metaPlus = { src: '/meta.swf', ratios: [9, 1.16, 16, 1.09, 24, 1.06, 37, 1.04, 74, 1.02, 1.01] };
	var metaPlusBold = { src: '/metabold.swf' };
	sIFR.activate(metaPlus, metaPlusBold);
	sIFR.replace(metaPlus, {
	  selector: 'h1',
	  forceSingleLine: true,
	  wmode: "transparent",
	  offsetTop: 4,
	  tuneHeight: 4,
	  css: '.sIFR-root { color: #E11422; } .sIFR-root em { font-style: normal; color: #a68361; }'
	});

	sIFR.replace(metaPlus, {
	  selector: 'h2',
	  wmode: "transparent",
	  offsetTop: 3,
	  tuneHeight: 3,
	  css: '.sIFR-root { color: #77543f; }'
	});

	sIFR.replace(metaPlus, {
	  selector: 'h3.brown',
	  wmode: "transparent",
	  offsetTop: 3,
	  tuneHeight: 3,
	  css: '.sIFR-root { color: #77543f; leading: 3; }'
	});

	sIFR.replace(metaPlus, {
	  selector: 'h3.ltBrown',
	  wmode: "transparent",
	  offsetTop: 3,
	  tuneHeight: 3,
	  css: '.sIFR-root { color: #987859; }'
	});

	sIFR.replace(metaPlus, {
	  selector: 'h3.gold',
	  wmode: "transparent",
	  offsetTop: 3,
	  tuneHeight: 3,
	  css: '.sIFR-root { color: #a68361; }'
	});


	sIFR.replace(metaPlus, {
	  selector: 'h3#caseTitle',
	  wmode: "transparent",
	  offsetTop: 3,
	  tuneHeight: 3,
	  css: '.sIFR-root { color: #a68361; } .sIFR-root em { font-style: normal; color: #e11422; }'
	});

	sIFR.replace(metaPlus, {
	  selector: 'h3',
	  wmode: "transparent",
	  offsetTop: 3,
	  tuneHeight: 3,
	  css: '.sIFR-root { color: #E11422; } .sIFR-root a { text-decoration: none; color: #77543f; } .sIFR-root a:hover { color: #77543f } .sIFR-root em { font-style: normal; color: #77543f; }'
	});

	sIFR.replace(metaPlusBold, {
	  selector: 'div.clientList_tableTitle',
	  wmode: "transparent",
	  offsetTop: 2,
	  tuneHeight: 3,
	  css: '.sIFR-root { color: #987859; }'
	});

	sIFR.replace(metaPlus, {
	  selector: 'div.sidebarNav',
	  forceSingleLine: true,
	  offsetTop: 2,
	  offsetLeft: 6,
	  tuneWidth: 6,
	  wmode: "transparent",
	  css: '.sIFR-root { color: #E11422 } .sIFR-root a { text-decoration: none; color: #E11422; } .sIFR-root a:hover { color: #E11422 }'
	});

	sIFR.replace(metaPlus, {
	  selector: 'div.sidebarNav_on',
	  forceSingleLine: true,
	  offsetTop: 2,
	  offsetLeft: 6,
	  tuneWidth: 6,
	  wmode: "transparent",
	  css: '.sIFR-root { color: #77543f } .sIFR-root a { text-decoration: none; color: #77543f } .sIFR-root a:hover { color: #77543f }'
	});

	sIFR.replace(metaPlus, {
	  selector: '#nav',
	  forceSingleLine: true,
	  wmode: "transparent",
	  css: '.sIFR-root { color: #fddd83 } .sIFR-root a { text-decoration: none; color: #ffffff; } .sIFR-root a:hover { color: #fddd83; } .sIFR-root a.selected { color: #fddd83; } .sIFR-root em { color: #fddd83; font-style: normal; }'
	});	
	
});