/*
	Class:			NiceCheckBox
	Author:			Matt Dolan
	Date:			14/07/10
	Description:	Replaces checkboxes in forms with a span, allowing for nicer styling.
	Requires:		Prototype 1.6
	
	Implementation:
		Just apply the class 'niceElements' to the form containing checkboxes.
		Style the class 'niceCheckBox' to match the website. 
*/
var NiceCheckBox = Class.create({

	toggle: function () {
		this.checkbox.checked = !this.checkbox.checked;
		this.updateSpanState();
	},
	
	spanClick: function (ev) { this.toggle(); Event.stop(ev); },
	
	spanKeydown: function (ev) { 
		if (ev.keyCode == 32) // space
			this.toggle();
	},
	
	updateSpanState: function () {
		if (this.checkbox.checked)
			this.span.addClassName('checked');
		else
			this.span.removeClassName('checked');
	},
	
	// the checkbox state can be changed by clicking on its label, so we need to keep
	// things in sync both ways
	checkboxChange: function (ev) {	this.updateSpanState();	},
	
	initialize: function (checkbox,options) {
		this.checkbox = checkbox;
		
		if (!this.checkbox || this.checkbox.tagName!='INPUT' || this.checkbox.type!='checkbox') {
			throw "NiceCheckBox requires a checkbox input to be passed on construction";
			return;
		}
		
		// don't initialize the same checkbox twice
		if (this.checkbox.hasBeenMadeNice) return;
		
		this.span = new Element('span',{'class':'niceCheckBox',tabindex: 0})
						.observe('click',this.spanClick.bind(this))
						.observe('keydown',this.spanKeydown.bind(this));
						
		this.updateSpanState();
		
		this.checkbox
				.insert({after: this.span})
				.observe('change',this.checkboxChange.bind(this))
				.hide();
		// mark checkbox as initialized
		this.checkbox.hasBeenMadeNice = true;
	}
});


Event.observe(document,'dom:loaded',function () {
	$$('form.niceElements input[type=checkbox]').each(function(checkbox) {
		new NiceCheckBox(checkbox);
	});
});
