﻿var HeightConversion = new Class({
    initialize: function(txtFeet, txtInches, txtCentimetres) {
        this.txtFeet = $(txtFeet);
        this.txtInches = $(txtInches);
        this.txtCentimetres = $(txtCentimetres);
        this.addEvents();
    },
    
    addEvents: function() {
        this.txtFeet.addEvent('change', function() { this.convertFromImperial(); }.bind(this));
        this.txtInches.addEvent('change', function() { this.convertFromImperial(); }.bind(this));
        this.txtCentimetres.addEvent('change', function() { this.convertFromMetric(); }.bind(this));
    },
    
    convertFromImperial: function() {
        var feet = this.txtFeet.value.length == 0 ? 0 : parseInt(this.txtFeet.value);
        var inches = this.txtInches.value.length == 0 ? 0 : parseInt(this.txtInches.value);
        if (isNaN(feet) || isNaN(inches))
            alert('Invalid height');
        else if (feet == 0)
            this.txtCentimetres.value = '';
        else
            this.txtCentimetres.value = Math.round((feet * 12 + inches) * 2.54);
    },
    
    convertFromMetric: function() {
        var cm = this.txtCentimetres.value.length == 0 ? 0 : parseInt(this.txtCentimetres.value);
        if (isNaN(cm))
            alert('Invalid height');
        else if (cm == 0)
            this.txtFeet.value = this.txtInches.value = '';
        else {
            var inches = Math.round(cm / 2.54);
            var feet = Math.round(inches / 12);
            this.txtFeet.value = feet;
            this.txtInches.value = (inches - (feet * 12));
        }
    }
});

var WeightConversion = new Class({
    initialize: function(txtLbs, txtKgs) {
        this.txtLbs = $(txtLbs);
        this.txtKgs = $(txtKgs);
        this.addEvents();
    },
    
    addEvents: function() {
        this.txtLbs.addEvent('change', function() { this.convertFromImperial(); }.bind(this));
        this.txtKgs.addEvent('change', function() { this.convertFromMetric(); }.bind(this));
    },
    
    convertFromImperial: function() {
        var lbs = this.txtLbs.value.length == 0 ? 0 : parseInt(this.txtLbs.value);
        if (isNaN(lbs))
            alert('Invalid weight');
        else if (lbs == 0)
            this.txtKgs.value = '';
        else
            this.txtKgs.value = Math.round(lbs / 2.20462262);
    },
    
    convertFromMetric: function() {
        var kgs = this.txtKgs.value.length == 0 ? 0 : parseInt(this.txtKgs.value);
        if (isNaN(kgs))
            alert('Invalid weight');
        else if (kgs == 0)
            this.txtLbs.value = '';
        else
            this.txtLbs.value = Math.round(kgs * 2.20462262);
    }
});
