 $(document).ready(function(){
	$('div.info_action_nojs').hide();
	
	function sld(s_header,s_block) {
	$(s_block).hide();
    $(s_header).click(function () {
     if ($(s_block).is(":hidden")) {
        $(s_block).show("slow");
        $(s_header).css("color","#428731");
      } else {
        $(s_block).slideUp();
        $(s_header).css("color","#05a9cc");
      }
    });
  }
  
	
	sld("l","#k");
	
});


function str_replace ( search, replace, subject ) {    // Replace all occurrences of the search string with the replacement string
    // 
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
 
    if(!(replace instanceof Array)){
        replace=new Array(replace);
        if(search instanceof Array){//If search    is an array and replace    is a string, then this replacement string is used for every value of search
            while(search.length>replace.length){
                replace[replace.length]=replace[0];
            }
        }
    }
 
    if(!(search instanceof Array))search=new Array(search);
    while(search.length>replace.length){//If replace    has fewer values than search , then an empty string is used for the rest of replacement values
        replace[replace.length]='';
    }
 
    if(subject instanceof Array){//If subject is an array, then the search and replace is performed with every entry of subject , and the return value is an array as well.
        for(k in subject){
            subject[k]=str_replace(search,replace,subject[k]);
        }
        return subject;
    }
 
    for(var k=0; k<search.length; k++){
        var i = subject.indexOf(search[k]);
        while(i>-1){
            subject = subject.replace(search[k], replace[k]);
            i = subject.indexOf(search[k],i);
        }
    }
 
    return subject;
 
}

//склонение окончаний
 function declension(num, expressions) { 
			var result;
			count = num % 100; 
			if (count >= 5 && count <= 20) { 
				result = expressions['2']; 
			} else { 
				count = count % 10; 
				if (count == 1) { 
					result = expressions['0']; 
				} else if (count >= 2 && count <= 4) { 
					result = expressions['1']; 
				} else { 
					result = expressions['2']; 
				} 
			} 
			return result; 
		}

//пробелы в цифрах		
//выводим стоимость правильно в инпуте
function setCost(value) {
		var val = '' + value;
		if (val.length == 1 || val.length == 2 || val.length == 3 || val.length == 4) {
			rval = val;
		}
		if (val.length == 5) {
			back = val.substr(2);
			front = val.substr(0,2);
			rval = front + " " + back;
		}
		if (val.length == 6) {
			back = val.substr(3);
			front = val.substr(0,3);
			rval = front + " " + back;
		}
		if (val.length == 7) {
			front = val.substr(0,1);
			midl = val.substr(1,3);
			back = val.substr(4);
			rval = front + " " + midl + " " + back;
		}
		if (val.length == 8) {
			front = val.substr(0,2);
			midl = val.substr(2,3);
			back = val.substr(5);
			rval = front + " " + midl + " " + back;
		}
			return rval;
}
	
	

//добавить товар в корзину на странице каталоаг
function addGood(type,element) {
		$.post("/classes/modules/pl/ajax.php", { id: element, type: type }, function(data){
			if (data == '1') {
				var count = $('div.cart span.count_good').html();
				
				$('div.info_action_nojs').removeClass('info_action_err').addClass('info_action').text('Товар успешно добавлен в корзину').fadeIn("fast").fadeOut(3000,"slow");
				count = parseInt(count)+1;
				$('div.cart span.count_good').html(count);
				$('div.cart span.ngood').html(declension(count,new Array('товар','товара','товаров')));
				//
				if (type == 'b')
					var price = str_replace( " ", "", $('div.element_'+element+' span.b_'+element+' span').text());
				else
					var price = str_replace( " ", "", $('div.element_'+element+' span.s_'+element+' span').text());
				var sum = str_replace( " ", "", $('div.cart span.sum').text());
				sum = parseInt(sum) + parseInt(price);
				//alert(sum);
				
				$('div.cart span.sum').html(setCost(sum));
				$('div.cart span.orub').html(declension(sum,new Array('рубль','рубля','рублей')));
				
				
			}
			else {
				$('div.info_action_nojs').removeClass('info_action').addClass('info_action_err').text('Ошибка добавления товара').fadeIn("fast").fadeOut(3000,"slow");
			}
				
		});
	
	}
	
function plusGood(order_id) {
	var count = parseInt($('span.count_'+order_id).text());
	$.post("/classes/modules/pl/ajax.php", { order_id: order_id, action: 'plus' }, function(data){
			if (data == '1') {
			//	alert('Аякс отработал хорошо');
				setNewSum(order_id, count, 'plus');
			}
			else {
				alert('Ошибка увеличения количества товара');
			}
		});
}

function minusGood(order_id) {
	var count = parseInt($('span.count_'+order_id).text());
	$.post("/classes/modules/pl/ajax.php", { order_id: order_id, action: 'minus' }, function(data){
			if (data == '1') {
			//	alert('Аякс отработал хорошо');
				setNewSum(order_id, count, 'minus');
			}
			else {
				alert('Ошибка уменьшения количества товара');
			}
		});
}

function delGood(order_id) {
	if (window.confirm("Уверены, что хотите удалить товар из списка заказа?")) { 
		$.post("/classes/modules/pl/ajax.php", { order_id: order_id, action: 'del' }, function(data){
			if (data == '1') {
				
				setNewSum(order_id, 0, 'del');
			}
			else {
				alert('Ошибка удаления товара');
			}
		});	
	}
}

function setNewSum(order_id, count, action) {
	if (action == 'plus') {
		var price = parseInt(str_replace( " ", "", $('td.sum_'+order_id).text()));
		price = price / count;
		var newcount = count + 1;
		if (newcount == 2)
			$('span.minus'+order_id).css("visibility","visible");
		$('span.count_'+order_id).html(newcount);
		
		$('td.sum_'+order_id).html(setCost(newcount * price));
		var allsum = parseInt(str_replace( " ", "", $('span.allsum').text()));
		$('span.allsum').html(setCost(allsum + price));
		//$('span.rub').html(declension(allsum + price,new Array('рубль','рубля','рублей')));
	}
	else if (action == 'minus') {
			var price = parseInt(str_replace( " ", "", $('td.sum_'+order_id).text()));
			var oneprice = price / count;
			var newcount = count - 1;
			if (newcount == 1)
				$('span.minus'+order_id).css("visibility","hidden");
			$('span.count_'+order_id).html(newcount);
			
			$('td.sum_'+order_id).html(setCost(price - oneprice));
			var allsum = parseInt(str_replace( " ", "", $('span.allsum').text()));
			$('span.allsum').html(setCost(allsum - oneprice));
			//$('span.rub').html(declension(allsum - price,new Array('рубль','рубля','рублей')));
	}
	else if (action == 'del') {
		var price = parseInt(str_replace( " ", "", $('td.sum_'+order_id).text()));
			var allsum = parseInt(str_replace( " ", "", $('span.allsum').text()));
			$('span.allsum').html(setCost(allsum - price));
			$('tr.good_'+order_id).empty();
		//	$("table.order_table tr:nth-child(odd)").addClass("odd");
		

			//$('span.rub').html(declension(allsum - price,new Array('рубль','рубля','рублей')));
	}
	
	
	else {
		alert('не плюс');
	}
}








