(function($) {
	var linkedEvents = ['click', 'change', 'mouseup', 'mousedown', 'mousemove'];

	$.fn.checkBox = function() {
		var checkboxes = $(this).filter(':checkbox, :radio');
		var radio = {};

		checkboxes.each(function() {
			var input = this;
			var checkbox = jQuery(input);

			if (checkbox.data('styled')) {
				return;
			}

			checkbox.data('styled', true);

			// Add uniq id if not set
			if (input.id.length === 0) {
				input.id = 'uniq' + Math.floor(Math.random() * 10000000);
			}

			// Move "on" Event to Event Listner
			for (var i = 0; i < linkedEvents.length; i++) {
				if (typeof input['on' + linkedEvents[i]] === 'function') {
					checkbox.bind(linkedEvents[i], input['on' + linkedEvents[i]]);

					input['on' + linkedEvents[i]] = null;
				}
			}

			var label = jQuery('<label for="' + input.id + '" class="ui-' + input.type + (input.checked ? ' ui-' + input.type + '-state-checked' : '') + (input.className ? ' ' + input.className : '') + '"></label>');

			// Collect Labels
			if (input.type === 'radio') {
				if (radio[input.name]) {
					radio[input.name].push(label);
				}
				else {
					radio[input.name] = new Array(label);
				}
			}

			checkbox.addClass('ui-input');
			checkbox.before(label);

			// Change callback - for label class changing
			checkbox.change(function () {
				checkbox.blur();

				if (input.checked) {
					if (input.type === 'radio') {
						$.each(radio[input.name], function (i, inp) {
							inp.removeClass('ui-' + input.type + '-state-checked');
						});
					}

					label.addClass('ui-' + input.type + '-state-checked');
				}
				else {
					label.removeClass('ui-' + input.type + '-state-checked');
				}
			});
		});

		return checkboxes;
	}
})(jQuery);
