Wiking.Player=new function()
{//wiking player version 2.0
    var obj=new Array();
    var started=0;
    var dates = [0,0];
    var step = 0;
    var interv = false;
    var speed = 80;
    this.setDates = function(from, to)
    {
        dates = [parseInt(from),parseInt(to)];
        started = 0;
        step = dates[0];
        speed = 80;
    }
    this.play = function(resume)
    {
        if (started==0)
        {
            obj=Wiking.getObjects();
            step = dates[0];
            for (var i=0, l=obj.length;i<l;i++)
            {//temp TODO: metoda obiektu histori setStep
                obj[i].setStep(0);
                //this.obj[i].Pojazd.options.set('point',new TLngLat(this.obj[i].arr[0][0],this.obj[i].arr[1][0]));
            }
            Wiking.Event.trigger({'e':'newpos'});
            //reset paths
        }
        started=1;
        interv = window.setInterval(do_step.bind(this),speed); //
    }
    this.setSpeed=function(x)
    {// 10 - 50
        speed=x;
        if (interv)
        {
            window.clearInterval(interv);
            interv = window.setInterval(do_step.bind(this),speed);
        }
    }
    this.pause=function()
    {
        window.clearInterval(interv);
        interv = false;
    }
    this.stop=function()
    {
        this.pause();
        started = 0;
    }
    // most important :
    var do_step = function()
    {
        for (var i=0, l=obj.length;i<l;i++)
        {
             if (step >= obj[i].getNextStepDate())
             { // jeżeli obiekt dla tego czasu posiada jakąś pozycję to:
                 obj[i].nextStep();
                 Wiking.Event.trigger({'e':'newpos'});
             }
        }
        step+=10;   // TODO hehe ;-) 
        
        // obsługa flasha
        Wiking.Event.trigger({'e':'playerstep'});
        //end
        if (step>dates[1])
        {
            //console.debug('playback end');
            window.clearInterval(interv);
            Wiking.Event.trigger({'e':'playbackend'});
        }
        //debug
        if (step%100==0)
        {
           // console.debug(new Date(parseInt(step+"000")));
        }
    }
    this.jumpTo = function(percent)
    {
        if (interv)
        {
            this.pause();
            var paused = true;
        }
        else
        {
            var paused = false;
        }
        var s = dates[1]-dates[0];
        s = Math.round(s*percent);
        s+= dates[0];
        step = s;
        //console.debug("s: "+s+" percent: "+percent);
        if (!started)
        {
            obj=Wiking.getObjects();
            started = true;
        }
        for (var i=0, l=obj.length;i<l;i++)
        { //TODO: clear object steps      
            obj[i].jumpTo(step);
        }
        if (paused)
        {
            this.play();
        }
    }
    this.setStep = function(instep)
    {
        if (interv)
        {
            this.pause();
            var paused = true;
        }
        else
        {
            var paused = false;
        }
        if (instep < dates[0])
        {
            step = dates[0];
        }
        else if (instep > dates[1])
        {
            step = dates[1];
        }
        step = instep;
        if (!started)
        {
            obj=Wiking.getObjects();
            started = true;
        }
        for (var i=0, l=obj.length;i<l;i++)
        { //TODO: clear object steps      
            obj[i].jumpTo(step);
        }
        if (paused)
        {
            this.play();
        }
    }
    this.getStep = function()
    {
        return step;
    }
    this.toString = function()
    {
        return "Player";
    }
}

Wiking.PlayerInterface = new function() // TODO: reinit przy reloadzie
{
    var binded = false;
    var playbutton = false;
    var setDateText = function(step)
    {
        var d = new Date(step*1000);
        var hours;
        var minutes;
        if ((hours = String(d.getHours())).length==1)
        {
            hours="0"+hours;
        }
        if ((minutes = String(d.getMinutes())).length==1)
        {
            minutes="0"+minutes;
        }
        var date = extend(d.getDate())+"-"+extend(d.getMonth()+1)+"-"+String(d.getFullYear()); //TODO extend + 0
        $('playerDate').innerHTML="<strong>"+(hours+":"+minutes)+"</strong><br /><small>"+date+"</small>";
    };
    var extend = function(s)
    {
        s = String(s);
        if (s.length==1)
        {
            s = "0"+s;
        }
        return s;
    };
    var onStep = function()
    {
        var step = Wiking.Player.getStep();
        var dates = Wiking.DataLoader.getPeriod();
        var x = step-dates[0]; // - x px
        var y = dates[1]-dates[0]; // - 148 px;
        $('bar').style.width=(Math.round(x*123/y))+"px";
        $('playerhand').style.marginLeft=(Math.round(x*123/y)-8)+"px"
        setDateText(step);
    }
    var play = function()
    {
        if (!playbutton)
        {
            Wiking.Player.play()
            $('play').innerHTML="||"; //TODO!
            playbutton=true;
        }
        else
        {
            Wiking.Player.pause();
            $('play').innerHTML='<img src="/wimg/play.png" style="margin-left:2px;">';
            playbutton=false;
        }
    }
    var tmpDragStart;
    var dragStart = function(e)
    {
        Event.stop(e);
        Wiking.Player.pause();
        tmpDragStart = e.pointerX();
        Event.observe(document.body,'mousemove',drag);
        Event.observe(document.body,'mouseup',dragEnd);
    }
    var dragEnd = function(e)
    {
        Event.stop(e);
        Event.stopObserving(document.body,'mouseup',dragEnd);
        Event.stopObserving(document.body,'mousemove',drag);
        var percent = Math.round(parseInt($('bar').style.width)*100/125)/100        
        Wiking.Player.jumpTo(percent);
        onStep();
        if (playbutton)
        {
            Wiking.Player.play();
        }
    }.bind(this);
    var drag = function(e)
    {
        Event.stop(e);
        var diff = tmpDragStart - e.pointerX();
        var x = parseInt($('playerhand').style.marginLeft)-diff;
        //var x2 = parseInt($('bar').style.marginLeft)-diff;
        tmpDragStart= e.pointerX();
        if (x < -8)
        {
            x = -8;
        }
        else if (x > 115)
        {
            x = 115;
        }
        $('bar').style.width=x+8+"px";
        $('playerhand').style.marginLeft=x+"px";
    }.bind(this);
    var playbackend = function()
    {
        $('play').innerHTML='<img src="/wimg/play.png" style="margin-left:2px;">';
        playbutton=false;
    }.bind(this);
    var changeSpeed = function()
    {
        switch($('speed').innerHTML)
        {
            case "1x":
            $('speed').innerHTML="2x";
            Wiking.Player.setSpeed(160);
            break;
            case "2x":
            $('speed').innerHTML="3x";
            Wiking.Player.setSpeed(80);
            break;   
            case "3x":
            $('speed').innerHTML="4x";
            Wiking.Player.setSpeed(40);
            break;    
            case "4x":
            $('speed').innerHTML="5x";
            Wiking.Player.setSpeed(20);
            break;    
            default:
            $('speed').innerHTML="1x";
            Wiking.Player.setSpeed(320);
            break;
        }
    }
    this.showMove = function()
    {// wyświetlanie na pasku playera okresów ruchu
     /*
      * TODO: ta metoda wymaga poprawek. koniecznie.
      */
        var cn = $('barfather').childNodes;
            for (var i=2,l=cn.length;i<l;i++) // tu jest zapewne problem na IE
            {
                Element.remove(cn[i]);
            }
        var obj = Wiking.getObjects();
        var len = obj.length;
        var array = [];
        while(len--)
        {
            if(obj[len].getFlag('data'))
            {
                array = array.concat(obj[len].getData()[3]);
            }
        }            
        if (array.length==0)
        {
            return
        }
        
        array.sort();
        len = array.length;
        this.przedzialy = [array[len-1]];
            //przedzialy.push(array.first());
        while(len>0)
        {
            len-=2;
            if (array[len+1]-array[len] > 600) // jeśli przedział większy niż x sec
            {
                this.przedzialy.push(array[len+1]);
                this.przedzialy.push(array[len]);
            }
        }
        this.przedzialy.push(array[0]);
        this.przedzialy.reverse();
        
        var dates = Wiking.DataLoader.getPeriod();
        var x; // - x px
        var y = dates[1]-dates[0]; // - 148 px;
        var lon = 0;
        var div = document.createElement("div");
            div.style.cssText="opacity: 0.5; position: absolute; margin-left: 1px; margin-top: -5px; height:4px; filter: alpha(opacity=50);";
        document.getElementById('barfather').appendChild(div);
        
        var div2;
        
        var start = 0;
        var margin=0;
        len = this.przedzialy.length;
        i = -2;
        while((i+=2)<len)
        {
            //oldfix = start+lon;
            x = this.przedzialy[i]-dates[0];
            start = (Math.round(x*122/y));
            lon = Math.round(((this.przedzialy[i+1]-dates[0])*122)/y)-start+1;
            if (lon<1)
            {
                continue
            }
            var div2 = document.createElement("div");
                div2.style.cssText="float:left;background:#aaa; height:4px;width:"+lon+"px;margin-left:"+(start-margin)+"px;";
            div.appendChild(div2);
            
            margin = start+lon;
        }
    }
    this.toNext = function()
    {
        var fromstep = Wiking.Player.getStep();
        
        for (var i=0,l=this.przedzialy.length;i<l;i++)
        {
            if (fromstep > this.przedzialy[i])
            {
                continue
            }
            //console.debug("setstep: ",new Date(this.przedzialy[i]*1000));
            Wiking.Player.setStep(this.przedzialy[i]+1);
            //console.debug('getstep:',new Date(Wiking.Player.getStep()*1000));
            onStep();
            break;
        }
    },
    this.init = function()
    {
        if (!binded)
        {
            Wiking.Event.bindAsEventListener(this,'playerstep',onStep);
            Wiking.Event.bindAsEventListener(this,'playbackend',playbackend);
            $('play').observe('click',play.bind(this));
            $('playerhand').observe('mousedown',dragStart.bind(this));
            $('speed').observe('click',changeSpeed.bind(this));
            $('toNext').observe('click',this.toNext.bind(this));
            binded=true;
        }
        var dates = Wiking.DataLoader.getPeriod();
        onStep();
        
        this.showMove();
        
        $('play').innerHTML='<img src="/wimg/play.png" style="margin-left:2px;">';
        $('speed').innerHTML="1x";
        playbutton=false;
        //$('wikingPlayerID').jumpTo(0,1);
        //$('wikingPlayerID').pause();
        setDateText(dates[0]);
    }
};

