/*
	jason lacouture
	10/2009 
	MOOOOOO
*/
window.addEvent('domready', function() {
	// ---- init ---- 
	// artistID
	var aID		= -1;
	
	// the height of the contribution content holder
	var contentHeight	= 450; 

	// a counter for the contributions animations
	var aniInc = 0; 

	// whether or not we're waiting for animations to finish
	var busy=false;

	// storage for things that happen next
	var nextName, currName, nextArtist = ""; 

	// elements we'll deal with a lot
	var content = $('contributionsContent');
	
	// the btns on the contributions menu
	var contributionMenuItems = $$('.menu div'); 

	// the btns in the artist menu
	var artistBTNs	= $('artistsMenu').getElements('.artistBTN_ank');

	// set within setRefs
	var bioMain, mainbox, connector, contentWrapper;

	// the ajax request
	var req;

	// animations -----------------------------------------
	// the main bio fades in and out
	var bioMorph = new Fx.Morph($('bioMain')); 

	// the artist title image fades in and out
	var imgMorph = new Fx.Morph($('bioTitle').getElement('img'));

	// the animation controller for the right content area
	var efx = new Fx.Morph(content); 

	// init mouse events -----------------------------------------
	// add the click listeners to each element
	contributionMenuItems.each(function(item, index){
		item.addEvent('click', function(e){
			var thisName	= $(this).get('name');
			if( !busy && nextName != thisName ){
				// store the current contribution menu btn
				currName	= nextName;
				resetMenuBTN();
				nextName	= thisName;
				hideCurrent(hideCurrentCompleteChain);
				$(this).setStyle('background-image',
						'url(pageDesign/layouts/0/artistsPage/'+thisName+'-selected.gif)');
			}
		})
	});
	// add an onClick handler for each artistBTN
	artistBTNs.each( function(item, index){
		item.addEvents({
			'click': function(e){
				// don't waste cpu on the same artist
				if( !busy && this.rel != aID ){
					lock();
					$('artistsMenu').getElement('.artistBTN-selected').set('class', 'artistBTN');	
					$(this).getElement('img').set('class', 'artistBTN-selected');
					nextArtist	= this.rel;
					currName	= nextName;
					hideCurrent(hideCurrentCompleteNoChain);
					Log.logger("clicker");
					bioMorph.addEvent('complete', bioMorphOutComplete).start({opacity:0});
					imgMorph = new Fx.Morph($('bioTitle').getElement('img')).start({opacity:0});
				}
			},
			'mouseover': function(e){
				setArtistIdentifier($(this).getElement('img').get('alt'));
			},
			'mouseout': function(e){
				setArtistIdentifier('');	
			}
		});
	});
	///////////////////////////////////////////////////////////////////
	// helper functions for lock&unlock
	///////////////////////////////////////////////////////////////////
	function lockHelper(item,index){	item.setStyle('cursor', 'wait');};
	function unlockHelper(item,index){	item.setStyle('cursor', 'pointer');};
	///////////////////////////////////////////////////////////////////
	// we're just about to start animating - lock all the btns 
	// so the ajax calls don't get all fucked up
	///////////////////////////////////////////////////////////////////
	function lock(){
		//$('loadingContent').setStyle('visibility','visible');
		Log.logger('lock');
		busy	= true;	
		contributionMenuItems.each(lockHelper);
		artistBTNs.each(lockHelper);
	}
	///////////////////////////////////////////////////////////////////
	// its safe to allow animations, unlock the btns
	///////////////////////////////////////////////////////////////////
	function unlock(){
		//$('loadingContent').setStyle('visibility','hidden');
		Log.logger('unlock');
		busy	= false;
		contributionMenuItems.each(unlockHelper);
		artistBTNs.each(unlockHelper);
	}
	// BIO LOGIC -------------------------------------------------
	function bioMorphOutComplete(e){ 	setArtist(nextArtist); }
	function bioMorphInComplete(e){ 	loadContributions(); }
	function setArtistTitle(title){ 	$('bioTitle').empty().set('html', title);}
	function setArtistBio(img, bio){ 	$('bioMain').empty().set('html', img+bio);}

	// CONTRIBUTIONS LOGIC ---------------------------------------
	///////////////////////////////////////////////////////////////////
	// restores the last contributions menu button to 
	///////////////////////////////////////////////////////////////////
	function resetMenuBTN(){
		if( currName != '' )
			$$('div.'+currName+'BTN').setStyle('background-image',
					'url(pageDesign/layouts/0/artistsPage/'+currName+'.gif)');
	}
	///////////////////////////////////////////////////////////////////
	// show the products now. needed for showing products on page load
	// and when you display a new artist.
	///////////////////////////////////////////////////////////////////
	function showProducts(){
		resetMenuBTN();
		$$('div.productsContentBTN').setStyle('background-image',
				'url(pageDesign/layouts/0/artistsPage/productsContent-selected.gif)');

		nextName	= "productsContent";
		showNext();
	}
	////////////////////////////////////////////////////////////////////
	// hide the current content in the contributions content area
	////////////////////////////////////////////////////////////////////
	function hideCurrent(onComplete){
		lock();
		efx.addEvent('complete', onComplete);
		if( ++aniInc % 2 == 0 ){
			Log.logger('hide-1');
			efx.start({
				'height': 0,
				'top': contentHeight
			});
		} else {
			Log.logger('hide-2');
			efx.start({ 'height': 0});
		}
	}
	////////////////////////////////////////////////////////////////////
	// main logic for hideCurrentComplete 
	// the way we're swapping content is by grabbing the content from 
	// the #hiddenContent and adopting it into the contributionsContent
	// area. when we hide the current, we just put it back into the 
	// hiddenContent area so it can be grabbed again later.
	////////////////////////////////////////////////////////////////////
	function hideCurrentCompleteHelper(){
		$(content).setStyle('display', 'none');
		Log.logger('hiddenContent is adopting '+currName);
		if( currName != "" ){
			$('hiddenContent').adopt($(currName));
		}
	}
	////////////////////////////////////////////////////////////////////
	// callback for when the hideCurrent() finishes with a call to showNext
	////////////////////////////////////////////////////////////////////
	function hideCurrentCompleteChain(){
		hideCurrentCompleteHelper();
		showNext();
		this.removeEvent('complete', hideCurrentCompleteChain);
	}
	////////////////////////////////////////////////////////////////////
	// callback for when the hideCurrent() finishes with NO call to showNext
	////////////////////////////////////////////////////////////////////
	function hideCurrentCompleteNoChain(){
		hideCurrentCompleteHelper();
		this.removeEvent('complete', hideCurrentCompleteNoChain);
	}
	////////////////////////////////////////////////////////////////////
	// grab the content the user is requesting and place it in the 
	// contributionContent area.
	////////////////////////////////////////////////////////////////////
	function showNext(){
		content.adopt($(nextName));

		// this is a fix because the animation was a little buggy 
		$(content).setStyle('display', '');
		
		efx.addEvent('complete', showNextComplete);
		if( aniInc % 2 == 0 ){
			Log.logger('show-1');
			efx.start({
				'height': contentHeight,
				'top': 0
			});
		} else {
			Log.logger('show-2');
			efx.start({'height':contentHeight});
		}
	}
	////////////////////////////////////////////////////////////////////
	// showNext animation is done
	////////////////////////////////////////////////////////////////////
	function showNextComplete(){
		unlock();	
		Log.logger('showNextDONEzo');
		this.removeEvent('complete', showNextComplete);
	}
	////////////////////////////////////////////////////////////////////
	// the bio data has come back from the server.
	// now create a request for the contributionContent
	////////////////////////////////////////////////////////////////////
	function loadContributions(){
		bioMorph.removeEvent('complete', bioMorphInComplete);
		adjustContentHeights();
		req	= $empty;
		req	= new Request.JSON({
			url:'artistSwitchboard.php?action=contributions&aid='+aID,
			onSuccess: function(result){
				setProducts(result.products);
				setDesigns(result.designs);
				setPhotos(result.photos);
				// contributions have their on rel='lightbox' stuff
				// tell slimbox to find them.
				Slimbox.scanPage();
				showProducts();
			},	
			onFailure: function() {
				Log.logger("no dice from loadContributions");
			}
		}).send();
	}
	function setProducts(products){ 	$('productsContent').empty().set('html', products.txt); }
	function setDesigns(designs){ 		$('designsContent').empty().set('html', designs.txt); }
	function setPhotos(photos){ 		$('photosContent').empty().set('html', photos.txt); }

	// ARTIST MENU LOGIC -----------------------------------------
	////////////////////////////////////////////////////////////////////
	// this is the rollover/out handler for the artistBTNs
	////////////////////////////////////////////////////////////////////
	function setArtistIdentifier(txt){ 	$('artistIdentifier').set('html', txt);	}
	////////////////////////////////////////////////////////////////////
	// click handler for artistBTNs
	////////////////////////////////////////////////////////////////////
	function setArtist(_aid){
		bioMorph.removeEvent('complete', bioMorphOutComplete);
		aID	= _aid;
		req	= $empty;
		// create a new ajax request for the bio
		req	= new Request.JSON({
			url:'artistSwitchboard.php?action=bio&aid='+_aid,
			onSuccess: function(artist){
				Log.logger("setArtist-onSuccess..."+artist.name);
				document.title	= "AntiDesigns artist: "+artist.name;
				setArtistTitle(artist.title);
				setArtistBio(artist.img,artist.bio);
				bioMorph.addEvent('complete', bioMorphInComplete).start({opacity:1});
				imgMorph = new Fx.Morph($('bioTitle').getElement('img')).start({opacity:1});
			},	
			onFailure: function() {
				Log.logger("no dice");
			}
		}).send();
	}
	function setPageRefs(){
		bioMain		= $('bioMain'); 
		mainbox		= $('mainbox');
		contentWrapper	= $('contentWrapper');
		connector	= $('connector');
	}
	function adjustContentHeights(){
		var offsetMarker	= $('bioOffsetMarker');
	//	var bioHeight		= offsetMarker.getPosition().y-bioMain.getPosition().y; 
		var bioHeight		= bioMain.getSize().y;
		var _contentHeight	= contentWrapper.getSize().y;

		// remember whether we've synced bioMain, connector, & content
		var synced		= false;

		// helpers
		var y0, y1, dy, targetHeight;

		var bioMorph	= new Fx.Morph(bioMain);

		y0		= offsetMarker.getCoordinates().bottom;
		var coords	= bioMain.getCoordinates();
		y1		= coords.bottom;

		// does bioMain need to 2b extended
		if( bioHeight < _contentHeight ){
			Log.logger('bioMain is shorter than content( '+bioHeight+' < '+_contentHeight+') wait for bMc');
			synced		= true;
			contentHeight	= _contentHeight;
			bioMorph.addEvent('complete', bioMorphComplete);
			bioMorph.start({'height': _contentHeight});
			connector.morph({height: _contentHeight});

		// does the text overflow outside of bioMain
		} else if( y0 > y1 ){
			dy		= y0 - y1;
			Log.logger('txt is overflowing by '+dy+' wait for bMc');
			contentHeight	= coords.height+dy;
			synced		= true;
			
			targetHeight	= coords.height+dy;
			bioMorph.addEvent('complete', bioMorphComplete);
			bioMorph.start({'height': targetHeight});
			//bioMain.morph({height: targetHeight});
			connector.morph({height: targetHeight});
			contentWrapper.morph({height: targetHeight});
		}
		
		if( !synced ){
			attemptToAdjustMainbox();	
			sync();
		}
	}
	function attemptToAdjustMainbox(){
		// is the bio extending past the mainbox?
		var y0	= $('bioBottom').getCoordinates().bottom;
		var y1	= mainbox.getCoordinates().bottom;
		if( y0 > y1 ){
			var dy	= y0 - y1 + 100;
			Log.logger('bioMain extending outside of mainbox by '+dy);
			mainbox.morph({height: mainbox.getSize().y+dy});
		}
	}
	function sync(){
		var targetHeight	= bioMain.getSize().y;
		var contentHeight	= targetHeight;
		contentWrapper.morph({height: targetHeight});
		connector.morph({height: targetHeight});
	}
	function bioMorphComplete(){
		this.removeEvent('complete', bioMorphComplete);
		Log.logger('bioMorphComplete');
		attemptToAdjustMainbox();
		sync();
	}
	showProducts();
	setPageRefs();
	adjustContentHeights();
});
