(function(jQuery) {
 
	jQuery.fn.featureWidget = function(o)
	{	
	    if (!o) {
	        o = {};
	    }
		return this.each(function() {
			window[this.id+"FeatWidgtInst"] = new jQuery.featureWidget(this, o);
		});
	};
	
	jQuery.featureWidget = function (e, o)
	{  
	    this.cont                  =   e;
	    this.animating             =   0;
	    this.previewSlideDuration  =   400;
	    this.previewSlideEasing    =   "easeInOutQuad";
	    this.featSlideDuration     =   400;
	    this.featSlideEasing       =   "easeInOutQuad";
	    this.changeInterval        =   8000;
	    this.interactionTimeout    =   10;
	    this.disableAnimation      =   false;
	    this.currentIndex          =   0;
	    this.firstItemBtmMargin    =   10;
	    this.previewItemBtmMargin  =   4;
	    this.numItems              =   Number($(this.cont).find(".featEventPreview li a").length);
	    this.interactionTimer      =   null;
	    this.autoTimer             =   null;
		this.autoScroll			   =   true;
		
		// Disable auto scrolling in IE 6
		if ($.browser.msie && $.browser.version < 7) {
			this.autoScroll = false;
		}
		
		
		this.init();
	};
	
	jQuery.featureWidget.fn = jQuery.featureWidget.prototype;
	
 	jQuery.featureWidget.fn.extend = jQuery.featureWidget.extend = jQuery.extend;
	
	jQuery.featureWidget.fn.extend({
        init: function() {
            var self = this;
            
            $(this.cont).find(".featEventPreview li a").each(function(i){
                var matches = this.href.match(/showfeat\=(\d+)/);
                $(this).attr("prevIndex", matches[1]);
            }).click(function(){ return self.handleClick(this)});
            $(this.cont).hover(function(){
                self.stopAuto();
            },
            function(){
                self.interactionTimer = window.setTimeout(function(){self.startAuto()}, self.interactionTimeout);
            });
            
            
            // Set current index to the index of the selected link
            this.currentIndex = $(".featEventPreview li.selected a").attr('prevIndex');
            this.startAuto();
        },
        show: function(index) {
            if (!index) {
                index = 0;
            }
            this.scrollTo(index);
        },
        handleClick: function(obj) {
            if (this.animating) {
                return false;
            }
            this.show($(obj).attr("prevIndex"));
            return false;
        },
        scrollTo: function(index) {
        	index = parseInt(index);
            if (this.animating) {
                return false;
            }
            if (this.currentIndex == index) {
                return false;
            }
            var self = this;
            var numPlaces = this.distanceBetween(index);
            //console.log("current: "+this.currentIndex+" new: "+index+" places: "+numPlaces);
            var featHeight = $(".featEventWrapper").height();
            
            // recycle items that will dissappear off the top and create feature items that are new
            var beforeTarget = true;
            $(this.cont).find(".featEventPreview li a").each(function(i){
                if ($(this).attr("prevIndex") == index) {
                    beforeTarget = false;
                }
                if (beforeTarget) {
                    var tmp = $("<li></li>");
                    var newTop = ($(".featEventPreview li a:last").outerHeight()
                                    + self.previewItemBtmMargin
                                    + $(".featEventPreview li a:last").position().top);
                    tmp.append($(this).clone().css("top", newTop+"px").click(function(){ return self.handleClick(this)}));
                    $(".featEventPreview ul").append(tmp);
                }
                if (i > 0 && (beforeTarget || $(this).attr("prevIndex") == index)) {
                    var tmpHTML = window.jsTemplateStore.get("featEvent_"+$(this).attr("prevIndex")).html();
                    $(tmpHTML).css("top", (0-(featHeight * i))+"px").prependTo($(this.cont).find(".featEventContent"));
                }
            });
            
            // scroll items up
            $(this.cont).find(".featEventPreview li a").each(function(count){
                var dist = $(this).outerHeight() * numPlaces;
                // work out how many bottom margins each item needs to move by
                if (count < numPlaces) {
                    dist += self.firstItemBtmMargin * numPlaces;
                } else if (count == numPlaces) {
                    dist += self.firstItemBtmMargin;
                    dist += self.previewItemBtmMargin * (numPlaces - 1);
                } else {
                    dist += self.previewItemBtmMargin * numPlaces;
                }
                self.animating++;
                $(this).animate({top: ($(this).position().top - dist)+"px"}, 
                    self.previewSlideDuration + ((self.previewSlideDuration/numPlaces) * (numPlaces -1)), 
                    self.previewSlideEasing,
                    function(){
                        
                        if ($(this).position().top < 0) {
                            $(this).parent().remove();
                        } else if ($(this).parent().parent().find(".selected").length < 1) {
                            $(this).parent().addClass("selected");
                        }
                        self.animating--;
                });
            });
            
            // scroll featurse down
            $(this.cont).find(".featEventWrapper").each(function(){
                var dist = featHeight * numPlaces;
                //animate
                self.animating++;
                $(this).animate({top: ($(this).position().top + dist)+"px"}, 
                    self.featSlideDuration + ((self.previewSlideDuration/numPlaces) * (numPlaces -1)), 
                    self.featSlideEasing,
                    function(){
                        if ($(this).position().top >= featHeight) {
                            $(this).remove();
                        }
                        self.animating--;
                });
            });
            this.currentIndex = parseInt(index);
        },
        distanceBetween: function(to, from) {
            if (!from) {
                from = this.currentIndex;
            }
            to = Number(to);
            from = Number(from);
            if (to == from) {
                return 0;
            } else if (to > from) {
                return to - from;
            } else {
                return (to + this.numItems) - from ;
            }
        },
        startAuto: function() {
			if ( ! this.autoScroll) {
				return;
			}
            var self = this;
            this.stopAuto(); // Reset eveything first
            this.autoTimer = window.setInterval(function(){self.next()}, this.changeInterval);
        },
        stopAuto: function() {
            clearTimeout(this.autoTimer);
            clearTimeout(this.interactionTimer);
        },
        next: function() {
            if (this.animating) {
                return false;
            }
            var nextIndex = this.currentIndex + 1;
            nextIndex = (nextIndex >= this.numItems)? nextIndex - this.numItems : nextIndex;
            //console.log(this.currentIndex+" "+this.numItems+" "+nextIndex);
            this.show(nextIndex);
        }
    });
    
})(jQuery);