function onlyCharNumDash(str) {
	return str && str.match(/[a-zA-Z0-9]/g).join('');
}

function initStyle() {
	var style = {};
	style.LanguageCode = window.location.pathname.toLowerCase().indexOf('/pt/') !== -1
			? 'pt-br'
			: 'en-us';

	return style;
}

function onSuporteReady() {

	var style = initStyle();
	var texts = {
		"pt-br" : {
			subjectRequiredText : "Informe o assunto",
			bodyRequiredText : "Descreva em detalhes seu pedido de suporte",
			emailRequiredText : 'Informe seu e-mail',
			emailInvalidText : 'Você informou um e-mail inválido',
			formInvalidText : 'Ocorreram erros durante a validação do preenchimento dos campos. Por favor, verifique',
			sendError : 'Ocorreu um erro durante o envio do seu pedido. Por favor, entre em contato com nosso suporte no e-mail "{1}"',
			successText : 'Seu pedido de suporte foi encaminhado. Entraremos em contato o mais rápido possível.',
			supportEmail : 'suporte@atadesk.com'
		},
		"en-us" : {
			subjectRequiredText : 'Enter the subject',
			bodyRequiredText : "Describe your support request in details",
			emailRequiredText : 'Enter your e-mail',
			emailInvalidText : 'You entered an invalid e-mail',
			formInvalidText : 'Some errors occurred during field validation. Please, correct the marked fields.',
			sendError : 'There was an error while sending your support request. Please, contact our staff at the e-mail "{1}"',
			successText : 'Your support request has been sent. We\'ll get back to you as soon as possible.',
			supportEmail : 'support@atadesk.com'
		}
	};

	$("#support_form").validate({
		rules : {
			subject : "required",
			body : "required",
			from : {
				required : true,
				email : true
			}
		},
		messages : {
			subject : texts[style.LanguageCode].subjectRequiredText,
			body : texts[style.LanguageCode].bodyRequiredText,
			from : {
				required : texts[style.LanguageCode].emailRequiredText,
				email : texts[style.LanguageCode].emailInvalidText
			}
		}
	});

	var sendError = texts[style.LanguageCode].sendError.replace(/\{1\}/,
			texts[style.LanguageCode].supportEmail);

	$('#submit-link').click(function() {
		if (!($("#support_form").valid())) {
			alert(texts[style.LanguageCode].formInvalidText);
		} else {
			var bodyVal = $('#description').val();
			bodyVal = bodyVal.replace(/(\r\n)|(\n)/g,"<br />");
			$('#description').val(bodyVal);

			$.ajax({
				type : "POST",
				dataType : 'json',
				url : "/atadesk/ashx/ControllerSupportSubmit.ashx",
				data : $('#support_form').formSerialize()
						+ '&to='
						+ encodeURIComponent(texts[style.LanguageCode].supportEmail),
				error : function(msg) {
					if (msg && msg.erros && msg.erros.length) {
						alert(msg.erros[0][1]);
					} else {
						alert(sendError);
					}
					return false;
				},
				success : function(msg) {
					if (msg && msg.success & msg.success == true) {
						document.getElementById("support_form").reset();
						scroll(0,0);						
						alert(texts[style.LanguageCode].successText);

					} else if (msg && msg.erros.length) {
						alert(msg.erros[0][1]);
					} else {
						alert(sendError);
					}
					return false;
				}
			});
		}
		return false;
	});
}

function onContrateReady(expDate) {
	var style = initStyle();
	var texts = {
		"pt-br" : {
			tdriveTrad : 'Gratuito',
			tdriveCost : '0',

			basicTrad : 'Básico',
			basicCost : 'R$ 49',

			silverTrad : 'Silver',
			silverCost : 'R$ 79',

			goldTrad : 'Gold',
			goldCost : 'R$ 149',

			primeironomeRequiredText : "Informe seu primeiro nome",
			ultimonomeRequiredText : "Informe seu último nome",
			emailRequiredText : 'Informe seu e-mail',
			emailInvalidText : 'Você informou um e-mail inválido',
			loginRequiredText : 'Informe o seu nome de usuário',
			senhaRequiredText : 'Preencha com sua nova senha',
			senhaMinLengthText : 'A senha deve conter pelo menos 5 caracteres',
			senhaconfirmRequiredText : 'Preencha novamente com sua nova senha',
			senhaconfirmEqualToText : 'A confirmação de senha deve ser igual à senha informada',
			tenantdescricaoRequiredText : 'Informe o nome de sua empresa ou negócio',
			timezoneidRequiredText : 'Indique a área de fuso horário em que você se encontra',
			idtenantRequiredText : 'Preencha a identificação de URL que será usada por você e por seus usuários',
			idtenantInvalidText : 'A identificação de URL só pode conter Letras e Números',
			formInvalidText : 'Ocorreram erros durante a validação do preenchimento dos campos. Por favor, verifique',
			eulaInvalidText : 'É necessário aceitar os termos antes de finalizar o cadastro',
			submitError : 'Ocorreu um erro durante a criação. Por favor, entre em contato com nosso suporte',
			successText : 'Parabéns ! Seu novo ambiente foi criado.\n\nVocê será redirecionado agora para seu espaço ATAdesk.'

		},
		"en-us" : {
			tdriveTrad : 'Free',
			tdriveCost : '0',

			basicTrad : 'Basic',
			basicCost : 'US$ 24',

			silverTrad : 'Silver',
			silverCost : 'US$ 49',

			goldTrad : 'Gold',
			goldCost : 'US$ 149',
			
			primeironomeRequiredText : "Enter your first name",
			ultimonomeRequiredText : "Enter your last name",
			emailRequiredText : 'Enter your e-mail',
			emailInvalidText : 'You entered an invalid e-mail',
			loginRequiredText : 'Enter your login',
			senhaRequiredText : 'Enter your new password',
			senhaMinLengthText : 'Password must be at least 5 characters long',
			senhaconfirmRequiredText : 'Re-type your password',
			senhaconfirmEqualToText : 'Password confirmation is different from the entered password',
			tenantdescricaoRequiredText : 'Enter your business name',
			timezoneidRequiredText : 'Select your city\'s time-zone ',
			idtenantRequiredText : 'Enter the URL address that will be used to access your ATAdesk space',
			idtenantInvalidText : 'The URL address must contain only numbers and letters',
			formInvalidText : 'Some errors occurred during field validation. Please, correct the marked fields.',
			eulaInvalidText : 'You need to accept our Terms of Service before continuing',
			submitError : 'There was an error while submitting your account information. Please, contact our support',
			successText : 'Congratulations ! Your account has been created.\n\nPress OK and you\'ll be redirected to your ATAdesk space.'
		}
	};
	
	var planosInfo = {
		tdrive : {
			id : 0,
			trad : texts[style.LanguageCode].tdriveTrad,
			cost : texts[style.LanguageCode].tdriveCost
		},
		basic : {
			id : 10,
			trad : texts[style.LanguageCode].basicTrad,
			cost : texts[style.LanguageCode].basicCost
		},
		silver : {
			id : 20,
			trad : texts[style.LanguageCode].silverTrad,
			cost : texts[style.LanguageCode].silverCost
		},
		gold : {
			id : 30,
			trad : texts[style.LanguageCode].goldTrad,
			cost : texts[style.LanguageCode].goldCost
		}
	};

	var plano = $.query.get('plano');
	var planoInfo = $('#plano_info');
	planoInfo.addClass(plano);
	planoInfo.attr('innerHTML', planosInfo[plano].trad);

	var planoPrice = $('#plano_price');
	if (planosInfo[plano].id === 0) {
		planoPrice.hide();
	}

	$('.exp_date').attr('innerHTML', expDate);
	$('.plano_price').attr('innerHTML', planosInfo[plano].cost);

	var tenantId = $('#signup_data_subdomain');
	var tenantInfo = $('#tenant');

	$('#signup_data_name').blur(function() {
		if (!tenantId.val()) {
			var tid = onlyCharNumDash(this.value).toLowerCase();
			tenantId.val(tid);
			tenantInfo.attr('innerHTML', tid);
		}
	});

	tenantId.keyup(function() {
		tenantInfo.attr('innerHTML', this.value);
	});

	jQuery.validator.addMethod("validtid", function(value, element, param) {
		return (element.value.match(/[a-zA-Z0-9_\-]/g).length === element.value.length);
	});

	$("#signup_form").validate({
		rules : {
			primeironome : "required",
			ultimonome : "required",
			email : {
				required : true,
				email : true
			},
			login : "required",
			senha : {
				required : true,
				minlength : 5
			},
			senhaconfirm : {
				required : true,
				equalTo : "#signup_data_password"
			},
			tenantdescricao : "required",
			timezoneid : "required",
			idtenant : {
				required : true,
				validtid : true
			}
		},

		messages : {
			primeironome : texts[style.LanguageCode].primeironomeRequiredText,
			ultimonome : texts[style.LanguageCode].ultimonomeRequiredText,
			email : {
				required : texts[style.LanguageCode].emailRequiredText,
				email : texts[style.LanguageCode].emailInvalidText
			},
			login : texts[style.LanguageCode].loginRequiredText,
			senha : {
				required : texts[style.LanguageCode].senhaRequiredText,
				minlength : texts[style.LanguageCode].senhaMinLengthText
			},
			senhaconfirm : {
				required : texts[style.LanguageCode].senhaconfirmRequiredText,
				equalTo : texts[style.LanguageCode].senhaconfirmEqualToText
			},
			tenantdescricao : texts[style.LanguageCode].tenantdescricaoRequiredText,
			timezoneid : texts[style.LanguageCode].timezoneidRequiredText,
			idtenant : {
				required : texts[style.LanguageCode].idtenantRequiredText,
				validtid : texts[style.LanguageCode].idtenantInvalidText
			}
		}
	});

	$('#place_order span.buttonLinkMed a').click(function() {

		if (!($("#signup_form").valid())) {
			alert(texts[style.LanguageCode].formInvalidText);
			return false;
		};

		var eulaChecked = $('#signup_accepts_eula').attr('checked');
		if (eulaChecked !== true) {
			alert(texts[style.LanguageCode].eulaInvalidText);
			return false;
		} else {
			$.ajax({
				type : "POST",
				dataType : 'json',
				url : "/atadesk/ashx/createtenant.ashx",
				data : $('#signup_form').formSerialize() + '&planoid='
						+ planosInfo[plano].id + '&languagecode='
						+ style.LanguageCode,
				error : function(msg) {
					if (msg && msg.erros && msg.erros.length) {
						alert(msg.erros[0][1]);
					} else {
						alert(texts[style.LanguageCode].submitError);
					}
					return false;
				},
				success : function(msg) {
					if (msg && msg.success & msg.success == true) {
						alert(texts[style.LanguageCode].successText);
						window.location = 'http://'
								+ $('#signup_data_subdomain').val()
								+ '.atadesk.com';
					} else if (msg && msg.erros.length) {
						alert(msg.erros[0][1]);
					} else {
						alert(texts[style.LanguageCode].submitError);
					}
					return false;
				}
			});
		}
		return false;
	});

	/*
	 * $('#signup_accepts_eula').click(function() { $('#place_order
	 * span.buttonLinkMed a').attr("disabled", this.checked ? "" : "disabled");
	 * });
	 */
}