﻿/***********************************************
* CMotion Image Gallery- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* Visit http://www.dynamicDrive.com for source code
* This copyright notice must stay intact for legal use
* Modified for autowidth and optional starting positions in
* http://www.dynamicdrive.com/forums/showthread.php?t=11839 by jschuer1 8/5/06
***********************************************/

//
// some changes
// Yakovlev I. V. aka LeXX
// Boiko A. S. aka Alex_B
//


MotionPanel = function(crossmain, direction, restarea, maxSpeed, startposV, startposH)
{
    // переменные определяемые пользователем
    this._Crossmain = crossmain;    // DIV маска (первый ребенок этого дива должен быть прокручиваемым DIV)
    this._Direction = direction;    // Направление (0 - горизонтальное, 1 - вертикальное, 2 - во всех направлениях)
    this._Restarea = restarea;      // Высота области по центру  при наведении на которую DIV "не крутится"
    this._MaxSpeed = maxSpeed;      // Максимальная скорость кручения DIV
    this._StartposV = startposV;    // Начальная позиция по вертикали (1 for left start, 0 for right, 2 for center)
    this._StartposH = startposH;    // Начальная позиция по горизонтали
    
    
    // Свойства
    
    this._ActualHeight = null;  // Высота прокручиваемого DIV
    this._MenuHeight = null;    // Высота DIV маски
    
    this._ActualWidth = null;   // Ширина прокручиваемого DIV
    this._MenuWidth = null;     // Ширина DIV маски
    
    
    this._BottomTime = null;
    this._TopTime = null;
    
    this._LeftTime = null;
    this._RightTime = null;
    
    
    this._MoveStateV = null;
    this._ScrollSpeedV = null;   // Текущая скорость
    
    this._MoveStateH = null;
    this._ScrollSpeedH = null;   // Текущая скорость
    
    this._Square = null;
    
    this._init();
}

MotionPanel.prototype = {
    _init : function()
    {
        //debugger;
    
        // Если крутить по горизонтали (или во всех направлениях), то
        //if(this._Direction == 0 || this._Direction == 2)
        //{
            this._MenuWidth = this._Crossmain.offsetWidth;
            this._ActualWidth = this._Crossmain.scrollWidth;
        //}
        // Если крутить по вертикали (или во всех направлениях), то
        //else if(this._Direction == 1 || this._Direction == 2)
        //{
            this._MenuHeight = this._Crossmain.offsetHeight;
            this._ActualHeight = this._Crossmain.scrollHeight;
        //}
        
        
        // Выставим необходимые стили прокручиваемому DIV

        // Начальная позиция по горизонтали
        if(this._StartposH == 0)
        {
            this._Crossmain.firstChild.style.left = "0px";
        }
        else
        {
            this._Crossmain.firstChild.style.left = (this._MenuWidth-this._ActualWidth)/this._StartposH+'px';
        }
        
        // Начальная позиция по вертикали
        if(this._StartposV == 0)
        {
            this._Crossmain.firstChild.style.top = "0px";
        }
        else
        {
            this._Crossmain.firstChild.style.top = (this._MenuHeight-this._ActualHeight)/this._StartposV+'px';
        }
        
        this._Crossmain.firstChild.style.position = "absolute";
        
        
        // Повесим обработчики событий на DIV-маску
        
        var me = this;

        // Если крутить по горизонтали
        if(this._Direction == 0)
        {        
            this._Crossmain.onmousemove = function(e){ me._motionengineH(e) };
        }
        // Если крутить по вертикали
        else if(this._Direction == 1)
        {
            this._Crossmain.onmousemove = function(e){ me._motionengineV(e) };
        }
        // Если крутить оп всем направлениям
        else if(this._Direction == 2)
        {
            this._Crossmain.onmousemove = function(e){ me._motionengineA(e) };
        }
        
        
        this._Crossmain.onmouseout = function(e){ me._stopmotion(e) };
        
        
        if (document.body.filters)
            this._onresize();
    },
    
    _ietruebody : function()
    {
        return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
    },

    _getposOffset : function(what, offsettype)
    {
        var totaloffset=(offsettype=="left")? what.offsetLeft: what.offsetTop;
        var parentEl=what.offsetParent;
        
        while (parentEl!=null)
        {
            totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
            parentEl=parentEl.offsetParent;
        }
        
        return totaloffset;
    },
    
    _moveleft : function()
    {
        this._MoveStateH = "left";
        if (parseInt(this._Crossmain.firstChild.style.left)>(this._MenuWidth-this._ActualWidth))
        {
            this._Crossmain.firstChild.style.left = 
                Math.max(this._MenuWidth-this._ActualWidth,
                    parseInt(this._Crossmain.firstChild.style.left)-this._ScrollSpeedH)+"px";
        }
        
        var me = this;    
        this._LeftTime = window.setTimeout( function(){ me._moveleft() },10);
    },
    
    _moveright: function()
    {
        this._MoveStateH = "right";
        if (parseInt(this._Crossmain.firstChild.style.left)<0)
        {
            this._Crossmain.firstChild.style.left = 
                Math.min(0, parseInt(this._Crossmain.firstChild.style.left)+this._ScrollSpeedH)+"px";
        }
        
        var me = this;    
        this._RightTime = window.setTimeout( function(){ me._moveright() },10);
    },
    
    _movetop : function()
    {
        this._MoveStateV = "top";
        if (parseInt(this._Crossmain.firstChild.style.top)>(this._MenuHeight-this._ActualHeight))
        {
            this._Crossmain.firstChild.style.top
                = Math.max(this._MenuHeight-this._ActualHeight,
                    parseInt(this._Crossmain.firstChild.style.top)-this._ScrollSpeedV)+"px";
        }
        
        var me = this;
        this._TopTime = window.setTimeout(function(){ me._movetop() }, 10);
    },
    
    _movebottom : function()
    {
        this._MoveStateV = "bottom";
        if (parseInt(this._Crossmain.firstChild.style.top)<0)
        {
            this._Crossmain.firstChild.style.top =
                Math.min(0,parseInt(this._Crossmain.firstChild.style.top) + this._ScrollSpeedV) + "px";
            //showhidediv("hidden");
        }

        var me = this;
        this._BottomTime = setTimeout( function(){ me._movebottom() },10);
    },
    
    // Обработчик движения мышки над DIV-маска (режим "крутить по горизонтали")
    _motionengineH : function(e)
    {
        var mainobjoffsetX=this._getposOffset(this._Crossmain, "left");
        var dsocx=(window.pageXOffset)? pageXOffset: this._ietruebody().scrollLeft;
        var curposx=window.event ? event.clientX : e.clientX ? e.clientX: "";
    
        curposx-=mainobjoffsetX-dsocx;
        var leftbound=(this._MenuWidth-this._Restarea)/2;
        var rightbound=(this._MenuWidth+this._Restarea)/2;
        
        if (curposx>rightbound)
        {
            this._ScrollSpeedH = (curposx-rightbound)/((this._MenuWidth-this._Restarea)/2) * this._MaxSpeed;
            window.clearTimeout(this._RightTime);
            if (this._MoveStateH!="left")
                this._moveleft();
        }
        else if (curposx<leftbound)
        {
            this._ScrollSpeedH=(leftbound-curposx)/((this._MenuWidth-this._Restarea)/2) * this._MaxSpeed;
            window.clearTimeout(this._LeftTime);
            if (this._MoveStateH!="right")
                this._moveright();
        }
        else this._ScrollSpeedH=0;
    },
    
    // Обработчик движения мышки над DIV-маска (режим "крутить по вертикали")
    _motionengineV : function(e)
    {
        var mainobjoffsetY = this._getposOffset(this._Crossmain, "top");
        //var dsocx=(window.pageXOffset)? pageXOffset: this._ietruebody().scrollLeft;
        var dsocy=(window.pageYOffset)? pageYOffset: this._ietruebody().scrollTop;
        var curposy=window.event? event.clientY : e.clientY? e.clientY: "";
        
        curposy-=mainobjoffsetY-dsocy;
        var topbound=(this._MenuHeight - this._Restarea)/2;
        var bottombound=(this._MenuHeight + this._Restarea)/2;
        
        if (curposy>bottombound)
        {
            this._ScrollSpeedV = (curposy-bottombound)/((this._MenuHeight-this._Restarea)/2) * this._MaxSpeed;
            window.clearTimeout(this._BottomTime);
            if (this._MoveStateV!="top")
            {
                this._movetop();
            }
        }
        else if (curposy<topbound)
        {
            this._ScrollSpeedV = (topbound-curposy)/((this._MenuHeight-this._Restarea)/2) * this._MaxSpeed;
            window.clearTimeout(this._TopTime);
            if (this._MoveStateV!="bottom")
            {
                this._movebottom();
            }
        }
        else
        {
            this._ScrollSpeedV = 0;
        }
    },
    
    _motionengineA : function(e)
    {
        this._motionengineH(e);
        this._motionengineV(e);
    },    
    
    
    //является ли a потомком b (не важно в каком колене)
    _contains_ns6 : function(a, b)
    {
        if (b!==null)
        while (b.parentNode)
        if ((b = b.parentNode) == a)
        return true;
        return false;
    },

    // Уход мыши с динамически созданного DIV
    _stopmotion : function(e, args)
    {
        if (!window.opera||(window.opera&&e.relatedTarget!==null))
            if ((window.event && !this._Crossmain.contains(event.toElement))
                || (e && e.currentTarget && e.currentTarget!= e.relatedTarget
                    && !this._contains_ns6(e.currentTarget, e.relatedTarget)))
            {
                window.clearTimeout(this._TopTime);
                window.clearTimeout(this._BottomTime);
                window.clearTimeout(this._LeftTime);
                window.clearTimeout(this._RightTime);
                
                this._MoveStateV=null;
                this._MoveStateH=null;
                this._Square=null;
            }
    },
    
    
    _onresize : function()
    {
//        if (typeof motioncontainer2!=='undefined'&&motioncontainer2.filters)
//        {
//            motioncontainer2.style.height="0";
//            motioncontainer2.style.height="";
//            motioncontainer2.style.height=Math.min(motioncontainer2.offsetHeight, maxheight)+'px';
//        }
        //debugger;
        this._MenuHeight = this._Crossmain.offsetHeight;
        this._Crossmain.firstChild.style.top=this._StartposV? (this._MenuHeight-this._ActualHeight)/this._StartposV+'px' : 0;
    }
    
}