$(document).ready (function()
{
	loadAjaxContent('/user/?mode=login&'+Math.round(Math.random()*10000000), 'loginPlace');
	//dateObj = new Date(year, month+1, date );
	var cText = {
			months: ["января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"]
	};
	var today = new Date();
	var month=today.getMonth()+1;
	dana=today.getDate()+" "+cText.months[today.getMonth()]+" "+today.getFullYear();
//	alert(dana);
    $("div.timus").text(dana);
  
    $("div#perd").click(function()
    		{
    	if ($(this).attr("class")=='per2')
    	{
    		$(this).addClass("per3");
        	$(this).removeClass("per2");
        	 $("div.perehod").addClass("perehod2");
             $("div.perehod").removeClass("perehod");
    	}
    	else if ($(this).attr("class")=='per3')
    	{
    		$(this).addClass("per2");
        	$(this).removeClass("per3");
        	 $("div.perehod2").addClass("perehod");
             $("div.perehod2").removeClass("perehod2");	
    	}
       
    		}
    		);
 
});

function find_form(id) {
	var price_b = $('#f'+id+' #price_before_new').val()/$('#f'+id+' #main_course').val();
	
	if (price_b < 1) {
		$('#f'+id+' #price_before').attr('value',price_b);
	} else {
		$('#f'+id+' #price_before').attr('value',Math.round(price_b));
	}
	
	var price_a = $('#f'+id+' #price_after_new').val()/$('#f'+id+' #main_course').val();
	
	if (price_a < 1) {
		$('#f'+id+' #price_after').attr('value',price_a);
	} else {
		$('#f'+id+' #price_after').attr('value',Math.round(price_a) );
	}
	
	return true;
}
function checkaddress() {
	
	if($('#addreadd input[name=attr_street_185]').val()!='' && $('#addreadd input[name=attr_house_175]').val()!='')
	{
	return true;
	}
	else {
		alert('Заполните пожалуйста поля адреса!');
		return false;
		}

}


function add_item(data_id)
{
	var url_1='/shcart/?data_id='+data_id+'&step=0&mode=add';
	window.top.frames["win_basket"].location = url_1;

//	var url_1='/shcart/?data_id='+data_id+'&step=2&nstep=2&mode=add';
//	document.location=url_1;

	CreateShMess();
}

/*function add_item(data_id){
	global_open('Товар добавлен в корзину.',3);
	var url_1='/shcart/?data_id='+data_id+'&step=0&mode=add';
	window.top.frames["win_basket"].location=url_1;
}
*/
function log_out()
{
	ht = document.getElementsByTagName("html");
	//ht[0].style.filter = "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)"; 
	ht[0].style.filter = "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)";
	if (confirm('Вы действительно хотите выйти?'))
	{
		return true;
	}
	else
	{
		ht[0].style.filter = "";
		return false;
	}
}


toMesHide = null;
tmSh = null;



function CreateShMess()
{
	removeShMess();

	message = "Товар добавлен в корзину. Выбирайте следущий товар или ";
	var text = document.createTextNode(message);

	var elem = document.createElement("div");

	elem.setAttribute('id', 'fixme');
	elem.setAttribute('onclick', 'removeShMess();');

	elem.appendChild(text);

//
//  document.write('<a href="#" onclick="auto_hide();return false;"><img src="/pics/cr.gif" title="Закрыть" alt="Закрыть" width=20 height=22 border=0></a>');



//
	var brelem = document.createElement("br");
	elem.appendChild(brelem);

	var elemlink = document.createElement("a");
	message = "переходите к оформлению заказа.";
	var textlink = document.createTextNode(message);
	elemlink.appendChild(textlink);
	elemlink.setAttribute('href', '/shcart/?step=2&nstep=2&url=/');
	elem.appendChild(elemlink);


	document.getElementsByTagName("body")[0].appendChild(elem);
	toMesHide = elem;
	tmSh = window.setTimeout(removeShMess, 6000);

}



function removeShMess()
{
	if (tmSh)	clearTimeout(tmSh);
	if (toMesHide)
	{
		document.getElementsByTagName("body")[0].removeChild(toMesHide);
		toMesHide = null;
	}
}


/*
---------------------------------------------------------
--------------- Авторизация пользователя ----------------
---------------------------------------------------------
*/


/* загрузка блока пользователя ajax */
function loadAjaxContent (content, place) {
	if($('#'+place).length) {
		$.ajax({
			url: content,
			dataType : "html",
			success: function (data) {
				$('#loginPlace').css('background','none');
				$(data).appendTo($('#'+place));
			}
		})
	}
}

/* Авторизация пользователя через блок входа */
function shopLogin() {
	$('<div id="loading"></div>').appendTo($('.newLine'));

	$.post('/user/', {
		mode : $('#log_mode').val(),
		type : $('#log_type').val(),
		email : $('#log_email').val(),
		password : $('#log_password').val()
		},
		function(data) {
			$('#loginPlace').html(data);
		}
	)
}

/* функции показывающие label для полей ввода в форме авторизации */
function hideTitle(elem) {
	$(elem).hide();
	$(elem).next().focus();
}

function clean(elem) {
	$(elem).prev().hide();
}

function showTitle(elem) {
	if ($(elem).val() == '')
	{
		$(elem).prev().show();
	}
}


/* Регистрация */
function shopReg(data) {

	var email2 = $('#reg_email').val();
	var pass = $('#reg_password').val();
	var pass2 = $('#reg_password2').val();

	emailTest = "^[_\\.0-9a-z-]+@([0-9a-z][0-9a-z_-]+\\.)+[a-z]{2,4}$";
	passTest = "^.{4,}";

	var errors = '';

	var regex_email = new RegExp(emailTest, 'i');
	var regex_pass = new RegExp(passTest);

	if (regex_email.test(email2) == false) {
		errors += '<li>e-mail</li>';
	}
	if (regex_pass.test(pass) == false) {
		errors += '<li>пароль</li>';
	}
	if (pass != pass2) {
		errors += '<li>подтверждение пароля</li>';
	}
	if (data != 1)
	{
		errors += '<li>число на изображении</li>';
	}
	if (errors != '')
	{
		$('#messageArea td').html('<strong>Не правильно заполнены следующие поля:</strong><ul>'+errors+'</ul>');
		$('#messageArea').show();
		return false;
	}
	else {

		$.post('/user/', {
			mode : 'reg',
			email : email2,
			password : pass
			},
			function(data) {
				if (data == 0)
				{
					$('<p class="redEr">Такой логин уже существует</p>').appendTo($('#emailContainer'));
					return false;
				}
				else {
					document.location = '/user/?mode=reg&klwfjfwehfjkwjhef';
				}
			}
		)
	}
}

/* Проверка капчи */
function checkCaptcha() {
	$.post('/captcha/captcha.php', {
		captcha : $('#captcha').val(),
		mode : 'check'
		}, shopReg
	)
	return false;
}

/* Востановление пароля */
function restorePass() {
	$('#b-restButton').css('background','url(/pics/loading_white.gif) 118px center no-repeat');
	$.post('/user/', {
		mode : 'restore',
		email : $('#res_email').val()
		},
		function(data) {
			if (data == 0)
			{
				$('#emailContainer span').hide();
				$('.errors').show();
			}
			else {
				$('#emailContainer span').hide();
				$('.good').show();
			}
			$('#b-restButton').css('background','none');
		}
	)
	return false;
}

/* Установка выбранного адреса в качестве основного */
function saveaddr() {
	$.post('/profile/', {
		mode : 'address',
		data_id : $('.radioBut:checked').attr('value'),
		action : 'update',
		attr_active : '1'
	},
	function(data) {
		document.location = '/profile/?mode=address';
	}
	)
}

/* Удаление адреса */
function deleteaddr(d_id) {
	$.post('/profile/', {
		mode : 'address',
		essense_name : 'address',
		data_id : d_id,
		action : 'delete'
	},
	function(data) {
		document.location = '/profile/?mode=address';
	}
	)
}

/* ПоказатьСкрыть блок */
function toggleBlock(elem) {
	$('#'+elem).toggle();
	return false;
}
function adds_click(id)
{
for(var i=0;i<=6;i++)
{
if(document.getElementById('icoImg'+i))
{
if(i==id)
{
document.getElementById('icoImg'+i).style.display=(document.getElementById('icoImg'+i).style.border = '1px #24841b solid');
$('a#galss'+i).show();
$('a#galr'+i).show();
if(i!=0)
{
$('a#galss0').hide();
$('a#galr0').hide();
}
}
else if(i!=id)
{
document.getElementById('icoImg'+i).style.display=(document.getElementById('icoImg'+i).style.border = '1px #b5aca1 solid');
$('a#galss'+i).hide();
$('a#galr'+i).hide();
}
}
}

} 
