/* 
$HACHeader: HAC_CalcConvert.js 115.HAC.1 2008/08/17  $
 +=========================================================================
 | COPYRIGHT
 |  2008 Hafele America Co.  All Rights Reserved. No unauthorized
 | 	duplication or re-use. 
 |
 | FILE
 |   HAC_CalcConvert.js
 |
 | DESCRIPTION
 |   This file contains javascript that supports the functionality of the Tape
 |   Measure Converter
 |
 | HISTORY
 |  Version         Date         Changed by      Description
 |  115.HAC.1       2008/08/15   SREECE          Creation of file.
  +=======================================================================*/


function ValidateEntry(e){

    var s1 = new String(document.frmCalc.numToConv.value);
    var retVal = false;
    var key;
    var keychar;


    //set key values
    if(window.event) {
        key = e.keyCode;
        isCtrl = window.event.ctrlKey
    }
    else if(e.which) {
        key = e.which;
        isCtrl = e.ctrlKey;
    }

    if (e.keyCode == 13){
        CalcConvert(document.frmCalc.numToConv.value);
    }

    //" (inches) Has to be last char in string
    //OR next to last is a c or m
    //ie. 5' 3 1/2"
    if ((s1.charCodeAt(s1.length - 1) == 34) || (s1.charCodeAt(s1.length - 2) == 99) || (s1.charCodeAt(s1.length - 2) == 109)){
        //a "  OR cm OR mm has been entered => end of entry so cancel
        return false;
    }
    //alert("1");

    if ((s1.indexOf("/") < s1.indexOf("'")) && !(s1.indexOf("/") <= 0)){
        //a ' has already been entered with a / (fraction) so cancel
        return false;
    }

    //alert("3 - Key code: " + key);


    //get character...
    keychar = String.fromCharCode(key);

    // check for backspace or delete, or if Ctrl was pressed
    if (key == 8 || isCtrl)
    {
        return true;
    }

    //alert("4");


    //is entry a ' (single quote - feet symbol)
    if (key == 39){
        //key is '
        //auto insert a space
        if (s1.indexOf("'") > 0){
            //a ' has already been entered so cancel
            return false;
        }

        //a number must come before the '
        if (!((s1.charCodeAt(s1.length - 1) > 47) && (s1.charCodeAt(s1.length - 1) < 58))){
            //prev char not a number so cancel
            return false;
        }

        //otherwise insert ' with a space
        s1 += "' ";

        //alert("4.5" + s1);

        document.frmCalc.numToConv.value = s1;
        return false;
    }

    //is entry a " (double quote - inches symbol)
    if (key == 34){
        //key is "
        //Has to be last char in string
        //ie. 5' 3 1/2"
        if (s1.indexOf('"') > 0){
            //a " has already been entered so cancel
            return false;
        }

        //a number must come before the "
        if (!((s1.charCodeAt(s1.length - 1) > 47) && (s1.charCodeAt(s1.length - 1) < 58))){
            //prev char not a number so cancel
            return false;
        }

        s1 += '"';
        document.frmCalc.numToConv.value = s1;
        return false;
    }

    //is entry a / (forward slash - indicates a fraction)
    //OR is entry a . (period)
    if ((key == 47) || (key == 46)){
        //key is /  OR .
        //Has to be after a number and a number must follow
        //Also the . (period) should not exist in string
        //ie. 5' 3 1/2"
        //ie. 5' 3 1.5"
        if (s1.indexOf('/') >= 0){
            //a / has already been entered so cancel
            //OR a . (period) has been entered so cancel
            return false;
        }
        if (s1.indexOf('.') >= 0){
            //a / has already been entered so cancel
            //OR a . (period) has been entered so cancel
            return false;
        }

        //a number must come before the slash
        if ((key == 47) && !((s1.charCodeAt(s1.length - 1) > 47) && (s1.charCodeAt(s1.length - 1) < 58))){
            //prev char not a number so cancel
            return false;
        }
        //The . (period) must be first OR come after a number OR after a space
        if ((key == 46) && !((s1.charCodeAt(s1.length - 1) > 47) && (s1.charCodeAt(s1.length - 1) < 58))){
            //is prev char a space
            if (s1.charCodeAt(s1.length - 1) == 32){
                return true;
            }

            //prev char not a number so check if first position
            if (!(s1.length == 0)){
                return false;
            }
        }

        return true;
    }


    //is entry a space
    if ((key == 32)){
        //do not allow double space
        if ((s1.charCodeAt(s1.length - 1) == 32)){
            return false;
        }

        //a number or a ' (foot) must come before the space
        if (!((s1.charCodeAt(s1.length - 1) > 47) && (s1.charCodeAt(s1.length - 1) < 58)) && !((s1.charCodeAt(s1.length - 1) == 39))){
            //prev char not a number OR ' so cancel
            return false;
        }

        //If a decimal has been entered then cancel
        if (s1.indexOf('.') >= 0){
            return false;
        }
        //If a / (slash) has been entered then cancel
        if (s1.indexOf('/') >= 0){
            return false;
        }

        //allow space
        return true;
    }

    //is entry a number...
    if ((key > 47) && (key < 58)){
        if ((s1.charCodeAt(s1.length - 1) == 109) || (s1.charCodeAt(s1.length - 1) == 99)){
            return false;
        }
        return true;
    }

    //is key a c (cm) OR C
    if (key == 99 || key == 67){
        //has ' (foot) OR " (inches) been entered
        if ((s1.indexOf('"') >= 0) || (s1.indexOf("'") >= 0)){
            return false;
        }

        //a number must come before the c
        if (!((s1.charCodeAt(s1.length - 1) > 47) && (s1.charCodeAt(s1.length - 1) < 58))){
            //prev char not a number so cancel
            return false;
        }

        s1 += 'cm';
        document.frmCalc.numToConv.value = s1;
        return false;
    }

    //is key a m (meter) OR M
    if (key == 109 || key == 77){
        //has ' (foot) OR " (inches) been entered
        if ((s1.indexOf('"') >= 0) || (s1.indexOf("'") >= 0)){
            return false;
        }

        //is length > 0
        if (s1.length <= 0){
            return false;
        }
        if ((s1.charCodeAt(s1.length - 2) == 99) || (s1.charCodeAt(s1.length - 2) == 109)){
            return false;
        }
        //is prev char a m or c
        if ((s1.charCodeAt(s1.length - 1) == 109) || (s1.charCodeAt(s1.length - 1) == 99)){
            //add another m and cancel
            s1 += 'm';
            document.frmCalc.numToConv.value = s1;
            return false;
        }

        //is prev char a number
        if ((s1.charCodeAt(s1.length - 1) > 47) && (s1.charCodeAt(s1.length - 1) < 58)){
            //prev char IS a number so add an m and cancel
            s1 += 'm';
            document.frmCalc.numToConv.value = s1;
            return false;
        }
    }


    return retVal;
}


function CalcConvert(strValue){
    //This function takes a string representing a measurment in inches/feet or metric and converts
    //the value to the opposite type from the input type.  ie. if metric input then standard output.

    var strChar = "";
    var strInputQty = "";
    var intNumerator = 0/*Replaced*/;
    var strFromUOM = "";
    var intMetricQty = 0/*Replaced*/;
    var intInches = 0/*Replaced*/;
    var intDenominator = 0/*Replaced*/;
    var strMetricInput = "Y";
    var intMultiplier = 0.0393700787;
    var intDecimalValue = 0;
    var strMetricApprox = ""/*Replaced*/;
    var strMetricUOM = "mm";
    var intFEET = 0/*Replaced*/;
    var strCharValue = ""/*Replaced*/;
    var strCharStandard = ""/*Replaced*/;
    var strCharDecimal = ""/*Replaced*/;
    var strCharFraction = ""/*Replaced*/;
    var strInchSymbol = ""/*Replaced*/;
    var strStandardApprox = ""/*Replaced*/;
    var strCharMetric = ""/*Replaced*/;

    try{
        for (var i=0;  i<strValue.length; i++){
            strChar = strValue.substring(i, i+1);

            //alert("LOOP #" + i + " strInputQty="+strInputQty)

            if (strChar.match("\\d")){
                strInputQty += strChar;
            }
            else{
                switch (strChar){
                    case ".":
                        strInputQty += strChar;//.substring(0,strChar.length-1);
                        break;

                    case "/":
                        intNumerator = parseFloat(strInputQty).valueOf()-0;
                        //alert(intNumerator);
                        strInputQty = "";
                        break;

                    case "c":
                        if (strFromUOM == '"'){
                            strFromUOM = strChar;
                            intMetricQty = intInches-0;
                            intInches = 0;
                        }
                        else{
                            strFromUOM += strChar;
                        }

                        if (strInputQty == ""/*Replaced*/){
                            if (intMetricQty == 0/*Replaced*/){
                                intMetricQty = intInches-0;
                                intInches = 0;
                            }
                        }
                        else{
                            intMetricQty = (parseFloat(strInputQty).valueOf())-0;
                            strInputQty = ""/*Replaced*/;
                        }
                        break;

                    case "m":
                        if (strFromUOM == '"'){
                            strFromUOM = strChar;
                            intMetricQty = intInches-0;
                            intInches = 0;
                        }
                        else{
                            strFromUOM += strChar;
                        }
                        if (strInputQty == ""/*Replaced*/){
                            if (intMetricQty == 0/*Replaced*/){
                                intMetricQty = intInches-0;
                                intInches = 0;
                            }
                        }
                        else{
                            intMetricQty = (parseFloat(strInputQty).valueOf())-0;
                            strInputQty = ""/*Replaced*/;
                        }
                        break;

                    case "'":
                        strFromUOM = strChar;
                        if (strInputQty != ""/*Replaced*/){
                            if (intNumerator == 0/*Replaced*/){
                                intInches += (parseFloat(strInputQty).valueOf())-0;
                            }
                            else{
                                intDenominator = (parseFloat(strInputQty).valueOf())-0;
                                if (intDenominator != 0){
                                    intInches += ((intNumerator-0)/(intDenominator-0))-0;
                                }
                            }
                            strInputQty = ""/*Replaced*/;
                        }
                        intInches = (intInches-0)*12;

                        break;

                    case '"':
                        strFromUOM = strChar;
                        //alert("a "+intInches);

                        if (strInputQty != ""/*Replaced*/){
                            if (intNumerator == 0/*Replaced*/){
                                intInches += (parseFloat(strInputQty).valueOf())-0;
                                //alert("b1 "+intInches);
                            }
                            else{
                                //alert("b2 "+strInputQty);
                                intDenominator = (parseFloat(strInputQty).valueOf())-0;
                                //alert("b2 "+intDenominator);
                                if (intDenominator != 0){
                                    //alert("c1 "+intInches + "::"+intNumerator +"::"+intDenominator );
                                    intInches = (intInches - 0) + ((intNumerator - 0)/(intDenominator - 0));
                                    //alert("c2 "+intInches);
                                }
                            }
                            strInputQty = ""/*Replaced*/;
                        }
                        //alert("c3 "+intInches);
                        break;

                    case " ":
                        if (strInputQty != ""/*Replaced*/){
                            if (intNumerator == 0/*Replaced*/){
                                intInches += (parseFloat(strInputQty).valueOf())-0;
                            }
                            else if(intDenominator == 0/*Replaced*/){
                                  intDenominator = (parseFloat(strInputQty).valueOf())-0;
                                  strFromUOM = '"';

                                  if (intDenominator != 0){
                                        intInches = (intInches - 0) + ((intNumerator - 0)/(intDenominator - 0));
                                  }
                            }
                            strInputQty = ""/*Replaced*/;
                        }
                        break;

                    default:
                            //strChar = "";
                }
            }
        }

        //alert(intMetricQty);
/*-----------------------------OK TO HERE------------------------------------*/
        if (strInputQty == ""/*Replaced*/){
            if (strFromUOM == ""/*Replaced*/){
                intMetricQty = (intInches-0);
                strFromUOM = "mm";
            }
        }
        else {
            if (intNumerator == 0/*Replaced*/){
                if (intInches == 0){
                    intMetricQty = (parseFloat(strInputQty).valueOf())-0;
                }
                else{
                    intInches = (intInches-0) + (parseFloat(strInputQty).valueOf())-0;
                }
            }
            else{
                if (intDenominator == 0/*Replaced*/){
                    intDenominator = (parseFloat(strInputQty).valueOf())-0;
                    strInputQty = ""/*Replaced*/;
                    strFromUOM = '"';
                    if (intDenominator != 0){
                          intInches = (intInches - 0) + ((intNumerator - 0)/(intDenominator - 0));
                    }
                }
            }
        }


        if (strFromUOM == "m"){
            intMetricQty *= 1000;
        }
        else if (strFromUOM == "cm"){
            intMetricQty *= 10;
        }
        else if (strFromUOM != "mm"){
            strMetricInput = "N";
            intMultiplier = 1/intMultiplier;
        }
       //alert(strMetricInput);
       //alert(intMultiplier);

        if (strMetricInput == "Y"){
            intDecimalValue = intMetricQty * intMultiplier;
            if (intMetricQty != (parseInt(intMetricQty+0.5).valueOf())-0){
                strMetricApprox = "Approx. &nbsp;&nbsp;";
            }
            intMetricQty = (parseInt(intMetricQty+0.5).valueOf()-0);
        }
        else{
            intDecimalValue = (intInches-0);
            //alert(":: " +intDecimalValue);
            intMetricQty = (parseInt((intInches * intMultiplier)+0.5).valueOf()-0);
            //alert(":: "+intMetricQty +" :: " + ((intInches * intMultiplier)+0.05).toFixed(1));

            if ((intMetricQty-0) != (((intInches * intMultiplier)+0.05).toFixed(1)-0)){
                strMetricApprox = "Approx.&nbsp;&nbsp;";
            }

        }

        if ((intMetricQty-0) > 999){
            intMetricQty /= 1000;
            strMetricUOM = "m";
        }

        intFEET = (parseInt(intDecimalValue/12).valueOf()-0);
        if (intFEET != 0){
            strCharValue = intFEET.toString() + "' ";
            strCharDecimal = strCharValue;
            intDecimalValue = (intDecimalValue-0) - intFEET * 12;
        }

        if (intDecimalValue != 0){
            strInchSymbol = '"';
        }
        intInches = (parseInt(intDecimalValue).valueOf())-0;

        if (intInches != 0){
            strCharValue += intInches.toString();
            intDecimalValue = (intDecimalValue-0) - (intInches-0);
            if (intDecimalValue != 0){
                strStandardApprox = "Approx.&nbsp;&nbsp;";
            }
        }

        intDenominator = 16;
        strStandardApprox = ""/*Replaced*/;

        for (var z=1;  z<5; z++){
            intNumerator = (parseInt((intDecimalValue * intDenominator)+0.5).valueOf())-0;
            if (intNumerator != (parseInt(intDecimalValue * intDenominator*10000).valueOf()/10000)-0){
                strStandardApprox = "Approx.&nbsp;&nbsp;";
            }
            if (intNumerator == 0){
                break;
            }
            else{
                strCharFraction = " " + intNumerator.toString() + "/" + intDenominator.toString();

                if ((10*parseInt(intNumerator/2).valueOf()) == (parseInt(5*intNumerator).valueOf()-0)){
                    intDenominator /= 2;
                }
                else{
                    break;
                }
            }
        }

        strCharStandard = strCharValue;

        if (strCharFraction != ""/*Replaced*/){
            strCharStandard += strCharFraction;
        }

        //alert("d0 "+intDecimalValue);
        if (intDecimalValue == 0){
            if (intInches != 0){
                strCharDecimal += intInches.toString();
            }
        }
        else{
            //alert("d1 "+intDecimalValue);
            //alert("d1 "+intInches);
            intDecimalValue += intInches-0; //+ 0.00005;
            //alert("d2 "+intDecimalValue);

            intDecimalValue = intDecimalValue.toFixed(4);
            strCharDecimal += (intDecimalValue-0);//.toFixed(4);
            //alert("d3 "+strCharDecimal);
        }

        if (strInchSymbol != ""/*Replaced*/){
            strCharStandard += strInchSymbol;
            strCharDecimal += strInchSymbol;
        }

        if (strStandardApprox != ""/*Replaced*/){
            strCharStandard = strStandardApprox + strCharStandard;
        }
        if (strCharStandard != strCharDecimal){
            if (strCharDecimal != "0"){
                strCharStandard += "&nbsp;(" + strCharDecimal + ")";
            }
        }

        if (strMetricApprox == ""/*Replaced*/){
            strCharMetric = intMetricQty.toString() + " " + strMetricUOM;
        }
        else{
            strCharMetric = strMetricApprox + intMetricQty.toString() + " " + strMetricUOM;
        }
        //strCharValue = strCharStandard + strCharMetric + " Entered: " + strValue;

        //alert("Std " + strCharValue + "");
        if (strCharStandard.indexOf("NaN") > 0 || strCharMetric.indexOf("NaN") > 0){
            strCharStandard = "ERROR: Calculation not executed"
            strCharMetric = "Please check your input"
            document.getElementById('div1').innerHTML = '<font color="Red" size="2"><b>&nbsp;' + strCharStandard + '</b></font>';
            document.getElementById('div2').innerHTML = '<font color="Red" size="2"><b>&nbsp;' + strCharMetric + '</b></font>';
        }
        else{
            document.getElementById('div1').innerHTML = '<font color="Black" size="2"><b>&nbsp;' + strCharStandard + '</b></font>';
            document.getElementById('div2').innerHTML = '<font color="Black" size="2"><b>&nbsp;' + strCharMetric + '</b></font>';
        }
    }
    catch(err){
        alert("ERROR: " + err.message + "\n" + err);
        strCharStandard = "ERROR: Calculation not executed"
        strCharMetric = "Please check your input"
        document.getElementById('div1').innerHTML = '<font color="Red" size="2"><b>&nbsp;' + strCharStandard + '</b></font>';
        document.getElementById('div2').innerHTML = '<font color="Red" size="2"><b>&nbsp;' + strCharMetric + '</b></font>';
    }


}

