gallery = {}
var img_path = '../images/';
var img_array = ['chicken_salad.jpg', 'caesar_salad.jpg', 'shrimp_salad.jpg', 'house_salad.jpg', 
								 'chicken_crepe.jpg', 'wings.jpg', 'burger.jpg', 'fish_chips.jpg', 
								 'sweet_potatoe_fries.jpg', 'onion_rings.jpg', 'ribeye.jpg', 'cheesecake.jpg',
								 'bar.jpg', 'bar3.jpg', 'dining_room1.jpg', 'dining_room2.jpg'];
var IMGS_PER_ROW = 4;
var THUMB_W = 100;
var THUMB_H = 75;
var img_selected = 0;
var imageObj = new Image();
var ident;

gallery.preload_images = function() {
	/* Dynamically load images into a table as thumbnails
	 *
	 */
	var tbody = getElement('tbody_thumbs');
	var num_rows = Math.ceil(img_array.length / IMGS_PER_ROW);
	
	var index = 0;
	for(i=0; i<num_rows; i++) {
		row = TR(null);
		for(var j=0; j<IMGS_PER_ROW; j++) {
			log(index);
			if(index > img_array.length-1) 
				row.appendChild(TD(null, ''));
			else
				row.appendChild(TD({'class':'thumb'},
													 A({'href':'#','onclick':'return gallery.show_modal(this, '+index+');'},
															IMG({'src':img_path+img_array[index], 'height':THUMB_H, 'width':THUMB_W,
																	 'style':{'border':'1px solid black'}}))));
			index += 1;
		}
		tbody.appendChild(row);
	}
}

gallery.show_image = function(index) {
	img_selected = index;
	if(index>img_array.length-1)
		img_selected = 0;
	else if(index<0)
		img_selected = img_array.length-1;
		
	var modal = getElement('modal_content');
	imageObj.src = img_path+img_array[img_selected];

	replaceChildNodes(modal, IMG({'src':img_path+img_array[img_selected],
															  'alt':'', 'border':'0', 
																'height':imageObj.height,
																'width':imageObj.width}));
	
	getElement('numberDisplay').innerHTML = 'Image '+(img_selected+1)+' of '+img_array.length;
	var thispop = Popup.get('modal');
	if(thispop) {
		getElement('modal') .style.width = (imageObj.width + 15) +'px';
		thispop.transition();
	}
	return false;
}

gallery.show_modal = function (obj, index) {
	var ind = (index)? index : 0;
	Popup.showModal('modal');
	gallery.show_image(ind);
	ident = connect(document, 'onkeydown', 
							function(e) {
								var e_str = e.key().string;
								if(e_str=='KEY_ESCAPE') {
									Popup.hide('modal');
									disconnect(ident);
								}
								else if(e_str=='KEY_ARROW_RIGHT') 
									gallery.show_image(++img_selected);
								else if(e_str=='KEY_ARROW_LEFT')
									gallery.show_image(--img_selected);
							});
	
	return false;
}

function innerDimensions() {
  if (self.innerHeight) {
    return [self.innerWidth, self.innerHeight];
  } else if (document.documentElement && document.documentElement.clientHeight) {
		log('1');
    return [document.documentElement.clientWidth, document.documentElement.clientHeight];
  } else if (document.body) {
		log('2');
    return [document.body.clientWidth, document.body.clientHeight];
	}
  return [0, 0];
}
