
/*
 * Doubleclique jQuery Styled Checkbox Plugin
 *
 * A plugin to style checkboxes
 *
 * Authors: Doubleclique Developers <dev@doubleclique.com>
 */

(function($) {
	$.fn.StyledCheckboxField = function(options) {

	function StyledCheckbox(checkboxElement, options) {
		var self = this;


		self.init = function(checkboxElement, options) {
			self.defaults = {
				height: 14,
				width: 14
			};

			self.defaults = $.extend({}, self.defaults, options);

			self.oldCheckbox = jQuery(checkboxElement);

			self.checkboxId   = self.oldCheckbox.attr('id');
			self.checkboxName = self.oldCheckbox.attr('name');

			self.checkboxLabel = jQuery('label[for=' + self.checkboxId + ']');

			if (!self.checkboxLabel.length) {
				alert("No label on checkbox: " + self.checkboxId);
			}

			self.newCheckbox = null;

			self.hideOldCheckbox();
			self.createStyledCheckbox();
			self.setInitialStyles();
			self.addEventHandlers();
			self.updateNewCheckbox();
		};


		self.hideOldCheckbox = function() {
			self.oldCheckbox.hide();
		};


		self.createStyledCheckbox = function() {
			var newCheckbox = jQuery('<div></div>').attr({ 'id': self.checkboxId + 'Pretty' }).addClass('newCheckbox');
			self.oldCheckbox.after(newCheckbox);

			self.newCheckbox = jQuery('#' + self.checkboxId + 'Pretty');
		};


		self.setInitialStyles = function() {
			self.newCheckbox.css({
				height: parseInt(self.defaults.width) + 'px',
				width: parseInt(self.defaults.height) + 'px',
				cursor: 'pointer'
			});
		};


		self.addEventHandlers = function() {
			self.oldCheckbox.bind('change', function() {
				self.updateNewCheckbox();
			});

			// make labels work in IE, other browsers work properly so an event handler for the label is unnecessary for them
			if (jQuery.browser.msie) {
				self.checkboxLabel.bind('click', function(event) {
					if (!jQuery(event.target).attr('href')) {
						event.preventDefault();
					}
					self.toggleCheckbox();
				});
			}

			self.newCheckbox.bind('click', function() {
				self.toggleCheckbox();
			});
		};


		self.updateNewCheckbox = function() {
			if (self.oldCheckbox.attr('checked')) {
				self.newCheckbox.css('background-position', 'left -'+self.defaults.height+'px');
			} else {
				self.newCheckbox.css('background-position', 'left 0px');
			}
		};


		self.toggleCheckbox = function() {
			if (self.oldCheckbox.attr('checked')) {
				self.oldCheckbox.attr('checked', false);
			} else {
				self.oldCheckbox.attr('checked', true);
			}
			self.oldCheckbox.trigger('change');
		};


		self.init(checkboxElement, options);
	}

    return this.each(function() {
        new StyledCheckbox(this, options);
    });
  }
})(jQuery);