vanilla.namespace('wisy.plugins.media');
vanilla.require('vanilla.toolkit.slide');

wisy.plugins.media.slider =
{
    containers : [],
    slideshows : [],

    add : function(container, slideURL, index, callback)
    {
        this.containers.push({container:container, slideURL:slideURL, index:index, callback:callback});
    },

    start : function()
    {
        this.containers.forEach
        (
            function(container)
            {
		var slideshow = null;

		if ( container.callback )
		{
		    slideshow = container.callback(container.container, container.slideURL);
		}
		else
		{
		    slideshow = new vanilla.toolkit.slide.Show(container.container, this._createSlideByType.bind(this, container.slideURL));
		    slideshow.setTransition(new vanilla.toolkit.slide.FadingTransition());
		}

		if ( slideshow )
		{
		    slideshow.init(container.index);
		    this.slideshows.push(slideshow);

		    new SimpleThread(slideshow.play.bind(slideshow), 1000).start();
		} 
            }
	    .bind(this)
        );
    },

    _createSlideByType : function(slideURL, type, parent, container)
    {
	var slide = null;
	if ( type == 'photo' )
	{
	    slide = new vanilla.toolkit.slide.ImageSlide(parent, container);
	}
	else if ( type == 'view360' )
	{
	    slide = new vanilla.toolkit.slide.Image360Slide(parent, container);
	}

	if ( slide && vanilla.html.DOM.hasClassName(container, "ajax") )
	{
	    var id = container.id.substr(slide.container.id.lastIndexOf("-") + 1);	    
	    slide.setLazyLoading(slideURL.replace("__ID__", id)); 
	}

	return slide;
    },

    getSlideshowById : function(id)
    {
	for ( var i = 0 ; i < this.slideshows.length ; i++ )
	{
	    var slideshow = this.slideshows[i];
	    if ( slideshow.container.id == id )
	    {
		return slideshow;
	    }
	}

	return null;
    },

    next : function(id)
    {
	this.getSlideshowById(id).next();
    },

    previous : function(id)
    {
	this.getSlideshowById(id).previous();
    },

    pause : function(id)
    {
	this.getSlideshowById(id).pause();
    },

    play : function(id)
    {
	this.getSlideshowById(id).play();
    },

    nextAndPlay : function(id)
    {
	var slideshow = this.getSlideshowById(id);
	slideshow.next();
	slideshow.play();
    },

    previousAndPlay : function(id)
    {
	var slideshow = this.getSlideshowById(id);
	slideshow.previous();
	slideshow.play();
    }
};

vanilla.addOnloadListener(wisy.plugins.media.slider.start, wisy.plugins.media.slider);
