/*
 * 图片浏览器
 */
Fangbole.ImageViewer = Class.create({
	initialize: function(elMainImage, elList, url, options){
		this.elMainImage = $(elMainImage);
		this.elList = $(elList);
		this.url = url;
		this.images = [];
		this.current = null;
		this.options = Object.extend({
			//TODO: max height
			maxDimension: [300, 300],
			start: [0, 0],
			onLoadList: Prototype.emptyFunction,
			onView: Prototype.emptyFunction,
			paginator:null
		}, options || {})
		
		this.imageCache = new Element('img');
		this.imageCache.observe('load', this.onLoadFulImage.bind(this));
		this.elList.observe('click', this.onClickList.bindAsEventListener(this));
		
		if(!this.options.paginator){
			this.paginator=new Fangbole.Paginator({page: this.options.start[1]});
			this.paginator.render(this.elList, 'after');
		}else{
			this.paginator=this.options.paginator;
		}
		this.query = new Fangbole.Query({
			page: this.paginator
		})
		this.pageRequest = new Fangbole.PageRequest(this.elList, this.url, this.query, Fangbole.Template.newHouse.defaults.imageViewer, {
			onSuccess: function(result){
				this.paginator.update({total: result.total, page: result.page});
				this.onLoadList(result);
			}.bind(this)
		})
		this.pageRequest.listen('page');
		this.pageRequest.refresh();
		
	},
	onClickList: function(e){
		var elt = e.element();
		if(elt.tagName.toUpperCase() == 'IMG'){
			var elItem = elt.up('li')
			var pid = elItem.id.replace('photo_', '');
			this.view(pid);
		}
	},
	onLoadList: function(data){
		this.options.onLoadList();
		this.images = data.data;
		var els = this.elList.select('li');
		this.images.each(function(image, i){
			image.element = els[i];
		})
		if(!this.current)
			this.view(this.options.start[0]);
		
	},
	onLoadFulImage: function(){
		this.elMainImage.src = this.imageCache.src;
	},
	view: function(pid){
		var maxWidth = this.options.maxDimension[0],
			photo = this.images.find(function(image){return image.id == pid}) || this.images[0];
		
		if(photo){
			if(this.current)
				this.current.element.removeClassName('current');
			this.current = photo;
			this.current.element.addClassName('current');	
			
			if(photo.width > maxWidth){
				this.elMainImage.width = maxWidth;
				this.elMainImage.height = maxWidth * photo.height / photo.width;
			}else{
				this.elMainImage.width = photo.width;
				this.elMainImage.height = photo.height;
			}
			this.elMainImage.src = photo.tURL;
			this.imageCache.src = photo.fURL;
			this.options.onView(photo);
		}	
	}
})
