/*
 * @name           Content Slider
 *
 * @description    Transform a list of items in a content slider component
 *
 * @requires       jQuery 1.3.2
 * @requires       jQuery.Class plug-in (http://www.taylanpince.com/blog/posts/jquery-class-plug-in)
 * @requires       Trapeze Core Plugins
 * @requires       jquery.easing (v. 1.3)
 *
 */

$.namespace("trapeze.ContentSlider");

trapeze.ContentSlider = $.Class.extend({
    conf : null,
    classes : null,
    copy : null,
    
    $obj : null,
    
    total_pages   : null,
    current_page  : null,
    content_heigh : null,
    content_width : null,
    timer         : null,
    
    /* Template Variables */
    wrapper             : '<div class="%(wrap_class)"></div>',
    control_wrapper     : '<div class="control %(control_class)">%(control_text)</div>',
    item_control        : '<li><span>%(content)</span></li>',
    
    showPage : function(page) {
        alert('test');
    },
    
    moveTo : function(evt) {
        if (this.current_page == null) {
            this.showPage(1); /* TODO: Set this right */
        }
        
        var last_page = null
        var from = this.current_page;
        var to   = (evt.data.page >= 0 ? evt.data.page : (evt.data.next ? evt.data.next : (evt.data.prev ? from - 1 : 0)));
            if (from == (this.total_pages-1) && to == 0){
                last_page = true;  
            }
            
        if ((from == to) || (to >= this.total_pages) || (to < 0)) { return false; }
        
        var new_position = null;
        
        this.$obj.find('li.'+ this.classes.slider_item +' .message').hide(); //hide all messages
        
        this.current_page = to;
        if (this.conf.direction == 'vertical') {
            new_position = to * this.content_heigh;
            
            this.$obj.find('li.'+ this.classes.slider_item).stop(true, true).animate({ top: ('-' + new_position + 'px') }, { 
                duration: this.conf.speed, 
                easing  : this.conf.easing,
                complete: this.showMessage.bind(this)
            });
        } else { // direction == horizontal // default value
            new_position = to * this.content_width;
            
            this.$obj.find('li.'+ this.classes.slider_item).stop(true, true).animate({ left: ('-' + new_position + 'px') }, { 
                duration: this.conf.speed,
                easing  : this.conf.easing,
                complete: this.showMessage.bind(this)
            });            
        }
    },

    togglePlayback : function(evt) {
        var $target = $(evt.currentTarget);
        if ($target.hasClass('paused')) {
            $target.removeClass('paused');
            var next_slide = this.current_page + 1;
            if (next_slide > this.total_pages) { next_slide = 0; };
            //this.timer = setInterval('this.moveTo({data: {next: '+ next_slide +'}})', this.conf.delay).bind(this); /* TODO: call the function */
            //Todo: change the content text to this.copy.play
        } else { // If it playing then pause
            clearInterval(this.timer);
            $target.addClass('paused');
            //Todo: change the content text to this.copy.pause
        }
    },

    autoPlay : function(evt) {
        var $target = $(".content-slider");
        var slide_data = {data: {next: '+ next_slide +'}}
        
        this.timer = setInterval(function(){
            var next_slide = this.current_page + 1;
            if (next_slide >= this.total_pages) { next_slide = 0; };
            this.moveTo({data: {next: next_slide }})
        }.bind(this), this.conf.delay);
    },
    
    buildBasicControls : function() {
        this.$obj
        .append(trapeze.render_template(this.control_wrapper, {
            'control_class'   : 'left',
            'control_text'    : this.copy.previous
        }))
        .append(trapeze.render_template(this.control_wrapper, {
            'control_class'   : 'right',
            'control_text'    : this.copy.next
        }))
        .find('.control.left').bind('click', {prev: true}, this.moveTo.bind(this))
        .parent()
        .find('.control.right').bind('click', {next: true}, this.moveTo.bind(this));
    },
    
    buildPagination : function() {
        this.$obj.append(trapeze.render_template(this.control_wrapper, {
            'control_class': this.classes.pagination,
            'control_text' : '<ul></ul>'
        }));
        this.$obj.find('li').each(function(i, obj) {
            this.$obj.find('.'+this.classes.pagination+' ul').append(trapeze.render_template(this.item_control, {
                'content': (i + 1)
            }))
            .find('li').eq(i).bind('click', {page: i }, function(){
                clearInterval(this.timer);
                this.moveTo({data: {page: i }});
            }.bind(this));     
        }.bind(this));
    },

    buildPlaybackControls : function() {
        this.$obj.append(trapeze.render_template(this.control_wrapper, {
            'control_class': this.classes.playback,
            'control_text' : '<ul></ul>'
        })).find('.' + this.classes.playback + ' ul').append(trapeze.render_template(this.item_control, {
            'content'   : this.copy.play
        })).find('li').bind('click', this.togglePlayback.bind(this));
    },

    showMessage : function(e) {
        var $msg = this.$obj.find('li.'+ this.classes.slider_item).eq(this.current_page).find('.'+this.classes.message);
        if ($msg.css('display') != 'block') { //TODO: Redo with another way to find if this method was already called
            $msg.css('bottom', ('-' + $msg.outerHeight() + 'px')).show()
            .animate({ bottom: ('0px') }, this.conf.msg_speed);
            this.cleanUp();
        }
    },
    
    cleanUp : function() {
        if (this.current_page == 0) {
            this.$obj.find('.control.left').addClass(this.classes.disabled);
        } else {
            this.$obj.find('.control.left').removeClass(this.classes.disabled);
        }
        if ((this.current_page + 1) == this.total_pages) {
            this.$obj.find('.control.right').addClass(this.classes.disabled);
        } else {
            this.$obj.find('.control.right').removeClass(this.classes.disabled);
        }
        this.$obj.find("."+this.classes.pagination+" ul li").each(function(i, obj){
            $(obj).toggleClass(this.classes.current_page, i==this.current_page);
        }.bind(this));
        //this.$obj.find("."+this.classes.pagination+" ul li").removeClass(this.classes.current_page)
        //.eq(this.current_pate).addClass(this.classes.current_page);
        //this.$obj.find("."+this.classes.pagination+" ul li:eq("+ this.current_page + ")").addClass(this.classes.current_page);
    },

    init : function(options, classes, copy) {
        var defaults = {
            basic_controls : false,             // If true it will render basic navigation controls: Next and Previous
            page_controls  : true,              // If true it will render pagingation controls
            play_controls  : false,             // if true it will render playback controls: Play and Pause
            
            //TODO: //fade_controls  : true,              // fade out when mouse is away and fade in when mouse is over
            
            show_first     : true,              // Shows the first item at the begining // not fully implemented yet
            speed          : 900,               // Transition speed
            effect         : 'scroll',          // Transition effect - just scroll is supported at the moment
            easing         : 'easeOutCubic',    // Easing property to be applied on the scroll animation
            auto_scroll    : true,             // if `true` automatically scroll to the next item // not implemented yet
            delay          : 8000,               // time before automatically scrolling to the next item
            //TODO: //continuous     : false,    // It will animate to the first item after the last item // not implemented yet
            direction      : 'horizontal',      // Animation direction - horizontal or vertical
            msg_speed      : 600,
            //TODO: //msg_position : 'bottom',    // position of messages
            
            //TODO: //onComplete     : function() {},     // Call back method after the animation is complete // not implemented yet
            selector       : null               // Selector for the slider(s)
        };

        var component_classes = {
            slider         : 'content-slider',  // Class applied to the root element of the content slider
            slider_item    : 'slider-item',
            disabled       : 'disabled',
            current_page   : 'current',
            message        : 'message',
            pagination     : 'pagination',
            playback       : 'playback'
        };

        var controls_copy  = {
            previous       : 'Previous',        // Text to be used on the previous control
            next           : 'Next',            // Text to be used on the next control
            play           : 'Play  ',            // Text to be used on the play control
            pause          : 'Pause'            // Text to be used on the pause control
        };
        
        this.conf = $.extend({}, defaults, options);
        this.classes = $.extend({}, component_classes, classes);
        this.copy = $.extend({}, controls_copy, copy);
        
        this.$obj = $(this.conf.selector);
        
        $(this.conf.selector).each(function(i, obj) { //cycles through each selected element to create the content sliders
            $(obj).wrap(trapeze.render_template(this.wrapper, {'wrap_class': this.classes.slider}))
            .find('li').addClass(this.classes.slider_item);
            
            this.$obj = $(obj).parent();
            this.total_pages = this.$obj.find('li.'+ this.classes.slider_item).length;
            this.content_heigh = this.$obj.find('.'+ this.classes.slider_item +':eq(0)').height();
            this.content_width = this.$obj.find('.'+ this.classes.slider_item +':eq(0)').width();
            
            //this.$obj.addClass(this.classes.main);
            
            if (this.conf.basic_controls) { this.buildBasicControls(); }
            if (this.conf.page_controls) { this.buildPagination(); }
            if (this.conf.play_controls) { this.buildPlaybackControls(); } // TODO: To be implemented
            
            if (this.conf.direction == 'horizontal') {
                $(this.conf.selector).width((this.total_pages*this.content_width) + 'px');
            }
            
            if (this.conf.show_first) {
                this.current_page = 0;
                this.$obj.find('li.'+ this.classes.slider_item).eq(this.current_page).find('.'+this.classes.message).hide();
                this.showMessage();
            } else { // TODO: Not fully tested yet
                this.$obj.find('li').hide();
            }
            
            if (this.conf.auto_scroll) { 
                //$('.content-slider').bind('ready', this.togglePlayback.bind(this)); 
                this.autoPlay();
            }
            
        }.bind(this));
    }
})