﻿$(document).ready(function() {
    $('#btnCalcSpeed').click(function() {
        setSpeedValues($('#txtWindSpeed').val());
    });

    $('#btnCalcChill').click(function() {
        var result = windchill($('#txtMS').val(), $('#txtCelsius').val());
        $('#lblChillResult').text(Math.round(result) + " °C");
    });
});

function setSpeedValues(speed) {
    $('#kmh').text(msToKmh(speed).toFixed(1));
    $('#knot').text(msToKnot(speed).toFixed(1));
    $('#mih').text(msToMih(speed).toFixed(1));
    $('#bea').text(msToBea(speed));
}

/********** convertion functions *******/

function msToKmh(ms) {
    if (ms < 0)
        return 0;
    else
        return ms * 3.6;
}

function msToKnot(ms) {
    if (ms < 0)
        return 0;
    else
        return ms * 1.9438444924406;
}

function msToMih(ms) {
    if (ms < 0)
        return 0;
    else
        return ms * 2.2369362920544;
}

function msToBea(ms) {
    if (ms < 0.3) return 0;
    else if (ms < 1.5) return 1;
    else if (ms < 3.3) return 2;
    else if (ms <5.5) return 3;
    else if (ms < 8) return 4;
    else if (ms < 11) return 5;
    else if (ms < 14) return 6;
    else if (ms < 17) return 7;
    else if (ms < 20) return 8;
    else if (ms < 24) return 9;
    else if (ms < 28) return 10;
    else if (ms <= 32) return 11;
    else if (ms > 32) return 12;
}

function windchill(wind, temp)
{
    var calculate=1;
    var t=0;
    var w=0;
    var chill=0;
    
    if (wind.length===0){
        calculate=0;
    }
    var comRGX=/,/g;
    
    wind=wind.replace(comRGX,".");
    
    if(isNaN(wind)===true){
        calculate=0;
    }

    if(wind.substring(wind.length-1,wind.length)==".")
    {
        return;
    }
    
    if(wind<1){
        calculate=0;
    }
    wind=(wind*3.6);
    
    if(temp.length===0){
        calculate=0;
    }
    comRGX=/,/g;
    temp=temp.replace(comRGX,".");
    
    if(isNaN(temp)===true){
        calculate=0;
    }
    
    if(temp.substring(temp.length-1,temp.length)=="."){
        return;
    }
    
    if(calculate==1){
        t=eval(temp)*1;
        w=eval(wind)*1;
        chill=(13.12+0.6215*t-11.37*Math.pow(w,0.16)+0.3965*t*Math.pow(w,0.16));
        chill=Math.round(chill);
        return chill;
    } else {
        return "-";
    }
}

/*
function windchill(wind, temp) {
    wind = wind * 3.6;

    chill = (13.12 + 0.6215 * temp - 11.37 * Math.pow(wind, 0.16) + 0.3965 * temp * Math.pow(wind, 0.16));
    chill = Math.round(chill);
    if ((wind < 5) || (wind > 100) || (temp < -70) || (temp > 5)) {
        return temp;
    }
    else {
        return chill;
    }
}
*/