Ext.onReady(function(){
	if (Ext.get('image_list')) {
		var selected_node;
		
		// create the required templates
		var image_template = new Ext.Template(
			'<div id="{name}" class="thumb_wrapper">'
			+ '<div class="thumbnail"><div style="border: 1px solid #000000; height: 97px; overflow: hidden; width: 120px;"><img src="{src}" title="{name}" width="120"></div></div>'
			+ '</div>'
		);
		image_template.compile();
		
		var detail_template = new Ext.Template(
			'<div style="text-align: center;"><img src="{src}" title="{name}"></div>'
		);
		detail_template.compile();
		
		// initialize the View		
		var view = new Ext.JsonView('image_list', image_template, {
			singleSelect: true,
			jsonRoot: 'images',
			emptyText : '<div style="padding:10px;">No images match the specified filter</div>'
		});
		
		view.load({
			url: '/scripts/portfolio.json.php',
			callback: function() {
				//view.select(0);
			}
		});
		
		view.on('selectionchange', function(view, nodes) {
			selected_node = nodes[0];
			if(selected_node && view.getCount() > 0){
				var data = image_data[selected_node.id];

				detail_template.overwrite(dialog_bd, data);

				dialog.show(selected_node.id);
			}
		});
		
		// Get all the image information into an array, so we can use it later
		var image_data = {};
		
		view.prepareData = function(data){
			image_data[data.name] = data;
			return data;
		};
		
		
		var dialog_div = Ext.DomHelper.append(document.body, {tag: 'div', id: 'dialog'});
		var dialog_bd = Ext.DomHelper.append(dialog_div, {tag: 'div', cls: 'x-dlg-bd'});
		
		var dialog = new Ext.BasicDialog(dialog_div, {
			autoCreate: true,
			closable: true,
			collapsible: false,
			draggable: true,
			resizable: false,
			proxyDrag: true,
			shadow: true,
			modal: true,
			fixedCenter: true
		});
		
		dialog.addButton("PREVIOUS", function() {
			dialog.hide(function () {
				var previous_node = view.indexOf(selected_node) - 1;
				if (previous_node < 0) {
					previous_node = view.getCount() - 1;
				}
				view.select(previous_node);
			});
		});
		
		dialog.addButton("NEXT", function() {
			dialog.hide(function() {
				var next_node = view.indexOf(selected_node) + 1;
				if (next_node == view.getCount()) {
					next_node = 0;
				}
				view.select(next_node);
			});
		});
		
		dialog.addButton("CLOSE WINDOW", function() {
			dialog.hide();
		});
		
		dialog.setContentSize(341, 275);
		dialog.center();
	}
});