﻿/**
 * @author pop webdev [cn]
 * @version: 0.2.
 * @classDescription: Detail Image Updater
 * @dependencies: Prototype v1.6.1.
 */
// start DetailImageUpdater
var DetailImageUpdater = Class.create ({
	initialize: function(image,links,options)
	{
		this.image = image;
		this.links = links;
		this.length = this.links.size();
		this.container = this.image.up();
		this.options = Object.extend({
			initialIndex: 0,
			speed: 0.5,
			appearEffect: false,
			activeClassName: 'active'
		}, options || {});
		if (this.options.initialIndex >= this.length)
		{
			this.options.initialIndex = 0;
		}
		this.currentItem = this.options.initialIndex;

		var boundClickHandler = this.__Click.bindAsEventListener(this);
		this.links.invoke('observe', 'click', boundClickHandler);

		// set initial position
		this.SwapImage(this.currentItem);
		
	},
	__Click: function(e)
	{
		e.stop();
		var element = e.findElement('a');
		for (var i=0; i<this.length; i++)
		{
			if (this.links[i] == element)
			{
				this.SwapImage(i);
				// broadcast custom event
				this.container.fire('updater:triggered', {index: i});
				break;
			}
		}
	},
	SwapImage: function(index)
	{
		this.currentItem = index;
		//update detail img
		this.image.setOpacity(0);
		this.image.src = this.links[index].href;
		this.image.alt = this.links[index].title;
		if (this.options.appearEffect)
		{
			this.image.appear({duration: this.options.speed});
		} else {
			this.image.setOpacity(1.0);
		}
		//highlight link
        var activeClassName = this.options.activeClassName;
        this.links.each(function(el, index) {
			el.up().removeClassName(activeClassName);
		}); // un-highlight all links parents
		this.links[index].up().addClassName(activeClassName); // highlight specific link parent
	}
});
// end DetailImageUpdater

