/**
 * Latitude/Longitude calculation utilities
 * 
 * @category    Utilities
 * @package     ATProcessor
 * @author      Sam Meredith <sam@aandtinstruments.com>
 * @version     0.1
 */

function decimalDegreesToDecimalMinutesArray(decDeg, orientation) {
    var decDegrees;
    var direction;

    if ( (decDegrees = parseFloat(decDeg)) === NaN) {
        return "";
    }

    if (orientation == "Latitude") {
        direction = (Math.sign(decDegrees) == 1) ? "N" : "S";
    } else if (orientation == "Longitude") {
        direction = (Math.sign(decDegrees) == 1) ? "E" : "W";
    } else {
        direction = "";
    }

    var absoluteDegrees = Math.abs(decDegrees);

    var degrees = Math.floor(absoluteDegrees).toFixed(0);
    var minutes = ((absoluteDegrees - degrees) * 60.0).toFixed(3);

    return [degrees, minutes, direction];
}

/**
 * Convert from decimal degrees to degrees and decimal minutes
 * @param string $decDeg String representation of position in decimal degrees
 * @param string $orientation Latitude or Longitude
 */
function decimalDegreesToDecimalMinutes(decDeg, orientation) {
    var resultArray = decimalDegreesToDecimalMinutesArray(decDeg, orientation);
    var result = "" + resultArray[0] + "&deg; " + resultArray[1] + "' " + resultArray[2];
    
    return result;
}

/**
 * Convert from degrees and decimal minutes to decimal degrees
 * @param string $deg String representation of the "degree" part of the coordinates
 * @param string $min String representation of the "decimal minute" part of the coordinates
 * @param string $dir String representation of the direction: "N" or "S" for Latitude, "E" or "W" for Longitude
 * @param string $orientation Latitude or Longitude
 */
 function decimalMinutesToDecimalDegrees(deg, min, dir, orientation) {
    let degrees = parseFloat(deg);
    let minutes = parseFloat(min);
    
    degrees = isNaN(degrees) ? 0 : degrees;
    minutes = isNaN(minutes) ? 0 : minutes;

    let decimalDegrees = degrees + minutes / 60.0;

    if (orientation == "Latitude") {
        if (dir == "S")
            decimalDegrees *= -1;
    }

    if (orientation == "Longitude") {
        if (dir == "W")
            decimalDegrees *= -1;
    }

    return decimalDegrees.toFixed(6);
 }