/*
Projects_
		The variables need to be genericized
		Create object for projects so they can be displayed alphabetically.
		Create option for ordering by name or index. Default name.
		Might be better off using Lumir method and then nothing weird should happen loading images.
		Add loaded flag for images, send XHR for image data and update flag when successfully loaded.
		Should wait until image is loaded before displaying
		Abstract project display to a class
		Use invoking ID to create a unique namespace.
		Make an array of the XML info and the order of that array order the way the divs are added to DOM.
		Display has fancy fade-in and fade-out

*/
/* XML functions */
function loadProjectXML ( category ) {
//alert('loadProjectXML invoked. category='+category);
	var file = fileLocation + category + '.xml';				// Name of xml data file
	typeOfProject = category;
	var myRequest = new Request({
		url: file,
		method: 'get',
		onSuccess: function( responseText, responseXML ) {
			//alert( responseText );
			parseProjectXML( responseXML );
		},
		onFailure: function() {
			alert( 'Loading XML failed.' );
			var el = new Element( 'div', {
				'html': 'There was a problem retrieving the XML file:<br/>' + file,
				'styles': {
					'color': '#ff0000',
					'text-align': 'left',
					'font-weight': 'bold' } 
			}).inject( 'headline', 'before' ); // 'headline' WILL NEED TO BE FIXED
		}
	});
	myRequest.send();
};
function setThisActive( thisOne ) {
	$$( '#projectList a' ).each( function(a){
		if( a.hasClass( 'active' )) a.removeClass( 'active' );
		if( a.name == thisOne ) { a.addClass( 'active' ); a.blur(); };
	});
};
function parseProjectXML ( receivedXML ) {
//alert("parseProjectXML invoked. receivedXML.firstChild.tagName="+receivedXML.firstChild.tagName);	
	// Assumptions: There is a div named projectDisplay.
	// If XML contains projects
	xmlObj = receivedXML;
	projects = xmlObj.getElementsByTagName( 'project' );
	defineDivs();
//alert( 'parseProjectXML: projects.length=' + projects.length );
	if ( projects.length > 0 ) {
		// Wipe the project list
		//new Effect.toggle(projectListDiv, 'appear');
		removeChildrenFromNode( projectListDiv );
		
		// Add new divs for project display
		// Create this:
		//    <div id="projectDisplay"><div id="projectDisplayLarge"></div><div id="projectDisplayThumbs"></div></div>
		projectDisplayDiv = $( 'projectDisplay' );
		
		projectDisplayLargeDiv = new Element( 'div', { 'id': 'projectDisplayLarge' });
		projectDisplayDiv.appendChild( projectDisplayLargeDiv );
		//projectDisplayLargeDiv = $( 'projectDisplayLarge' );
		projectDisplayEffect = new Fx.Morph( $( 'projectDisplayLarge' ), { duration:1000 });
		
		projectDisplayThumbsDiv = new Element( 'div', { 'id': 'projectDisplayThumbs' });
		projectDisplayDiv.appendChild( projectDisplayThumbsDiv );
		//projectDisplayThumbsDiv = $( 'projectDisplayThumbs' );
		
		// Add thumbnail display where navigation is
		// Assumption: The LI tag has a class with the same name as typeOfProject
		var whereToStore = $$( 'ul.projectsSecNav li.'+typeOfProject )[ 0 ];
		var listDiv = new Element( 'ul', { 'id': 'projectList' });
		whereToStore.appendChild( listDiv );

		
		// For every project in the XML, display the title
		for ( var i=0; i < projects.length; i++ ) {
			// Init title variable
			var title = '';
			// If the project has at least one title, Store the first title
			var projectTitles = projects[ i ].getElementsByTagName( 'title' );
			if ( projectTitles.length > 0 ) title = projectTitles[ 0 ].firstChild.nodeValue;
			//alert("title="+title);
	
			// if the project has at least one title
			if (title != '') {				
				// Create new A node
				var aNode = document.createElement( 'a' );
				// Set the proper source and events
				aNode.href = 'javascript:;';
				aNode.title = title;
				aNode.name = i;
				aNode.onclick  = function () {
					displayProject( this.name );
					setThisActive( this.name );
					return false;
				};
				
				// Create new text node
				var aText = document.createTextNode( title );
				// Append text to A
				aNode.appendChild( aText );
				var li = document.createElement( 'li' );
				li.setAttribute( 'id', 'div'+i );
				li.appendChild( aNode );
				// Attach DIV to the document
				listDiv.appendChild( li );
			} // endif project images exist
		} // endfor every project
		
		// If projects exist, display the first one
		if ( projects.length > 0 ) {
			// Reference the first project
			var firstProject = $( 'div0').getElementsByTagName( 'a' )[0].name;
			displayProject( firstProject );
			setThisActive( firstProject );
		};
	};// endif XML contains projects
};
function removeChildrenFromNode(nodeToClear) {
//alert("removeChildrenFromNode invoked.");
	if ( nodeToClear != null) while( nodeToClear.firstChild ) nodeToClear.removeChild( nodeToClear.firstChild );
}
function changeInstructions () {
//alert("changeInstructions invoked");
	// Create new link
	var aNode = document.createElement('a');
	aNode.href="javascript:;";
	aNode.onclick = restoreOrigText;
	// Create new text for link
	var newInstructions = document.createTextNode( 'Reset page' );
	aNode.appendChild(newInstructions);

	removeChildrenFromNode(instructionsDiv);
	instructionsDiv.appendChild(aNode);
}
function storeOrigText () {
	// Assumptions: 
	//   After the DIV tag, there has to be an immediate tag
	//   whether its H2 or P. Any whitespace gets read as a node
	//   which screws this up.
//alert("storeOrigText invoked.");
	origHeadline = headlineDiv.firstChild.firstChild.nodeValue;
	origDescription = descriptionDiv.firstChild.firstChild.nodeValue;
	origInstructions = instructionsDiv.firstChild.nodeValue;
}
function restoreOrigText () {
	// Restore headline
	headlineDiv.firstChild.firstChild.nodeValue = origHeadline;
	// Restore description
	removeChildrenFromNode(descriptionDiv);
	var descriptionText = document.createElement("p");
	descriptionText.appendChild(document.createTextNode(origDescription));
	descriptionDiv.appendChild(descriptionText);
	// Restore instruction
	removeChildrenFromNode(instructionsDiv);
	var newInstructions = document.createTextNode(origInstructions);
	instructionsDiv.appendChild(newInstructions);
	// Hide projectDisplay
	projectDisplayDiv.style.visibility = "hidden";
	projectDisplayThumbsDiv.style.visibility = "hidden";
	resetThumbBorders (listDiv);
}
function displayProject ( nodeNumber ) {
//alert("displayProject: nodeNumber="+nodeNumber);
	// Store selected project number
	projectNumber = nodeNumber;
	// Set pointer to the selected project
	var project = projects[ nodeNumber ];
	
	// Clear the headline div
	removeChildrenFromNode( headlineDiv );
	// Add the new headline
	/*var headlineDivNode = document.createElement( headlineElement );
	var headlineText = project.getElementsByTagName( 'title' )[0].firstChild.nodeValue;
	var headlineDivText = document.createTextNode( headlineText );
	headlineDivNode.appendChild( headlineDivText );*/
	var headlineText = project.getElementsByTagName( 'title' )[ 0 ].firstChild.nodeValue;
	var headlineDivNode = new Element( headlineElement, { 'class': 'company' }).set( 'text', headlineText );
	headlineDiv.appendChild( headlineDivNode );
	
	// Clear the description div
	removeChildrenFromNode( descriptionDiv );
	// Add container for descriptions
	var descriptionContainer = document.createElement( descriptionContainerElement );
	// Get the new descriptions
	var descriptions = project.getElementsByTagName( 'description');
	// Add the new descriptions
	for (var i=0; i<descriptions.length; i++) {
		var descriptionDivNode = document.createElement( descriptionElement );
		var descriptionText = descriptions[ i ].firstChild.nodeValue;
		var descriptionDivText = document.createTextNode( descriptionText );
		descriptionDivNode.appendChild( descriptionDivText );
		descriptionContainer.appendChild( descriptionDivNode );
	};
	descriptionDiv.appendChild( descriptionContainer );
	
	// Clear the url div
	removeChildrenFromNode( urlDiv );
	// Add the new url(s)
	var urlTexts = project.getElementsByTagName( 'urlText' );
	var urls = project.getElementsByTagName( 'url' );
	if( urls.length > 0 ) {
		for( var i=0; i<urls.length; i++ ){
			var a = new Element( 'a', { href: urls[ i ].firstChild.nodeValue });
			if( urlTexts[ i ].firstChild.nodeValue ) {
				a.set( 'text', urlTexts[ i ].firstChild.nodeValue);
			} else {
				a.set( 'text', urls[ i ].firstChild.nodeValue );
			};
			var tmp = new Element( urlElement ).appendChild( a );
			urlDiv.appendChild( tmp );
		};
	};	
	//changeInstructions();
	displayLargeImage( 0 );
	
	// Clear the project thumbnails div
	removeChildrenFromNode( projectDisplayThumbsDiv );
	// Get the image names
	var images = project.getElementsByTagName( 'image' );
	if ( images.length > 1 ) {
		// Create a container for the thumbnails
		var newThumbDiv = new Element( 'div', { 'id': 'newThumb' });
		preload = new Array();
		//projectDisplayThumbsDiv.appendChild( newThumbDiv );
		for( var i=0; i<images.length; i++) {
			// Create new A node, set the proper source and events
			var aNode = new Element( 'a', {
				'href': 'javascript:;',
				'title': headlineText,
				'name': i,
				'class': 'normal'
			}).set( 'text', 'Image ' + ( i+1 ));
			$( aNode ).addEvent('click', function(e) {
				e.stop();
				resetNewThumb();
				displayLargeImage( this.name );
				this.className = 'active';
				this.blur();
				return false;
			});
			newThumbDiv.appendChild( aNode );
			if( i==0 ) aNode.className = 'active';
			if( images.length > ( i+1 )) newThumbDiv.appendChild( new Element( 'span' ).set( 'text', ' | ' ) );

			preload.push( largeLocation + images[ i ].firstChild.nodeValue + largeType );			
		};
		projectDisplayThumbsDiv.setStyle( 'visibility', 'visible' );
		projectDisplayThumbsDiv.appendChild( newThumbDiv );
		preloadImages( preload );
	} else {
		projectDisplayThumbsDiv.setStyle( 'visibility', 'hidden' );
	};
	// Display projectDisplay
	projectDisplayDiv.setStyle( 'visibility', 'visible' );
};
function preloadImages() {
	//alert('preloadImages invoked.');
    for (var i = 0; i < arguments.length; i++){
        preloaded[i] = document.createElement('img');
        preloaded[i].setAttribute('src',arguments[i]);
    };
};

function resetThumbBorders( thumbsDiv ) {
//alert("resetThumbBorders invoked");
	// Get the array of thumbnails
	/*var thumbsToChange = thumbsDiv.getElementsByTagName( 'a' );
	// How many thumbmails are there?
	var numThumbs = thumbsToChange.length;
	for ( var i=0; i<numThumbs; i++ ) {
		thumbsToChange[i].style.borderColor = thumbNormal;
		thumbsToChange[i].firstChild.style.visibility = "visible";
	}*/
	$$( thumbsDiv.getElementsByTagName( 'a' )).each( function( t, idx ) {
		t.setStyle( 'borderColor', thumbNormal );
		t.setStyle( 'visibility', 'visible' );
	});
};
function resetNewThumb () {
	// Get an array of thumbnails
	/*var newThumbDiv = document.getElementById( 'newThumb');
	var thumbsToChange = newThumbDiv.getElementsByTagName("a");
	// How many thumbnails are there?
	var numThumbs = thumbsToChange.length;
	for ( var i=0; i<numThumbs; i++ ) {
		thumbsToChange[i].className = "normal";
	}*/
	$$( document.getElementsByTagName( '#newThumb a' )).each( function( t, idx ) {
		t.setStyle( 'class', 'normal' );
	});
};
function displayLargeImage ( imageNumber ) {
//alert('displayLargeImage invoked. imageNumber='+imageNumber);
	var project = projects[ projectNumber ];
	var images = project.getElementsByTagName( 'image' );
	var largeName = images[ imageNumber ].firstChild.nodeValue;
	var largeFile = 'url(' + largeLocation + largeName + largeType + ')';
	//alert('largeFile='+largeFile);
	
	// Change the background of projectDisplayLarge Div
	projectDisplayEffect.start({ height: [0,236], opacity: [0,1] });
	projectDisplayLargeDiv.style.backgroundImage = largeFile;
	
	// Add display effect here
};
function defineDivs () {
//alert("defineDivs invoked.");
	// Assumptions:
	//   The following DIVs must exist in the document for this
	//   xmlProjectDisplay to function correctly
	content2Div= $( 'content' );
	headlineDiv = $( 'headline' );
	descriptionDiv = $( 'description' );
	//instructionsDiv = $( 'instructions' );
	projectListDiv = $( 'projectList' );
	urlDiv = $( 'url' );
};
var xmlDoc;																	// The XML file
var xmlObj;  																// The resulting XML object
var origHeadline;															// The original text to replace with title
var origDescription;														// The original text to replace with description
var origInstructions;														// The original instructions
var content2Div;															// Location of the DIVs for project display
var headlineDiv;
var headlineElement = 'h2';
var descriptionDiv;
var descriptionContainerElement = 'ul';
var descriptionElement = 'li';
//var instructionsDiv;
var urlDiv;
var urlElement = 'p';
var listDiv;
var preloaded;																// Array of images to preload
var projects;																// Array of project nodes from xmlObj
var projectDisplayDiv;
var projectDisplayLargeDiv;
var projectDisplayEffect;
var projectDisplayThumbsDiv;
var projectListDiv;															// Gets wiped when thumbs are displayed
var typeOfProject;															// Which category of projects are displayed
var projectNumber;															// Selected project
var thumbLocation = "thumbs/";												// Where thumbs are stored
var fileLocation ='/xml/';
var largeLocation = "large/";												// Where large versions are stored
var thumbType = ".jpg";														// Image type of thumbs
var largeType = ".jpg";														// Image type of large
var thumbNormal = "#000000";												// Color of inactive thumbnail border
var thumbActive = "#333333";												// Color of selected thumbnail border
var thumbHover = "#ffffff";

//addLoadEvent( defineDivs );
//addLoadEvent( storeOrigText );