  var landscape = true;
  var data = null;
  var fromCookie = new Cookie("fromCurrency");
  var toCookie = new Cookie("toCurrency");
  var amountCookie = new Cookie("fromAmount");
  var source = null;
  var symbols = null;
	    
  function setup() {
    setTimeout(function() {window.scrollTo(0,1)}, 1);
    landscape = window.innerWidth < window.innerHeight;    
    source = new XavierSource();
    source.setLink($("SourceLink"));
    symbols = source.symbols;
    fillSelect("FromSelect");
    fillSelect("ToSelect");
    var from = fromCookie.get();
    if (from) {
      $("FromSelect").value = from;
    }
    var to = toCookie.get();
    if (to) {
      try {
        var values = eval(to);
        var options = $("ToSelect").options;
        $("ToSelect").selectedIndex = -1;
        for (var i = 0; i < values.length; i++) {
      	  for (var j = 0; j < options.length; j++) {
      	  	if (options[j].value == values[i]) {
      	  	  options[j].selected = true;
      	  	  $("ListForm").style.display = "none";
      	  	  break;
      	  	}
      	  }
        }
      }
      catch (e) {
        console.log(e);
      }  
    }
    var amount = amountCookie.get();
    if (amount) {
      $("Amount").value = amount;
    }
    reload();
  }
  
  function done(success, msg, noConnection) {
    $("Loading").style.visibility = "hidden";
    if (success) {
      setTimeStamp(msg, noConnection);
    }
    else {
      $("TimeStamp").innerHTML = msg;
    }
    recreate();
  }
  
  function initialize() {
    var value = $("FromSelect").value;
    if (value.length == 0) {
      return;
    }
    fromCookie.store(value);
    $("Loading").style.visibility = "visible";
    $("List").innerHTML = "";
    data = new Object();
    data.from = value;
    $("ListFrom").innerHTML = value + " <span class='listFromSmall'>(" + symbols[value] + ")</span>";
    /*
    var url = "http://currencysource.com/RSS/" + value;
    url += ".xml";
    var feed = new google.feeds.Feed(url);
    feed.setNumEntries(50);
    feed.load(function(result) {
      if (!result.error) {
        data.to = new Object();
        for (var i = 0; i < result.feed.entries.length; i++) {
          var entry = result.feed.entries[i];
          var line = parseDataLine(entry.title);
          data.to[line.symbol + ""] = line;
        }
        document.getElementById("Loading").style.visibility = "hidden";
        recreate();
      }
      else {
        console.log(result.error.message);
        document.getElementById("Loading").style.visibility = "hidden";
      }
    });
    /**/
    source.reload(false, value, data, done);    
  }

  function setTimeStamp(date, noConnection) {
    $("TimeStamp").innerHTML = "Last Check: " + date.toLocaleDateString() + " - " + date.toLocaleTimeString();
    if (noConnection) {
      $("TimeStamp").innerHTML = $("TimeStamp").innerHTML + "<br>(Check internet connection!)";
    }  
  }

  function reload() {
    initialize();
  }
  
  function recreate() {
    var container = $("List");
    container.innerHTML = "";
    var amount = parseFloat($("Amount").value);
    if (isNaN(amount) || amount <= 0) {
      amount = 1;
    }
    amountCookie.store(amount);
    var cookieValue = "[";
    var options = $("ToSelect").options;
    for (var i = 0; i < options.length; i++) {
    	if (options[i].selected) {
    	  if (cookieValue.length > 1) {
    	    cookieValue += ",";
    	  }
    	  cookieValue += "'" + options[i].value + "'";
    	  var value = data.to[options[i].value + ""];
    	  var li = document.createElement("li");
    	  container.appendChild(li);
    	  
    	  var toggle = document.createElement("img");
    	  toggle.className = "listToggle";
    	  toggle.src = "toggle.png";
    	  toggle.onclick = function() {
    	    toggleCalculator(this);
    	  }
    	  li.appendChild(toggle);
     	  
    	  var title = document.createElement("div");
    	  title.className = "listTitle";
    	  title.innerHTML = "<div class='listTitleName'>" + symbols[value.symbol] + "</div>"
    	                    + (amount * value.rate).toFixed(2) 
    	                    +  "&nbsp;" + value.symbol;
    	  title.onclick = function() {
    	    toggleCalculator(this);
    	  }
    	  li.appendChild(title);
     	  
    	  var subtitle = document.createElement("div");
    	  subtitle.className = "listSubtitle";
    	  subtitle.innerHTML = amount.toFixed(2) + "&nbsp;" + value.symbol
    	                    + "&nbsp;=&nbsp;" + (amount / value.rate).toFixed(2) 
    	                    + "&nbsp;" + data.from;
    	  li.appendChild(subtitle);
    	  
    	  var calculator = document.createElement("div");
    	  calculator.className = "listCalculator";
    	  var value1 = document.createElement("input");
    	  value1.name = "zip";
    	  value1.type = "number";
    	  value1.className = "listCalcInput";
    	  value1.value = amount.toFixed(2);
    	  value1.rate = value.rate;
    	  value1.onchange = function() {
    	    var amount = parseFloat(this.value);
    	    if (isNaN(amount)) {
    	      this.result.value = "0";
    	      return;
    	    }
    	    this.result.value = (amount * this.rate).toFixed(2);
    	  }
    	  calculator.appendChild(value1);
    	  calculator.appendChild(document.createTextNode(data.from + " = "));
    	  var value2 = document.createElement("input");
    	  value2.name = "zip";
    	  value2.type = "number";
    	  value2.className = "listCalcInput";
    	  value2.value = (amount * value.rate).toFixed(2);
    	  value2.rate = 1/value.rate;
    	  value2.onchange = function() {
    	    var amount = parseFloat(this.value);
    	    if (isNaN(amount)) {
    	      this.result.value = "0";
    	      return;
    	    }
    	    this.result.value = (amount * this.rate).toFixed(2);
    	  }
    	  calculator.appendChild(value2);
    	  calculator.appendChild(document.createTextNode(value.symbol));
    	  value1.result = value2;
    	  value2.result = value1;
    	  toggle.calculator = calculator;
    	  title.calculator = calculator;
    	  li.appendChild(calculator);
    	}
    }
    cookieValue += "]";
    toCookie.store(cookieValue);
  }
  
  function toggleCalculator(element) {
    if (element.calculator.style.display == "block") {
      element.calculator.style.display = "none";
    }
    else {
      element.calculator.style.display = "block";    	      
    }    
  }
  
  function fillSelect(id) {
    for (var i in symbols) {
    	var option = document.createElement("option");
    	option.value = i;
    	option.innerHTML = symbols[i];
    	$(id).appendChild(option);
    }
  }
  
  function tellFriend() {
    var body = "Hi,<br><br>I just stumbled upon this iPhone Currencies Exchange application:" +
        "<br><br>http://rates.speedymarks.com<br><br>" +
        "Monitors the exchange rates for all major currencies." +
        "<br><br>Best regards";
    window.open("mailto:?subject=Currencies on the iPhone&body=" + body, "_self");  
  }

	function orientationChanged() {
    landscape = window.innerWidth < window.innerHeight;
    setTimeout(function() {window.scrollTo(0,1)}, 1);
  }
	
  function debug(msg) {
    var e = document.getElementById("Debug");
    e.innerHTML += msg + "<br>";
  }
  
  function $(id) {
    return document.getElementById(id);
  }

  
  function XavierSource() {
    var _self = this;
    this.eurData = null;
    this.request = null;
    
    this.setLink = function(link) {
      if (!link) {
        return;
      }
      link.href = "http://finance.xaviermedia.com/";
      link.innerHTML = "Currency Converter";
    }
    
    this.reload = function(bypassCache, code, result, callback) {
      var lastChecked = new Cookie("RatesCacheLast");
      var cache = new Cookie("RatesCache");
      var today = new Date();
      var last = parseInt(lastChecked.get());
      if (cache.get() && (today.getTime() - last) < 3600000 && !bypassCache) {
        if (!this.eurData) {
          debug("Parse Cache");
          this.parseData(new DOMParser().parseFromString(cache.get(), "text/xml"));
        }
        this.getRates(code, result);
        callback(true, new Date(last));
        debug("From cache");
        return;
      }
      if (window.android) {
        var request = new Object();
        request.send = function(data) {};
      }
      else {
        var request = new XMLHttpRequest();
        request.open("GET", "xavierTest.xml");//"http://api.finance.xaviermedia.com/api/latest.xml");
        //request.open("GET", "http://api.finance.xaviermedia.com/api/latest.xml");
      }
      request.onload = function() {
        debug(this);
        if (request.status == 200 || request.status == 0) {
          debug("Parse Data");
          _self.parseData(new DOMParser().parseFromString(request.responseText, "text/xml"));
          _self.getRates(code, result);
          callback(true, today);
          cache.store(request.responseText);
          lastChecked.store(today.getTime());
          debug("Received");
        }
        else {
          if (cache.get()) {
            debug("Xavier Failed - From Cache"); 
            if (!_self.eurData) {
              debug("Parse Cache");
              _self.parseData(new DOMParser().parseFromString(cache.get(), "text/xml"));
            }
            _self.getRates(code, result);
            callback(true, new Date(last), true);
          }
          else {
            callback(false, "Error loading data: Check internet connection!");
          }  
        }  
      }
      request.onerror = function() {
        if (cache.get()) {
          debug("Xavier Failed - From Cache"); 
          if (!_self.eurData) {
            debug("Parse Cache");
            _self.parseData(new DOMParser().parseFromString(cache.get(), "text/xml"));
          }
          _self.getRates(code, result);
          callback(true, new Date(last), true);
        }
        else {
          callback(false, "Error loading data: Check internet connection!");
        }  
      }
      this.request = request;
      if (window.android) {
        window.android.sendRequest("http://api.finance.xaviermedia.com/api/latest.xml");
      }
      else {
        request.send(null);
      }
      debug("Sent");
    };
    
    this.onload = function(code, text) {
      debug("Received: " + code);
      if (this.request) {
        this.request.responseText = text;
        this.request.status = code;
        this.request.onload();
      }
    };
    
    this.parseData = function(xml) {
      var result = new Object();
      var fx = xml.getElementsByTagName("fx");
      for ( var i = 0; i < fx.length; i++) {
        var obj = new Object();
        obj.symbol = fx[i].getElementsByTagName("currency_code")[0].firstChild.data;
        obj.rate = parseFloat(fx[i].getElementsByTagName("rate")[0].firstChild.data);
        result[obj.symbol + ""]  = obj;
      }
      this.eurData = result;
    }
    
    this.getRates = function(code, result) {
      result.to = new Array();
      var rate1 = this.eurData[code].rate;
      if (rate1 == 0) {
        return;
      }
      for ( var key in this.eurData) {
        var obj = new Object();
        obj.symbol = key;
        obj.rate = this.eurData[key].rate / rate1;
        result.to[key] = obj;
      }
    }

    this.symbols = {
        "USD": "U.S. Dollar $",
        "EUR": "Euro &euro;",
        "JPY": "Japanese Yen &yen;",
        "GBP": "U.K. Pound &pound;",

        "AUD": "Australian Dollar",
        "CAD": "Canadian Dollar",
        "CNY": "Chinese Yuan",
        "RUB": "Russian Ruble",
        "CHF": "Swiss Frank",
        "ZAR": "South African Rand",
        "BGN": "Bulgarian Lev",
        "HRK": "Croatian Kuna",
        "CZK": "Czech Koruna",
        "DKK": "Danish Krone",
        "EEK": "Estonian Kroon",
        "HUF": "Hungarian Forint",
        "NOK": "Norwegian Krone",
        "RON": "Romanian Lei",
        "SEK": "Swedish Krona",
        "HKD": "Honk Kong Dollar",
        "IDR": "Indonesian Rupiah",
        "KRW": "Korean Won",
        "NZD": "New Zealand Dollar",
        "PHP": "Philippine Peso",
        "MYR": "Malaysian Ringgit",
        "SGD": "Singapore dollar",
        "THB": "Thai Baht",
        
        "000": null
    }
  }
  
  function GoogleSource() {
    var _self = this;

    this.setLink = function(link) {
      if (!link) {
        return;
      }
      link.href = "http://www.currencysource.com";
      link.innerHTML = "currencysource.com";
    };
    
    this.reload = function(bypassCache, code, rssResult, callback) {
      var url = "http://currencysource.com/RSS/" + code;
      url += ".xml";
      var feed = new google.feeds.Feed(url);
      feed.setNumEntries(50);
      feed.load(function(result) {
        if (!result.error) {
          rssResult.to = new Object();
          for (var i = 0; i < result.feed.entries.length; i++) {
            var entry = result.feed.entries[i];
            var line = _self.parseDataLine(entry.title);
            rssResult.to[line.symbol + ""] = line;
          }
          callback(true, new Date());
        }
        else {
          callback(false, result.error.message);
        }
      });
    };
    
    this.parseDataLine = function(line) {
      var result = new Object();
      result.line = line;
      var index = line.indexOf("=");
      if (index > 0) {
        var symbol = line.substring(index + 2, index + 5);
        result.symbol = symbol;
      }
      index = line.indexOf("(");
      if (index > 0) {
        var end = line.indexOf(")", index);
        if (end > 0) {
          result.rate = parseFloat(line.substring(index + 1, end));
        }
      }
      return result;
    };
    
    this.symbols = {
        "USD": "U.S. Dollar $",
        "EUR": "Euro &euro;",
        "JPY": "Japanese Yen &yen;",
        "GBP": "U.K. Pound &pound;",
        "ARS": "Argentine Peso",
        "AUD": "Australian Dollar",
        "BHD": "Bahrain Dinar",
        "BRL": "Brazilian Real",
        "BND": "Brunei Dollar",
        "CAD": "Canadian Dollar",
        "CLP": "Chilean Peso",
        "CNY": "Chinese Yuan",
        "COP": "Colombian Peso",
        "DKK": "Danish Krone",
        "HUF": "Hungarian Forint",
        "ISK": "Icelandic Krona",
        "INR": "Indian Rupee",
        "IDR": "Indonesian Rupiah",
        "ILS": "Israeli New Shekel",
        "KRW": "Korean Won",
        "KWD": "Kuwaiti Dinar",
        "MXN": "Mexican Peso",
        "NZD": "New Zealand Dollar",
        "NOK": "Norwegian Krone",
        "PKR": "Pakistan Rupee",
        "SAR": "Saudi Arabian Riyal",
        "SGD": "Singapur Dollar",
        "ZAR": "South African Rand",
        "SEK": "Swedish Krona",
        "CHF": "Swiss Frank",
        "THB": "Thai Baht",
        
        "000": null
    };
  }
