/* Making it possible to style <abbr> in IE6. */
document.createElement('abbr');

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);

    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();

    /* 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);

        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;
            description.innerHTML = videoInfo.innerHTML;
        }
    };

    /* change video */
    videoPlayer.prototype.changeTo = function(node){
        var newNode = node;

        if(this.currentNode !== newNode){
            /* skip all of this if we really don't change node */
            $Y.DOM.removeClass(this.currentNode,'current');
            $Y.DOM.addClass(newNode,'current');

            this.currentNode = newNode;
            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(
                'http://common.tv2.dk/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 = $Y.SELECT('a', this.currentNode, true).href;
            xmlfile = 'http://common.tv2.dk/flashplayer/playlistSimple.xml.php/clip-' + this.videoId[1] + '.xml';

            swf.addVariable('playlist', xmlfile);
            swf.addVariable('stats', "true");
            swf.addVariable("player_id", "go");
            swf.addVariable("adtech_alias", "go");
            swf.addVariable("autoplay", "1");
            swf.addVariable("controls", this.showControlles ? "1" : "0");
            swf.useExpressInstall("http://common.tv2.dk/flash/expressinstall.swf");
            swf.setUseStreamMetrix(true);
            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;
    };





if(!TV2){ var TV2 = {}; }
if(TV2 && !TV2.SITE){ TV2.SITE = {}; }
if(TV2 && TV2.SITE && !TV2.GO){ TV2.SITE.GO = {}; }

TV2.SITE.GO.clock = (function(){
    // where we are going, we don't need roads

    var time, node, intervalId;

    return {
        start : function(n, t){
            // kill the interval, if the clock is already running
            if(intervalId) TV2.SITE.GO.clock.stop();

            // 't', time set in milliseconds; if set, use that
            if(t) TV2.SITE.GO.clock.setTime(t);

            // if a node (n) is set, use that
            if(n) TV2.SITE.GO.clock.setNode(n);

            // if a node, and
            intervalId = window.setInterval(
                TV2.SITE.GO.clock.update,
                1000
            );
        },
        stop : function(){
            window.clearInterval(intervalId);
            intervalId = undefined;
        },
        setNode : function(n){
            node = n;
        },
        setTime : function(t){
            time = new Date(t);
        },
        update : function(){
            // don't show time, if time is not set
            if(typeof time === 'undefined' && typeof node === 'undefined') return;

            // add a second to the time
            TV2.SITE.GO.clock.setTime( time.getTime() + 1000 );

            node.innerHTML =
                (time.getHours()  <  10 ? '0':'') + time.getHours() + ":" +
                (time.getMinutes() < 10 ? '0':'') + time.getMinutes() + ":" +
                (time.getSeconds() < 10 ? '0':'') + time.getSeconds();
        }
    };
})();

TV2.SITE.GO.theme = (function(){

    var getTheme = function(){
        var theme = 'theme-', time = new Date();

        time = (time.getHours()  <  10 ? '0':'') + time.getHours();

        /* find the current theme based on the hour of the day*/
        if(time >= '05' && time < '13'){ theme += 'morning'; }
        else if(time >= '13' && time < '16'){ theme += 'day'; }
        else if(time >= '16' && time < '18'){ theme += 'afternoon'; }
        else if(time >= '18' && time < '21'){ theme += 'evening'; }
        else { theme += 'late-night'; }

        return theme;
    };

    return {
        init : function(){
            /* if a theme is set from the server we should not set one on the
             * client side */
            if(/theme-/.test(document.body.className)) { return; }

            YAHOO.util.Dom.addClass(document.body, getTheme());
        }
    };
}());

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

    TV2.SITE.GO.theme.init();

    /* start a clock at the clients current time, using the dom element with
     * the id 'clock' */
    var clock = document.getElementById('clock');

    if(clock)
        TV2.SITE.GO.clock.start(
            document.getElementById('clock'),
            (new Date).getTime()
        );

    if(YAHOO.util.Dom.inDocument('content-video')){
        var videoplayer = new videoPlayer(document.getElementById('content-video'));
    }


});
