/**
 * Create a slideshow for a given set of images.
 *
 * The `ep.uiSlides()` method creates a slideshow for a given set of images.
 *
 * ### Examples
 * Create a simple slideshow.
 *
 * JavaScript:
 *
 *     ep('#slides01')
 *       .uiSlides({
 *         images  : '#images img',
 *         action  : "lightbox",
 *         caption : true,
 *         count   : true,
 *         delay   : 500,
 *         autoplay: true
 *     });
 *
 * HTML:
 *
 *     <ul id="images" style="display:none;">
 *       <li>
 *         <img
 *           alt="Bild 1"
 *           src="ep/ui/slidesTest_Image1.jpg"
 *           data-src-m="ep/ui/slidesTest_Image1.jpg"
 *           data-src-l="ep/ui/slidesTest_Image1.jpg"
 *         />
 *       </li>
 *       <li>
 *         <img
 *           alt="Bild 2"
 *           src="ep/ui/slidesTest_Image2.jpg"
 *           data-src-m="ep/ui/slidesTest_Image2.jpg"
 *           data-src-l="ep/ui/slidesTest_Image2.jpg"
 *         />
 *       </li>
 *       <li>
 *         <img
 *           alt="Bild 3"
 *           src="ep/ui/slidesTest_Image1.jpg"
 *           data-src-m="ep/ui/slidesTest_Image1.jpg"
 *           data-src-l="ep/ui/slidesTest_Image1.jpg"
 *         />
 *       </li>
 *     </ul>
 *     <div id="slides01" style="width:400px;height:400px;"></div>
 *
 *
 * @class jQuery.ui.uiSlides
 * @extends jQuery.widget
 *
 * @uses ep.ui.core
 * @uses jQuery.event.special.load
 * @uses jQuery.event.special.touch
 * @uses jQuery.fn.class
 * @uses jQuery.tmpl
 * @uses jQuery.ui.widget
 * @since 6.14.0
 */

/**
 * @cfg {String} images A set of images which will be displayed.
 */

/**
 * @cfg {String} effect The change over effect.
 */

/**
 * @cfg {Number} delay The time images will be visible in the play mode.
 */

/**
 * @cfg {Boolean} autoplay A boolean indication wether to change images automatically by delay.
 */

/**
 * @cfg {String} controls The way the controls will be displayed (auto / visible / hidden).
 */

/**
 * @cfg {Boolean} caption A boolean indication wether to show the caption of the images.
 */

/**
 * @cfg {Boolean} count A boolean indication wether to show the count of the images like (i of n).
 */

/**
 * @cfg {String} defaultSize which image size should be used as default ( 'XS' / 'S' / 'M' / 'L' ).
 */

/**
 * See `jQuery.ui.uiSlides` for details.
 *
 * @param {Object} options A map of additional options pass to the method.
 * @param {String} images A set of images which will be displayed.
 * @param {String} effect The change over effect.
 * @param {Number} delay The time images will be visible in the play mode.
 * @param {Boolean} autoplay A boolean indication wether to change images automatically by delay.
 * @param {String} controls The way the controls will be displayed (auto / visible / hidden).
 * @param {Boolean} caption A boolean indication wether to show the caption of the images.
 * @param {Boolean} count A boolean indication wether to show the count of the images like (i of n).
 * @param {String} defaultSize which image size should be used as default ( 'XS' / 'S' / 'M' / 'L' ).
 *
 * @method uiSlides
 * @member jQuery
 *
 * @since 6.14.0
 */

/*
 * @copyright        © Copyright 2006-2012, epages GmbH, All Rights Reserved.
 *
 * @module            ep.ui.slides
 */

/*jslint browser: true, plusplus: true, nomen: true, ass: true*/
/*global define*/

define("ep/ui/slides", [
    "jquery",
    "ep",
    "$dict!ep/dict",
    "$tmpl!ep/ui/slides",

    "jquery/ui/widget",
    "jquery/fn/class",
    "jquery/event/special/load",
    "jquery/event/special/touch",
    "ep/ui/core"
], function ($, ep, epDict, tmplSlides) {

    'use strict';

    var tExpand = epDict.translate("Expand");

    $.widget("ui.uiSlides", {
        options: {
            //    action            : "lightbox",        //
            images: "img", // selector / array of data / data / image node / array of image nodes / jQuery object
            effect: "standard", // change-over effect
            delay: 3000, // how long are the images visible in play mode
            autoplay: false, // flag whether to change images automatically by delay
            controls: 'auto', // show controls or not ('auto' / 'visible' / 'hidden')
            caption: false, // show caption of images
            count: false, // show count of images like (i of n)
            defaultSize: 'M' // which image size should be used as default ( 'XS' / 'S' / 'M' / 'L' )
        },

        _create: function () {
            var self = this,
                o = self.options,
                imgs = self.images = ep.ui.imgData(o.images).on("change.uiSlides", $.proxy(self, "_change"));

            // load template and add element names to instance
            $.extend(self, tmplSlides([{
                expand: tExpand
            }])
                .appendTo(self.element)
                .tmplItem('elements'));

            self.ctrlPrevHandle.on("click.uiSlides", function () {
                imgs.current("prev");
            });

            self.ctrlNextHandle.on("click.uiSlides", function () {
                imgs.current("next");
            });

            self.container.on("click.uiSlides", function (event) {
                if (!$(event.originalTarget).is('.ep-uiSlides-ctrl a') && o.action) {
                    self._external(true);
                    imgs.trigger(o.action);
                }
            })
                .on("touchdrag.uiSlides", function (event) {
                    event.preventDefault();
                })
                .on("touchswiperight.uiSlides", function () {
                    imgs.current("prev");
                })
                .on("touchswipeleft.uiSlides", function () {
                    imgs.current("next");
                });

            self._setOptions(o);
        },

        _init: function () {
            var self = this;

            self._internal(true);
            self._change();
        },

        destroy: function () {
            var self = this;

            self.images.off(".uiSlides");
            self.container.remove();
            self._superApply(arguments);
        },

        _internal: function (set) {
            return arguments.length ? (this.eventInernal = set) : this.eventInernal;
        },

        _external: function (set) {
            var self = this;

            if (set) {
                self.eventExternal = true;
                self._autoplay();
            }

            return self.eventExternal;
        },

        _autoplay: function () {
            var self = this,
                o = self.options;

            clearInterval(self.playTimeout);

            if (o.autoplay && !self._external()) {
                // auto play with delay interval
                self.playTimeout = setTimeout(function () {
                    self._internal(true);
                    self.images.current(self.images.currentItem === self.images.length - 1 ? 0 : "next");
                }, o.delay);
            }
        },

        _setOption: function (key, value) {
            var self = this;

            if (key === "action") {
                self.container.css("cursor", value ? "pointer" : "");
            } else if (key === "controls") {
                self.container.removeClass(/ep-uiSlides-ctrl-[\w]+/)
                    .addClass("ep-uiSlides-ctrl-" + value);
            }

            return this._superApply(arguments);
        },

        _change: function () {
            var self = this,
                o = self.options,

                imgs,
                imgsNumber,
                imgsLength,
                prev,
                curr,
                next,

                imgSrc,

                boxNext,
                img,
                alt;

            self._external(!self._internal());
            self._internal(true);

            imgs = self.images;
            imgsNumber = imgs.currentItem + 1;
            imgsLength = imgs.length;
            prev = imgs.prev();
            curr = imgs.current() || {};
            next = imgs.next();

            // Get optimal image size for box and check image by default src
            imgSrc = curr._checkSrcName(curr['src' + o.defaultSize], curr.getSrcFor(self.box));
            alt = curr.node && curr.node.alt ? curr.node.alt : "";
            // escape double quotes in alt attribute
            alt = alt.replace(/"/g, "&quot;");

            self.ctrlPrev.addClass('ui-hidden');
            self.ctrlNext.addClass('ui-hidden');

            // change curr <> next
            boxNext = self.boxNext;
            self.boxNext = self.boxCurr;
            self.boxCurr = boxNext;

            self.desc.stop(true, true)
                .slideUp();

            img = $('<img alt="' + alt + '" src="' + imgSrc + '"/>')
                .on("load", function () {
                    var slideshow = $('#ProductSlideshow'),
                        currentHeight = slideshow.height();

                    if (this.height > currentHeight) {
                        slideshow.height(this.height);
                    }

                    self.boxCurr.show().append(img);
                    self.boxNext.hide().empty();

                    self.ctrlPrev.toggleClass('ui-hidden', !prev);
                    self.ctrlNext.toggleClass('ui-hidden', !next);

                    self.descCount.html(imgsNumber + "/" + imgsLength)
                        .toggle(!!o.count);

                    self.descCaption.html(curr.desc.replace(/\n/g, "<br />"))
                        .toggle(!!(o.caption && curr.desc));

                    if (o.count || (o.caption && curr.desc)) {
                        self.desc.stop(true, true)
                            .slideDown();
                    }

                    self._autoplay();
                })
                .appendTo('head');
        }
    });

    return ep;

});