/*
	Enhanced CRIR - Enhanced Checkbox & Radio Input Replacement
	Author: Christian Snodgrass
	www.arwebdesign.net/scripts/ecrir
	Based on CRIR by Chris Erwin: www.chriserwin.com/script/crir
*/
var detect_image_src = "http://www.vaikuta.org/images/tiny-detect.png";
var ecrir_class = "ecrir";
/*
	You may remove this portion of the header comments when you deploy to save on filesize. The first 6 lines, however,
	must remain intact.
	Planned Modifications and Improvements:
	- Add Safari Support - Complete
	- Combine all radio images and all checkbox images into a single file.
	
	Update January 31, 2008:
	Fixed full Safari support. Now works in all versions.
	Improved base CSS, resulting in a smaller filesize.
	Added support for disabled options.
	Fixed minor warnings with radio buttons (undeclared variable warning)
	Fixed minor warnings with check boxes (undeclared variable warning)
	
	Update January 30, 2008:
	Now supports Safari. Tested on version 3.0.4. on Windows XP.
	
	Original created January 30, 2008.
	The original became unusable if javascript and css were enabled by images were disabled.
	Also contained minor errors, and was not compatible with Safari.
	Integrated the Image-enabled detection method to remove this initial error.
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////
	Originally based on:
	CRIR - Checkbox & Radio Input Replacement
	Author: Chris Erwin (me[at]chriserwin.com)
	www.chriserwin.com/scripts/crir/

	Updated July 27, 2006.
	Jesse Gavin added the AddEvent function to initialize
	the script. He also converted the script to JSON format.
	
	Updated July 30, 2006.
	Added the ability to tab to elements and use the spacebar
	to check the input element. This bit of functionality was
	based on a tip from Adam Burmister.
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////
	Image detection method based on:
	Unobtrusive Javascript for detecting whether images are enabled or not
	Author: V V K Chandra
	http://webgeekblog.com/2007/04/15/unobtrusive-javascript-for-detecting-whether-images-are-enabled-or-not/
	////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/
// Checks to make sure images are enabled in browsers.
if( document.getElementById && document.createElement ) {
	var img = document.createElement("img");
	img.id = "detect-img";
	img.src = detect_image_src;
	document.body.appendChild(img);
}

var ecrir = {
	userAgent: '',
	isSafari: false,
	hasImages: false,
	
	init: function() {
		this.userAgent = navigator.userAgent.toLowerCase();
		this.isSafari = ((this.userAgent.indexOf('safari')!=-1)&&(this.userAgent.indexOf('mac')!=-1))?true:false;
		
		if (this.isSafari) 
  		{
  			var labels = document.getElementsByTagName("label");
  			for (i = 0; i < labels.length; i++) {
    			labels[i].addEventListener("click", ecrir.addLabelFocus, false);
    		}
  		}
		
		if(ecrir.hasImages) {
//			if (! this.isSafari) { // the script doesn't work in safari.
				arrLabels = document.getElementsByTagName('label');
			
				searchLabels:
				for (var i=0; i<arrLabels.length; i++) {			
					// get the input element based on the for attribute of the label tag
					if (arrLabels[i].getAttributeNode('for') && arrLabels[i].getAttributeNode('for').value != '') {
						labelElementFor = arrLabels[i].getAttributeNode('for').value;				
						inputElement = document.getElementById(labelElementFor);
					}
					else {				
						continue searchLabels;
					}	
									
					inputElementClass = inputElement.className;	
				
					// if the input is specified to be hidden intiate it
					if (inputElementClass == ecrir_class) {
						inputElement.className = 'crirHidden';
						
						inputElementType = inputElement.getAttributeNode('type').value;	
						
						// add the appropriate event listener to the input element
						if (inputElementType == "checkbox") {
							inputElement.onclick = ecrir.toggleCheckboxLabel;
						}
						else {
							inputElement.onclick = ecrir.toggleRadioLabel;
						}
						
						// set the initial label state
						if (inputElement.disabled) {
							if (inputElementType == 'checkbox') { arrLabels[i].className = 'checkbox_disabled'}
							else { arrLabels[i].className = 'radio_disabled' }
						}
						else if (inputElement.checked) {
							if (inputElementType == 'checkbox') { arrLabels[i].className = 'checkbox_checked'}
							else { arrLabels[i].className = 'radio_checked' }
						}
						else {
							if (inputElementType == 'checkbox') { arrLabels[i].className = 'checkbox_unchecked'}
							else { arrLabels[i].className = 'radio_unchecked' }
						}
					}
					else if (inputElement.nodeName != 'SELECT' && inputElement.getAttributeNode('type').value == 'radio') { // this so even if a radio is not hidden but belongs to a group of hidden radios it will still work.
						arrLabels[i].onclick = ecrir.toggleRadioLabel;
						inputElement.onclick = ecrir.toggleRadioLabel;
					}
//				}
			}
		}
	},	
	
	findLabel: function (inputElementID) {
		arrLabels = document.getElementsByTagName('label');
	
		searchLoop:
		for (var i=0; i<arrLabels.length; i++) {
			if (arrLabels[i].getAttributeNode('for') && arrLabels[i].getAttributeNode('for').value == inputElementID) {				
				return arrLabels[i];
				break searchLoop;		
			}
		}
		
		return 0;
	},	
	
	toggleCheckboxLabel: function () {
		var labelElement = ecrir.findLabel(this.getAttributeNode('id').value);
	
		if(labelElement.className == 'checkbox_checked') {
			labelElement.className = "checkbox_unchecked";
		}
		else {
			labelElement.className = "checkbox_checked";
		}
	},	
	
	toggleRadioLabel: function () {			 
		var clickedLabelElement = ecrir.findLabel(this.getAttributeNode('id').value);
		
		var clickedInputElement = this;
		var clickedInputElementName = clickedInputElement.getAttributeNode('name').value;
		
		var arrInputs = document.getElementsByTagName('input');
	
		// uncheck (label class) all radios in the same group
		var inputElementType, inputElementName, inputElementClass, inputElementID, labelElement;
		for (var i=0; i<arrInputs.length; i++) {			
			inputElementType = arrInputs[i].getAttributeNode('type').value;
			if (inputElementType == 'radio') {
				inputElementName = arrInputs[i].getAttributeNode('name').value;
				inputElementClass = arrInputs[i].className;
				// find radio buttons with the same 'name' as the one we've changed and have a class of chkHidden
				// and then set them to unchecked
				if (inputElementName == clickedInputElementName && inputElementClass == 'crirHidden') {				
					inputElementID = arrInputs[i].getAttributeNode('id').value;
					labelElement = ecrir.findLabel(inputElementID);
					if(labelElement.className != 'radio_disabled')
						labelElement.className = 'radio_unchecked';
				}
			}
		}
	
		// if the radio clicked is hidden set the label to checked
		if (clickedInputElement.className == 'crirHidden') {
			clickedLabelElement.className = 'radio_checked';
		}
	},
	
	imagesEnabled: function() {
		if(document.getElementById("detect-img").offsetWidth == 515)
			ecrir.hasImages = true;
		else
			ecrir.hasImages = false;
	
		document.body.removeChild(document.getElementById("detect-img"));
	},
	
	addEvent: function(element, eventType, doFunction, useCapture){
		if (element.addEventListener) 
		{
			element.addEventListener(eventType, doFunction, useCapture);
			return true;
		} else if (element.attachEvent) {
			var r = element.attachEvent('on' + eventType, doFunction);
			return r;
		} else {
			element['on' + eventType] = doFunction;
			return 0;
		}
	},
	
	addLabelFocus: function() {
		var item = document.getElementById(this.getAttribute("for"));
		
		item.focus();
		if (item.getAttribute("type") == "checkbox")
		{
			if (!item["checked"])
			{
				item["checked"] = true;
				this.className = "checkbox_checked";
			}
			else
			{
				item["checked"] = false;
				this.className = "checkbox_unchecked";
			}
		}
		else if (item.getAttribute("type") == "radio")
		{
			var allRadios = document.getElementsByTagName("input");
			var radios = new Array();
			for (i = 0; i < allRadios.length; i++)
			{
				if (allRadios[i].getAttribute("name") == item.getAttribute("name"))
				{
					radios.push(allRadios[i]);
				}
			}
			for (i = 0; i < radios.length; i++)
			{
				if (radios[i]["checked"] && radios[i].getAttribute("id") != item.getAttribute("id"))
				{
					radios[i]["checked"] = false;
					ecrir.findLabel(radios[i]["id"]).className = "radio_unchecked";
				}
			}
			
			item["checked"] = true;
			this.className = "radio_checked";
		}
	}
}

ecrir.addEvent(document.getElementById("detect-img"), 'load', ecrir.imagesEnabled, false);
ecrir.addEvent(window, 'load', ecrir.init, false);