var radioGroupNames = null;

Event.observe(window, 'load', function (e){
	attachHelp();
	attachTextValidation()
	attachRadioValidation();
	
	$('validationErrors').setOpacity(0);
	
	$('calculator').observe('keypress', function(e){
		if (e.keyCode == Event.KEY_RETURN) {
			e.stop();
			return false;
		}
	});
	
	$('calculator').observe('submit', function (e) {
		
		var isValid = performValidation(e);
		if (!isValid){
			e.stop();
			showValidationError();
		}
		return isValid;
	});
	
	
	Calendar.setup({
		"ifFormat":"%Y-%m-%d",
		"daFormat":"%Y-%m-%d",
		"ttFormat":"%Y-%m-%d",
		"button":"driedOffEarly1",
		"range": new Array('2007', '2011' ),
		"onSelect" : function (calendar, date){ 
		
			selectDropDownItemWithValue('dryOffDateDay',(calendar.date.getDate()) );
			selectDropDownItemWithValue('dryOffDateMonth',(calendar.date.getMonth() + 1) );
			selectDropDownItemWithValue('dryOffDateYear',(calendar.date.getFullYear()) );
			
			if (calendar.dateClicked) { 
				calendar.callCloseHandler();
			}
		}
	}); 
	
	Calendar.setup({
		"ifFormat":"%Y-%m-%d",
		"daFormat":"%Y-%m-%d",
		"ttFormat":"%Y-%m-%d",
		"button":"driedOffEarly2",
		"range": new Array('2007', '2011' ),
		"onSelect" : function (calendar, date){ 
		
			selectDropDownItemWithValue('dryOff2DateDay',(calendar.date.getDate() ) );
			selectDropDownItemWithValue('dryOff2DateMonth',(calendar.date.getMonth() +1) );
			selectDropDownItemWithValue('dryOff2DateYear',(calendar.date.getFullYear()) );
			
			if (calendar.dateClicked) { 
				calendar.callCloseHandler();
			}
		 }
	}); 
	
	Calendar.setup({
		"ifFormat":"%Y-%m-%d",
		"daFormat":"%Y-%m-%d",
		"ttFormat":"%Y-%m-%d",
		"button":"driedOffEarly3",
		"range": new Array('2007', '2011' ),
		"onSelect" : function (calendar, date){ 
		
			selectDropDownItemWithValue('dryOff3DateDay',(calendar.date.getDate() ) );
			selectDropDownItemWithValue('dryOff3DateMonth',(calendar.date.getMonth() + 1) );
			selectDropDownItemWithValue('dryOff3DateYear',(calendar.date.getFullYear()) );
			
			if (calendar.dateClicked) { 
				calendar.callCloseHandler();
			}
		}
	}); 
	
	Calendar.setup({
		"ifFormat":"%Y-%m-%d",
		"daFormat":"%Y-%m-%d",
		"ttFormat":"%Y-%m-%d",
		"button":"lastSupply",
		"range": new Array('2007', '2011' ),
		"onSelect" : function (calendar, date){
			
			selectDropDownItemWithValue('lastSupplyDateDay',(calendar.date.getDate() ) );
			selectDropDownItemWithValue('lastSupplyDateMonth',(calendar.date.getMonth() +1) );
			selectDropDownItemWithValue('lastSupplyDateYear',(calendar.date.getFullYear()) );
			
			if (calendar.dateClicked) { 
				calendar.callCloseHandler();
			}
		}
	}); 
	
});


function selectDropDownItemWithValue(element, value) {

	element = $(element);
	if (null == element)	
		return;
		
	if ( value == null || value.length <= 0)
		return;
		
	var opts = $(element).select('option');
	for (var i=0, len = opts.length; i < len; i++){
		if (opts[i].value == value){
		
			element.selectedIndex = i;
			
			break;
			
		}	
	}
	 
}


function attachHelp(){
	var helpIcons = $$('.helpIcon');

	for (var i=0, len= helpIcons.length; i < len; i++){
		
		var icon=helpIcons[i];
		
		var popUp = $(icon.readAttribute('rel'));
		if (null != popUp){
			popUp.setOpacity(0);
			//popUp.show();
		}
		
		$(icon).observe('mouseover', function (e){
			var icon = $(e.target);
			
			
			var popUp = $(icon.readAttribute('rel'));
			
			if (null == popUp)
				return;

			var iconDims = icon.getDimensions();
			var iconOffset = icon.viewportOffset();
			var iconScrollOffset = icon.cumulativeScrollOffset();
			
			popUp.style.left = ( iconOffset.left + (iconDims.width/2) + iconScrollOffset.left ) + 'px' ;
			popUp.style.top = (iconOffset.top - popUp.getHeight() - 10  + iconScrollOffset.top) + 'px';
			
			//possibly add an effect??

			
			new Effect.Opacity( popUp.identify(), { 
				from: 0.0, 
				to: 1.0, 
				duration: 0.2 ,
				beforeStart: function (effect) {
					effect.element.show();

				}
				});
			
		});	
		
		$(icon).observe('mouseout', function (e){
		
			var icon = $(e.target);			
			var popUp = $(icon.readAttribute('rel'));

			if (null == popUp)
				return;
				
			
			new Effect.Opacity(popUp.identify(), 
			{ 
				from: 1.0, 
				to: 0.0, 
				duration: 0.2,
				afterFinish: function (effect) {		
					effect.element.hide();
				}
			});
		});	
	}

}

function attachRadioValidation() {

	var f = $('calculator');
	var radios = f.getInputs('radio');
	radioGroupNames = $H();
	
	
	for (var i=0, len=radios.length; i < len; i++ ){
		
		var radioName = radios[i].name;
		
		
		if (null == radioGroupNames.get( radioName ));
			radioGroupNames.set(radioName,true);
				
		radios[i].observe('click', function (e) {
			
			var validationIcon = $(e.target.parentNode).select('img');
			var t = $(e.target);
			var rel = t.readAttribute('rel');
			var n = $( rel );
			
			if (null != n) {
				if (t.value == 'yes'){
					n.enable();
				} else {
					n.value = 0;
					n.disable();
				}
			}
			
			if (validationIcon.length == 1)
				validationIcon[0].src = "/images/tick.gif";

		});
			
	}
}


function attachTextValidation() {
	
	var f = $('calculator');
	var texts = f.getInputs('text');
		
	for (var i=0, len=texts.length; i < len; i++ ){
		
		texts[i].observe('change', function (e){
			validateText(e.target);
		});
		
		texts[i].observe('blur', function (e){
			validateText(e.target);
		});
		
	}
	
	
}

function validateText(n){

	var isValid = true;
	var value = n.value;

	n = $(n);
	
	if (value == null || 0 >=value.length )
		value = "zzzz";
			
	value = (value.replace(/\W*/,'')) * 1;
		
	var validationIcon = null;
	if( null != $(n.parentNode).select('img').length==1) {
		var imageNodes = $(n.parentNode).select('img');
		validationIcon = $(n.parentNode).select('img')[imageNodes.length - 1];
	}		


		//we attach different classes to the inputs to determine how to validate.
		// eg big num.. must be a number between 5 and six digits
		if ( n.hasClassName('bigNum') ){
			if (isNaN(value))
				isValid = false;
				
			isValid = ( value >= 100000 && value < 10000000);
			
		} else if (n.hasClassName('optNum')){

			//if (0 == value.length) {
			//	isValid = true;
			//} else if (0 < value.length) {
				isValid = !isNaN(value);
			//} else {
			//	isValid = false;
			//}
			
		} else {
			if (isNaN( value ) || 0 > value || 0 >= value.length){
				isValid = false;
			} else {
				isValid = true;
			}
		}
	
	
	//add additional checks here.. that make the text dependant on another item.
	
	
	if (isValid){
		validationIcon.src = "/images/tick.gif";
		return true;		
	} else {
		validationIcon.src = "/images/cross.gif";
		return false;		
	}
}



function validateRadioButtonsGroups(){

	var radioGroupsAreValid = true;
	var radioGroupNameKeys = radioGroupNames.keys();
	var f = $('calculator');
	
	
	for (var i=0, len= radioGroupNameKeys.length; i < len; i++){
		
		var radioGroup = f.getInputs('radio', radioGroupNameKeys[i]);
		
		var validGroup = false;
		for(var j=0, lenj=radioGroup.length; j < lenj ;j++ ){
			validGroup = radioGroup[j].checked;
			if (validGroup)
				break;			
		}
		
		var validationIcon = null;
		if( null != $(radioGroup[0].parentNode).select('img').length==1) {
			validationIcon = $(radioGroup[0].parentNode).select('img')[0]
		}		
		
		if (validGroup){
			validationIcon.src = "/images/tick.gif";
		} else {
			radioGroupsAreValid = false;
			validationIcon.src = "/images/cross.gif"
		}
	}
	
	return radioGroupsAreValid;
}

function validateTextFields() {
	var f = $('calculator');
	var texts = f.getInputs('text');
	var textsAreValid = true;
	
	var validText=false;
	for (var i=0, len=texts.length; i < len; i++ ){
		validText = validateText(texts[i]);
		if (!validText) {
			textsAreValid = false;
		}
	}
	return textsAreValid;
}


function validateDates(){
	return 1 == 1;
}

function performValidation(e){

	//first validate radio buttons	
	var radioGroupsAreValid = validateRadioButtonsGroups();
	var textsAreValid = validateTextFields();
	var datesAreValid = validateDates();

	return (radioGroupsAreValid && textsAreValid && datesAreValid);//or with all of the validation items.	
}

function showValidationError(){
	
	var popUp = $('validationErrors');
	popUp.show();
	
	var icon = $('calculateSubmit');
	
	var iconDims = icon.getDimensions();
	var iconOffset = icon.viewportOffset();
	var iconScrollOffset = icon.cumulativeScrollOffset();
			
	popUp.style.left = ( iconOffset.left - popUp.getWidth() - 20 + iconScrollOffset.left ) + 'px' ;
	popUp.style.top = (iconOffset.top - (iconDims.height/2) + 10  + iconScrollOffset.top) + 'px';
	
	new Effect.Opacity( 'validationErrors', { from: 0.0, to: 1.0, duration: 0.2 });	
}

function hideValidationError() {
	new Effect.Opacity( 'validationErrors', { 
		from: 1.0, 
		to: 0.0, 
		duration: 0.2
		}
		
	);
	$('validationErrors').hide();
}