
var cmarket = {
	version: 1.0
};

cmarket.ItemPopupManager = Class.create();

cmarket.ItemPopupManager.prototype = {
	initialize: function(selector, options) {
		this.cache = {};
		this.timer = null;
		
        this.options = Object.extend({ offsetLeft: 20, offsetTop: -40, prefix: 'item_' }, options || {});;
        
        this.evtfn_display = this.display.bindAsEventListener(this);
        this.evtfn_hide = this.hide.bindAsEventListener(this);

		this.setup();
		this.registerForPopup(selector);
	},
	setup: function() {
		var dropdowns = document.getElementsByTagName('select');
		for (var i = 0; i < dropdowns.length;  ++i) {
			dropdowns[i].style.zIndex = "1";
		}
		
		// preload images used by popups
		var tttop = new Image();
		tttop.src = "/img/auction/tooltip_top.gif";
		
		var ttbtm = new Image();
		ttbtm.src = "/img/auction/tooltip_btm.gif";
		
		var ptrleft = new Image();
		ptrleft.src = "/img/auction/tooltip_pointer.gif";
		
		var ptrright = new Image();
		ptrright.src = "/img/auction/tooltip_pointer_rgt.gif";
		
		this.container = this.createContainer();
		document.body.appendChild(this.container);
		
		if (navigator.userAgent.indexOf("MSIE") != -1) {
			this.shim = this.createShim();
			document.body.appendChild(this.shim);
		}
	},
	display: function(e) {
		var target = Event.findElement(e, 'a');

		if (!target) { return; }

		var itemId = target.getAttribute("itemId") || target.itemId;

		if (this.timer) {
			clearTimeout(this.timer);
			this.timer = null;
		}
		
		// set timeout for 1 second
		this.timer = setTimeout(this.displayPopup.bind(this, Event.findElement(e, 'a'), Event.pointerX(e), Event.pointerY(e)), 1000);
	},
	displayPopup: function(target, eventX, eventY) {
		if (!target) { return; }

		var itemId = target.getAttribute("itemId") || target.itemId;

		if (!this.cache[itemId]) {
			this.cache[itemId] = new cmarket.ItemPopup(this.container, this.shim, itemId, eventX, eventY, this.options);
		} else {
			this.cache[itemId].update(eventX, eventY);
			this.cache[itemId].show();
		}
	},
	hide: function(e) {
		// clear timeout
		if (this.timer) {
			clearTimeout(this.timer);
			this.timer = null;
		}

		var target = Event.findElement(e, 'a');

		if (!target) { return; }

		var itemId = target.getAttribute("itemId") || target.itemId;
		
		if (!this.cache[itemId]) { return; }
		
		this.cache[itemId].hide();
	}, 
	registerForPopup: function(selector) {
		var items = $$(selector);
		
		for (var i=0; i < items.length; ++i) {
		    var itemid = items[i].id.sub(this.options.prefix, '');

			var links = items[i].getElementsByTagName('a');
			for (var j = 0; j < links.length; ++j) {
				this.addListeners(links[j], itemid);
			}
		}
	},
	unregisterForPopup: function(selector) {
        var items = $$(selector);
        
        for (var i=0; i < items.length; ++i) {
            var links = items[i].getElementsByTagName('a');
            
            for (var j = 0; j < links.length; ++j) {
                this.removeListeners(links[j]);
            }
        }
	},
	addListeners: function(link, itemId) {
		if (link.setAttribute) {
			link.setAttribute("itemId", itemId);
		} else {
			link.itemId = itemId;
		}

        Event.observe(link, 'mouseover', this.evtfn_display, false);
        Event.observe(link, 'focus', this.evtfn_display, false);
        Event.observe(link, 'mouseout', this.evtfn_hide, false);
        Event.observe(link, 'blur', this.evtfn_hide, false);
	},
	removeListeners: function(link) {
        Event.stopObserving(link, 'mouseover', this.evtfn_display, false);
        Event.stopObserving(link, 'focus', this.evtfn_display, false);
        Event.stopObserving(link, 'mouseout', this.evtfn_hide, false);
        Event.stopObserving(link, 'blur', this.evtfn_hide, false);
	},
	createContainer: function() {
	    var container = $('itempopup');
	    
	    if (container) {
	       return container;
		}
		
		container = document.createElement('DIV');
		
		container.id = 'itempopup';
		container.className = 'tooltip';
		container.style.position = 'absolute';
		container.style.display = 'none';
		container.innerHTML = '<div class="tooltipbox"></div>';

		return container;
	},
	createShim: function() {
    	var shim = document.createElement("<iframe scrolling='no' frameborder='0' src='/cmarketplace/blank.jsp' style='position:absolute; top:-1000px; left:-1000px; display:none'></iframe>"); 

		// make it transparent
	    shim.style.filter="progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";
		shim.style.position = "absolute";
		shim.style.display = "block";
		shim.style.zIndex = 50;
    
    	return shim;
	}
};

cmarket.ItemPopup = Class.create();

cmarket.ItemPopup.prototype = {
	initialize: function(container, shim, itemId, eventX, eventY, options) {
		this.container = container;
		this.itemId = itemId;
		this.eventX = eventX;
		this.eventY = eventY;
		this.loading = true;
		this.showing = true;
		this.options = options;
		this.content = null;
		this.shim = null;
		this.setup();
	},
	setup: function() {
		new Ajax.Request('/auction/item/Item.action?tooltip', {method:'get', parameters:"id=" + this.itemId, onSuccess:this.handleUpdate.bind(this), onFailure:this.handleError.bind(this) });
	},
	handleUpdate: function(request) {
		this.content = request.responseText;
		this.loading = false;
		
		if (!this.showing) { return; }
		
		this.update();
		this.show();
	},
	handleError: function(request) {
	},
	show: function() {
		this.showing = true;

		if (this.loading) { return; }
		if (!this.content) { return; }
		
		var container = $(this.container);
		var tooltipbox = $(container).select('.tooltipbox')[0];
		
		$(tooltipbox).replace(this.content);
		
		this.update();
		$(this.container).show();
		
		if (this.shim) {
			this.shim.show();
		}
	},
	hide: function() {
		$(this.container).hide();
		
		if (this.shim) {
			$(this.shim).hide();
		}
		
		this.showing = false;
	},
	update: function(evx, evy)  {
		if (evx) {
			this.eventX = evx;
		}
		if (evy) {
			this.eventY = evy;
		}
		
		var windim = this.getWindowDimensions();
		var popdim = Element.getDimensions(this.container);
		
		var x = this.eventX + this.options.offsetLeft;
		var y = this.eventY + this.options.offsetTop;
		
		Position.prepare();
		var yoffset = Position.deltaY;
		var popy = y + popdim.height;
		var popx = x + popdim.width;
		if ((x + popdim.width) > (Position.deltaX + windim.width)) {
			// subtract two times offsetLeft to counter the adding of offsetLeft
			x = x - popdim.width - (this.options.offsetLeft * 2);
			this.switchPointer('right');
		} else {
			this.switchPointer('left');
		}
		if ((y + popdim.height) > (Position.deltaY + windim.height)) { 
			y = y - this.options.offsetTop - ((y + popdim.height) - (Position.deltaY + windim.height));
		}
		
		this.container.style.left = x+"px";
		this.container.style.top = y+"px";
		
		if (this.shim) {
			this.shim.style.left = x+"px";
			this.shim.style.top = y+"px";
			this.shim.width = popdim.width;
			this.shim.height = popdim.height;
		}
	},
	getWindowDimensions: function() {
		var dims = {};
		
		dims.height = self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0;
		dims.width = self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0;
		
		// take off some space in firefox for scrollbar
		if (self.innerWidth) {
			dims.width = dims.width - 20;
		}
		
		return dims;
	},
	switchPointer: function(side) {
		if ($('tipptrleft')) { $('tipptrleft').remove();  }
		if ($('tipptrrgt')) { $('tipptrrgt').remove();  }
	
		if (side == 'right') {
			new Insertion.Bottom($('itempopup'), '<div id="tipptrrgt"><img src="/img/auction/tooltip_pointer_rgt.gif" width="42" height="66" alt="" /></div>');
		} else {
			new Insertion.Top($('itempopup'), '<div id="tipptrleft"><img src="/img/auction/tooltip_pointer.gif" width="42" height="66" alt="" /></div>');
		}
	}
};

