var youTuberActive = null, youtubePlayer = null, youtubeContainer = null;
var youTubeReplaceImg = null;
var youTubeReplaceMargin = null;
var box = null;

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


	youtubeContainer = new Element('div', {id: 'youtubeContainer', style:'display: table-cell; clear: none; position: absolute; top: 0; left: 0; height: 0; width: 0; background-color: #f00;', events: {'click' : function(e) { e.stop(); youTuberClose(); }} });
	youtubeContainer.inject('site-container', 'bottom');
	youtubePlayer = new YtMooPlayer('youtubeContainer', {
		'height': '100%',
		'width': '100%',
		'onReady': function() {
//			console.log('readying');
			youtubePlayer.play();
		},
		'onPlay': function() {
//			console.log('playing');
		},
		'onEnded': function() {
//			console.log('ending');
		},
		'onPaused': function() {
//			console.log('pausing');
		},
		'onNotAllowed': function() {
//			console.log('discriminating');
		},
		'onNotFound': function() {
//			console.log('failing');
		},
		'onError': function(error) {
//			console.log('AN ERROR OCCURRED!!!!!!!!!!!!!!!!!!!11');
//			console.log(error);
		}
	});
	
	$$('img.youtuber').each(function(img)  {
		img.addEvent('click', function(e) {
			e.stop();
			youTuber(img);
		});
    }); 
	
	$$('div.bigImg').each(function(turnOffDisplay){
		turnOffDisplay.fade('hide');
	});
	$$('div.bigDesc').each(function(turnOffDisplay){
		turnOffDisplay.fade('hide');
	});
	$('leftBorder').fade('hide');
	$('rightBorder').fade('hide');

	var slideContainer = $('slideContainer');
	shiftEffect['slideContainer'] = new Fx.Morph(slideContainer, {duration: 'normal', transition: Fx.Transitions.Expo.easeInOut, link: 'cancel'});
	shiftEffect['slideContainer'].start({'left': 0});
	//shiftContainer = new Fx.Morph(slideContainer, {duration: 'normal', transition: Fx.Transitions.Expo.easeInOut, link: 'cancel'});
	$('slideContainer').addEvents({mouseenter: function(){canSlideLeft();canSlideRight();},mouseleave: function() {arrowFadeOut();}});
	$('leftBorder').addEvents({mouseenter: function() {canSlideRight();},mouseleave: function() {arrowFadeOut();}, click: function(){slideRight();}});
	$('rightBorder').addEvents({mouseenter: function() {canSlideLeft();},mouseleave: function() {arrowFadeOut();}, click: function(){slideLeft();}});
	
	$$('div.portfolioColumn').each(function(addListener){
		addListener.addEvents({mouseenter: function(){toggleFade(this);},mouseleave: function() {toggleFade(this);}});
	});
	
	var currentDomain = window.location.host;
	$(document.body).addEvent('click', function(evt)
	{
		var target = $(evt.target);
		if (target.get('tag') !== 'a')
		{
			target = target.getParent();
		}

		if (target && target.get('tag') === 'a' && target.get('href').test('http') && !target.get('href').test(currentDomain))
		{
			window.open(target.get('href'), '_blank');
			return false;
		}
	});
	//bring all client detail panes just outside the right side of viewport
	moveClientDetails();
	
});


window.addEvent('load', function(){
//javascript needed to handle some dynamic positioning of elements within client detail panes
	prepareClientDetailPanes();
});
//javascript needed to handle some dynamic positioning of elements within client detail panes
function prepareClientDetailPanes(){
	
	var firstImages = new Array();
	firstImages = $$('img.firstDetail');
	for(var i=0; i < firstImages.length; i++){
		var myImage = firstImages[i];
		var myWidth = myImage.getStyle('width').toInt();
		var myWidth = myImage.width;
		var mySecondImage = $('secondPane'+myImage.id.substr(9));
		mySecondImage.setStyle('margin-left', myWidth - 10);
		//alert(mySecondImage.getStyle('margin-left'));
		//init their animations so we dont get weird behavior on first run
		var firstPaneAsString = 'firstPane' + myImage.id.substr(9);
		firstPaneShift[firstPaneAsString] = new Fx.Morph(myImage, {duration: 'normal', transition: Fx.Transitions.Expo.easeInOut, link: 'cancel'});
		firstPaneShift[firstPaneAsString].start({'left': 0});
	}
}

function toggleFade(myDescription){
	var ph = $('portfolio' + myDescription.id + 'desc');
	if(ph){
		ph.fade('toggle');
	}
}

function arrowFadeIn(){
	$('leftBorder').fade('in');
	$('rightBorder').fade('in');
}

function arrowFadeOut(){
	$('leftBorder').fade('out');
	$('rightBorder').fade('out');
}

function calculateContainerWidth(){
		var images = $$('img.slideImg');
		var totalWidth = 0;
		
		for(var i = 0; i < images.length; i++){
			var image = images[i];
			totalWidth += image.getStyle('width').toInt();
		}
		logoWidth = totalWidth;
}

function canSlideLeft(){
	var canSlide = false;
	var viewSize = Window.getSize();
	distanceToSlide = viewSize.x;
	
	if(isDetailOpen){
		distanceToSlide = viewSize.x * 0.3;
		var myImgs = $$('div#'+openDetailID+' img.detailImg');
		var textPanes = $$('div#'+openDetailID+' img.firstDetail');
		//var videoPanes = $$('div#'+openDetailID+' img.youtuber');
		var openVideos = $$('div#'+openDetailID+' div.youTubeContainer object');
		myImgs = myImgs.concat(textPanes);
		//myImgs = myImgs.concat(videoPanes);
		myImgs = myImgs.concat(openVideos);
		var width = 0;
		for(var i=0; i < myImgs.length; i++){
			var image = myImgs[i];
			width += image.width.toInt();
		}


		if(width <= -leftOffset + lastLeftOffset + viewSize.x){//if (at the end of portfolio, cant move)
			canSlide = false;
		}
		else if(width > (-leftOffset + lastLeftOffset + viewSize.x + distanceToSlide)){//else if( able to make full slide )
			canSlide = true;
		}
		else{ // need to make a partial move
			distanceToSlide = width - (-leftOffset + lastLeftOffset + viewSize.x);
			canSlide = true;
		}
	}
	else{
		if(logoWidth <= -leftOffset + viewSize.x){//if (at the end of portfolio, cant move)
			canSlide = false;
		}
		else if(logoWidth > (-leftOffset + viewSize.x + distanceToSlide)){//else if( able to make full slide )
			canSlide = true;
		}
		else{ // need to make a partial move
			distanceToSlide = logoWidth - (-leftOffset + viewSize.x);
			canSlide = true;
		}
		
	}
	if(canSlide){
		$('rightBorder').fade('in');
	}
	else{
		$('rightBorder').fade('out');
	}
	return canSlide;
}

function canSlideRight(){
	var canSlide = false;
	
	if(isDetailOpen){
		if(leftOffset < lastLeftOffset){
			canSlide = true;
			$('leftBorder').fade('in');
		}
		else{
			$('leftBorder').fade('out');
		}
	}
	else{
		if(leftOffset < 0){
			canSlide = true;
			$('leftBorder').fade('in');
		}
		else{
			$('leftBorder').fade('out');
		}
	}

	
	return canSlide;
}

function slideLeft(){
	//var viewSize = Window.getSize();
	//distanceToSlide = viewSize.x * 0.3;
	if(canSlideLeft()){
		if(!shiftEffect['slideContainer']){
			var slideContainer = $('slideContainer');
			shiftEffect['slideContainer'] = new Fx.Morph(slideContainer, {duration: 'normal', transition: Fx.Transitions.Expo.easeInOut, link: 'cancel'});
		}
		//set up the math
		leftOffset = leftOffset - distanceToSlide;
		lastDistanceToSlide = distanceToSlide;
		//check to see if client detail is open, if so, set up tweens
		if(isDetailOpen){
			var firstPaneAsString = 'firstPane' + openDetailID.substr(13);
			if(!firstPaneShift[firstPaneAsString]){
				var myImage = $(firstPaneAsString);
				firstPaneShift[firstPaneAsString] = new Fx.Morph(myImage, {duration: 'normal', transition: Fx.Transitions.Expo.easeInOut, link: 'cancel'});
			}
			firstPaneShift[firstPaneAsString].start({'left': -leftOffset + lastLeftOffset});
		}
		shiftEffect['slideContainer'].start({'left': leftOffset});
		canSlideLeft();
		canSlideRight();
		moveClientDetails();
	}
}

function slideRight(){
	var viewSize = Window.getSize();
	if(canSlideRight()){
		if(!shiftEffect['slideContainer']){
			var slideContainer = $('slideContainer');
			shiftEffect['slideContainer'] = new Fx.Morph(slideContainer, {duration: 'normal', transition: Fx.Transitions.Expo.easeInOut, link: 'cancel'});
		}
		//do the math
		leftOffset = leftOffset + lastDistanceToSlide;
		if(isDetailOpen){
			lastDistanceToSlide = viewSize.x * 0.3;
		}
		else{
			lastDistanceToSlide = viewSize.x;
		}
		if(leftOffset > 0){
			leftOffset = 0;
		}
		//if detail is open...
		if(isDetailOpen){
			var firstPaneAsString = 'firstPane' + openDetailID.substr(13);
			if(!firstPaneShift[firstPaneAsString]){
				var myImage = $(firstPaneAsString);
				firstPaneShift['firstPane' + openDetailID.substr(13)] = new Fx.Morph(myImage, {duration: 'normal', transition: Fx.Transitions.Expo.easeInOut, link: 'cancel'});
			}
			firstPaneShift[firstPaneAsString].start({'left': -leftOffset + lastLeftOffset});
		}
		else{

		}
		shiftEffect['slideContainer'].start({'left': leftOffset});
		//arrowFadeIn();
		canSlideLeft();
		canSlideRight();
	}
}

//this function handles moving Client Detail panes in and out of view.
function movePane(divName, openClose){
	
	if(divName){
		var clickedDiv = $(divName);
		var windowSize = Window.getSize();
		openDetailID = divName;
		if(!myEffect[divName]){
			myEffect[divName] = new Fx.Morph(clickedDiv, {duration: 'normal', transition: Fx.Transitions.Expo.easeInOut, link: 'ignore'});
		}

	}
	switch(openClose){
		case 'open':
			myEffect[divName].start({'left': -leftOffset });
			$('leftBorder').setStyle('left', 339);
			isDetailOpen = true;
			lastLeftOffset = leftOffset;
			windowResize();
			canSlideLeft();
			break;
		case 'close':
			youTuberClose();
			if(!shiftEffect['slideContainer']){
				var slideContainer = $('slideContainer');
				shiftEffect['slideContainer'] = new Fx.Morph(slideContainer, {duration: 'normal', transition: Fx.Transitions.Expo.easeInOut, link: 'cancel'});
			}
			var firstPaneAsString = 'firstPane' + openDetailID.substr(13);
			var myImage = $(firstPaneAsString);
			if(!firstPaneShift[firstPaneAsString]){
				firstPaneShift['firstPane' + openDetailID.substr(13)] = new Fx.Morph(myImage, {duration: 'normal', transition: Fx.Transitions.Expo.easeInOut, link: 'cancel'});
			}
			windowSize.x = windowSize.x - leftOffset;
			if(myImage.getStyle('left').toInt() != 0){
				firstPaneShift[firstPaneAsString].start({'left': 0}).chain(function() {
					myEffect[divName].start({'left': windowSize.x + 10}).chain(function() {
						openDetailID = '';//reset the open detail id
						shiftEffect['slideContainer'].start({'left': lastLeftOffset}).chain(function() {
							moveClientDetails();//move all client detail panes off of the screen
						});//send the view back to the last left offset before user clicked on client detail
					});
				});
			}
			else{
				myEffect[divName].start({'left': windowSize.x + 10}).chain(function() {
					openDetailID = '';//reset the open detail id
					shiftEffect['slideContainer'].start({'left': lastLeftOffset}).chain(function() {
						moveClientDetails();//move all client detail panes off of the screen
					});//send the view back to the last left offset before user clicked on client detail
				});
			}
			$('leftBorder').setStyle('left', 0);
			isDetailOpen = false;
			leftOffset = lastLeftOffset;//and set our leftOffset back to where it should be.
			canSlideLeft();
			canSlideRight();
			break;
		default:
			return false;
	}
}


// this overlays a youtube video on an img
function youTuber(img)
{


	// left this in for while i'm debugging without flash
	if (youTuberActive)
	{
		youTuberClose();
		return false;
	}
	
	youTuberActive = img.get('rel');
	youTubeReplaceMargin = img.getStyle('margin-left');
	youTubeHeight = img.getStyle('height');
	youTubeWidth = img.getStyle('width');
	
	img.setStyle('opacity', .5);
	box = new Element('div', {id: 'box_' + img.get('rel'), width: img.width, height: img.height, 'class': 'youTubeContainer', style:'display: inline; position: relative; top: 0; background-color: #fff; margin-left: '+ youTubeReplaceMargin +';', events: 
	{'click' : function(e) { e.stop(); }}
	});
	box.wraps(img, 'top');
	youTubeReplaceImg = img.src;
	box.innerHTML = '<object width="'+ youTubeWidth + '" height="'+ youTubeHeight +'"><param name="movie" value="http://www.youtube.com/v/'+ youTuberActive +'?fs=1&amp;hl=en_US&amp;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><param name="wmode" value="opaque"></param><embed src="http://www.youtube.com/v/'+youTuberActive+'?fs=1&amp;hl=en_US&amp;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="opaque" width="'+ youTubeWidth +'" height="'+ youTubeHeight + '"></embed></object>';
	/*youtubeContainer.inject(box, 'top');
	youtubeContainer.setStyle('width', img.width);
	youtubeContainer.setStyle('height', img.height);
	youtubePlayer.options.width = img.width;
	youtubePlayer.options.height = img.height;
	youtubePlayer.playVideo(img.get('rel'));*/
	
	/*closer = new Element('div', {id : 'video_closer',
		style: 'cursor: pointer; z-index: 100; position: absolute; width: 20px; height: 20px; background: #0f0; font-size: 20px; line-height: 20px; font-family: monospace; text-align: center;',
		events: {'click' : function(e) { e.stop(); youTuberClose(); }},
		html: 'X'
	});
	closer.inject(box, 'top');*/
	
	
	//	youtubePlayer.options.width = img.width;
	//	youtubePlayer.options.height = img.height;
	youtubePlayer.setOptions({'width': img.width, 'height' : img.height});
	//youtubePlayer.playVideo(img.get('rel'));

/*
		'width': img.width,
		'height': img.height,
		'videoId' : img.get('rel'),
*/
	
	

}

// this closes a youtube video
function youTuberClose()
{
	if (youTuberActive)
	{
		youtubePlayer.stop();
		if ($('video_closer'))
			$('video_closer').dispose(); // kill close button first since it's the first child
	 	youtubeContainer.setStyle('width', 0);
		youtubeContainer.setStyle('height', 0);
		youtubeContainer.inject($('site-container'), 'bottom');
//		$('video_' + youTuberActive).dispose(); // now kill flash
		//img = $('box_' + youTuberActive).getFirst(); // and we should be left with the image
		//if (img)
			//img.inject($('box_' + youTuberActive), 'after');
		
		
		newReplace = new Element('img', { 'class' : 'youtuber detailImg',
			style: 'visibility: visible;  opacity: 1.0; margin-left: '+youTubeReplaceMargin+';',
			rel: youTuberActive,
			src: youTubeReplaceImg,
			events: {'click' : function(e) { e.stop(); youTuber(this);}}
		});
		newReplace.inject(box, 'after');
		box.dispose();
//		youtubePlayer = null;
//		$('box_' + youTuberActive).destroy();
		youTuberActive = null;
	}
}
