const savefile=returnProfDir("boc13579.tmp");

function onload() {
  //Set Global Variables
  txtAmount = document.getElementById('txtAmount');
  txtDate = document.getElementById('txtDate');
  txtTime = document.getElementById('txtTime');
  txtBuy = document.getElementById('txtBuy');
  txtAsk = document.getElementById('txtAsk');
  txtFrom = document.getElementById('txtFrom');
  txtTo = document.getElementById('txtTo');  
  txtRate = document.getElementById('txtRate');
  txtConvert = document.getElementById('txtConvert');
  mnuFrom = document.getElementById('mnuFrom');
  mnuTo = document.getElementById('mnuTo');
  btnSbmt = document.getElementById('submit');
  btnReset = document.getElementById('reset');
  fileMnuReset = document.getElementById('fileMnuReset');
  status = document.getElementById("status");
  
  btnSbmt.focus();
  centerWindow(650,300);
}

function resetForm() {
  //Rest all of the forms to defaults
  txtAmount.value = "1.00";
  txtDate.value = "";
  txtTime.value = "";
  txtBuy.value = "";
  txtAsk.value = "";
  txtFrom.value = "";
  txtTo.value = "";
  txtRate.value = "";
  txtConvert.value = "";
  mnuFrom.value = "USD";
  mnuTo.value = "CAD";
  btnReset.setAttribute("disabled", "true");
  fileMnuReset.setAttribute("disabled", "true");
}

function showConsole() {
  window.open("chrome://global/content/console.xul", "_blank",
  "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar");
}

function aboutExch() {
  window.open("chrome://exch/content/about.xul", "_blank",
  "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar");
}

function parseCSVfile() {
  var parselocalcsv = savefile;
  var fileIn = FileIO.open(parselocalcsv);
  var str = FileIO.read(fileIn);
  var strsplit = str.split(',');
  FileIO.unlink(fileIn);
  return strsplit;
}


function delfile(deletefile) {
  var fileOut = FileIO.open(deletefile);
  FileIO.unlink(fileOut);
}

function sbmtCurrency() {
  btnReset.setAttribute("disabled", "false");
  fileMnuReset.setAttribute("disabled", "false");
  setStatus("Loading " + 'http://finance.yahoo.com/d/quotes.csv?s=' + mnuFrom.value + mnuTo.value + '=X&f=sl1d1t1ba&e=.csv');
  downloadFile('http://finance.yahoo.com/d/quotes.csv?s=' + mnuFrom.value + mnuTo.value + '=X&f=sl1d1t1ba&e=.csv', savefile);
}

function invertCurr() {
  btnReset.setAttribute("disabled", "false");
  fileMnuReset.setAttribute("disabled", "false");
  var mnuTmp = mnuTo.value;
  mnuTo.value = mnuFrom.value;
  mnuFrom.value = mnuTmp;
  setStatus("Loading " + 'http://finance.yahoo.com/d/quotes.csv?s=' + mnuFrom.value + mnuTo.value + '=X&f=sl1d1t1ba&e=.csv');
  downloadFile('http://finance.yahoo.com/d/quotes.csv?s=' + mnuFrom.value + mnuTo.value + '=X&f=sl1d1t1ba&e=.csv', savefile);
}

/*---------------------------------------------------
Returns the savefile var with the profile directory 
of the user/application appended to the beginning of 
the variable
---------------------------------------------------*/ 
function returnProfDir(filename) {
  //start, used from http://www.captain.at/programming/xul/
  try {
    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
  } catch (e) {
    alert("Permission to save file was denied.");
  }
  
  // get the path to the user's home (profile) directory
  const DIR_SERVICE = new Components.Constructor("@mozilla.org/file/directory_service;1","nsIProperties");
  
  try { 
    path=(new DIR_SERVICE()).get("ProfD", Components.interfaces.nsIFile).path; 
  } catch (e) {
    alert("error");
  }
  
  // determine the file-separator
  if (path.search(/\\/) != -1) {
    path = path + "\\";
  } else {
    path = path + "/";
  }
  
  newfilename = path+filename;
  //end, used from http://www.captain.at/programming/xul/
  return newfilename;
}

//modified downloadFile function from http://xul.andreashalter.ch/
function downloadFile(srcURI, savefile) { 
  //new obj_URI object 
  try { 
    var obj_URI = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(srcURI, null, null); 
  } catch (e) { alert(e); } 
  
  //new file object 
  try { 
    var obj_TargetFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); 
  } catch (e) { alert(e); } 
  
  //set file with path 
  obj_TargetFile.initWithPath(savefile); 
  
  //if file doesn't exist, create 
  if(!obj_TargetFile.exists()) { 
    try { 
      obj_TargetFile.create(0x00,0644); 
    } catch (e) { alert(e); } 
  } 

  persistListener = new PersistProgressListener;
  
  //new persitence object 
  try { 
    obj_Persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Components.interfaces.nsIWebBrowserPersist); 
  } catch (e) { alert(e); }  
  
  //obj_Persist.saveURI(obj_URI,null,null,null,null,obj_TargetFile);
  
  //obj_Persist.currentState,obj_Persist.PERSIST_STATE_FINISHED
  try { 
    obj_Persist.progressListener = persistListener;
  }
  catch (e) { alert(e); }  
  
  obj_Persist.saveURI(obj_URI,null,null,null,null,obj_TargetFile);
}

function setProgress(current, max) {
  progress = current + " out of " + max;
}

function PersistProgressListener() {
  this.init();
}

PersistProgressListener.prototype = {
  _requestsStarted: 0,
  _requestsFinished: 0,
  QueryInterface : function(aIID) {
    if(aIID.equals(Components.interfaces.nsIWebProgressListener))
      return this;
    throw Components.results.NS_NOINTERFACE;
  },
  
  init : function() {
  
  },
  
  destroy : function() {
  
  },
  
  // nsIWebProgressListener
  onProgressChange : function (aWebProgress, aRequest,
                               aCurSelfProgress, aMaxSelfProgress,
                               aCurTotalProgress, aMaxTotalProgress) {
    setProgress(aCurTotalProgress, aMaxTotalProgress);
  },
  
  onStateChange : function(aWebProgress, aRequest, aStateFlags, aStatus) {
    const WPL = Components.interfaces.nsIWebProgressListener;
    
    var progress = document.getElementById('progress');
    
    if (aStateFlags & WPL.STATE_IS_REQUEST) {
      if (aStateFlags & WPL.STATE_START) {
        this._requestsStarted++;
      } else if (aStateFlags & WPL.STATE_STOP) {
        this._requestsFinished++;
      }
      if (this._requestsStarted > 0) {
        var value = (100 * this._requestsFinished) / this._requestsStarted;
        progress.setAttribute("mode", "determined");
        progress.setAttribute("value", value + "%");
      }
    }
    
    if (aStateFlags & WPL.STATE_IS_NETWORK) {
      if (aStateFlags & WPL.STATE_START) {
        progress.setAttribute("style", "");
      } else if (aStateFlags & WPL.STATE_STOP) { 
        setTimeout("resetProgressBar()", 200);
        this.onStatusChange(aWebProgress, aRequest, 0, "Done");
        this._requestsStarted = this._requestsFinished = 0;
      }
    }
    
    if (aStateFlags==327696) {
      csvarray = parseCSVfile();
      //alert(csvarray);
      //csvarray[0]"USDCAD=X"
      //csvarray[1]1.2354
      //csvarray[2]"4/22/2005"
      //csvarray[3]"5:34pm"
      //csvarray[4]1.2354
      //csvarray[5]1.2357 
      
      //grab the input values off of the form and compute the values
      //for the output form
      
      txtDate.value = stripQuotes(csvarray[2]);
      txtTime.value = stripQuotes(csvarray[3]);
      txtBuy.value = csvarray[4];
      txtAsk.value = csvarray[5];
      txtFrom.value = txtAmount.value + ' ' + mnuFrom.label + '(s)';
      txtTo.value = mnuTo.label + '(s)';            
      txtRate.value = csvarray[1];
      txtConvert.value = Math.round((txtAmount.value * csvarray[1])*100)/100 + ' ' + mnuTo.label + '(s)';
    }
  },
  
  onLocationChange : function(aWebProgress, aRequest, aLocation) {
  
  },
  
  onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage) {
    setStatus(aMessage);
    //var status = document.getElementById("status");
    //status.setAttribute("label", aMessage);  
  },
  
  onSecurityChange : function(aWebProgress, aRequest, aState) {
  
  }
}

//new function, old is commented out
function setStatus(text) {
  //astatus[i] = text;
  //i++;
  //var status = document.getElementById("status");
  status.setAttribute("label", text);  
}

function stripQuotes(txtQuoted) {
  var txtQuotesRemoved = txtQuoted.substring(1,txtQuoted.length - 1);
  return txtQuotesRemoved;
}

function resetProgressBar() {
  var progress = document.getElementById('progress');
  progress.setAttribute('value', 0);
}

//addEventListener("load", onload, false);
