var SerieCarousel = new Class({
    Implements: [Events, Options],
	
	//options / variables 
    options: {
		viewport:null,
        carousel:null,
        previous:null,
        next:null,
        listItems:null,
        orientation:'horizontal',
        jumpNumItems:3
    },
	provider: null,
    actualSize: 0,
    viewportSize: null,
    scrollerOffset:0,
    moveX: 330, //three items not including large one
    FxMorph: null,
    currentItemIndex:0,
    maxItemReached: null,
    scrollable: true,
    
    //dimensions
    dimensions: {
        horizontal:{
            viewportSize:'x',
            itemSize: 'x',
            itemMarginStyle:'margin-right',
            carouselMarginStyle:'marginLeft'
        },
        vertical:{
            viewportSize:'y',
            itemSize: 'y',
            itemMarginStyle:'margin-bottom',
            carouselMarginStyle:'marginTop'
        }
    },
    dimensionRef: null,

    initialize: function(options, provider) {
        this.setOptions(options);
        this.provider = provider;
        
        //set dimension ref
        this.dimensionRef = this.dimensions[this.options.orientation];
        
        //alert(this.options.viewport.getSize().x);
        this.viewportSize = this.options.viewport.getSize()[this.dimensionRef.viewportSize];
        this.options.listItems.each(function(el, i) {
            this.actualSize += el.getSize()[this.dimensionRef.itemSize]  + 
                el.getStyle(this.dimensionRef.itemMarginStyle).toInt();
        },this);
        
        this.options.listItems.each(function(el, i) {
            if(el.parentNode.className == 'active') {
                if(i > 4) {
                    this.jumpToItemByIndex(i - 2);
                }
            }
        },this);
        
        //previous is default hidden
        
        
        // no use for scroller
        if (this.actualSize <= this.viewportSize){
            this.scrollable = false;
            return;
        }
        
        this.toggleButton('next','show');
        
        //previous / next
        this.setupEventListeners();
    },
	
	setupEventListeners: function(){
        this.options.previous.addEvent('click', function(e){
            this.onPreviousClicked(e);
        }.bind(this));
        this.options.next.addEvent('click', function(e){
            this.onNextClicked(e);
        }.bind(this));
    },
    
    onNextClicked: function(e){
        e.stop();
        this.jumpToItemByIndex(this.currentItemIndex + this.options.jumpNumItems);
    },
    
    onPreviousClicked: function(e){
        e.stop();
        this.jumpToItemByIndex(this.currentItemIndex - this.options.jumpNumItems);
    },
    
    jumpToItem: function(element){
        for (var i = 0; i < this.options.listItems.length; i++){
            if (element == this.options.listItems[i]){
                this.jumpToItemByIndex(i);
                break;
            }
        }
    },
    
    jumpToItemByIndex: function(index){
        
        //not scrollabe, do nothing
        if (!this.scrollable){
            return;
        }
        this.cancelMorph();
        this.FxMorph = new Fx.Morph(this.options.carousel);
        
        //calculate next item, check item boundaries
        this.currentItemIndex = index;
        if (this.currentItemIndex < 0){
            this.currentItemIndex = 0;
        }
        else if (this.maxItemReached !== null && this.currentItemIndex > this.maxItemReached){
            this.currentItemIndex = this.maxItemReached;
        }
        else if(this.currentItemIndex >= this.options.listItems.length){
            this.currentItemIndex = this.options.listItems.length - 1;
        }
        
        //calculate new offset
        var newOffset = 0;
        for (var i = 0; i < this.options.listItems.length; i++){
            if (i == this.currentItemIndex){
                break;
            }
            var el = this.options.listItems[i];
            newOffset += el.getSize()[this.dimensionRef.itemSize]  + 
                el.getStyle(this.dimensionRef.itemMarginStyle).toInt();
        }
        
        this.toggleButton('next','show');
        this.toggleButton('previous','show');
        
        //check offset boundaries and set togglers
        if (newOffset == 0){
            this.FxMorph.onComplete = function(){
                this.toggleButton('previous','hide');
            }.bind(this);
        }
        else if (this.viewportSize + newOffset > this.actualSize){
            this.maxItemReached = this.currentItemIndex;
            newOffset = this.actualSize - this.viewportSize;
            this.FxMorph.onComplete = function(){
                this.toggleButton('next','hide');
            }.bind(this);
        }
        
        //morph it
        var props = {};
        props[this.dimensionRef['carouselMarginStyle']] = -newOffset;
        this.FxMorph.start(props);
        
    },
    
    toggleButton: function(type,toggle){
        var buttons = {
            'previous':this.options.previous,
            'next':this.options.next
        }
        var toggleStyles = {
            'hide':'hidden',
            'show':'visible'
        }
        $(buttons[type]).setStyle('visibility',toggleStyles[toggle]);
    },
    
    cancelMorph: function(){
        if (this.FxMorph){
            this.FxMorph.cancel();
        }
    }
	
});


var ArttubePlayer = new Class({
    Implements: [Events, Options],
	
	//options / variables 
    options: {
		flashUrl: null,
		instanceId: 'leuk',
		containerId: null,
		sd: null,
		hd: null,
		flowplayerOptions: {
			clip: null,
            key: null,
            logo: { opacity: 0 }
		},
		isLoaded: false,
		
		//chapter
        activeChapter:false,
        chapters: null,
        cuepoints:[],
        chapterByCuepoint:{},
		chapterContainerId: null,
		onBeginCuePoint:0,
        
        //foldout
        
        activeFoldout: false,
        FxFoldout: null
    },
	flowplayer: null,
	provider: null,
    chapterCarousel: null,
    firstPlayed : false,
    windowUnloaded: false,

    initialize: function(globalOptions,instanceOptions,provider) {
        this.setOptions(globalOptions);
		this.setOptions(instanceOptions);	
		this.options.flowplayerOptions.playlist = [this.options.sd, this.options.hd];
		this.provider = provider;
		this.setupChapters();
		this.bindFlowplayerEventListeners();
		this.create();
        this.setupChapterCarousel();
        
        window.addEvent('beforeunload', function() {
           this.onWindowBeforeUnload();
        }.bind(this));
    },
    
    onWindowBeforeUnload: function(){
        if (this.options.firstPlayed && (!this.options.windowUnloaded)){
            var timeinSecs = parseInt(this.flowplayer.getTime());
            var timeLabel = Math.floor(timeinSecs /  60) + ':' + (timeinSecs % 60);
            trackAnalyticsEvent("Watched until", timeLabel, timeinSecs);
            this.options.windowUnloaded = true;
            //alert(timeLabel);
        }
        
    },
    
    setupChapterCarousel: function(){
        var el = $('chapters');
        //alert(el);
        this.chapterCarousel = new SerieCarousel({
            viewport:el.getElement('div.viewport'),
            carousel:el.getElement('ol'),
            previous:el.getElement('a.previous'),
            next:el.getElement('a.next'),
            listItems:el.getElements('li'),
            orientation:'vertical'
        }, this);
    },
	
    create: function(){
		this.flowplayer = $f( 
			this.options.containerId, 
			{src:this.options.flashUrl,  wmode: "opaque"}, 
			this.options.flowplayerOptions
		);
    },

	//to bind, track and propagate
	bindFlowplayerEventListeners: function(){
    
		var flowplayerEvents = this.options.flowplayerOptions;
        
		flowplayerEvents.onLoad = function(){ 
			this.onLoad();
		}.bind(this);
            
		flowplayerEvents.onFullscreen = function(){ 
            //trackAnalyticsEvent("Video: " + this.flowplayer.getClip().url, "Fullscreen", this.flowplayer.getClip().url, parseInt(this.flowplayer.getTime()));
			this.onFullscreen();
		}.bind(this);	
        
        flowplayerEvents.onFullscreenExit = function(){ 
            //trackAnalyticsEvent("Video: " + this.flowplayer.getClip().url, "FullscreenExit", this.flowplayer.getClip().url, parseInt(this.flowplayer.getTime()));
			this.onFullscreen();
		}.bind(this);
            
        flowplayerEvents.onSeek = (function(clip,time){ 
            /*var timeinSecs = parseInt(this.flowplayer.getTime());
            var timeLabel = Math.floor(timeinSecs /  60) + ':' + (timeinSecs % 60);
            trackAnalyticsEvent("Seek", timeLabel, timeinSecs);
			this.onSeek(clip, time);*/
		}).bind(this);
		
		flowplayerEvents.clip.onBegin = (function(clip){ 
            if (!this.options.firstPlayed){
                this.options.firstPlayed = true;
                trackAnalyticsEvent("Watched video", "site"); 
            }
			this.onBegin();
		}).bind(this);
        
        flowplayerEvents.onUnload = function(){ 
		}.bind(this);	
        
        flowplayerEvents.clip.onStart = (function(clip){ 
            //trackAnalyticsEvent("Start", clip.url, parseInt(this.flowplayer.getTime()));
		}).bind(this);
        
        
        flowplayerEvents.clip.onPause = (function(clip){ 
            //trackAnalyticsEvent("Video: " + clip.url, "Pause", clip.url, parseInt(this.flowplayer.getTime()));
		}).bind(this);
        
        flowplayerEvents.clip.onStop = (function(clip){ 
            //trackAnalyticsEvent("Video: " + clip.url, "Stop", clip.url, parseInt(this.flowplayer.getTime()));
		}).bind(this);
        
        flowplayerEvents.clip.onFinish = (function(clip){ 
            //trackAnalyticsEvent("Video: " + clip.url, "Finish", clip.url);
		}).bind(this);
        
        flowplayerEvents.clip.onStop = (function(clip){ 
            //trackAnalyticsEvent("Video: " + clip.url, "Stop", clip.url, parseInt(this.flowplayer.getTime()));
		}).bind(this);
        
     
        
        if (this.options.cuepoints.length == 0){
            return;
        }
        flowplayerEvents.clip.onCuepoint = [this.options.cuepoints, function(clip, cuepoint) { 
            //trackAnalyticsEvent("Video: " + clip.url, "CuePoint reached: " + cuepoint, clip.url, parseInt(this.flowplayer.getTime()));
            this.onCuepoint(clip, cuepoint);
		}.bind(this)];
        
	},
    
    setupChapters: function(){
        var list = $$('#' + this.options.chapterContainerId +' li');
        for (var i = 0; i < list.length;i++){
			
			var elChapter = $(list[i]);
            if(elChapter.hasClass('firstline')) {
                continue;
            }
			var cuepoint = this.getCuepointByChapterElement(elChapter);
			
			//* 1000 = fix inconsistent flowplayer cuepoints / seek API
			cuepoint *= 1000;
			this.options.cuepoints.push(cuepoint);
            this.options.chapterByCuepoint[cuepoint] = elChapter;
			
			//add onclick event to chapter

            var chapterImg = elChapter.getElements('div.thumbnailContainer');

			chapterImg.addEvent('click', function(e){
			  var chapter = e.target;
			  while(chapter.tagName != 'LI'){
				chapter = chapter.parentNode;
			  }
			  this.onChapterClicked($(chapter));
			  
			}.bind(this));
            //<p><a href="#" class="full-description">volledige beschijving &laquo; </a></p>
                    
            if (!elChapter.getElement('div.foldout')){
                continue;
            }

            elChapter.getElement('.item h3').addEvent('click', function(e) {
                        var chapter = e.target;
                        e.stop();
                        while(chapter.tagName != 'LI'){
                            chapter = chapter.parentNode;
                        }
                        
                        this.onButtonFoldClicked($(chapter));
            }.bind(this));
            
            /**
            var buttonFoldout = new Element('a', {
                'class': 'full-description',
                'href': 'javascript:void(0)',
                'html': this.provider.getPageLanguage() == 'nl' ? 'meer info &raquo;' : 'more info &raquo;',
                'events': {
                    //add onclick event
                    'click': function(e){
                        
                        var chapter = e.target;
                        e.stop();
                        while(chapter.tagName != 'LI'){
                            chapter = chapter.parentNode;
                        }
                        
                        this.onButtonFoldClicked($(chapter));
                    }.bind(this)
                }
            });
            buttonFoldout.inject(new Element('p').inject(elChapter));
            **/
        }
        
        // bah bah
		var button = new Element('a', {
			'id': 'button-close-chapter-foldout',
			'href': 'javascript:void(0)',
			'html': this.provider.getPageLanguage() == 'nl' ? 'sluiten' : 'close',
			'events': {
				//add onclick event
				'click': function(e){
					this.onButtonCloseFoldClicked();
				}.bind(this)
			}
		});
        button.inject($('chapter-foldout'));
    },
    
    onButtonCloseFoldClicked: function(){
        var folder = $('chapter-foldout');
        this.FxFoldout = new Fx.Morph(folder);
        this.FxFoldout.start( {
            'left': 680
        });
        if (this.options.activeFoldout){
            this.options.activeFoldout.removeClass('folded-out');
        }
        this.options.activeFoldout = null;
    },
    
    onButtonFoldClicked: function(item){
        
        this.flowplayer.pause();
        if (!item){
            return;
        }
        if (this.options.activeFoldout){
            this.options.activeFoldout.removeClass('folded-out');
        }
        this.options.activeFoldout = item;
        item.addClass('folded-out');
        var folder = $('chapter-foldout');
        var clone = item.getElement('div.foldout').clone().replaces(folder.getElement('div.foldout'));
        
        this.FxFoldout = new Fx.Morph(folder);
        this.FxFoldout.start( {
            'left': 35
        });
    },
    
    onChapterClicked: function(self){

        var cuepoint = this.getCuepointByChapterElement(self);
        
        var noteLabel = self.getElements('h3')[0].innerHTML;
        trackAnalyticsEvent("Note clicked", noteLabel);
        
        this.setActiveChapter(self);
		if (!this.options.isLoaded){
			this.options.onBeginCuePoint = cuepoint;
			this.flowplayer.play();
			return;
        }
        this.flowplayer.seek(cuepoint);
	},
	
	getCuepointByChapterElement: function(chapter){
		return parseInt(chapter.getParent().getElement('span.cuepoint').innerHTML,10)
	},
    
    setActiveChapter: function(item){
        this.onButtonCloseFoldClicked();
        if (!item){
            return;
        }
        if (this.options.activeChapter){
            this.options.activeChapter.removeClass('active');
        }
        this.options.activeChapter = item;
		item.addClass('active');
        //this.chapterCarousel.jumpToItem(item);
    },
    
	onLoad: function(){
		//alert(this.options.flashUrl);
        //this.flowplayer.seek(2000);
	},
	
	onBegin: function(clip){
		if (!this.options.isLoaded){
			this.flowplayer.seek(this.options.onBeginCuePoint);
			this.options.isLoaded = true;
        }
		
	},
	
	onFullscreen: function(){
		//this.flowplayer.seek(200);
	},
    
    onSeek: function(clip, time){
		//find the current playlist item and activate it
		var previousChapter = null;
        for (var i in this.options.chapterByCuepoint){
			if(i > time * 1000 && previousChapter){
				this.setActiveChapter(previousChapter);
				break;
			}
			previousChapter = this.options.chapterByCuepoint[i];
        }
        if (previousChapter){
            this.setActiveChapter(previousChapter);
        }
    },
    
    onCuepoint: function(clip, cuepoint){
		
		//activate the next playlist item 
        this.setActiveChapter(this.options.chapterByCuepoint[cuepoint]);
    }
	
});


var Application = new Class({
    Implements: [Events, Options],
    options: {
		playerOptions: null,
		pageToolsFoldout: null,
		reactionToggler: null,
        videoTrackingSlug:null
    },
	videoPlayers:{},
    serieCarousels:[],
    
    initialize: function(options) {
        this.setOptions(options);
        window.addEvent('domready', function() {
           this.onDomReady();
        }.bind(this));
    },
    
    onDomReady: function() {
        this.setupDraggableLogo();
        this.setupDraggableToolbox();
        this.setupPageToolsFoldouts();
        this.setupAutoSelectCodeElements();
        this.setupReactionToggler();
        this.setupCreditsToggler();
        this.setupCarousels();
        this.setupFavoriteButtons();
        this.setupSaveVideoLightBox();
        this.setupVideoStatistics();
    },
    
    setVideoTrackingSlug: function(strSlug){
        this.options.videoTrackingSlug = strSlug;
    },
    
    getVideoTrackingSlug: function(){
        return this.options.videoTrackingSlug;
    },
    
    setupVideoStatistics: function(){
       
       //download
        var buttonDownload = $('button-download');
        if (buttonDownload){
            buttonDownload.addEvent('click', 
                function(){
                    trackAnalyticsEvent('Downloaded');
                }
            )
        }
        
        //share
        var list = $$('#subsection-share li a');
        for (var i = 0; i < list.length; i++){
            list[i].addEvent('click', 
                function(){
                    var el = this.getElement('img');
                    if (!el){
                        return;
                    }
                    trackAnalyticsEvent('Shared',el.getProperty('alt'));
                }
            )
        }
    },
    
    setupSaveObject: function(){
        var form = $('save-object-form');
        if (!form) {
          return;
        }
        var submitb = $('save-object-submit');
        var submitted = function() {
          form.send();
          $('video-save-box').set('html', '');
          $('video-save-box').setAttribute('style', 'display:none');
          return false;
        }
        submitb.addEvent('click',submitted );
    },

    setupSaveVideoLightBox: function(){
        var setupSaveObject = this.setupSaveObject; 
        var el = $('mark-as-favorite');
        var box = $('video-save-box');
        if (!el) {
          return;
        }
        el.addEvent('click', function(e) {
            if($$('p.logged-in').length == 0) {
                $('nav-login').fireEvent('click');
            }
            href = this.getProperty('href');
            box.setProperty('style','display: block;');
            // fill the light box
            var getForm = new Request.HTML({url: href,
                                            onSuccess: function (tree,elements,html,js){
                                            box.set('html',html);
                                              //create hook to close the box
                                              $$('.close-me-link').addEvent('click', function(){
                                                box.setProperty('style','display: none;');
                                                return false;
                                              });
                                              setupSaveObject();
                                              return false;
                                            }
            }).get();
            e.stop();
        });
    },

    setupDraggableLogo: function(){
        //lekker hard coded en een beetje vies, want ik ga er vanuit dat de site-toolbox altijd bestaat
        
        var el = $('logo-arttube-container');
        el.setStyle('display','block');
        var marginLeft = Cookie.read('logoMarginLeft');
        if (marginLeft){
            el.setStyle('marginLeft',marginLeft);
        }
        var styleTop = Cookie.read('logoTop');
        if (styleTop){
            el.setStyle('top',styleTop);
        }


        
        var drag = new Drag('logo-arttube-container', {
            snap: 0,
            onSnap: function(el){
                el.addClass('dragging');
                $('site-toolbox').setStyle('z-index', '200');
                el.setStyle('z-index', '300');
            },
            onComplete: function(el){
                var duration = 100;
                el.removeClass('dragging');
                var cookie = Cookie.write('logoMarginLeft',el.getStyle('marginLeft'),{duration: duration, path: '/'});
                var cookie = Cookie.write('logoTop',el.getStyle('top'),{duration: duration, path: '/'});
            },
            modifiers: {x: 'marginLeft', y: 'top'}
        });
    },

    setupDraggableToolbox: function(){
        //lekker hard coded en een beetje vies, want ik ga er vanuit dat de logo-container altijd bestaat
        if($('search-text')) {
            $('search-text').addEvent('click', function(e) {
                this.focus();
                e.stop();
            });
        }
        
        if($('id_username')) {
            $('id_username').addEvent('click', function(e) {
                this.focus();
                e.stop(); 
            });
            $('id_password').addEvent('click', function(e) {
                this.focus();
                e.stop(); 
            });
        }
        
        var el = $('site-toolbox');
        var close = $('close-mijn');
        var open = $('nav-login');

        //el.setStyle('display','block');
        if(close) {
            close.addEvent('click', function(e) {
                $(el).setStyle('display', 'none');
                var cookie = Cookie.write('mijnClosed', 'yes', {duration: 100, path: '/'});
            });
        }
    
        if(open) {
            open.addEvent('click', function(e) {
                $(el).setStyle('display', 'block');
                $(el).setStyle('top', 100);
                $(el).setStyle('margin-left', -300);
                var cookie = Cookie.write('mijnClosed', 'no', {duration: 100, path: '/'});
            });
        }


        var closed = Cookie.read('mijnClosed');
        if(closed != 'no') {
            $(el).setStyle('display', 'none');
        }

        
        if(el) {
            //el.setStyle('display','block');
            var marginLeft = Cookie.read('toolboxMarginLeft');
            if (marginLeft){
                el.setStyle('marginLeft', marginLeft);
            }
            var styleTop = Cookie.read('toolboxTop');
            if (styleTop){
                el.setStyle('top',styleTop);
            }
            var drag = new Drag('site-toolbox', {
                snap: 0,
                onSnap: function(el){
                    el.addClass('dragging');
                    $('logo-arttube-container').setStyle('z-index', '200');
                    el.setStyle('z-index', '300');
                },
                onComplete: function(el){
                    var duration = 100;
                    el.removeClass('dragging');
                    var cookie = Cookie.write('toolboxMarginLeft',el.getStyle('marginLeft'),{duration: duration, path: '/'});
                    var cookie = Cookie.write('toolboxTop',el.getStyle('top'),{duration: duration, path: '/'});
                },
                modifiers: {x: 'marginLeft', y: 'top'}
            });
        }


    },
 
	setupPageToolsFoldouts: function(){
		var options = this.options.pageToolsFoldout;
		if (!$(options.containerId)){
			return;
		}
		options.identifiers.each(function(id, i) {
            if ($('button-' + id)) {
                $('button-' + id).addEvent('click', function(e){
                    e.stop();
                    var options = this;
                    var oldActiveId = options.activeId;
                    options.activeId = e.target.getProperty('id').split('button-')[1];
                    if (oldActiveId){
                        $(options.containerId).removeClass(oldActiveId + '-active');
                        if (oldActiveId == options.activeId){
                            options.activeId = null;
                            return;
                        }
                    }
                    $(options.containerId).addClass(options.activeId + '-active');
                }.bind(this));
            }
		}, options);
	},
	
	
	setupAutoSelectCodeElements: function(){
		$$('code').each(function(el, i) {
			
			el.addEvent('click', function(e){
				this.autoSelect(e.target);
			}.bind(this));
			//alert(el);
		}, this);
	},
	
	/* This script and many more are available free online at
	The JavaScript Source!! http://javascript.internet.com
	Created by: Matt Murphy | http://www.matts411.com/ */
	autoSelect: function(selectTarget) {
		//alert(selectTarget);
		//return;
		if(selectTarget != null && ((selectTarget.childNodes.length == 1
		  && selectTarget.childNodes[0].nodeName == "#text") || (selectTarget.tagName == "INPUT"
		  && selectTarget.type == "text"))) {
			if(selectTarget.tagName == 'TEXTAREA' || (selectTarget.tagName == "INPUT" && selectTarget.type == "text")) {
				 selectTarget.select();
			} else if(window.getSelection) { // FF, Safari, Opera
				var sel = window.getSelection();
				var range = document.createRange();
				range.selectNode(selectTarget.firstChild);
				sel.removeAllRanges();
				sel.addRange(range);
			} else { // IE
				document.selection.empty();
				var range = document.body.createTextRange();
				range.moveToElementText(selectTarget);
				range.select();
			}
		}
	},
	
	getPageLanguage: function(){
		return $$('html').getProperty('lang');
	},
	
	setupReactionToggler: function(){
        
		var options = this.options.reactionToggler;
		if (!$(options.containerId)){
			return;
		}
		
		//create toggler
		var toggler = new Element('a', {
			'id': options.togglerId,
			'href': 'javascript:void(0)',
			'class': 'button-show-hide',
			'html': options.text[this.getPageLanguage()].hide,
			'events': {
				//add onclick event
				'click': function(e){
					var options = this.options.reactionToggler;
					var container = $(options.containerId);
					var el = $(options.togglerId);
					if (container.hasClass('collapsed')){
						el.set('text', options.text[this.getPageLanguage()].hide);
						container.removeClass('collapsed');
						return;
					}
					el.set('text', options.text[this.getPageLanguage()].show);
					container.addClass('collapsed');
				}.bind(this)
			}
		});
		
		//inject it
		toggler.inject($(options.containerId), 'top');
        toggler.fireEvent('click');
		
		//make page tools button smarter
		var pagetoolsButton = $(options.pageToolsButtonId);
		if($(pagetoolsButton)) {
    		pagetoolsButton.addEvent('click', function(e){
    			var options = this;
    			if ($(options.containerId).hasClass('collapsed')){
    				$(options.togglerId).fireEvent('click');
    			}
    		}.bind(options));
        }
	},
    
    setupCreditsToggler: function(){
        //ATTENTION FUNCTION DISABLED!!!!!!!! (nick)
        return;
		var options = this.options.creditsToggler;
		if (!$(options.containerId)){
			return;
		}
		
		//create toggler
		var toggler = new Element('a', {
			'id': options.togglerId,
			'href': 'javascript:void(0)',
			'class': 'button-show-hide',
			'html': options.text[this.getPageLanguage()].show,
			'events': {
				//add onclick event
				'click': function(e){
					var options = this.options.creditsToggler;
					var container = $(options.containerId);
					var el = $(options.togglerId);
					if (container.hasClass('collapsed')){
						el.set('text', options.text[this.getPageLanguage()].hide);
						container.removeClass('collapsed');
						return;
					}
					el.set('text', options.text[this.getPageLanguage()].show);
					container.addClass('collapsed');
				}.bind(this)
			}
		});
		
		//inject it
		toggler.inject(new Element(
            'p',
            {id:'credits-show-hide-container'}
        ).inject($(options.containerId), 'after'));
		
	},
    
    setupCarousels: function(){
        var list = $$('div.section-video-scroller');
		list.each(function(el, i) {
			this.serieCarousels.push(new SerieCarousel({
                viewport:el.getElement('div.viewport'),
                carousel:el.getElement('ul.scroller'),
                previous:el.getElement('a.previous'),
                next:el.getElement('a.next'),
                listItems:el.getElements('li a')
            }, this));
		}, this);
     },

    //for each button-favorite <a> element we add an onclick event that will fire a mark ajax call
    setupFavoriteButtons: function(){
        var list = $$('a[id^="button-favorite-"]');
		list.each(function(el, i) {
			id = el.getProperty('id').substring(16);
			el.addEvent('click', function(){
    			var myRequest = new Request({url: '/mark/video/'+id,
			    	                         method: 'post',
				                             data: 'action=mark',
				                             onSuccess: function (txt,xml){
    			                                 var response = JSON.decode(txt);
    				                             alert('I got an:' + response[0] + 'with details:' + response[1]);
    				                         }
    			}).send({method: 'post', data:'action=mark'});
    			return false;
			});
		}, this);
     },
	
	createVideoPlayer: function(options){
		var player = new ArttubePlayer(this.options.playerOptions, options, this);
		this.videoPlayers[options.playerId] = player;
		return player;
	}
});




var IE6Fixes = new Class({
    Implements: [Events, Options],
	
	//options / variables 
    options: {
		
    },

    initialize: function(options) {
    
        //no ie6: let's quit
        if (!(Browser.Engine.trident && Browser.Engine.version <= 4)){
            return;
        }
        
        //set those options
        this.setOptions(options);
        
        //set onload listener
        window.addEvent('domready', function() {
           this.onDomReady();
        }.bind(this));
        
        //setups
        this.setupBackgroundCacheForcer();
    },
    
    onDomReady: function() {
    
        //setups
        this.setupHoverElements();
    },
    
    setupBackgroundCacheForcer: function(){
        try {
            document.execCommand("BackgroundImageCache", false, true);
        } 
        catch(e){
        
        };
    },
    
    setupHoverElements: function(){
        
        this.options.hoverElements.each(function(cssQuery) {

            $$(cssQuery).each(function(el) {
                
                //mouseover
                el.addEvent('mouseover', function(e){
                    e.stop();
                    if (this.hasClass('hover')){
                        return;
                    }
                    this.addClass('hover');
                });
                
                //mouseout
                el.addEvent('mouseout', function(e){
                    e.stop();
                    this.removeClass('hover');
                });
                
            });

        });
    }
    
});


function trackAnalyticsEvent(action, opt_label, opt_value){

    var category = 'Video player: ' + arttube.getVideoTrackingSlug();
    if (!opt_label){
        var opt_label = null;
    }
    if (!opt_value){
        var opt_value = null;
    }
    //alert('**' + category);
    //var test =($$('div.content')[0]);
    //test.innerHTML = category + ', ' + action + ', ' + opt_label + ',' + opt_value +'<hr>' + test.innerHTML;
    pageTracker._trackEvent(category, action, opt_label, opt_value);
}

