/*
  Price Comparison Calculator
  File: Application.js   Version 2.0
  (c)2007-2010 Brian McMillin.  All Rights Reserved.
*/
var PriceCalcVer = 'PriceCalc 2.0.30 of 14Apr10';
var CurrentFieldId='';
var CurrencyXML=''; // The Currency identifiers and conversion rates
var Kind='';        // like "Length"
var U1='';          // like "each"
var U2='';          // like "dozen"
var P1='';          // Like "123.45"
var P2='';
var Q1='';          // like "14"
var Q2='';
var R1='';          // like 12.345"
var R2='';
var Metric='';      // like "Both"
var Local='';       // like "$ USD"
var Lsym='';        // like "$"
var Lid='';         // like "USD"
var Favorite='';    // like "&pound; GBP"
var Fsym='';        // like "&pound;"
var Fid='';         // like "GBP"
var Alt='';
var cursor='';
var grayPrice = '<small style="color:gray">Price</small>';
var grayQty   = '<small style="color:gray">Qty</small>';

/****************************************************************************************/
// Here we handle displaying a Promo page if we are loaded by an ordinary browser
//
function makeFunc() {
  var args = Array.prototype.slice.call(arguments);
  var func = args.shift();
  return function() {
    return func.apply(null, args.concat(Array.prototype.slice.call(arguments)));
  };
}
function XMLloadStart(url, target) {
  document.getElementById(target).innerHTML = ' Fetching data...';
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (req != undefined) {
    req.onreadystatechange = makeFunc (XMLloadDone, url, target);
    req.open("GET", url, true);
    req.send("");
  }
}
function XMLloadDone(url, target) {
  if (req.readyState == 4) { // only if req is "loaded"
    if (req.status == 200) { // only if "OK"
      document.getElementById(target).innerHTML = req.responseText;
    } else {
      document.getElementById(target).innerHTML=" XML Load Error:\n"+ req.status + "\n" +req.statusText;
    }
  }
}
function browserCheck() {
  if (navigator.appVersion.indexOf('iPod') != -1) return true;
  if (navigator.appVersion.indexOf('iPad') != -1) return true;
  if (navigator.appVersion.indexOf('iPhone') != -1) return true;
  XMLloadStart ('promo/','TheWholeThing');
  return false;
}
/****************************************************************************************/
function XMLdataLoad(url) {
  req = new XMLHttpRequest();
  req.onreadystatechange = XMLdataDone;
  req.open("GET", url, true);
  req.send("");
}
function XMLdataDone() {
  if (req.readyState == 4) { // only if req is "loaded"
    if (req.status == 200) { // only if "OK"
      CurrencyXML = req.responseText;
      document.getElementById("Currency").innerHTML = CurrencyXML;
      buildCurrency();
    }
  }
}
/****************************************************************************************/
function init() {
  if (!browserCheck()) return;

  document.getElementById('TheWholeThing').setAttribute ("style", "background-color:black");

  clearit();

  CurrencyXML = document.getElementById('Currency').innerHTML;
  loadPersistentData();
  XMLdataLoad ('currency.xml');   // Grab the current conversion rates

  hideSetup();
  setInterval('blink()',500);
  messages(PriceCalcVer);
  choose();
}
/****************************************************************************************/
function message(txt) {document.getElementById("Dmessages").innerHTML = txt; }
/****************************************************************************************/
function messages(txt) {
  if(document.getElementById("Dmessages").innerHTML!='')document.getElementById("Dmessages").innerHTML += '<br>';
  document.getElementById("Dmessages").innerHTML += txt;
}
/****************************************************************************************/
function blink() {
  if (cursor == "|") cursor = "&nbsp;"; else cursor = "|";

  document.getElementById('P1c').innerHTML = (CurrentFieldId == "P1"?cursor:"&nbsp;");
  document.getElementById('P2c').innerHTML = (CurrentFieldId == "P2"?cursor:"&nbsp;");
  document.getElementById('Q1c').innerHTML = (CurrentFieldId == "Q1"?cursor:"&nbsp;");
  document.getElementById('Q2c').innerHTML = (CurrentFieldId == "Q2"?cursor:"&nbsp;");
}

/****************************************************************************************/
// Make the string s appear small it its length is greater than L.
function smallIt(L,s) {
  return ((s.length>L) ? ('<small>'+s+'</small>') : s);
}
/****************************************************************************************/
function showit() {
  if(isNaN(R1)) R1 = '';
  if(isNaN(R2)) R2 = '';

  document.getElementById("P1").innerHTML = P1==''?grayPrice:P1;
  document.getElementById("P2").innerHTML = P2==''?grayPrice:P2;
  document.getElementById("Q1").innerHTML = Q1==''?grayQty  :smallIt(4,Q1);
  document.getElementById("Q2").innerHTML = Q2==''?grayQty  :smallIt(4,Q2);

  document.getElementById("R1").innerHTML = Lsym + ' ' + smallIt (12, (R1==''?"-.--":R1)+' / ' + U1);
  document.getElementById("R2").innerHTML = Lsym + ' ' + smallIt (12, (R2==''?"-.--":R2)+' / ' + U1);
}

/****************************************************************************************/
// Either do a Clear Entry or Clear All
function clearit() {
  if(document.getElementById("ClearKey").innerHTML == "C") {
    P1 = P2 = Q1 = Q2 =  R1 = R2 = '';
    document.getElementById("R1").setAttribute ("style", "background-color:white");
    document.getElementById("R2").setAttribute ("style", "background-color:white");

    CurrentFieldId = "P1";
    clearResult();
    document.getElementById("ClearKey").innerHTML = "CE";
  } else {
    field(CurrentFieldId);   // This is a Clear Entry, just like touching the field
  }
  showit();
}

/****************************************************************************************/
function setUnits(u, d) {
var L = '';
  for (var i in u) L += '<option value="' + u[i] + '"'+(u[i]==d?'selected="selected"':'')+'>' + u[i];
  document.getElementById("U1").innerHTML = L;
  document.getElementById("U2").innerHTML = L;
  U1 = d;
  U2 = d;
}

/****************************************************************************************/
function setUnitKind(k) {
  Metric = getSelected('Metric');
  Kind = k;
  if (Metric == 'Metric') {
    if(k == 'units' ) setUnits (['each','dozen'                ], 'each' );
    if(k == 'weight') setUnits (['gram','Kg'                   ], 'Kg'   );
    if(k == 'volume') setUnits (['mL'  ,'Liter'                ], 'Liter');
    if(k == 'length') setUnits (['mm'  ,'cm'   ,'meter','Km'   ], 'meter');
  }

  if (Metric == 'English') {
    if(k == 'units' ) setUnits (['each' ,'dozen'                ], 'each' );
    if(k == 'weight') setUnits (['ounce','pound'                ], 'ounce');
    if(k == 'volume') setUnits (['fl oz','pint' ,'quart','gal'  ], 'fl oz');
    if(k == 'length') setUnits (['inch' ,'foot' ,'yard'         ], 'inch' );
  }

  if (Metric == 'Both') {
    if(k == 'units' ) setUnits (['each' ,'dozen'                                        ], 'each' );
    if(k == 'weight') setUnits (['gram' ,'ounce','pound','Kg'                           ], 'ounce');
    if(k == 'volume') setUnits (['mL'   ,'Liter','fl oz','pint' ,'quart','gal'          ], 'fl oz');
    if(k == 'length') setUnits (['inch' ,'foot' ,'yard' ,'mm'   ,'cm'   ,'meter','Km'   ], 'inch' );
  }

  document.getElementById("units").setAttribute ("style", (k=='units'?"background-color:blue;color:white":"background-color:white;color:black"));
  document.getElementById("weight").setAttribute ("style", (k=='weight'?"background-color:blue;color:white":"background-color:white;color:black"));
  document.getElementById("volume").setAttribute ("style", (k=='volume'?"background-color:blue;color:white":"background-color:white;color:black"));
  document.getElementById("length").setAttribute ("style", (k=='length'?"background-color:blue;color:white":"background-color:white;color:black"));

  choose();
}

/****************************************************************************************/
// Make the Currency Selector use the currency that is loaded in XML
// parse something that liiks like this:
// <currency>
// <date>Currency Conversions Updated 13Apr10 14:27 UTC</date>
// <exchange id="CAD" symbol="$">1.00199</exchange>
// <exchange id="CNY" symbol="&yen;">6.82998</exchange>
// <exchange id="EUR" symbol="&euro;">0.734775</exchange>
// <exchange id="GBP" symbol="&pound;">0.647825</exchange>
// <exchange id="JPY" symbol="&yen;">92.7577</exchange>
// <exchange id="MXN" symbol="$">12.1775</exchange>
// <exchange id="USD" symbol="$">1.0</exchange>
// </currency>

function buildCurrency() {
var ls = CurrencyXML.split('<exchange');
var res = '';
var v;
  if (CurrencyXML.indexOf('<currency>') == -1) return;   // blow off if it doesn't look complete
  if (CurrencyXML.indexOf('</currency>') == -1) return;   // blow off if it doesn't look complete
  for (var i in ls) if(ls[i].indexOf("id=")!=-1) {
    if (CurrencyXML.indexOf('</exchange>') == -1) return;   // blow off if it doesn't look complete
    res += '<option value="'
    v = ls[i]; v = v.substring(v.indexOf('id="'));  v = v.substring(v.indexOf('"')+1); v = v.substring(0,v.indexOf('"'));
    res += v + '"> ';
    v = ls[i]; v = v.substring(v.indexOf('symbol="'));  v = v.substring(v.indexOf('"')+1); v = v.substring(0,v.indexOf('"'));
    res += v + ' ';
    v = ls[i]; v = v.substring(v.indexOf('id="'));  v = v.substring(v.indexOf('"')+1); v = v.substring(0,v.indexOf('"'));
    res += v;
  }
  document.getElementById("Local").innerHTML = res;
  document.getElementById("Favorite").innerHTML = '<option value="none">none' + res;
  setSelected('Local','USD');
  setSelected('Local',Lid);
  setSelected('Favorite',Fid);
}
/****************************************************************************************/
//
function Currency(v) {
  Local = getSelected('Local');
  Favorite = getSelected('Favorite');
  if(Favorite==Local) Favorite = 'none';

  Lid = Lsym = Local.replace(/ /g,'');       // Kill the embedded spaces
  Fid = Fsym = Favorite.replace(/ /g,'');    // Kill the embedded spaces

  Lsym = Lsym.substr(0,Lsym.length-3);  // Local Symbol
  Lid = Lid.substr(-3,3);               // Local currency ID

  Fsym = Fsym.substr(0,Fsym.length-3);   // Select only the 3-letter currency ID
  Fid  = Fid.substr(-3,3);               // Favorite currency ID

  document.getElementById("C1").innerHTML = Lsym+' ';
  document.getElementById("C2").innerHTML = Lsym+' ';

  if (Favorite=='none') return '';
  return '<small>Conversion:</small> '+
         Lsym+' '+v+
         ' <small>('+Local+')</small> '+
         ' is '+
         Fsym+' '+numericFormat(v * Conversion(Fid) / Conversion(Lid))+
         ' <small>('+Favorite+')</small> '
}
/****************************************************************************************/
function Conversion(key) {
var ls = CurrencyXML.split('<exchange');
  if (CurrencyXML.indexOf('</currency>') == -1) {   // use default conversions if it doesn't look complete
    if(key=='CAD') return 1.03129;
    if(key=='CNY') return 6.82720;
    if(key=='EUR') return 0.73623;
    if(key=='GBP') return 0.66522;
    if(key=='JPY') return 89.1427;
    if(key=='MXN') return 12.7159;
    if(key=='USD') return 1;
    return 1;
  }
  for (var i in ls) if(ls[i].indexOf(key)!=-1) return ls[i].substring(ls[i].indexOf('>')+1,ls[i].indexOf('<'));
  alert('Unknown Currency.');
}
/****************************************************************************************/
function hideSetup() {
  document.getElementById("Setup").setAttribute ("style", "display:none");
  document.getElementById("Main").setAttribute ("style", "display:block");
  document.getElementById("Help").setAttribute ("style", "display:none");
  document.getElementById("infoButton").setAttribute ("style", "visibility:visible");
  document.getElementById("backButton").setAttribute ("style", "visibility:hidden");
}

/****************************************************************************************/
function showSetup() {
  document.getElementById("Setup").setAttribute ("style", "display:block");
  document.getElementById("Main").setAttribute ("style", "display:none");
  document.getElementById("Help").setAttribute ("style", "display:block");
  document.getElementById("backButton").setAttribute ("style", "visibility:visible");
  document.getElementById("infoButton").setAttribute ("style", "visibility:hidden");
}

/****************************************************************************************/
function clearResult() {
  document.getElementById("Result").innerHTML = '<span style="font-size:14px"><b>Select Units, enter Price and Quantity</b></span>';
  document.getElementById("ResultAlt").innerHTML = 'See best price in your Favorite Currency.';
  document.getElementById("Results").setAttribute ("style", "background-color:palegoldenrod");

  document.getElementById("R1").setAttribute ("style", "background-color:white");
  document.getElementById("R2").setAttribute ("style", "background-color:white");
}

/****************************************************************************************/
function showResult() {
  showit();
  document.getElementById("Results").setAttribute ("style", "background-color:white");
}
/****************************************************************************************/
function entry(key) {
var html = '';
  if(CurrentFieldId=='P1') html = P1;
  if(CurrentFieldId=='P2') html = P2;
  if(CurrentFieldId=='Q1') html = Q1;
  if(CurrentFieldId=='Q2') html = Q2;

  if (html == "0") html = "";
  if (key == "P") {
    if (html.indexOf('.') >= 0) return(0);
    if (html == "")  html = "0";
    key = ".";
  };

  if (html.length < 6) {
    html += key;
  }
  if(CurrentFieldId=='P1') P1 = html;
  if(CurrentFieldId=='P2') P2 = html;
  if(CurrentFieldId=='Q1') Q1 = html;
  if(CurrentFieldId=='Q2') Q2 = html;
  choose();
  document.getElementById("ClearKey").innerHTML = "CE";  // There is an entry, so we make a Clear Entry key
}

/****************************************************************************************/
function getSelected(id) {
var selectedIndex = document.getElementById(id).selectedIndex;
  return document.getElementById(id).options[selectedIndex].text;
}

/****************************************************************************************/
function setSelected(id,value) {
  for (var i in document.getElementById(id).options) {
    if (document.getElementById(id).options[i].text ==value) document.getElementById(id).selectedIndex = i;
    if (document.getElementById(id).options[i].value==value) document.getElementById(id).selectedIndex = i;
  }
}

/****************************************************************************************/
function field(fieldID) {
  CurrentFieldId = fieldID;
  if(CurrentFieldId=='P1') P1 = '';
  if(CurrentFieldId=='P2') P2 = '';
  if(CurrentFieldId=='Q1') Q1 = '';
  if(CurrentFieldId=='Q2') Q2 = '';

  choose();
  blink();   // Make it look more responsive
  document.getElementById("ClearKey").innerHTML = "C";  // Now it will be Clear All
}

/****************************************************************************************/
function factor(unit) {
  if(unit=='each' ) return 1;
  if(unit=='dozen') return 1/12;
  if(unit=='gram' ) return 28.3495231;
  if(unit=='ounce') return 1;
  if(unit=='pound') return 0.0625;
  if(unit=='Kg'   ) return 0.0283495231;
  if(unit=='mL'   ) return 29.5735297;
  if(unit=='fl oz') return 1;
  if(unit=='pint' ) return 1/16;
  if(unit=='quart') return 1/32;
  if(unit=='gal'  ) return 1/128;
  if(unit=='Liter') return 0.0295735297;
  if(unit=='inch' ) return 0.0254;
  if(unit=='foot' ) return 0.3048;
  if(unit=='yard' ) return 0.9144;
  if(unit=='mile' ) return 1609.344;
  if(unit=='mm'   ) return 1/1000;
  if(unit=='cm'   ) return 1/100;
  if(unit=='meter') return 1;
  if(unit=='Km'   ) return 1000;
  alert('Missing Factor: "'+unit+'"');
  return 1;
}
/****************************************************************************************/
function choose() {
  chooser();
  showResult();
  showit();
}
/****************************************************************************************/
function chooser() {
var v;
  U1 = getSelected("U1");
  U2 = getSelected("U2");
  clearResult();
  try {R1 = numericFormat(P1 / Q1)} catch(e){R1 = '';};
  try {R2 = numericFormat(P2 / Q2 * factor(U2)/factor(U1))} catch(e){R2 = '';};

  R1 = R1-0;   // This crap is CRITICAL to making the comparison work.  R1 and R2 MUST be numbers.
  R2 = R2-0;

  v = '';
  Alt = '';
  if (R1 == R2) {
    v = "Costs are equal";
    document.getElementById("R1").setAttribute ("style", "background-color: #ADFF2F");  /*green*/
    document.getElementById("R2").setAttribute ("style", "background-color: #ADFF2F");  /*green*/
    Alt = Currency(P1);
  }

  if (R1 < R2) {
    v = "Buy "+Q1+" "+ U1+ " for "+Lsym+P1;
    document.getElementById("R1").setAttribute ("style", "background-color: #ADFF2F");  /*green*/
    document.getElementById("R2").setAttribute ("style", "background-color: #FFB6C1");  /*red*/
    Alt = Currency(P1);
  }

  if (R1 > R2) {
    v = "Buy "+Q2+" "+ U2+ " for "+Lsym+P2;
    document.getElementById("R1").setAttribute ("style", "background-color: #FFB6C1");  /*red*/
    document.getElementById("R2").setAttribute ("style", "background-color: #ADFF2F");  /*green*/
    Alt = Currency(P2);
  }

  if (P1=='') {clearResult(); v=Alt=''; };
  if (P2=='') {clearResult(); v=Alt=''; };
  if (Q1=='') {clearResult(); v=Alt=''; };
  if (Q2=='') {clearResult(); v=Alt=''; };

  if (v=='') v = 'Set Price and Quantity';
  if (Alt=='') if(P1!=0) Alt=Currency(P1);
  if (Alt=='') if(P2!=0) Alt=Currency(P2);
  if (Alt=='') Alt = 'Set Your Favorite Currency on Settings Page';

  //document.getElementById("Result").innerHTML = "("+R1+","+R2+")"+v;
  document.getElementById("Result").innerHTML = v;
  document.getElementById("ResultAlt").innerHTML = Alt;

  savePersistentData();
}

/****************************************************************************************/
function numericFormat(v)
{
var s;
  s = "";
  if (v > 999999) { return("-.--"); };
  s = s + Math.floor((v % 1000000) / 100000); if (s == 0) s = "";
  s = s + Math.floor((v %  100000) /  10000); if (s == 0) s = "";
  s = s + Math.floor((v %   10000) /   1000); if (s == 0) s = "";
  s = s + Math.floor((v %    1000) /    100); if (s == 0) s = "";
  s = s + Math.floor((v %     100) /     10); if (s == 0) s = "";
  s = s + Math.floor((v %      10)         ); v = v *   10;
  s = s + ".";
  s = s + Math.floor(v % 10   ); v = v *   10;
  s = s + Math.floor(v % 10   ); v = v *   10;
  s = s + Math.floor(v % 10   ); v = v *   10;
  s = s + Math.round(v % 10);
  s = s.substr(0,6);
  return(s);
}

/****************************************************************************************/
//  There are currently eleven Persistent Data Items.
//
//  Kind, Metric, Local, Favorite, U1, U2, P1, P2, Q1, Q2, Currency
function loadPersistentData() {
var ls;
  ls = '';
  try {
    ls = localStorage.getItem("State");
//    messages(ls);    // Show the complete saved data for debugging.
  } catch (e) {
    alert ('Cannot Load Previous State');
    ls = '';
  }
  if (ls==undefined) ls='';
  if (ls=='') ls = 'units,Both,USD,none,each,each,,,,,' + document.getElementById("Currency").innerHTML;

  ls = ls.split(',');
  Kind   = ls[0];
  Metric = ls[1];  setSelected("Metric",Metric); setUnitKind(Kind);
  Lid    = ls[2];  setSelected("Local",Lid);
  Fid    = ls[3];  setSelected("Favorite",Fid);
  U1     = ls[4];  setSelected("U1",U1);
  U2     = ls[5];  setSelected("U2",U2);
  P1     = ls[6];
  P2     = ls[7];
  Q1     = ls[8];
  Q2     = ls[9];
  CurrencyXML = ls[10];
  document.getElementById("Currency").innerHTML = CurrencyXML;
  buildCurrency();
  Currency(1);   // This sets all the display symbols, etc.
}
/****************************************************************************************/
function savePersistentData() {
var ls = Kind+
     ','+Metric+
     ','+Lid+
     ','+Fid+
     ','+U1+
     ','+U2+
     ','+P1+
     ','+P2+
     ','+Q1+
     ','+Q2+
     ','+CurrencyXML;
  localStorage.clear();
  localStorage.setItem("State",ls);
}