// Require vars: domains

var formData = {
	service: {
		id: undefined,
		domain: undefined,
		operation: undefined
	},
	subservices: [],
	customer: {
		type: undefined,
		company: undefined,
		iva: undefined,
		firstname: undefined,
		lastname: undefined,
		identifier: undefined,
		telephone: undefined,
		birthplace: undefined,
		birthday: undefined,
		birthmonth: undefined,
		birthyear: undefined,
		birthprovincia: undefined,
		cellulare: undefined,
		country: undefined,
		province: undefined,
		postalcode: undefined,
		city: undefined,
		address: undefined,
		email: undefined,
		password: undefined
	},
	domain: {
		type: undefined,
		company: undefined,
		iva: undefined,
		firstname: undefined,
		lastname: undefined,
		identifier: undefined,
		telephone: undefined,
		birthplace: undefined,
		birthday: undefined,
		birthmonth: undefined,
		birthyear: undefined,
		birthprovincia: undefined,
		cellulare: undefined,
		country: undefined,
		province: undefined,
		postalcode: undefined,
		city: undefined,
		address: undefined,
		email: undefined
	},
	payment: undefined
};

/******************** Analytics function **************************************/
function analyticsPage(page) {
	if (typeof(_gaq) != 'undefined') {
		_gaq.push(['_trackPageview', page]);
	}
}

/******************** Toggle functions ****************************************/

/* Toggle on first level choice "new customer" or "old customer" */
function toggleTypeRegistration() {
	if ($('#registration-new-customer').attr('disabled') || $('#registration-new-customer').length == 0) {
		$('#new-customer-data').show("slow");
		$('#old-customer-data').hide("slow");
	} else if ($('#registration-old-customer').attr('disabled')) {
		$('#old-customer-data').show("slow");
		$('#new-customer-data').hide("slow");
	} else {
		$('#new-customer-data,#old-customer-data').hide("slow");
	}
}

/* Toggle on second level choice "use same data of customer" or "other data" */
function toggleDomainData() {
	if ($('#not-use-customer-data').attr('checked')) {
		$('#domain-customer-data').show("slow")
	} else {
		$('#domain-customer-data').hide("slow")
	}
}

function toggleServiceData() {
	$('.service-options').hide('slow');
	selectedServiceId = $('.service.selected').val();
	$('.options-of-' + selectedServiceId).show('slow');
}

/**
 * toggle specific field of company or person registered
 */
var firstToggleNewCustomerData = false;
function toggleNewCustomerData() {
	if ($('#new-customer-type-person').attr('checked')) {
		if (!firstToggleNewCustomerData) {
			firstToggleNewCustomerData = true;
			$('#new-customer-data .field').fadeIn();
		}
		$('#new-customer-data .company').fadeOut();
		$('#new-customer-data .person').fadeIn();
	} else if ($('#new-customer-type-company').attr('checked')){
		if (!firstToggleNewCustomerData) {
			firstToggleNewCustomerData = true;
			$('#new-customer-data .field').fadeIn();
		}
		$('#new-customer-data .person').fadeOut();
		$('#new-customer-data .company').fadeIn();
	} else {
		$('#new-customer-data .field').fadeOut();
	}
}

var firstToggleDomainCustomerData = false;
function toggleDomainCustomerData() {
	if ($('#domain-customer-type-person').attr('checked')) {
		if (!firstToggleDomainCustomerData) {
			firstToggleDomainCustomerData = true;
			$('#domain-customer-data .field').fadeIn();
		}
		$('#domain-customer-data .company').fadeOut();
		$('#domain-customer-data .person').fadeIn();
	} else if ($('#domain-customer-type-company').attr('checked')) {
		if (!firstToggleDomainCustomerData) {
			firstToggleDomainCustomerData = true;
			$('#domain-customer-data .field').fadeIn();
		}
		$('#domain-customer-data .company').fadeIn();
		$('#domain-customer-data .person').fadeOut();
	} else {
		$('#domain-customer-data .field').fadeOut();
	}
}

/******************** Accordion function **************************************/

/*
 * Hide all contents then show content with class "selected"
 */
function manageAccordion() {
	$('.step').find('.content').hide("slow").end().filter('.selected').find('.content').show("slow");
}

/*
 * Check the active step and then go to the next.
 */
function nextStep() {
	var maxStep = 5;
	$('.step.selected').addClass('selectable completed');
	var nextSelected = $('.step.selected').next();
	$('.step').removeClass('selected').addClass('selectable');
	nextSelected.addClass('selected');
	manageAccordion();
}

/******************** Control functions **************************************/

/**
 * Set the domain and if is to register or to transfer
 *
 * @param domain Domain
 * @param ext Extension of domain
 * @param type register or transfer
 */
function setDomain(domain, ext, type) {
	clearError('#step-domain-check', '#register-domain');
	$('#register-domain').val(domain + '.' + ext);
	if (type == 'register') {
		$('#register-domain-operation-register').attr('checked', true);
	} else {
		$('#register-domain-operation-transfer').attr('checked', true);
	}
}

/**
 * Check the root of a domain for all extensions available and return the HTML
 *
 * Warning: async function !
 */
function checkDomains() {
	var value = $('#register-domain').val().split('.');
	var html_code = "<table id=\"whois-results\" class=\"whois\">";
	for(var i=0; i < domains.length; i++) {
		extension = domains[i];
		$.askService({
			type:'SR_Model_Whois',
			method:'query',
			data: [value[0], extension],
			async: true,
			onComplete: function (risp) {
				ext = '';
				for(var j = 0; j < domains.length; j++) {
					if (typeof(risp.result[domains[j]]) != 'undefined') {
						ext = domains[j];
						break;
					}
				}
				available = risp.result[ext].available;
				row = $('table#whois-results tr.' + ext);
				if (available) {
					row.addClass('available');
					row.find('.status').text('DISPONIBILE');
					row.find('.action').html('<a href="javascript:setDomain('
					+ '\'' + escape(value[0]) + '\','
					+ '\'' + ext + '\','
					+ '\'' + 'register' + '\')">Registra questo dominio</a>');
				} else {
					row.addClass('unavailable');
					row.find('.status').text('NON DISPONIBILE');
					row.find('.action').html('<a href="javascript:setDomain('
					+ '\'' + escape(value[0]) + '\','
					+ '\'' + ext + '\','
					+ '\'' + 'transfer' + '\')">Trasferisci questo dominio</a>');
				}
			}
		});
		html_code += '<tr class="' + extension + '"><td class="domain">' + escape(value[0]) + '<span class="extension">.' + domains[i] + '</span></td>'
			+ '<td class="status">IN ELABORAZIONE</td>'
			+ '<td class="action"></td></tr>';
	}
	html_code += '</table>';
	return html_code;
}

/*
 * Check if domain is free and:
 * - show errors if domain is wrong or busy
 * - go to the next step if it is free
 */
function checkDomain() {
	analyticsPage('check_domain.html');
	var error = false;
	var message = false;
	var value = $('#register-domain').val().split('.');
	if (value.length > 0) {
		if ((value.length == 2 && value[0].length >= 3 && value[0].length <= 255 && value[1].length > 0 && value[1].length < 5)
		|| (value.length == 1 && value[0].length >= 3 && value[0].length <= 255)) {
			if ($("#register-domain-operation-register").attr('checked') || value.length == 1) {
				var oldVal = $('#command-start').text();
				$('#command-start').text('Avvio registrazione in corso ...')
					.attr('readOnly', true).attr('disabled', true);
				$('#register-domain').attr('readOnly', true).attr('disabled', true);
				var response = {};
				if (value.length == 2) {
					response = $.askService({type:'SR_Model_Whois', method:'query', data: [value[0], value[1]]});
				}
				if (response.error && response.error.message && response.error.message.length > 0) {
					if ($.inArray(value[1], domains) == -1) {
						error = "Non è possibile registrare un dominio per l'estensione richiesta.";
					} else {
						error = response.error.message;
					}
				} else if ((response.result && response.result[value[1]] && response.result[value[1]].available == false)
					|| value.length == 1) {
					moreDomains = checkDomains();
					if (moreDomains.error && moreDomains.error.message) {
						error = moreDomains.error.message;
					} else {
						if (value.length == 2) {
							message = "<p><strong>Il dominio da te richiesto risulta già occupato.</strong><br/>";
							message += 'Puoi selezionare un\'estensione diversa oppure scegliere di trasferire questo dominio<br /></p>';
						} else {
							message = "<p><strong>Seleziona il dominio che desideri.</strong><br/>";
							message += 'Puoi selezionare uno dei domini disponibili, oppure quelli occupati se sono già di tua proprietà ma presso un altro hosting provider<br /></p>';
						}
						message += moreDomains;
						message += "<p class=\"normal\">Oppure puoi sempre scegliere un differente nome del dominio e cliccare nuovamente su 'Avvia la registrazione'.<br />";
						if (value.length == 2) {
							message += "<a href=\"#\" id=\"register-domain-operation-register-link\" title=\"Visualizza i dati del registro WHOIS\">Se vuoi, puoi visualizzare il contenuto del registro WHOIS</a></p><br />";
							message += "<pre id=\"register-domain-operation-register-whois\" style=\"display:none\">"
							message += response.result[value[1]].details
							message += "<br/><a id=\"register-domain-operation-register-link-hide\" href=\"#\">Nascondi i dettagli del registro WHOIS</a>"
							message += "</pre>";
						}
					}
				}
				$('#register-domain').removeAttr('readOnly').removeAttr('disabled');
				$('#command-start').removeAttr('readOnly').removeAttr('disabled')
					.text(oldVal);
			}
		} else {
			analyticsPage('dominio_errato.html');
			error = 'Il nome del dominio è errato';
		}
	} else if (value.length == 1 && !(value[0].length >= 3 && value[0].length <= 255)) {
		analyticsPage('nome_dominio_tra_3_e_255.html');
		error = 'Il nome del dominio deve essere compreso tra 3 e 255 caratteri';
	} else if (!(value[0].length >= 3 && value[0].length <= 255)){
		analyticsPage('dominio_senza_estensione.html');
		error = 'Devi scrivere il dominio completo di estensione, come ad esempio tuosito.com';
	}
	clearError('#step-domain-check', '#register-domain');
	clearMessage('#step-domain-check', '#register-domain');
	if (error) {
		addError('#step-domain-check', '#register-domain', error);
	} else if (message) {
		addMessage('#step-domain-check', '#register-domain', message);
	}else {
		var summary = '';
		if ($("#register-domain-operation-register").attr('checked')) {
			summary += 'Registrazione di ';
		} else {
			summary += 'Trasferimento di ';
		}
		summary += $('#register-domain').val();
		$('#step-domain-check-info').text(summary);
		$('#summary-domain').text(summary);
		$('#paypal_item_name').val(summary);
		formData.service.domain = $('#register-domain').val();
		formData.service.operation = $("#register-domain-operation-register").attr('checked') ? 'register' : 'transfer';
		totalCostOfService();
		nextStep();
	}
}

function confirmService() {
	analyticsPage('confirm_service.html');
	clearError('#step-domain-services');
	if ($('.service.selected').length != 1) {
		addError('#step-domain-services');
	} else {
		var service = $('.service.selected').val();
		formData.service.id = service;
		var summary = $('#label-service-' + service).text();
		$('#step-domain-services-info').text(summary);
		var summary_subservices = '';
		$('.option-of-' + service + '.service-option.selected').each(function () {
			summary_subservices += $('#label-option-' + $(this).val()).text() + ', ';
			formData.subservices.push($(this).val());
		});
		if (summary_subservices.length > 0) {
			summary += ' con ' + summary_subservices + ' per un totale di '
			        + $('#step-domain-service-total').text()
		} else {
			summary += ' per un totale di ' + $('#step-domain-service-total').text()
		}
		$('#summary-services').text(summary);
		nextStep();
	}
}

function confirmCustomer() {
	analyticsPage('confirm_customer.html');
	function trim(val) {
		return val.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
	}
	var emptyFields = new Array();
	var error = false;
	clearError('#step-domain-user');
	if (($('#registration-new-customer').attr('disabled') || $('#registration-new-customer').length == 0)
		&& ($('#new-customer-type-person').attr('checked')
		|| $('#new-customer-type-company').attr('checked'))) {
		dontCheck = 'company';
		if ($('#new-customer-type-company').attr('checked')) dontCheck = 'person'
		emptyFields = new Array();
		$('#new-customer-data .field').not('.' + dontCheck).find('input').each(function() {
			if (trim($(this).val()).length == 0) {
				emptyFields.push($(this).attr('id'));
			}
			clearError('#step-domain-user', '#' + $(this).attr('id'));
		});
		for(i = 0; i < emptyFields.length; i++) {
			error = true;
			addError('#step-domain-user', '#' + emptyFields[i], "Non puoi lasciare vuoto questo campo !")
		}
		if (emptyFields.length == 0) {
			type = 'person';
			if ($('#new-customer-type-company').attr('checked')) {
				type = 'company';
			}
			formData.customer = {
				type: type,
				company: $('#new-customer-company').val(),
				iva: $('#new-customer-iva').val(),
				firstname: $('#new-customer-firstname').val(),
				lastname: $('#new-customer-lastname').val(),
				identifier: $('#new-customer-identifier').val(),
				telephone: $('#new-customer-telephone').val(),
				birthplace: $('#new-customer-birthplace').val(),
				birthday: $('#new-customer-birthday').val(),
				birthmonth: $('#new-customer-birthmonth').val(),
				birthyear: $('#new-customer-birthyear').val(),
				birthprovincia: $('#new-customer-birthprovincia').val(),
				cellulare: $('#new-customer-cellulare').val(),
				country: $('#new-customer-country').val(),
				province: $('#new-customer-province').val(),
				postalcode: $('#new-customer-postalcode').val(),
				city: $('#new-customer-city').val(),
				address: $('#new-customer-address').val(),
				email: $('#new-customer-email').val()
			}
			if (type == 'person') {
				$('#summary-customer').text(formData.customer.lastname + ' ' + formData.customer.firstname);
			} else {
				$('#summary-customer').text(formData.customer.company);
			}
		}
	} else if ($('#registration-old-customer').attr('disabled')) {
		emptyFields = new Array();
		$('#old-customer-data .field').find('input').each(function() {
			if (trim($(this).val()).length == 0) {
				emptyFields.push($(this).attr('id'));
			}
			clearError('#old-customer-data', '#' + $(this).attr('id'));
		});
		for(i = 0; i < emptyFields.length; i++) {
			error = true;
			addError('#step-domain-user', '#' + emptyFields[i], "Non puoi lasciare vuoto questo campo !")
		}
		if (emptyFields.length == 0) {
			var response = $.askService({type:'SR_Model_User', method:'check',
				data: [$('#old-customer-email').val(), $('#old-customer-password').val()]
			});
			if (response.error && response.error.message) {
				clearError('#step-domain-user');
				addError('#step-domain-user');
				error = true;
			} else if (response.result != true) {
				clearError('#step-domain-user', '#old-customer-email');
				addError('#step-domain-user', '#old-customer-email', "E-mail o password errati");
				clearError('#step-domain-user', '#old-customer-password');
				addError('#step-domain-user', '#old-customer-password', "E-mail o password errati");
				error = true;
			}
			formData.customer = {
				email: $('#old-customer-email').val(),
				password: $('#old-customer-password').val()
			}
			$('#summary-customer').text(formData.customer.email);
		}
	} else {
		error = true;
		addError('#step-domain-user');
	}

	if ($('#not-use-customer-data').attr('checked')) {
		dontCheck = 'company';
		if ($('#domain-customer-type-company').attr('checked')) dontCheck = 'person';
		emptyFields = new Array();
		$('#domain-customer-data .field').not('.' + dontCheck).find('input').each(function() {
			if (trim($(this).val()).length == 0) {
				emptyFields.push($(this).attr('id'));
			}
			clearError('#domain-customer-data', '#' + $(this).attr('id'));
		});

		for(i = 0; i < emptyFields.length; i++) {
			error = true;
			addError('#step-domain-user', '#' + emptyFields[i], "Non puoi lasciare vuoto questo campo !")
		}

		if (emptyFields.length == 0) {
			type = 'person';
			if ($('#domain-customer-type-company').attr('checked')) {
				type = 'company';
			}
			formData.domain = {
				type: type,
				company: $('#domain-customer-company').val(),
				iva: $('#domain-customer-iva').val(),
				firstname: $('#domain-customer-firstname').val(),
				lastname: $('#domain-customer-lastname').val(),
				identifier: $('#domain-customer-identifier').val(),
				telephone: $('#domain-customer-telephone').val(),
				birthplace: $('#domain-customer-birthplace').val(),
				birthday: $('#domain-customer-birthday').val(),
				birthmonth: $('#domain-customer-birthmonth').val(),
				birthyear: $('#domain-customer-birthyear').val(),
				birthprovincia: $('#domain-customer-birthprovincia').val(),
				cellulare: $('#domain-customer-cellulare').val(),
				country: $('#domain-customer-country').val(),
				province: $('#domain-customer-province').val(),
				postalcode: $('#domain-customer-postalcode').val(),
				city: $('#domain-customer-city').val(),
				address: $('#domain-customer-address').val(),
				email: $('#domain-customer-email').val()
			}
			if (type == 'person') {
				$('#summary-domain-customer').text(formData.domain.lastname + ' ' + formData.domain.firstname);
			} else {
				$('#summary-domain-customer').text(formData.domain.company);
			}
		}
	} else if ($('#use-customer-data').attr('checked')) {
		$('#summary-domain-customer').text(formData.customer.email);
	} else {
		error = true;
		addError('#step-domain-user');
	}

	if (!error) {
		nextStep();
	}
}

function confirmPayment() {
	analyticsPage('confirm_payment.html');
	if ($('.registration-payment.selected').length != 1) {
		addError('#step-domain-payment');
	} else {
		formData.payment = $('.registration-payment.selected').val();
		$('#summary-payment').text($('#label-payment-' + $('.registration-payment.selected').val()).text());
		nextStep();
	}
}

function confirmRegistration() {
	$('#command-confirm').attr('disabled');
	$('#command-confirm').val('Conclusione registrazione...');
	var response = $.askService({
		type:'SR_Model_Helper_Register',
		method:'registerDomain',
		data: [
			formData.service,
			formData.subservices,
			formData.customer,
			formData.domain,
			formData.payment
		]
	});
	if (response.error && response.error.message && response.error.message.length > 0) {
		error = response.error.message;
	} else {
		if ($('#registration-payment-paypal').attr('checked')) {
			$('#paypal_form').submit();
		} else {
			window.location = response.result;
		}
	}
}

/*
 * Check the service (and options) selected from user, than ask server
 * the total.
 * - Show the price and discount (if greater than 0)
 */
function totalCostOfService() {
	function centToEuro(cent) {
		cent = cent + '';
		for (i = cent.length; i < 3; i++) {
			cent = '0' + cent;
		}
		return cent.substr(0, cent.length - 2) + ',' + cent.substr(cent.length - 2, 2);
	}
	$('#step-domain-service-total').html('-');
	var service = $('.service.selected').val();
	var options = new Array();
	$('.option-of-' + service + '.service-option.selected').each(function () {
		options.push($(this).val());
	});
	/*
	server = $.askService({type:'SR_Model_ServiceTypes', method:'calculate', data: [service, options, formData.service.domain]});
	if (server.result != undefined) {
		$('#step-domain-service-total').text(centToEuro(server.result) + " \u20ac (iva esclusa)");
	}*/
	server = $.askService({
		type:'SR_Model_ServiceTypes',
		method:'calculate',
		data: [service, options, formData.service.domain],
		async: true,
		onComplete: function (inp) {
			if (inp != undefined) {
				$('#step-domain-service-total').text(centToEuro(inp.result) + " \u20ac (iva esclusa)");
				$('#paypal_amount').val(centToEuro(inp.result * 1.2).replace(',','.'));
			}
		}
	});
}

/**
 * Given a root and the class of field, add message
 * @param root String query string of name
 * @param element String query string of element
 * @param text String message that explain the error
 */
function addMessage(root, element, text, type) {
	if (type == undefined ) {
		type = 'message';
	}
	if (element != undefined) {
		$(root).find(element).addClass(type).parent()
			.append('<div class="' + type + '"><p>' + text + '</p></div>');
	} else {
		if (text == undefined) {
			$(root).find('.information').addClass(type);
		} else {
			$(root).find('.information').addClass(type)
				.append('<div class="' + type + '"><p>' + text + '</p></div>');
		}
	}
}

/**
 * Given a root and the class of field, clear errors
 * @param root String query string of name
 * @param element String query string of element
 */
function clearMessage(root, element, type) {
	if (type == undefined) {
		type = 'message';
	}
	if (element == undefined) {
		$(root).remove('.' + type);
	} else {
		$(root).find(element).removeClass(type).parent().find('.' + type).remove();
	}
}

/**
 * Given a root and the class of field, add error message
 * @param root String query string of name
 * @param element String query string of element
 * @param text String message that explain the error
 */
function addError(root, element, text) {
	addMessage(root, element, text, 'error');
}

/**
 * Given a root and the class of field, clear errors
 * @param root String query string of name
 * @param element String query string of element
 */
function clearError(root, element) {
	clearMessage(root, element, 'error');
}

$(document).ready(function () {
	// Set initial visible data o "toggle" areas
	toggleTypeRegistration();
	toggleDomainData();
	toggleServiceData();
	toggleNewCustomerData();
	toggleDomainCustomerData();
	// Set initial state of accordion widget
	manageAccordion();
	// Check value of register-domain
	if ($('#register-domain').val().length > 0) {
		checkDomain();
	}
	// Association of events with functions
	$('.step.selectable h2').live('click', function () {
		if (!$(this).parent().hasClass('selected')) {
			$('.step').removeClass('selected');
			$(this).parent().addClass('selected');
			manageAccordion();
		}
	});
	$('#register-domain-operation-register-link,#register-domain-operation-register-link-hide').live("click", function (e) {
		$('#register-domain-operation-register-whois').toggle('slow');
		e.preventDefault();
	});
	$('#registration-new-customer,#registration-old-customer').bind("click", function (e) {
		if ($(e.target).attr('id') != 'registration-new-customer') {
			$('#registration-old-customer').attr('disabled', true);
			$('#registration-new-customer').attr('disabled', false);
		} else {
			$('#registration-old-customer').attr('disabled', false);
			$('#registration-new-customer').attr('disabled', true);
		}
		toggleTypeRegistration();
	});
	$('#use-customer-data,#not-use-customer-data').bind("click", function (e) {
		toggleDomainData()
	});
	$('#new-customer-type-person,#new-customer-type-company').bind('click', function (e) {
		toggleNewCustomerData();
	});
	$('#domain-customer-type-person,#domain-customer-type-company').bind('click', function (e) {
		toggleDomainCustomerData();
	});
	$('#command-start').bind('click', function () {
		checkDomain();
	});
	$('#register-domain').bind('keyup', function (e) {
		var code = e.keyCode || e.which;
		if(code == 13) {
			checkDomain();
		}
		e.preventDefault();
	});
	$('#command-service').bind('click', function () {
		confirmService();
	});
	$('#command-user').bind('click', function () {
		confirmCustomer();
	});
	$('#command-payment').bind('click', function () {
		confirmPayment();
	});
	$('#command-confirm').bind('click', function () {
		confirmRegistration();
	});
	totalCostOfService();
	$('.service').bind('click', function () {
		$('.service').removeClass('selected');
		$(this).addClass('selected');
		toggleServiceData();
		$('.service-option').attr('disabled', 'disabled').attr('readonly','readonly');
		totalCostOfService();
		$('.service-option').removeAttr('disabled').removeAttr('readOnly');
	});
	$('.service-option').bind('click', function () {
		if ($(this).attr('checked')) {
			$(this).addClass('selected');
		} else {
			$(this).removeClass('selected');
		}
		$('.service-option').attr('disabled', 'disabled').attr('readonly','readonly');
		totalCostOfService();
		$('.service-option').removeAttr('disabled').removeAttr('readOnly');
	});
	$('.registration-payment').bind('click', function () {
		$('.registration-payment').removeClass('selected');
		$(this).addClass('selected');
	});
});

