/**
 * Prescription rules and validation class
 * 
 * IMPORTANT! Validation relies on options quantity and order, so do not change it
 * 
 * Select options:
 * ---------------
 * validate-usefor - "What do you use your glasses for?"
 *  0 - Single Vision (Everyday Use)
 *  1 - Progressive (Distance & Reading)  (+$90)
 *  2 - Bi-Focal with line (Distance & Reading) (+$70)
 *  3 - Reading
 *  4 - Frames Only
 * validate-lensmaterial - "Lens Material"
 *  0 - Basic Lenses
 *  1 - Our standard optical plastic lenses
 *  2 - Thin Lenses
 *  3 - Thin & Light Polycarbonate Lenses
 *  4 - Extra Thin Lenses 
 * validate-lenscoating - "Eye Protection and Lens Coatings"
 *  0 - Anti-Scratch Coating
 *  1 - UV Coating
 *  2 - Anti-Reflecting Coating
 *  3 - Save $5 - Combine all 3 coatings for only
 * validate-extralensoptions - "Add Extra Lens Options"
 *  0 - No Extras
 *  1 - Transitions Lenses - Light Adjusting - Gray +$110.00
 *  2 - Transitions Lenses - Light Adjusting - Brown +$110.00
 *  3 - Polarized Lenses - Sunglasses - Gray +$70.00
 *  4 - Polarized Lenses - Sunglasses - Brown +$70.00
 *  5 - Polarized Lenses - Sunglasses - Green +$70.00
 *
 * Text options:
 * -------------
 * validate-sph
 * validate-cyl
 * validate-axis
 * validate-add
 * 
 * Moves:
 * "container-left-pd" & "container-right-pd" into "place-for-two-pd"
 * 
 */
var Rules = {

	/**
	 * Initialises prescription rules
	 */
	init : function () {
		Rules.moveTwoPd();
		Rules.applyFalseOptions();
	    Rules.applyValidationRules();
	    Rules.updateNearPdStatus();
	    Rules.updateAxisStatus();
	    Rules.updateAddStatus();
	},
	
	/**
	 * Displays nice alert
	 */
    alert : function (message) {
		Dialog.alert(message, {
			className: "magento",
            width: 400,
            okLabel: "Ok",
            cancelLabel: "No",
            zIndex: 5556,
            showEffect : Element.show,
            hideEffect : Element.hide,
            onOk: function(win){
                return true;
            },
            onCancel: function(win){
                return false;
            }
		});
    },
    
    /**
     * Applies validation rules
     */
    applyValidationRules : function () 
    {
        // SPH (both)
    	$$('.validate-sph').each(function(item, key) {
    		item.observe('change', function(e) {

    			// Signs differs
    			var sphod = $$('.validate-sph')[0].getValue();
    			var sphos = $$('.validate-sph')[1].getValue()
    			if(Rules.isSignsDiffers(sphod, sphos)) {
    				var message = 'You have entered + and - values for your sphere (SPH). For most people the SPH is either Negative (-) or Positive (+) in both eyes. Are you sure your prescription shows both? For help, please contact our customer service. You may also fax your prescription to 888-250-6925.';
    				Rules.alert(message);
    			}

        		// Update lens material status
        		Rules.updateStandardLensesStatus();
    		});
    	});
    	
    	// CYL (both)
    	$$('.validate-cyl').each(function(item, key) {
    		item.observe('change', function(e) {

    			// Signs differs
    			var od = $$('.validate-cyl')[0].getValue();
    			var os = $$('.validate-cyl')[1].getValue()
    			if(Rules.isSignsDiffers(od, os)) {
    				var message = "You have entered + and - values for your Cylinder (CYL). That's Unusual! For most people the Cylinder (CYL) is either Negative (-) or Positive (+). Are you sure your prescription shows both? For help, please contact our customer service. You may also fax your prescription to 888-250-6925.";
    				Rules.alert(message);
    			}    			

    			// CYL is chosen
    			Rules.updateAxisStatus();

        		// Update
    			Rules.updateColorTint();
        		Rules.updateStandardLensesStatus();
        		opConfig.reloadPrice();
    		});    		
    	});
    	
    	// "I have 2 numbers for my PD"
    	$('two-pd-numbers').observe('click', function(){
    		Rules.turnOnTwoPd($('two-pd-numbers').checked);
    	});
        
    	/**
    	 * "Save $5 - Combine all 3 coatings for only"
    	 */
    	$$('.validate-lenscoating')[3].observe('click', function(){
    		Rules.updateLensCoatingStatus();
    	});    	
    	
    	/**
    	 * Click on "What do you use your glasses for?" [usefor]
    	 */ 
    	$$('.validate-usefor').each(function(item, key){
    		item.observe('click', function(){
    			Rules.resetStep2();
    			Rules.updateAllLenses();
    			Rules.updateLensMaterialSelection();
    			Rules.updateAddStatus();
	    		Rules.updateNearPdStatus();
	    		Rules.updateTransitionsAndPolarized();
	    		opConfig.reloadPrice();
    		});
    	});
    	
    	/**
    	 * Click on "Lenses" [lensmaterial]
    	 */
    	$$('.validate-lensmaterial').each(function(item, key){
    		item.observe('click', function(){
    			Rules.updateTransitions();
    			Rules.updateColorTint();
    			Rules.updatePolarizedStatus();
    			opConfig.reloadPrice();
    		});
    	});
    		
    	/**
    	 * Click on "Extra Lens Options:" [extralensoptions]
    	 */
    	$$('.validate-extralensoptions-checkbox').each(function(item, key){
    		item.observe('click', function(){
    			Rules.deselectExtraOptionsExceptThis(item);
    			Rules.updateAllExtraOptionsSelects();
    			Rules.updateAllLenses();
    			opConfig.reloadPrice();
    		});
    	});
    	
//        Rules.alert('Rules is applied!');
    },
    
    /**
     * Updated lens coatings (disable simple coatings when combined chosen) 
     */
    updateLensCoatingStatus : function() {
    	var coating_options = $$('.validate-lenscoating');
    	var combined_coating = coating_options[3];
    	
    	coating_options.each(function(element, key){
    		if(key == 3) {
    			return;
    		}
    		element.checked = false;
    		element.disabled = combined_coating.checked
    	});
    	opConfig.reloadPrice();
    },
    
    /**
     * Updates Axis status
     */
    updateAxisStatus : function () {
    	$$('.validate-cyl').each(function(item, key){
    		if(isNaN(item.getValue())) {
    			$$('.validate-axis')[key].disabled = true;
    			$$('.validate-axis')[key].removeClassName('validate-number');
    			$$('.validate-axis')[key].removeClassName('validation-failed');
    			
        		// If advices displayed
        		if($('advice-validate-number-axisod') || $('advice-validate-number-axisos')) {
    				$('advice-validate-number-axisod').hide();
    				$('advice-validate-number-axisos').hide();
        		}
    		} else {
    			$$('.validate-axis')[key].disabled = false;
    			$$('.validate-axis')[key].addClassName('validate-number');
    		}
    	});
    },
    
    /**
     * Updates lens material (observes SPH and CYL)
     * 
     * Only Basic lenses
     */
    updateStandardLensesStatus : function () {
    	var turnOff = 0;
		
    	// SPH
    	for(var i=0; i < $$('.validate-sph').length; i++) {
			var value = $$('.validate-sph')[i].getValue();
			if(isNaN(value)) {
				continue;
			}
			if(-6 > value) {
				turnOff++;
			}
		}
    	
    	// CYL
    	for(var i=0; i < $$('.validate-cyl').length; i++) {
			var value = $$('.validate-cyl')[i].getValue();
			if(isNaN(value)) {
				continue;
			}
			if((-2.25 >= value) || (2.25 <= value)) {
				turnOff++;
			}
		}
    	
    	// If going to reset Standard Lenses - free other lenses by disabling Color Tint
    	var color_tint = $$('.validate-extralensoptions-checkbox')[2];
    	if(turnOff) {
    		color_tint.checked = false;
    	}
    	
    	Rules.disableElement(color_tint, turnOff);
    	Rules.updateAllExtraOptionsSelects();
		Rules.updateThinLensesStatus();
		Rules.updateThinnestAvailableStatus();
		Rules.updatePolycarbonateStatus();
		Rules.updateSuperThinStatus();

		// Disable standard lenses
    	var lens_materials = $$('.validate-lensmaterial');
    	var message = 'The High Prescription you entered requires a thinner lens than the one selected. Please select Thin Lenses (Hi Index 1.61) or a thinner option';
    	Rules.disableElement(lens_materials[0], turnOff, message, 'lnk_product');
    	Rules.updateLensMaterialSelection();
    	
    	opConfig.reloadPrice();
    },
    
    /**
     * Updates ADD (observes "What do you use your glasses for?")
     */
    updateAddStatus : function() {
    	var length = $$('.validate-usefor').length;
    	var option_singlevision = $$('.validate-usefor')[0];
    	var option_framesonly = $$('.validate-usefor')[length-1];
    	
    	if(option_singlevision.checked || option_framesonly.checked) {
    		$('add-title').hide();
    		$$('.validate-add').each(function(item, key) {
    			item.disabled = true;
    			item.hide();
    		});    		
    	} else {
    		$('add-title').show();
    		$$('.validate-add').each(function(item, key) {
    			item.show();
    			item.disabled = false;
    		});
    	}
    	
//    	var option_progressive = Rules.isChosenProgressive();
//    	var option_bifocal = Rules.isChosenBifocal();

    	if(Rules.isChosenProgressive() || Rules.isChosenBifocal()) {
    		$$('.validate-add').each(function(item, key) {
    			item.addClassName('validate-number');
    		});
    	} else {
    		
    		// If advices displayed
    		if($('advice-validate-number-addod') || $('advice-validate-number-addos')) {
				$('advice-validate-number-addod').hide();
				$('advice-validate-number-addos').hide();
    		}
   		
    		$$('.validate-add').each(function(item, key) {
    			item.removeClassName('validate-number');
    			item.removeClassName('validation-failed');
    		});
    	}
    },
    
    /**
     * Updates Near PD visibility
     * Visible if "Bifocal" and "Progressive" chosen
     */
    updateNearPdStatus : function() {
    	var near_pd_row = $('rules-near-pd');
    	if(Rules.isChosenBifocal() || Rules.isChosenProgressive()) {
    		near_pd_row.show();
    	} else {
    		near_pd_row.hide();
    	}
    },

    /**
     * Moves "Left PD" and "Right PD" near to "Pupillary Distance (PD)"
     * and hides them
     */
    moveTwoPd : function () {
    	if(Rules.isOldVersionPd()) {
    		// alert('no left or right PD found');
    		$('two-pd-numbers-checkbox-container').hide();
    		return;
    	}
    	//$("place-for-two-pd").appendChild($("container-right-pd"));
    	//$("place-for-two-pd").appendChild($("container-left-pd"));
    	//$("place-for-two-pd").hide();
    },
    
    /**
     * Changes: Thin Lenses
     * Depends:
     * - Bifocal
     */
    updateThinLensesStatus : function () {
    	var isDisablingNeeded = Rules.isChosenBifocal();
    	var thinlenses = $$('.validate-lensmaterial')[2];
    	var message = '"Thin Lenses" is not available with this option, please check another lens type';
    	Rules.disableElement(thinlenses, isDisablingNeeded, message);
    	Rules.updateLensMaterialSelection();
    },    
    
    /**
     * Changes: "Thinnest Available (1.74)"
     * Depends on: 
     * "Polarized Lenses (Sunglasses)"
     * "Bi-Focal (Distance & Reading)"
     * "Transition Lenses"
     * "Color Tint"
     */
    updateThinnestAvailableStatus : function () {
    	var isDisablingNeeded = 0;

    	// If "thinnest available" does not even exists
    	if(Rules.isOldVersionLensMaterial()) {
    		return; 
    	}
    	
    	// Bifocal
    	if(Rules.isChosenBifocal()) {
    		isDisablingNeeded++;
    	}
    	
    	// Transition, Polarized or Color Tint
    	if(Rules.isChosenAnyExtra()) {
			isDisablingNeeded++;
    	}
   	
    	// TurnOn
    	var thinnestAvailable = $$('.validate-lensmaterial')[4];
    	var message = '"Thinnest Available" is not available with this option, please check another lens type';
    	Rules.disableElement(thinnestAvailable, isDisablingNeeded, message);
    	Rules.updateLensMaterialSelection();
    },
    
    /**
     * Updates "Polarized Lenses (Sunglasses)"
     * Depends on
     */
    updatePolarizedStatus : function () {
    	var disablingNeeded = Rules.isChosenBifocal() || Rules.isChosenThinnest();
    	var polarized = $$('.validate-extralensoptions-checkbox')[1];
    	
    	Rules.disableElement(polarized, disablingNeeded);
    	Rules.updateAllExtraOptionsSelects();
    },
  
    /**
     * Updates "super thin"  
     */
    updateSuperThinStatus : function () {
    	var superthin = $$('.validate-lensmaterial')[3];
    	var message = '"Extra Thin Lenses" is not available with this option, please check another lens type';
//    	Rules.disableElement(superthin, Rules.isChosenColorTint(), message);
    	Rules.updateLensMaterialSelection();
    },
    
    /**
     * Changes: "Thin & Light Polycarbonate Lenses" status
     * 
     * Depends on:
     * - Bifocal
     * - Color Tint
     * - Transition
     */
    updatePolycarbonateStatus : function() {
    	var isDisablingNeeded = 0;
    	
    	// If no polycarbonate
    	if(Rules.isOldVersionLensMaterial()) {
    		return;
    	}

    	// Bifocal
    	if(Rules.isChosenBifocal()) {
    		isDisablingNeeded++;
    	}

    	// Transition(1,2)
    	if(Rules.isChosenTransition()) {
    		isDisablingNeeded++;    		
    	}
    	
    	// Color Tint(6,7,8)
    	/*
    	if(Rules.isChosenColorTint()) {
    		isDisablingNeeded++;    		
    	}
    	*/
    	var polycarbonate = $$('.validate-lensmaterial')[1];
    	var message = '"Thin & Light Polycarbonate Lenses" is not available with this option, please check another lens type';
    	Rules.disableElement(polycarbonate, isDisablingNeeded, message);
    	Rules.updateLensMaterialSelection();
    },

    /**
     * Disables/Enables transitions and polarized
     * Observes: "Bifocal"
     */
    updateTransitionsAndPolarized : function () {
    	var isDisablingNeeded = Rules.isChosenBifocal();
    	var extraOptions = $$('.validate-extralensoptions-checkbox');
    	var transitions_number = 0;
    	var polarized_number = 1;
    	
    	extraOptions[transitions_number].checked = false;
		Rules.disableElement(extraOptions[transitions_number], isDisablingNeeded);
		
		extraOptions[polarized_number].checked = false;
		Rules.disableElement(extraOptions[polarized_number], isDisablingNeeded);
		
		Rules.updateAllExtraOptionsSelects();
    },
    
    /**
     * Updates Transitions option
     */
    updateTransitions : function () {
    	var transitions = $$('.validate-extralensoptions-checkbox')[0];
    	var isDisablingNeeded = Rules.isChosenBifocal() || Rules.isChosenThinNLight() || Rules.isChosenThinnest();
    	
    	Rules.disableElement(transitions, isDisablingNeeded);
    	Rules.updateAllExtraOptionsSelects();
    },
    
    /**
     * Updates Color Tint option
     */
    updateColorTint : function () {
    	var isDisablingNeeded = 0;

    	// If any lens-material except Standard lenses chosen
    	$$('.validate-lensmaterial').each(function(item, key){
    		// Skip basic, thin, super thin lenses
    		if((key==0) || (key==1) || (key==2) || (key==3) ){
    			return;
    		}
    		if(item.checked) {
    			isDisablingNeeded++;
    		}
    	});
    	
    	// SPH < -6
    	for(var i=0; i < $$('.validate-sph').length; i++) {
			var value = $$('.validate-sph')[i].getValue();
			if(isNaN(value)) {
				continue;
			}
			if(-6 > value) {
				isDisablingNeeded++;
			}
		}
    	
    	// CYL not in [-2.25; 2.25]
    	for(var i=0; i < $$('.validate-cyl').length; i++) {
			var value = $$('.validate-cyl')[i].getValue();
			if(isNaN(value)) {
				continue;
			}
			if((-2.25 >= value) || (2.25 <= value)) {
				isDisablingNeeded++;
			}
		}      	
    	
    	var tint_number = 2;
    	Rules.disableElement($$('.validate-extralensoptions-checkbox')[tint_number], isDisablingNeeded);

    },
    
    updateAllLenses : function () {
		Rules.updateStandardLensesStatus();
		Rules.updatePolycarbonateStatus();
		Rules.updateThinLensesStatus();
		Rules.updateSuperThinStatus();
		Rules.updateThinnestAvailableStatus();
    },
    
    updateAllExtraOptionsSelects : function (){
    	var check = $$('.rules-extra-lens-option-item input');
    	var sel = $$('.rules-extra-lens-option-item select');
    	check.each(function(item, key){
    		if((!check[key].checked || check[key].disabled)){
    			Rules._disableFoxyDropdown(sel[key], true);
    		} else {
    			Rules._disableFoxyDropdown(sel[key], false);
    		}
    	});
    	opConfig.reloadPrice();
    },
    
    /**
     * Disables 
     */
    _disableFoxyDropdown : function (dropdown, disablingNeeded) {
    	var first_option = dropdown.options[0];
		var false_option = document.createElement("OPTION");
		false_option.value = '';
		false_option.text = first_option.text;

    	if(disablingNeeded) {
    		
    		// If already disabled
    		if(dropdown.disabled) {
    			return;
			}
    		
        	// Add false-option (that looks like a currently selected option)
    		dropdown.options.add(false_option);
    		
    		// Choose our false-option
    		dropdown.options.selectedIndex = dropdown.options.length - 1;
    		
    		// Disable
    		dropdown.disabled = true;
    	} else {
    		
    		// If already enabled
    		if(!dropdown.disabled) {
    			return;
			}
    		
    		// Remove false-option
    		dropdown.remove(dropdown.options.length - 1);
    		
    		// Enable
    		dropdown.disabled = false;
    	}

    },
    
    /**
     * Applies foxy dropdowns
     */
    applyFalseOptions : function () {
    	$$('.rules-foxy-dropdown').each(function(item, key) {
    		Rules._disableFoxyDropdown(item, true);
    	});
    },
    
//    _addFalseOption : function (select) {
//    	select.options.selectedIndex
//    },
    
    /**
     * Updates select list of extra option
     * observes checkbox
     */
    updateExtraOptionsSelect : function (number) {
    	var check = $$('.rules-extra-lens-option-item input')[number];
    	var sel = $$('.rules-extra-lens-option-item select')[number];
		var disablingNeeded = !check.checked || check.disabled ;
		
		Rules._disableFoxyDropdown(sel, disablingNeeded);
		opConfig.reloadPrice();
	},
	
	/**
	 * Deselect other options to
	 */
	deselectExtraOptionsExceptThis : function (checkbox) {
		var checked_value = checkbox.value;
		var extras = $$('.validate-extralensoptions-checkbox');
		extras.each(function(item, key){
			if(item.value != checked_value) {
				item.checked = false;
			}
		});
	},

    /**
     * Returns true if any of extra lens options is chosen (Transitions, Polarized, Tint)
     */
    isChosenAnyExtra : function () {
    	var elements = $$('.validate-extralensoptions-checkbox');
    	for(var i=0; i < elements.length; i++) {
    		if(elements[i].checked){
    			return true;
    		}
    	}
    	return false;
    },

    /**
     * Return true if "Thin&Light" option is chosen
     */
    isChosenThinNLight : function () {
    	var thinNLight = $$('.validate-lensmaterial')[1];
		return thinNLight.checked;
    },
    
	/**
	 * Return true if "Thinnest available" options is chosen
	 */
	isChosenThinnest : function () {
    	var thinnest = $$('.validate-lensmaterial')[4];
		return thinnest.checked;
	},
	
    /**
     * Returns true if "Transitions" chosen
     */
    isChosenTransition : function() {
    	var transitions = $$('.validate-extralensoptions-checkbox')[0];
    	return transitions.checked;
    },
    
    /**
     * Returns true if "Bifocal" lenses chosen
     */
    isChosenBifocal : function () {
    	if(Rules.isOldVersionUseFor()) {
    		return false;
    	}
    	return $$('.validate-usefor')[2].checked;
    },
    
    /**
     * Returns true if "Progressive" chosen
     */
    isChosenProgressive : function () {
    	if(Rules.isOldVersionUseFor()) {
    		return false;
    	}    	
    	return $$('.validate-usefor')[1].checked;
    },
    
    /**
     * Returns true if "Color Tint" chosen
     */
    isChosenColorTint : function () {
    	if(Rules.isOldVersionExtraLensOptions()) {
    		return false;
    	}
    	
    	// Color Tint
    	var colorTint = $$('.validate-extralensoptions-checkbox')[2];
    	if(colorTint.checked) {
    		return true;
    	}
    	return false;
    },
    
    /**
     * Resets "lens-material" and "lens-extras" options 
     * when 'use-for' changed
     */
    resetStep2 : function () {
    	var lensMaterial = $$('.validate-lensmaterial');
    	var lensExtras = $$('.validate-extralensoptions-checkbox');
    	
    	lensMaterial.each(function(item, key){
    		Rules.disableElement(item, 0);
    	});
    	Rules.updateLensMaterialSelection();
    	
    	lensExtras.each(function(item, key){
    		item.checked = false;
    		Rules.disableElement(item, 0)
    	});
    	
    	Rules.updateAllExtraOptionsSelects();
    },
    
    /**
     * Disable specified element
     * 
     * @param HTMLELement element to disable
     * @param bool true if disable, false if enable
     * @param string message message to display if disabled option was checked
     */
    disableElement : function (element, disable, message, scrollTo) {
    	if(disable) {
    		
    		// If already disabled
	    	if(element.disabled) {
	    		return;
	    	}
	    	
	    	// If checked
	    	if(element.checked) {
	    		if(message) {
	    			Rules.alert(message);
	    		}
	    		if(scrollTo) {
	    			Effect.ScrollTo(scrollTo, { duration: 0.8 });
	    		}
	    		
	    		element.checked = false;
	    	}
	    	element.disabled = true;
	    	$(element.parentNode).addClassName('disabled');
    	} else {
    		element.disabled = false;
    		$(element.parentNode).removeClassName('disabled');
    	}
    },
    
    /**
     * Select first available "Lenses"
     */
    updateLensMaterialSelection : function() {
    	var elements = $$('.validate-lensmaterial');
    	var isSelectionMade = false;
    	var firstAvailable = 0;
    	var firstAvailableFound = false;
    	var isAnyChecked = 0;    	

    	// Thin #2, Standard #0, Super thin #3
    	var priority = new Array(0, 2, 3, 1, 4);
    	priority.each(function (item, key) {
    		// Skip disabled
    		if(elements[item].disabled) {
    			return;
    		}
    		
    		// Any checked
    		if(elements[item].checked) {
    			isAnyChecked = 1;
    			return;
    		}

    		// If first avaialable already found
			if(firstAvailableFound) {
				return;
			}
			
			firstAvailable = item;
			firstAvailableFound = 1;
    	});

    	// If any option is already checked - no action
    	if(isAnyChecked) {
    		return;
    	}
    	
    	// Check first available
    	elements[firstAvailable].checked = true;
    	},
//    	return;
//    	

//    	
//    	for(i=0; i < elements.length; i++) {
//    		// Skip disabled
//    		if(elements[i].disabled) {
//    			continue;
//    		}
//    		
//    		// Remember first available option
//    		if(!firstAvailableFound) {
//    			firstAvailable = i;
//    			firstAvailableFound = true;
//    		}
//    		
//    		// Count selected
//    		if(elements[i].checked) {
//    			isSelectionMade++;
//    		}
//    	};
//    	
//    	// If no selection - select first available
//    	if(!isSelectionMade) {
//    		elements[firstAvailable].checked = true;
//    	}
//    },
    
    /**
     * Turns two PDs on 
     */
    turnOnTwoPd : function (turnOn) {
    	if(Rules.isOldVersionPd()) {
    		return;
    	}    	
    	
    	var one_pd_block = $('one-pd-block');
    	var two_pd_block = $('place-for-two-pd');
    	
    	if(turnOn) {
    		one_pd_block.hide();
    		two_pd_block.show();
    	} else {
    		one_pd_block.show();
    		two_pd_block.hide();
    	}
    },
    
    /**
     * Checks is elements values sing differs from each other
     */
    isSignsDiffers : function (val1, val2) {
		if(isNaN(val1) || isNaN(val2)) {
			return false;
		}
		if(0 > (parseFloat(val1) * parseFloat(val2))) {
			return true;
		}
		return false;    	
    },
    
    /**
     * Returns true if found any old version of 
     */
    isOldVersion : function () {
    	return Rules.isOldVersionUseFor() || Rules.isOldVersionPd() || Rules.isOldVersionLensMaterial() || Rules.isOldVersionExtraLensOptions();  
    },
    
    /**
     * Return true if old version of "What do you use your glasses for" detected
     */
    isOldVersionUseFor : function () {
    	return (5 > $$('.validate-usefor').length); 
    },
    
    /**
     * Returns true if old version of "Lens Material" (or just "Lens:")
     */
    isOldVersionLensMaterial : function () {
    	return (5 > $$('.validate-lensmaterial').length);
    },
    
    /**
     * Returns true if old version of "Extra Lens Options" detected (No "color tint" detected)
     */
    isOldVersionExtraLensOptions : function () {
    	return (3 > $$('.validate-extralensoptions-checkbox').length);
    },
    
    /**
     * Returns true if old version of "I have 2 PD" detected
     */
    isOldVersionPd : function () {
    	return (!$("container-left-pd") && !$("container-right-pd"));
    },

    /**
     * Returns true if any of SHP or CYL is number 
     */
    isPrescriptionFormTouched : function() {
    	var sph = $$('.validate-sph');
    	var cyl = $$('.validate-cyl');
    	
//    	return !isNaN(sph[0].getValue()) || !isNaN(sph[1].getValue()) || !isNaN(cyl[0].getValue()) || !isNaN(cyl[1].getValue());
    	return !isNaN(sph[0].getValue()) || !isNaN(sph[1].getValue());
    },
    
    /**
     * Returns true if all prescription fields are filled
     */
    isPrescriptionFormFilled : function() {
    	var sph = $$('.validate-sph');
    	var cyl = $$('.validate-cyl');
    	
//    	return !isNaN(sph[0].getValue()) && !isNaN(sph[1].getValue()) && !isNaN(cyl[0].getValue()) && !isNaN(cyl[1].getValue());    	
    	return !isNaN(sph[0].getValue()) && !isNaN(sph[1].getValue());    	
    },

	/**
	 * Adds requirements to prescription page
	 */
	addRequirements : function(turnOn) {
    	var sph = $$('.validate-sph'); // .validate-sph .validate-number
    	//var cyl = $$('.validate-cyl'); // .validate-cyl .validate-number
    	//var add = $$('.validate-add'); // .validate-add .validate-number
    	//var axi = $$('.validate-axis'); // .validate-axis .validate-number
    	
		// #two-pd-numbers
		var validate = 'validate-number';
		if(turnOn){
			sph[0].addClassName(validate);
			sph[1].addClassName(validate);
		} else {
			sph[0].removeClassName(validate);
			sph[1].removeClassName(validate);
		}
		Validation.validate(sph[0]);
		Validation.validate(sph[1]);
	},    
    
    /**
     * Checks prescription
     * 
     * @return bool true validation should be halted, false otherwise
     * @todo Simplify logic?:)
     */
    checkPrescription : function() 
    {
    	var isChecked = $('option-prescription-online').checked;
    	var isPrescriptionFormTouched = Rules.isPrescriptionFormTouched();
    	var isPrescriptionFormFilled = Rules.isPrescriptionFormFilled();
    	
    	// If ("Fill prescription online" not checked) OR (prescription filled ok) - remove any requirements and let form be submited
    	if(!isChecked || isPrescriptionFormFilled){
    		Rules.addRequirements(false);
    		return false;
    	}
    	
    	// If form not completed
		var question = 'You have not provided complete prescription. Proceed to checkout anyway?'
		var addRequirementsFlag = true;		
    	var haltValidationFlag = false;    	
    	
    	// If form even untouched
    	if(!isPrescriptionFormTouched) {
        	question = 'You have not provided a prescription. Proceed to checkout anyway?';
        	addRequirementsFlag = false;
        	haltValidationFlag = true;
    	}
    	
    	// If pressed OK - submit form
    	if(confirm(question)) {
    		Rules.addRequirements(false);
    		return false;
    	}
    	//alert('required=' + addRequirementsFlag + ';haltNeeded=' + haltValidationFlag);
		Rules.addRequirements(addRequirementsFlag);
		return haltValidationFlag;
    }
};

/**
 * Run section
 */

// Apply rules for just loaded page
Event.observe(window, 'load', function() {
	Rules.init();
	opConfig.reloadPrice();
});
