var obj;
var idInt=Array;
var loading=' <img id="loader" src="/images/loading.gif" />';

function updateBacket(obj){
	kol=$(obj).val();
	if (kol==0){
	     alert('Укажите количество больше 0');
	     $(obj).val(1);
	} else if (kol<0){
	     kol=0;
	     $(obj).val(1);
	}
	if (kol>0){
		id=$(obj).attr('id');
		id=id.replace('kol','');
		$('#sum'+id).html(loading);
		//$('#forresult').append(id+' '+kol+' | ');
		JsHttpRequest.query(
		    '/cart/?todo=edit&id='+id+'&kol='+kol,
		    {},
		    function(result, errors){
			if (result["all_kol"]){
				$('#kol'+id).val(result["kol"]);
				$('#sum'+id).text(result["sum"]);
				updateTotalValues(result);
			}
			//if (result['err']=='') alert('Товар успешно добавлен');
		    },
		    true  // do not disable caching
		);
	}
}

$(document).ready(function(){
	var prods=$('.catal, .cat');
	var obj='.cat_img,.catal_img';
	var fadeTo=0.7;
	//$(obj,prods).fadeTo(100,fadeTo);
	//$(prods).hover(function(){ $(obj,this).stop(true,true).fadeTo(200,1);},function(){ $(obj,this).fadeTo(300,fadeTo);});

	$('a[prod]').click(function(){
		//$('.catal:has(a[prod='+$(this).attr('prod')+'])').animate({opacity: 0.5},2000);
		JsHttpRequest.query(
		    '/cart/?todo=put&id='+$(this).attr('prod'),
		    {},
		    function(result, errors){
			if (result["err"]){
				alert(result["err"]);
			} else if (result["all_kol"]){
				alert('Товар "'+result['name']+'" успешно добавлен в корзину');
				updateTotalValues(result);
				$('.catal a[prod='+$(this).attr('prod')+']').css('border','#cc0000');
			}
		    },
		    true  // do not disable caching
		);
	});

	$('input[name=prod_kol]').keyup(function(){ 
		obj1=$(this);
		clearTimeout(idInt[obj1.attr('id')]);
		if (obj1.val()) idInt[obj1.attr('id')]=setTimeout("updateBacket(obj1)",500);
		//$('#forresult').append(obj.attr('id')+' | ');
	});

	$('a[id^=del]').click(function(){
		if (confirm('Вы хотите удалить этот товар?')){
			id=$(this).attr('id').replace('del','');
			JsHttpRequest.query(
			    '/cart/?todo=del&id='+id,
			    {},
			    function(result, errors){
				if (result["all_kol"]){
					$('#tr'+id).fadeOut(500);
					$('#trr'+id).fadeOut(500,function(){
						updateTotalValues(result);
						if (result["all_kol"]==0){
							$('#topBacket').html('<b>Мои заказы:</b> (Отсутствуют)');
							$('#content table').hide();
							$('#content h1').after('Корзина пуста');
						}
					});
				}
			    },
			    true  // do not disable caching
			);
		}
	});
	
	var objInput;
	var myForm=$('input:visible, textarea, select');
	myForm.focus(function(){
		$(this).css('border','1px solid #000');
	}).blur(function(){
		if ($(this).val().length<3 && $(this).attr('rel')=='req'){
			if ($('img#'+$(this).attr('name')).length==0){
				$(this).after(' <img id="'+$(this).attr('name')+'" src="/images/del.jpg" alt="Введите значение" />');
			}
			$(this).css('border','1px solid #c00');
		} else {
			if ($(this).attr('name')=='email'){
				$('#'+$(this).attr('name')).remove();
				$(this).after(loading);
				objInput=$(this);
				JsHttpRequest.query(
				    '/cart/?todo=check_email&email='+$(objInput).val(),
				    {},
				    function(result, errors){
					$('#loader').remove();
					if (result["ok"]==0){
						if ($('img#'+$(objInput).attr('name')).length==0){
							$(objInput).after('<span id="'+$(objInput).attr('name')+'"><img src="/images/del.jpg" title="Введите значение" /><br /><small>Введите верный e-mail</small></div>');
						}
						$(objInput).css('border','1px solid #c00');
					} else {
						$('img#'+$(objInput).attr('name')).remove();
						$(objInput).css('border','1px solid #999');
					}
				   },false
				);
				
			} else {
				$('img#'+$(this).attr('name')).remove();
				$(this).css('border','1px solid #999');
			}
		}
	});

	$('a#sendOrder').click(function(){
		sendForm=true;
		toEl='';
		myForm.each(function(){
			if ($(this).val()=='' && $(this).attr('rel')=='req'){
				sendForm=false;
				if (!toEl) toEl=$(this);
			}
		});
		if (sendForm){
			if ($(this).attr('send')!='send'){
				$(this).attr('send','send').fadeTo(300,0.5);
				$('#bform').submit();
			} else alert('Пожалуйста подождите, заказ уже отправляется');
		} else {
			alert('Заполните все необходимые поля');
			if (toEl) $(toEl).focus();
		}
	});
});

function updateTotalValues(result){
	$('#topBacket').html('<a href="/esm/"><b>Мои заказы:</b></a> <span id="red">'+result['all_kol']+'</span> шт на сумму: <span id="red">'+result['all_sum']+'</span> р.</a>');
	$('#itogo').text(result["all_sum"]);
}


