/* makes it possible to style the abbr element in ie6 */
document.createElement('abbr');

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

/* ======================================================================
 * = Videoplayer                                                        =
 * ======================================================================*/
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", "programmer");
        swf.addVariable("adtech_alias", "programmer");
        swf.addVariable("geocheck", "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;
    };

 /* ======================================================================
  * = Image galleries                                                    =
  * ======================================================================*/
var imageGalleryLauncher = function(node){
    this.node = node;
    this.addClickHandlers();
};

imageGalleryLauncher.prototype.openGallery = function(e){
    YAHOO.util.Event.preventDefault(e);

    var target = YAHOO.util.Event.getTarget(e),
        galleryLink = target.tagName.toUpperCase() !== 'A'
            ? $Y.DOM.getAncestorByTagName(target,'a')
            : target;

    window.open(''+galleryLink.href,'gallery','width=855,height=720,location=no, menubar=no, resizable=no, titlebar=yes, toolbar=no, status=no, directories=no, channelmode=no, scrollbars=no');

    return false;
};

imageGalleryLauncher.prototype.addClickHandlers = function(){

    $Y.EVENT.addListener(
        $Y.SELECT('.title a', this.node),
        'click', 
        this.openGallery
    );
      
};


/* ======================================================================
 * = Carousel Teaser                                                    =
 * ======================================================================*/
var carouselTeaser = function(node){
    this.node = document.getElementById(node);

    this.queueNode = $Y.SELECT('.item-queue ul', this.node, true);
    this.displayNode = $Y.SELECT('.item-display', this.node, true);

    this.queueNode = $Y.SELECT('.item-queue ul', this.node, true);

    this.cache = new Array();

    this.initQueueList();

    this.displayTemplate = this.displayNode.getElementsByTagName('div')[0].cloneNode(true);

    if(!$Y.DOM.hasClass(this.queueNode,'locked')){ this.startQueueCycling(); }
    
    // Add click handlers
    $Y.EVENT.addListener(
        $Y.SELECT('li p', this.queueNode), 'click', 
        function(e){
            var link = $Y.DOM.getPreviousSiblingBy(
                $Y.EVENT.getTarget(e),
                function(el){ return el.tagName.toUpperCase() === 'A'; }
            );
            window.location = link.href;
        },
        this, true
    );

    $Y.EVENT.addListener(
        this.displayNode, 'click', 
        function(e){
            var link = $Y.SELECT('li.current a', this.queueNode, true);
            window.location = link.href;
        },
        this, true
    );

};
    carouselTeaser.prototype.initQueueList = function(){
        this.queue = $Y.SELECT('li', this.queueNode);

        this.currentNode = this.queue[0];
    };

    carouselTeaser.prototype.createItem = function(node){

        var item = this.displayTemplate.cloneNode(true),
            img = $Y.DOM.getStyle($Y.SELECT('p', node, true),'background-image'),
            title = $Y.SELECT('a span', node, true).innerHTML,
            desc = $Y.SELECT('p', node, true).innerHTML;

        $Y.DOM.setStyle(item,'background-image',img);
        $Y.SELECT('.item-title', item, true).innerHTML = title;
        $Y.SELECT('.item-description', item, true).innerHTML = desc;

        return item;
        
    };

    carouselTeaser.prototype.fetchItem = function(node){
        for(var i = (this.cache.length-1); this.cache[i] !== undefined; i--){
            if(this.cache[i].node === node) break;
        }
        if(i == -1){ 
            this.cache.push({
                'node':node,
                'html':this.createItem(node)
            }); 
            i = this.cache.length-1;
        }
        
        return this.cache[i].html;
    };

    /* change to another item in the queue */
    carouselTeaser.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');

            ////////////////////////////////////////////////////////////////////
            // Animation code start ////////////////////////////////////////////
            var oldItems = $Y.DOM.getChildren(this.displayNode);
            var newItem = this.fetchItem(node);

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

            this.displayNode.appendChild(newItem);

            var fadeIn = new YAHOO.util.Anim(newItem, { opacity: { from: 0, to: 1 }}, 3);
            var fadeOut = new YAHOO.util.Anim(oldItems, { opacity: { from: 1, to: 0 }}, 2.5);

            // fixes an issue in ie browsers, where the info box will not disappear 
            $Y.DOM.setStyle($Y.SELECT('.item-info', newItem, true),'display','block');
            $Y.DOM.setStyle($Y.SELECT('.item-info', oldItems[0], true),'display','none');

            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();
            // Animation code end //////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////////

            this.currentNode = newNode;
        }

        return this.currentNode;
    };

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

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

    /* Cycle queue */
    carouselTeaser.prototype.startQueueCycling = function(){
        var timer;
        (function(obj){
            timer = window.setInterval(
                function(){ obj.changeToNext(); },
                obj.timeoutInterval || 15000
            );
        })(this);
        return this.timerId = timer;
    };
    carouselTeaser.prototype.stopQueueCycling = function(){
        if(this.timerId){ 
            window.clearTimeout(this.timerId);
            this.timerId = undefined;
        };
    };
/* ======================================================================
 * Setting a class on the body                                          =
 * ====================================================================*/

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

TV2.SITE.PROGRAMMER.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 < '22'){ theme += 'prime'; }
        else { theme += 'late-prime'; }

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

/* ======================================================================
 * = Initializers                                                       =
 * ======================================================================*/
YAHOO.util.Event.onDOMReady(function(){

    if($Y.DOM.inDocument('content-program-teasers')){
        var topteaser = new carouselTeaser('content-program-teasers');
    }

    if($Y.DOM.inDocument('content-images')){ 
        var imageGallery = new imageGalleryLauncher('content-images');
    }


    if($Y.DOM.inDocument('sputnik-content-video')){ 
        var sputnik = new videoPlayer(
            document.getElementById('sputnik-content-video')
        );
        sputnik.disablePlayerControlles();
        sputnik.startPlaylistCycling();
    }
    
    TV2.SITE.PROGRAMMER.theme.init();

});
