/**
 * jQuery Fast Show slideshow plugin
 * by Glenn Yonemitsu - glenn <at> kratedesign <dot> com
 *
 * This creates a fading slideshow like any other slideshow, except you must
 * pass an array of image URIs (along with other optional attributes) to it. The
 * plugin then loads only the first one, then loads the others in sequence. This
 * ensures the slides which need to be visible are visible first, instead of 
 * having all download at once, forcing visitors to wait.
 *
 * Copyright (c) 2010 Glenn Yonemitsu
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
jQuery.fn.fast_show = function (images, options) {
    var defaults = {
            /**
             * # of milliseconds between transitions
             */
            interval: 6000,
            /**
             * Transition function that takes the current and next jQuery
             * objects
             */
            transition: function (curr, next) {
                curr.fadeOut(1000);
                next.fadeIn(1000);
            },
            pre_op: function (images) {
                return images;
            }
        },
        opts = jQuery.extend(defaults, options);
    return this.each(function () {
        if (images.length)
        {
            var el = jQuery(this),
                loaded = 0, // slides loaded
                ready = 0, // loaded and ready slides
                position = 0, // current slide position
                pre_slide = jQuery('> div.slide', el), // HTML hard coded slide
                pre_slide_count = pre_slide.length,
                image,
                image_count = images.length + pre_slide_count,
                img, div,
                slides,
                slides_complete = false,
                curr, next,
                attr_merge = function (attrs) {
                    var attr = '', a;
                    for (a in attrs)
                    {
                        if (typeof(a) === 'string' && (a === 'alt' || a === 'src'))
                        {
                            attr += a + '="' + attrs[a] + '" ';
                        }
                    }
                    return attr;
                },
                slide_info = function (image) {
                    var text = jQuery('<div class="lifestyle_text" />');

                    text.append('<p class="intro">' + 
                                    'A lifestyle of tea:<br>' +
                                    'your mood, your day, your life.' +
                                '</p>');
                    if (image.primary !== undefined)
                    {
                        text.append('<p class="primary">' + image.primary + '</p>');
                    }
                    if (image.secondary !== undefined)
                    {
                        text.append('<p class="secondary">' + image.secondary + '</p>');
                    }
                    if (image.tertiary !== undefined)
                    {
                        text.append('<p class="tertiary">' + image.tertiary + '</p>');
                    }
                    if (image.type !== undefined)
                    {
                        switch (image.type)
                        {
                            case 'person':
                                text
                                    .addClass('lifestyle_type_person')
                                    .append('<p class="info">' + 
                                                'Tea is a way to refresh, decompress, and express. ' +
                                                'Premium Steap gets it. With teas from around the world, ' +
                                                'Premium Steap provides vibrant, fresh and fragrant teas. ' +
                                                'It’s not just a lifestyle. It’s <em>your</em> lifestyle.' +
                                            '</p>');
                            break;
                            case 'product':
                                text.addClass('lifestyle_type_product');
                            break;
                        }
                    }
                    if (image.uri !== undefined && image.uri !== '')
                    {
                        text.append('<a class="link_overlay" href="' + image.uri + '">&nbsp;</a>');
                    }
                    return text;
                },
                load_cb = function () {
                    if (!slides_complete)
                    {
                        loaded += 1;
                        if (loaded < image_count)
                        {
                            image = images[loaded];
                            img = jQuery('<img ' + attr_merge(image) + ' />')
                                .load(load_cb);

                            a = (image.uri === undefined || image.uri === '')
                                ? img
                                : jQuery('<a href="' + image.uri + '" />').append(img);

                            div = jQuery('<div class="slide" />')
                                .append(a)
                                .append(slide_info(image))
                                .hide();
                            el.append(div);
                        }
                        else
                        {
                            /**
                             * All images have been processed. Setting 
                             * remaining global variables (in plugin scope)
                             */
                            slides_complete = true;
                            slides = jQuery('> div.slide', el);
                            ready = slides.length;
                        }
                    }
                },
                /**
                 * Main slideshow fading loop
                 */
                fade_loop = function () {
                    if (slides_complete === false)
                    {
                        slides = jQuery('> div.slide', el);
                        /**
                         * last slide is still loading
                         */
                        ready = slides.length - 1;
                    }
                    /**
                     * Don't transition if the second slide isn't ready or
                     * doesn't exist
                     */
                    if (ready > 1)
                    {
                        var beans = jQuery('#lifestyle_counter .lifestyle_counter_bean'),
                        curr = slides.eq(position);

                        if (position + 1 >= ready)
                        {
                            position = 0;
                        }
                        else
                        {
                            position += 1;
                        }
                        next = slides.eq(position);
                        //opts.transition(curr, next);
                        slides.fadeOut();
                        next.fadeIn();
                        beans.removeClass('lifestyle_counter_bean_picked')
                        beans.eq(position)
                            .addClass('lifestyle_counter_bean_picked');
                    }
                },
                plugin_start = function () {
                    images = opts.pre_op(images);
                    image = images[0];
                    /**
                     * Load the first image into the DOM, and setup the 
                     * recursive callback function
                     */
                    // CUSTOM FOR PREMIUM STEAP
                    img = jQuery('<img ' + attr_merge(image) + ' />')
                        .load(load_cb);
                    a = (image.uri === undefined || image.uri === '')
                        ? img
                        : jQuery('<a href="' + image.uri + '" />').append(img);

                    div = jQuery('<div class="slide" />')
                        .append(a)
                        .append(slide_info(image));
                    if (pre_slide_count)
                    {
                        div.hide();
                    }
                    el.append(div);
                    setInterval(fade_loop, opts.interval);
                };

            /**
             * Check for existing slides hardcoded in the HTML and wait for
             * those to finish loading first
             */
            if (pre_slide_count)
            {
                jQuery('> img', pre_slide).load(plugin_start);
            }
            else
            {
                plugin_start();
            }

        }
    });
};

