/*jslint evil: true, laxbreak: true */
/*global $ $$ $clear Browser Class Events Fx Options Update document*/

// Playerlist2 class
var UpdatePlaylist2 = new Class({
    Implements: [Options, Events],

    options:
	{
	    totalIncrement: 0,
	    boxSize: 128,
	    slideNo: 5,
	    increment: 0,

	    videoClips: [],

	    noItems: 0,

	    maxRightIncrementBeforeOddNo: 0,
	    maxRightIncrement: 0,
	    inUneavenEnd: false,

	    myTransition: new Fx.Transition(Fx.Transitions.Sine, 3),
	    fx: {},

	    currentPlayingClip: {},
	    previouslyPlayedClip: null,

	    arrClipsData: {},

	    color: '',

	    activeTab: 0
	},

    initialize: function(options) {
        this.setOptions(options);

        this.options.increment = this.options.boxSize * this.options.slideNo;

        // Bind this to the functions called from outside
        this.bound = {
            resetStart: this.resetStart.bind(this)
			,clearMarkedClips: this.clearMarkedClips.bind(this)
			,markCurrentPlayingClip: this.markCurrentPlayingClip.bind(this)
        };

    },

    resetStart: function() {
        this.options.totalIncrement = 0;
		this.options.videoClips = $$('#slider-stage li.thumbContainer');

        // If the cliplist is empty for some reason, stop everything to prevent javascript errors
        if (this.options.videoClips.length === 0) {
            return;
        }

		this.options.increment = this.options.boxSize * this.options.slideNo;
		
        // Set the fx, duration up on the html element
        this.options.fx = new Fx.Morph('slider-list', { duration: 1500, transition: this.options.myTransition.easeInOut, wait: true });

        //list elements
        this.options.noItems = this.options.videoClips.length;
        if (this.options.noItems === 0) {
            this.options.maxRightIncrementBeforeOddNo = 0;
            this.options.maxRightIncrement = 0;
        } else {
            this.options.maxRightIncrementBeforeOddNo = -this.options.increment * (Math.floor(this.options.noItems / this.options.slideNo) - 1);
            this.options.maxRightIncrement = this.options.maxRightIncrementBeforeOddNo - (this.options.noItems % this.options.slideNo * this.options.boxSize);
        }
        this.options.arrClipsData = JSON.decode(document.getElement('.updatePlaylist2JSON').get('html'), true);

        Update.RegisterClipClearedEvent(document.getElement('.updatePlaylist2Holder'), this.bound.clearMarkedClips);

        // Make buttons visible
        /*
        document.getElement(".updatePlaylist2Next").setStyle('display', 'block');
        document.getElement(".updatePlaylist2Previous").setStyle('display', 'block');
        */


        //-------------------------------------
        // EVENTS for the button "previous"
        $('previous').addEvents({
            'click': function(event) {
                if (this.options.totalIncrement < 0) {
                    this.options.totalIncrement = this.options.totalIncrement + this.options.increment;
                    // Check if we are at an uneven end
                    if (this.options.inUneavenEnd) {
                        this.options.inUneavenEnd = false;
                        this.options.totalIncrement = this.options.maxRightIncrementBeforeOddNo;
                    }
                    this.options.fx.cancel();
                    this.options.fx.start({ 'margin-left': this.options.totalIncrement });

                }
                this.checkButtonState();
            } .bind(this)
        });

        //-------------------------------------
        // EVENTS for the button "next"
        $('next').addEvents({
            'click': function(event) {
                if (this.options.totalIncrement > this.options.maxRightIncrementBeforeOddNo) {
                    this.options.totalIncrement = this.options.totalIncrement - this.options.increment;
                    this.options.fx.cancel();
                    this.options.fx.start({ 'margin-left': this.options.totalIncrement });
                }
                else if (this.options.totalIncrement > this.options.maxRightIncrement) {
                    this.options.inUneavenEnd = true;
                    this.options.totalIncrement = this.options.maxRightIncrement;
                    //console.log(this.options);
                    this.options.fx.cancel();
                    this.options.fx.start({ 'margin-left': this.options.totalIncrement });
                }
                this.checkButtonState();
            } .bind(this)
        });

        // Check if there is enough items to scroll or if the arrows should be grayed out
        this.checkButtonState();

        //************************************************
        // Mouse over event
        //************************************************
        this.options.color = this.options.videoClips[0].getStyle('backgroundColor');

        this.options.videoClips.each(function(videoClip, i) {
            videoClip.thumbMorph = new Fx.Morph(videoClip, { duration: 200 });

            videoClip.addEvents({
                'mouseover': function(e) {
                    if (Browser.Engine.gecko) {
                        videoClip.thumbMorph.cancel();
                        videoClip.thumbMorph.start({ 'background-color': '#fff' });
                    }
                    else {
                        videoClip.setStyle('background-color', '#fff');
                    }
                } .bind(this),
                'mouseleave': function(e) {
                    if (Browser.Engine.gecko) {
                        videoClip.thumbMorph.cancel();
                        videoClip.thumbMorph.start({ backgroundColor: this.options.color });
                    }
                    else {
                        videoClip.setStyle('background-color', this.options.color);
                    }

                } .bind(this),
                'click': function(e) {
                    this.options.currentPlayingClip = videoClip;
                    Update.LoadClip(this.options.arrClipsData[(i)], this.bound.markCurrentPlayingClip, false);
                } .bind(this)
            });

        } .bind(this));

        //************************************************
        // Mouse over event for tumbs
        //************************************************
        this.options.videoClips.each(function(videoClip, i) {
            videoClip.addEvents({
                'mouseover': function() {
                this.getElement(".updatePlaylist2Dimmer").setStyle('display', 'block');
                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');
                }
            });
        });

        //** Tab controll **

        //tab elements
        var tabHolder = document.getElement('div.updatePlaylist2Topbar');
        var tabElements = tabHolder.getElements('div.updatePlaylist2Tab a');

        // Set first to be active		
        tabElements[this.options.activeTab].getParent().set('class', 'updatePlaylist2TabActive updatePlaylist2Tab updatePlaylist2Tab' + this.options.activeTab);

        //Loop through elements
        tabElements.each(function(tabElement, i) {
            tabElement.addEvents({
                'click': function(e) {
                    this.resetTabs(tabElements);
                    e.target.getParent().set('class', 'updatePlaylist2TabActive updatePlaylist2Tab updatePlaylist2Tab' + (i));
                    // Set ajax loader
                    if (document.getElement('.updatePlaylist2Holder .DR_AJAX_Extensions_AJAXPanel .ajaxLoading').getStyle('display') == "none") { // only do the following if we're not already loading something
                        document.getElement('.updatePlaylist2Holder .DR_AJAX_Extensions_AJAXPanel .ajaxLoading').setStyle('display', 'block');
                        document.getElement('.updatePlaylist2Holder .DR_AJAX_Extensions_AJAXPanel #slider-list').dispose();
                    }
                    this.startLoadLoop(e.target);
                    this.options.activeTab = i;
                } .bind(this)
            });
        } .bind(this));


        //End resetStart 

    },



    // Set button states
    checkButtonState: function() {
        //alert(this.options.noItems);
        // Set next button state
        if (this.options.totalIncrement > this.options.maxRightIncrement) {
            document.getElement(".updatePlaylist2Next").set('src', '/Design/www/update/img/playlist2/update_playlist2_right_arrow.gif');
        } else {
            document.getElement(".updatePlaylist2Next").set('src', '/Design/www/update/img/playlist2/update_playlist2_right_arrow_stop.gif');
        }

        // Set previous button state
        if (this.options.totalIncrement < 0) {
            document.getElement(".updatePlaylist2Previous").set('src', '/Design/www/update/img/playlist2/update_playlist2_left_arrow.gif');
        } else {
            document.getElement(".updatePlaylist2Previous").set('src', '/Design/www/update/img/playlist2/update_playlist2_left_arrow_stop.gif');
        }
        //$('fb_login').setProperty('src', '/images/login.png');
    }, //End checkButtonState


    resetTabs: function(tabElements) {
        // Loop through
        tabElements.each(function(tabElement, i) {
            // reset tab
            tabElement.getParent().set('class', 'updatePlaylist2Tab updatePlaylist2Tab' + (i));
        });
    }, //End resetTabs


    startLoadLoop: function(targetTab) {
        if (document.getElement('.updatePlaylist2Holder .DR_AJAX_Extensions_AJAXPanel .ajaxLoading').getStyle('display') == "none") {
            this.setupPrevNextButtons();
            return false;
        }
        // if the "Loading data" div is shown we need to load some data, så we read the href from the first tab and fire the event
        else {
            var ajaxLoop;
            var loopCount = { counter: 0 };
            var count = 1;
            var delay = 3000;

            var getPlaylist2Data = function() {
                if (document.getElement('.updatePlaylist2Holder .DR_AJAX_Extensions_AJAXPanel .ajaxLoading').getStyle('display') == "none") { // if the loading screen had display none, the data must be loaded
                    //console.log('data seems to be loaded in playlist 2. Breaking from loop', delay);
                    ajaxLoop = $clear(ajaxLoop);
                }
                else {
                    var ClipList2DefaultContent = targetTab.getProperty('href');
                    eval(ClipList2DefaultContent); // here's our first try at loading the data. If this should go wrong, we'll try again in the loop below
                    //console.log(delay);
                }

                if (count >= 6) { // If we give up on the loading, there's probably an error. So we display the error text
                    ajaxLoop = $clear(ajaxLoop);
                    document.getElement('.updatePlaylist2Holder .DR_AJAX_Extensions_AJAXPanel .ajaxLoading .ajaxLoadingImageBlue').set('class', 'ajaxLoadingImageBlueError');
                    document.getElement('.updatePlaylist2Holder .DR_AJAX_Extensions_AJAXPanel .ajaxLoading .ajaxLoadingTextBlue').set('html', 'fejl ved indlæsning');
                }

                count = count + 1;
                delay = delay * 2;

            };

            getPlaylist2Data(); // Initial request for data.. Might be enough

            ajaxLoop = getPlaylist2Data.periodical(delay); // if not we'll run this periodical that tries to get the data 5 times or gives up
        }
    }, // End startLoadLoop

    clearMarkedClips: function() {
        if (typeof this.options.previouslyPlayedClip === 'undefined' || this.options.previouslyPlayedClip === null) {
			return;
		}
		
		var previouslyPlayedThumb = this.options.previouslyPlayedClip.getElement(".thumb");
		if (previouslyPlayedThumb !== null) {
			previouslyPlayedThumb.setStyle('border', 'none');
            previouslyPlayedThumb.setStyle('margin-left', '4px');
            previouslyPlayedThumb.setStyle('margin-top', '4px');

            this.options.previouslyPlayedClip = null;
        }
    }, //End clearMarkedClips


    markCurrentPlayingClip: function() {
		var currentPlayingThumb = this.options.currentPlayingClip.getElement(".thumb");
        if (currentPlayingThumb !== null) {
            currentPlayingThumb.setStyle('border', '1px solid #fff');
            currentPlayingThumb.setStyle('margin-left', '3px');
            currentPlayingThumb.setStyle('margin-top', '3px');
        }
        
		this.options.previouslyPlayedClip = this.options.currentPlayingClip;
    } //End markCurrentPlayingClip
});


var objUpdatePlaylist2;

function initPlaylist2() { 
	var ajaxPanel = document.getElement('.updatePlaylist2Holder .DR_AJAX_Extensions_AJAXPanel');

	objUpdatePlaylist2 = new UpdatePlaylist2({});
	Update.LoadCliplistContents(ajaxPanel, objUpdatePlaylist2.bound.resetStart, document.getElement('.cliplist2TabLink').getProperty('href'));
}
