var miscSlider;
var homeSlider;
var toggleLinks;

function HorizontalSliderArrow(options){
    // Defaults
   
    this.sliderContainer = jQuery(options.container);
    this.slides = this.sliderContainer.find(options.slides);
    
    this.prevArrow = jQuery(options.arrow_left);
    this.nextArrow = jQuery(options.arrow_right);
    
    this.speed = (options.speed ? options.speed : 1000);
    this.nestedEls = (options.nested ? options.nested : 1);
    this.easing = (options.easing ? options.easing : "easeOutQuad");
    this.auto = (options.auto ? options.auto : false);
	
	
    if(options.indicator_container){
        this.indicatorContainer = jQuery(options.indicator_container);
        this.indicators = this.indicatorContainer.find(options.indicators);
        this.hasIndicator = true;
    }else{
        this.hasIndicator = false;
    }
    
    if(options.labels && options.labels.length === this.slides.length){
        this.labels = options.labels;
        this.labelContainer = jQuery(options.label_container);
        this.labelText = (options.label_text ? options.label_text : "%title%");
        this.hasLabel = true;
    }else{
        this.hasLabel = false;
    }
    // End Defaults
    
	this.deactivated = {
		left: false,
		right: false
	}
    this.autoOrient = "right";
	
    this.init();
}

HorizontalSliderArrow.prototype = {
    init:function(){
        
        if(this.slides.length > this.nestedEls){
            var self = this;
			var autoId;
			
			if(this.auto){
				
				autoId = setInterval(function(){
					self.triggerClickAuto();
				}, 5000);
			}
			
            this.curSlide = this.slides.eq(0);
            
            this.prevArrow.bind("click", function(e){
				
                self.movePrev.call(self,e);
				if(self.auto && e.originalEvent) clearInterval(autoId);
            });
            this.nextArrow.bind("click", function(e){
                self.moveNext.call(self,e);
				if(self.auto && e.originalEvent) clearInterval(autoId);
            });
            
			this.slides.bind("mouseover",function(e){
				if(self.auto && e.originalEvent) clearInterval(autoId);
			});
			
            if(this.hasIndicator){
                this.indicators.bind("click",function(e){
                    self.moveToIndex.call(self, e);
					if(self.auto && e.originalEvent) clearInterval(autoId);
                });
            }
            this.toMoveX = this.calcToMove();
            var maxToMove = Math.ceil(this.slides.length / this.nestedEls) - 1;
            this.maxX = -maxToMove * this.toMoveX;

			
        }else{
            this.deactivateArrow("both");
        }
    },
    
    calcToMove:function(){
        var totalWidth = parseInt(this.curSlide.width()) + parseInt(this.curSlide.css("margin-right")) +
                                                                    parseInt(this.curSlide.css("margin-left")) + parseInt(this.curSlide.css("padding-right")) +
                                                                                                                         parseInt(this.curSlide.css("padding-left"));
        return totalWidth * this.nestedEls;
        
    },
    movePrev:function(e){
            var xVal = this.getCurX() - this.toMoveX;
            
            var self = this;
            var slidePrev = (-xVal > 0) ? false : true;
            var prevSlideInd = this.getCurIndex() - this.nestedEls;
            var disablePrev = (-(xVal - this.toMoveX) > 0) ? true : false;
            
            if(slidePrev){
                this.sliderContainer.animate({
                    left:-xVal
                }, {duration:this.speed, easing:this.easing, complete:function(){
                    self.setActive(prevSlideInd);
                    self.manageArrows.call(self, prevSlideInd);
                    }
                });
            }
            
          
            e.preventDefault();
    },
    
    moveNext:function(e){

            var xVal = this.getCurX() + this.toMoveX;
            
            var self = this;
            var slideNext = (-xVal < this.maxX) ? false : true;
            var nextSlideInd =  this.getCurIndex() + this.nestedEls;
            var disableNext = (-(xVal + this.toMoveX) < this.maxX) ? true : false;
            //console.log(nextSlideInd);
            
            if(slideNext){
                
                this.sliderContainer.animate({
                    left:-xVal
                }, {duration:this.speed, easing:this.easing, complete: function(){
                    self.setActive(nextSlideInd);
					self.manageArrows.call(self, nextSlideInd);
                    }
                });
                
            }
            
            
            e.preventDefault();
    },
    
    moveToIndex:function(e){
        var xVal, i = this.indicators.index(e.target);
        var self = this;
        if(i != -1){
            xVal = i * (this.toMoveX / this.nestedEls);
            this.sliderContainer.animate({
               left:-xVal
            }, {duration: this.speed, easing:this.easing, complete: function(){
                self.setActive(i);
                self.manageArrows.call(self, i);
                }
            });
        }
        e.preventDefault();
        
        
    },
    
    setActive:function(ind){
        this.curSlide = this.slides.eq(ind);
        
        if(this.hasIndicator){
            this.indicators.removeClass("active");
            this.indicators.eq((ind / this.nestedEls)).addClass("active");
        }
        
        if(this.hasLabel){
            this.setLabel((ind / this.nestedEls));
        }
    },
    
	manageArrows:function(i){
		if(i === 0){
            this.deactivateArrow("prev");
            this.activateArrow("next");
        }else if(i >= this.slides.length - 1){
            this.deactivateArrow("next");
            this.activateArrow("prev");
        }else if(i != 0  && i < this.slides.length - 1){
			this.activateArrow("next");
			this.activateArrow("prev");
		}else{
			this.deactivateArrow("next");
			this.deactivateArrow("prev");
		}
	},
    setLabel:function(ind){
        var finalLabel = this.labelText;
        var curLabel = this.labels[ind];
        if(curLabel){
            finalLabel = finalLabel.replace(/%title%/gi, curLabel);
            finalLabel = finalLabel.replace(/%cur%/gi, ind+1);
            finalLabel = finalLabel.replace(/%total%/gi, this.slides.length);
            
            this.labelContainer.html(finalLabel);
        }
    },
    
    getCurIndex:function(){
        var i = this.slides.index(this.curSlide);
        return i;
    },
    
    getCurX:function(){
        return this.getCurIndex()  * (this.toMoveX / this.nestedEls);
    },

    
    deactivateArrow:function(arrow){
        
        switch(arrow){
            case "both":
                this.prevArrow.addClass("active").css("cursor","default");
                this.nextArrow.addClass("active").css("cursor","default");
                this.deactivated.left = this.deactivated.right = true;
                break;
            case "prev":
                this.prevArrow.addClass("active").css("cursor","default");
				this.deactivated.left = true;
				this.deactivated.right = false;
                break;
            case "next":
                this.nextArrow.addClass("active").css("cursor","default");
				this.deactivated.left = false;
				this.deactivated.right = true;
        }
    },
    activateArrow:function(arrow){
        
        switch(arrow){
            case "both":
                this.prevArrow.removeClass("active").css("cursor","pointer");
                this.nextArrow.removeClass("active").css("cursor","pointer");
                break;
            case "prev":
                this.prevArrow.removeClass("active").css("cursor","pointer");
                break;
            case "next":
                this.nextArrow.removeClass("active").css("cursor","pointer");
        }
    },
	triggerClickAuto:function(){
		if(this.autoOrient == "right"){
			if(!this.deactivated.right){
				this.nextArrow.trigger("click");
			}else{
				this.autoOrient = "left";
				this.prevArrow.trigger("click");
			}
		}else{
			if(!this.deactivated.left){
				this.prevArrow.trigger("click");
			}else{
				this.autoOrient = "right";
				this.nextArrow.trigger("click");
			}
		}
		
	}
}



function ToggleVisibility(options){
    this.toggleParentSel = jQuery(options.toggleParentSel);
    this.toggleChildrenSel = this.toggleParentSel.find(options.toggleChildrenSel);
    this.toggleEls = jQuery(options.toggleEls);
    this.jScrollPane = (options.jScrollPane ? true : false);
    this.togglePaneVisibility = (this.jScrollPane && options.togglePaneVisibility ? true : false);
    
    this.canStopPane =  true;
    this.init();

}

ToggleVisibility.prototype = {
    init:function(){
        var self = this;
        this.toggleChildrenSel.bind("click",function(e){
            self.toggle.call(self, e);
        });
        
        this.toggleChildrenSel.eq(0).trigger("click");
    },
    toggle:function(e){
        var i, self = this, _this = e.target;

        i = this.toggleChildrenSel.index(_this);
        this.toggleChildrenSel.removeClass("active");
        this.toggleChildrenSel.eq(i).addClass("active");
        this.toggleEls.addClass("hidden");
        this.toggleEls.eq(i).removeClass("hidden");
        var pane;
        if(this.jScrollPane){
            pane = this.toggleEls.eq(i).jScrollPane();
            if(this.togglePaneVisibility){
                   this.detectStopDrag(pane);
                   pane.find(".jspVerticalBar").css("display","none");
                   pane.hover(function(){
                        self.endedHover = false;
                        jQuery(this).find(".jspVerticalBar").css("display","block");
                   },function(){
                        self.endedHover = true;
                        if(self.canStopPane){
                            jQuery(this).find(".jspVerticalBar").css("display","none");
                        }
                   })
                   
            }
        }
     
        e.preventDefault();
         
    },
    detectStopDrag:function(jtarget){
        var self = this;
        var api = jtarget.jScrollPane().bind(
            'jsp-scroll-y',
            function(event, scrollPositionY, isAtBottom, isAtTop)
            {
                self.canStopPane = false;
                jQuery(document)
                    .unbind('mouseup.jsp-demo')
                    .bind(
                        'mouseup.jsp-demo',
                        function()
                        {
                            jQuery(document).unbind('mouseup.jsp-demo');
                            self.canStopPane = true;
                            if(self.endedHover){
                                jtarget.find(".jspVerticalBar").hide();
                                self.endedHover = false;
                            }
                        }
                    )
            }
        ).data('jsp');
    }
}


jQuery(document).ready(function(){
    
    miscSlider = new HorizontalSliderArrow({
        container:"#slider-misc-1",
        slides: ".cols",
        arrow_left: "a.left",
        arrow_right: "a.right",
        speed: 800,
        nested: 2
    });
    

    
    homeSlider = new HorizontalSliderArrow({
        container:"#banner-container",
        slides: ".banner",
        arrow_left: "a#left-a",
        arrow_right: "a#right-a",
        speed: 1000,
        nested: 1,
        indicator_container: "#banner-circles-sel",
        indicators: 'a',
        easing:"easeOutCubic",
        labels: ["FreeStyle Progress", "FreeStyle Optium", "FreeStyle InsuLinx system", "FreeStyle InsuLinx system - tutorial"],
        label_container: '#home-banner .label',
        label_text: "%cur%/%total% %title%",
		auto: true
    });
    
    newsPanel = new ToggleVisibility({
       toggleParentSel:"#misc-box .box-3",
       toggleChildrenSel:"h3 a",
       toggleEls:".pannel-toggle",
       jScrollPane:true,
       togglePaneVisibility:true
    });
	
	//FAQS
	if(jQuery("ol#accordion-container a.question").length){
		jQuery("ol#accordion-container li").each(function(){
	    	if(!jQuery(this).hasClass("active")) jQuery(this).find("span.answer").hide();
		});
		
		jQuery("ol#accordion-container a.question").bind("click",function(e){
			if(jQuery(this).parent("li").hasClass("active")){
				jQuery(this).siblings("span.answer").slideUp("slow",function(){
					jQuery(this).parent("li").removeClass("active");
				});
			}else{
				jQuery(this).parent("li").addClass("active");
				jQuery(this).siblings("span.answer").slideDown("slow");

			}
			e.preventDefault();
		});
	}
	

})
