var ajaxResults = null;
var currentCompanyIndex = null;
var currentExampleIndex = null;
var exampleSelectorDivsArray = new Array();
var companyNavigationArray = null;
var examplesNavigationArray = null;
var myLightBox = null;

/*-------------------------------------------
| Retrieve data via AJAX
---------------------------------------------*/
	function getPortfolioData() {	
		//retrieve the block of data to display
		var ajax = new ajaxObj("/services/portfolio.php");
		ajax.obj.onreadystatechange = function() {
			if (ajax.obj.readyState == 4) {
				if (ajax.obj.status == 200) {
						ajax.results = eval("(" + ajax.obj.responseText + ")");
						ajaxResults = ajax.results;
						showPortfolio();
				}
				ajax = null;
			}
		}
		ajax.obj.send(null);
	}
	
	
/*-------------------------------------------
| Create navigation
---------------------------------------------*/
	function createCompaniesNavigation() {
		//Find the DOM element with companiesNavPlaceholder ID and use a copy of it to construct a navigation list of companies
		
		//find the nav element placeholder and associated array and clear it out
		document.getElementById("subNav_left_all").innerHTML = "";
		companiesNavigationArray = new Array();
		
		//find the placeholder node to clone
		var srcNode = document.getElementById("companiesNavPlaceholder");
		
		//create nav elements for all companies based on the cloned placeholder
		for(var i=0; i < ajaxResults.length; i++) {
			var myCompany = ajaxResults[i];
			var clone = srcNode.cloneNode(true);
			clone.id = "companySelector" + i;
			
			//add a label
			var linkLabel = document.createTextNode(myCompany.name);
			clone.appendChild(linkLabel);
			//append the node to the document
			document.getElementById("subNav_left_all").appendChild(clone);
			//make the node visible
			removeClassName(clone, 'placeholderNav');
			
			createCompanyNavItem(i, clone.id);
		}
	}

	function createCompanyNavItem(companyIndex, elementId) {
		//wire up js for each company nav item and load them into an array
		companiesNavigationArray[companyIndex] = new Uize.Widget.Button({idPrefix: elementId});
		companiesNavigationArray[companyIndex].addEventHandler('Click', function() {setCompanyNavigation(companyIndex)});
		companiesNavigationArray[companyIndex].wireUi();
	}
	
	function createExamplesNavigation(companyIndex) {
		//create example navigation list, if it doesn't exist already
		//TODO: if (document.getElementById("exampleSelectorDiv" + companyIndex)) return false;
		//TODO: don't clear it out.  Instead, create a parent <div> to contain example navigation and hide it when not needed.  Don't recreate the <div> if it already exists.  This will save having to reconstruct example navigation each time the company is selected.
		
		//TODO: hide all exampleNavContainers except this one
		//TODO: create a new exampleNavContainer for the current company, if it doesn't exist already
		//TODO: initialize new lightbox for the company object, if it hasn't been initialized already
			
		//create a div to contain all example nav elements
		var myCompany = ajaxResults[companyIndex];
		var myExampleSelectorDiv = document.createElement("div");
		myExampleSelectorDiv.id = "exampleSelectorDiv" + companyIndex;
		addClassName(myExampleSelectorDiv, "exampleSelectorDiv");
		exampleSelectorDivsArray[companyIndex] = myExampleSelectorDiv;
		document.getElementById("exampleSelectorsShell").appendChild(myExampleSelectorDiv);
		
		examplesNavigationArray = new Array();
		
		//create nav elements for all examples based on the cloned placeholder
		for(var i=0; i < myCompany.examples.length; i++) {			
			createExampleNavItem(companyIndex, i);
			createExampleThumbnailItem(companyIndex,i);
		}
		//create and initialize a lightbox for all of the examples of this company
		myLightbox = new Lightbox(document.getElementById("exampleThumbnailShell"));
		
	}

	function createExampleNavItem(companyIndex, exampleIndex) {
		//Find the DOM element with "examplesNavPlaceholder" ID and use copies of it to construct a subnav list of examples for each company
		var srcNode = document.getElementById("examplesNavPlaceholder");
		var clone = srcNode.cloneNode(true);
		clone.id = "exampleSelector" + exampleIndex;
		document.getElementById("exampleSelectorDiv" + companyIndex).appendChild(clone); //append new node
		removeClassName(clone, 'placeholderNav');
		
		//wire up js for each button and load them in the array created in the calling function
		examplesNavigationArray[exampleIndex] = new Uize.Widget.Button({idPrefix: clone.id});
		examplesNavigationArray[exampleIndex].addEventHandler('Click', function() {setExampleNavigation(companyIndex, exampleIndex)});
		examplesNavigationArray[exampleIndex].wireUi();
	}
	
	function createExampleThumbnailItem(companyIndex, exampleIndex) {
		//create a new DOM element for the thumbnail link
		
		var company = ajaxResults[companyIndex];
		
		var thumbnailLink = document.createElement("a");
		thumbnailLink.id = "company" + companyIndex + "_exampleLink" + exampleIndex;
		//if there is a large example image, display that image in lightbox when the image is clicked.  Otherwise, just display the thumbnail
		//the href, rel, and title attributes are used by lightbox.js to create a slideshow popup for the large image
		thumbnailLink.setAttribute("href",company.examples[exampleIndex].image != "" ? company.examples[exampleIndex].image : company.examples[exampleIndex].thumbnail);
		thumbnailLink.setAttribute("rel","lightbox[company" + companyIndex +"]");
		thumbnailLink.setAttribute("title","<strong>" + company.examples[exampleIndex].title + "</strong>:" + company.examples[exampleIndex].description);
		addClassName(thumbnailLink,"exampleThumbnailLink");
		
		//create a new DOM element for the thumbnail image
		var exampleImage = document.createElement("img");
		exampleImage.setAttribute("title", company.examples[exampleIndex].title + " (click to view full-size image)");
		//if no thumbnail exists, show the large image instead
		exampleImage.src = (company.examples[exampleIndex].thumbnail != "") ? company.examples[exampleIndex].thumbnail : company.examples[exampleIndex].image;
		addClassName(exampleImage,"exampleThumbnailImage");
		thumbnailLink.appendChild(exampleImage);
		
		document.getElementById("exampleThumbnailShell").appendChild(thumbnailLink);
	}

/*-------------------------------------------
| Set navigation and show data
---------------------------------------------*/
	function showPortfolio(companyIndex) {
		//after the data is retrived via AJAX, the company list is constructed and a company is selected in the nav
		var companyIndex = companyIndex ? companyIndex : 0;
		createCompaniesNavigation();
		setCompanyNavigation(companyIndex);
	}
	
	function setCompanyNavigation(companyIndex,exampleIndex) {
		//select a company in the company nav list and create navigation elements for the children examples
		if (currentCompanyIndex == companyIndex) return false;
		var exampleIndex = exampleIndex ? exampleIndex : 0;
		var company = ajaxResults[companyIndex];
		//make sure only the clicked element is selected
		for (var i=0; i<companiesNavigationArray.length; i++) {
			companiesNavigationArray[i].set({selected : (i==companyIndex) ? true : false});
		}
		createExamplesNavigation(companyIndex);
		
		//hide all exampleSelectors except the one associated with this company
		for (var i=0; i<exampleSelectorDivsArray.length; i++) {
			if(exampleSelectorDivsArray[i]) {
				alert(exampleSelectorDivsArray[i].id)
				exampleSelectorDivsArray[i].style.display = (exampleSelectorDivsArray[i].id == "exampleSelectorDiv" + companyIndex) ? "block" : "none";
			}
		}
		
		document.getElementById("examplesTitle").innerHTML = company.name;
		currentCompanyIndex = companyIndex;
		setExampleNavigation(companyIndex, exampleIndex);
	}
	
	function setExampleNavigation(companyIndex, exampleIndex) {
		//select an example in the example nav list and show its thumbnail		
		var exampleIndex = exampleIndex ? exampleIndex : 0;
		var myCompany = ajaxResults[companyIndex];
		
		//make sure only the clicked nav element is selected
		for (var i=0; i<examplesNavigationArray.length; i++) {
			examplesNavigationArray[i].set({selected : (i==exampleIndex) ? true : false});
		}
		
		//swap out display text in placeholder DOM elements to show data relevant to current example
		document.getElementById("exampleTitle").innerHTML = myCompany.examples[exampleIndex].title;
		document.getElementById("exampleDescription").innerHTML = myCompany.examples[exampleIndex].description;
		
		//TODO: Hide all thumbnail links except for the one to display
		for(var i=0; i<examplesNavigationArray.length; i++) {
			var curLink = document.getElementById("company" + companyIndex + "_exampleLink" + i)
			curLink.style.display = (curLink.id == "company" + companyIndex + "_exampleLink" + exampleIndex) ? "block" : "none";
		}
		
		//store new active nav element for later comparison
		currentExampleIndex = exampleIndex;
		
		updatePrevNextButtons();
	}
	
/*-------------------------------------------
| Forward/Back buttons
---------------------------------------------*/
	function previousExample() {
		if (currentCompanyIndex == 0 && currentExampleIndex == 0) return false;
		
		if (currentExampleIndex == 0) {
			//we're on the first example, so go to the last example of the previous company
			var newCompanyIndex = currentCompanyIndex-1;
			var newCompany = ajaxResults[newCompanyIndex];
			setCompanyNavigation(newCompanyIndex, newCompany.examples.length-1);
		}
		else {
			setExampleNavigation(currentCompanyIndex, currentExampleIndex-1);
		}
	}
	
	function nextExample() {
		if (currentCompanyIndex == ajaxResults.length-1 && currentExampleIndex == ajaxResults[currentCompanyIndex].examples.length-1) return false;
		
		var currentCompany = ajaxResults[currentCompanyIndex];
		
		if (currentExampleIndex == currentCompany.examples.length-1) {
			//we're on the last example, so go to the first example of the next company
			var newCompanyIndex = currentCompanyIndex+1;
			var newCompany = ajaxResults[newCompanyIndex];
			setCompanyNavigation(newCompanyIndex);
		}
		else {
			setExampleNavigation(currentCompanyIndex, currentExampleIndex+1);
		}
	}
	
	function updatePrevNextButtons() {
			//top
		_examplePrevButton_top.set({enabled : (currentCompanyIndex == 0 && currentExampleIndex == 0) ? false : true });
		_exampleNextButton_top.set({enabled : (currentCompanyIndex == ajaxResults.length -1 && currentExampleIndex == ajaxResults[currentCompanyIndex].examples.length-1) ? false : true });
		
		//bottom
		_examplePrevButton_bottom.set({enabled : (currentCompanyIndex == 0 && currentExampleIndex == 0) ? false : true });
		_exampleNextButton_bottom.set({enabled : (currentCompanyIndex == ajaxResults.length -1 && currentExampleIndex == ajaxResults[currentCompanyIndex].examples.length-1) ? false : true });
	}

/*-------------------------------------------
| Show first portfolio on page load
---------------------------------------------*/
	var oldOnload = window.onload;
	
	window.onload = function() {
		getPortfolioData();
		oldOnload;
	}
	
/*-------------------------------------------
| Capture left-right keys and use them as back/next buttons
---------------------------------------------*/
	var oldOnKeydown = document.onkeydown;
	
	document.onkeydown = function (e) {
		var keynum;
		var e = getEvent(e);

		keynum = e.keyCode ? e.keyCode : e.which;
		if (keynum == 37) { //left arrow
			previousExample();
		}
		if (keynum == 39) { //right arrow
			nextExample();
		}
	}

