var $Y = (function(){
    return {
        'SELECT' : YAHOO.util.Selector.query,
        'EVENT' : YAHOO.util.Event,
        'DOM' : YAHOO.util.Dom
    };
}());


var videoPlayer = function(node,sponsor){
    
    this.container = node;    
    this.playerArea = $Y.SELECT('.video-player', this.container, true);

    this.initializePlaylists(); /* provides this.playList */

    this.currentNode = $Y.SELECT('.current', this.playList, true);
    
    this.autoplay = false;
    
    this.splash = null;

    if(this.currentNode === null){
        this.currentNode = $Y.DOM.getFirstChild(this.playList);
        $Y.DOM.addClass(this.currentNode,'current');
    }


    /* looks for video-tools and video-description classes. If they do
     * description and tools will be moved to these places, when the video is
     * changed 
     *
     * Notice; tools haven't been implemented yet
     **/
    this.videotools = $Y.SELECT('.video-tools', this.container, true);
    this.videodesc = $Y.DOM.getElementsByClassName('video-description', 'div', this.container);


    /* Hijack the link to the video pages, and instead activate the player on
     * page, showing the chosen video */
    $Y.EVENT.addListener(
        $Y.DOM.getElementsByClassName('showlisting','a',this.container),
        'click', this.selectedVideo, 
        this, true
    );

    /* Should the player have controlles, others than play/pause? true says yes */
    this.showControlles = true;

    /* Play the current selected video when clicking the thumbnail */
    $Y.EVENT.addListener(
        this.playerArea,
        'click', this.selectedVideo,
        this, true
    );

    /* Add handlers for the toolbox */


    //var playBtn = document.createElement('div');

    //if(YAHOO.env.ua.ie !== 6){ 
        /* the play button graphics is applied using the .video-play-button css 
         * rule. The graphic is a transparent png, so we do not use it for ie6 
         */
    //    playBtn.className = "video-play-button"; 
    //}

    //this.playerArea.appendChild(playBtn);    

    /* initialize html */
    this.setPlayerDescription();
    this.setPlayerThumbNail();
    
    var show = $Y.DOM.getElementsByClassName('showlisting','a',this.currentNode);

    /* this link has a class that is called class_(numbers), we get the 
     * video id by */        
    this.videoId = /clip_(\d*)/.exec(show[0].className)[1];
    this.autoplay = false;
    this.spawnPlayer();

    /* if we are parsed an advert link, we include it between the video and the description */
    if(typeof sponsor === 'object'){

        var advert = document.createElement('p');
        advert.className = "advert-box";
        var advertLink = document.createElement('a');
        advertLink.href = sponsor.link;
        advertLink.innerHTML = sponsor.title;
    
        advert.appendChild(advertLink);
        this.playerArea.parentNode.insertBefore(advert , this.playerArea );
    }        

};

    videoPlayer.prototype.disablePlayerControlles = function(){
        this.showControlles = false;
    };
    
    /* */
    videoPlayer.prototype.selectedVideo = function(e){
        YAHOO.util.Event.preventDefault(e);
        this.stopPlaylistCycling();

        /* Determens if the click is from the playlist, or on the current thumb.
         * If it is from the playlist, it changes the current node to the chosen
         * one. If not, it spawns the player, using the current (eg. the one
         * shown in the thumbnail) */
        if( !$Y.DOM.isAncestor( this.playerArea, $Y.EVENT.getTarget(e) ) ){

            this.changeTo(
                $Y.DOM.getAncestorByTagName(
                    $Y.EVENT.getTarget(e),
                    'li'
                )
            );

        }
        
        /* the event listener on the thumbnail is no longer needed */
        $Y.EVENT.removeListener(this.playerArea, 'click', this.selectedVideo);

        var show = $Y.DOM.getElementsByClassName('showlisting','a',this.currentNode);

        /* this link has a class that is called class_(numbers), we get the 
         * video id by */        
        this.videoId = /clip_(\d*)/.exec(show[0].className)[1];
        this.autoplay = true;
        this.spawnPlayer();
    };

    /* */
    videoPlayer.prototype.setPlayerThumbNail = function(){

        // if($Y.DOM.getChildren(this.playerArea).length !== 0){
        if(this.playerArea.getElementsByTagName('img').length !== 0){
        
            // append image to the container            
            var oldNodes = this.playerArea.getElementsByTagName('img');
            var newNode = this.currentNode.getElementsByTagName('img')[0].cloneNode(false);

            $Y.DOM.setStyle(newNode,'opacity',0);

            this.playerArea.appendChild(newNode);
            
            var fadeIn = new YAHOO.util.Anim(newNode, { opacity: { from: 0, to: 1 }}, 5);
            var fadeOut = new YAHOO.util.Anim(oldNodes, { opacity: { from: 1, to: 0 }}, 2.5);
            
            var removeElement = function(){
                /* get the list of elements that has been animated */
                var el = this.getEl(),
                    parentnode = el[0].parentNode;

                /* removing every element from the dom, except the last */
                for(var i = 0, len = el.length-1; i < len; i++){
                    parentnode.removeChild(el[0]);
                }
            };
            
            fadeOut.onComplete.subscribe(removeElement); 

            fadeOut.animate();
            fadeIn.animate();
            
        } else {
            // add the image to the container
            var img = this.currentNode.getElementsByTagName('img')[0].cloneNode(false);
            this.playerArea.appendChild(img);     
        }
    };

    videoPlayer.prototype.setPlayerDescription = function(){
        // set video description
        if(this.videodesc.length !== 0){

            var description = this.videodesc[0],
                videoInfo = this.currentNode;
            var link = $Y.SELECT('.v1.showlisting', this.currentNode, true).href;
            description.innerHTML = videoInfo.innerHTML+'<p><span class="video-link">'+link+'</span></p>';
        }
    };

    videoPlayer.prototype.writePlayerDescription = function(title, desc){
        // set video description
        var description = this.videodesc[0];
        description.innerHTML = ''
            + '<h5 class="title">' + title + '</h5>' 
            + desc;
    };

    /* change video */
    videoPlayer.prototype.changeTo = function(node){
        TV2_Video.video.removeCurrentlyPlaying();
        
        $Y.DOM.removeClass(this.currentNode,'current');
        $Y.DOM.addClass(node,'current');
        
        this.currentNode = node;
        this.setPlayerThumbNail();
        this.setPlayerDescription();
            
        return this.currentNode;
    };

    videoPlayer.prototype.changeToNext = function(){ 
        return this.changeTo(
            $Y.DOM.getNextSibling(this.currentNode) 
            || $Y.DOM.getFirstChild(this.playList)
        );
    };

    videoPlayer.prototype.changeToPrevious = function(){ 
        return this.changeTo(
            $Y.DOM.getPreviousSibling(this.currentNode) 
            || $Y.DOM.getLastChild(this.playList)
        );
    };


    /* Cycle playlist */
    videoPlayer.prototype.startPlaylistCycling = function(){
        var timer;
        (function(obj){
            timer = window.setInterval(
                function(){ obj.changeToNext(); },
                obj.timeoutInterval || 15000
            );
        })(this);
        return this.timerId = timer;
    };
    videoPlayer.prototype.stopPlaylistCycling = function(){
        if(this.timerId){ 
            window.clearTimeout(this.timerId);
            this.timerId = undefined;
        };
    };


    /* ======================================================================
     * = Playlists                                                          =
     * ======================================================================*/
    videoPlayer.prototype.initializePlaylists = function(){
        this.playLists = $Y.SELECT('.video-playlist', this.container);

        if(this.playLists.length > 0){ 
            /* */
            this.playList = this.playLists[0];        

            if(this.playLists.length > 1){
                /* we've got more than one playlist, applying logic that change
                 * between them */
                var playlistHandlers = new Array();

                for(var i = 0, len = this.playLists.length; i < len; i++){
                    playlistHandlers.push($Y.DOM.getPreviousSiblingBy(this.playLists[i],function(){
                        return $Y.DOM.hasClass(this,'title');
                    }));
                }

                YAHOO.util.Event.on(
                    playlistHandlers, 
                    'click', function(e){ 
                        this.changePlaylistTo($Y.EVENT.getTarget(e)); 
                    }, 
                    this, true
                );
                
                $Y.EVENT.on(
                    $Y.DOM.getElementsByClassName('showlisting','a',this.container),
                    'focus', 
                    function(e){ 
                        var node = $Y.DOM.getAncestorByClassName(
                            $Y.EVENT.getTarget(e),
                            'video-playlist'
                        );     
                        this.changePlaylistTo(node);
                    },
                    this, true
                );     
                
            }
        } 
        else {
            /* no playlists found, returning */
            return;
        }        
    };

    videoPlayer.prototype.changePlaylistTo = function(node){

        var oldPlayList = $Y.SELECT(
            'ul.video-playlists > li.current ol', 
            $Y.DOM.getAncestorByTagName(node,'div'),
            true
        );
        
        if($Y.DOM.hasClass(node,'video-playlist')){
            var newPlayList = node;
        }
        else {

            var newPlayList = $Y.DOM.getNextSiblingBy(
                node,
                function(that){
                    return YAHOO.util.Dom.hasClass(that,'video-playlist');
                }(this)
            );
        }

        /* don't do anything if the new playlist is the same */
        if(oldPlayList === newPlayList) return;


        /* animating the transactions on playlist switches */
        var myHeight = parseInt($Y.DOM.getStyle(oldPlayList,'height'), 10),
            open = new YAHOO.util.Anim(newPlayList, { 'height': { from: 0, to: myHeight }}, 0.1),
            close = new YAHOO.util.Anim(oldPlayList, { 'height': { from: myHeight, to: 0 }}, 0.1);


        /* preparing the styles for the animation, removing scroolbars, etc. */
        $Y.DOM.setStyle([oldPlayList,newPlayList],'overflow','hidden');
        $Y.DOM.setStyle(newPlayList,'position','relative');

        
        open.onComplete.subscribe(function(){ 
            $Y.DOM.addClass(
                $Y.DOM.getAncestorByTagName(this.getEl(),'li'), 
                'current'
            );

            /* adding the scrollbar, if there is more videos than space */
            $Y.DOM.setStyle(this.getEl(),'overflow','auto');
        });

        
        close.onComplete.subscribe(function(){ 
            $Y.DOM.removeClass(
                $Y.DOM.getAncestorByTagName(this.getEl(),'li'),
                'current'
            );
        }); 

        open.animate();
        close.animate();

        this.playList = newPlayList;
        
    };

    /* spawn player */
    videoPlayer.prototype.spawnPlayer = function(){
        var swf = new deconcept.SWFObject(
                TV2_COMMON_URL + '/flash/videoplayer.swf',
                "videoclip", 
                YAHOO.util.Dom.getStyle(this.playerArea,'width'),
                YAHOO.util.Dom.getStyle(this.playerArea,'height'),
                '9.0.115', 
                '#000000'
            ),
            title = function(){
                var headline = $Y.SELECT('.title', this.currentNode, true);
                return headline.innerHTML || "Ingen titel";
            },

            date = function(){

                var now = new Date(),
                    H = now.getHours().toString(),
                    i = now.getMinutes().toString(),
                    d = (now.getDay()+1).toString(),
                    m = (now.getMonth()+1).toString(),
                    Y = now.getFullYear().toString();

                if(H.length == 1) H = "0"+H;
                if(i.length == 1) i = "0"+i;
                if(d.length == 1) d = "0"+d;
                if(m.length == 1) m = "0"+m;

                return H + i + d + m + Y;
            },

        xmlfile = TV2_COMMON_URL+'/flashplayer/playlistSimple.xml.php/clip-' + this.videoId  + '.xml';
            
        var img = this.currentNode.getElementsByTagName('img')[0].cloneNode(false);
        if(this.splash)
        	img = this.splash;
        
        swf.addVariable('playlist', xmlfile);
        swf.useExpressInstall(TV2_COMMON_URL+"/flash/expressinstall.swf");
        swf.setUseStreamMetrix(true);
        swf.addVariable("player_id", "front-video-small");
        swf.addVariable("related", "/relatedvideos.php/id-"+this.videoId+".xml");
        swf.addVariable("domain", "video.tv2.dk");
        swf.addVariable("geocheck", "1");
        swf.addVariable("autoplay", this.autoplay ? "1" : "0");
        if(img)
        	swf.addVariable("splash", img.src);
        swf.addVariable("adtech_alias", "player_go");
        swf.addParam("allowScriptAccess", "always");
        swf.addParam("allowFullScreen", this.showControlles);
        swf.doWrite(this.playerArea, title(), ["FRONTPAGE","SMALL"], date());

    };


    /* Debug */
    videoPlayer.prototype.debug = function(){
        // return this.currentId;
    };

var videoplayer = null;

YAHOO.util.Event.onDOMReady(function(){

    videoplayer = new videoPlayer(document.getElementById('content-video'));

});
