/*jslint laxbreak: true */
/*global $clear Browser Class Events Fx Options Update document */
var booSelected				= false;
var arrClipsData	= [];
var arrAllClipListTags		= [];
var bLoadFirstTime			= true;
var currentPlayingClip= {};

// Create the class object
var objUpdatePlaylist1 = {};

// Playerlist1 class
var UpdatePlaylist1 = new Class({
    Implements: [Options, Events],

    options:
	{
	    objRootElement: {},
	    booSelected: false,
	    arrClipsData: [],
	    arrAllClipListTags: [],

	    bLoadFirstTime: true,

	    // Vars setup
	    myTransition: new Fx.Transition(Fx.Transitions.Sine, 3),
	    fx: {},

	    intCurrJsonPosition: 0,
	    intCurrClipPlaying: 0,

	    previouslyPlayedClip: null,
	    currentPlayingClip: {},

	    videoClips: {}
	},

    initialize: function(options) {

        this.setOptions(options);

        // Bind this to the functions called from outside
        this.bound = {
            resetStart: this.resetStart.bind(this)
			, markCurrentPlayingClip: this.markCurrentPlayingClip.bind(this)
			, clearMarkedClipsPlaylist1: this.clearMarkedClipsPlaylist1.bind(this)
			, playerCompleted: this.playerCompleted.bind(this)
        };

        // Vars setup
        //this.options.fx = new Fx.Morph('slider-list', { duration: 200, transition: this.options.myTransition.easeInOut, wait: true });
    },

    resetStart: function() {
        // Reset the currently playing clip (if the contents of Cliplist1 has changed via AJAX)
        this.options.intCurrJsonPosition = 0;

        // Get jason string
        this.options.arrClipsData = JSON.decode(this.options.objRootElement.getElement('div.updatePlaylist1JSON').get('html'), true);

        // If the cliplist is empty for some reason, stop everything to prevent javascript errors
        if (this.options.arrClipsData.length === 0) {
            return;
        }

        Update.RegisterClipClearedEvent(this.options.objRootElement, this.bound.clearMarkedClipsPlaylist1);
        Update.RegisterClipCompletedEvent(this.options.objRootElement, this.bound.playerCompleted);

        //***> Get all vid clips
        //** Breaking News or Direct  Video clip events
        this.options.videoClips = this.options.objRootElement.getElements('ul.updatePlaylist1ClipListDifferent li.thumbContainer');

        this.setupEvents(this.options.videoClips, this.options.arrClipsData, this.options.intCurrJsonPosition, false);
        this.options.intCurrJsonPosition += this.options.videoClips.length;
        // Add to the collected list
        this.options.arrAllClipListTags = this.options.videoClips;

        //** Top stories Video clip events
        this.options.videoClips = this.options.objRootElement.getElements('ul.updatePlaylist1ClipListTopStories li.thumbContainer');
        this.setupEvents(this.options.videoClips, this.options.arrClipsData, this.options.intCurrJsonPosition, true);
        this.options.intCurrJsonPosition += this.options.videoClips.length;
        // Add to the collected list	
        this.options.arrAllClipListTags = this.options.arrAllClipListTags.concat(this.options.videoClips);

        //** Video clip events
        this.options.videoClips = this.options.objRootElement.getElements('ul.updatePlaylist1ClipListRegular li.thumbContainer');
        this.setupEvents(this.options.videoClips, this.options.arrClipsData, this.options.intCurrJsonPosition, true);
        // Add to the collected list	
        this.options.arrAllClipListTags = this.options.arrAllClipListTags.concat(this.options.videoClips);

        this.startFirstClip();

        this.setupTextIconViewButtons();
    }, // End resetStart


    //************************************************
    // Text / icon view function
    //************************************************
    setupTextIconViewButtons: function() {
        // Icon view button
        this.options.objRootElement.getElement('div#icCL1Iconview').addEvent('click', function(event) {
            if (event.target.getStyle('background-image').indexOf("off") > -1) {
                event.target.setStyle('background-image', 'url(/Design/www/update/img/playlist1/iconview_on.gif)'); // else set it to on
                this.options.objRootElement.getElement('div#icCL1Textview').setStyle('background-image', 'url(/Design/www/update/img/playlist1/textview_off.gif)'); // and set textview off

                // Check if there is a clip there is selected
                this.bound.clearMarkedClipsPlaylist1(true);

                // Change the id
                this.options.objRootElement.getElement("div#Cliplist1Inner_textView").setProperty('id', 'Cliplist1Inner_iconView');

                // Change the style on marked clip
                this.bound.markCurrentPlayingClip(true);
            }
        } .bind(this));

        // Text View button
        this.options.objRootElement.getElement('div#icCL1Textview').addEvent('click', function(event) {
            if (event.target.getStyle('background-image').indexOf("off") > -1) {
                event.target.setStyle('background-image', 'url(/Design/www/update/img/playlist1/textview_on.gif)');
                this.options.objRootElement.getElement('div#icCL1Iconview').setStyle('background-image', 'url(/Design/www/update/img/playlist1/iconview_off.gif)');

                this.bound.clearMarkedClipsPlaylist1(true);

                // Change the id
                this.options.objRootElement.getElement("div#Cliplist1Inner_iconView").setProperty('id', 'Cliplist1Inner_textView');

                // Change the style on marked clip
                this.bound.markCurrentPlayingClip(true);
            }

            //videoClips.removeEvents();
        } .bind(this));

        /*
        if (!Browser.Engine.trident) {
        // SET THE ICONVIEW BUTTON AS ON FROM THE START
        document.getElement('#icCL1Iconview').setStyle('background-image', 'url(/Design/www/update/img/playlist1/iconview_on.gif)');
        }
        */

    }, // End setupTextIconViewButtons

    isAutoPlayValid: function() {
        if (this.options.intCurrClipPlaying === this.options.arrAllClipListTags.length - 1 || !this.options.booSelected) {
            return false;
        } else {
            return true;
        }
    },

    //************************************************
    // Starts the first clip in the list
    //************************************************
    startFirstClip: function() {
        var jsonDeeplinkClip = document.getElement('#updatePlayerDeeplinkClipJson');
        if (jsonDeeplinkClip !== null && jsonDeeplinkClip.get("html") != "") {
            Update.LoadClip(JSON.decode(jsonDeeplinkClip.get("html")), null, false);
            this.options.bLoadFirstTime = false;
            return;
        }

        // Check if there is a deeplink playing allready and that it is the first load of playlist 1
        if (!this.options.bLoadFirstTime) {
            return;
        }

        this.options.bLoadFirstTime = false;

        // Add the html element to the current html clip playing
        this.options.currentPlayingClip = this.options.arrAllClipListTags[0];
        Update.LoadClip(this.options.arrClipsData[0], this.bound.markCurrentPlayingClip, false);

        // Settings for the default autoplay option. Set to false to switch autoplay checkbox off by default.
        document.getElement('.updatePlaylist1AutoplayBox').checked = true;

    }, // End startFirstClip

    //************************************************
    // Function that checks what to do if the player is stoped
    //************************************************
    playerCompleted: function() {
        // Check if this is the current playlist that is playing	
        if (!this.options.booSelected || !document.getElement('#updatePlaylist1AutoplayBoxId').checked) {
            return;
        }

        // Play next clip
        this.options.intCurrClipPlaying++;
        // Add the file to the current file
        this.options.currentPlayingClip = this.options.arrAllClipListTags[this.options.intCurrClipPlaying];
        //alert("play next clip " + this.options.intCurrClipPlaying)
        // Play the next file in list
        Update.LoadClip(this.options.arrClipsData[this.options.intCurrClipPlaying], this.bound.markCurrentPlayingClip, false);

    }, // End playerCompleted

    //************************************************
    // Clear Marked Clips function
    //************************************************
    clearMarkedClipsPlaylist1: function(booViewChange) {
        // When playing a clip for the first time, there will not be any previously marked clip 
        if (typeof (this.options.previouslyPlayedClip) === 'undefined' || this.options.previouslyPlayedClip === null) {
            return;
        }

        if (document.getElement('#Cliplist1Inner_textView')) {
            this.options.previouslyPlayedClip.setStyle('border', 'none');
        }
        else {
            var previousThumb = this.options.previouslyPlayedClip.getElement(".thumb");
            if (previousThumb) {
                previousThumb.setStyle('border', 'none');
                previousThumb.setStyle('margin-left', parseInt(previousThumb.getStyle('margin-left'), 10) + 1);
                previousThumb.setStyle('margin-top', parseInt(previousThumb.getStyle('margin-top'), 10) + 1);
            }
        }
        this.options.previouslyPlayedClip = null;

        // Check if it is a view change
        if (typeof (booViewChange) === 'undefined') {
            this.options.booSelected = false;
        }
    }, //clearMarkedClipsPlaylist1

    //************************************************
    // Mark Clips function
    //************************************************
    markCurrentPlayingClip: function(booViewChange) {
        // Check if it is a view change
        if (typeof (booViewChange) === 'undefined') {
            this.options.booSelected = true;
        }

        if (!this.options.booSelected) {
            return;
        }

        if (document.getElement('#Cliplist1Inner_textView')) {
            this.options.currentPlayingClip.setStyle('border-top', '1px solid #00b0ea');
            this.options.currentPlayingClip.setStyle('border-bottom', '1px solid #00b0ea');
        }
        else {
            var currentThumb = this.options.currentPlayingClip.getElement(".thumb");
            if (currentThumb !== null) {
                currentThumb.setStyle('border', '1px solid #00b0ea');
                currentThumb.setStyle('margin-left', parseInt(currentThumb.getStyle('margin-left'), 10) - 1);
                currentThumb.setStyle('margin-top', parseInt(currentThumb.getStyle('margin-top'), 10) - 1);
            }
        }

        this.options.previouslyPlayedClip = this.options.currentPlayingClip;
    }, // markCurrentPlayingClip

    //************************************************
    // Setup Events function
    //************************************************
    setupEvents: function(arrVideoClips, arrVideoJsonString, intCurrArrayPosition, booUseDimmerInfo) {
        if (arrVideoClips.length === 0) {
            return;
        }

        var color = arrVideoClips[0].getStyle('backgroundColor');

        // Run through the objects and give them events and effects
        arrVideoClips.each(function(videoClip, i) {
            videoClip.thumbMorph = new Fx.Morph(videoClip, { duration: 200 });

            videoClip.addEvents({
                'mouseover': function(e) {
                    if (!Browser.Engine.trident) {
                        videoClip.thumbMorph.cancel();
                        videoClip.thumbMorph.start({ 'background-color': '#00b0ea' });
                    }
                    else {
                        videoClip.setStyle('background-color', '#00b0ea');
                    }
                } .bind(this),
                'mouseleave': function() {
                    if (!Browser.Engine.trident) {
                        videoClip.thumbMorph.cancel();
                        videoClip.thumbMorph.start({ backgroundColor: color });
                    }
                    else {
                        videoClip.setStyle('background-color', color);
                    }
                } .bind(this),
                'click': function(e) {
                    this.options.currentPlayingClip = videoClip;
                    this.options.intCurrClipPlaying = (intCurrArrayPosition + i);
                    Update.LoadClip(arrVideoJsonString[intCurrArrayPosition + i], this.bound.markCurrentPlayingClip, false);
                } .bind(this)
            });

        } .bind(this));

        // Check if it should use the dimmer with the text over the image
        if (booUseDimmerInfo) {
            //** Mouse overs for tumbs **
            arrVideoClips.each(function(videoClip, i) {
                videoClip.addEvents({
                    'mouseover': function() {
                        this.getElement(".updatePlaylist2Dimmer").setStyle('display', 'block');

                        // hide the headline text if cliplist 1 is set to iconview
                        if (!Browser.Engine.trident) {
                            if (document.getElement('#icCL1Iconview').getStyle('background-image').indexOf('off') == -1) { this.getElement(".updatePlayerClipSubText").setStyle('display', 'none'); }
                        }
                        else {
                            this.getElement(".updatePlayerClipSubText").setStyle('display', 'none');
                        }

                        this.getElement("div.thumb").setStyle('height', '91px');
                    },
                    'mouseleave': function() {
                        this.getElement(".updatePlaylist2Dimmer").setStyle('display', 'none');
                        this.getElement(".updatePlayerClipSubText").setStyle('display', 'block');
                        this.getElement("div.thumb").setStyle('height', '66px');
                    }
                });
            });
        }
    } // End setupEvents
});

function initPlaylist1() {
	var oRootElement = document.getElement("div.clipList1Container");
	objUpdatePlaylist1 = new UpdatePlaylist1({objRootElement:oRootElement});
	Update.LoadCliplistContents(oRootElement.getElement('.DR_AJAX_Extensions_AJAXPanel'), objUpdatePlaylist1.bound.resetStart, document.getElement('.cliplist1TabLink').getProperty('href'));
}
