var Application = Class.create();
Application.prototype = {
	initialize: function() {
		Event.observe(window, "load",   this.boot.bind(this));
		Event.observe(window, "unload", this.shutdown.bind(this));
	},
	
	boot: function() {
		// console.log("Booting");

		Event.observe($("chk_education"),   'change', this.show_edu_details);
		Event.observe($("input_quantity"),  'keyup',  this.change_quantity);
		
		Event.observe($("select_seats"),    'change', function(e) {
			$("chk_site_license").checked = true;
		});
		
    this.pluralise_licenses();
	},
	
	shutdown: function() {
		// console.log("Shutting down");
		// Form.enable("form_purchase");
		$("submit_button").disabled = false; // TODO: enable the button on unload?
	},
	
	show_edu_details: function(e) {
		if($("chk_education").checked) {
			new Effect.Parallel([
				new Effect.Appear("edu_details"),
				new Effect.BlindDown("edu_details")
			], {duration: 0.5});
		} else {
			new Effect.Parallel([
				new Effect.Fade("edu_details"),
				new Effect.BlindUp("edu_details")
			], {duration: 0.5});
		}
	},
	
  change_quantity: function(e) {
    $("chk_single_user").checked = true;
    window.app.pluralise_licenses();
  },

  price: function(eur) {
    eur = eur * (100 + vat_rate) / 100;
    var str = '€' + eur;
    var usd = '$' + Math.round(eur * rate + 0.5);
    if(only_usd) {
      str = usd;
    }
    else if(rate > 0) {
      str += ' ≈ ' + usd;
    };
    return str;
  },

	pluralise_licenses: function() {
		var qty = Math.abs($("input_quantity").value);
		if(qty == 1) {
			$("license_pluralism").innerHTML = 'license (' + this.price(39) + ')';
		} else if(qty > 1) {
      var discount = 0;
      if(qty >= 15)       { discount = 30; }
      else if(qty >= 10)  { discount = 25; }
      else if(qty >= 4)   { discount = 20; }

      var eur = Math.round(qty * 39 * (100 - discount) / 100);
			$("license_pluralism").innerHTML = 'licenses (' + this.price(eur) + ')';
		}
	}
}

window.app = new Application();

function validate_form (form) {
    var res = true;
    $('submit_button').disabled = true;

    var vat_number = form.vat_number.value;
    if(vat_number != '') {
        new Ajax.Request('/service/validate_vat', {
            method:       'get',
            asynchronous: false,
            parameters:   { iso: form.country.value, number: vat_number },
            onSuccess: function(transport){
              var data = transport.responseJSON;
              if(!data.valid) {
                  alert(data.error + "\n\nWe validate VAT numbers via VIES. Please see their FAQ for problems: http://ec.europa.eu/taxation_customs/vies/faqvies.do");
                  res = false;
                  $('submit_button').disabled = false;
              }
            }
        });
    }

    return res;
}

