// jQuery Plugin SelectSwitcher
// A plugin to switch content visibility based on the selected option of a select 
// Version 0.2 - 9. 6. 2011
// by Fredi Bach

(function($) {

    $.selectSwitcher = function(element, options) {

        var defaults = {
			onChange: function() {},
			affectedElements: {},
			stateConfigs: {},
			defaultConfigs: [],
			speed: 'fast'
        }

        var plugin = this;
		
        plugin.settings = {}

        var $element = $(element),
             element = element;

		var first = true;
		
        plugin.init = function() {
            plugin.settings = $.extend({}, defaults, options);
			$element.change(function() {
				plugin.updateElements();
			});
			plugin.updateElements();
        }
		
		plugin.updateElements = function(){
			var state = $element.val();
			if (plugin.settings.stateConfigs[state] != undefined){
				var configs = plugin.settings.stateConfigs[state];
			} else {
				var configs = plugin.settings.defaultConfigs;
			}
			$.each(plugin.settings.affectedElements, function(index, value){
				if (configs.indexOf(index) == -1){
					if (first){
						$(value).hide();
					} else {
						$(value).slideUp(plugin.settings.speed);
					}
				} else {
					$(value).slideDown(plugin.settings.speed);
				}
			});
			if (first){
				first = false;
			}
        }

		plugin.init();

    }

    $.fn.selectSwitcher = function(options) {

        return this.each(function() {
            if (undefined == $(this).data('selectSwitcher')) {
                var plugin = new $.selectSwitcher(this, options);
                $(this).data('selectSwitcher', plugin);
            }
        });

    }

})(jQuery);

if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function(obj, start) {
	     for (var i = (start || 0), j = this.length; i < j; i++) {
	         if (this[i] === obj) { return i; }
	     }
	     return -1;
	}
}
