/**
* Class used for the rotation articlelist tile.
*
* Supports periodical execution of rotation, navigation with previous/next links and article thumbnails.
*
* If thumbs is used, the thumb matching the article that is shown is marked as active with a css class, and it's
* also possible to click on thumbs to switch to matching article.
*
* Clicking on navigation links or thumbs will stop periodical execution.
*
*/

var RotationArticlelist = Class.create({

	/**
	* @param interval - Number of seconds used in periodical executor. If 0 is given, periodical execution is not used.
	*/
    initialize: function(element,interval) {
    	this.element = element;
    	this.interval = interval;
    	this.tileId = element.id.substring(5);
    	
    	this.articleCounter = 0;
    	
    	// Get all article-divs with that class-name
    	//this.articles = this.element.select('div.rotation-article'); 
    	this.articles = $$('div.rotation-article'); 
    	
    	/*console.log(this.articles)
    	console.log($$('div.rotation-article'))*/
    	
    	// Set the first rotation article div to be current
    	this.currentArticle = this.articles.first();
    	
    	// Get navigation bar if set (previous/next links)
    	this.navigation = this.element.select('div.rotation-navigation').first(); 
    	
    	// Check if navigation bar is set
    	if(typeof this.navigation == 'undefined' || this.navigation ==  null) {
    		// We now that navigation isn't added, so the variable must be set to null
            this.navigation = null;
        }
        else {
        	// If navigation should be available display it, since it by default set to display none in html
        	this.navigation.show();
        }
        
    	// Get all thumbs with given class-name
    	var thumbsElementContainer = $('thumbs-menu');

    	// Check if thumbs is set
    	if(typeof thumbsElementContainer == 'undefined' || thumbsElementContainer==null) {
    		// We now that thumbs menu isn't added, so the variable for thumbs must be set to null
            this.thumbs = null;
        }
        else {
        	// If thumbs should be available display them, since they are by default set to display none in html
        	thumbsElementContainer.show();
        	
        	this.thumbs = thumbsElementContainer.select('div.nav-thumb');
        	
        	// Since we display thumbs, we have to mark the thumbnail that is active initially
        	this.setActiveThumb();
        }
    
    	// Add listeners
    	this.addListeners();
    	
    },
    
    /**
    *	Function used to add listeners to elements
    */
    addListeners: function() {
    	// Start periodical executer with given interval. Interval like 0 indicates that periodical execution should not happen

    	if(this.interval > 0) {
    		
    		this.pe = new PeriodicalExecuter(this.periodicalExecutor.bind(this), this.interval);
    	}

    	// Navigation listener (previous/next links) if set
        if(this.navigation != null) {
        	// If navigation is added we must have listener to previous and next links
        	
        	// Listener for previous link
        	this.element.select('a.rotation-previous').first()
                .observe('click', this.previousArticleListener.bindAsEventListener(this));
            
            // Listener for next link
            this.element.select('a.rotation-next').first()
                .observe('click', this.nextArticleListener.bindAsEventListener(this));
        }
        
        // Thumbnails listener to each thumb if set
        if(this.thumbs != null) {
        	this.thumbs.each(function(element) {
               element.observe('click', this.thumbnailListener.bindAsEventListener(this));
            }.bind(this));
        }
    },
    
    /**
    *	Function used to mark active thumbnail with a given css class.
    *	This is done based on the id for current article element.
    *
    *	If no thumbs should be display, the function does nothings and returns.
    * 
    */
    setActiveThumb: function() {
    	// Return if there are no thumbnails
        if(typeof this.thumbs == "undefined" || this.thumbs == null) {
            return;
        }
        
        var currentArticleElementID = this.currentArticle.identify();
        
        var currentArticleUniqueID = currentArticleElementID.substring(currentArticleElementID.lastIndexOf('-') + 1);
        
        // Loop through thumbs to see if we find matching a thumb with matching id
        this.thumbs.each(function(thumb) {
        	var thumbElementID = thumb.identify();
        	var uniqueThumbID = thumbElementID.substring(thumbElementID.lastIndexOf('-') + 1);
           	
        	// Set css class on active thumb
        	if(currentArticleUniqueID == uniqueThumbID){
        		thumb.addClassName('active-thumb');
        	}
        	// Remove active css class if thumb not active
        	else if(thumb.hasClassName('active-thumb')) {
        		thumb.removeClassName('active-thumb');
        	}
        	
        });
     
    },
    
    /**
    *	Function used to stop the periodical execution
    *	It's used if some of the click listeners triggers
    */
    stopPeriodicalExecutor: function() {
    	// stop periodical executer if it's defined
    	if(typeof this.pe != "undefined") {
            this.pe.stop();
        }
    },
    
    /**
    *	Function that get the next article to show and calls to the functions that displays an article element
    */
    nextArticle: function() {
    	
    	var nextArticleElement = this.currentArticle.next();

    	// If we can't get the next article element, use the first in articles array
     	if(nextArticleElement == null || nextArticleElement.hasClassName('rotation-article') == false) {
    		nextArticleElement = this.articles.first();
    	}

    	this.changeRotationArticle(nextArticleElement);
    	
    },
    
    /**
    *	Function that get the previous article to show and calls to the functions that displays an article element
    */
    previousArticle: function() {
    	
    	var previousArticleElement = this.currentArticle.previous();
    	
    	if(previousArticleElement == null  || previousArticleElement.hasClassName('rotation-article') == false) {
    		previousArticleElement = this.articles.last();
    	}
    	
    	this.changeRotationArticle(previousArticleElement);
    },
    
    /**
    * Rotate to a given article element
    *
    * @param toArticleElement - The article element that should be set visible
    */
    changeRotationArticle: function(toArticleElement) {
    	
    	// For now, current article is previous article and should no longer be visible - hide it
        this.currentArticle.hide();
        
        // Reset current article to be article we change to
        this.currentArticle = toArticleElement; 
        
        // Set the new current article to be visible
        this.currentArticle.show();
        
        // Mark active thumb
        this.setActiveThumb();
    },
    
    // ========================================================================
    // Event listeners
    
    nextArticleListener: function(event) {
        event.stop();

        // Periodical execution should be stopped
        this.stopPeriodicalExecutor();
        
        // Switch to next article
        this.nextArticle();
    }, 
    
    previousArticleListener: function(event) {
        event.stop();
        
        // Periodical execution should be stopped
        this.stopPeriodicalExecutor();
        
        // Switch to previous article
        this.previousArticle();
    },
    
    thumbnailListener: function(event) {
        event.stop();
        
        // Find the unique id to article element we want to show
        var clickedThumbElementID = event.findElement('div').identify();
        
        // Get the div element that represents wanted article element
        var articleElementToShowID = clickedThumbElementID.replace('thumb-','rotation-article-');
        
        var articleElementToShow = $(articleElementToShowID);

        if(articleElementToShow != null) {
        	// Periodical execution should be stopped
        	this.stopPeriodicalExecutor();
        
        	this.changeRotationArticle(articleElementToShow);
        }
        
    },
    
    periodicalExecutor: function(pe) {
        this.nextArticle();
    }
  
});