/*
 *  Plaza SjideSwitch
 *
 */
slideSwitch = function(options){

	var _self = this;
    var _slideshowAutoPlay   = null;
    var _slideshowSize   = -1;
    var _imageCurrentId = null;
    var slideshowId = "#plz-header-slideshow";
    var slideshowItems = "#plz-header-slideshow img";

	/* Settings */
    this.settings   = {
        defaultIndex : 3, // int - Default options index to start the slideshow on
        slideshowAuto : true, // bool - True to run the auto slideshow, false to disable it
        slideshowAutoTimeout : 5000, // int - milliseconds to wait on each image. Void if 'slideshowAuto' is false
        selectedClass : "plz-selected" // string - classname to assign to the list element (ul>li, not the image) when selected
    };

    /* Initialization method */
    this.init = function (options){
        // Merge the settings
        this.settings   = $.extend(true, this.settings, options || {});

		// Carousel size (start from 0)
		this._slideshowSize  = $(slideshowItems).length-1;
		
		// First image display
        var defaultIndex = this.settings.defaultIndex <= this._slideshowSize ? this.settings.defaultIndex : 0;
		_self._imageCurrentId = this.settings.defaultIndex;

		$(slideshowItems+":eq("+_self._imageCurrentId+")").show();

    	// Auto play
		if(this.settings.slideshowAuto){
			this._slideshowAutoPlay = setInterval(this.imageAutoSwitch, this.settings.slideshowAutoTimeout);

			$(slideshowId).hover(
				function(){clearInterval(_self._slideshowAutoPlay);},
				function(){_self._slideshowAutoPlay = setInterval(_self.imageAutoSwitch,_self.settings.slideshowAutoTimeout);}
			);
		}
	}

    /* Switches the current selected optio */
    this.imageSwitch = function(theImageId){
		// Set auto current image id for autoplay
		this._imageCurrentId = theImageId;

		// Hiding visible images
		$(slideshowItems).fadeOut(200, function(){});

		// Display current image
		$(slideshowItems+":eq("+theImageId+")").fadeIn(1000);
	}

    /* Interval callback method */
    this.imageAutoSwitch = function(){

		// If first or last image
    	if(_self._imageCurrentId == _self._slideshowSize){
			_self._imageCurrentId = 0;
		}
		// Else set imageAutoCurrentId to next sibling
	 	else{
			_self._imageCurrentId ++;
		}

        // Switch to the next image
		_self.imageSwitch(_self._imageCurrentId);
	}

    // Execute self::init()
    this.init(options);
}

/* Pageload Initialization */
$(document).ready(
	function(){
        var settings = {};

        try {
            if (typeof pbx.obj.betaCarousel == "object")
                settings = pbx.obj.betaCarousel;
        } catch (e) {
            // Do nothing
        }
        
		slideSwitch(settings);
});

