var enter_bar_focus = true; 
var req=null;
var submit_disabled = true;

function login()
{
	var login = (document.getElementById('form_login')).value;
	var pass = (document.getElementById('form_pass')).value;
	sendRequest("/form.php?a=my&xhr=1&f=auth_xhr","login="+login+"&password="+pass);
}	

function sendRequest(url,params)
{
	req=initXMLHTTPRequest();
	if (req)
	{
		req.onreadystatechange=onReadyState;
		req.open("POST",url+'&test='+Math.random(),true);
		req.setRequestHeader("Connection", "close");
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(params);
	}
}

function initXMLHTTPRequest()
{
	var xRequest=null;
	// Инициализация объекта запроса
	if (window.XMLHttpRequest)
	{
		xRequest=new XMLHttpRequest();
	} else if (window.ActiveXObject)
	{
		xRequest=new ActiveXObject("Microsoft.XMLHTTP");
	}
	return xRequest;
}

// Определение обработчика обратного вызова
function onReadyState()
{
	var ready=req.readyState;
	var d = null;
	// Проверка readyState
	if (ready==4)
	{
		// Чтение данных ответа
		resp=req.responseText;
		req=null;
	}
	else
	{
		return 0;
	}
	eval(resp);
	if(response.status == 'ok'){
		document.getElementById('user_menu').innerHTML = "<div class=user-name><a href=/my/info>Личная информация</a></div><div class=history-order><a href=/my/history>История заказов</a></div><div class=exit><a href=/exit>Выход</a></div>";
		document.getElementById('enter_block').style.display = 'none';
	}else {
		document.getElementById('form_mes').style.color = 'red';
		document.getElementById('form_mes').innerHTML = 'Неправильный логин или пароль';
	}
}
function check_focus(){
	element = document.getElementById('enter_block');
	if(enter_bar_focus == false  && element.style.display == ''){
	element.style.display = 'none';
	document.getElementById('form_mes').innerHTML = '&nbsp;';
	}
}
function show_hide(id) {
	elem = document.getElementById(id);
	document.getElementById('form_mes').innerHTML = '&nbsp;';
	block_submit();
	if(elem == null) {
		return true;
	} else {
		if (elem.style.display == '')	elem.style.display = 'none';
		else {
			elem.style.display = '';
			document.getElementById('form_login').focus();
		}
		return false;
	}
	
}
function block_submit(){ 
	el_login = document.getElementById('form_login');
	el_pass = document.getElementById('form_pass');

	if(el_login.value == '' || el_pass.value == ''){
		document.getElementById('submit').disabled = true;
	}else{
		submit_disabled = false;
		document.getElementById('form_mes').innerHTML = '&nbsp;';
		document.getElementById('submit').disabled = false;
	}
}

var old_count;

function obj(idelem){ return document.getElementById(idelem);}

function chenge(){
	show_hide(obj('cartf1'));
	show_hide(obj('cartf2'));
	show_hide(obj('carte'));
}

function money(c){
	c = ""+((Math.round(c*100))/100);
	l = c.length;
	return c.substring(l-3,l-2)=='.'?c:(c.substring(l-2,l-1)=='.'?c+"0":c+".00");
}

function add2cart(e,idgd,price) {
	//srcElement = ie ? event.srcElement : e.target;
	var div = document.getElementById('div'+idgd);
	//var imgcart = document.getElementById('img'+idgd);
	var idgd = parseInt(idgd);
	var price = parseFloat(price);
	var img = new Image();
	var cart_num = parseFloat(obj('cart_num').innerHTML);
	var cart_sum = Math.round(parseFloat(obj('cart_sum').innerHTML)*100)/100;
	if (obj('id'+idgd).innerHTML == "В корзину"){
		//imgcart.src = '/i/outcart.gif'
		img.src = '/shop/cart/'+idgd+'/1/'+Math.random()+'.gif';
		var cost = money(cart_sum + price);
		document.getElementById('id'+idgd).innerHTML = "Добавление";
		img.onload = function() {
			document.getElementById('cart_num').innerHTML = cart_num + 1;
			document.getElementById('cart_sum').innerHTML = cost;
			document.getElementById('id'+idgd).innerHTML = "Из корзины";
			div.className = 'outcart';
			if (obj('cart_num').innerHTML == 1) chenge();
		}
	}else{
		//imgcart.src = '/i/incart.gif'
		img.src = '/shop/cart/'+idgd+'/0/'+Math.random()+'.gif';
		var cost = money(cart_sum - price);
		document.getElementById('id'+idgd).innerHTML = "Удаление";
		img.onload = function() {	
			document.getElementById('cart_num').innerHTML = cart_num - 1;
			document.getElementById('cart_sum').innerHTML = cost;
			document.getElementById('id'+idgd).innerHTML = "В корзину";
			div.className = 'incart';
			if (obj('cart_num').innerHTML == 0) chenge();
		}
	}
}

function del_from_cart(e,idgd,price) {
	var div = document.getElementById('div'+idgd);
	var idgd = parseInt(idgd);
	var count = parseInt(document.getElementById('cart'+idgd).value);
	var price = parseFloat(price);
	var img = new Image();
	var cart_num = parseFloat(document.getElementById('cart_num').innerHTML);
	var cart_sum = Math.round(parseFloat(document.getElementById('cart_sum').innerHTML)*100)/100;
	var cost = money(cart_sum - (price*count));
	img.src = '/shop/cart/'+idgd+'/0/'+Math.random()+'.gif';
	img.onload = function() {
		document.getElementById('cart_num').innerHTML = cart_num - count;
		document.getElementById('cart_sum').innerHTML = cost;
		show_hide(div);
	}
	if (obj('cart_num').innerHTML == 1){
		location.replace('/shop/cart/'+idgd+'/0/goback');
		return true;
	}
}

function chenge_count(idgd,price){
	var idgd = parseInt(idgd);
	var price = parseFloat(price);
	var count = parseInt(document.getElementById('cart'+idgd).value);
	if(isNaN(count) || count < 1) {
	if(document.getElementById('cart'+idgd))
	document.getElementById('cart'+idgd).value = old_count;
	old_count = null;
	return;
	}
	var img = new Image();
	var cart_num = parseFloat(obj('cart_num').innerHTML);
	var cart_sum = Math.round(parseFloat(obj('cart_sum').innerHTML)*100)/100;
	var difference = count - old_count;
	var cost = money(cart_sum + price*difference);
	if (difference != 0){
		img.src = '/shop/cart/'+idgd+'/'+count+'/'+Math.random()+'.gif';
		img.onload = function() {
			document.getElementById('cart_num').innerHTML = cart_num + difference;
			document.getElementById('cart_prefix').innerHTML = cart_prefix(cart_num + difference);
			if(document.getElementById('cart_num2'))
			document.getElementById('cart_num2').innerHTML = cart_num + difference;
			document.getElementById('cart_prefix2').innerHTML = cart_prefix(cart_num + difference);
			document.getElementById('cart_sum').innerHTML = cost;
		}
	}
	old_count = null;
	update_total_cost(cost);
	update_idgd_cost(price*count,'idgd_cost'+idgd);
}

function cart_prefix(num){
	var num = String(num);
	var prfx1 = '';
	var prfx2 = 'ов';
	var prfx3 = 'а';
	var reg1 = /^(.*)(11|12|13|14|15|16|17|18|19)$/;
	var reg2 = /^(.*)1$/;
	var reg3 = /^(.*)(2|3|4)$/;
	var reg4 = /^(.*)$/;
	if(num.match(reg1))return prfx2;
	if(num.match(reg2))return prfx1;
	if(num.match(reg3))return prfx3;
	if(num.match(reg4))return prfx2;
}

function update_total_cost(cost){
	obj('total_cost').innerHTML = money(cost);
}

function update_idgd_cost(cost,idgd){
	obj(idgd).innerHTML = money(cost);
}

function read_count(idgd){
	if (old_count == null){
		old_count = parseInt(document.getElementById('cart'+idgd).value);
	}
}
function is_email(email) {
	re = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z0-9]{2,4})$/ig;
	if (email && !re.test(email)) {	return false;	}
	return true;
}
function is_icq(icq) {
	re = /^[0-9]{5,}$/ig;
	if (icq && !re.test(icq)) {return false;}
	return true;
}
function is_phone(phone) {
	re = /[\+\s\(\)\-]/gi;
	phone = phone.replace(re, '');
	re = /^[\d]{10,}$/ig;
	if (phone && !re.test(phone)) {return false;}
	return true;
}


function check_info()	{
//	submit_button = document.getElementById('submit');
//	submit_button.focus();
	name_ = document.content['content[name]'];
	email = document.content['content[email]'];
	telefon = document.content['info[telefon]'];
	pass = document.content['pass'];
	pass2 = document.content['pass2'];
	if (document.content.action.indexOf('reg') != -1) {
		login = document.content['content[login]'];
		if (login.value=='')		{alert('Заполните, пожалуйста, поле \'Логин\'');login.focus();return false;}
		if (pass.value=='')			{alert('Заполните, пожалуйста, поле \'Пароль\'');pass.focus();return false;}
		if (pass2.value=='')		{alert('Повторите ввод пароля, пожалуйста');pass2.focus();return false;}
	}


	if (name_.value=='')			{alert('Укажите свое ФИО, пожалуйста');name_.focus();return false;}
	if (pass2.value != pass.value)	{alert('Ошибка! Пароли не совпадают'); pass.value=''; pass2.value=''; pass.focus(); return false; }
	if (!is_email(email.value))		{alert("Вы ввели некорректный email");email.focus();return false;}
	if (telefon.value=='')			{alert('Заполните, пожалуйста, поле \'Телефон\'');telefon.focus();return false;}

	return true;
}

function subscribe(elem) {
if (elem.checked) {
document.content['subscribe[info]['+elem.value+'][format]'].disabled = true;
document.content['subscribe[info]['+elem.value+'][charset]'].disabled = true;
} else {
document.content['subscribe[info]['+elem.value+'][format]'].disabled = false;
document.content['subscribe[info]['+elem.value+'][charset]'].disabled = false;
}
}

function check_quick_info(){

	submit = document.quick_order['submit'];
	submit.focus();
	name_ = document.quick_order['user[name]'];
	telefon = document.quick_order['user[login]'];
	
	if (telefon.value=='')			{alert('Укажите номер Вашего телефона');telefon.focus();return false;}
	if (!is_phone(telefon.value))	{alert('Проверьте, правильно ли Вы указали номер своего телефона. Он должен содержать код города и состоять минимум из 10 символов');telefon.focus();return false;}
	if (name_.value=='')			{alert('Укажите Ваше имя и фамилию');name_.focus();return false;}
	
	return true;
}
function producer(x,y){
if(x == 'deselect'){
document.getElementById('filter_all').checked = false;
return}
if(y.checked){
	checked = true;
	y.name = 'filter[]';
	y.value = 'all'
} else {
	checked = false;
}
var arr = document.getElementsByName(x);
var l = arr.length;
for (var i = 0; i < l; i++) { 
arr[i].checked = checked;
 }
 }

function change_picture( path , idmea ,  zoom ){
	var prefix= '';
	var postfix= '';
	if(zoom){
		var path_ = path.substring(0, path.length-1);
		document.getElementById('image').innerHTML = '<a href="' + path_ + '.jpg" target="_blank" rel="zoomin"><img src="' + path + '.jpg"></a>';
	}
	if(document.getElementById('pic' + old_idmea))document.getElementById('pic' + old_idmea).className = 'attach-img';
	if(document.getElementById('pic' + idmea))document.getElementById('pic' + idmea).className = 'attach-img attach_selected';
	old_idmea = idmea;
}

function RTrim(str) {
 for (var i=str.length-1; ((str.charAt(i)<=" ")&&(str.charAt(i)!="")); i--);
 return str.substring(0,i);
}




















