/**
* labelImage.js
*
* Adds onclick-handler to images in labels.
* (Firefox does support this feature automaticly.)
*
* @Author OW
* @Since 04-2008
*
* ----------------------------------------------------------------------------------
*
* FeatureRequest: Bei Auswahl wird dem Bild bzw. dem Label eine Klasse zugeordnet
* FeatureRequest: Unterstützung von tiefen Pics
* FeatureRequest: Bessere Lösung für onclick?
*/

document.observe("dom:loaded",function() {
	
	// IE9 doesnt need this script for clickable images in labels (indexOf always returns -1, if the string isnt found, workaround for contains() method)
	var ie = (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.indexOf("MSIE 9.0") < 0) ? true : false;
	
	if(!ie) {
		return; // update only for IE < 9
	}
	
	var pics = $$('label > img'); // get all pics directly in a label
	var labelSpans = $$('label > span');
	pics.each(function(pic){ // loop all pics
		var _for = pic.parentNode.attributes['for'].value; // get for Attribute of pic (=input)
		
		Event.observe(pic, 'click', function() { // add click handler
		
			/*
			if($(_for).attributes['type'].value != 'checkbox'){
			
				// reset all images
				var picContainer = $(_for).parentNode.parentNode;
				var picContainerId = $this(picContainer).id;
				
				$$("#"+picContainerId+" .answerPic").each(function(pic){
					pic.removeClassName("imageSelected");
				});
			}*/
			
			if(!$(_for).checked){ // activate input field (input OR checkbox)
				$(_for).checked = true;
				//pic.addClassName('imageSelected');
			}else { 
				if($(_for).attributes['type'].value == 'checkbox') { // disactivate only checkbox input (NOT radio!!!)
					$(_for).checked = false;
				}
			}
			
				
			var code = $(_for).attributes['onclick'].value; // get onclick JS code
			code = code.replace("this","$(_for)"); // replace this with for attribute
			eval(code); // run onclick JS code
		});
	});
	
	
	// temporary disabled - didnt work properly (caused bug in IE7 and IE8)
	/*labelSpans.each(function(spanElem){ // loop all spans
		var _for = spanElem.parentNode.attributes['for'].value; // get for Attribute of label (=input)
		
		Event.observe(spanElem, 'click', function() { // add click handler
		
			if(!$(_for).checked){ // activate input field (input OR checkbox)
				$(_for).checked = true;
			}else { 
				if($(_for).attributes['type'].value == 'checkbox') { // disactivate only checkbox input (NOT radio!!!)
					$(_for).checked = false;
				}
			}
			
				
			var code = $(_for).attributes['onclick'].value; // get onclick JS code
			code = code.replace("this","$(_for)"); // replace this with for attribute
			eval(code); // run onclick JS code
		});
	});*/
	
});
