// constants
var FORMA_METER_WIDTH = (1 / 3);
var FORMA_FEET_WIDTH = 1.0936;
var FLOOR_WIDTH = 27;
var FLOOR_LENGTH = 50;

// globals
var numTilesWidth = 0; // number of tiles across the width
var numTilesLength = 0; // number of tiles along the length

/*
 * Converts area to tiles.
 */
function areaToTiles(width, length, units, round) {
  if (width <= 0 || length <= 0) {
    alert("Please enter the Area dimensions.");
    return false;
  }

  if (isNaN(width) || isNaN(length)) {
    alert("Invalid input. Please try again.");
    return false;
  }
  
  // actual area desired
  var actArea = Math.round(width * length * 100) / 100; // round to hundredths
  var result = "Area you'd like to cover: " + actArea + " square " + units + "\n";
  var area = 0; // area the tiles will cover

  if (units == "meters") {
    if (round == "up") {
      numTilesWidth = Math.ceil(width / FORMA_METER_WIDTH);
      numTilesLength = Math.ceil(length / FORMA_METER_WIDTH);
    } else { // round down
      numTilesWidth = Math.floor(width / FORMA_METER_WIDTH);
      numTilesLength = Math.floor(length / FORMA_METER_WIDTH);
    }
    // special case round flooring to zero
    if (numTilesWidth == 0) numTilesWidth++;
    if (numTilesLength == 0) numTilesLength++;
    area = Math.round(numTilesWidth * numTilesLength * FORMA_METER_WIDTH * FORMA_METER_WIDTH * 100) / 100; // round to hundredths
  } else { // units are feet
    if (round == "up") {
      numTilesWidth = Math.ceil(width / FORMA_FEET_WIDTH);
      numTilesLength = Math.ceil(length / FORMA_FEET_WIDTH);
    } else { // round down
      numTilesWidth = Math.floor(width / FORMA_FEET_WIDTH);
      numTilesLength = Math.floor(length / FORMA_FEET_WIDTH);
    }
    // special case round flooring to zero
    if (numTilesWidth == 0) numTilesWidth++;
    if (numTilesLength == 0) numTilesLength++;
    // rotate floor 90 degrees if needed
    if ((numTilesWidth > FLOOR_WIDTH) || (numTilesLength > FLOOR_LENGTH)) {
    	if ((numTilesLength <= FLOOR_WIDTH) && (numTilesWidth <= FLOOR_LENGTH)) {
    		//alert("Your floor was rotated 90 degrees\nso it would fit onto the page.");
    		var tempTiles = 0;
    		tempTiles = numTilesWidth;
    		numTilesWidth = numTilesLength; // switch length and width
    		numTilesLength = tempTiles;
    	}
    }
    		
    area = Math.round(numTilesWidth * numTilesLength * FORMA_FEET_WIDTH * FORMA_FEET_WIDTH * 100) / 100; // round to hundredths
  }
  var numTiles = numTilesWidth * numTilesLength;
  result += "Area covered by tiles: " + area + " square " + units + "\n";
  result += "Number of tiles: " + numTiles + " total tiles (" + numTilesWidth + " across the width, " + numTilesLength + " along the length)";
  document.areaForm.coverage.value = result;
  document.areaForm.width.value = numTilesWidth; // set hiddens
  document.areaForm.length.value = numTilesLength;
  return true; // submit form
}

