/**
* добавление товара в корзину
*/
function add_to_basket(id){
	$.ajax({
		type:'POST',
		url:'/basket/oparations_basket.php',
		data:({
			act:'add_to_basket',
			tovar_id:id
		}),		
		success:function() {
      window.scrollTo(0,0);
			continue_market();
		}
	});

	/*$("#basket_update_question").load("/basket/oparations_basket.php", { act:"add_to_basket", tovar_id: id },
															function(responseText, statusText, xhr){
																$("#basket_update_question").animate({ opacity: 'show' }, "fast");
															});*/
}

/**
* возвращение к покупкам 
*/
function continue_market(){
	$("#basket_update_question").animate({ opacity: 'hide' }, "fast");
	$("#basket").load("/basket/oparations_basket.php", {act:"update_basket_info"});
}
/**
* обновление блока "корзина"
*/
function update_basket_info(){
	$("#basket").load("/basket/oparations_basket.php", {act:"update_basket_info"});
}
/**
* обновление корзины (на лету)
*/
function refresh_basket(){
	var str = "";
	var e=document.getElementsByClassName("cc");
	for(var i=0;i<e.length;i++){
		str = str + e[i].name+"=>"+e[i].value+";";
	}
	var to_delete = "";
	var e=document.getElementsByClassName("item_to_delete");
	for(var i=0;i<e.length;i++){
		if (e[i].checked)
			to_delete = to_delete + e[i].name+";";
	}
	
	$.ajax ({
		type:'POST',
		url:'/basket/oparations_basket.php',
		data:({
			act:'update_basket',
			str: str,
			to_delete: to_delete
		}),
		success:function(msg){
			window.location.reload();
		}
	});
//	$("#basket_main_div").load("/basket/oparations_basket.php", {  act:"update_basket",str: str, to_delete: to_delete});
}

/**
* проверка всех введнных параметров для активации кнопки "купить" (на лету)
*/
function check_info_basket() {
	var email = $('#email').attr('value');
	var name = $('#basket_test_name').attr('value');
	var phone = $('#basket_phone').attr('value');
	var address = $('#basket_address').attr('value');
	var capcha = $('#capcha').attr('value');
	$.ajax({
		type:'POST',
		url:'/basket/form_check.php',
		data:({
			act:'check_capcha2',
			capcha:capcha
		}),
		success:function(msg){
			if (msg == 0) {
				$('#buybasketbutton').attr('disabled',1);
			} else {
				$.ajax({
					type:'POST',
					url:'/basket/form_check.php',
					data:({
						act:'check_email2',
						email:email
					}),
					success:function(msg){
						if (msg == 0) {
							$('#buybasketbutton').attr('disabled',1);
						} else {
							if ((name == '')||(name == undefined)) {
								$('#buybasketbutton').attr('disabled',1);
							} else {
								$.ajax({
									type:'POST',
									url:'/basket/form_check.php',
									data:({
										act:'check_name2',
										name:name
									}),
									success:function(msg){
										if (msg == 0) {
											$('#buybasketbutton').attr('disabled',1);
										} else {											
											if ((phone == '')||(phone == undefined)) {
												$('#buybasketbutton').attr('disabled',1);
											} else {										
												$.ajax({
													type:'POST',
													url:'/basket/form_check.php',
													data:({
														act:'check_phone2',
														phone:phone
													}),
													success:function(msg){	
														if (msg == 0) {
															$('#buybasketbutton').attr('disabled',1);
														} else {					
															if ((address == '')||(address == undefined)) {
																$('#buybasketbutton').attr('disabled',1);
															} else {
																$.ajax({
																	type:'POST',
																	url:'/basket/form_check.php',
																	data:({
																		act:'check_address2',
																		address:address
																	}),
																	success:function(msg){
																		if (msg == 0) {
																			$('#buybasketbutton').attr('disabled',1);
																		} else {
																			$('#buybasketbutton').attr('disabled',0);
																		}
																	}
																});
															}
														}
													}
												});
											}
										}
									}
								});
							}
						}
					}
				});
			}
		}
	});
}

/**
* вызов валидации емейла (на лету)
*/
function check_email(email){
	$("#emailcheck").load("/basket/form_check.php", {  act:"check_email",email: email});
	check_info_basket();
}
/**
* вызов валидации имени (на лету)
*/
function check_name(name){
	$("#namecheck").load("/basket/form_check.php", {  act:"check_name",name: name});
	check_info_basket();
}
/**
* вызов валидации телефона (на лету)
*/
function check_phone(phone){
	$("#phonecheck").load("/basket/form_check.php", {  act:"check_phone",phone: phone});
	check_info_basket();
}
/**
* вызов валидации адреса (на лету)
*/
function check_address(address){
	$("#addresscheck").load("/basket/form_check.php", {  act:"check_address",address: address});
	check_info_basket();
}

/**
* вызов валидации кода (на лету)
*/
function check_capcha(capcha){
	$("#capchacheck").load("/basket/form_check.php", {  act:"check_capcha",capcha: capcha});
/*	$.ajax({
		type:'POST',
		url:'/basket/form_check.php',
		data:({
			act:'check_capcha2',
			capcha:capcha
		}),
		success:function(msg){
			if (msg == 0) {
				$('#buybasketbutton').attr('disabled',1);
			} else {
				$('#buybasketbutton').attr('disabled',0);
			}
		}
	});*/
	check_info_basket();
}

/**
* вызов обновления кода (на лету)
*/
function refresh_capcha(){
	$("#capcha_image_wrapper").load("/basket/inc/capcha.php");
	check_capcha('');
}

/**
* проверка валидности формы, сабмит формы в случае успешной валидаци
*/
function check_validation(){
	var count = 0;
	var e=document.getElementsByClassName("to_confirm");
	for(var i=0;i<e.length;i++){
		if (e[i].value == "1")
			count++;
	}
	
	var tovar_ex = 0;
	var e1=document.getElementsByClassName("to_confirm_t"); 
	
	//alert(e1[0].value);
	
	if(e1[0] != undefined){
		if(e1[0].value != undefined){
			tovar_ex = 1;
		}
	}
	/**
	* count - показатель того что все 5ть полей(обязательных) заполнены
	* tovar_ex - показатель наличия товара в корзине
	*/
	if ((count == 5)&&(tovar_ex == 1))
	{
		document.getElementById("order_form").submit();
	}
	else{
		if((count == 5)&&(tovar_ex != 1)){
			$("#message_box").html("Для завершения покупки необходимо наличие товара");
		}
		else if((count < 5)&&(tovar_ex != 1)){
			$("#message_box").html("Для завершения покупки необходимо иметь товар в корзине и правильно заполнить форму заказа");
		}
		else if((count < 5)&&(tovar_ex == 1)){
			$("#message_box").html("Для завершения покупки необходимо правильно заполнить форму заказа");
		}
		else{
			$("#message_box").html("11");
		}
	}
}

/**
* очистка корзины (из страницы корзины)
*/
function clear_basket(){
	$.ajax({
		type:'POST',
		url:'/basket/oparations_basket.php',
		data:({
			act:'clear_basket'
		}),
		success:function(msg){
			window.location.reload();
		}
	});
/*	if($("#basket_main_div")){
		$("#basket_main_div").load("/basket/oparations_basket.php", {act:"clear_basket"});
	}
	if($("#basket")){
		$("#basket").load("/basket/oparations_basket.php", {act:"update_basket_info"});
	}*/
}

/**
* очистка корзины (из блока "корзина")
*/
function clear_basket_n(){
	if($("#basket")){
		$("#basket").load("/basket/oparations_basket.php", {act:"clear_basket_n"});
		$("#basket").load("/basket/oparations_basket.php", {act:"update_basket_info"});
	}
}

function refresh_captcha() {	
	$.ajax({
		url: '/captcha/index.php',
		success: function(msg) {
			$('#captchaplace').html('<img border=0 src="/captcha'+msg+'" />');
		}
	});	
}
/*Добавление отзыва*/
function add_opinion (name,opinion,capcha,tovar_id) {
	$.ajax({
		type:'POST',
		url:'/!virtuoz/ext/data/check_capcha.php',
		data:({
			capcha:capcha
		}),
		success:function(msg) {
			if (msg == 0) {
				alert('Неверно введено изображение с картинки');
			} else {
				$.ajax({
					type:'POST',
					url:'/!virtuoz/ext/data/add_opinion_for_item.php',
					data:({
						name:name,
						content:opinion,
						capcha:capcha,
						tovar_id:tovar_id
					}),
					success:function(msg) {
						$('#_OPIN_name').attr('value','');
						$('#_OPIN_content').attr('value','');
						$('#_OPIN_capcha').attr('value','');
						alert(msg);
						window.location.reload();
					}
				});
			}
		}
	});
}
function logout() {
	$.ajax({
		url : '/!virtuoz/ext/data/logout.php',
		success: function(msg) {
			deleteCookie('userhash', '/', '');
			deleteCookie('userid', '/', '');
			window.location.reload();
			return true;
		}
	});
}

function test_capcha(code) {
  $.ajax({
    type : 'POST',
    url : '/!virtuoz/ext/data/check_capcha.php',
    data :  ({
      capcha : code
    }),
    success : function (msg) {
      if (msg==1) {
        $('#sendletterformsubmit').attr('disabled',0);
      } else {
        $('#sendletterformsubmit').attr('disabled',1);
      }
    }
  });
}
$(document).ready(function(){

	$("#basket").load("/basket/oparations_basket.php", {act:"update_basket_info"});
	$('#order_form').ajaxForm(function(msg){alert(msg);window.location.reload();});
	$('#sendSV').ajaxForm(function(msg){alert(msg);window.location.reload();});
	$('#LOGIN_AUTH').ajaxForm(function(msg){
			if (msg == 'ok') {
				window.location.reload();
			} else {
				alert(msg);
			}
		}
	);
	
	$.ajax({
		url: '/captcha/index.php',
		success: function(msg) {
			$('#captchaplace').html('<img border=0 src="/captcha'+msg+'" />');
		}
	});
	
	/*var location = window.location.toString();
	var strpos = location.indexOf('aldiga.ru');
	if (strpos) {
		var nextdir = location.substr(strpos+9);
		if ((nextdir == '/') || (nextdir == '')) {
		} else {
      $('#header').css('width',$('body').attr('offsetWidth')-150+'px');
			//alert($('#header').attr('offsetLeft'));
		}
	}*/
});

