var menuUpdater;

function init(section) {
	ajaxEngine.registerRequest( 'getXML', 'xml/' + section + '.xml' );
	
	ajaxEngine.registerAjaxElement( 'lnav' );
	ajaxEngine.registerAjaxElement( 'image' );
	ajaxEngine.registerAjaxElement( 'text' );
	
	menuUpdater = new MenuUpdater( section );
	
	ajaxEngine.registerAjaxObject( 'menu', menuUpdater );

	ajaxEngine.sendRequest( 'getXML' );
	
	
}

function showImage(itemNum) {
	menuUpdater.setMenu(itemNum);
}

var MenuUpdater = Class.create();

MenuUpdater.prototype = {
	initialize: function(section) {
		this.pageArray = new Array();
		this.currentPage = 0;
		this.sectionName = section;
	},

	ajaxUpdate: function(ajaxResponse) {
		this.buildmenu(ajaxResponse);
		
	},

	buildmenu: function(data) {
		var nodes = new Array();
		var menuContent = ''; //= '<p>more <a href="javascript:blur();" onlick="menuUpdater.prevMenu();"><</a> <a href="javascript:blur();" onlick="menuUpdater.nextMenu();">></a></p>';
		
		nodes = data.getElementsByTagName('imageItem');


		for(i=0;i<nodes.length;i++) {
			var imageNode = new Object();
			
			var thumb = nodes[i].getElementsByTagName('thumb');
			var image = nodes[i].getElementsByTagName('image');
			var tag = nodes[i].getElementsByTagName('tag');
			var tagText = '';
			
			for (var j=0; j<tag.length; j++) {
				tagText += tag[j].firstChild.nodeValue + '<br/>';
			}
			
			//menuContent += '<a href="javascript:void(0);" onfocus="blur();" onclick="showImage('+i+');blur();"><img src="images/' + this.sectionName + '/' +thumb[0].firstChild.nodeValue+ '" alt=""/></a>';
			menuContent += '<img src="images/' + this.sectionName + '/' +thumb[0].firstChild.nodeValue+ '" onclick="showImage('+i+');blur();" alt=""/>';
			this.pageArray.push([thumb[0].firstChild.nodevalue, image[0].firstChild.nodeValue, tagText]);
		}
		
		document.getElementById('lnav').innerHTML = menuContent;

		this.setMenu(0);
	},

	setMenu: function(pageNum) {
		var item = this.pageArray[pageNum];
		this.currentPage = pageNum;
		
		document.getElementById('image').innerHTML = '<img src="images/' + this.sectionName + '/' + item[1] + '"/>';
		document.getElementById('tag').innerHTML = item[2];
		
		this.setNavState();	
	},

	nextMenu:  function() {
		if (this.currentPage < (this.pageArray.length - 1)) {
			this.currentPage++;
			this.setNavState();
		}
    },

	prevMenu:  function() {
		if (this.currentPage > 0) {
			this.currentPage--;
			this.setNavState();
		}
    },

	setNavState: function() {
		var activeID = this.currentPage;
		var links = new Array();
	    links = document.getElementById('lnav').getElementsByTagName('a');

		for (var i=1;i<(links.length-1);i++) {
			if (activeID == links[i].id) {
				links[i].className = "down";
			}
			else {
				links[i].className = "up";
			}
		}
	},

	reset: function() {
		if (this.currentPage != 0) {
			this.currentPage = 0;
			this.setNavState();
			ajaxEngine.sendRequest('getXML');
		}
	}
}
