/*
function addBasket(id){
	req.onreadystatechange = function() { 	
		if (req.readyState == 4) {
			//alert(req.responseText);
			if(req.responseJS){
				 if (req.responseJS.rez != ""){ 
					$("#zakaz_"+id).empty();
					$("#zakaz_"+id).html(req.responseJS.rez);
					$(".basket_text").empty();
					$(".basket_text").html(req.responseJS.mosmsg); 					
					$(".basket").css("background-image", "url(/images/basket2.gif)");
				}
			}
		}
	}
	req.open(null, "/modul/scripts/srv_basket.php", false);
	req.send( {'action': 'add_basket', 'id': id} ); 
}
*/


function add_basket(id) {
	$(".tov_"+id+"").attr("src", "/modul/scripts/loading-small.gif");
	$(".tov_"+id+"").attr("height", "16");
	$(".tov_"+id+"").attr("vspace", "16");
	var req = new JsHttpRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			//alert(req.responseText);
			$(".tov_"+id+"").attr("src", "/images/add_basket.gif");
			$(".tov_"+id+"").attr("height", "48");
			$(".tov_"+id+"").attr("vspace", "0");
			$(".tov_"+id+"").attr("alt", "Товар в корзине");
			$(".tov_"+id+"").attr("title", "Товар в корзине");
			$(".tov_"+id+"").attr("onclick", "");
			$(".tov_"+id+"").attr("style", "");
			$(".span_"+id+"").attr("style", "color: green; font-weight: bold;");
			$(".span_"+id+"").text("В корзине");
			$(".span_"+id+"").attr("onclick", "");
		}
	}
	req.open(null, "/modul/scripts/srv_basket.php", true);
	req.send( { 'action': 'add_basket', 'id': id } );
}

function delBasket(id){
	req.onreadystatechange = function() { 	
		if (req.readyState == 4) {
			//alert(req.responseText);
			if(req.responseJS){
				 if (req.responseJS.rez != ""){ 
					$("#zakaz_"+id).empty();
					$("#zakaz_"+id).html(req.responseJS.rez);
					$(".basket_text").empty();
					$(".basket_text").html(req.responseJS.mosmsg); 
					$(".basket").css("background-image", req.responseJS.basket_img);				
				}
			}
		}
	}
	req.open(null, "/modul/scripts/srv_basket.php", false);
	req.send( {'action': 'del_basket', 'id': id} );  
}


function delBasket_step1(id){
	//записать все проставленные количества в сессию, потом уже уалять позицию
	value=GEByID('f');
	req.onreadystatechange = function() { 	
		if (req.readyState == 4) {
			//alert(req.responseText);
			if(req.responseJS){
				 if (req.responseJS.rez != ""){ 
					//alert(req.responseJS.rez);
					$("#basket_table").empty();
					$("#basket_table").html(req.responseJS.rez);
					$(".basket_text").empty();
					$(".basket_text").html(req.responseJS.mosmsg); 
					$(".basket").css("background-image", req.responseJS.basket_img);
				} 
			}
		}
	}
	req.open(null, "/modul/scripts/srv_basket.php", false);
	req.send( {'action': 'del_basket_step1', 'id': id, 'q': value} );  
	return;
	
}

function go_step2(){
	saveQuant();
	location.href='/my_basket/step2/';
	return;
}

function saveQuant(){
	value=GEByID('f');
	req.onreadystatechange = function() { 
		if (req.readyState == 4) {
			//alert(req.responseText);
		}
	}
	req.open(null, "/modul/scripts/srv_basket.php", false);
	req.send( {'action': 'saveQuant', 'q': value} );  
	return;	
}

function getSumm(n){
	var summ=0;
	for(i=0;i<n;i++){
		//цена
		price=$("#price_"+i).val();
		if(price.indexOf(',')>0){
			price=price.replace(/,/, '.');
		}
		price=parseFloat(price);

		//количество
		kol=$("#kol_"+i).val();
		if(kol.indexOf(',')>0){
			kol=kol.replace(/,/, '.');
		}
		kol=parseFloat(kol);
		if(isNaN(kol)) kol=1;
		$("#kol_"+i).val(kol);
		
		//сумма
		summ_item=price*kol;
		summ_str=summ_item+'';
		pos=summ_str.indexOf('.');
		if(pos>0){
			summ_str=summ_str.substr(0, pos)+'.'+summ_str.substr(pos+1, 2);
			summ_item=parseFloat(summ_str);
		}
		$("#summ_item_"+i).html(""+summ_item);
		summ+=summ_item;
	}

	//итоговая сумма
	summ_str=summ+'';
	pos=summ_str.indexOf('.');
	if(pos>0){
		summ_str=summ_str.substr(0, pos)+'.'+summ_str.substr(pos+1, 2);
		summ=parseFloat(summ_str);
	}
	$("#summ_tovar").html(summ+" руб.");
}

///////////////--------Авторизация---------------/////////////
function rozn_login(){
	value=GEByID('form_login_rozn');
	JsHttpRequest.query(
		'/modul/scripts/auth_rozn.php',
		{'status': 'login', 'q': value},
		function(result, errors) {
			//alert(errors);
			location.href='/kabinet/';	
		},
		false
	);	
}

function rozn_rem_pass(){
	value=GEByID('f');
	JsHttpRequest.query(
		'/modul/scripts/auth_rozn.php',
		{'status': 'rem_pass', 'q': value},
		function(result, errors) {
			//alert(errors);
			if (result) {
				if(result['tmpl']==""){ //шаблон пустой, работаем с текущей анкетой
					$("#msg_anketa").html(result['msg']);
				}
				else{
					$("#msg_anketa").html(result['msg']);
					$("#inc_form").html(result['tmpl']);
				}
			}	
		},
		false
	);	
}

///////////////--------Определение варианта анкеты (с/без e-maila) ---------------/////////////
function get_formVariant(){
	ch=GEByID('anketa_check_email').checked;
	if(ch){
		//нет почты
		JsHttpRequest.query(
			'/modul/scripts/auth_rozn.php',
			{'status': 'get_anketa_nomail'},
			function(result, errors) {
				//alert(errors);
				if (result) {
					$("#msg_anketa").html(result['msg']);
					$("#inc_form").html(result['tmpl']);
				}	
			},
			false
		);
	}
	else{
		ch=0;
		if($("#login_page").val()==""){
			err_field_style("login_page"); ch++;
		}
		if($("#anketa_pass*").val()==""){
			err_field_style("anketa_pass*"); ch++;
		}		
		if(ch>0){
			//alert('Заполните обязательные поля! \n\nлибо поставьте галочку, что у Вас нет электронной почты');
			$.prompt("Заполните обязательные поля!<br /><br />либо поставьте галочку, что у Вас нет электронной почты",{prefix:'brownJqi'});
		}
		else		
			check_user();
	}
}

function err_field_style(item){
	$("#"+item).css("border", "solid #f00 1px");
	$("#"+item).css("background-color", "#FFF2F2");
	$("#"+item).keypress(function(){
		$(this).css("border", "solid #D5C3A7 1px");
		$(this).css("background-color", "#fff");
	});	
}

function ch_ch(){
	ch=GEByID('anketa_check_email').checked;
	if(ch){
		$("#login_page").attr("disabled","disabled");
		$("#login_page").css("border", "solid #eee 1px");
		$("#login_page").css("background-color", "#fff");
		$("#anketa_pass*").attr("disabled","disabled");
		$("#anketa_pass*").css("border", "solid #eee 1px");
		$("#anketa_pass*").css("background-color", "#fff");
	}
	else{
		$("#login_page").removeAttr("disabled");
		$("#login_page").css("border", "solid #D5C3A7 1px");
		$("#anketa_pass*").removeAttr("disabled");
		$("#anketa_pass*").css("border", "solid #D5C3A7 1px");
	}
}

function check_user(){
	value=GEByID('f');
	var req = new JsHttpRequest();
	JsHttpRequest.query(
		'/modul/scripts/auth_rozn.php',
		{"q": value, "st": "reg_before", "status": "query_user"},
		function(result, errors) {
			//alert(errors);
			if (result) {
				if(result['msg']==''){ //авторизовались
					location.href='/kabinet/';
				}
				$("#msg_anketa").html(result['msg']);
				if(result['tmpl']!="") $("#inc_form").html(result['tmpl']);
			}
		},
		false
	);	
}

function valid_anketa(){
	value=GEByID('f');
	var req = new JsHttpRequest();
	JsHttpRequest.query(
		'/modul/scripts/auth_rozn.php',
		{"q": value, "st": "reg_new", "status": "query_user"},
		function(result, errors) {
			//alert(errors);
			if (result) {
				if(result['tmpl']==""){ //шаблон пустой, работаем с текущей анкетой
					if(result['msg']!=""){ //проверили только логин
						if (result["post"]){ // то есть есть ошибки	
							err_field_style(result['post']);
						}
						//alert(result['msg']);
						$.prompt(result['msg'],{prefix:'brownJqi'});
					}
					else{ //проверяем дальше
						//alert('проверяем дальше');
						JsHttpRequest.query(
							'/modul/scripts/auth_rozn.php',
							{"q": value, "status": "empty_field"},
							function(result, errors) {
								//alert(errors);
								if (result) {
									if (result["post"] != ""){ // то есть есть ошибки
										arr=result['post'];
										for(i=0; i<arr.length; i++){
											if(i==0) $("#"+arr[i]+"").focus();
											err_field_style(arr[i]);
										}
										//alert("Заполните обязательные поля!");
										$.prompt("Заполните обязательные поля!",{prefix:'brownJqi'});
									}
									else{
										if (result["msg"] != ""){ //Пароль содержит недопустимые символы.
											err_field_style('anketa_pass*');
											$("#anketa_pass*").focus();
											$("#anketa_pass*").val('');
											//alert(result["msg"]);
											$.prompt(result['msg'],{prefix:'brownJqi'});
										}
										else{
											location.href='/my_basket/step3/';
										}
									}
								}
							},
							false
						);						
					}
				}
				else{
					$("#inc_form").html(result['tmpl']);
					if(result['msg']!=""){
						$("#msg_anketa").html(result['msg']);
					}
				}
			}
		},
		false
	);
}

function check_code(){
	value=GEByID('f');
	var req = new JsHttpRequest();
	JsHttpRequest.query(
		'/modul/scripts/auth_rozn.php',
		{"q": value, "status": "check_code"},
		function(result, errors) {
			//alert(errors);
			status=$("#status_rem").val();
			if (result) {
				if(status=="zakaz"){
					if(result['tmpl']==""){ //шаблон пустой, работаем с текущей формой
						$("#msg_anketa").html(result['msg']);
					}
					else{
						$("#msg_anketa").html(result['msg']);
						$("#inc_form").html(result['tmpl']);
						if(GEByID('anketa_date_distrib')) $($.date_input.initialize);						
					}
				}
				else if(status=="rem_pass" || status=="login"){
					if(result['tmpl']==""){ //шаблон пустой, работаем с текущей анкетой
						$("#msg_anketa").html(result['msg']);
					}
					else{
						//alert("Пароль сохранён. Вы авторизованы.");
						$.prompt("Пароль сохранён. Вы авторизованы.",{prefix:'brownJqi'});
						location.href='/kabinet/';
					}				
				}
			}
		},
		false
	);	
}
//------------------------------------ ЛИЧНЫЙ КАБИНЕТ ------------------------------------------//
function edit_anketa(){
	$("#msg").html("");
	value=GEByID('f');
	JsHttpRequest.query(
		'/modul/scripts/auth_rozn.php',
		{"status": "edit_anketa", "q": value},
		function(result, errors) {
			//alert(errors);
			if (result["post"] != ""){ // не все обязательные поля заполнены				
				arr=result['post'];
				for(i=0; i<arr.length; i++){
					err_field_style(arr[i]);
				}
				$("#"+arr[0]+"").focus();
				//alert("Заполните обязательные поля!");
				$.prompt("Заполните обязательные поля!",{prefix:'brownJqi'});
			}
			else{
				$('#msg_anketa').html('<strong class="ok">Данные успешно сохранены.</strong>');
			}				
		},
		false
	);
}

function logout_rozn(){
	JsHttpRequest.query(
		'/modul/scripts/auth_rozn.php',
		{'status': 'logout'},
		function(result, errors) {
			location.href='/kabinet/';	
		},
		false
	);
}
///////////////--------Заказы в кабинете ---------------/////////////
function show_zakaz(id){
	value=GEByID('f');
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
			//alert(req.responseText);
			if(req.responseJS){
				$('#inc_tbl').html(req.responseJS.rez);			
			}
        }
    }
    req.open(null, "/modul/scripts/kabinet_orders.php", false);
    req.send( {'status': 'show_zakaz',  "q": value, "id": id} );	
	
}
