
function toggleDisplayForm()
{
	if ( !$('login_container').visible() ) {
		new Effect.BlindDown('login_container', 
			{ 	duration: 0.7,
				afterFinish: function() { $('Username').focus(); } });
		
	}
	else {
		new Effect.BlindUp('login_container', { duration: 0.7 });
	}
	
	return false;
}

function setFocus()
{
	$('Username').focus();
}



function validateOrderFormFirstPart(){
	
	
	var currentDt = new Date();
	
	year = $('FittingDateYear').value;
	month = parseInt($('FittingDateMonth').value,10) -1;
	day   = parseInt($('FittingDateDay').value,10);
	var formDt = new Date();
	formDt.setFullYear(year,month, day);
	
	
	if (currentDt>formDt) {
		alert('Please choose a valid date in the future.');
		return false;
	}	
	
	
	if (!$('KLABTechnicians_ID').value){
		alert('Please specify a Technician');	
		$('KLABTechnicians_ID').focus();
	}
	else if (!$('KLABLocations_ID').value){
		alert('Please specify a Location');	
		$('KLABLocations_ID').focus();
	}
	else if (!$('ShoeGender').value){
		alert('Please specify a Gender');	
		$('ShoeGender').focus();
	}	
	else{
		prepareUnitData();
		$('generalInfo').style.display = 'none';
		$('firstPart').style.display = '';
	}
}

function verifyOrthoticOrderSecondPart(buttonElem){

	if (!$RF(buttonElem.form, 'Orthotics')) {
		alert('Please choose an orthotic.');
		return false;
	}

	if (isNoShellMaterialSelected(buttonElem)) {
		alert('Please choose a shell material.');
		return false;
	}
	
	if (!$RF(buttonElem.form, 'ShellLength')) {
		alert('Please choose a shell length.');
		return false;
	}	

	var orthoticID = $RF(buttonElem.form, 'Orthotics');
	var shellLength = $RF(buttonElem.form, 'ShellLength');

	// 1. When you select XPE or EVA for any orthotic other than soft shell or D/A Multi layer
	// have a message that says Select Soft Shell or Multi-Layer orthotic with a soft shell material
	if ($RF(buttonElem.form, 'SoftShellMaterial') && (orthoticID != 11 && orthoticID != 12)) {
		alert('Please select Soft Shell or  D/A Multi-Layer orthotic with a soft shell material.');
		return false;
	}

	// 2. When you select a semi-rigid material for a Soft Shell or Multi Layer orthotic 
	// have a message that says Semi-rigid materials are not available for soft shell orthotics
	if ($RF(buttonElem.form, 'SemiRigidShellMaterial') && (orthoticID == 11 || orthoticID == 12)) {
		alert('Semi-rigid materials are not available for soft shell orthotics.');
		return false;
	}	
	
	// 3. When you select Polypro Direct for a Womens Heel orthotic
	// have a message that says Polypro direct is not available for Womens Heel orthotic.
	if (orthoticID == 4 && $RF(buttonElem.form, 'SemiRigidShellMaterial') == 3) {
		alert('Polypro direct is not available for Women\'s Heel orthotic.');
		return false;
	}		

	// 4. The Full Contact materials (Miterplast and Plastezote) are only available in the full length option 
	// so if 3/4 or sulcus is selected then a message can say Full contact materials are only available in full length orthotics.
	if ($RF(buttonElem.form, 'FullContactMaterial') && (shellLength == 1 || shellLength == 2) ) {
		alert('Full contact materials are only available in full length orthotics.');
		return false;
	}		

	// 5. The Full Contact materials (Miterplast and Plastezote) are only available for the Soft-Shell orthortic, 
	// so if a full contact material is selected and something other than the Soft-Shell orthortic is selected 
	// display a message saying Full contact materials are only available for soft shell orthotics
	if ($RF(buttonElem.form, 'FullContactMaterial') && (orthoticID != 11) ) {
		alert('Full contact materials are only available for soft shell orthotics.');
		return false;
	}		
				
	// 6. When you select XT Graphite or a non semi-rigid material for a UCBL or Roberts orthotic 
	// have a message that says the selected shell material is not available on this orthotic.
	if ((orthoticID == 13 || orthoticID == 14) && (!$RF(buttonElem.form, 'SemiRigidShellMaterial') || $RF(buttonElem.form, 'SemiRigidShellMaterial') == 4)) {
		alert('The chosen shell material is not available on UCBL or Roberts Whitman orthotics.');
		return false;
	}
	
	$('firstPart').style.display='none';
    $('secondPart').style.display='';
}


function isNoShellMaterialSelected(buttonElem){
	return (!$RF(buttonElem.form, 'SemiRigidShellMaterial') && !$RF(buttonElem.form, 'SoftShellMaterial') && !$RF(buttonElem.form, 'FullContactMaterial') );
}

function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }

    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}



function DeselectOrthoticsOptions(inputFieldName){
	var elements = $$('input[name="' + inputFieldName + '"]');		
	
	for(var j=0; j<elements.length; j++){
		elements[j].checked = false;
	}
	$('clear_'+inputFieldName).style.display = 'none';
	
}


function initializeOrthoticsForm(){
	divName = '#orderForm input';
	var inputFields = $$(divName);
	bindOrthoticFormEvents(inputFields);

	function bindOrthoticFormEvents(elements)
	{
		for ( i = 0; i < elements.length; i++ ) {			
			if (elements[i].type =='radio'){			
				Event.observe(elements[i], 'click', displayClearButton.bindAsEventListener(elements[i]));	
				
				if (elements[i].checked == true ){
					
					if ($('clear_'+elements[i].name)){
						$('clear_'+elements[i].name).style.display = '';
					}
				}
				
			}
		}
	}	
}

function displayClearButton(e){

	var element = Event.element(e);
	if ($('clear_'+element.name)){
		$('clear_'+element.name).style.display = '';
	}
	
}


function updateMaterialsValues(inputField){

	if (inputField.name == 'SemiRigidShellMaterial'){
		var elems = $$('input[name="SoftShellMaterial"]');
		resetCheckBoxValues(elems);
		var elems = $$('input[name="FullContactMaterial"]');	
		resetCheckBoxValues(elems);
		
	}
	else if(inputField.name == 'SoftShellMaterial'){

		var elems = $$('input[name="SemiRigidShellMaterial"]');		
		resetCheckBoxValues(elems);
		var elems = $$('input[name="FullContactMaterial"]');	
		resetCheckBoxValues(elems);
		
	}
	else if(inputField.name == 'FullContactMaterial'){
		
		var elems = $$('input[name="SemiRigidShellMaterial"]');		
		resetCheckBoxValues(elems);
		var elems = $$('input[name="SoftShellMaterial"]');	
		resetCheckBoxValues(elems);
	}
	
	else if (inputField.name == 'SupportRating'){
			var elems = $$('input[name="MaterialThickness"]');		
			resetCheckBoxValues(elems);		
	}
	
	else if (inputField.name == 'MaterialThickness'){
			var elems = $$('input[name="SupportRating"]');		
			resetCheckBoxValues(elems);		
	}
	
		
}

function resetCheckBoxValues(elems){
	
	for (i=0; i <elems.length; i++){
			elems[i].checked=false;
			if ($('clear_'+elems[i].name) && $('clear_'+elems[i].name).style.display==''){
				$('clear_'+elems[i].name).style.display='none';
			}
	}	
}

function updateDefaultValues(inputField){
		if ($(inputField.name+"Left")){
			$(inputField.name+"Left").checked = true;
		}
		if ($(inputField.name+"Right")){
			$(inputField.name+"Right").checked = true;
		}
}

function orderFormPrevious(){
	$('generalInfo').style.display = 'none'
	$('firstPart').style.display='block';
    $('secondPart').style.display='none';
}

function orderFormInitial(){
	$('generalInfo').style.display = '';
	$('firstPart').style.display='none';
    $('secondPart').style.display='none';
}

function initializeOrderGeneralInfoScreen(){

	element = $('KLABTechnicians_ID');
	if (element && element.options.length==2){
			element.options[1].selected = true;
	}
	
	element = $('KLABLocations_ID');
	if (element && element.options.length==2){
			element.options[1].selected = true;
	}
	
	initializeUnits();
}

function initializeUnits(){
	
	
	if ($('Height').value){		
		
		var height = $('Height').value;
		$('HeightTopUnitMetric').selectedIndex = parseInt(height.charAt(0));
		$('HeightLowerUnitMetric').selectedIndex = parseInt(height.charAt(1)+height.charAt(2));	
	}
	if ($('Weight').value){		
		
		var weight = eval($('Weight').value).toFixed(0);
		if (weight%2){
				weight= weight -(weight%2);
		}
		//$('WeightMetric').value = weight;
		
		var select = $('WeightMetric');
			
		for(j=0; j<select.length; j++){
			
			if (parseInt(select.options[j].text)==parseInt(weight)){					
					$('WeightMetric').selectedIndex = j;
			}
		}
		
	}
	
	adjustUnits('imperial','Height');
	adjustUnits('imperial','Weight');
}

 
function adjustUnits(unit, type){
	
	if (unit=='metric'){
		
		//check the current values to verify if they need to be converted
		if (type=='Height'){
			feet   = $F('HeightTopUnitImperial');
			inches = $F('HeightLowerUnitImperial');
			
			cm = eval(feet * 30.48 + inches * 2.54).toFixed(0); 
			
			if (cm.length > 2){		
				$('HeightTopUnitMetric').selectedIndex = cm.charAt(0);
				$('HeightLowerUnitMetric').selectedIndex = cm.charAt(1)+cm.charAt(2);	
			}
			else{
				$('HeightTopUnitMetric').selectedIndex = 0;
				$('HeightLowerUnitMetric').selectedIndex = cm.charAt(0)+cm.charAt(1);	
			}
			
			$('metric'+type).style.display = '';
			$('imperial'+type).style.display = 'none';
		}
		else if (type=='Weight'){
			currentWeight = $F('WeightImperial');
			newWeight = eval(currentWeight*0.45359237).toFixed(0);
			
			if (newWeight%2){
				decimalCheck = eval(currentWeight*0.45359237).toFixed(1);
				decimalLowerEndCheck = Math.abs(decimalCheck - newWeight  - (newWeight%2));
				decimalHigherEndCheck =  Math.abs(decimalCheck - newWeight  + (newWeight%2));
			
				if (decimalLowerEndCheck > decimalHigherEndCheck){					
					newWeight= parseInt(newWeight -(newWeight%2));
				}
				else{
					newWeight= parseInt(newWeight +(newWeight%2));
				}
			}
			
			
			var select = $('WeightMetric');
			
			for(j=0; j<select.length; j++){
				
				if (parseInt(select.options[j].text)==parseInt(newWeight)){			
					$('WeightMetric').selectedIndex = j;
				}
			}
			
			
			$('Weight').value = newWeight;
			$('weight_unit').innerHTML = 'Kgs.';
			$('WeightMetric').style.display = '';
			$('WeightImperial').style.display = 'none';
		}
		
		
	}
	else{
		
		if (type=='Height'){
			metres =  $F('HeightTopUnitMetric');
			cms =  $F('HeightLowerUnitMetric');	
					
			height = metres + cms; 
			feet = Math.floor(height/30.48); 
			inches =  eval((height/2.54) - (feet*12)).toFixed(0);
	
			$('HeightTopUnitImperial').selectedIndex = feet;
			$('HeightLowerUnitImperial').selectedIndex = inches;
	
			$('metric'+type).style.display = 'none';
			$('imperial'+type).style.display = '';		
		}
		else if (type=='Weight'){
			
			currentWeight = $F('WeightMetric');
			newWeight =  eval(currentWeight/0.45359237).toFixed(0);
			if (newWeight%5){
				if (newWeight%5 >=3){
					increaseFactor = 5 -(newWeight%5);				
					newWeight = parseInt(newWeight) + parseInt(increaseFactor);
					
				}
				else{
					newWeight= parseInt(newWeight) - parseInt((newWeight%5));	
				}
				
			}
		
			var select = $('WeightImperial');
			
			for(j=0; j<select.length; j++){
			
				if (parseInt(select.options[j].text)==parseInt(newWeight)){					
					$('WeightImperial').selectedIndex = j;
				}
			}
	
		
			$('Weight').value = newWeight;
			$('weight_unit').innerHTML = 'lbs.';
			$('WeightMetric').style.display = 'none';
			$('WeightImperial').style.display = '';
		}
		
	}
}


function prepareUnitData(){
	
	if ($('metricHeight').style.display != 'none'){
		//user is using metric units 
		$('Height').value = $F('HeightTopUnitMetric')+$F('HeightLowerUnitMetric');
	}
	else{
		//we need to make the convertion 		
			feet   = $F('HeightTopUnitImperial');
			inches = $F('HeightLowerUnitImperial');
			cm = eval(feet * 30.48 + inches * 2.54).toFixed(0); 
			$('Height').value = cm;
	}
	
	
	if($('unit_weight_imperial').checked == true){
		//$('Weight').value = eval($('WeightImperial').value*0.45359237).toFixed(0);
		selectedIndex = $('WeightImperial').selectedIndex;
		$('Weight').value = eval($('WeightImperial').options[selectedIndex].text*0.45359237).toFixed(0);
	}
	else{
		selectedIndex = $('WeightMetric').selectedIndex;
		$('Weight').value = $('WeightMetric').options[selectedIndex].text;
		//$('Weight').value = $('WeightMetric').value;	
	}
	
}

/**
* Ajax call to retrieve order form defaults for a given orthotic type
*/
function setOrthoticsOrderDefaults(OrthoticID)
{
	params = 'OrthoticsID=' + OrthoticID;
	
	
	var Req = new Ajax.Request('/client_services/orthotics_order_defaults.json.php',
				{
					method:'post',
					parameters: params,
					onSuccess: function(xmlHttpRequest){ handleSetOrthoticsOrderDefaultsResponse(xmlHttpRequest) },
					onFailure: function(xmlHttpRequest){ alert('Something went wrong... ') }
				});
}

/**
* Pre-select default settings in orthotic order form from the data returned by the ajax call in 
* the setOrthoticsOrderDefaults function
*/
function handleSetOrthoticsOrderDefaultsResponse(xmlHttpRequest)
{
	var json = xmlHttpRequest.responseText.evalJSON();
	
	
	clearPreviousSelection();
	$H(json).each(function(pages){ setOrderFormPageDefaults(pages) });

	function setOrderFormPageDefaults(page) {
		currentPageName = page.key;
		$H(page.value).each(function(fields){ setField(currentPageName, fields) });
	}
	
	function setField(currentPageName, field) {
		fieldName = field.key;
		fieldType = field.value.Type;
		fieldDefaultValue = field.value.Value;
		
		if ( fieldType.toLowerCase() == 'radio') {
			var inputFields = $$("input[type=radio][name='" + fieldName + "']" );
			
			for ( var j = 0; j < inputFields.length; j++ ) {
			
				Form.Element.setValue(inputFields[j].name, fieldDefaultValue);
			}
		}
	}
	
	function clearPreviousSelection() {
		
		var elemNames = $A(['SemiRigidShellMaterial', 'ShellLength', 'HF', 'FF', 'CastFillLeft', 'CastFillRight', 'TopCover', 'TopCoverLength',
						'MaterialThickness', 'ForefootExtensions', 'ForefootLength', 'ForefootThickness', 'SoftShellMaterial', 'ArchFill', 'TopCoverComboBacking']);
		
		elemNames.each( function(elemName) {
				var elems = $$('input[type=radio][name="' + elemName + '"]');
				resetCheckBoxValues(elems);
			});
	}
}


Form.Element.setValue = function(element,newValue) {
    element_id = element;
    element = $(element);
    if (!element){element = document.getElementsByName(element_id)[0];}
    if (!element){return false;}
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.SetSerializers[method](element,newValue);
    return true;
}

Form.Element.SetSerializers = {
  input: function(element,newValue) {
    switch (element.type.toLowerCase()) {
      case 'submit':
      case 'hidden':
      case 'password':
      case 'text':
        return Form.Element.SetSerializers.textarea(element,newValue);
      case 'checkbox':
      case 'radio':
        return Form.Element.SetSerializers.inputSelector(element,newValue);
    }
    return false;
  },

  inputSelector: function(element,newValue) {
    fields = document.getElementsByName(element.name);
    for (var i=0;i<fields.length;i++){
      if (fields[i].value == newValue){
        fields[i].checked = true;
      }
    }
  },

  textarea: function(element,newValue) {
    element.value = newValue;
  },

  select: function(element,newValue) {
    var value = '', opt, index = element.selectedIndex;
    for (var i=0;i< element.options.length;i++){
      if (element.options[i].value == newValue){
        element.selectedIndex = i;
        return true;
      }        
    }
    return false;
  }
}