/**
 * SavableImages Class
 * 
 * @author   Volodymyr Iatsyshyn
 * @date     2009-06-01
 * @see
 */

if (!window.Keepa)
	var Keepa = {};

dojo.provide('Keepa.SavableImages');

dojo.declare('Keepa.SavableImages', null, {
	clazz: null,
	menu: null,
	
	constructor: function (c, e) {
		this.clazz = c;
		this.menu = e;
		this.scan();
		
		dojo.connect(e, 'mouseover', this, 'onMouseOver_');
		dojo.connect(e, 'mouseout', this, 'onMouseOut_');
		
		dojo.subscribe('container-size-changed', this, 'onContainerSizeChanged_e_');
	},
	
	onMouseOver_: function (event) {
	    if (event.currentTarget.timer) {
	        clearTimeout(event.currentTarget.timer);
	        event.currentTarget.timer = undefined;
	    }
	},
	
	onMouseOut_: function (event) {
	    this.onMouseOver_({currentTarget: this.menu});
	    
	    var menu = this.menu;
	    event.currentTarget.timer = setTimeout(function () {
	        dojo.style(menu, 'display', '');
	    }, 1500);
	},
	
	onContainerSizeChanged_e_: function () {
		this.scan();
		
		return this;
	},
	
	scan: function (e) {
		dojo.query('.' + this.clazz, e).forEach(function (el) {
			if (!el.upBind_)
				el.upBind_ = dojo.connect(el, 'contextmenu', this, 'onItemMouseUp_');
		}, this);
	},
	
	onItemMouseUp_: function (event) {
		this.showMenu(event.currentTarget, event.clientX, event.clientY);
		event.preventDefault();
		event.stopPropagation();
		
		return this;
	},
	
	showMenu: function (target, x, y) {
		this.menu.target = target;
		this.onMouseOut_({currentTarget: this.menu});
		
		dojo.style(this.menu, {
			display: 'block',
			left: x + 'px',
			top: y + 'px'
		});
		
		return this;
	}
});

dojo.mixin(Keepa.SavableImages, {
	initialize: function () {
		new Keepa.SavableImages('savable', dojo.byId('context-menu'));
		return this;
	}
});

dojo.addOnLoad(Keepa.SavableImages, 'initialize');