// note: Don't waste your time overwriting,
// I'm not allowing invalid requests anyways.
(function() {
					
var License = {
  setProject: function(project) {
	  this.project = project;
		delete window.License;
	}
};

window.License = License;

var info = {
  Lightview : {
	  noncommercial: {
		  description: 'Non-commercial - Single domain',
		  price: 3
	  },
	  noncommercialUnlimited: {
		  description: 'Non-commercial - Unlimited',
		  price: 15
	  },
	  commercial: {
		  description: 'Commercial - Single domain',
		  price: 49
	  },
	  commercialUnlimited: {
		  description: 'Commercial - Unlimited',
		  price: 295
	  }
  },
  Prototip : {
	  noncommercial: {
		  description: 'Non-commercial - Single domain',
		  price: 3
	  },
	  noncommercialUnlimited: {
		  description: 'Non-commercial - Unlimited',
		  price: 15
	  },
	  commercial: {
		  description: 'Commercial - Single domain',
		  price: 49
	  },
	  commercialUnlimited: {
		  description: 'Commercial - Unlimited',
		  price: 295
	  }
  },
  Starbox : {
	  noncommercial: {
		  description: 'Non-commercial - Single domain',
		  price: 3
	  },
	  noncommercialUnlimited: {
		  description: 'Non-commercial - Unlimited',
		  price: 15
	  },
	  commercial: {
		  description: 'Commercial - Single domain',
		  price: 29
	  },
	  commercialUnlimited: {
		  description: 'Commercial - Unlimited',
		  price: 145
	  }
  }
};


var EUCountries = ['Belgium', 'Bulgaria', 'Cyprus', 'Denmark', 'Germany', 'United Kingdom', 'Estonia', 'Finland', 'France', 'Greece', 'Hungary', 'Ireland', 'Italy', 'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Netherlands', 'Austria', 'Poland', 'Portugal', 'Romania', 'Slovenia', 'Slovak Republic', 'Spain', 'Czech Republic', 'Sweden'];

var Helpers = {
	inNL: function() {
		return $F('country') == 'Netherlands';
	},
	
	inEU: function() {
		return EUCountries.member($F('country'));
	},
	
	isVATShifted: function() {
		return this.inEU() && !this.inNL() && this.isVATRegistered();
	},
	
	isCompany: function() {
		return !$F('company').blank();
	},
	
	/* VAT Registered */
	setVATRegisteredRadios: function(registered) {
		var radios = $('paypal_purchase').select('input.radio[name=isVATRegistered]');
		
		radios[0].checked = registered ? false : true;
		radios[1].checked = registered;
		
		//$('company')[(registered ? 'add' : 'remove') + 'ClassName']('required');
		$('vatid')[(registered ? 'add' : 'remove') + 'ClassName']('required');
	},
	
	removeBadCompanyVAT: function() {
		$('company').removeClassName('bad');
		$('vatid').removeClassName('bad');
	},
	
	isVATRegistered: function() {
		return $('paypal_purchase').select('input.radio[name=isVATRegistered]')[1].checked;
	}

};
var _H = Helpers;

function changeCountry() {
  // clean up
  $('vatid').value = '';
	$('company').value = '';
  $('vatid').removeClassName('required');
	//$('company').removeClassName('required');

  if (_H.inNL()) {
		_H.setVATRegisteredRadios(false);
		$('vatRegisteredContainer').hide();
		$('EUVATid').hide();
	  $('companyContainer').show();
	}
	else if (_H.inEU()) {
		// radio zichtbaar maken
		$('vatRegisteredContainer').show();
		
		// als radio geselecteerd is
		if (_H.isVATRegistered()) {
			$('companyContainer').show();
			$('EUVATid').show();
			// company en vat zijn verplicht als je een VAT ID hebt
			//$('company').addClassName('required');
			$('vatid').addClassName('required');
		} else {
			$('companyContainer').hide();
			$('EUVATid').hide();
		}
	} else {
		// buiten EU
		_H.setVATRegisteredRadios(false);
		$('vatRegisteredContainer').hide();
		$('EUVATid').hide();
		$('companyContainer').show();
	}
}

// radio buttons
function changeVATRegistered() {
	var registered = _H.isVATRegistered() && !_H.inNL() && _H.inEU();
	
	if (!registered) {
		$('company').value = '';
		$('vatid').value = '';
		_H.removeBadCompanyVAT();
	}
		
	$('EUVATid')[registered ? 'show' : 'hide']();
	$('companyContainer')[registered ? 'show' : 'hide']();
	//$('company')[(registered ? 'add' : 'remove') + 'ClassName']('required');
	$('vatid')[(registered ? 'add' : 'remove') + 'ClassName']('required');
}

function paypalPost() {
  // disable buttons while processing submit
  $$('a.submit').invoke('stopObserving', 'click');

  this.stopObserving();
  this.removeClassName('paypalCorrect');
  this.addClassName('loading');

  new Ajax.Request('include/createorder.php', {
	  parameters: $('paypal_purchase').serialize(),
	  beforeStart: Form.disable.curry('paypal_purchase'),
	  onComplete: function(xhr) {
			$('custom').value = xhr.responseText;
			$('paypal_purchase').submit();
	  }
  });
}

function doubleCheck(event) {
  event.stop();
  
  // cleanup
  $('shiftedvat').value = 0;
  $('shiftedtotal').value = 0;

  var selected = $F('selectedLicense'),
			form = $('paypal_purchase'),
			project = License.project,
			price = '' + (info[project.capitalize()][selected].price).toFixed(2),
			isSingle = $('remindSelectedLicense').innerHTML.toLowerCase().include('single'),
			message = '',
			inNL = _H.inNL(),
			inEU = _H.inEU(),
			tax = ((inEU && !_H.isVATRegistered()) || inNL) ? (price * 0.19).toFixed(2) : 0, // EU niet VAT geregistreerden betalen ook 19% VAT, zoals NL
			vatShifted = _H.isVATShifted();

  //console.log('project: ', License.project);
	var feedback = [];
	
	
  // set europe
  $('EU').value = (inEU ? 'inside' : 'outside');

  $('feedback').removeClassName('good');
  if (!project) {
    $('feedback').update('Please select a project.').show();
		return;
  }

  // set the product
  $('item_name').value = project.capitalize() + ' ' + info[project.capitalize()][selected].description;

  // check each required input
  var bad = 0;
  form.select('.required').each(function(element) {
		if (element.id != 'domain' && element.value == '') {
			bad++;
			element.addClassName('bad');
		}
		else if (isSingle && element.value == '') {
			bad++;
			element.addClassName('bad');
		}
		else element.removeClassName('bad');
  });

  // country
  if ($F('country') == 'select') {
    bad ++;
		$('country').addClassName('bad');
  }
  else $('country').removeClassName('bad');

  if (bad) {
		feedback.push('You forgot ' + ((bad == 1) ? 'a' : 'some') + ' required field' + ((bad == 1) ? '' : 's'));
	}
	
  // email
  if ($F('email') && !$('email').hasClassName('bad') && $F('email') != $F('email_confirm')) {
		$('email').addClassName('bad');
		$('email_confirm').addClassName('bad');
		feedback.push('Email address not confirmed');
  }
  
	// company en vat id zijn verplicht als je vat registered bent
	if (_H.isVATRegistered()) {
		/*if ($F('company').length < 1) {
			$('company').addClassName('bad');
		  feedback.push('Please provide your company name for VAT shifting purposed, if you don\'t have one answer "No" to "VAT registered"');
		}*/
		var VATID = $F('vatid');
		if (VATID.length < 5 || !VATID.match(/\d/) || !VATID.match(/^([A-Za-z]{2})/)) {
			$('vatid').addClassName('bad');
			feedback.push('Please enter a valid VAT Identification Number for VAT Shifting purposes. It should be a number prefixed with your country code, e.g. FR64752393038.');
			feedback.push('Please make sure the VAT ID is valid using the <a href="http://ec.europa.eu/taxation_customs/vies/vieshome.do" target="_blank">VIES Website</a>, it will help you get the correct formatting.');
			feedback.push('If you don\'t have a an ID answer "No" to "VAT registered"');
		}
	}
  
  // give feedback
  if (feedback.length > 0) {
		var message = feedback.join('<br\/>');
  	$('feedback').update(message).show();
		$('confirmation').hide();
		//(function() { new Effect.ScrollTo('page', { duration: 0.24 }); }).delay(0.3);
  }
  else {
	// set the Price
    $('tax').value = tax;
    $('price').value = price;
    $('total').value = parseFloat(price) + parseFloat(tax);
	if (vatShifted) {
	  $('shiftedvat').value = (parseFloat(price) * 0.19).toFixed(2);
	  $('shiftedtotal').value = (parseFloat(price) + (parseFloat(price) * 0.19)).toFixed(2);
	}
	else {
		$('shiftedvat').value = 0;
		$('shiftedtotal').value = 0;
	}

	$('feedback').hide();
	
	// double check, show the confirmation
	updateConfirm(event);
		$('data').hide();
    $('confirmation').show();
  }
}

function updateConfirm(event) {
  var c = $('confirmation'),
			isSingle = $('remindSelectedLicense').innerHTML.toLowerCase().include('single'),
			vatShifted = _H.isVATShifted();
  
  c.down('.item').update($F('item_name'));
  c.down('.price').update('&euro; ' + $F('price'));
  c.down('.firstname').update($F('first_name'));
  c.down('.lastname').update($F('last_name'));
  c.down('.address').update($F('address1'));
  c.down('.city').update($F('city'));
  c.down('.postalcode').update($F('postalcode'));
  c.down('.country').update($F('country'));
  c.down('.email').update($F('email'));
  
  if ($F('message'))
    c.down('.message').update($F('message')).up('p').show();
  else
    c.down('.message').up('p').hide();

  // company
  if ($F('company')) {
    c.down('.company').update($F('company')).up('p').show();
	}
	else {
	  c.down('.company').up('p').hide();	
	}
	
	// VAT ID
	if ($F('vatid')) {
			c.down('.vatid').update($F('vatid')).up('p').show();
	}
  else {
  	c.down('.vatid').up('p').hide();
  } 
  
  var tax = parseFloat($F('tax')),
  		price = parseFloat($F('price'));
  
  if (vatShifted)
    c.down('.price').update('&euro; ' +(price + tax).toFixed(2) + ' (Ex. VAT - VAT shifted)');
  else if (tax > 0) // check for EU non-entrepreneur
    c.down('.price').update('&euro; ' +(price + tax).toFixed(2) + ' (&euro; ' + $F('price') + ' + 19% VAT)');

  if (isSingle && $F('domain'))
    c.down('.domain').update($F('domain')).up('p').show();
  else
    c.down('.domain').up('p').hide();
}

function observeSubmits() {
	$('licenseOptions').select('a.submit').invoke('observe', 'click', doubleCheck);
}

function selectProject() {
  var project = $F(this);
  
  if(project != 'select');
    location.href = 'index.php?project=' + project;
}

function selectLicense(event) {
	event.stop();
	
	var selected = event.findElement('a.submit').rel,
			project = $(document.body).id.substr(8);
	
	$('selectedLicense').value = selected;
	$('remindSelectedLicense').update(project.capitalize() + ' ' + info[project.capitalize()][selected].description);
	
	$('licenseOptions').hide();
	$('data').show();
}





document.observe('dom:loaded', function() {
  if ($('selectProject'))
	  $('selectProject').observe('change', selectProject);
  
  if(!$('licenseOptions')) return;
  
  $('licenseOptions').select('a.submit').invoke('observe', 'click', selectLicense);

  $('feedback').observe('click', function(event) {
		var element = event.findElement('a');
		if (!element) this.hide();
	});
  $$('.navlink[rel]').invoke('observe', 'click', function(event) {
		event.element().blur();
		event.stop();
		if (this.rel && $(this.rel)) {
			if (Prototype.Browser.IE6) $(this.rel).scrollTo();
			else new Effect.ScrollTo(this.rel, { duration: 0.6 });
		}
  });

  $('downloads').select('div.links a[rel]').invoke('observe', 'click', function(event) {
		event.stop();
		window.location.href = this.rel;
  });
  $('toPaypal').observe('click', paypalPost);

  $('makeChanges').observe('click', function(event) {
		event.stop();
		$('confirmation').hide();
		$('data').show();
  });

  $$('.asterix').each(function(element) {
		new Tip(element, 'required', { className: 'pinktip' });						   
  });

  $('data').down('.back').observe('click', function() {
		$('data').hide();
		$('licenseOptions').show();
  });
  $('data').down('.next').observe('click', doubleCheck);

  $('country').observe('change', changeCountry);
	
  //$('company').observe('keyup', checkCompany);
	
	// VAT yes/no
	$('paypal_purchase').select('input.radio[name=isVATRegistered]').invoke('observe', 'click', changeVATRegistered);
  
	
	// TODO: select the first country
	$('country').selectedIndex = 0;
	$('company').value = '';
	$('vatid').value = '';
	_H.setVATRegisteredRadios(false);
	//$('companyContainer').hide();
});

})();