////
// Plugin - jquery.boxswitch.js
// @author BouchibaneAm
(function(){
	// Constructor
	(BoxSwitch = function(element, options) {
		this.elem = jQuery(element);
		// Merge options with default values
		this.settings = jQuery.extend({}, this.defaultValues, options || {});
		this.init();
	}).prototype = {
		defaultValues : {
			'openerClass' : 'BoxSwitchOpener',
			'openerTitle' : '',
			'shutterClass' : 'BoxSwitchShutter',
			'shutterTitle' : '',
			'contentClass' : 'BoxSwitchContent',
			'contentClosedClass' : 'BoxSwitchContentClosed',
			'ignoredClass': 'BoxSwitchIgnore'
		},
		elem : null,
		switcher : null,
		settings : {},

		init : function() {
			this.switcher = jQuery('.' + this.settings['openerClass'], this.elem);
			if(this.switcher.length <= 0) {
				this.switcher = jQuery('.' + this.settings['shutterClass'], this.elem);
			}
			this.switcher.on('mouseup', jQuery.proxy(this.toggleView, this));
			this.switcher.on('keyup', jQuery.proxy(this.toggleView, this));	// accessibility
		},

		toggleView : function(e) {

			var ignoredElements = jQuery('.' + this.settings.ignoredClass, this.elem);
			if (ignoredElements.is(e.target) || ignoredElements.has(e.target).length) {
				return false;
			}

			var content = jQuery('.' + this.settings['contentClass'], this.elem);

			if (e.key === 'Enter' || e.which === 1) {	// accessibilty - 1 is mouseup
				if(!content.hasClass(this.settings['contentClosedClass'])) {
					this.switcher.removeClass(this.settings['shutterClass']);
					this.switcher.addClass(this.settings['openerClass']);
					this.switcher.prop('title', this.settings['openerTitle']);
					content.addClass(this.settings['contentClosedClass']);
				} else {
					this.switcher.removeClass(this.settings['openerClass']);
					this.switcher.addClass(this.settings['shutterClass']);
					this.switcher.prop('title', this.settings['shutterTitle']);
					content.removeClass(this.settings['contentClosedClass']);
				}
			}
		}
	};
	jQuery.fn.boxSwitch = function(options) {
		var returnValue = this.each(function() {
			var element = jQuery(this);
			// Return early if this element already has a plugin instance
			if (element.data('boxSwitch')) {
				return;
			}
			// Store plugin object in this element's data
			element.data('boxSwitch', new BoxSwitch(this, jQuery.extend({}, options)));
		});
		return returnValue;
	};
})();
