﻿BF.tabSwitcher = function (contentWrap, triggers, targets, options) {

    this.options = $.extend({
        activeClass: 'active', 	// class to use for active trigger
        index: 0, 				// index of tab to start on
        fadeSpeed: 300, 		// speed of content fade between tabs, set to 0 for no fade
        fixedHeight: true		// boolean whether or not to calculate and set fixed height for tabs (keeps layout from shifting around when switching between tabs)
    }, options || {});

    var self = this;

    // instance variables
    self.contentWrap = contentWrap;
    self.triggers = triggers;
    self.targets = targets;
    self.index = self.options.index;
    self.newIndex = null;


    // setup
    self.setup();

    // events
    self.triggers.click(function (e) {
        e.preventDefault();
        //self.newIndex = $(this).index();
        self.newIndex = self.triggers.index(this);
        self.switchTab();
    });
};
BF.tabSwitcher.prototype = {

	// hide all tabs except chosen index, size contentWrap to keep layout during transitions
	setup: function () {
		var self = this;
		var maxContentHeight = 0;

		if (self.options.fixedHeight === true) {
			self.targets.each(function () {
				var currentContentHeight = $(this).outerHeight();
				if (currentContentHeight > maxContentHeight) {
					maxContentHeight = currentContentHeight;
				}
			});
			self.contentWrap.height(maxContentHeight);
		}

		self.targets.hide();
		self.triggers.eq(self.index).addClass(self.options.activeClass);
		self.targets.eq(self.index).show();
	},

	// switch to new tab on click
	switchTab: function () {
		var self = this;
		self.triggers.eq(self.index).removeClass(self.options.activeClass);
		self.targets.eq(self.index).removeClass(self.options.activeClass).hide(self.options.fadeSpeed);
		self.triggers.eq(self.newIndex).addClass(self.options.activeClass);
		self.targets.eq(self.newIndex).addClass(self.options.activeClass).fadeIn(self.options.fadeSpeed);
		self.index = self.newIndex;
	}
};
