var hideProductAddedDivChecker;
window.alert = function(text){
    $('productAddedDivSpan')
					.setOpacity(0.8)
					.update(text)
					.show();

    if (null != hideProductAddedDivChecker) {hideProductAddedDivChecker.stop(); hideProductAddedDivChecker = null;};
    hideProductAddedDivChecker = new PeriodicalExecuter(function(){$('productAddedDivSpan').hide(); hideProductAddedDivChecker.stop(); hideProductAddedDivChecker = null}, 3);
    
    if (Prototype.Browser.IE){
        var offset = document.viewport.getScrollOffsets();
        $('productAddedDivSpan').setStyle({
            position: 'absolute',
            top: offset.top + 40 + "px",
            right: "20px"
        });
    }
}

function toggleLeftMenu(id){
    $('categoriesLinks_'+id).toggle();
    
    $('categoriesLinkItem_'+id).removeClassName('expandedCategory');
    $('categoriesLinkItem_'+id).removeClassName('collapsedCategory');
    
    if ($('categoriesLinks_'+id).visible())
        $('categoriesLinkItem_'+id).addClassName('expandedCategory');
    else
        $('categoriesLinkItem_'+id).addClassName('collapsedCategory');
    
}


//////////// корзина


function viewCart(){

	new Ajax.Updater(
  	{success: 'cartContentDiv'},
  	"/ajax.php",{
  		method: 'post',
      parameters: {
        act: 'cartContent'
      },
    onComplete: function (r){
    
        if (Prototype.Browser.IE){
            var offset = document.viewport.getScrollOffsets();
            $('cartContentDiv').setStyle({
                position: 'absolute',
                top: offset.top + 400 + "px"
            });
        }
    
        $('cartContentDiv').show();
        
        $$('.deleteFromCartIcon').each(function (el){
            el.title="Удалить из корзины";
            el.observe('click',function(){deleteFromCart(el.id.replace(el.className+"_",""))});
        });
        
        $$('.recalculateProductCountIcon').each(function (el){
            el.title="Обновить количество";
            el.observe('click',function(){recalculateCartProductCount(el.id.replace(el.className+"_",""))});
        });
        
        $$('.productCartCountVolume').each(function (el){
            el.observe('keypress',function(event){if (event.keyCode == 13) recalculateCartProductCount(el.id.replace(el.className+"_",""))});
        });
    }
	});
}

function recalculateCartProductCount(id){

	if (!/^\d+$/.match($F('productCartCountVolume_'+id)) ){
		alert("Пожалуйста, укажите правильное количество товара");
		return;
	}
	
	if ($F('productCartCountVolume_'+id) == 0){
		alert("Удалите товар из корзины");
		return;
	}
    
    new Ajax.Request("/ajax.php",{
        method: 'post',
        sanitizeJSON: 'true',
        parameters: {
            act: 'updateCart',
            id: id,
            count: $F('productCartCountVolume_'+id)
        },
        onSuccess: function (r){
            var JSONobj = r.responseJSON;

            if(JSONobj.result && JSONobj.result=='ok'){
                alert("Количество товара обновлено");
                checkCartInfo(JSONobj);
                $('totalProductPrice_'+JSONobj.currentProduct.id).update(JSONobj.currentProduct.price);
                $('cartProductCountVolumeSpan_'+JSONobj.currentProduct.id).update(JSONobj.currentProduct.count);
                if ($('productCountVolumeSpan_'+JSONobj.currentProduct.id))
                $('productCountVolumeSpan_'+JSONobj.currentProduct.id).update(JSONobj.currentProduct.count);
                return;
            }
        }
  	});

}

function deleteFromCart(id){
  new Ajax.Request('/ajax.php',{
        method: 'post',
        sanitizeJSON: 'true',
        parameters: {
            act: 'deleteFromCart',
            id: id
        },
  		onSuccess: function(r){
            var JSONobj = r.responseJSON;
            
            if(JSONobj.result && JSONobj.result=='ok'){
                alert("Товар удалён из корзины");
                $('productCartRow_'+r.request.parameters.id).remove();
                checkCartInfo(JSONobj);
                
				if (JSONobj.total.products == 0){
					$('cartNotExistsDiv').show();
					$('cartExistsDiv').hide();
					$('cartContentDiv').hide();
					alert("Корзина очищена");
				}
				
                return;
            }
  			
            alert("Произошла ошибка при удалении товара. Пожалуйста, попробуйте ещё раз.");
      }
  	});
}

function addToCart(id){

    if (!/^\d+$/.match($F('productCountVolume_'+id)) ){
        alert("Пожалуйста, укажите правильное количество товара");
        return;
    }

    new Ajax.Request('/ajax.php',{
        method: 'post',
        sanitizeJSON: 'true',
        parameters: {
            act: 'addToCart',
            id: id,
            count: $F('productCountVolume_'+id)
        },
    	onSuccess: function(r){
        	var JSONobj = r.responseJSON;
        	if(JSONobj.result=='ok'){
        		checkCartInfo(JSONobj);
                alert("Товар добавлен в корзину");
            }
        	else{
                alert("Произошла ошибка при добавлении товара. Пожалуйста, попробуйте ещё раз.");
            }
        }
    }
    )
}


function updateCartValues(){
    new Ajax.Request("/ajax.php",{
    	method: 'post',
    	sanitizeJSON: 'true',
    	parameters: {
        	act: 'cartInfo'
    	},
    	onSuccess: function (r){
			var JSONobj = r.responseJSON;
			if(JSONobj.result=='ok'){
				checkCartInfo(JSONobj);
			}
		}
  	});
}

function checkCartInfo(JSONobj){

	if (JSONobj.total.products > 0){
		$('totalCartInfo_Volumes').update(JSONobj.total.products);
		$('totalCartInfo_Price').update(JSONobj.total.price);
		
		if ($('totalCartPrice'))
			$('totalCartPrice').update(JSONobj.total.price);
		
		$('cartNotExistsDiv').hide();
		$('cartExistsDiv').show();
	} else {
		$('cartNotExistsDiv').show();
		$('cartExistsDiv').hide();
	}
}



function clearCart(){
    if (!confirm("Вы уверены, что хотите очистить корзину?"))
        return;

    new Ajax.Request("/ajax.php",{
    	method: 'post',
    	sanitizeJSON: 'true',
    	parameters: {
        	act: 'clearCart'
    	},
    	onSuccess: function (r){
			var JSONobj = r.responseJSON;
			if(JSONobj.result=='ok'){
                $$(".productCountVolumeSpans").each(function(el){
                    el.update(0);
                });
                $('cartContentDiv').hide();
                updateCartValues();
                alert("Корзина очищена!");
			}
		}
  	});
}






function confirmOrder(){
    new Ajax.Updater(
  	{success: 'cartContentDiv'},
	"/ajax.php",{
			method: 'post',
			evalScripts: true,
			parameters: {
			    act: 'confirmOrder'
			}
  	});
}

function sendOrder(form){
    if ($F('sendOrderFormName').length < 5){
        alert("Пожалуйста, заполните поле «Имя»");
        return;
    }
    if ($F('sendOrderFormPhone').length < 6){
        alert("Пожалуйста, заполните поле «Телефон»");
        return;
    }
    
    new Ajax.Request('/ajax.php',{
        method: 'post',
        parameters: $('sendOrderForm').serialize(),
        onSuccess: function (r){
			var JSONobj = r.responseJSON;
			if(JSONobj.result=='ok'){
                alert("Ваша заявка принята");
                $('cartContentDiv').hide();
				updateCartValues();
                $$(".productCountVolumeSpans").each(function(el){
                    el.update(0);
                });
			}
		}
    });
}
