var amount, stuff_txt='', stuff_num='', cart_amount_descr, i, tmp='', article_images='';
var divider='\n------'; 
var dga	= '\t'; 
var dgs	= '\n'; 
var good = new Array();
var obj_counter = 'span.big'
var table = '';
debug=0;

$(document).ready(function(){

	debug==1 ? console.log($(obj_counter)) : '';

	$(obj_counter).each(function() {		// set amount to navigation menu after page load
		$(this).text(count_goods());
	});

	var loc=document.location.toString(); // get current location
	if (loc.indexOf('cart') != -1) {
		insert_goods();	// set goods text in fields
		recount();		// пересчет суммы товаров
	}

	// show additional contact info if checkbox was checked (before page refresh too)
	// show/hide extended div

	$("input#dostavka").click(function(){ 
		if ($("input#dostavka").is(":checked")) {
			$("div#contacts_extended").slideDown();
		} else {
			$("div#contacts_extended").slideUp();
		}
	});


	//if sending was successfull - clear cookies
	if ($("div#ok").length==1) {
		$.cookie('goods','0',{path:'/',expires:-1});
		$(obj_counter).each(function() {		// set amount of goods to zero
			$(this).text(0);
		});
	}

	// add pointer to cursor via css to link without href attr
	$("table.cart tbody tr").hover(
		function () {
			$(this).addClass("hover");
		}, 
		function () {
			$(this).removeClass("hover");
		}
	);

	// при изменении количества - пересчитываем цены
	$("table.cart input").keyup( recount );


});//$(document).ready(function(){



function add_to_cart(article_id,good_id) {
	good['article_id'] = article_id;	// set article's id (=article_id)
	good['good_id'] = good_id;			// set good's id 	(=good_id)
	
	// get old cookie
	if ($.cookie("goods")) {
		stuff_txt=$.cookie("goods")+';'+good['article_id']+':'+good['good_id'];
	} else {
		stuff_txt=good['article_id']+':'+good['good_id']
	}
	
	// make strings to store in cookie
	var good_string ='';
	$.cookie("goods",stuff_txt,{path:'/',expires:1});	// create cookie for this stuff
	
	// count amount of goods
	$(obj_counter).each(function() {
		$(this).text(count_goods());
	});
	
	image_fly(article_id,good_id);
	$.gritter.add({
		title:'Товар добавлен в корзину!',
		text: 'Ваша корзина пополнилась ещё одним товаром. Теперь в ней <b>' + count_goods() + '</b> шт. <br /><br /> <a href="http://zimaleto.by/index.php?s=cart">Перейти к оформлению</a>',
		time: '3000'
	});
	gritter_center();
}

function count_goods() {
	if ($.cookie("goods")) {
		amount = $.trim($.cookie("goods")).split(";").length;
		returner = amount;
	} else {
		returner = 0;
	}
	
	if (amount > 0)
		$(".cartimg a").animate({opacity: 1}, 400)
	else
		$(".cartimg a").animate({opacity: 0.5}, 400)

	return returner;
}

// delete last new line symbol
function remove_last_char(str,char) {
	last_char=str.substring(str.length-1);
	if (last_char==char) str=str.substr(0,str.length-1);
	return str;
}

// create text list of goods for insertion to textarea to send via email
function insert_goods() {
	output='';
	if ($.cookie("goods")) { //check if there is goods in cart
		// nothing to do :)
	} else {
		$("#order_list").val(''); 		// clear good's fields fo safety
		$("#order_list_orig").val('');	
		return 0;
	}

	debug==1 ? console.log(good) : '';

	table = $("table.cart tbody tr");
	output_user = '';
	output_orig = '';
	for (i=0;i<table.length;i++) {
		var type 	= $(table).eq(i).find(".good_type").text();
		var id 		= $(table).eq(i).find(".good_id").text();
		var title 	= $(table).eq(i).find(".title_id").text();
		var size 	= $(table).eq(i).find(".size_id").text();
		var qty 	= $(table).eq(i).find(".qty_id_input").val();
		var qty_prefix = type=='tire' ? ' шт. = ' : ' компл. = ';
		var price 	= $(table).eq(i).find(".price_id").text();
		var sub_total=$(table).eq(i).find(".sub_total").text();

		output_user	+=	"Название: "		+ title +
						"\nРазмер: "		+ size 	+ 
						"\nЦена: "			+ price + 
						" × "				+ qty 	+ 
						qty_prefix 			+ sub_total 	+
						"\nКоличество: "	+ qty 	+ "\n----\n";
					
		output_orig	+=	"\nID: " 		+ id 	+
						"\nРазмер: "	+ size 	+ 
						"\nЦена: "		+ price + 
						" × "			+ qty 	+ 
						qty_prefix		+ sub_total 	+
						"\nЦена: "		+ price + "\n----\n";
	}
	// get total price and add to cart text
	total_price = $(".total_price").text();
	output_user	+= "\n=====\nИтого: "+ total_price;
	output_orig	+= "\n=====\nИтого: "+ total_price;
	
	debug==1 ? console.log(output_orig) : '';
	$("#order_list").val(output_user); 		// add goods list to textarea with ability to change...
	$("#order_list_orig").val(output_orig);	// ...and to hidden textarea to void user changes
}

// пересчитываем значения в корзине при смене количества
function recount() {
	total = 0;
	table.each(function(){
		qty 	= $(this).find(".qty_id_input").val();
		price 	= $(this).find(".price_id").text();
		sub_total = qty * price;
		total += sub_total;
		// вписываем новую цену
		$(this).find(".sub_total").text(sub_total);
	});
	$(".total_price").text(total);
	insert_goods();
}

function good_delete(id) {
	good=$.cookie("goods").split(';');		// split string of goods to array
	good.splice(id,1);						// delete required element from array
	goods_str=good.join(';'); 				// join all 'good' into one string 'goods' before writing the cookie
	
	$.cookie("goods", goods_str,{path:'/',expires:1}); 		// write cookie
	
	$(".cart tbody tr").eq(id).fadeOut(500);				// hide row with delted good

	$(obj_counter).each(function() {						// set amount to navigation menu after deletion
		$(this).text(count_goods());
	});

	$.gritter.add({
		title: 	'Товар удалён. Перезагрузка списка…',
		text: 	'Пожалуйста, подождите…',
		sticky: true
	});
	gritter_center();
	window.location.reload();								// reload document after deletion
}
 
// position gritter notice in the center of screen
function gritter_center() {
	var div= $("#gritter-notice-wrapper");
	div.css({
		top:  ( $(window).height() - div.height() )/2  + 'px',
		left: ( $(window).width()  - div.width()  )/2  + 'px'
	});
};


function image_fly(article_id,good_id) {
	// найдем кнопку, которую нажали
	button = $( "input[onclick*='" + article_id + "," + good_id + "']" );
	// найдем картинку шины
	img = button.closest(".entry-full").find("img")
	
	var productX 	= $(img).offset().left;
	var productY 	= $(img).offset().top;

	var basketX 	= $("#cart").offset().left;
	var basketY 	= $("#cart").offset().top;
	
	var gotoX 		= basketX - productX;
	var gotoY 		= basketY - productY;
	
	var newImageWidth 	= $(img).width()  / 3;
	var newImageHeight	= $(img).height() / 3;
	
	$(img)
		.clone()
		.insertBefore(img)
		.css({'position' : 'absolute'})
		.animate({opacity: 0.5}, 100 )
		.animate({opacity: 0.2, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight}, 1200, function() {
			$(this).remove();
	});	
}
