/*
 * This plugin is developed by Roy Yu as a part of his hobby projects.  Feel free to use or modify it as any way as you like.
 * This plugin will do
 *  - run slideshow with generated navigator based on your data, please see the dummy html for detail
 */

(function($) {
    // the each loop in plugin will create this instance
    var instance = function(el, options) {
        this.opts = options;
        return this;
    };
    // instance scope functions
    $.extend(instance.prototype, {
        init:function() {
            $(this.opts.iHolder).hide();  
        }
    });

    // jquery plugin definition
    $.fn.SlideShow = function(options, callback) {
        /* --- define variables
         * @param counter: keep track of position of the showing image ( for slideshow ), if last go back to first
         * @param timer
         * @param params - user provided options plus defult options
         */
        var params = $.extend({slideShowLink:'slideShowLink',runSlideLink:'runSlideLink',counter:0},$.fn.SlideShow.default_options,options);

        var runner, timer, total = $(params.iHolder).size(),
            $firstChild = $(params.iHolder + ':nth-child(1)'), $tmpChild = $firstChild.next();

        // check if user pass in callback as 1st param
        if($.isFunction(options)) {
            callback = options;
            options = null;
        }

        // methods for this plugin - not neccessary to wrap that, just for "fancy" purpose
        var methods = {
            init: function() {
                // real time create links
                for(var start=1;start<=total;start+=1) {
                    $("<a></a>",{id:start,href:'#','class':params.slideShowLink,text:start}).appendTo(params.imgNavigator);
                }
                // create link for slideshow to run again
                $("<a></a>",{href:'#','class':params.runSlideLink,text:params.runSlideLinkText}).appendTo(params.imgNavigator).hide();

                // what to do when navigator is clicked
                $("a."+params.slideShowLink).click(function() {
                    $(params.iHolder).hide();
					var $node = $(params.iHolder + ':nth-child('+$(this).attr('id')+')');
                    $node.show();
					$(params.imgFlashTextHolder).html(methods.getImgText.apply(this,[$node])).hide().show();
                });
                // slide show stop when you click the number
                $(params.imgNavigator).children().each(function(){				
                    $(this).bind('click',function(e){
						e.preventDefault();
						$(params.imgNavigator).children().removeClass('selected');
                        window.clearInterval(timer);
                        $("a."+params.runSlideLink).fadeIn('slow');
						$(this).addClass('selected');
                    });
                });
                // reenable the slideshow
                $("a."+params.runSlideLink).click(function() {
                    timer = window.setInterval(function(){methods.runner.apply(this,[]);}, params.iFlashSpeed);
                    $(this).hide();
                });
            },
            // run the slide show
            runner: function(firstrun) {
                // stop if it meet the condition				
                if(params.iRunTotal != 0 && params.counter > params.iRunTotal) {
                    window.clearInterval(timer);
					params.counter = 0;
                } else {
                    // if the next element string has 0 length
                    if($tmpChild.length <= 0) {
                        $tmpChild = $firstChild;
                        params.counter++;
                    }
					
					if(firstrun) {						
						$tmpChild = $firstChild;
					} 
					
					$(params.imgNavigator).children().removeClass('selected');			
					var $indicator = $tmpChild.index() + 1;		
					$(params.imgNavigator + ' a#' + $indicator).addClass('selected');
					
                    $(params.iHolder).hide();
                    $tmpChild.show();
                    $(params.imgFlashTextHolder).html(methods.getImgText.apply(this,[$tmpChild])).hide().show();
                    $tmpChild = $tmpChild.next();
                }
            },
            // only for getting image contents
            getImgText:function(node) {
                return '<h4>'+node.attr(params.imgTitle) + '</h4><br />' + node.attr(params.imgCaption);
            }
        };
        // initialize the plugin
        methods.init.apply(this,[]);
        // call user setup callback
        $.isFunction(callback) && callback.call(this);
        
        this.each(function() {
           // create an individual instance for each item
           new instance(this,params).init({total:total});
        });
		
		methods.runner.apply(this,[true]);

        timer = window.setInterval(function(){methods.runner.apply(this,[]);}, params.iFlashSpeed);
    };

    /* //----- default parameter
       * imgHolder     - element that holds the data
       * imgFlashHolder - element you want the flash message shows
       * iRunTotal    - how many times you want the flash messages run
       * iFlashSpeed  - speed for the flash in ms
       * imgFlashTextHolder - Title holder for the image // please see example
       * imgTitle - name of the title attribute of the image
       * imgCaption - name of the caption attribute of the image
       * imgNavigator - navigation for the slideshow
       * runSlideLinkText - the text value for the link for slideshow
    */
    $.fn.SlideShow.default_options = {
        iRunTotal:0, iFlashSpeed:5000, iHolder:'#img img',imgTitle:'title',
        imgCaption:'data-caption',imgNavigator:'.flash-nav', runSlideLinkText:'SlideShow',
        imgFlashTextHolder:'.flash-text'
    };

})(jQuery);

// This is how your run this slideshow
$(document).ready(function() {
    $('#img img').SlideShow({});
});
