// SET UP VARIABLES
var inc = 15; // SET THE NUMBER OF PIXELS TO MOVE EACH TIME MOVERIGHT() OR MOVELEFT() IS RUN - LOWER NUMBER = SMOOTHER
var timeInc = 50; // SET THE NUMBER OF MILLISECONDS TO WAIT BEFORE RUNNING THE MOVERIGHT() OR MOVELEFT() FUNCTIONS AGAIN - HIGHER NUMBER = FASTER
var div = 'gallery'; // THE NAME OF THE MAIN CONTENT ELEMENT (DIV) THAT WE WILL BE MOVING LEFT AND RIGHT
var divWidth = 865; // THE WIDTH OF THE MAIN CONTENT ELEMENT
var descWidth = 220; // THE WIDTH OF PRODUCT DESCRIPTION BOXES

// DECLARE OTHER VARIABLES
var t, curOp, lastChild, ct, eMarLeft, dt, cdt;
var moveRight, moveLeft, checkArrows, getMargin, getContentWidth, centerContent, tweenObjectLeft, tweenObjectRight, fadeOut, fadeIn, getNegWidth, getLastChild, getSecondToLastChild, getFirstChild, resetAll, getArtboardPos, setOpaque, calculateGalleryWidth;

// FUNCTION TO MOVE THE MAIN ELEMENT (DIV) RIGHT
// IMPORTANT: THIS FUNCTION REQUIRES getMargin(), getNegWidth() AND getContentWidth() FOUND BELOW
function moveRight() {
	checkArrows();
	var e = $(div);
	var lvalue = getMargin(e);
	var negContentWidth = ((0 - getContentWidth())+divWidth)+inc;
	if (lvalue < negContentWidth) { 
		e.style.marginLeft = getNegWidth() + 'px';
		return; 
	}
	e.style.marginLeft = (lvalue-inc) + 'px';
	t = setTimeout(moveRight, timeInc);
}
// FUNCTION TO MOVE THE MAIN ELEMENT (DIV) LEFT
// IMPORTANT: THIS FUNCTION REQUIRES getMargin() AND getContentWidth() FOUND BELOW
function moveLeft() {
	var e = $(div);
	var lvalue = getMargin(e);
	if (lvalue > (0-inc)) { 
		e.style.marginLeft = '0px';
		return; 
	}
	e.style.marginLeft = (lvalue+inc) + 'px';
	checkArrows();
	t = setTimeout(moveLeft, timeInc);
}
function checkArrows() {
	// LEFT ARROW
	var firstChild = getFirstChild();
	if (getObjLeft(firstChild) === getObjLeft('artboard')) {
		$('move_left').hide();
	} else {
		$('move_left').show();
	}
	
	// RIGHT ARROW
	if (getMargin(div) == getNegWidth()) {
		$('move_right').hide();
	} else {
		$('move_right').show();
	}
}
// MOVE TO A CERTAIN SECTION, PLACING THE SECTION DIVIDER FLUSH TO THE LEFT
function findSection(section) {
	resetAll();
	var sObjLeft = getObjLeft(section);
	var newLeft = (getMargin(div) - sObjLeft) + getObjLeft('artboard');
	var nextSibs = $(section).nextSiblings();
	if (nextSibs[0] === getLastChild()) {
		newLeft = getNegWidth();
	}
	if (sObjLeft < getObjLeft('artboard')) {
		tweenObjectRight(div, newLeft, 50);
	} else {
		tweenObjectLeft(div, newLeft, 50);
	}
}
// FIND THE LEFT MARGIN OF OUR MAIN ELEMENT, 
// SO THAT WE CAN CALCULATE A NEW MARGIN UPON MOVELEFT() AND MOVERIGHT()
function getMargin(element) {
	var mleft = $(element).style.marginLeft;
	var mlength = mleft.length;
	var mvalue = parseInt(mleft.substring(0, mlength-2), 10);
	return mvalue;
}
// FUNCTION TO GET THE OVERALL WIDTH OF THE MAIN ELEMENT (DIV)
// WE MUST FIND THE CONTENT WIDTH DYNAMICALLY, BECAUSE NEW MATERIAL WILL
// BE ADDED TO THE MAIN ELEMENT OCCASIONALLY. THUS, WE CANNOT USE A FIXED WIDTH.
function getContentWidth() {
	var ccLength = 0;
	var cChildren = $(div).childElements();
	for (var i=0; i < cChildren.length; i++) {
		ccLength = ccLength + parseInt($(cChildren[i]).offsetWidth, 10);
	}
	return ccLength;
}
// FUNCTION TO OPEN A GIVEN DESCRIPTION DIV
function showDesc(item, desc) {
	var i, allBox;
	var thisItem = $(item);
	var iSiblings = thisItem.nextSiblings();
	var thisDesc = iSiblings[0];
	var d = $(thisDesc);
	if (d.style.display == 'none') {
		var allDesc = $$('.desc');
		for (i=0; i < allDesc.length; i++) {
			$(allDesc[i]).hide();
		}
		allBox = $$('.box');
		for (i=0; i < allBox.length; i++) {
			if (allBox[i] !== thisItem) {
				new Effect.Opacity(allBox[i], { from: 0.99, to: 0.5, duration: 1.0 });
			}
			if (allBox[i] === thisItem) {
				new Effect.Opacity(allBox[i], { from: 0.5, to: 0.99, duration: 1.0 });
			}
		}
		if (item == getFirstChild()) { 
			d.show();
			$(div).style.marginLeft = "0px";
			return; 
		}
		d.show();
		centerContent(item, thisDesc);
	} else {
		d.hide();
		allBox = $$('.box');
		for (i=0; i < allBox.length; i++) {
			var fadeThis = true;
			var getDesc = $$('.desc');
			if (allBox[i] === thisItem) { fadeThis = false; }
			if (fadeThis === true) {
				new Effect.Opacity(allBox[i], { from: 0.5, to: 0.99, duration: 0.5 });
			}
		}
		if (item == getLastChild()) { $(div).style.marginLeft = getNegWidth() + 'px'; return; }
		if (item == getSecondToLastChild()) { $(div).style.marginLeft = getNegWidth() + 'px'; return; }
		if (item == getFirstChild()) { $(div).style.marginLeft = '0px'; return; }
		if (getMargin(div) < getNegWidth()) { tweenObjectRight(div, getNegWidth(), 20); }
	}
}
function centerContent(item, desc) {
	var i = $(item);
	var d = $(desc);
	var adjAmount = getObjLeft(item) - ((divWidth - (i.offsetWidth + descWidth))/2);
	var newLeft = (getMargin(div) - adjAmount) + getArtboardPos();
	if (item == getLastChild()) {
		newLeft = getNegWidth();
	}
	if (getObjLeft(item) < (divWidth/2)) {
		tweenObjectRight(div, newLeft, 20);
	} else {
		tweenObjectLeft(div, newLeft, 20);
	}
}
// MOVES THE PASSED ELEMENT TO THE GIVEN END LEFT MARGIN
function tweenObjectLeft(element, end, tweenAmount) {
	e = $(element);
	eMarLeft = getMargin(element);
	if (eMarLeft == end+0.5) {
		return;
	}
	// if ((eMarLeft - descWidth) < getNegWidth()) {
	// 	return;
	// }
	if ((eMarLeft - tweenAmount) < end) {
		e.style.marginLeft = end + 'px';
		clearTimeout(t);
		return;
	}
	else {
		e.style.marginLeft = eMarLeft-tweenAmount + 'px';
		t = setTimeout("tweenObjectLeft('" + element + "', " + end + ", " + tweenAmount + ")", 1);
	}
}
// MOVES THE PASSED ELEMENT TO THE GIVEN END LEFT MARGIN
function tweenObjectRight(element, end, tweenAmount) {
	e = $(element);
	eMarLeft = getMargin(element);
	if ((eMarLeft + end) > 0) {
		return;
	}
	if ((eMarLeft + tweenAmount) > end) {
		e.style.marginLeft = end + 'px';
		clearTimeout(t);
		return;
	}
	else {
		e.style.marginLeft = eMarLeft+tweenAmount + 'px';
		t = setTimeout("tweenObjectRight('" + element + "', " + end + ", " + tweenAmount + ")", 1);
	}
}
function fadeOut(e) {
	var fadeThis = true;
	var getDesc = $$('.desc');
	for (var i=0; i < getDesc.length; i++) {
		if ($(getDesc[i]).style.display != 'none') { fadeThis = false; }
	}
	if (fadeThis === true) {
		curOp = $(e).style.opacity;
		$(e).fade({ duration: 0.5, from: curOp, to: 0.5 });
	}
}
function fadeIn(e) {
	var fadeThis = true;
	var getDesc = $$('.desc');
	for (var i=0; i < getDesc.length; i++) {
		if ($(getDesc[i]).style.display != 'none') { fadeThis = false; }
	}
	if (fadeThis === true) {
		curOp = $(e).style.opacity;
		$(e).fade({ duration: 0.5, from: curOp, to: 0.99 });
	}
}
function fadeInElement(e) {
	curOp = $(e).style.opacity;
	$(e).fade({ duration: 0.5, from: curOp, to: 0.99 });
}
function fadeOutElement(e) {
	curOp = $(e).style.opacity;
	$(e).fade({ duration: 0.5, from: curOp, to: 0.5 });
}
function setOpaque(e) {
	t = setTimeout(function() { $(e).fade({ duration: 0.5, from: 0.5, to: 0.99 }); }, 500);
}
function getNegWidth() {
	var mWidth = 0 - (getContentWidth() - divWidth);
	return mWidth;
}

// GET THE LAST (VISIBLE) CHILD OF THE MAIN DIV
// **NOTE** THIS FUNCTION WAS SET UP ON A GALLERY THAT INCLUDES A HIDDEN DESC BOX, THEREFORE THE
// 			FUNCTION IS NOT ACTUALLY GETTING THE "LAST" CHILD, BUT THE LAST VISIBLE CHILD
function getLastChild() {
	var divChildren = $(div).childElements();
	return divChildren[divChildren.length-2];
}
function getSecondToLastChild() {
	var divChildren = $(div).childElements();
	return divChildren[divChildren.length-4];
}
// GET THE FIRST CHILD OF THE MAIN DIV
function getFirstChild() {
	var divChildren = $(div).childElements();
	return divChildren[0];
}
// THIS WILL HIDE ANY OPEN DESCRIPTION BOXES, AND FADE IN ALL THE MAIN BOXES
function resetAll() {
	var i;
	var allDesc = $$('.desc');
	for (i=0; i < allDesc.length; i++) {
		$(allDesc[i]).hide();
	}
	var allBox = $$('.box');
	for (i=0; i < allBox.length; i++) {
		fadeIn(allBox[i]);
	}
}
function getElementWidth(element) {
	var e = $(element);
	var eWidth = e.offsetWidth;
	return eWidth;
}

function getArtboardPos() {
	var gpPos = getObjLeft('artboard');
	return gpPos;
}
function updateLeftMargin() {
	var lMargin = $(div).style.marginLeft;
	$('result').update("Left Margin: " + lMargin);
}
function showArrows() {
	$('move_left').style.opacity = 1;
	$('move_right').style.opacity = 1;
}
function hideArrows() {
	$('move_left').style.opacity = 0;
	$('move_right').style.opacity = 0;
}
// SWITCH PHOTOS
function switchPhoto(element, thisWidth, hrefId) {
	var cWidth = getContentWidth();
	$('gallery').style.width = (cWidth+thisWidth) + 'px';
	var waitTime;
	var eSibs = $(element).siblings();
	for (var i=0; i < eSibs.length; i++) {
		if ($(eSibs[i]).style.display != 'none') { var isDisplayed = eSibs[i]; }
	}
	var pWidth = $(element).parentNode.style.width;
	if (parseInt(pWidth.substring(0, pWidth.length-2), 10) < thisWidth) {
		waitTime = 700;
	} else {
		waitTime = 300;
	}
	$(isDisplayed).fade({ queue: 'front' });
	$(element).appear({ queue: 'end' });
	var t = setTimeout(function() { $(element).parentNode.morph('width: '+thisWidth+'px;'); }, waitTime);
	$(element).parentNode.style.opacity = '.99';
	
	// ADD "SELECTED" CLASS TO THIS HREF, AND REMOVE "SELECTED" FROM SIBLING HREFS
	var thisHref = $(hrefId);
	thisHref.addClassName('selected_photo');
	
	var thisSiblings = $(hrefId).siblings();
	for (var i=0; i < thisSiblings.length; i++) {
		$(thisSiblings[i]).removeClassName('selected_photo');
	}
//	calculateGalleryWidth();
}
function getObjLeft(element) {
	var obj = $(element).getBoundingClientRect();
	var objLeft = obj.left;
	return objLeft;
}
function delayedCloseDesc() {
	var i, newTimeout;
	var closeAll = false;
	var getDesc = $$('.desc');
	for (var i=0; i < getDesc.length; i++) {
		// IF ANY DESC BOXES ARE OPEN, CLOSE THEM ALL AND FADE IN ALL THE PHOTOS
		if ($(getDesc[i]).style.display != 'none') { 
			closeAll = true;
			var thisDesc = getDesc[i];
			var thisPrevSiblings = $(getDesc[i]).previousSiblings();
			var thisPrevSib = thisPrevSiblings[0];
		}
	}
	if (closeAll === false) {
		return;
	} else {
		if (getObjLeft(thisDesc) > 0) {
			newTimeout = setTimeout(function() { 
				var allBox = $$('.box');
				for (i=0; i < allBox.length; i++) {
					if (allBox[i] !== thisPrevSib) {
						new Effect.Opacity(allBox[i], { from: 0.5, to: 0.99, duration: 1.0 });
					}
				}
			}, 500);
		} else {
			$(thisDesc).hide();
			$(div).style.marginLeft = getMargin(div) + descWidth + 'px';
		}
	}
}
function calculateGalleryWidth() {
	var cWidth = getContentWidth();
	$('gallery').style.width = (cWidth+descWidth) + 'px';
}
// CREATE AN EVENT.OBSERVE ON THE DOCUMENT, SO THAT WE CAN MOVELEFT() AND MOVERIGHT() ON MOUSEOVER
document.observe('dom:loaded', function() {
	$('move_left').observe('mouseover', function() { 
		dt = setTimeout(function() {
			moveLeft();
			delayedCloseDesc();
		}, 400);
	});
	$('move_left').observe('mouseout', function() {	
		ct = clearTimeout(t);
		cdt = clearTimeout(dt);
	});
	$('move_right').observe('mouseover', function() { 
		dt = setTimeout(function() {
			moveRight(); 
			delayedCloseDesc();
		}, 400);
	});
	$('move_right').observe('mouseout', function() { 
		ct = clearTimeout(t);
		cdt = clearTimeout(dt);
	});
});
// CALCULATE THE WIDTH OF ALL CHILDREN (OF THE MAIN DIV), AND THEN ASSIGN A WIDTH TO THE MAIN DIV 
document.observe('dom:loaded', function() {
	var cWidth = getContentWidth();
	$('gallery').style.width = (cWidth+descWidth) + 'px';
});
document.observe('dom:loaded', function() {
	checkArrows();
});
