/*
 * ANTETYPE Website JavaScript 
 * using MooTools 1.3.1
 * Author: Björn Busch-Geertsema, ERGOSIGN Technologies GmbH 2011
 */

var init = function() {
	// Add class for different styling on non-macs, 
	// e.g. Helvetica Neue rendering issues!
	if(!Browser.Platform.mac)
		$(document.body).addClass('nomac');
	
	if($$('body#index').length > 0)	{
		initDownloadFormSignup();
		initBetaSignup();
		initContentPaneNav();
		initLiveScreenshot();
		initNewsletterForm();
		initAlternatingQuotes();
	}
	
	initTooltips();
	initLightbox();
	
	// EXAMPLES
	if($$('.example-file').length > 0)
		initExamples();
	
	// STORE
	if($$('#store-purchase').length > 0)
		initStore();
		
	// EDU LICENSE APPLICATION
	if($$('#educational-license').length > 0)
		initStudentLicense();
};

var initAlternatingQuotes = function() {
	$$('.header-quote-area.hide').fade('hide').removeClass('hide');
	
	alternateQuotes.periodical(10000, {quotes: $$('.header-quote-area')});
};
var alternateQuotes = function() {
	for(var i = 0; i < this.quotes.length; i++) {
		if(this.quotes[i].hasClass('on')) {
			this.quotes[i].fade('out').removeClass('on');
			this.quotes[(i + 1) % this.quotes.length].fade('in').addClass('on');
			break;
		}
	}
}

var initBetaSignup = function() {
	// Validate lightly
	$$('#beta-signup-flyout input.check-not-empty')
		.addEvent('change', validateNotEmpty)
		.addEvent('blur', validateNotEmpty);
	$$('#beta-signup-flyout input.check-email')
		.addEvent('change', validateEmail)
		.addEvent('blur', validateEmail);
	
	$('beta-signup').addEvent('click', function(event) {
		event.preventDefault();
		
		var flyout = $('beta-signup-flyout');
		var pos = this.getCoordinates();
		
		flyout.setStyles({
			left: pos.left - 4,
			top: pos.bottom - 8
		});
		flyout.inject(document.body);
		flyout.fade('in');
	});
	
	new Form.Placeholder('ipad-beta-name', { color: '#555555' });
	new Form.Placeholder('chihry-chihry', { color: '#555555' });
	
	$('beta-button').addEvent('click', function(e) {
		e.preventDefault();
		
		$$('#beta-signup-flyout input.check-not-empty, #beta-signup-flyout input.check-email').fireEvent('blur');
		
		// display error message if necessary
		var display = $('check-privacy2').get('checked') ? 'none' : 'block';
		$('check-privacy2').getSiblings('.error-message').setStyle('display', display);

		// any error indicators?
		if($$('input.check-error').length > 0 || !$('check-privacy2').get('checked'))
			return; // abort

		// If we get here, everything is ok and we proceed		
		$('beta-form').submit();		
		$('beta-signup-flyout').fade('out');
	});
	$('beta-button-cancel').addEvent('click', function(event) {
		event.preventDefault();
		
		$('beta-signup-flyout').fade('out');
	});
}

var initDownloadFormSignup = function() {
	// Validate lightly
	$$('#download-form input.check-not-empty')
		.addEvent('change', validateNotEmpty)
		.addEvent('blur', validateNotEmpty);
	$$('#download-form input.check-email')
		.addEvent('change', validateEmail)
		.addEvent('blur', validateEmail);
	
	$('download-button').addEvent('click', function(event) {
		event.preventDefault();
		
		var flyout = $('download-signup-flyout');
		var pos = this.getCoordinates();
		
		flyout.setStyles({
			left: pos.left - 25,
			top: pos.bottom - 4
		});
		flyout.inject(document.body);
		flyout.fade('in');
	});
	
	new Form.Placeholder('download-form-name', { color: '#555555' });
	new Form.Placeholder('download-form-email', { color: '#555555' });
	
	$('download-form-button').addEvent('click', function(e) {
		e.preventDefault();
		
		$$('#download-form input.check-not-empty, #download-form input.check-email').fireEvent('blur');
		
		// display error message if necessary
		var display = $('check-privacy').get('checked') ? 'none' : 'block';
		$('check-privacy').getSiblings('.error-message').setStyle('display', display);

		// any error indicators?
		if($$('input.check-error').length > 0 || !$('check-privacy').get('checked'))
			return; // abort

		// If we get here, everything is ok and we proceed with the download
		
		// fetch data
		var cmNameValue = $$('#download-form #download-form-name')[0].get('value').trim();
		var cmEmailValue = $$('#download-form #download-form-email')[0].get('value').trim();
		
		if($('check-mail-news').get('checked')) {
			// Register with campaign monitor
			var cmURL = 'http://antetype.createsend.com/t/r/s/fhyhdk/'
			var cmEmail = 'cm-fhyhdk-fhyhdk';
			
			// Register via AJAX/JSONP
			// Mootools Request.JSONP doesn't work because of bad URL
			var ajaxURL = cmURL + '?callback=registerDownload&cm-name=' + encodeURIComponent(cmNameValue) + '&' + cmEmail + '=' + encodeURIComponent(cmEmailValue);
			var ajaxCall = new Element('script');
			ajaxCall.set('src', ajaxURL);
			ajaxCall.inject(document.body);
		} else {
			// Downloader doesn't want newsletter, save locally
			var jsonRequest = new Request.JSON({
				url: './ajax-register-download.php',
				data: 'name=' + encodeURIComponent(cmNameValue) + '&email=' + encodeURIComponent(cmEmailValue),
				method: 'post',
				onSuccess: registerDownload
			}).send();
		}
	});
	$('download-form-button-cancel').addEvent('click', function(event) {
		event.preventDefault();
		
		$('download-signup-flyout').fade('out');
	});
}
var registerDownload = function(r) {
	$('download-signup-flyout').fade('out');

	// Start download by forwarding to the download page
	document.location = 'http://www.antetype.com/download.php';
}

/* TOOLTIP FUNCTIONS */
var initTooltips = function() {
	// remove warning tooltips if possible
	if(Browser.safari || Browser.chrome || (Browser.firefox && Browser.version >= 4) ) {

		$$('#tooltip-webviewer1, #tooltip-webviewer2, #tooltip-webviewer3, #tooltip-webviewer4, #tooltip-webviewer5, #tooltip-webviewer6, #tooltip-webviewer7, #tooltip-webviewer8').dispose();
	}
	
	$$('.tooltip').each(function(tooltip, index) { // cycle through all tooltips
		tooltip.fade('hide');	// hide tooltips
		
		// find corresponding tooltip trigger element, has class 'has-tooltip-xyz'
		var id = tooltip.get('id').split('-');
		var tooltipTrigger = $$('.has-tooltip-' + id[1]); 
		
		if(tooltipTrigger.length == 0)
			return;
		
		tooltipTrigger = tooltipTrigger[0];
		
		// store relevant information
		tooltip.store('tooltipVisible', false);
		tooltip.store('tooltipTrigger', tooltipTrigger);
		tooltip.store('tooltipHover', false);
		tooltipTrigger.store('tooltipVisible', false);
		tooltipTrigger.store('tooltip', tooltip);
		tooltipTrigger.store('tooltipHover', false);
		
		// add events
		tooltipTrigger.addEvent('mouseenter', showTooltip.bind(tooltipTrigger));
		tooltipTrigger.addEvent('mouseenter', mouseEnterTooltip.bind(tooltipTrigger));
		tooltipTrigger.addEvent('mouseleave', mouseLeaveTooltip.bind(tooltipTrigger));
		tooltip.addEvent('mouseenter', mouseEnterTooltip.bind(tooltip));
		tooltip.addEvent('mouseleave', mouseLeaveTooltip.bind(tooltip));
	});
};
var showTooltip = function() {
	// this: tooltipTrigger
	
	var tooltip = this.retrieve('tooltip');
	if(tooltip.retrieve('tooltipVisible')) return; // tooltip already visible
	
	var arrowAdjustment = tooltip.getChildren('.tooltip-arrow')[0].getStyle('left').toInt() + 5;
	
	// position tooltip
	var pos = this.getCoordinates();
	if(tooltip.hasClass('small-target')) {
		// precise positioning, for live screenshot dots
		tooltip.setStyles({
			left: pos.left + (pos.width / 2) - arrowAdjustment,
			top: pos.bottom - 3
		});
		
	} else {
		// less precise positioning, appropriate for buttons
		tooltip.setStyles({
			left: pos.left - arrowAdjustment + 30
		});
		
		// temporarily fix hover styling to avoid flickering when tooltip appears on top
		// of the button, under the cursor!
		this.addClass('hover');
		(function() { this.removeClass('hover'); }).bind(this).delay(550);
		
		tooltip.morph({
			top: [pos.bottom - 15, pos.bottom - 4]
		});
	}
	
	// show tooltip
	tooltip.fade('in');
	
	tooltip.store('tooltipVisible', true);
};
var mouseEnterTooltip = function() {
	this.store('tooltipHover', true);
};
var mouseLeaveTooltip = function() {
	this.store('tooltipHover', false);
	hideTooltip.bind(this).delay(350); // trigger tooltip hide after some delay
};
var hideTooltip = function() {
	// hide tooltip, but only if cursor neither over tooltip nor trigger!
	// we don't know if this function has been triggered by the tooltip or the trigger!
	var tooltip = this.retrieve('tooltip');
	if(tooltip == null)
		tooltip = this;
	var tooltipTrigger = this.retrieve('tooltipTrigger');
	if(tooltipTrigger == null)
		tooltipTrigger = this;
	
	if(tooltip.retrieve('tooltipHover') == false
		&& tooltipTrigger.retrieve('tooltipHover') == false) {
		
		tooltip.fade('out');
		tooltip.store('tooltipVisible', false);	
	}
};

/* CONTENT PANE NAVIGATION */
var animationActive = false;
var currentContentPane = 'contentarea-widgetlibrary';
var initContentPaneNav = function() {
	$$('.sub-nav-item, #dot-nav span').each(function(item, index) {
		var id = item.get('id').split('-');
		
		item.store('order', index);			// store correct order to know if to scroll to left or right
		item.store('contentpane', id[2]);	// store id for corresponding content pane
		item.addEvent('click', navigateContentPane.bind(item));
											// add click handler
	});
};
var navigateContentPane = function() {
	// only run if no navigation is active
	if(animationActive)	return;
	animationActive = true;
	
	// find correct contentpane to navigate to
	var paneId = this.retrieve('contentpane');
	var pane = $('contentarea-' + paneId);
	
	// sind schon da!
	if(currentContentPane == 'contentarea-' + paneId) {
		animationActive = false;
		return;
	}
	currentContentPane = 'contentarea-' + paneId;
	
	// determine direction of animation, it doesn't matter if we use the top or the bottom (dot) nav for this
	var direction = $('sub-nav-' + paneId).retrieve('order') < $$('.sub-nav-item.on')[0].retrieve('order') ? 'right' : 'left';
	
	// update navigation buttons
	$$('.sub-nav-item.on, #dot-nav span.on').removeClass('on');
	$$('#sub-nav-' + paneId + ', #dot-nav-' + paneId).addClass('on');
	
	
	var totalWidth = $('stripe-contentarea').getSize().x;
	
	// calculate target position
	var targetPosition = direction == 'left' ? -1 * ((totalWidth - 960) / 2) - 960 : totalWidth;
	
	// Animate
	var slideOutFx = new Fx.Tween($$('.contentarea-pane.on')[0], {
		property: 'left',
		unit: 'px',
		transition: 'quad:in:out',
		onComplete: function(element) {
			element
				.removeClass('on')
				.setStyle('left', '-9999px');
		}
	}).start(targetPosition);
	
	// calculate origin
	var originPosition = direction == 'left' ?  totalWidth : -1 * ((totalWidth - 960) / 2) - 960;
	
	// Animate
	var slideInFx = new Fx.Tween(pane, {
		property: 'left',
		unit: 'px',
		transition: 'quad:in:out',
		onComplete: function(element) {
			element.addClass('on');
			animationActive = false;
		}
	}).start(originPosition, 0);
	
	if(paneId == 'dynamiclayout')
		initToolbarAnimation();
};
var initToolbarAnimation = function() {
	$$('#features-toolbar-area-cutoff div').addClass('hidden-icon');
	
	$$('#features-toolbar-area-cutoff div.hidden-icon').each(function(item, index) {
		(function() { item.removeClass('hidden-icon'); }).delay((index+1) * 2000);
	});
};

/* SCREENSHOT INTERACTIVE ELEMENTS */
var initLiveScreenshot = function() {
	$$('.screenshot-overlay').fade('hide').setStyle('display', 'block');
	
	// preload overlay images
	Asset.image('./img/live-screenshot-resize.jpg');
	Asset.image('./img/live-screenshot-zoom.jpg');
	
	$('resizing-button')
		.addEvent('mousedown', function() {
			$('screenshot-overlay-resize').fade('in');
			
			$('sc-resizing').addClass('resized');
			$('tooltip-resizing').addClass('resized');

			// delay hiding for at least 1.2 seconds!
			this.store('delayHiding', true);
			(function() { this.store('delayHiding', false); }.bind(this)).delay(1200);
		})
		.addEvent('mouseup', function() {
			var hideme = function() {
				// check if delay has finished already, else wait and try again
				if(this.retrieve('delayHiding')) {
					hideme.delay(250);
					return;
				};
				
				$('screenshot-overlay-resize').fade('out');

				$('sc-resizing').removeClass('resized');
				$('tooltip-resizing').removeClass('resized');
			}.bind(this);
			
			hideme.delay(250);
		});
	
	$('zoom-button')
		.addEvent('mousedown', function() {
			$('screenshot-overlay-zoom').fade('in');
			
			// delay hiding for at least 1.2 seconds!
			this.store('delayHiding', true);
			(function() { this.store('delayHiding', false); }.bind(this)).delay(1200);
		})
		.addEvent('mouseup', function() {
			var hideme = function() {
				// check if delay has finished already, else wait and try again
				if(this.retrieve('delayHiding')) {
					hideme.delay(250);
					return;
				};
				
				$('screenshot-overlay-zoom').fade('out');
			}.bind(this);
			
			hideme.delay(250);
		});
};

/* LIGHTBOX INITIALIZATION */
var initLightbox = function() {
	
	// no lightbox for iOS
	if(Browser.Platform.ios) return;
	
	// no lightbox for IE < 8
	if(Browser.ie6 || Browser.ie7) return;
	
	new XtLightbox('#overview-video-poster', {
		adaptors: ['Vimeo'],
		adaptorOptions: {
			Vimeo: {
				width: 604,
				height: 454
				}
	        },
		incrementalPreLoad: 0	
	});
	new XtLightbox('.tutorial-video a.poster', {
		adaptors: ['Vimeo'],
		adaptorOptions: {
			Vimeo: {
				width: 768,
				height: 454
			}
	     },
		rendererOptions: {
			positionText: 'Tutorial {x} of {total}'
		},
		incrementalPreLoad: 0	
	});
};

/* NEWSLETTER FORM INIT */
var initNewsletterForm = function() {
	new Form.Placeholder('name', { color: '#555555' });
	new Form.Placeholder('kydudd-kydudd', { color: '#555555' });
	
	$('newsletter-button').addEvent('click', function(e) {
		e.preventDefault();
		$('newsletter-form').submit();
	});
};

/* WEB EXAMPLES */
var initExamples = function() {
	
}

/* STORE */
var licensePrice = {
	USD: 289,
	EUR: 199
};
var studentLicensePrice = 49;
var vat = 19;
var needsVAT = false;
var isEU = false;
var isDE = false;

function initStore() {
	// init currency
	$('switch-currency-usd').addEvent('click', handleCurrencyClick.bind({ currency: 'USD' }));
	$('switch-currency-eur').addEvent('click', handleCurrencyClick.bind({ currency: 'EUR' }));
	
	// update total price	
	$('copies').addEvent('change', updateAmount);
	updateAmount();
	
	$('country')
		.addEvent('click', updateAmount)
		.addEvent('blur', updateAmount);
	
	displayVATID();
	
	// form validation
	initFormValidation();
	
	$('submit').addEvent('click', nextStep);
	
	new Form.Placeholder('company');
	new Form.Placeholder('zip');
}
function handleCurrencyClick(event) {
	event.preventDefault();
	
	switchCurrency(this.currency);
}
function switchCurrency(currency, updateNeeded) {
	if(updateNeeded == null)
		updateNeeded = true;
		
	if(currency == 'EUR') {
		$('switch-currency-usd').removeClass('on');
		$('switch-currency-eur').addClass('on');
		$('currency').set('value', 'EUR');
	} else {
		$('switch-currency-eur').removeClass('on');
		$('switch-currency-usd').addClass('on');
		$('currency').set('value', 'USD');
	}
	if(updateNeeded) updateAmount();
}
function updateAmount() {
	checkMwSt();
	var copies = $('copies').get('value');
	copies = copies.toInt();
	if(copies < 1) {
		copies = 1;
		$('copies').set('value', '1');
	}
	
	// check VAT
	var vatFactor = 1;
	if(needsVAT) {
		vatFactor = 1 + vat/100;
		$('vat-info').setStyle('display', 'block');
	} else {
		$('vat-info').setStyle('display', 'none');
	}
	// update price
	var currency = $('currency').get('value');
	var price = copies * licensePrice[currency] * vatFactor;
	
	if(couponResult != null) {
		switch(couponResult.type) {
			case 'student':
				// Student license is always US $
				switchCurrency('USD', false);
				currency = 'USD';
				$$('#switch-currency-eur, #switch-currency-usd').setStyle('display', 'none');
			
				$('coupon-info')
					.setStyle('display', 'block')
					.set('text', 'discounted educational license');
				price = studentLicensePrice;
				
				break;
			case 'price':
				switchCurrency(couponResult.currency, false);
				currency = couponResult.currency;
				$$('#switch-currency-eur, #switch-currency-usd').setStyle('display', 'none');
			
				$('coupon-info')
					.setStyle('display', 'block')
					.set('text', 'reduced price');
				price = couponResult.value * vatFactor;
				
				break;
			case 'percent':
				$('coupon-info')
					.setStyle('display', 'block')
					.set('text', 'discounted by ' + couponResult.value + '%');
				price = licensePrice[currency] * (1 - couponResult.value/100) * vatFactor;
				break;
			case 'free':
				$$('#switch-currency-eur, #switch-currency-usd').setStyle('display', 'none');
				$('coupon-info').setStyle('display', 'none');
				price = 0;
				
				$('amount').set('html', 'FREE COPY');
				
				// hide payment options
				$('payment-options').setStyle('display', 'none');
				
				return; // cancel execution of the rest
		}
	} else {
		$('coupon-info').setStyle('display', 'none')
	}
	
	$('amount').set('html', price.format({
		decimal: '.',
		group: ',',
		decimals: 2,
		prefix: currency == 'USD' ? 'US $ ' : 'EUR '
	}));
	
	// Update VAT Amount
	if(needsVAT) {
		vatAmount = (vat * price / (1+vat/ 100)) / 100;
		$('vat-amount').set('html', vatAmount.format({
			decimal: '.',
			group: ',',
			decimals: 2,
			prefix: currency == 'USD' ? 'US $ ' : 'EUR '
		}));
	}
	
	if(copies > 1)
		$('text-copy').set('text', 'copies');
	else
		$('text-copy').set('text', 'copy');
}
function initFormValidation() {
	// Not-empty fields
	$$('input.check-not-empty')
		.addEvent('change', validateNotEmpty)
		.addEvent('blur', validateNotEmpty);
	$$('input.check-email')
		.addEvent('change', validateEmail)
		.addEvent('blur', validateEmail);
	$$('input.check-optional')
		.addEvent('change', validateOptional)
		.addEvent('blur', validateOptional);
	
	if($$('#company, #ustid').length > 0) {
		$$('#company, #ustid')
			.addEvent('change', updateAmount)
			.addEvent('blur', updateAmount);

		$('country').addEvent('click', displayVATID);
		
	}
	
	
	if($$('input#coupon').length > 0)
		initCouponValidation();
	
}
function initCouponValidation() {
	$('coupon').addEvent('blur', validateCoupon);
}
var couponCode = '';
var couponResult = null;
function validateCoupon() {
	var couponField = $('coupon');
	couponResult = null;
	
	// only validate if entered string has the right length
	if(couponField.get('value').trim().length != 15 && couponField.get('value').trim().length < 32)
		return;

	// only validate if entered string has changed
	if(couponField.get('value').trim() == couponCode)
		return;	
	couponCode = couponField.get('value').trim();
	
	couponField.addClass('waiting');
	
	ajaxURI = 'ajax-coupon-check.php';
	jsonRequest = new Request.JSON({url: ajaxURI,
		onSuccess: function(result) {
			couponResult = result;
			
			couponField.removeClass('waiting');			
			if(result.valid == true) {
				// only one license per coupon
				$('copies')
					.set('value', '1')
					.setStyle('display', 'none');
				$('copies-fixed').set('text', 'one');
				
				updateAmount();
				
				// show ok tick and make readonly
				couponField
					.removeClass('check-error')
					.addClass('check-ok')
					.set('readonly', 'readonly');

			} else {
				couponField
					.removeClass('check-ok')
					.addClass('check-error');
				
				updateAmount();
			}
		}
	}).send({
	    method: 'post',
	    data: 'code=' + couponCode
	});
}
function validateNotEmpty() {
	var value = $(this).get('value');
	
	if(value.clean() == '') {
		this.addClass('check-error');
		this.removeClass('check-ok');
	} else {
		this.removeClass('check-error');
		this.addClass('check-ok');
	}
}
function validateEmail() {
	var value = $(this).get('value');
	
	var regex_email = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/;
	if(value.search(regex_email) >= 0) {
		this.removeClass('check-error');
		this.addClass('check-ok');
	} else {
		this.addClass('check-error');
		this.removeClass('check-ok');
	}
}
function validateOptional() {
	var value = $(this).get('value');
	
	if(value.clean() == '') {
		this.removeClass('check-ok');
	} else {
		this.addClass('check-ok');
	}
}
function checkMwSt() {
	var country = $('country').get('value');
	var valueCompany = $('company').get('value').clean();
	var valueUStID = $('ustid').get('value').clean();
	
	// Check EU
	isEU = false;
	isDE = false;
	
	switch(country) {
		case 'BE':		case 'BG':		case 'DK':		case 'EE':		case 'FI':
		case 'FR':		case 'GR':		case 'IE':		case 'IT':		case 'LV':
		case 'LT':		case 'LU':		case 'MT':		case 'NL':		case 'AT':
		case 'PL':		case 'PT':		case 'RO':		case 'SE':		case 'SK':
		case 'SI':		case 'ES':		case 'CZ':		case 'HU':		case 'GB':
		case 'CY':
			isEU = true;
			break;
		case 'DE':
			isEU = true;
			isDE = true;
			break;
	}
	// MwSt wird hinzugerechnet, falls Land Deutschland ist, oder Land in der EU ist und keine UStID angegeben ist
	if(isDE || (isEU && (valueUStID == '' || valueCompany == ''))) {
		needsVAT = true;
	} else {
		needsVAT = false;
	}
	
}
function displayVATID() {
	updateAmount();
	
	if(isEU) {
		$('ustid-form-row').setStyle('display', 'block');
	} else {
		$('ustid-form-row').setStyle('display', 'none');
	}
}
function validateAll() {
	$$('input.check-not-empty, input.check-email, input.check-optional').fireEvent('blur');
	
	var display = $('country').get('value') != '--' ? 'none' : 'block';
	$('country').getSiblings('.error-message').setStyle('display', display);
	
	if($('check-agb')) {
		display = $('check-agb').get('checked') ? 'none' : 'block';
		$('check-agb').getSiblings('.error-message').setStyle('display', display);
	}
	
	if($('check-eula')) {
		display = $('check-eula').get('checked') ? 'none' : 'block';
		$('check-eula').getSiblings('.error-message').setStyle('display', display);
	}	
	
	display = $('email').get('value') == $('email2').get('value') ? 'none' : 'block';
	$('email2').getSiblings('.error-message').setStyle('display', display);
	
	if($('student-id')) {
		display = $('student-id').get('value') != '' ? 'none' : 'block';
		$('student-id').getParent().getSiblings('.error-message').setStyle('display', display);
	}
	
	// any error messages?
	for (var i=0; i < $$('.error-message').length; i++) {
		if($$('.error-message')[i].getStyle('display') == 'block')
			return false;
	};
	
	// any error indicators?
	if($$('input.check-error').length > 0)
		return false;
	else
		return true;
}
function nextStep(event) {
	event.preventDefault();
	
	if(!validateAll())
		return;
	
	var checkAgb = $("check-agb").get('checked') ? 1 : 0;
	var checkEula = $("check-eula").get('checked') ? 1 : 0;
	var checkNewsletter = $("check-newsletter").get('checked') ? 1 : 0;
	
	ajaxURI = 'ajax-creditcard.php';
	jsonRequest = new Request.JSON({url: ajaxURI,
		onSuccess: function(result) {
			if(result['AMOUNT'] == 0) {
				window.location = 'http://www.antetype.com/payment-free.php';
				return;
			}
			
			var form = new Element('form', {method: 'post', action: 'https://secure.payengine.de/ncol/prod/orderstandard.asp'});
			
			Object.each(result, function(item, index) {
				var input = new Element('input', {type: 'hidden', name: index, value: item});
				input.inject(form);
			});
			form.inject(document.body);
			form.submit();
		}
	}).send({
	    method: 'post',
	    data: 'name=' + $("name").get('value')
			+ '&company=' + $("company").get('value')
			+ '&ustid=' + $("ustid").get('value')
			+ '&address=' + $("address").get('value')
			+ '&zip=' + $("zip").get('value')
			+ '&city=' + $("city").get('value')
			+ '&email=' + $("email").get('value')
			+ '&copies=' + $("copies").get('value')
			+ '&currency=' + $('currency').get('value')
			+ '&country=' + $("country").get('value')
			+ '&method=' + $$('input[name=payment]:checked').get('value')
			+ '&agb=' + checkAgb
			+ '&eula=' + checkEula
			+ '&newsletter=' + checkNewsletter
			+ '&coupon=' + $('coupon').get('value')
	});
	
	
}

/* EDUCATIONAL LICENSE APPLICATION */
function fileInputs() {
	var val = this.get('value'),
		valArray = val.split('\\'),
		newVal = valArray[valArray.length-1],
		button = this.getSiblings('.file-button'),
		fakeFile = this.getSiblings('.file-holder');
		
	if(newVal !== '') {
		button.set('text', 'File Chosen');
		if(fakeFile.length !== 0) {
			fakeFile.set('text', newVal);
		}
	}
}
function initStudentLicense() {
	initFormValidation();
	$('submit').addEvent('click', studentLicenseApply);
	
	$$('.file-wrapper input[type=file]')
		.addEvent('change', fileInputs)
		.addEvent('focus', fileInputs)
		.addEvent('click', fileInputs);
}
function studentLicenseApply(event) {
	event.preventDefault();
	
	if(!validateAll())
		return;
	
	$('student-form').submit();
}




/* TRIGGER INITIALIZATION */
window.addEvent('domready', init);
