var FormValidator = {
	checkField:function(inp,type,params){
		switch(type){
			case 'invite': 
					if(!inp.value.match(/^([A-Z0-9]){3}-([A-Z0-9]){3}-([A-Z0-9]){4}-([A-Z0-9]){4}$/)){
						this.showFieldError(inp,this.MSG.BAD_INVITE);
					}else if(params){
						this.checkRemote(inp,params);
					}else{
						this.hideFieldError(inp);
					}
				break;
			case 'login':
					if(inp.value.length<3){
						this.showFieldError(inp,this.MSG.SHORT_LOGIN);
					}else if(inp.value.length>16){
						this.showFieldError(inp,this.MSG.LONG_LOGIN);
					}else if(!inp.value.match(/^[a-z0-9\-_]+$/i)){
						this.showFieldError(inp,this.MSG.BAD_SYMBOLS);
					}else if(params){
						this.checkRemote(inp,params);
					}else{
						this.hideFieldError(inp);
					}
				break;
			case 'pass':
					if(inp.value.length<6){
						this.showFieldError(inp,this.MSG.SHORT_PASS);
					}else if(inp.value.length>16){
						this.showFieldError(inp,this.MSG.LONG_PASS);
					}else if(!inp.value.match(/^[a-z0-9]+$/i)){
						this.showFieldError(inp,this.MSG.BAD_SYMBOLS);
					}else{
						this.hideFieldError(inp);
					}
				break;
			case 'email':
					if(!inp.value.match(/^((([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+(\.([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+)*)@((((([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.))*([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.)[\w]{2,4}|(((([0-9]){1,3}\.){3}([0-9]){1,3}))|(\[((([0-9]){1,3}\.){3}([0-9]){1,3})\])))$/i)){
						this.showFieldError(inp,this.MSG.BAD_EMAIL);
					}else if(params){
						this.checkRemote(inp,params);
					}else{
						this.hideFieldError(inp);
					}
				break;
			case 'wmr':
					if(!inp.value.match(/^R\d{12}$/i)){
						this.showFieldError(inp,this.MSG.BAD_WMR);
					}else{
						this.hideFieldError(inp);
					}
				break;
			case 'nick':
					if(inp.value.length<3){
						this.showFieldError(inp,this.MSG.SHORT_NICK);
					}else if(inp.value.length>32){
						this.showFieldError(inp,this.MSG.LONG_NICK);
					}else if(params){
						this.checkRemote(inp,params);
					}else{
						this.hideFieldError(inp);
					}
				break;
			case 'noempty': 
					if(inp.value.length==0){
						this.showFieldError(inp,this.MSG.EMPTY_FIELD);
					}else if(inp.value.length>255){
						this.showFieldError(inp,this.MSG.LONG_FIELD);
					}else{
						this.hideFieldError(inp);
					}
				break;

		}
	},
	showErrors:function(errors){
		var err = '';
		for(var i=0;i<errors.length;i++){
			if(errors[i].field=='MAIN'){
				err = errors[i].msg;
			}else{
				this.showFieldError($('#'+errors[i].field),errors[i].msg);
			}
		}
		if(err) alert(err);
	},
	checkRemote:function(inp,params){
		$.post(params.url,params,function(data){
			if(data.errors){
		        FormValidator.showErrors(data.errors)
			}else if(data.isAuthNeeded){
				alert('Authorization lost...');
			}else if(data.result){
				FormValidator.hideFieldError(inp);
			}
		},'json');
	},
	showFieldError:function(inp,msg){
			td = ($(inp).parent('div').attr('tdeq'))?$(inp).parent('div'):$(inp).parent('td:eq(0)');
	
			td.addClass('err');
			if($('.errorblock',td).length>0){
				$('.errorblock div.brd div',td).html(msg);
			}else{
				html = '<table border="0" cellspacing="0" cellpadding="0" class="errorblock" style="position:absolute;z-index:1000;display:none;">';
				html += '<tr><td style="border: none; padding: 0; width:4px;height:4px;background:url(\'/images/ea1.gif\') no-repeat;"></td><td style=" border: none; padding: 0; background:url(\'/images/ea2.gif\') repeat-x;"></td><td style="border: none; padding: 0; width:4px;height:4px; background:url(\'/images/ea3.gif\') no-repeat;"></td></tr>';
				html += '<tr><td style="border: none; padding: 0; background:url(\'/images/ea4.gif\') repeat-y;"></td><td style="border: none; padding: 0; background: #929191; color:white;">'+msg+'</td><td style="border: none; padding: 0; background:url(\'/images/ea5.gif\') repeat-y;"></td></tr>';
				html += '<tr><td style=" border: none; padding: 0; width:4px;height:4px;background:url(\'/images/ea6.gif\') no-repeat;"></td><td style="border: none; padding: 0; background:url(\'/images/ea7.gif\') repeat-x;"></td><td style="border: none; padding: 0; width:4px;height:4px; background:url(\'/images/ea8.gif\') no-repeat;"></td></tr>';
				td.prepend(html);
			}
			eb = $('.errorblock',td);
			eb.show();
			eb.hide();
	//		eb.show();
	$(document).ready(function(){
	//alert($('div.brd div',eb).height());
	
	//		eb.css('left',$(inp).offset().left+$(inp).width()-$('div.brd div',eb).width()+5);
			eb.css('top',eb.offset().top+16-$('div.brd div',eb).height());
	});
			var offset = $(td).parents().filter(function(){return $(this).css('position')=='absolute'}).eq(0).offset();
			ml=$(inp).offset().left+$(inp).width()/2;mt=$(inp).offset().top-35;
			if(offset) {ml=ml-offset.left; mt=mt-offset.top;}
//			alert(td.offset().top);
			eb.css('left',(td.offset().left-320)+'px'); 
			eb.css('top',(td.offset().top-225)+'px'); //
	//		eb.css('left',ml+'px'); $(inp).offset().left
	//		eb.css('top',mt+'px'); //$(inp).offset().top
	//		eb.hide();
			eb.show();
			if(typeof inp == 'string') $(inp).focus(); else if(inp) inp.focus();
			FormValidator.tryForm(inp.form);
		
	},
	hideFieldError:function(inp){

		td = ($(inp).parents('div').attr('tdeq'))?$(inp).parents('div'):$(inp).parents('td:eq(0)');
//		$(inp).parents('td:eq(0)').removeClass('err');
//		$(inp).parents('td:eq(0)').children('.errorblock').remove();
		$(td).removeClass('err');
		$(td).children('.errorblock').hide();
		setTimeout(function(){$(td).children('.errorblock').remove();}, 10);

		this.tryForm(inp.form);
	},
	tryForm:function(form){
	  	if(this.hasErrors(form)){
	  		this.disableSubmit(form);
		}else{
	  		this.enableSubmit(form);
		}
	},
	hasErrors:function(form){
//		return $('td.err',form).length>0;
		return false;
	},
	disableSubmit:function(form){
//		$('.button:last',form).addClass('bdisabled');
	},
	enableSubmit:function(form){
		$('.button',form).removeClass('bdisabled');
	},
	validateForm:function(form){
		els=form.elements;
		for(var i=0;i<els.length;i++){
			try{
				if(els[i].tagName!='SELECT'){
					els[i].focus();
					els[i].blur();
					$(els[i]).trigger('change');
				}
			} catch(e){
			}
		}
	},
	getForm:function(form){
		var obj = {};
		for(var i=0;i<form.elements.length;i++){
			el = form.elements[i];
			elN = (el.name||el.id); 
			elV = el.value;
			try{
				elT = $(el).attr('type').toUpperCase();
			}
			catch(e){
				elT = null;
			}

			if(el.tagName=='INPUT'){
				if(elT=='RADIO'){
					if(!el.checked){
					    continue;
					}
				}else if(elT=='IMAGE'){
					continue;
				}else if(elT=='CHECKBOX'){
					if(!el.checked){
//						elV='off:'+elV;
						elV=0;
					}else{
//						elV='on:'+elV;
						elV=1;
					}
				}
			}else if(el.tagName=='BUTTON'){
				continue;
			}else if(el.disabled){
				continue;
			}
			obj[elN]=elV;
		}
		return obj;
	},
	trySubmitForm:function(form,callback){
	 	if(this.hasErrors(form)){
	 		return false;
		}else{
			this.submitForm(form,callback);
		}
	},
	submitForm:function(form,callback){
//		if(data.errors) this.showErrors(data.errors);		
//		if(!callback) callback=function(data){};
		var cbck = function(data){
			if(data.isAuthNeeded){
				alert('Authorization lost...');
				return;
			}
			if(data.errors){
				FormValidator.showErrors(data.errors);
			}
			if(data.result){
				if(typeof(data.redirect)!='undefined'){
					if(typeof(data.message)!='undefined')
						alert(data.message);
					if(typeof(data.delay)!='undefined'){
						setTimeout("location.replace('"+data.redirect+"')",data.delay);
					}else{
						location.href=data.redirect;
					}
				}
			}
			if(callback) callback(data);
		}
		params = this.getForm(form);
		ExitForm.noChanged();
		$.post($(form).attr('action'),params,cbck,'json');
	},

	initForm:function(form,callback){
//		$('a.bsubmit',form).addClass('bdisabled');

//		this.setOnChange(form);
//		this.exitForm(form);

		$('a.bsubmit',form).click(function(){
			$(this).addClass('bdisabled');
			var cbck = function(data){
				$('a.bsubmit',form).removeClass('bdisabled');
				if(data.result){
					$('a.bsubmit',form).fadeOut(250,function(){$('<span style="float:right;font-size:9pt;">Данные успешно сохранены</span>').appendTo($(this).parent()).fadeOut(1000,function(){
						obj = $('a.bsubmit',$(this).parent());
						if(!obj.hasClass('nodisable')){
							obj.addClass('bdisabled');
						}
						obj.fadeIn(250);
						$(this).remove();
					})});
				}
				if(callback) callback(data);
			}
			FormValidator.trySubmitForm($(this).parents('form')[0],cbck);
			return false;
		});
		var obj = {};
		for(var i=0;i<form.elements.length;i++){
			el = form.elements[i];
			$(el).bind('change',function(){
//				$('a.bsubmit',$(this).parents('form')).fadeIn(250);
				$('a.bsubmit',$(this).parents('form')).removeClass('bdisabled');
			});
		}
	}
}
FormValidator.MSG = {
	SHORT_LOGIN	:'<b style="color: #fff;">Ошибка!</b> Введен слишком короткий логин!',
	SHORT_PASS	:'<b style="color: #fff;">Ошибка!</b> Введен слишком короткий пароль!',
	SHORT_NICK	:'<b style="color: #fff;">Ошибка!</b> Введен слишком короткий ник!',
	LONG_LOGIN	:'<b style="color: #fff;">Ошибка!</b> Введен слишком длинный логин!',
	LONG_PASS	:'<b style="color: #fff;">Ошибка!</b> Введен слишком длинный пароль!',
	LONG_NICK	:'<b style="color: #fff;">Ошибка!</b> Введен слишком длинный ник!',
	BAD_SYMBOLS	:'<b style="color: #fff;">Ошибка!</b> Обнаружены недопустимые символы!',
	BAD_EMAIL	:'<b style="color: #fff;">Ошибка!</b> Введен недопустимый адрес!',
	LONG_FIELD	:'<b style="color: #fff;">Ошибка!</b> Количество символов превышает предел 255 символов!',
	EMPTY_FIELD	:'<b style="color: #fff;">Ошибка!</b> Это поле не может быть пустым!',
	BAD_INVITE	:'<b style="color: #fff;">Ошибка!</b> Неверный формат кода приглашения!',
	BAD_WMR		:'<b style="color: #fff;">Ошибка!</b> Неверный формат кошелька WMR!'
}




var ExitForm = {
	
	allElems:{},
	FunOk:null,
	FunCancel:null,
	Mess:null,
	fid:null,

	getForms:function(form){
		var obj = {}; 
		for(var i=0;i<form.elements.length;i++){
			el = form.elements[i];
			elN = (el.id||el.name);
			elV = el.value;
			try{
				elT = $(el).attr('type').toUpperCase();
			}
			catch(e){
				elT = null;
			}

			if(el.tagName=='INPUT'){
				if(elT=='RADIO'){
					if(!el.checked){
					    elV=0;
					}else elV=1;
				}else if(elT=='IMAGE'){
					continue;
				}else if(elT=='CHECKBOX'){
					if(!el.checked){
						elV=0;
					}else{
						elV=1;
					}
				}
			}else if(el.tagName=='BUTTON'){
				continue;
			}else if(el.disabled){
				continue;
			} 
			obj[elN]=elV;
		}
		return obj;
	},

	vals:function(ob){
		elT = $(ob).attr('type').toUpperCase();
		el=$(ob)[0]; 
			if(el.tagName=='INPUT'){ 
				if(elT=='RADIO' || elT=='SELECT-ONE'){
					if(!el.checked){
					    return 0;
					}else return 1;
				}else if(elT=='CHECKBOX'){
					if(!el.checked){
						return 0;
					}else{
						return 1;
					}
				  }
			} 
			
		return $(ob).val();
	},

	setOnChange:function(form){
		elem=this['obj'+form.id].elem;
		for(id in elem){  
			$('#'+id).data('_val',elem[id]).change(function(){  
				if($(this).data('_val')!=ExitForm.vals(this)) {$(this).attr('changed',true);} 
				else { $(this).attr('changed',false); }

			});
		}

	},

	noChanged:function(){
		if(!this['obj'+this.fid]) return;
		elem=this['obj'+this.fid].elem;
		for(id in elem){
			$('#'+id).attr('changed',false);
		}
	},

	isChanged:function(){ //alert(ExitForm.fid);
		if(!this['obj'+this.fid]) return false;
		this.FunOk=this['obj'+this.fid].Fok;
		this.FunCancel=this['obj'+this.fid].Fcancel;
		this.Mess=this['obj'+this.fid].mess;
 		elem=this['obj'+this.fid].elem;
		for(id in elem){
			if($('#'+id).attr('changed')=='true') {
				return true;
			}
		}
		return false;
	},

	message:function(_const){
		if(ExitForm.MSG[_const]) return ExitForm.MSG[_const];
		else return _const;
	},

	create:function(form,text,Fok,Fcancel){
		this['obj'+form.id] = {};
		this['obj'+form.id].mess = this.message(text);
		this['obj'+form.id].Fok = Fok;
		this['obj'+form.id].Fcancel = Fcancel;
		this['obj'+form.id].elem = this.getForms(form);
		this.setOnChange(form);

	},

	exitFun:function(){ //alert(this.isChanged());
		if(this.isChanged() && typeof this.FunOk == 'function'){
			if(!confirm(this.Mess)){
				if(typeof this.FunCancel == 'function') {	
					this.noChanged();
					return this.FunCancel(); 
				}
			} else {
				this.noChanged();
				this.FunOk(); 
			}
		} 
	},
	initForm:function(){ 
		$(document).click(function(e){ 
			f=$(e.target).parents('form').attr('id'); 
			if(f!==undefined) {ExitForm.fid = f; } 
			if(e.target.tagName.toUpperCase() == "A" || (ExitForm.fid && f!=ExitForm.fid)) {  return ExitForm.exitFun(); } 
			//else if(f || f!='undefined' || f!='') ExitForm.fid = ff;

		});

	}

}

ExitForm.MSG = {
	EXIT_MSG : "Данные были изменены. Вы хотите сохранить?"
}


