


ProductImageViewer = Class.create({
  initialize: function() {
	this.imageCount = 0;
	this.imageArea = this.down('.MainImageArea');
	this.thumbs = new Array();
	this.selectedIndex = 0;
	var c = 0;
	var i = this.down('.ImageNav .item', c++);
	while(i){
		this.thumbs.push(i);
		i.observe('click', this.onThumbClicked.bind(this, c-1));
		i = this.down('.ImageNav .item', c++);
	}

	this.imageData = new Array();
	this.imageLookup = {};
	var link = this.imageArea.down('a');
	this.addImage(link);
	this.doAdjust(0);

  },
  addImage: function(link, index)
  {
	if(index === undefined)
		index = 0;
	var img = link.down('img');
	var url = link.href;

	var id = url.split('get=')[1].split('_')[0];
	this.imageData[index] = {
		id:id,
		link: link,
		image: img
	};
	img.observe('load', this.doAdjust.bind(this, index));
	this.imageLookup[id] = index;
	link.makePositioned();
	img.makePositioned();
	this.imageCount++;

  },
  createImage: function(id){
	var ourl = 'images.php?get=' + id + '_original';
	var durl = 'images.php?get=' + id + '_productdetail';
	this.imageArea.insert(
		'<a href="' + ourl + '" target="_blank" style="display:none;">' +
			'<img src="' + durl + '"/>' +
		'</a>'
	);
	return this.imageArea.down('a', this.imageCount);
  },
  onThumbClicked: function (index){
//	alert(index);
	this.hideAll();
	if(!this.imageData[index]){
		var tId = this.thumbs[index].down('img').src.split('get=')[1].split('_')[0];
		this.addImage(this.createImage(tId), index);
	}else{
		this.imageData[index].link.show();
	}
  },
  doAdjust: function (index){
  	var link = this.imageData[index].link;
  	link.show();
	var img = this.imageData[index].image;
   	var d = img.getDimensions();


  	link.style.top = -(d.height/2) + 'px';
  	link.style.left = -(d.width/2) + 'px';
  },
  hideAll: function(){
  	var c = 0;
	var i = this.imageArea.down('a', c++);
	while(i){
		i.hide();
		i = this.imageArea.down('a', c++);
	}
  }
});

