window.alert = function(text){
    $('productAddedDivSpan').setOpacity(0.8);
    $('productAddedDivSpan').update(text);
    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 + 20 + "px",
            right: "20px"
        });
    }
    $('productAddedDivSpan').show();
}

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');
    
}

var hideProductAddedDivChecker;

function viewCart(){
    var myAjax = 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'){

                $('productCartRow_'+r.request.parameters.id).remove();
                if ($$('#cartProductsTable tbody tr').length == 0){
                    alert("Корзина очищена");
                    $('cartContentDiv').hide();
                }else{
                    alert("Товар удалён из корзины");
                }
                
                
                checkCartInfo(JSONobj);
                if ($('productCountVolumeSpan_'+id))
                $('productCountVolumeSpan_'+id).update(0);
                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);
        		$('productCountVolumeSpan_'+JSONobj.currentProduct.id).update(JSONobj.currentProduct.count);
        		$('productCountVolume_'+JSONobj.currentProduct.id).value="";
                
                alert("Товар добавлен в корзину");
                
                updateCartValues();
            }
        	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);
		
		$('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 addAllProductsToCart(id){
	$$('#productsTable_'+id+' tbody input').each(function (el){
		if (/^\d+$/.match($F(el)) && $F(el)!=0){
			var id = el.id.replace("productCountVolume_","");
		    new Ajax.Request('/ajax.php',{
		        method: 'post',
		        parameters: {
		            act: 'addToCart',
		            id: id,
		            count: $F(el)
		        }
		    });
    		$('productCountVolumeSpan_'+id).update($F(el));
    		$('productCountVolume_'+id).value="";
		}
	});
	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);
                });
			}
		}
    });
}

function viewProduct(id){

    new Ajax.Updater(
        {success: 'cartContentDiv'},
        "/ajax.php",{
        	method: 'post',
            parameters: {
                id: id,
                act: 'viewProduct'
          },
        onSuccess: function (r){
            if (Prototype.Browser.IE){
                var offset = document.viewport.getScrollOffsets();
                $('cartContentDiv').setStyle({
                    position: 'absolute',
                    top: offset.top + 400 + "px"
                });
            }
            $('cartContentDiv').show();
        }
	});
}

/*
document.observe("DOMContentLoaded", function() {
    $$('.addToCartIcon').each(function (el){
        //el.title="Добавить в корзину";
        //el.observe('click',function(){addToCart(el.id.replace(el.className+"_",""))});
    });

    $$('.addAllProductsSpan').each(function(el){
		el.observe('click',function(){addAllProductsToCart(el.id.replace(el.className+"_",""))});
	});
});*/