/**
* Copyright (c) InOut TV 2008
* @file drag.js
* @author Albert Daurell
* @brief Drag and drop layers
* @date 07/03/08
*/

var Drag = {

	obj : null,
	objWheel : null,

	init : function(obj, minY, maxY, owner)
	{
	    obj.owner=owner;
	    obj.onmousedown	= Drag.start;
		obj.selfRef = obj;
		obj.minY	= typeof minY != 'undefined' ? minY : null;
		obj.maxY	= typeof maxY != 'undefined' ? maxY : null;
		if (isNaN(parseInt(obj.selfRef.style.top   ))) obj.selfRef.style.top    = "0px";
		if (isNaN(parseInt(obj.selfRef.style.bottom))) obj.selfRef.style.bottom = "0px";
		obj.selfRef.onDrag	= new Function();
		Drag.objWheel=obj;
		
	},

	start : function(e)
	{        
        var o = Drag.obj = this;
		e = Drag.fixE(e);
		var y = parseInt(o.selfRef.style.top);
        
		o.lastMouseY	= e.clientY;

		if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
		if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		
		document.onmousemove	= Drag.drag;
		document.onmouseup		= Drag.end;

		return false;
	},

	drag : function(e)
	{
	    e = Drag.fixE(e);
		var o = Drag.obj;
		
		var ey	= e.clientY;
		var y = parseInt(o.selfRef.style.top);
		
		if (o.minY != null) ey = Math.max(ey, o.minMouseY);
		if (o.maxY != null) ey = Math.min(ey, o.maxMouseY);

		var ny = y + ((ey - o.lastMouseY) * 1);

		Drag.obj.selfRef.style["top"] = ny + "px";

		Drag.obj.lastMouseY	= ey;

		Drag.objWheel.lastWheelY = 0;

		Drag.obj.selfRef.onDrag(ny);
		return false;
	},

    wheel: function(e,ey)
    {
        if(!IOLayers.isVisible(Drag.objWheel.owner)) return false;
        
        Drag.obj=Drag.objWheel;
        
        e = Drag.fixE(e);
		
		var o = Drag.obj;
	
		var y = parseInt(o.selfRef.style.top);

        o.lastWheelY=parseInt(Drag.obj.selfRef.style["top"]);
        ey=o.lastWheelY+ey;
        
        o.minWheelY=0;
        o.maxWheelY=o.maxY;
                            
		if (o.minY != null) ey = Math.max(ey, o.minWheelY);
		if (o.maxY != null) ey = Math.min(ey, o.maxWheelY);

        var ny = y + ((ey - o.lastWheelY) * 1);

		Drag.obj.selfRef.style["top"] = ny + "px";

		Drag.obj.selfRef.onDrag(ny);
		
		return (ey - o.lastWheelY)!=0;
		
    },
    
    end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};

