function trim(str) {
    var newstr = str.replace(/^\s*(.+?)\s*$/, "$1");
    if (newstr == " ") {
        return "";
    }
    return newstr;
} 
function prepare_string(str) {
    var newstr = trim(str); //функцию trim() см. выше
    return newstr.replace(/(\s)+/g, "$1");
}
function drop_spaces(str) {
    var newstr = trim(str); //функцию trim() см. выше
    return newstr.replace(/(\s)+/g, ""); 
}
function check_email(email) {
    var template = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z])+$/;
    email = drop_spaces(email); //функцию drop_spaces() см. выше
    if (template.test(email)) {
        return true;
    }
    return false; 
}
function check_phone(phone) {
    var template = /^[0-9]{10}$/;
   	if (template.test(phone)) {
        return true;
    }
    return false; 
}
function check_login(login) {
    var template = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)$/;
    login = drop_spaces(login); //функцию drop_spaces() см. выше
    if (template.test(login)) {
        return true;
    }
    return false; 
}
function check_password(pass) {
    var template = /^([a-zA-Z0-9]*)$/;
    pass = drop_spaces(pass); //функцию drop_spaces() см. выше
    if (template.test(pass)) {
        return true;
    }
    return false; 
}

////////////////////
function alertMessage(s){
	alert(s);
}

function checkLogin(login){

	if(trim(login.value)=='')return  "Введите логин";
	
	if(check_login(login.value)=='')return "Введите корректный логин";
	
	if(login.value.length<6)return "Длина логина не менее 6 символов";
	
	return "";
}

function checkCapture(field){

	if(field.value.length<6)return "Введите правильный код!";
	
	return "";
}

function checkMail(mail){

	if(trim(mail.value)=='')return "Введите e-mail";
	
	if(check_email(mail.value)=='')return "Введите корректный e-mail";

	return "";
}

function checkPhone(phone){

	if(trim(phone.value)=='')return "Введите телефон";
	
	if(check_phone(phone.value)=='')return "Введите корректный телефон (10 цифр)";

	return "";
}

function checkPassword(pass){

	if(trim(pass.value)=='')return "Введите пароль";
	
	if(check_password(pass.value)=='')return "Введите корректный пароль";
	
	if(pass.value.length<6)return "Пароль должен содержать не менее 6 символов";
	
	if($(pass.form).find("*[name='cpassword']").length>0 
		&& pass.value!=$(pass.form).find("*[name='cpassword']")[0].value){
		return "Не совпадает пароль и подтверждение";
	}
	return "";
}

;(function($) {
	$.fn.extend({
		initForm:function(){
			/*инициализируем автоподстановку городов :)*/
			$(this).find(".town").autocomplete("/autocomplete_city.php",{scroll:false,delay:400, max:10});
			//$(this).find("*[name='town']").autocomplete("/autocomplete_city.php",{scroll:false,delay:400, max:10});
			
			$(this).find("*[type='submit']").attr("disabled","disabled");
			valid=true;
			
			checkAll=function(form){
				valid=true;
				$(form).find("*[name='u_login']").each(function(){
					if(valid && checkLogin(this).length>0){
						valid=false;
					}				
				});
				$(form).find("*[name='capture']").each(function(){
					if(valid && checkCapture(this).length>0){
						valid=false;
					}				
				});
				$(form).find("*[name='u_mail']").each(function(){
					if(valid && checkMail(this).length>0){
						valid=false;
					}				
				});
				$(form).find("*[name='u_phone']").each(function(){
					if(valid && checkPhone(this).length>0){
						valid=false;
					}				
				});
				$(form).find("*[name='u_password']").each(function(){
					if(valid && checkPassword(this).length>0){
						valid=false;
					}				
				});
				
				$(form).find(".error").each(function(){
					if(valid && $(this).text().length>0){
						valid=false;
					}				
				});
				
				
				if(valid){
					$(form).find("*[type='submit']").removeAttr( "disabled" );
				}else{
					$(form).find("*[type='submit']").attr( "disabled","disabled" );
				}
				
				return valid;
			}
			checkAll(this);
			
			$(this).find("*[name='u_login']").keyup(function(){
				var message=checkLogin(this);
				$(this).removeClass("error");
				if(message.length>0){
					$(this).addClass("error");
				}
				$(this.form).find("#error-u_login").text(message);
				checkAll(this.form);				
			});
			$(this).find("*[name='capture']").keyup(function(){
				var message=checkCapture(this);
				$(this).removeClass("error");
				if(message.length>0){
					$(this).addClass("error");
				}
				$(this.form).find("#error-capture").text(message);
				checkAll(this.form);				
			});
			
			$(this).find("*[name='u_mail']").keyup(function(){
				var message=checkMail(this);
				$(this).removeClass("error");
				if(message.length>0){
					$(this).addClass("error");
				}
				$(this.form).find("#error-u_mail").text(message);	
				checkAll(this.form);			
			});
			
			$(this).find("*[name='u_phone']").keyup(function(){
				var message=checkPhone(this);
				$(this).removeClass("error");
				if(message.length>0){
					$(this).addClass("error");
				}
				$(this.form).find("#error-u_phone").text(message);	
				checkAll(this.form);			
			});
			
			$(this).find("*[name='u_password']").keyup(function(){
				var message=checkPassword(this);
				$(this).removeClass("error");
				$(this.form).find("*[name='cpassword']").removeClass("error");
				if(message.length>0){
					$(this).addClass("error");
					$(this.form).find("*[name='cpassword']").addClass("error");
				}
				$(this.form).find("#error-u_password").text(message);	
				checkAll(this.form);			
			});
			$(this).find("*[name='cpassword']").keyup(function(){
				var message=checkPassword(this.form.u_password);
				$(this).removeClass("error");
				$(this.form).find("*[name='u_password']").removeClass("error");
				if(message.length>0){
					$(this).addClass("error");
					$(this.form).find("*[name='u_password']").addClass("error");
				}
				$(this.form).find("#error-u_password").text(message);
				checkAll(this.form);				
			});
			
			
			
			$(this).bind("submit",function(){
				submitText=$(this).find("*[type='submit']").attr("value");

				$(this).find("*[type='submit']").attr("value","Отправка").attr("disabled","disabled");
				$(this).find("input").attr("readonly","readonly");
				
				var data=$(this).serialize();
				form=this;
				$.post($(this).attr("action"),data+"&ajax=true",function(resp){
					var redirect_name="redirect=";
					var message_name="message=";
//					alert(resp);
					if(resp=='ok'){
						document.location='/';
					}else if(resp.substring(0,redirect_name.length)==redirect_name){
						document.location=resp.substring(redirect_name.length);
					}
					else if(resp.substring(0,message_name.length)==message_name){
						alert(resp.substring(message_name.length));
					}
					else{
						$(resp).find("div").each(function(){
							$(form).find("#error-"+this.id).text($(this).text());
							if($(this).text().length>0){
								$(form).find("*[name='"+this.id+"']").addClass('error');
							}
						});
					}	
					$(form).find("*[type='submit']").attr("value",submitText);
					$(form).find("input").removeAttr("readonly");
					checkAll(form);
				});
				return false;
			});
			
			//alert($(this).attr("class"));
			return false;
			/////////////////////////////////////
			/////////////////////////////////////
			$(this).attr("method","POST");
			num=$(this).find("#num");
			message=$(this).find("#message");
			messageBar=$(this).find("#message-bar");
			
			cb=function(resp){
				//num.attr("value",$(resp).find("div.num").text());
				
				$(resp).find("div.num").each(function(){	
					num.attr("value",this.innerHTML);
				});
				$(resp).find("div.message").each(function(){
					//alert($(this).html());
					messageBar.html(messageBar.html()+"<div>"+$(this).html()+"</div>");	
				});
				messageBar.scrollTop(messageBar.scrollTop()+1000);
				$("#test").text(parseInt($("#test").text())+1);
				//alert(num.attr("value"));
				
				//$("#test").toggle(2000,function(){
					$.post(action,"action=get&num="+num.attr("value"),cb);
				//});
			};
			action=$(this).attr("action");
//			$.post(action,"action=get&num="+num.attr("value"),cb);
			//$("#test").toggle(2000,function(){
			$.post(action,"action=get&num="+num.attr("value"),cb);
			//	});
			
		}
	});
})(jQuery);
