dojo.require("dojo.io.BrowserIO");
dojo.require("dojo.event.*");
dojo.require("dojo.html");
dojo.require("dojo.fx.html");


/* 
This demo does a search on Amazon for album art and displays the results in a 5x2 table that you can scroll like the iTunes music store.
API request looks something like this 
http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&Operation=ItemSearch&SearchIndex=Music&SubscriptionId=14BW7T0107C1HF9J65R2&ResponseGroup=Images&Keywords=&Artist=Coldplay&Title=&
*/

initEvents = function() {
	stepPos = document.getElementById("pos");
	buttonPrev = document.getElementById("prevButton");
	buttonNext = document.getElementById("nextButton");
	searchBox = document.getElementById("searchSelect");
	searchString = searchBox.options[searchBox.selectedIndex].value;
	
	
	container = document.getElementById("imagesContainer");
	slider = document.getElementById("slidingContainer");
	imageContainers = dojo.html.getElementsByClassName("imgTarget");
	
	//Basically at this stage we're just initializing things
	resetFields();
	
	dojo.event.connect(buttonNext, "onclick", "doNext");
	dojo.event.connect(searchBox, "onchange", "doSearch");
	
	//Fetch the first results
	fetchAlbumArt(searchString);
}

// When the combobox changes
doSearch = function(evt) {
	resetFields();
	searchString = evt.target.options[evt.target.selectedIndex].value;
	fetchAlbumArt(searchString);
}

resetFields = function() {
	//Reset Buttons 
	dojo.event.connect(buttonNext, "onclick", "doNext");
	dojo.event.disconnect(buttonPrev, "onclick", "doPrevious");
	
	buttonNext.src = "images/buttonNext.gif";
	buttonPrev.src = "images/buttonPrevDone.gif";
	
	//Reset everything
	itemPage = 1;
	currentStep = 0;
	farthestPoint = 0;
	isRunning = false;
	stepPos.src = "images/pos1.gif";
	
	//Remove all current images 
	for(var i=0; i < imageContainers.length; i++)	{
		var table = imageContainers[i].getElementsByTagName("table")[0];
		if(table)	{
			table.parentNode.removeChild(table);
		}
	}
	dojo.fx.slideTo(slider, 0, [0,0]);
}

/* Going forwards
	 First thing we do is check to make sure that going forward we don't grab the results
	 again if we already did it before. (ie. we pressed back and then forward again.) 
	 This could be done by checking the nodes to see if there are images present however that seemed
	 a little inflexible in case we ever put an image in for some reason. And it also seemed a little 
	 more time consuming than just checking a number.
*/
doNext = function()	{
	if(isRunning)	{
		return;
	} else	{
		isRunning = true;
	}
	
	currentStep++;
	if(farthestPoint > currentStep)	{
		slideIt(-500,0);
	}
	else {
		farthestPoint = currentStep+1;
		itemPage++;
		fetchAlbumArt(searchString);
	}
	
	if(currentStep == 1)	{
		dojo.event.connect(buttonPrev, "onclick", "doPrevious");
		buttonPrev.src = "images/buttonPrev.gif";
	} else if (currentStep == 3)	{
		dojo.event.disconnect(buttonNext, "onclick", "doNext");
		buttonNext.src = "images/buttonNextDone.gif";
	}
}

/*Going backwards? Just checks the connections to make sure we don't allow 'previous' to be active on the 
first frame which would send us off into blank land
*/

doPrevious = function()	{
	if(isRunning)	{
		return;
	} else	{
		isRunning = true;
	}
	
	if(currentStep == 3)	{
		dojo.event.connect(buttonNext, "onclick", "doNext");
		buttonNext.src = "images/buttonNext.gif";
	} else if(currentStep == 1)	{
		dojo.event.disconnect(buttonPrev, "onclick", "doPrevious");
		buttonPrev.src = "images/buttonPrevDone.gif";
	}
	currentStep--;
	slideIt(500,0);
}

/* Create the URL.. maybe later we'll expand this and give a search capability but I leave that to you */
createUrl = function(keywords)	{
	return "amazonProxy.php?Keywords="+keywords+"&ItemPage="+itemPage;
}

//Do the request to AWS
fetchAlbumArt = function(keywords)	{
	dojo.io.bind({
		url:createUrl(keywords),
		load: function(load, data, e) {
			var xmlResult = dojo.dom.createDocumentFromText(data);
			renderResults(xmlResult);
		},
		error: function(e) {
			dj_debug(e);
		}
	});
}

//Render out the artwork into a nice 5x2 table
renderResults = function(xmlResult)	{
	var hrefNodes = xmlResult.getElementsByTagName("DetailPageURL");
	var imgNodes = xmlResult.getElementsByTagName("ImageSet");
	
	//Make the display table
	var table = document.createElement("table");
	var tbody = document.createElement("tbody");
	var tr = document.createElement("tr");
	var tr2 = document.createElement("tr");
	
	for (var i=0; i < hrefNodes.length; i++)	{
		if(imgNodes[i] != undefined)	{
			var td = document.createElement("td");
			var a = document.createElement("a");
			a.href = hrefNodes[i].firstChild.nodeValue;
			var img = document.createElement("img");
			img.src = imgNodes[i].getElementsByTagName("SmallImage")[0].firstChild.firstChild.nodeValue;
			a.appendChild(img);
			td.appendChild(a);
			if(i <= 4) {
				tr.appendChild(td);
				
			} else {
				tr2.appendChild(td);
			}
		}
		
		tbody.appendChild(tr);
		tbody.appendChild(tr2);
		table.appendChild(tbody);
		imageContainers[currentStep].appendChild(table);
	}
	if(currentStep!= 0) {
			slideIt(-500, 0);
		}
}

updateStepPosition = function() {
	stepPos.src = "images/pos"+(currentStep+1)+".gif";
}

slideIt = function(startCoords, endCoords)	{
	dojo.fx.slideBy(slider, 600, [startCoords, endCoords], function()	{
			updateStepPosition();
			isRunning = false;
	});
}

dojo.event.connect(dojo.hostenv, "loaded", "initEvents");
