/*global jQuery */

"use strict";

(function ($) {
	function Checkbox(checkbox, conf) {
		var publ = {}, priv = {};


		priv.defaults = {
			styledCheckboxClass: 'styledCheckbox'
		};


		priv.init = function (checkbox, conf) {
			priv.initVariables();

			priv.storeSettings(conf);
			priv.storeElements(checkbox);

			priv.main();
		};


		priv.initVariables = function () {
			priv.settings       = null;
			priv.checkbox       = null;
			priv.label          = null;
			priv.styledCheckbox = null;
			priv.checkboxState  = null;
		};


		priv.storeSettings = function (conf) {
			priv.settings = $.extend(priv.defaults, conf);

			priv.settings.styledCheckboxSelector = '.' + priv.settings.styledCheckboxClass;
		};


		priv.storeElements = function (checkbox) {
			priv.checkbox = $(checkbox);
			priv.label    = $('label[for=' + priv.checkbox.attr('id') + ']');
		};


		priv.main = function () {
			priv.createStyledCheckbox();
			priv.storeStyledCheckbox();
			priv.checkbox.hide();

			priv.addEventHandlers();
		};


		priv.createStyledCheckbox = function () {
			priv.checkbox.wrap('<div class="' + priv.settings.styledCheckboxClass + '" />').wrap('<div class="' + priv.getCheckboxState() + '" />');
		};


		priv.getCheckboxState = function () {
			if (priv.checkbox.attr('checked')) {
				return 'checked';
			}
			return 'unchecked';
		};


		priv.storeStyledCheckbox = function () {
			priv.styledCheckbox = priv.checkbox.closest(priv.settings.styledCheckboxSelector);
			priv.checkboxState  = priv.checkbox.parent();
		};


		priv.addEventHandlers = function () {

			var clickers = new Array(priv.styledCheckbox, priv.label);
			
			$(clickers).each(function () {
				$(this).bind('click', function () {
					publ.toggle();
				});
			});

			
		};


		publ.toggle = function () {
			if (priv.getCheckboxState() === 'checked') {
				publ.uncheck();
			} else {
				publ.check();
			}
		};


		publ.check = function () {
			priv.checkbox.attr('checked', true);
			priv.checkbox.val(1);
			priv.checkbox.change();
			if ($('input[type="hidden"][name="'+ priv.checkbox.attr('name') +'"]').length) {
				
				$('input[type="hidden"][name="'+ priv.checkbox.attr('name') +'"]').val(1);
				
			}
			priv.checkboxState.addClass('checked').removeClass('unchecked');
		};


		publ.uncheck = function () {
			priv.checkbox.attr('checked', false);
			priv.checkbox.val(0);
			priv.checkbox.change();
			if ($('input[type="hidden"][name="'+ priv.checkbox.attr('name') +'"]').length) {

				$('input[type="hidden"][name="'+ priv.checkbox.attr('name') +'"]').val(0);

			}
			priv.checkboxState.removeClass('checked').addClass('unchecked');
		};


		priv.init(checkbox, conf);


		return publ;
	}

	$.fn.styledCheckbox = function (conf) {
		var instances = [];

		this.each(function () {
			instances.push(new Checkbox(this, conf));
		});

		return (instances.length === 1) ? instances[0] : instances;
	};
}(jQuery));
