﻿function checkRusText(str) {
	if(str=='') return false;
	if(str.replace(/[^йцукенгшщзхъфывапролджэячсмитьбюё]/gi,'').length>0) return true;
	return false;
}
function checkEnText(str) {
	if(str=='') return false;
	if(str.replace(/[^\w]/gi,'').length>0) return true;
	return false;
}
function checkEmptyText(str) {
	if(str=='') return false;
	if(str.replace(/[\s]/g,'').length>0) return true;
	return false;
}

function checkNum(num,len){
	if(num=='') return false;
	if(num.replace(/[0-9]/g,'').length>0) return false;
    if(num.length!=len) return false;
 return true;
}
function checkDate(date){// date dd.mm.YYYY
	if(date=='') return true;
	if(date.replace(/([\d]{2})\.([\d]{2})\.([\d]{4})/g,'').length>0) return false;
 return true;
}
function checkPhone(num){
	if(num=='') return false;
	if(num.replace(/[0-9+\-()\s]/g,'').length>0) return false;
 return true;
}
function echeck(str) {
	if(str=='') return false;
	if(str.replace(/([a-z_\-\.\d]+)+@+([a-z\-\d]+)+\.+([a-z]{2,4})/gi,'').length>0) return false;
	return true;
}
function check_captcha(o){
        var c = $('#captcha_md5').get(0);
		if ((o != null) && (c != null)) {
        if (hex_md5($(o).val()) != $(c).val()) {
	        $.ajax(
					{
						url: '/index.html',
						type: 'GET',
						data: "tpl=captcha&f=read_tpl",
						success: function(html){$('#cpt_container').html(html);}
					});
	    return false;
        }else return true;
       } 
return false;
}

var err=0;
function userAccauntExists(originalRequest){
	var q = eval('(' + originalRequest.responseText + ')');
	inp=$("#"+q['inpID']);
	if(parseInt(q['exists'])==1 && inp!=null){
		$(inp).val($(inp).attr('exMsg'));
		$(inp).attr('class','fe4');
		err=1;
	}
}

function show_error(originalRequest){
	if(typeof originalRequest.responseText!='undefined' && originalRequest.responseText!='') var q = eval('(' + originalRequest.responseText + ')');
	else document.location.reload();
	if(q['title']) $('#msg_sent_block h1').html(q['title']);
	if(q['error']) $('#msg_sent_block p').html(q['error']);
	if(q['time']!=undefined) time=q['time'];
	else time=3000; //время показа сообщения
	$('.fade').show();
	if(q['parent']!=undefined){// скрываем окно-причину, показываем собщение
		wnd=q['parent'].split(":");
		for(i=0;i<wnd.length;i++){
			$('#'+wnd[i]).hide();
		}
		if(q['hide']!="1"){//если нет флага скрыть окно-причину, восстанавливаем его
			setTimeout(function(){
			wnd=q['parent'].split(":");
			for(i=0;i<wnd.length;i++){
				$('#'+wnd[i]).show();
			}
		}, time);
		}
		$('#w_message').show();
		if(q['reload']==undefined && q['location']==undefined) setTimeout(function(){ //если имеется флаг перезагрузки, не скрываем сообщение
			$('#w_message').hide();
			if(q['hide']=='1') $('.fade').hide(); //если указано скрыть окно-причину, скрываем темный слой
		}, time);
	}else{//если у сообщения нет окна-причины
		show_form('w_message');
		setTimeout("hide_form('w_message')", time);
	}
	
	if(q['reload']!=undefined) setTimeout("document.location.reload()",time);
	else if(q['location']!=undefined) setTimeout("document.location="+q['location'],time);
}

function Combine(inputs,textareas){
var ary=[];
for (var zxc0=0;zxc0<inputs.length;zxc0++){
ary.push(inputs[zxc0]);
}
for (var zxc1=0;zxc1<textareas.length;zxc1++){
ary.push(textareas[zxc1]);
}
return ary;
}

var password="";
function checkForm(oForm)
{
if(oForm==undefined || oForm.name==undefined) return false;
err=0;
var inp=null;
var stype=null;
textAreas=$(oForm).find("textarea").get();
inputs=$(oForm).find("input").get();
inputs=Combine(inputs,textAreas);
$('.error').hide();
for(i=0;i<=inputs.length;i++){
	inp=inputs[i];
		if(typeof inp == 'object')
		{
		stype=$(inp).attr("stype");
		if(typeof stype!='undefined'){
			$(inp).attr("class","fe");//восстанавливаем цвета полей
			if(stype=="rtxt"){
				if(!checkRusText($(inp).val()) || $(inp).attr("erMsg")==$(inp).val() || $(inp).attr("defvalue")==$(inp).val()){
					err=1;
					if(typeof $(inp).attr('erMsg')=='undefined') $(inp).parent().parent().find('.error').show();
					else $(inp).val($(inp).attr("erMsg"));
					$(inp).attr("class","fe2");
					}
			}else if(stype=="txt"){
				if(!checkEmptyText($(inp).val()) || $(inp).attr("erMsg")==$(inp).val() || $(inp).attr("defvalue")==$(inp).val()){
					err=1;
					if(typeof $(inp).attr('erMsg')=='undefined') $(inp).parent().parent().find('.error').show();
					else $(inp).val($(inp).attr("erMsg"));
					$(inp).attr("class","fe2");
				}else{
					if($(inp).attr('type')=='password') password=$(inp).val();
				}
			}else if(stype=="captcha"){
				if(!check_captcha(inp)){
					err=1;
					if(typeof $(inp).attr('erMsg')=='undefined') $(inp).parent().parent().find('.error').show();
					else $(inp).val($(inp).attr("erMsg"));
					$(inp).attr("class","fe2");
					}
			}else if(stype=="phone"){
				if(!checkPhone($(inp).val()) || $(inp).attr("erMsg")==$(inp).val() || $(inp).attr("defvalue")==$(inp).val()){
					err=1;
					if(typeof $(inp).attr('erMsg')=='undefined') $(inp).parent().parent().find('.error').show();
					else $(inp).val($(inp).attr("erMsg"));
					$(inp).attr("class","fe2");
					}
			}else if(stype=="date"){
				if((!checkDate($(inp).val()) || $(inp).attr("erMsg")==$(inp).val()) && $(inp).attr("defvalue")!=$(inp).val()){
					err=1;
					if(typeof $(inp).attr('erMsg')=='undefined') $(inp).parent().parent().find('.error').show();
					else $(inp).val($(inp).attr("erMsg"));
					$(inp).attr("class","fe2");
					}
			}else if(stype=="email"){
				if(!echeck($(inp).val()) || $(inp).attr("erMsg")==$(inp).val() || $(inp).attr("defvalue")==$(inp).val()){
					err=1;
					if(typeof $(inp).attr('erMsg')=='undefined') $(inp).parent().parent().find('.error').show();
					else $(inp).val($(inp).attr("erMsg"));
					$(inp).attr("class","fe2");
					
					}else if($(oForm).attr('name')=="register"){
					$.ajax(
					{
						url: '/index.php',
						type: 'POST',
						data: "email="+$(inp).val()+"&inpID="+$(inp).attr('id')+"&action=check_user_accaunt",
						complete: userAccauntExists
					});
					}
			}else if(stype=="login"){
				if(!checkEnText($(inp).val()) || $(inp).attr("erMsg")==$(inp).val() || $(inp).attr("defvalue")==$(inp).val()){
					err=1;
					if(typeof $(inp).attr('erMsg')=='undefined') $(inp).parent().parent().find('.error').show();
					else $(inp).val($(inp).attr("erMsg"));
					$(inp).attr("class","fe2");
				}else if($(oForm).attr('name')=="register"){
					$.ajax(
					{
						url: '/index.php',
						type: 'POST',
						data: "login="+$(inp).val()+"&inpID="+$(inp).attr('id')+"&action=check_user_accaunt",
						complete: userAccauntExists
					});
				}
			}else if(stype=="conf_pass"){
				if(password!=$(inp).val()){
					err=1;
					if(typeof $(inp).attr('erMsg')=='undefined') $(inp).parent().parent().find('.error').show();
					else $(inp).val($(inp).attr("erMsg"));
					$(inp).attr("class","fe2");
				}
			}
		}
	}
}
	if(err){
		 return false;
	}else{
		if(typeof $(oForm).attr('ajax')!='undefined'){
			setTimeout(function(){
			if(!err){
				$(oForm).find('input, textarea').each(function(){
					if($(this).attr("defvalue")!=undefined && $(this).attr("defvalue")==$(this).val()) $(this).val("");
				});
				$.ajax(
				{
					url: document.location.href,
					type: 'POST',
					data: $(oForm).serialize(),
					complete: show_error
				});
				}
			},1000);
		}else $(oForm).get(0).submit();
	}
}

$(document).ready(function(){
	$(".form_cont input, .form_cont textarea").focus(function(){
		$(this).attr("class","fe");
		if(typeof $(this).attr("erMsg")!='undefined' && $(this).attr("erMsg")==$(this).val()) $(this).val("");
		if(typeof $(this).attr("exMsg")!='undefined' && $(this).attr("exMsg")==$(this).val()) $(this).val("");
		if(typeof $(this).attr("defvalue")!='undefined' && $(this).attr("defvalue")==$(this).val()) $(this).val("");
	});
	$(".form_cont input, .form_cont textarea").blur(function(){
		$(this).attr("class","fe");
		if(typeof $(this).attr("defvalue")!='undefined' && $(this).val()=="") $(this).val($(this).attr("defvalue"));
	});
	$('#cpt_reset').click(function(){
		$.ajax(
					{
						url: '/index.html',
						type: 'GET',
						data: "tpl=captcha&f=read_tpl",
						success: function(html){$('#cpt_container').html(html);}
					});
	})
});
