// Copyright (C) 2005  Chris Halstead
//
// chris.halstead [at] gmail.com
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// The full text of the GPL is available at http://www.gnu.org/copyleft/gpl.html
//

function getGearData() {
    var httpRequestObject;
    httpRequestObject = getHTTPObject();
    httpRequestObject.open("GET", gearDataURL, true);
    httpRequestObject.onreadystatechange = function () {
        if ( httpRequestObject.readyState == 4 ) {
            var dataLines = httpRequestObject.responseText.split("\n");
            for (var i = 0; i < dataLines.length; i++ ) {
                var dataLine = dataLines[i].split("|");
                if ( dataLine[0].charAt(0) != "#" ) {
                    addOption(dataLine[0], dataLine[1]);
                }
            }
        }
    };
    httpRequestObject.send(null)
}

function addOption(optionText, optionValue) {
    var o = document.forms['preSelectedSets'].vehicleList;
    if ( !hasOptions(o)) {
        var index = 0;
    }
    else {
        var index=o.options.length;
    }
    o.options[index] = new Option( optionText, optionValue, false, false);
    o.selectedIndex = 0;
}

function hasOptions(obj) {
   var hasOptions = false;
   if ( obj != null && obj.options != null ) {
       hasOptions = true;
   }
   return hasOptions;
}

function handlePreselectOnChange() {
    var selectIndex = document.preSelectedSets.vehicleList.options.selectedIndex;
    if ( selectIndex > 1 ) {
        updateRatioList( document.preSelectedSets.vehicleList.options[selectIndex].value )
    }
    else {
        document.preSelectedSets.vehicleList.options.selectedIndex = 0;
        updateRatioList( defaultData );
    }
}

function updateRatioList(data) {
    hideElement( 'results' );
    var dataArray = data.split( ":" );
    document.ratiosForm.REAR_RATIO.value   = dataArray[0];
    document.ratiosForm.REDLINE.value      = dataArray[1];
    document.ratiosForm.TIRE_WIDTH.value   = dataArray[2];
    document.ratiosForm.ASPECT_RATIO.value = dataArray[3];
    document.ratiosForm.WHEEL_SIZE.value   = dataArray[4];
    document.ratiosForm.FIRST_GEAR.value   = dataArray[5];
    document.ratiosForm.SECOND_GEAR.value  = dataArray[6];
    document.ratiosForm.THIRD_GEAR.value   = dataArray[7];
    document.ratiosForm.FOURTH_GEAR.value  = dataArray[8];
    document.ratiosForm.FIFTH_GEAR.value   = dataArray[9];
    document.ratiosForm.SIXTH_GEAR.value   = dataArray[10];
    document.ratiosForm.SEVENTH_GEAR.value = dataArray[11];
    document.ratiosForm.TIRE_DIAMETER.disabled = true;
    document.ratiosForm.USE_TIRE_DIAMETER.checked = false;
    document.ratiosForm.TIRE_WIDTH.disabled = false;
    document.ratiosForm.ASPECT_RATIO.disabled = false;
    document.ratiosForm.WHEEL_SIZE.disabled = false;
    updateTireDiameter();
}

function updateTireDiameter() {
    document.ratiosForm.TIRE_DIAMETER.value = ( ( Math.round( ( ( ( parseInt(document.ratiosForm.WHEEL_SIZE.value) * in2mm ) + ( ( parseInt(document.ratiosForm.TIRE_WIDTH.value) ) * ( ( parseInt(document.ratiosForm.ASPECT_RATIO.value) / 100 ) * 2 ) ) ) * mm2in ) * 10 ) ).toFixed(2) / 10 );
}

function hideElement(el) {
    if (document.getElementById(el).style.display != 'none') {
        document.getElementById(el).style.display = 'none';
    }
}

function showElement(el) {
    if (document.getElementById(el).style.display != 'block') {
        document.getElementById(el).style.display = 'block';
    }
}


function count_gears() {
    for (var gear = 0; gear < 7; gear++) {
        var gear_value = parseFloat(document.ratiosForm[gear_array[gear]].value);
        if ( !parseFloat(gear_value) )  { return gear; }
    }
    return gear++;
}

function computeMPH(gearName, rpm, revsPerMile) {
    return ( ( ( ( 1 / ( ( parseFloat(document.ratiosForm[gearName].value) ) * parseFloat( document.ratiosForm.REAR_RATIO.value ) ) ) / revsPerMile ) * 60 ) * rpm );
}

function doHeaderRow(theTable, numGears) {
    trElem = theTable.insertRow(theTable.rows.length);
    trElem.className = "headerRow";
    tdElem = trElem.insertCell(trElem.cells.length);
    tdElem.className = "headerCell";
    tdElem.width = rpm_col_width;
    tdElem.align = "center";
    tdElem.innerHTML = "RPM";
    for (i = 0; i < numGears; i++) {
        tdElem = trElem.insertCell(trElem.cells.length);
        tdElem.className = "headerCell";
        tdElem.align = "center";
        tdElem.width = gear_col_width;
        tdElem.innerHTML = gear_names[i];
    }
}

function calculateSpeeds() {
    var tbodyElem = document.getElementById("resultTableBody");
    var rpm_step = parseInt(document.ratiosForm.RPM_STEP.value);
    var redline = parseInt(document.ratiosForm.REDLINE.value);
    var numGears = count_gears();
    var revs_per_mile = 0;
    if ( document.ratiosForm.USE_TIRE_DIAMETER.checked ) {
        revs_per_mile = ( inches_in_mile / ( ( parseFloat(document.ratiosForm.TIRE_DIAMETER.value) * pi ) * fudge ) );
    } else {
        revs_per_mile = ( inches_in_mile / ( ( ( ( ( parseInt(document.ratiosForm.WHEEL_SIZE.value) * in2mm ) + ( ( ( parseInt(document.ratiosForm.ASPECT_RATIO.value) / 100 ) * 2 ) * parseInt(document.ratiosForm.TIRE_WIDTH.value) ) ) * pi ) * mm2in ) * fudge ) );
    }
    var trElem;
    var tdElem;
    var mod = 0;
    var col = 0;
    var rpm = rpm_step;
    var loop = 1;
    clearTable('resultTableBody');
    doHeaderRow(tbodyElem, numGears);
    while ( loop == 1 ) {
        if ( rpm >= redline) { rpm = redline; loop = 0; }
        trElem = tbodyElem.insertRow( tbodyElem.rows.length );
        trElem.className = "gearDetailLine" + ( mod % 2 );
        mod++;
        // RPM column
        tdElem = trElem.insertCell( trElem.cells.length );
        tdElem.className = "RPMCol";
        tdElem.align = "center";
        tdElem.innerHTML = rpm;
        // Gear columns
        for ( i = 0; i < numGears; i++ ) {
            tdElem = trElem.insertCell( trElem.cells.length );
            tdElem.className = "col_" + gear_array[i];
            tdElem.align = "center";
            tdElem.innerHTML = ( Math.round( computeMPH( gear_array[i], rpm, revs_per_mile ) * 10 ) / 10 ).toFixed(1);
        }
        rpm += rpm_step;
    }
    showElement('results');
}

function clearTable(tableBodyName) {
    var tbodyElem = document.getElementById( tableBodyName );
    for ( var i = ( tbodyElem.rows.length - 1 ); i > -1; i-- ) {
        tbodyElem.deleteRow( i );
    }
}

function toggleTireSpecs() {
    if ( document.ratiosForm.USE_TIRE_DIAMETER.checked ) {
                document.ratiosForm.TIRE_WIDTH.disabled = true;
                document.ratiosForm.ASPECT_RATIO.disabled = true;
                document.ratiosForm.WHEEL_SIZE.disabled = true;
                document.ratiosForm.TIRE_DIAMETER.disabled = false;
    } else {
                document.ratiosForm.TIRE_WIDTH.disabled = false;
                document.ratiosForm.ASPECT_RATIO.disabled = false;
                document.ratiosForm.WHEEL_SIZE.disabled = false;
                document.ratiosForm.TIRE_DIAMETER.disabled = true;
    }
}

function toggleFudge() {
    if ( document.ratiosForm.USE_FUDGE.checked ) {
        fudge = .965;
    } else {
        fudge = 1;
    }
}

