var script_location = "/wp-content/plugins/worldfirst/worldfirst-ajax.php";


function Hash()
{
	this.length = 0;
	this.items = new Array();
	for (var i = 0; i < arguments.length; i += 2) {
		if (typeof(arguments[i + 1]) != 'undefined') {
			this.items[arguments[i]] = arguments[i + 1];
			this.length++;
		}
	}
   
	this.removeItem = function(in_key)
	{
		var tmp_previous;
		if (typeof(this.items[in_key]) != 'undefined') {
			this.length--;
			var tmp_previous = this.items[in_key];
			delete this.items[in_key];
		}
	   
		return tmp_previous;
	}

	this.getItem = function(in_key) {
		return this.items[in_key];
	}

	this.setItem = function(in_key, in_value)
	{
		var tmp_previous;
		if (typeof(in_value) != 'undefined') {
			if (typeof(this.items[in_key]) == 'undefined') {
				this.length++;
			}
			else {
				tmp_previous = this.items[in_key];
			}

			this.items[in_key] = in_value;
		}
	   
		return tmp_previous;
	}

	this.hasItem = function(in_key)
	{
		return typeof(this.items[in_key]) != 'undefined';
	}

	this.clear = function()
	{
		for (var i in this.items) {
			delete this.items[i];
		}

		this.length = 0;
	}
}


var Worldfirst = {
  'key': 'YW1iZXJncmVlbjpNYXJxdWlzZVA3OTM=',
  'rate': 0.0,
  'from_value' : 0.0,
  'from_name' : '',
  'to_value' : 0.0,
  'to_name' : '',
  'amount_to_convert': 0.0,
  'total_amount': 0.0
};

Worldfirst.currency_hash = new Hash(
  "EUR", 1,
  "GBP", 2,
  "AUD", 3,
  "NZD", 4,
  "BWP", 5,
  "USD", 6,
  "CAD", 7,
  "CHF", 8,
  "SGD", 9,
  "DKK", 10,
  "ZAR", 11,
  "HKD", 12,
  "NOK", 13,
  "TRY", 14,
  "PLN", 15,
  "AED", 16,
  "SEK", 17,
  "BBD", 18,
  "BHD", 19,
  "CYP", 20,
  "CZK", 21,
  "ILS", 22,
  "INR", 23,
  "ISK", 24,
  "JMD", 25,
  "JOD", 26,
  "KES", 27,
  "KWD", 28,
  "MAD", 29,
  "MTL", 30,
  "MUR", 31,
  "MXN", 32,
  "OMR", 33,
  "QAR", 34,
  "SAR", 35,
  "THB", 36,
  "TND", 37,
  "TZS", 38,
  "XCD", 39,
  "SKK", 40,
  "CNY", 41,
  "EGP", 42,
  "FJD", 43,
  "MYR", 44,
  "PHP", 45,
  "PKR", 46,
  "TTD", 47,
  "JPY", 48,
  "HUF", 49,
  "RON", 50
);

// Define namespaced functions
Worldfirst.roundNumber = function(num, dec) {
  return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
};

Worldfirst.loading = function() {
  jQuery('#result_hook').html('');
  var output = ['<p class="wf-message">'];
    output.push('Loading.......');
  output.push('</p>');
  jQuery('#result_hook').append(output.join(''));
};

Worldfirst.append_result = function() {
  jQuery('#result_hook').html('');
  var output = ['<p class="wf-message">'];
    output.push('<strong>At current exchange rates you will receive: ' + Worldfirst.total_amount + ' ' + Worldfirst.to_name +'</strong> (Rate: ' + Worldfirst.rate + ')');
  output.push('</p>');
  jQuery('#result_hook').append(output.join(''));
};

Worldfirst.append_error = function(error_type) {
  jQuery('#result_hook').html('');
  switch(error_type)
  {
    case 0:
      var output = ['<p class="wf-error">'];
        output.push('We are currently unable to ascertain this rate at present.');
      output.push('</p>');
    break;
    case 1:
      var output = ['<p class="wf-error">'];
        output.push('<strong>Error:</strong><br />');
        output.push('The currency amount must be a number greater than zero.');
      output.push('</p>');
    break;
    case 2:
      var output = ['<p class="wf-error">'];
        output.push('We are currently unable to ascertain this rate at present.');
      output.push('</p>');
    break;
  }; 
  jQuery('#result_hook').append(output.join(''));
};

jQuery(document).ready(function() {
  jQuery('#worldfirst_currency').submit(function() {
    // Do the loading screen
    Worldfirst.loading();
    
    // Get the values from the DOM
    Worldfirst.from_value = jQuery('#currency_from').val();
    Worldfirst.from_name = jQuery('#currency_from :selected').text();
    Worldfirst.to_value = jQuery('#currency_to').val();
    Worldfirst.to_name = jQuery('#currency_to :selected').text();
    Worldfirst.amount_to_convert = parseFloat(jQuery('#amount_to_convert').val());
    
    // Now we check that the amount entered is valid
    if (Worldfirst.amount_to_convert > 0.0 && typeof Worldfirst.amount_to_convert == 'number') {
      
      // Set divide equal to false and set the default conversion rate up
      var div = false;
      var from_value = Worldfirst.from_value;
      var to_value = Worldfirst.to_value;
      
      // Here we check if the order is correct for worldfirst, if not we reverse it and tell the widget to divide
      var order_from = Worldfirst.currency_hash.getItem(Worldfirst.from_value);
      var order_to = Worldfirst.currency_hash.getItem(Worldfirst.to_value);
      if (order_from > order_to) {
        div = true;
        var from_value = Worldfirst.to_value;
        var to_value = Worldfirst.from_value;
      }
      
      // Do a GET request to fetch the data
      jQuery.get(script_location,
      {
        'worldfirst_get_rate': 'true',
        'from': from_value,
        'to': to_value,
        'key': Worldfirst.key,
      }, function(data, status) {
        if (typeof data.error == 'undefined') {
          if (data.output == "NOQUOTE") {
            Worldfirst.append_error(2);
          } else {
            Worldfirst.rate = Worldfirst.roundNumber(data.RATE, 3);
            
            if (div) {
              Worldfirst.total_amount = Worldfirst.roundNumber((Worldfirst.amount_to_convert / Worldfirst.rate), 2);
            } else {
              Worldfirst.total_amount = Worldfirst.roundNumber((Worldfirst.amount_to_convert * Worldfirst.rate), 2);  
            }
              
            
            Worldfirst.append_result();
          }
        } else {
          Worldfirst.append_error(0);
        }  
      }, 'json');
    } else {
      Worldfirst.append_error(1);
    }
    return false;
  });
});