/*
* jQuery jSlider 1.3.0.1
* http://onesite.se/jquery/jslider/
*
* Copyright 2010 Fredrik Forsmo (@Frozzare)
* Contribution by: David Rodrigues (@DavidProw)
* jSlider is under MIT license (MIT-License.txt)
*
*/

(function ($) {

    var version = '1.3.0.1';

    // Global data
    var global = {
        // Pre-defined base options
        base: {},
        // jSlider version
        version: 'jSlider: ' + version
    };

    // setup
    jSlider = {};

    // Constructor method
    var jSliderObject = function (object, base, options, collection) {
        // This object
        var self = this;
        // The div object
        var object = object;
        // The timer controller
        var timer;
        // currentIndex, current images.
        var currentIndex;
        // jSlider version
        var version = global.version;
        // The collection images
        var collection = collection;
        // tell $t that is the object
        var $t = object;
        // images var
        var images;
        // plugin images
        this.images;
        // collection check
        var isCollection = false;
        // is stop
        var isStop = false;
        // if it is collection, change to true
        if (collection) isCollection = true;
        // check if user using collection
        if (!isCollection) {
            // count images
            images = $t.children('img');
            // make ready for plugins
            this.images = $t.children('img');
        } else {
            if (collection) {
                for (var c = 0; c < collection.length; c++) {
                    $t.append('<img />');
                    $t.children('img').eq(c).attr('src', collection[c][0]).attr('alt', collection[c][1]);
                }
            }
            // count images
            images = $t.children('img');
            // make ready for plugins
            this.images = $t.children('img');
        }
        // images size
        var l = images.size();

        // Load options
        if (base == null) base = 'default';
        if (typeof base == 'string') base = $.jSlider.base(base);
        var options = $.extend(base, options);
        // just shorting down options
        var j = options;
        // prev base
        var prevBase = '<a class="slideprev" href="#">' + j.text.Prev + '</a>';
        // next base
        var nextBase = '<a class="slidenext" href="#">' + j.text.Next + '</a>';

        // we have to storge the width and height somewhere
        jSlider.settings = {};
        // used by cleanTime
        jSlider.aPlay;

        jSlider.clearTime = function () {
            window.clearInterval(jSlider.aPlay);
        };
        jSlider.autoPlay = function (play) {
            if (play) {
                jSlider.clearTime();
                jSlider.aPlay = window.setInterval(function () {
                    jSlider.action.slides(currentIndex + 1, 'next')
                }, j.time);
            } else {
                jSlider.clearTime();
            }
        };

        jSlider.btnSlide = function (p) {
            jSlider.clearTime();
            if (p) jSlider.action.slides(parseInt(currentIndex + 1), 'next');
            else jSlider.action.slides(parseInt(currentIndex - 1), 'prev');
            if (!isStop) jSlider.autoPlay(j.autoPlay);
        };
        jSlider.action = new function () {

            this.afterCheck = function (nextIndex, prevIndex) {
                for (var c = 0; c < l; c++) {
                    if (c == prevIndex || c == nextIndex) { }
                    else {
                        images.eq(c).removeClass().removeAttr('style');
                    }
                }
            };

            this.slides = function (nextIndex, type) {
                var plugins = $.jSlider.plugin.getPlugins.length;
                var prevIndex;
                if (!prevIndex) prevIndex = 0;
                if (prevIndex > 0) prevIndex = currentIndex;
                if (prevIndex < images.size()) prevIndex = currentIndex;

                if (j.effect == 'default') {
                    this.slide(nextIndex, type, prevIndex);
                }
                else {

                    if (nextIndex == images.size()) nextIndex = 0;

                    if (type == 'prev') {
                        if (nextIndex < 0) {
                            nextIndex = images.size() - 1;
                        }
                    }

                    currentIndex = nextIndex;

                    if (j.effect == 'fade') {
                        images.eq(prevIndex).css({ "z-index": 2 });
                        images.eq(nextIndex).css({ "opacity": 0, "z-index": 3 }).animate({ "opacity": 1 }, j.speed);
                        jSlider.action.afterCheck(nextIndex, prevIndex);
                    } else {
                        // call the plugin effect we like to use
try {
                         $.jSlider.plugin.effect[j.effect](images, nextIndex, prevIndex, type);
} catch(ex) {
this.slide(nextIndex, type, prevIndex);
}
                    }

                    // we change current cicle to
                    $t.find('.bulletcontrol a').removeClass('active').eq(nextIndex).addClass('active');
                    if (j.title) jSlider.action.setTitle(images.eq(nextIndex).attr('alt'));
                }
            };

            this.slide = function (nextIndex, type, prevIndex) {
                var currentSize;

                if (type == 'bullet') {
                    // find out if nextIndex is bigger, smaller or equal then currentIndex
                    if (nextIndex < currentIndex) {
                        currentSize = 'smaller';
                        if (prevIndex > 0) prevIndex + 1;
                    }
                    if (nextIndex > currentIndex) {
                        currentSize = 'bigger';
                        if (prevIndex < l) prevIndex - 1;
                    }
                    if (nextIndex == currentIndex) {
                        currentSize = 'equal';
                    }

                    if (currentSize) {
                        if (currentSize == 'smaller') {
                            images.eq(prevIndex).css({
                                "z-index": 2
                            }).removeClass().addClass('prev');
                            images.eq(nextIndex).css({
                                "left": -jSlider.settings.width,
                                "z-index": 3
                            }).animate({
                                "left": 0
                            }, j.speed).removeClass().addClass('current');
                        }

                        if (currentSize == 'bigger') {
                            images.eq(prevIndex).css({
                                "z-index": 2
                            }).removeClass().addClass('prev');
                            images.eq(nextIndex).css({
                                "left": jSlider.settings.width,
                                "z-index": 3
                            }).animate({
                                "left": 0
                            }, j.speed).removeClass().addClass('current');
                        }

                        if (currentSize == 'equal') {
                            // Why do anything? Let's have a cop of tea instead :)
                        }

                        jSlider.action.afterCheck(nextIndex, prevIndex);

                    }

                    currentIndex = nextIndex;
                }

                if (type == 'next') {
                    if (nextIndex == l) nextIndex = 0;

                    images.eq(prevIndex).css({
                        "z-index": 2
                    }).removeClass().addClass('prev');
                    images.eq(nextIndex).css({
                        "left": jSlider.settings.width,
                        "z-index": 3
                    }).animate({
                        "left": 0
                    }, j.speed).removeClass().addClass('current');

                    jSlider.action.afterCheck(nextIndex, prevIndex);

                    currentIndex = nextIndex;
                }

                if (type == 'prev') {

                    if (nextIndex > 0) nextIndex = currentIndex - 1;
                    if (nextIndex < 1) nextIndex = 0;
                    if (currentIndex == 0) nextIndex = images.size() - 1;

                    images.eq(prevIndex).css({
                        "z-index": 2
                    }).removeClass().addClass('prev');
                    images.eq(nextIndex).css({
                        "left": -jSlider.settings.width,
                        "z-index": 3
                    }).animate({
                        "left": 0
                    }, j.speed).removeClass().addClass('current');

                    jSlider.action.afterCheck(nextIndex, prevIndex);

                    currentIndex = nextIndex;
                }


                $t.find('.bulletcontrol a').removeClass('active').eq(nextIndex).addClass('active');

                if (j.title) jSlider.action.setTitle(images.eq(nextIndex).attr('alt'));

            };

            this.autoGenerate = function () {

                function autoTitle() {
                    $t.append('<div class="titlecontrol"><span class="fix"><p class="titlehide"><span class="title"></span> <span class="hide"><a href="#">' + j.text.Hide + '</a></span></p><p class="titleshow" style="display:none; margin-top:30px"><span class="show"><a href="#">' + j.text.Show + '</a></span></p></span></div>');
                }

                function autoBullet() {
                    $t.append('<div class="bulletcontrol" />');
                    var n = 0;
                    var html = '';
                    for (var c = 0; c < images.size(); c++) {
                        n = c + 1;
                        if (c === 0) {
                            html += '<a href="#" class="active" rel=' + c + '">' + n + '</a>';
                        } else {
                            html += '<a href="#" rel="' + c + '">' + n + '</a>';
                        }
                    }

                    $t.find('.bulletcontrol').append(html);
                }

                function autoNav() {
                    $t.append('<div class="navcontrol" />');
                    $t.find('.navcontrol').append(prevBase).append(nextBase);
                }

                if (j.hide == 'nav') {
                    autoBullet();
                }
                else if (j.hide == 'bullet') {
                    autoNav();
                }
                else if (j.hide == 'both') { } else {
                    autoNav();
                    autoBullet();
                    if (j.title) autoTitle();
                }

            };

            this.customRendering = function () {
                var up = j.customRendering.upLine;
                var bottom = j.customRendering.bottomLine;
                var prev = "%prev";
                var next = "%next";
                var bullet = "%bullet";
                var bulletBase = '';
                var html = '';
                var errmsg = "You can't set nav or both if you like to use ";

                function bulletDo(line) {
                    var $n = $(j.bulletClass);
                    html = '<div class="bulletcontrol">';
                    if (line.indexOf(prev) != -1) html += '<a href="#" class="slideprev">' + j.text.Prev + '</a>';
                    for (var e = 0; e < l; e++) {
                        n = e + 1;
                        if (e == 0) {
                            html += '<a href="#" class="active" rel="' + e + '">' + n + '</a>';
                        } else {
                            html += '<a href="#" rel="' + e + '">' + n + '</a>';
                        }
                    }
                    if (line.indexOf(next) != -1) html += ' ' + sam + ' <a href="#" class="slidenext">' + j.text.Next + '</a>';
                    html += '</div>';
                    return html;

                }

                function lastCheck(line) {
                    return line.replace(prev, "").replace(bullet, "").replace(next, "");
                }

                function renderReady(line) {
                    var li = line;
                    var q; // just a variable for renderReady
                    if (line.indexOf(prev) != -1 && !line.indexOf(bullet) != -1) {
                        q = lastCheck(renderReplace(li));
                    }
                    if (line.indexOf(next) != -1 && !line.indexOf(bullet) != -1) {
                        q = lastCheck(renderReplace(li));
                    }
                    if (line.indexOf(bullet) != -1) {
                        bulletBase = bulletDo(li);
                        q = lastCheck(renderReplace(li));
                    }
                    return q;
                }

                // running this function last when prev, next and bulletBase is ready to append

                function renderReplace(line) {
                    var q; // just a variable for renderReplace
                    var b;
                    if (line.indexOf(prev) != -1 && !line.indexOf(bullet) != -1) {
                        q = line.replace(prev, prevBase);
                    }
                    if (line.indexOf(next) != -1 && !line.indexOf(bullet) != -1) {
                        b = line.replace(next, nextBase);
                    }
                    if (line.indexOf(bullet) != -1) {
                        q = line.replace(bullet, bulletBase);
                    }
                    if (b != null) if (line.indexOf(bullet) != -1) b = "";
                    else q = q + b;

                    return lastCheck(q);
                }

                if (up != null) {
                    if (options.hide != 'btns' && options.hide != 'both') $t.append('<div class="upcontrol">' + renderReady(up) + '</div>');
                    else {
                        alert(errmsg + "up line");
                    }
                }

                if (bottom != null) {
                    if (options.hide != 'bullet' && options.hide != 'both') $t.append('<div class="bottomcontrol">' + renderReady(bottom) + '</div>');
                    else {
                        alert(errmsg + "bottom line");
                    }
                }
            };

            this.setTitle = function (title) {
                if (typeof (title) !== 'undefined' && title != null) {
                    $t.find('.title').empty().text(title);
                }
            };

            this.bulletRendering = function () {
                if (j.bulletClass.length > 0) {
                    var $n;
                    var n = 0;
                    if (j.bulletClass.indexOf(',') != -1) {
                        var b = j.bulletClass.split(',');
                        for (var c = 0; c < b.length; c++) {
                            $n = $(b[c]);
                            var html = '<div class="bullet">';
                            for (var e = 0; e < l; e++) {
                                n = e + 1;
                                if (e == 0) {
                                    html += '<a href="#" class="active" rel="' + e + '">' + n + '</a>';
                                } else {
                                    html += '<a href="#" rel="' + e + '">' + n + '</a>';
                                }
                            }
                            html += '</div>';
                            $n.append(html);
                        }
                    } else {
                        $n = $(j.bulletClass);
                        var html = '<div class="bullet">';
                        for (var e = 0; e < l; e++) {
                            n = e + 1;
                            if (e == 0) {
                                html += '<a href="#" class="active" rel="' + e + '">' + n + '</a>';
                            } else {
                                html += '<a href="#" rel="' + e + '">' + n + '</a>';
                            }
                        }
                        html += '</div>';
                        $n.append(html);
                    }
                }
            };

            this.navRendering = function () {
                if (j.navClass.length > 0) {
                    var $n;
                    var prevBase = '<a class="slideprev" href="#">' + j.text.Prev + '</a>';
                    var nextBase = '<a class="slidenext" href="#">' + j.text.Next + '</a>';
                    if (j.navClass.indexOf(',') != -1) {
                        var b = j.navClass.split(',');
                        for (var c = 0; c < b.length; c++) {
                            $n = $(b[c]);
                            $n.prepend(prevBase).append(nextBase);
                        }
                    } else {
                        $n = $(j.navClass);
                        $n.prepend(prevBase).append(nextBase);
                    }
                }
            };
        };

        var navClass = j.navClass;
        if (navClass.length > 0) {
            if (navClass.indexOf(',') != -1) {
                var nav = navClass.split(',');
                for (var c = 0; c < nav.length; c++) {
                    $(b[c]).find('.slidenext').live('click', function (e) {
                        jSlider.btnSlide(true);
                        e.preventDefault();
                    });
                    $(b[c]).find('.slideprev').live('click', function (e) {
                        jSlider.btnSlide(false);
                        e.preventDefault();
                    });
                }
            } else {
                $(navClass).find('.slidenext').live('click', function (e) {
                    jSlider.btnSlide(true);
                    e.preventDefault();
                });
                $(navClass).find('.slideprev').live('click', function (e) {
                    jSlider.btnSlide(false);
                    e.preventDefault();
                });
            }
        };

        // setup
        jSlider.init = function () {

            function appendToCollection() {
                jSlider.settings.height = images.eq(0).height();
                jSlider.settings.width = images.eq(0).width();
                $t.find('.collection').css({ "height": jSlider.settings.height, "width": jSlider.settings.width });
                $t.children('img').appendTo('.collection');
            }

            $t.prepend('<div class="collection" />');

            images.each(function () {
                if (this.width != 0) { appendToCollection(); }
                else { images.eq(0).load(function () { appendToCollection(); }); }
            });

            currentIndex = 0;

            images.eq(currentIndex).css({
                "z-index": 3
            });

            if (j.autoGenerate) {
                jSlider.action.autoGenerate();
                if (j.stopStartClass.length > 0) {
                    $(j.stopStartClass).empty().text(j.text.Stop).attr('rel', 'stop');
                }
            } else {
                if (j.bulletClass.length > 0) {
                    jSlider.action.bulletRendering();
                }

                if (j.navClass.length > 0) {
                    jSlider.action.navRendering();
                }

                if (j.bulletClass.lenght == 0 && j.navClass.length == 0) {
                    jSlider.action.customRendering();
                }
            }

            if (j.autoPlay) jSlider.autoPlay(j.autoPlay);

            if (j.title) jSlider.action.setTitle(images.eq(0).attr('alt'));

        };

        jSlider.init();

        var bulletClass = j.bulletClass;
        if (bulletClass.length > 0) {
            if (bulletClass.indexOf(',') != -1) {
                var bullet = bulletClass.split(',');
                for (var c = 0; c > bullet; c++) {
                    $(bullet[c]).find('.bullet a').live('click', function (e) {
                        if ($(this).attr('rel')) {
                            jSlider.clearTime();
                            jSlider.action.slides(parseInt($(this).attr('rel')), 'bullet');
                            if (!isStop) jSlider.autoPlay(j.autoPlay);
                            e.preventDefault();
                        }
                    });
                }
            } else {
                $(bulletClass).find('.bullet a').live('click', function (e) {
                    if ($(this).attr('rel')) {
                        jSlider.clearTime();
                        jSlider.action.slides(parseInt($(this).attr('rel')), 'bullet');
                        if (!isStop) jSlider.autoPlay(j.autoPlay);
                        e.preventDefault();
                    }
                });
            }
        };

        $(j.stopStartClass).live('click', function (e) {
            if ($(this).attr('rel') == 'stop') {
                jSlider.clearTime();
                $(this).attr('rel', 'start').empty().text(j.text.Start);
                isStop = true;
            } else {
                jSlider.autoPlay(j.autoPlay);
                $(this).attr('rel', 'stop').empty().text(j.text.Stop);
                isStop = false;
            }
        });


        $t.find(".bulletcontrol a").live("click", function (e) {
            if ($(this).attr('rel')) {
                jSlider.clearTime();
                jSlider.action.slides(parseInt($(this).attr('rel')), 'bullet');
                if (!isStop) jSlider.autoPlay(j.autoPlay);
                e.preventDefault();
            }
        });

        $t.find(".slidenext").live('click', function (e) {
            jSlider.clearTime();
            jSlider.action.slides(parseInt(currentIndex + 1), 'next');
            if (!isStop) jSlider.autoPlay(j.autoPlay);
            e.preventDefault();
        });

        $t.find(".slideprev").live('click', function (e) {
            jSlider.clearTime();
            jSlider.action.slides(parseInt(currentIndex - 1), 'prev');
            if (!isStop) jSlider.autoPlay(j.autoPlay);
            e.preventDefault();
        });

        $t.live('mouseover', function (e) {
            if (j.pauseOnHover) jSlider.clearTime();
            e.preventDefault();
        });

        $t.live('mouseout', function (e) {
            if (!isStop) jSlider.autoPlay(j.autoPlay);
            e.preventDefault();
        });

        $t.find('.hide a').live('click', function (e) {
            $t.find('.titlehide').animate({ "margin-top": 30 }, 800).hide();
            $t.find('.titleshow').animate({ "margin-top": 0 }, 800).show();
            e.preventDefault();
        });

        $t.find('.show a').live('click', function (e) {
            $t.find('.titleshow').animate({ "margin-top": 30 }, 800).hide();
            $t.find('.titlehide').animate({ "margin-top": 0 }, 800).show();
            e.preventDefault();
        });

        // Change option in runtime
        this.option = function (name, value) {
            // Multi-option method
            if (typeof name != "string") return $.each(name, function (key, value) {
                self.option(key, value);
            });
            // Readonly options
            if (name == 'type') return;
            // Get method
            if (value == null) return options[name];
            // Set method
            options[name] = value;
        };
    };


    // Extends jQuery (constructor method, collection)
    // this works only for the this instance
    $.fn.jSlider = function (_p1, _p2, collection) {
        return new jSliderObject(this.eq(0), _p1, _p2, collection);
    };

    // $.jSlider(selector, options, collection);
    // Extends jQuery (global method)
    $.jSlider = function (selector, options, collection) {
        return new jSliderObject($(selector), null, options, collection);
    };


    $.jSlider['base'] = function (keyName, value) {
        if (value == null) return global['base'][keyName];
        global['base'][keyName] = value;
    };

    // allow users to add custom effect plugins
    $.jSlider.plugin = new function () {
        var plugins = [];

        // add plugins to list
        this.add = function (name) {
            plugins[plugins.length] = name;
        };

        // get plugins list
        this.getPlugins = plugins;

        // effect base
        this.effect = new function () {

            var effectName = [];

            this.afterCheck = function (images, nextIndex, prevIndex) {
                for (var c = 0; c < images.size(); c++) {
                    if (prevIndex == c || nextIndex == c) { }
                    else images.eq(c).removeClass().removeAttr('style');
                }
            };

            this.add = function (name, func) {
                effectName[effectName.length] = name;
                this[effectName] = func;
            };

            this.getEffects = effectName;
            this.findEffect = function (obj) {
                return jQuery.inArray(obj, effectName);
            };
        };
    };
    
    
    // Prepare default of jSlider
    // Default configuration
    $.jSlider.base('default', {
        effect: 'fade',
        time: 1000,
        speed: 800,
        autoPlay: true,
        autoGenerate: true,
        title: true,
        pauseOnHover: true,
        text: {
            Prev: 'Previous',
            Next: 'Next',
            Hide: 'Hide',
            Show: 'Show',
            Start: 'Start',
            Stop: 'Stop'
        },
        stopStartClass: '.stopstart',
        hide: '',
        callback: false,
        bulletClass: '.bulletsquare',
        navClass: '',
        customRendering: {
            upLine: '%prev %next',
            bottomLine: '%bullet'
        }
    });
})(jQuery);
