/*global window: false */
/*global document: false */
/*global jQuery: false */

(function ($) {
    // selfinvoking annonimous function

    $.featureShow = function (el, options) {
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;

        // Access to jQuery and DOM versions of element
        base.$wrapper = $(el);
        base.wrapper = el;

        // Set up a few defaults
        base.currentPage = -1;
        base.timer = null;
        base.playing = false;
        base.busy = false;
        base.imgSrcs = [];
        base.imgLoaded = 0;
        base.errorTimer = null;

        // Add a reverse reference to the DOM object
        base.$wrapper.data("AnythingSlider", base).removeClass('js_disabled');

        base.init = function () {
            base.options = $.extend({},
            $.featureShow.defaults, options);

            // setup the HTML required for the plugin
            base.setupHTML();

            // If pauseOnHover then add hover effects
            if (base.options.pauseOnHover) {
                base.$wrapper.hover(function () {
                    if (base.timer) {
                        window.clearInterval(base.timer);
                    }
                },
                function () {
                    base.startStop(base.playing);
                });
            }

            // enable clickability of features
            base.$captionsCtr.click(function (e) {
                this.blur();
                // get the current feature:
                document.location = $(base.$features[base.currentPage]).attr('href');
                e.preventDefault();
            });

            base.captionsInit();
            base.preload();
        };
        // end of base.init
        base.setupHTML = function () {
            // get the current list of elements and remove it from the DOM
            var $ul = base.$wrapper.find('> ul').remove(),
            $li = $ul.children(),
            $div = $('<div></div>');

            // create the new container elements so they can be populated
            base.$featuresCtr = $('<div class="features"></div>');
            base.$captionsCtr = $('<ul class="captions"></ul>').css({
                'z-index': 3
            });
            base.$thumbsCtr = $('<ul class="featureNav"></ul>');

            $li.each(function (index) {
                var $this = $(this),
                className = $this.attr('className'),
                $img = $this.find('> img'),
                imgSrc = $img.attr('src'),
                shrtDescr = $img.attr('alt'),
                thumbSrc,
                $a = $this.find('a'),
                title = $a.text(),
                link = $a.attr('href'),
                $p = $this.find('p'),
                longDescr = $p.html(),
                $feature = $('<a></a>'),
                $caption = $('<li></li>'),
                $captionTxt = $('<div class="captionTxt"></div>'),
                $thumb = $('<li></li>'),
                $t_a = $('<a></a>'),
                $t_img = $('<img/>');

                base.imgSrcs[base.imgSrcs.length] = imgSrc;

                if (typeof(base.options.thumbsFormatter) === "function") {
                    thumbSrc = base.options.thumbsFormatter(imgSrc);
                    base.imgSrcs[base.imgSrcs.length] = thumbSrc;
                } else {
                    thumbSrc = imgSrc;
                }

                // create the feature and append it to the div
                $feature.attr('href', link);
                $feature.css('background-image', 'url(' + imgSrc + ')');
                $div.append($feature);

                // create the caption and append it to base.$captionsCtr
                $caption.attr('className', className);
                $caption.append('<div class="captionBg"></div>');

                $captionTxt.append('<h5>' + title + '</h5>');
                $captionTxt.append('<p>' + longDescr + '</p>');
                $caption.append($captionTxt);
                base.$captionsCtr.append($caption);

                // create the thumbs and append them
                $t_a.attr('href', '#');
                $t_a.attr('title', shrtDescr);
                $t_img.attr('src', thumbSrc);
                $t_img.attr('alt', shrtDescr);
                $t_a.append($t_img);
                $thumb.append($t_a);
                base.$thumbsCtr.append($thumb);
            });

            base.$featuresCtr.append($div);
            base.$wrapper.append(base.$featuresCtr);
            base.$wrapper.append(base.$captionsCtr);
            base.$wrapper.append(base.$thumbsCtr);
            base.$features = base.$featuresCtr.find('> div a').css({
                'z-index': 0,
                'display': 'none'
            });
            base.$captions = base.$captionsCtr.find('> li');
            base.$captionTxts = base.$captions.find('> div.captionTxt');
            base.$captionBgs = base.$captions.find('> div.captionBg')
            .css({
                opacity: base.options.captionOpacity
            });
            base.$thumbs = base.$thumbsCtr.find('> li');
            base.$thumbImgs = base.$thumbs.find('img');

            // Get the details
            base.singleWidth = base.$captionsCtr.outerWidth();
            base.singleHeight = base.$captionsCtr.outerHeight();

        };
        // end of base.setupHTML
        base.preload = function () {
            if (base.imgSrcs && base.imgSrcs.length && base.imgSrcs[base.imgLoaded]) {
                var img = new Image();
                //new img obj
                img.src = base.imgSrcs[base.imgLoaded];
                //set src either absolute or rel to css dir
                if (!img.complete) {
                    jQuery(img).bind('error load onreadystatechange', base.onImgComplete);
                } else {
                    base.onImgComplete();
                }
                base.errorTimer = setTimeout(base.onImgComplete, base.options.errorDelay);
                // handles 404-Errors in IE
            } else if (base.imgSrcs && base.imgSrcs.length) {
                base.featuresInit();
                base.navigationInit();
            }
        };

        base.onImgComplete = function () {
            clearTimeout(base.errorTimer);
            if (base.imgSrcs && base.imgSrcs.length && base.imgSrcs[base.imgLoaded]) {
                base.imgLoaded = base.imgLoaded + 1;
                base.preload();
            }
        };

        // end of base.preload
        base.featuresInit = function () {
            base.totalPages = base.$features.length;
            base.currentPage = 0;
            base.$features.eq(base.currentPage).css({
                'z-index': 2,
                'opacity': 0,
                'display': 'block'
            }).animate(
            {
                opacity: 1
            },
            base.options.slideTransitionSpeed,
            base.options.slideTransitionEasing,
            function () {
                if ($.browser.msie) {
                    this.style.removeAttribute('filter');
                }

                base.$features.css({
                    'display': 'block'
                });
                base.showCaption();
                base.startStop(true);
            }
            );
        };
        // end of base.featuresInit
        base.showFeature = function (index, callback) {
            var $next = base.$features.eq(index).css({
                'z-index': 1
            }),
            $current;

            base.updateNavigation(index);

            //fade the top item out, revealing the next item
            $current = base.$features.eq(base.currentPage);
            $current.animate(
            {
                opacity: 0,
                left: 100
            },
            base.options.slideTransitionSpeed,
            base.options.slideTransitionEasing,
            function () {
                if ($.browser.msie) {
                    this.style.removeAttribute('filter');
                }
                $current.css({
                    'z-index': 0,
                    'opacity': 1,
                    'left': 0
                });
                $next.css({
                    'z-index': 2
                });
                base.currentPage = index;
                if (callback) {
                    callback();
                }
            });
        };
        // end of base.showFeature
        base.captionsInit = function () {
            // Hide the captions
            base.$captionsCtr.find('> li.caption_top').css({
                width: base.singleWidt
            }).each(
            function () {
                var $this = $(this);
                $this.css({
                    top: -$this.outerHeight(),
                    opacity: 0
                });
            }
            );
            base.$captionsCtr.find('> li.caption_bottom').css({
                width: base.singleWidt
            }).each(
            function () {
                $(this).css({
                    top: base.singleHeight,
                    opacity: 0
                });
            }
            );
            base.$captionsCtr.find('> li.caption_left').css({
                width: base.options.captionWidth
            }).each(
            function () {
                var $this = $(this);
                $this.css({
                    left: -$this.outerWidth(),
                    opacity: 0
                });
            }
            );
            base.$captionsCtr.find('> li.caption_right').css({
                width: base.options.captionWidth
            }).each(
            function () {
                $(this).css({
                    left: base.singleWidth,
                    opacity: 0
                });
            }
            );
            base.$captionsCtr.css({
                display: 'block'
            });
        };
        // end of captionsInit
        base.hideCaption = function (callback) {
            var $caption = $(base.$captions[base.currentPage]),
            className = $caption.attr('className');
            switch (className) {
            case "caption_top":
                if ($.browser.msie) {
                    $caption.animate({
                        top:
                        -$caption.outerHeight()
                    },
                    base.options.captionTransitionOutSpeed, base.options.captionTransitionEasing, callback);
                } else {
                    $caption.animate({
                        top: -$caption.outerHeight(),
                        opacity: 0
                    },
                    base.options.captionTransitionOutSpeed, base.options.captionTransitionEasing, callback);
                }
                break;
            case "caption_bottom":
                if ($.browser.msie) {
                    $caption.animate({
                        top:
                        base.singleHeight
                    },
                    base.options.captionTransitionOutSpeed, base.options.captionTransitionEasing, callback);
                } else {
                    $caption.animate({
                        top: base.singleHeight,
                        opacity: 0
                    },
                    base.options.captionTransitionOutSpeed, base.options.captionTransitionEasing, callback);
                }
                break;
            case "caption_left":
                if ($.browser.msie) {
                    $caption.animate({
                        left:
                        -$caption.outerWidth()
                    },
                    base.options.captionTransitionOutSpeed, base.options.captionTransitionEasing, callback);
                } else {
                    $caption.animate({
                        left: -$caption.outerWidth(),
                        opacity: 0
                    },
                    base.options.captionTransitionOutSpeed, base.options.captionTransitionEasing, callback);
                }
                break;
            case "caption_right":
                if ($.browser.msie) {
                    $caption.animate({
                        left:
                        base.singleWidth
                    },
                    base.options.captionTransitionOutSpeed, base.options.captionTransitionEasing, callback);
                } else {
                    $caption.animate({
                        left: base.singleWidth,
                        opacity: 0
                    },
                    base.options.captionTransitionOutSpeed, base.options.captionTransitionEasing, callback);
                }
                break;
            }
        };
        // end of base.hideCaption
        base.showCaption = function (callback) {
            var $caption = $(base.$captions[base.currentPage]),
            $captionTxt = $(base.$captionTxts[base.currentPage]),
            className = $caption.attr('className');
            if (!$.browser.msie) {
                $captionTxt.css({
                    left: 100,
                    opacity: 0
                });
            }
            switch (className) {
            case "caption_top":
                if ($.browser.msie) {
                    $caption.animate({
                        top:
                        0
                    },
                    base.options.captionTransitionInSpeed, base.options.captionTransitionEasing, callback);
                } else {
                    $caption.animate({
                        top: 0,
                        opacity: 1
                    },
                    base.options.captionTransitionInSpeed, base.options.captionTransitionEasing,
                    function () {
                        $captionTxt.animate(
                        {
                            left: 0,
                            opacity: 1
                        },
                        base.options.captionTransitionInSpeed,
                        base.options.captionTransitionEasing,
                        callback
                        );
                    }
                    );
                }
                break;
            case "caption_bottom":
                if ($.browser.msie) {
                    $caption.animate({
                        top:
                        base.singleHeight - $caption.outerHeight()
                    },
                    base.options.captionTransitionInSpeed, base.options.captionTransitionEasing, callback);
                } else {
                    $caption.animate({
                        top: base.singleHeight - $caption.outerHeight(),
                        opacity: 1
                    },
                    base.options.captionTransitionInSpeed, base.options.captionTransitionEasing,
                    function () {
                        $captionTxt.animate(
                        {
                            left: 0,
                            opacity: 1
                        },
                        base.options.captionTransitionInSpeed,
                        base.options.captionTransitionEasing,
                        callback
                        );
                    }
                    );
                }
                break;
            case "caption_left":
                if ($.browser.msie) {
                    $caption.animate({
                        left:
                        0
                    },
                    base.options.captionTransitionInSpeed, base.options.captionTransitionEasing, callback);
                } else {
                    $caption.animate({
                        left: 0,
                        opacity: 1
                    },
                    base.options.captionTransitionInSpeed, base.options.captionTransitionEasing,
                    function () {
                        $captionTxt.animate(
                        {
                            left: 0,
                            opacity: 1
                        },
                        base.options.captionTransitionInSpeed,
                        base.options.captionTransitionEasing,
                        callback
                        );
                    }
                    );
                }
                break;
            case "caption_right":
                if ($.browser.msie) {
                    $caption.animate({
                        left:
                        base.singleWidth - $caption.outerWidth()
                    },
                    base.options.captionTransitionInSpeed, base.options.captionTransitionEasing, callback);
                } else {
                    $caption.animate({
                        left: base.singleWidth - $caption.outerWidth(),
                        opacity: 1
                    },
                    base.options.captionTransitionInSpeed, base.options.captionTransitionEasing,
                    function () {
                        $captionTxt.animate(
                        {
                            left: 0,
                            opacity: 1
                        },
                        base.options.captionTransitionInSpeed,
                        base.options.captionTransitionEasing,
                        callback
                        );
                    }
                    );
                }
                break;
            }
        };
        // end of base.hideCaption
        base.navigationInit = function () {
            base.$thumbImgs.css({
                opacity: base.options.thumbOpacity
            });
            var $a = base.$thumbsCtr.find('a');
            $a.each(function (i) {
                $(this).click(function (e) {
                    this.blur();
                    base.gotoPage(i);
                    e.preventDefault();
                });
            });

            base.$thumbsCtr.css({
                opacity: 0,
                display: 'block'
            }).animate(
            {
                opacity: 1
            },
            base.options.slideTransitionSpeed,
            base.options.slideTransitionEasing,
            function () {
                if ($.browser.msie) {
                    this.style.removeAttribute('filter');
                }
            }
            );
            base.updateNavigation(0);
        };
        // end of base.navigationInit
        base.updateNavigation = function (index) {
            $(base.$thumbs[base.currentPage]).removeClass('active');
            $(base.$thumbImgs[base.currentPage]).animate(
            {
                opacity: base.options.thumbOpacity
            },
            base.options.slideTransitionSpeed,
            base.options.slideTransitionEasing
            );
            $(base.$thumbImgs[index]).animate(
            {
                opacity: 1
            },
            base.options.slideTransitionSpeed,
            base.options.slideTransitionEasing,
            function () {
                if ($.browser.msie) {
                    this.style.removeAttribute('filter');
                }
                $(base.$thumbs[index]).addClass('active');
            }
            );
        };
        // end of base.updateNavigation
        base.gotoPage = function (page, autoplay) {
            // When autoplay isn't passed, we stop the timer
            //			if (autoplay !== true) autoplay = false;
            //			if (!autoplay) base.startStop(false);
            if (typeof(page) === "undefined" || page === null) {
                page = 1;
                //				base.setCurrentPage(1);
            }

            // Just check for bounds
            if (page >= base.totalPages) {
                page = base.totalPages - 1;
            }
            if (page < 0) {
                page = 0;
            }

            base.hideCaption(function () {
                base.showFeature(page, base.showCaption);
            });
        };
        // end of base.gotoPage
        base.goForward = function () {
            if (base.currentPage === base.totalPages - 1) {
                base.gotoPage(0);
            } else {
                base.gotoPage(base.currentPage + 1);
            }
        };

        base.startStop = function (playing) {
            if (playing !== true) {
                playing = false;
            }
            // Default if not supplied is false
            // Update variable
            base.playing = playing;

            // Toggle playing and text
            //			if (base.options.autoPlay) base.$startStop.toggleClass("playing", playing).html( playing ? base.options.stopText : base.options.startText );
            if (playing) {
                if (base.timer) {
                    window.clearInterval(base.timer);
                }
                base.timer = window.setInterval(function () {
                    base.goForward(true);
                },
                base.options.delay);
            } else {
                if (base.timer) {
                    window.clearInterval(base.timer);
                }
            }
        };
        // end of base.startStop
        base.init();
    };
    // end of $.featureShow()
    $.featureShow.defaults = {
        slideTransition: 'fade',
        slideTransitionSpeed: 1200,
        slideTransitionEasing: 'swing',
        captionTransition: 'fade',
        captionTransitionInSpeed: 'slow',
        captionTransitionOutSpeed: 'slow',
        captionTransitionEasing: 'swing',
        captionOpacity: 0.6,
        captionWidth: 250,
        thumbOpacity: 0.35,
        thumbsFormatter: null,
        delay: 7000,
        pauseOnHover: true,
        errorDelay: 999
    };
    // end of defaults
    $.featureShow.defaults.thumbsFormatter = function (src) {
        return 'http://www.related-platform.nl/wp-content/plugins/wp-feature-show/includes/timthumb/timthumb.php?src=' + src + '&h=100&w=100&zc=1"';
    };

    $.fn.featureShow = function (options) {
        if (!options) {
            return this.each(function (i) {
                (new $.featureShow(this, {}));
            });
        } else if (typeof(options) === "object") {
            return this.each(function (i) {
                (new $.featureShow(this, options));
            });
        } else if (typeof(options) === "number") {
            return this.each(function (i) {
                var featureShow = $(this).data('featureShow');
                if (featureShow) {
                    featureShow.gotoPage(options);
                }
            });
        }
    };
    // end of $.fn.featureShow
    
    $(document).ready(function() {
	  $('.featureShow').featureShow();
	});
}(jQuery));