/**
 * @author Andrei Gherasim
 */
	var currentStep = 1;
	var errorCount = 0;
	var start = true;
	var x = 1;
	
	$(document).ready(function(){
		prepareValidateData(true);
		step(currentStep);
		$("#new_profile").bind("submit",function(){			
			if(currentStep < 3){
//				if(validateData()){
				xStep = currentStep + 1;
				step(xStep);	
//				}
				return false;
			}else{
				return validateCaptcha();
				//return false;
			}
		});
		$("#new_username").keyup(function(){
			var username = $("#new_username").val();
			username = username.replace(/\W/g,"");
			//_hideError(this,false);
			if (username.length >= 5) {
				_hideError(this,true);
				//alert("test");
				$("#new_username+span").html("<a href=\"#\" id=\"checkUsernameAvail\">Verifica disponibilitate</a>");
				$("#checkUsernameAvail").click(function(){
					//alert('test');
					$("#new_username+span").html("&nbsp;<img src=\""+base+"public/images/preloader.gif\" />");
					$(this).hide();
					validateUsername(false);
					/*$.ajax({
							type: "POST",
							url: base + 'request/checkUsername',
							data: "username="+$("#new_username").val(),
							success: function(data){
								if(data == "0"){
									html="&nbsp;<img src=\""+base+"public/images/icons/accept.gif\" />";
									html += "&nbsp;<span style=\"color:green\">Numele de utilizator este disponibil";
								}else{
									html="&nbsp;<img src=\""+base+"public/images/icons/exclamation.gif\" />";
									html += "&nbsp;<span style=\"color:red\">Numele de utilizator nu este disponibil";
								}
								$("#new_username+span").html(html);
							}
					});*/
				});				
			} else {
				$("#new_username+span").html("");
				_showError(this,'Campul are nevoie de minim 5 caractere');
			}
			
		});
	})

	function step(stepNumber)
	{
	//	alert(errorCount);
		if (!start) {
			prepareValidateData(false);
		}
		//alert(errorCount);
		if (errorCount == 0) {
			for (var i = 0; i < 3; i++) {
				$("#tab_step" + (i + 1)).attr("class", "tab");
				$("#tab_step" + stepNumber).attr("class", "tab selected");
				$("#step" + (i + 1)).hide();
			}
			currentStep = stepNumber;
			__show();
		}
		start = false;
		prepareValidateData(true);
//		alert(start);
/*		if (!start) {
			prepareValidateData(true);
		}*/
//		if(errorCount <= 0) start = false;
	//	alert(errorCount);
	}
	
	function __show()
	{
		if(currentStep < 3){
			$("#nextStep").attr("value","Pasul urmator >>");
		}else{
			$("#nextStep").attr("value","Salveaza");
		}
		$("#step"+currentStep).fadeIn(1000);
	}


	//data validation
	function prepareValidateData(simple)
	{
		//reset errorCount
		//errorCount  = 0;
		
		$('#step'+currentStep+' > input').each(function(){
			if ($(this).prev('label').hasClass('required')) {
				if (simple) {
					$(this).blur(function(){
						dataValidation(this);
					});
				}else{
					dataValidation(this);
				}
			}
		});
		$('#step'+currentStep+' > select').each(function(){
			if ($(this).prev('label').hasClass('required')) {
				if (simple) {
					$(this).blur(function(){
						dataValidation(this);
					});
				}else{
					dataValidation(this);
				}
			}
		});
		$('#step'+currentStep+' > input:checkbox').each(function(){
			if($(this).prev('label').hasClass('required')){
				if(simple) {
					$(this).click(function(){
						dataValidation(this);
					});
				}else{
					dataValidation(this);
				}
			}
		});
		return true;
	}
	
	function validateUsername(email)
	{
		var url = base + 'request/checkUsername';
		var data = "username=" + $("#new_username").val();
		if (email) {
			url = base + 'request/checkUsername';
			data = "email=" + $("#new_email").val();
		}
			
			$.ajax({
				type: "POST",
				url: url,
				data: data,
				success: function(data){
					//alert(data);
					if (data == "0") {
						if (!email) {
							$("#new_username").prev('label').attr('class', 'required_ok');
							html = "&nbsp;<img src=\"" + base + "public/images/icons/accept.gif\" />";
							html += "&nbsp;<span style=\"color:green\">Numele de utilizator este disponibil";
							$("#new_username+span").html(html);
						}
						else {
							$("#new_email").prev('label').attr('class', 'required_ok');
							html = "&nbsp;<img src=\"" + base + "public/images/icons/accept.gif\" />";
							html += "&nbsp;<span style=\"color:green\">Adresa de email este disponibila";
							$("#new_email+span").html(html);
						}
						errorCount--;
						return true;
					}
					else {
						if (!email) {
							$("#new_username").prev('label').attr('class', 'required');
							html = "&nbsp;<img src=\"" + base + "public/images/icons/exclamation.gif\" />";
							html += "&nbsp;<span style=\"color:red\">Numele de utilizator nu este disponibil";
							$("#new_username+span").html(html);
						}else{
							$("#new_email").prev('label').attr('class', 'required');
							html = "&nbsp;<img src=\"" + base + "public/images/icons/exclamation.gif\" />";
							html += "&nbsp;<span style=\"color:red\">Adresa ta de email a fost folosita deja";
							$("#new_email+span").html(html);
						}
						errorCount++;
						return false;
					}
				}
			});
	}
	
	function dataValidation(elm) {
		var elmId = $(elm).attr('id');
		switch(elmId){
			case 'new_username':
				$(elm).val($(elm).val().replace(/\W/g,""));
				console.debug($(elm).val());
				if ($(elm).val() == '') {
					_showError(elm, 'Camp obligatoriu');
				}
				else {
					_hideError(elm,true);
					if ($(elm).val().length < 5 && $(elm).val().length != 0) {
						_showError(elm, 'Campul are nevoie de minim 5 caractere');
					}
					else {
						_hideError(this,true);
						validateUsername(false);
					}
				}
				break;
			case 'new_passwd':

				if ($(elm).val() == '') {
					_showError(elm, 'Camp obligatoriu');
				}
				else {
					if ($(elm).val().length < 5 && $(elm).val().length > 0) {
						_showError(elm, 'Campul are nevoie de minim 5 caractere');
					}
					else {
						_hideError(elm,true);
					}
				}
				break;
			case 'conf_new_passwd':
				if($(elm).val() != $('#new_passwd').val() || $(elm).val() == '') {
					_showError(elm, 'Campurile sunt diferite');
				}else{
					_hideError(elm,true);
				}
				break;
			case 'new_sex':
				//alert($(elm).val());
				if($(elm).val() == '0') {
					_showError(elm,'Camp obligatoriu');
				}else{
					_hideError(elm,true);
				}
				break;
			case 'new_email':
				//http://www.zparacha.com/validate-email-address-using-javascript-regular-expression/
				var validEmail = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
				if(! validEmail.test($(elm).val()) || $(elm).val() == '') {
					_showError(elm, 'Campul nu contine un email valid');
				}else{
					_hideError(elm,true);
					validateUsername(true);
				}
				break;
			case 'new_terms':
				//alert($(elm).attr('checked'));
				if($(elm).attr('checked') != true) {
					_showError(elm, 'Trebuie sa fii de acord cu conditiile noastre pentru a continua');
				}else{
					_hideError(elm,true);
				}
				break;
			default:
				//alert($(elm).attr('id'));
				if($(elm).val() == '') {
					//alert('default');
					_showError(elm,'Camp obligatoriu');
				}else{
					_hideError(elm,true);
				}
				break;
		}
	}
	
	function _showError(elm,msg){
		if ($(elm).next(':not(option)').attr('class') != 'error') {
			$(elm).prev().attr('class','required');
			$(elm).after('<span class="error">'+msg+'</span>');
			$(elm).attr('style', 'border:1px dotted red;');
		}else{
			$(elm).next(':not(option)').text(msg)
		}
		errorCount ++;
	}
	
	function _hideError(elm,repaired) {
		if($(elm).next(':not(option)').attr('class') == 'error') {
			$(elm).next(':not(option)').replaceWith('');
		}
		if (repaired) {
			$(elm).prev().attr('class', 'required_ok');
		}
		$(elm).attr('style','');	
		
		errorCount --;
		if(errorCount < 0) errorCount = 0;
	}

	function validateCaptcha() {
		//alert($("#captcha").text());
		if($("#captcha").val() == '') {
			_showError($("#captcha_img"),'Nu ati introdus codul de validare. Mai incercati odata!');
			return false;
		}
		$.ajax({
			type: "POST",
			url: base + 'request/captcha',
			data: "captcha="+$("#captcha").val(),
			success: function(data){
				if(data == "0"){
					errorCount --;
					_hideError($("#captcha_img"),true);
					if(errorCount == 0) return true;
					return false;
				}else{
					errorCount ++;
					//alert(base+'request/captcha/');
					img = base+'request/captcha/'+x;
					x++;
					//alert(img);
					$("#captcha_img").attr('src',img);
					_showError($("#captcha_img"),'Cod de validare incorect. Mai incercati odata!');
					return false;
				}
			}
		});
	}
