var landscape = false;
var fixedId = "Result";

function setup() {
  orientationChanged();
  fix("Result");
  calculate();
}

function fix(id) {
  $(fixedId + "Input").style.display = "inline";
  $(fixedId + "Text").style.display = "none";
  fixedId = id;  
  $(fixedId + "Input").style.display = "none";
  $(fixedId + "Text").style.display = "block";
  //$("Method").disabled = id == "Percent";
  $("Predefined").disabled = id == "Percent";
  calculate();
}

function calculate() {
  var total = getValue("Total");
  var percent = getValue("Percent");
  var result = getValue("Result");
  var method = $("Method").selectedIndex;
  if (method == 1) {
    percent += 100;
  }  
  else if (method == 2) {
    percent = 100 - percent;
  }  
  if (fixedId == "Result") {
    result = total * percent / 100;
    setValue("Result", result);
  }
  if (fixedId == "Percent") {
    percent = result / total * 100;
    if (method == 1) {
      percent = percent - 100;
    }  
    else if (method == 2) {
      percent = 100 - percent;
    }  
    setValue("Percent", percent);
  }
  if (fixedId == "Total") {
    total = result / percent * 100;
    setValue("Total", total);
  }
}

function predefinedChanged() {
  var percent = parseFloat($("Predefined").value);
  setValue("Percent", percent);
  $("Predefined").selectedIndex = 0;
  calculate();
}

function methodChanged() {
  calculate();
}

function setValue(id, value) {
    if (isNaN(value) || value == -Infinity || value == Infinity) {
      $(id + "Text").innerHTML = "#Error";      
    }
    else {
      $(id + "Text").innerHTML = value.toFixed(2);
      $(id + "Input").value = value.toFixed(2);
    }    
}

function getValue(id) {
  var value = parseFloat($(id + "Input").value);
  if (isNaN(value)) {
    $(id + "Input").style.backgroundColor = "#FFE0E0";
  }
  else {
    $(id + "Input").style.backgroundColor = "#FFFFFF";    
  }
  return value;
}

function $(id) {
  return document.getElementById(id);    
}

function tellFriend() {
  var body = "Hi,<br><br>I just stumbled upon this iPhone percentage calculator:" +
      "<br><br>http://percent.speedymarks.com<br><br>" +
      "Calculate the percentage of two values." +
      "<br><br>Best regards";
  window.open("mailto:?subject=Percentage calculator on the iPhone&body=" + body, "_self");  
}

function orientationChanged() {
  if (window.orientation != undefined) {
    landscape = window.orientation != 0 && window.orientation != 180;
  }
  else {
    landscape = window.innerWidth > window.innerHeight;
  }  
  setTimeout(function() {window.scrollTo(0,1)}, 1);
}
