function goToDownload(attachment) {
	// haal de url
	new Request.JSON({
		url: 'http://' + site_url + '/index.php?action=ajaxgetattachments',
		data: 'attach_to=' + attachment[0] + '&attach_to_id=' + attachment[1],
		onComplete: function(response) {
			location.href = 'http://' + site_url + '/' + response.file.filepath;			
		}
	}).send();
}

window.addEvent('domready', function() {
	
	// let op 'bonus' linkjes
	$$('.download-bonus').each(function(link) {
		link.addEvent('click', function(e) {
			e.stop();
			
			var attach= this.get('rel').split(':'), pos = this.getPosition();
			
			// heb je nog geen cookie?
			if (Cookie.read('sela_bonus') == null) {
				// dan eerst nog even je e-mailadres achterlaten
				var overlay = drawOverlay();
				overlay.setStyle('background', 'none');
				
				new Element('div', {
					'class': 'bonus',
					'html': '<div class="bonus-container"><div class="item"><strong>Vul eenmalig je e-mailadres in</strong><br /><input type="email" class="input" /><input type="submit" class="submit" value="Download bestand" /><br /><br /><span id="cancel">Annuleren</span></div></div>',
					'styles': {
						top: (pos.y - 20)
					}
				}).inject(overlay);
				
				// actie!
				overlay.getElement('input.submit').addEvent('click', function() {
					if (!overlay.getElement('input.input').get('value').trim().test('^[a-z0-9._%+-]+@(?:[a-z0-9-]+\.)+[a-z]{2,4}$', 'i')) 
						alert('Geef een geldig e-mailadres op');
						
					else {
						// cookie zetten
						Cookie.write('sela_bonus', 1, {duration: 365});
						
						// emailadres opslaan
						new Request({
							url: 'index.php?action=ajaxsaveemail',
							data: 'email=' + overlay.getElement('input.input').get('value').trim()
						}).send();
						
						// opruimen
						overlay.destroy();
						
						// naar de downloads!
						goToDownload(attach);
						
					}
				});
				// annuleren
				overlay.getElement('span#cancel').addEvent('click', function() {
					overlay.destroy();
				});
			}
			else {
				// direct naar de downloads!
				goToDownload(attach);
			}
		});
	});
});
