/*
* Javascript for filmstrip
*
* created by Jonathan Heebner
* Last updated 1-25-11
*
* draggable elements courtesy Luke Breuer
* http://luke.breuer.com/tutorial/javascript-drag-and-drop-tutorial.aspx
*
*/

var _startX = 0; // mouse starting positions 
var _offsetX = 0; // current element offset 
var _dragElement; // needs to be passed from OnMouseDown to OnMouseMove 

var maxheight = 134; //max height for each photo
var maxwidth = 227; //max width for each photo
var widthInterval = 227;//273; //difference in x-position between each photo

var filmstripWidth; //total width of all the photos
var numberOfPhotos; //number of photos in our array
var scrollLeftLimit; //left limit for the photos

var scrollSize = 796; //the width of the scrollbar. change if needed.
var sliderWidth = 98; //the width of the slider. change if needed.
var myFilmstrip; //this will alias the filmstrip <ul>

var distance; //keeps track of how far the filmstrip must move on an arrow click
var startPosition; //keeps track of the filmstrip start position on an arrow click

var correctTarget; //targets the textHolder div when you hover over a photo
var targetLoc; //the target location of the textHolder div
var startingLoc = 110; //home position for the textHolder div
var mousedIn = true; //boolean to prevent reactivating mouseover event
var mouseOutArray = []; //will hold textHolder divs that still need to finish closing

//access the xml file
function init()
{
	activate();
}

function activate ()
{
	//var photoArray = $(".linkHolder");//document.getElementsByClassName('linkHolder');
	//document.getElementsByClassName('filmstrip')[0].onmouseover = photoMouseOver;
	//numberOfPhotos = 4;
	filmstripWidth = numberOfPhotos * widthInterval + 10; //10 is margin left on photoHolder
	myFilmstrip = document.getElementById('photos1');
	detect();
}
//loop through the XML results and place the images in the filmstrip
function DisplayResponse(request)
{
	
	
}

//detects when you mouse over a photo and begins moving the correct text div accordingly
function photoMouseOver(e)
{
	// IE
	if (e == null)
	{ 
		e = window.event;
	}
	
	// IE uses srcElement, others use target 
	var target = e.target != null ? e.target : e.srcElement;
	if(target.className == 'hoverClass')
	{
		if(mousedIn == false)
		{
			getCorrectTarget(target);
			correctTarget.style.top = 120+'px';
			targetLoc = maxheight - correctTarget.clientHeight;
			mousedIn = true;
			moveDiv(-1);
		}
	}
	else
	{
		mousedIn = false;
		if(correctTarget != undefined)
		{
			if(!mouseOutArray.exists(correctTarget))
			{
				mouseOutArray.push(correctTarget);
			}
		}
		moveDiv(1);
	}
	
}

//will correctly parse up from our hover target until the correct element('linkHolder') is found, then selects div textHolder.
function getCorrectTarget(target)
{
	if(target.className == 'linkHolder')
	{
		correctTarget = target.getElementsByClassName('textHolder')[0];
	}
	else
	{
		getCorrectTarget(target.parentNode);
	}
}

//recurring function that moves the description div on our photos
function moveDiv(dir)
{
	if(correctTarget != undefined)
	{
		var distance = ExtractNumber(correctTarget.style.top) - targetLoc;
		if(dir == -1 && !mouseOutArray.exists(correctTarget))
		{
			if(distance > 0)
			{
				correctTarget.style.top = ExtractNumber(correctTarget.style.top) - Math.ceil(0.2*distance)-1+"px";
				if(ExtractNumber(correctTarget.style.top) - targetLoc > 0)
				{
					setTimeout('moveDiv(-1)', 25);
				}
				else
				{
					correctTarget.style.top = targetLoc + 'px';
				}
			}
		}
		if(dir == 1)
		{
			var doItAgain = false;
			for(var k = 0; k < mouseOutArray.length; k++)
			{
				distance = ExtractNumber(mouseOutArray[k].style.top) - startingLoc;
				if(distance < 0)
				{
					mouseOutArray[k].style.top = ExtractNumber(mouseOutArray[k].style.top) - Math.ceil(0.2*distance)+1+"px";
				}
				if(ExtractNumber(mouseOutArray[k].style.top) - startingLoc >= 0)
				{
					mouseOutArray[k].style.top = startingLoc + 'px';
					mouseOutArray.splice(k, 1);
				}
				else
				{
					doItAgain = true;
				}
			}
			if(doItAgain)
			{
				setTimeout('moveDiv(1)', 25);
			}
		}
	}
}

//sets the left and right limits for the slider. Called on load and resize.
function detect()
{
	var windowWidth = detectSize();
	scrollLeftLimit = filmstripWidth - windowWidth;
	if(filmstripWidth < windowWidth)
	{
		$("#filmControls").css("display","none");     
		//document.getElementById('filmControls').style.display = 'none';
	}
	else
	{
		$("#filmControls").css("display","block");     
		//document.getElementById('filmControls').style.display = 'block';
	}
}

//when you click a draggable object (className == drag), preps the event listeners and variables
function OnMouseDown(e) 
{ 
	// IE is retarded and doesn't pass the event object 
	if (e == null)
	{ 
		e = window.event;
	}
	
	// IE uses srcElement, others use target 
	var target = e.target != null ? e.target : e.srcElement;
	
	// for IE, left click == 1 
	// for Firefox, left click == 0 
	if ((e.button == 1 && window.event != null || e.button == 0) && target.className == 'drag') 
	{
		// grab the mouse position 
		_startX = e.clientX; 
		
		// grab the clicked element's position 
		_offsetX = ExtractNumber(target.style.left); 
		
		// we need to access the element in OnMouseMove 
		_dragElement = target;
		// tell our code to start moving the element with the mouse 
		document.onmousemove = OnMouseMove; 
		
		// cancel out any text selections 
		document.body.focus(); 
		
		// prevent text selection in IE 
		document.onselectstart = function () { return false; };
		
		// prevent IE from trying to drag an image 
		target.ondragstart = function() { return false; }; 
		 
		// prevent text selection (except IE) 
		return false; 
	} 
}

//when you move the mouse while holding a draggable object, drags it
function OnMouseMove(e) 
{ 
	if (e == null)
	{ 
		var e = window.event;
	}
	
	// this is the actual "drag code"
	_dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px';
	var currentLeft = ExtractNumber(_dragElement.style.left);
	
	//limits the scrollbar to the scroll area
	if(currentLeft < 0)
	{
		_dragElement.style.left = 0 + 'px';
		currentLeft = 0;
	}
	if(currentLeft > (scrollSize - sliderWidth))
	{
		_dragElement.style.left = (scrollSize - sliderWidth) + 'px';
		currentLeft = scrollSize - sliderWidth;
	}
	
	//controls the filmstrip based on: the X of the slider divided by the total scrollable area
	var scrollbarPercent = currentLeft / (scrollSize - sliderWidth);
	myFilmstrip.style.left = scrollbarPercent * scrollLeftLimit * -1 + 'px';
}

//fires when you let go of a draggable object, removing event listeners
function OnMouseUp(e) 
{ 
	if (_dragElement != null) 
	{ 
		// we're done with these events until the next OnMouseDown 
		document.onmousemove = null; 
		document.onselectstart = null; 
		_dragElement.ondragstart = null; 
		 
		// this is how we know we're not dragging 
		_dragElement = null; 
	} 
}

//utility function. Parses css style value left for number value
function ExtractNumber(value) 
{ 
	var n = parseInt(value); 
	return n == null || isNaN(n) ? 0 : n; 
}

//detects the window width.
function detectSize() 
{
  	var myWidth = 0;
  	if(typeof(window.innerWidth) == 'number') 
	{
  		//Non-IE
		myWidth = window.innerWidth;
    } 
	else if( document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) 
	{
    	//IE 6+ in 'standards compliant mode'
    	myWidth = document.documentElement.clientWidth;
    } 
	else if(document.body && ( document.body.clientWidth || document.body.clientHeight)) 
	{
    	//IE 4 compatible
    	myWidth = document.body.clientWidth;
    }
	return myWidth;
}

//function called when clicking an arrow on the filmstrip controls.
function quickScroll(e)
{
	// IE is retarded and doesn't pass the event object 
	if (e == null)
	{ 
		e = window.event;
	}
	
	// IE uses srcElement, others use target 
	var target = e.target != null ? e.target : e.srcElement;
	startPosition = ExtractNumber(myFilmstrip.style.left);
	if(target.id == 'arrowLeft')
	{
		if(startPosition + widthInterval > 0)
		{
			distance = -startPosition;
		}
		else
		{
			distance = widthInterval;
		}
		moveIt(1);
	}
	if(target.id =='arrowRight')
	{
		var moveValue = startPosition - widthInterval;
		if(startPosition - widthInterval < -scrollLeftLimit)
		{
			distance = startPosition + scrollLeftLimit;
		}
		else
		{
			distance = widthInterval;
		}
		moveIt(-1);
	}

}

/*
* recurring function that moves the filmstrip when an arrow is clicked.
* accepts one variable, either 1 or -1, which determines if the filmstrip moves left or right
*/
function moveIt(dir)
{
	if(dir == 1)
	{
		if(ExtractNumber(document.getElementById('sliderTool').style.left) > 0)
		{
			var traveled = ExtractNumber(myFilmstrip.style.left) - startPosition;
			myFilmstrip.style.left = ExtractNumber(myFilmstrip.style.left) + Math.ceil(0.3*(distance - traveled))+3+"px";
		
			var currentLeft = ExtractNumber(myFilmstrip.style.left);
			var scrollPercent = currentLeft / scrollLeftLimit;
			document.getElementById('sliderTool').style.left = scrollPercent * (scrollSize - sliderWidth) * -1 + 'px';
			if(distance - traveled > 0)
			{
				document.getElementById('arrowLeft').onclick = null;
				document.getElementById('arrowRight').onclick = null;
				setTimeout("moveIt(1)", 25);
			}
			else
			{
				myFilmstrip.style.left = startPosition + distance + "px";
				document.getElementById('sliderTool').style.left = scrollPercent * (scrollSize - sliderWidth) * -1 + 'px';
				document.getElementById('arrowLeft').onclick = quickScroll;
				document.getElementById('arrowRight').onclick = quickScroll;
			}
		}
		else
		{
			document.getElementById('arrowLeft').onclick = quickScroll;
			document.getElementById('arrowRight').onclick = quickScroll;
		}
	}
	
	if(dir == -1)
	{
		if(ExtractNumber(document.getElementById('sliderTool').style.left) < scrollSize - sliderWidth)
		{
			var traveled = ExtractNumber(myFilmstrip.style.left) - startPosition;
			myFilmstrip.style.left = ExtractNumber(myFilmstrip.style.left) - Math.ceil(0.3*(distance + traveled))-3+"px";
		
			var currentLeft = ExtractNumber(myFilmstrip.style.left);
			var scrollPercent = currentLeft / scrollLeftLimit;
			document.getElementById('sliderTool').style.left = scrollPercent * (scrollSize - sliderWidth) * -1 + 'px';
			if(distance + traveled > 0)
			{
				document.getElementById('arrowLeft').onclick = null;
				document.getElementById('arrowRight').onclick = null;
				setTimeout("moveIt(-1)", 25);
			}
			else
			{
				myFilmstrip.style.left = startPosition - distance + "px";
				document.getElementById('sliderTool').style.left = scrollPercent * (scrollSize - sliderWidth) * -1 + 'px';
				document.getElementById('arrowLeft').onclick = quickScroll;
				document.getElementById('arrowRight').onclick = quickScroll;
			}
		}
		else
		{
			document.getElementById('arrowLeft').onclick = quickScroll;
			document.getElementById('arrowRight').onclick = quickScroll;
		}
	}
}

window.onload = function()
{
	Array.prototype.exists = function(o) 
	{
		for(var i = 0; i < this.length; i++)
		{
			if(this[i] === o)
			{
				return true;
			}
		}
		return false;
	}
	
	if (document.getElementsByClassName == undefined) 
	{
		document.getElementsByClassName = function(className)
		{
			var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
			var allElements = document.getElementsByTagName("*");
			var results = [];

			var element;
			for (var i = 0; (element = allElements[i]) != null; i++) 
			{
				var elementClass = element.className;
				if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
				{
					results.push(element);
				}
			}
			return results;
		}

		
	}

	document.onmousedown = OnMouseDown; 
	document.onmouseup = OnMouseUp;
	document.getElementById('arrowLeft').onclick = quickScroll;
	document.getElementById('arrowRight').onclick = quickScroll;
	init();
}

window.onresize = function()
{
	detect();
}
