function check_cart_empty(){
    var cart_items_count = parseFloat($('#crt').html());
    if (cart_items_count == 0 || cart_items_count < 0){
        document.location = '/index.php?shopping_cart=yes';
    }
}

$(document).ready(function(){

        $('span', $('.faq')).click(function(){
            $(this).parent().children('div').toggle('normal');
            return false;
        });

        $('.wait_to_order', $('#cart2')).click(function(){
            $(this).parent().parent().parent().parent().css("background-color","#feffaf");
            var itemID = $(this).parent().parent().parent().parent().attr('id');
            var tmp = itemID.split('itm');
            itemID = tmp[1];
            var productID = $(this).parent().parent().parent().attr('id');
            tmp = productID.split('prd');
            productID = tmp[1];
            var price = parseFloat(($('#p'+itemID)).html());
            $.get("/index.php", {'wait_to_order': itemID, 'ajx': 1}, function(status){
                var crtrto = parseInt($('#crtrto').html());
                var crtwto = parseInt($('#crtwto').html());
                var crtapd = parseInt($('#crtapd').html());
                if (status == 3){
                    $('#crtwto').html(++crtwto);
                    $('#crtapd').html(--crtapd);
                }else{
                    $('#crtwto').html(++crtwto);
                    $('#crtrto').html(--crtrto);
                }
                update_shopping_cart_info(0, 0, price, 'down');
                $('#ci'+productID).remove();
                $('#itm'+itemID).remove();
                check_cart_empty();
			});
            return false;
        });

        $('.ready_to_order', $('#cart2')).click(function(){
            $(this).parent().parent().parent().parent().css("background-color","#b5ffaf");
            var itemID = $(this).parent().parent().parent().parent().attr('id');
            var productID = $(this).parent().parent().parent().attr('id');
            var tmp = itemID.split('itm');
            itemID = tmp[1];
            tmp = productID.split('prd');
            productID = tmp[1];
            if (itemID == ''){
                itemID = productID;
            }
            var price = parseFloat(($('#p'+itemID)).html());
            $.get("/index.php", {'ready_to_order': itemID, 'ajx': 1}, function(status){
                var crtrto = parseInt($('#crtrto').html());
                var crtwto = parseInt($('#crtwto').html());
                var crtapd = parseInt($('#crtapd').html());
                if (status == 3){
                    $('#crtrto').html(++crtrto);
                    $('#crtapd').html(--crtapd);
                }else{
                    $('#crtrto').html(++crtrto);
                    $('#crtwto').html(--crtwto);
                }

                update_shopping_cart_info(0, 0, price, 'up');
                //$('tr:odd td div', $('#cart2')).removeClass('bgp2','bgp1').addClass('bgp1');
	            //$('tr:even td div', $('#cart2')).removeClass('bgp2','bgp1').addClass('bgp2');
                var name = $('.bgp2,.bgp1 ', $('#prd'+productID)).find('a:eq(0)').html();
                $('#cart_info').append('<a href="/category_alias/product_alias-'+productID+'.html" id="ci'+productID+'"><span>1 x </span>'+name+'</a>');
                //for different ceils
                 if (itemID != productID)
                    $('#itm'+itemID).remove();
                else
                    $('#prd'+productID).parent().remove();
			});
            return false;
        });

        $('.remove', $('#cart2')).click(function(){
            $(this).parent().parent().parent().parent().css("background-color","#ffafaf");
            var itemID = $(this).parent().parent().parent().parent().attr('id');
            var productID = $(this).parent().parent().parent().attr('id');
            var tmp = itemID.split('itm');
            itemID = tmp[1];
            tmp = productID.split('prd');
            productID = tmp[1];
            var price = parseFloat(($('#p'+itemID)).html());
            $.get("/index.php", {'shopping_cart': 'yes', 'remove': itemID, 'ajx': 1}, function(status){
                if (status == 1){
                    var crtwto = parseInt($('#crtwto').html());
                    $('#crtwto').html(--crtwto);
                }else if (status == 3){
                    var crtapd = parseInt($('#crtapd').html());
                    $('#crtapd').html(--crtapd);
                }else if (status == 2){
                    var crtoos = parseInt($('#crtoos').html());
                    $('#crtoos').html(--crtoos);
                }else{
                    var crtrto = parseInt($('#crtrto').html());
                    $('#crtrto').html(--crtrto);
                    update_shopping_cart_info(0, 0, price, 'down');
                }
                $('#ci'+productID).remove();
                $('#itm'+itemID).remove();
                if (status != 2){
                    check_cart_empty();
                }
			});
            return false;
        });

        $('.cremove', $('#cart2')).click(function(){
            $(this).parent().parent().parent().parent().css("background-color","#ffafaf");
            var productID = $(this).parent().parent().parent().attr('id');
            tmp = productID.split('prd');
            productID = tmp[1];
            var price = parseFloat(($('#p'+productID)).html());
            $.get("/index.php", {'shopping_cart': 'yes', 'cremove': productID, 'ajx': 1}, function(status){
                if (status == 2){
                    var crtoos = parseInt($('#crtoos').html());
                    $('#crtoos').html(--crtoos);
                }else if (status == 1){
                    var crtwto = parseInt($('#crtwto').html());
                    $('#crtwto').html(--crtwto);
                }else{
                    var crtrto = parseInt($('#crtrto').html());
                    $('#crtrto').html(--crtrto);
                    update_shopping_cart_info(0, 0, price, 'down');
                }
                $('#ci'+productID).remove();
                $('#prd'+productID).parent().remove();
                check_cart_empty();
			});
            return false;
        });

        var chprevent_default = 0;

        var timeout_id_quant;
        //manual quantity
        $('.quant input', $('#cart2')).keydown(function(e){
            //48-57, 8
            var code = e.keyCode;
            var keys = [8,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105];
            var length = $(this).val().length;
            //if(code != 8 && (code < 48 || code > 57)){

            if(keys.indexOf(code) == -1){
                chprevent_default = 1;
            }else{
                if(length == 3 && code != 8)
                    $(this).val($(this).val().substring(1,3));

                if (!$(this).data("qnt"))
                    $(this).data("qnt", parseInt($(this).val()));

                clearTimeout(timeout_id_quant);
                chprevent_default = 0;

            }
        }).keyup(function(e){
            var code = e.keyCode;
            var keys = [8,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105];
            var length = $(this).val().length;
            var o = $(this);
            //if 0
            if ((code == 48 && length == 1) || length == 0){
                $(this).val($(this).data("qnt"));
            }else if(keys.indexOf(code) != -1){   
                timeout_id_quant = setTimeout(function()
						{
                            var first_value = $(o).data("qnt");
            				var value = parseInt($(o).val());
            				var product_id = $(o).parent().attr('id').split('td');
            				product_id = product_id[1];
                            update_quants(product_id);
            				update_product_price_manual(product_id, first_value, value);
                            $(o).data("qnt", value);
            				return false;
						}, 1000
					);
            }
        }).keypress(function(e){
            if (chprevent_default == 1){
                e.preventDefault();
            }
        })

        $('#cart_switcher').click(function(){
            if (!$('#cart_info').hasClass('open'))
                $('#cart_info').addClass('open').animate({height: 'show'}, 'fast');
            else
                $('#cart_info').removeClass('open').animate({height: 'hide'}, 'fast');
        });

        $('.t_help', $('#content')).mouseover(function(){
            $(this).children('div').fadeIn("fast");
        }).mouseout(function(){
            $(this).children('div').fadeOut("fast");
        });

        $('.t_info', $('#content')).mouseover(function(){
            $(this).children('div').fadeIn("fast");
        }).mouseout(function(){
            $(this).children('div').fadeOut("fast");
        });

		var help_search_show = 0;
		var last_searchstring = '';
		var timeout_id
		$('#search').keyup(function()
			{
				var searchstring = $(this).val();
				if (searchstring.length > 2 && last_searchstring != searchstring) {
					clearTimeout(timeout_id);
					timeout_id = setTimeout(function()
						{
							$.post("/ajax.php", {'help_search_string': searchstring}, function(xml)
								{
									var html = '';
									$(xml).find('p').each(function()
										{
											html += '<a href="/'+lng+$(this).find('href').text()+'">'+$(this).find('name').text()+'</a>';
										}
									);
									$('#help_search').html(html);
									$('p', $('#help_search')).click(function()
										{
											$('#search').val($(this).text());
										}
									);
								}
							);
							last_searchstring = searchstring;
							$('#help_search').fadeIn("fast");
						}, 800
					);
				}
			}
		).mouseover(function() {
				if ($('#search').val() != '' && $('a', $('#help_search')).size() > 0) {
					$('#help_search').stop().css('opacity', 1).css('display', 'block');
					help_search_show = 1;
				}
			}
		).mouseout(function() {
				$('#help_search').fadeOut("fast");
				help_search_show = 0;
			}
		);;

		$("#help_search").mouseout(function()
			{
				if (help_search_show != 2) {
					$(this).fadeOut("fast");
					help_search_show = 0;
				}
			}
		).mouseover(function() {
				$(this).stop().css('display', 'block');
				help_search_show = 1;
			}
		);

		//fix z-index for ie6/7 selects
		if(browserVersion() < 8) {
			$(function()
				{
					var zIndexNumber = 1000;
					$('.slabel,.currency_block,.search').each(function()
						{
							$(this).css('zIndex', zIndexNumber);
							zIndexNumber -= 5;
						}
					);
				}
			);
		}

		/*$('.a3').click(function()
			{
				var obj = document.getElementsByName('did[]');
				var obj2 = document.getElementsByName('did2[]');
				var d = "";
				var s = "";
				for(var i = 0; i<obj.length; i++) {
					if(obj[i].checked)
					{
						d += obj[i].value+",";
						s += obj2[i].value+",";
					}
				}
				document.getElementById('d_ids').value = d;
				document.getElementById('d_ids2').value = s;
				document.getElementById('del_form').submit();
				return false;
			}
		);*/

		//standart selects  countryID zoneID

		$("#stcountryID").change(function()
			{
				var id = $('#stcountryID option:selected').val();
				$.ajax(
					{url: 'ajax.php?country_id='+id,
					type: 'GET',
					datatype: 'xml',
					success: function(xml) {
							var count = $(xml).find('count').text();
							if (count > '1') {
								$('#area_zone').removeClass('inp_3_bg');
								var areazoneclass = $('#area_zone').attr('class');
								if (areazoneclass == 'input') {
									$('#area_zone').removeClass('input').addClass('select');
									$('#area_zone').html('<select class="nosel" name="zone_id" id="stzoneID"></select>');
									$('#area_zone').removeClass('inp_3_bg');
								}else {
									$('#area_zone').html('<select class="nosel" name="zone_id" id="stzoneID"></select>');
								}
								$('#stzoneID option').remove();
                                var html = '';
								$(xml).find('zone').each(function()
									{
										html += '<option value="'+$(this).find('zone_id').text()+'">'+$(this).find('zone_name').text()+'</option>';
									}
								);
                                $('#stzoneID').html(html);
							}else {
								var areazoneclass = $('#area_zone').attr('class');
								if (areazoneclass == 'select') {
									$('#area_zone').removeClass('select').addClass('input');
									$('#area_zone').html();
									$('#area_zone').addClass('inp_3_bg');
									$('#area_zone').html('<input type="text" name="state" class="inp_3" value="">');
								}else {
									$('#area_zone').html();
									$('#area_zone').html('<input type="text" name="state" class="inp_3" value="">');
								}
							}
						}
					}
				);
			}
		);
		//////////////////////////////////shopping cart
		var global_cc = get_current_currency();

		$('.down').click(function()
			{
				var first_value = parseInt($(this).next().val());
				if (first_value > 1) {
					value = first_value - 1;
					$(this).next().val(value);
					var product_id = $(this).parent().attr('id').split('td');
					product_id = product_id[1];
					update_quants(product_id);
					update_product_price(product_id, first_value, value);
				}
				return false;
			}
		);

		$('.up').click(function()
			{
				var first_value = parseInt($(this).prev().val());
				value = first_value + 1;
				$(this).prev().val(value);
				var product_id = $(this).parent().attr('id').split('td');
				product_id = product_id[1];
				update_quants(product_id);
				update_product_price(product_id, first_value, value);
				return false;
			}
		);

		function update_quants(p) {
			var obj = document.getElementsByName('upd[]');
			var it = "";
			var ids = "";
			for(var i = 0; i<obj.length; i++) {
				it += obj[i].value+",";
			}
			$.each(obj, function()
				{
					var tmp = $(this).attr('id').split('it');
					ids += tmp[1]+",";
				}
			);
			$.post("/index.php?shopping_cart=yes&rq=1", {f_ids: ids, f_qty: it});
		}

		function get_current_currency() {
			var cc = document.getElementById('current_currency');
			var _cc = " грн.";
			switch (cc.value) {
				case "2": _cc = "грн.";
					break;
				case "3": _cc = "$";
					break;
				case "4": _cc = "€";
					break;
				case "5": _cc = "руб.";
					break;
				case "6": _cc = "WMZ";
					break;
			}
			return _cc;
		}

		function get_price_with_currency(p) {
			var position = 0;
			switch (global_cc) {
				case 'грн.': position = 0;
					break;
				case '$': position = 1;
					break;
				case '€': position = 1;
					break;
				case 'руб.': position = 0;
					break;
				case 'WMZ': position = 1;
					break;
			}
			if (position == 0) {
				return p + ' ' + global_cc;
			}else {
				return global_cc + ' ' + p;
			}
		}

        function update_product_price_manual(p, f, q) {
			var price = parseFloat($('#p'+p).html().replace(global_cc, ''));
			var new_price = price * q / f;
			var one_price = price / f;
            var fix_price;
            var total_price_with_discount = parseFloat($('#total_price_with_discount').html());
            var crt = parseFloat($('#crt').html());
            var discount = 1;
            var csum;

            if ($('#discount').length) {
				discount = $('#discount').html().replace('%', '');
                discount = (100 - discount) / 100;
                var discount_price = 100 *
                $('#discount_price').html(crt);
			}

			if (f < q){
                fix_price = new_price - price;
                total_price_with_discount += fix_price * discount;
                crt = crt - f + q;
            }else{
                fix_price = price - new_price;
                total_price_with_discount -= fix_price * discount;
                crt = crt - q + f;
            }

            if ($('#discount').length) {
                var discount_price = total_price_with_discount * (1 - discount) / (discount);
                $('#discount_price').html(get_price_with_currency(discount_price.toFixed(2)));
                $('#discount_in_summ').html(get_price_with_currency(discount_price.toFixed(2)));
                $('#total_with_discount').html(get_price_with_currency(total_price_with_discount.toFixed(2)));
                csum = total_price_with_discount+discount_price;
			}else{
                csum = total_price_with_discount;
            }

            $('#total_price_with_discount').html(get_price_with_currency(total_price_with_discount.toFixed(2)));
            $('#csum').html(get_price_with_currency(csum.toFixed(2)));
            $('#crt').html(crt);

			//update
			$('#p'+p).html(get_price_with_currency(new_price.toFixed(2)));
		}

		function update_product_price(p, f, q) {
			var price = parseFloat($('#p'+p).html().replace(global_cc, ''));
			var new_price = price * q / f;
			var one_price = price / f;
			if (f < q)
				update_total_price_with_discount(one_price, 'up');
			else
				update_total_price_with_discount(one_price, 'down');
			//update
			$('#p'+p).html(get_price_with_currency(new_price.toFixed(2)));
		}

		function update_total_price_with_discount(p, d) {
			var total_price_without_discount = parseFloat($('#csum').html().replace(global_cc, ''));

			var total_price_with_discount = parseFloat($('#total_price_with_discount').html().replace(global_cc, ''));
			var discount = 0;
			var discount_price_to_html = '';

			if ($('#discount').length) {
				discount = $('#discount').html().replace('%', '');
			}
			/*
   if (d == 'up')
        total_price_with_discount += p * (100 - discount) / 100;
   else
        total_price_with_discount -= p * (100 - discount) / 100;    */
			if (d == 'up')
				total_price_without_discount += p;
			else
				total_price_without_discount -= p;

			total_price_with_discount = total_price_without_discount * (100 - discount) / 100;

			if ($('#discount').length) {
				discount_price_to_html = get_price_with_currency((total_price_without_discount - total_price_with_discount).toFixed(2));
				$('#discount_price').html(discount_price_to_html);
			}

			$('#total_price_with_discount').html(get_price_with_currency(total_price_with_discount.toFixed(2)))
			update_shopping_cart_info(discount_price_to_html, total_price_with_discount, p, d);
		}

		function update_shopping_cart_info(d, dp, p, dir) {
			var count_products = parseInt($('#crt').html());
			var total_price_without_discount = parseFloat($('#csum').html().replace(global_cc, ''));
			var total_price_without_discount_to_html = ''
			if (dir == 'up') {
				count_products += 1;
				total_price_without_discount += p;
			}else {
				count_products -= 1;
				total_price_without_discount -= p;
			}
			$('#crt').html(count_products);
			total_price_without_discount_to_html = get_price_with_currency(total_price_without_discount.toFixed(2));
			if ($('#discount').length) {
                if (d == 0 && dp == 0){
                    var discount = parseFloat($('#discount').html());
                    var discount_in_price = total_price_without_discount * discount / 100;
    				$('#discount_in_summ').html(get_price_with_currency(discount_in_price.toFixed(2)));
    				$('#total_with_discount').html(get_price_with_currency((total_price_without_discount - discount_in_price).toFixed(2)));
    				$('#csum').html(total_price_without_discount_to_html);
                    if ($('#total_price_with_discount').length){
                        $('#total_price_with_discount').html(get_price_with_currency((total_price_without_discount - discount_in_price).toFixed(2)));
                        $('#discount_price').html(get_price_with_currency(discount_in_price.toFixed(2)));
                    }
                }else{
    				$('#discount_in_summ').html(d);
    				$('#total_with_discount').html(get_price_with_currency(dp.toFixed(2)));
    				$('#csum').html(total_price_without_discount_to_html);
                }
			}else {
                if ($('#total_price_with_discount').length) {
                    $('#total_price_with_discount').html(total_price_without_discount_to_html);
                }
				$('#csum').html(total_price_without_discount_to_html);
			}
		}
		//////////////////////////////////shopping cart

		$(".stars-wrapper2").stars(
			{
			cancelShow: false
			}
		);

		$(".stars-wrapper2 a").click(function()
			{
				var pid = $(this).parent().parent().attr("id").split("p");
				var mark = $(this).html();
				$.post("http://www.audiobooks.com.ua/rating.php", {rate: mark, product_id: pid[1]}, function(data)
					{
						var mark = data;
					}
				);
			}
		);

		$(".stars-wrapperD").stars(
			{
			disabled: "disabled",
			cancelShow: false
			}
		);

		$('#add_comment .submit').click(function()
			{
				document.add_comment.submit();
			}
		);

		$('#current_currency_fake > span').mousedown(function()
			{
				document.ChangeCurrencyForm.submit();
			}
		);

		$(".ozvuch_block").click(function()
			{
				document.location = "/index.php?show_aux_page=187";
			}
		);

		$(".quaranty_block div").click(function()
			{
				document.location = "index.php?show_aux_page=272";
			}
		);

		//shipping form
		$("#shipping_form .b4").click(function()
			{
				if ($(':radio[name="select_shipping_method"]:checked').val() != undefined)
					document.forms.MainForm.submit();
				return false;
			}
		);

		//payment form
		$("#payment_form .b4").click(function()
			{
				if ($(':radio[name="select_payment_method"]:checked').val() != undefined)
					document.forms.MainForm.submit();
				return false;
			}
		);

		//comments form
		$("#comments_form .b4").click(function()
			{
				document.forms.MainForm.submit();
				return false;
			}
		);




		$("input:checkbox").not('.mustshow').css('display', 'none');

		$(".niceCheck").mousedown(
			function() {
				changeCheck($(this));
			}
		);


		$(".niceCheck").each(
			function() {
				changeCheckStart($(this));
			}
		);

	}
).keyboard('ctrl enter', function(){
    if ($.browser.msie){
        var ddd = document.selection.createRange();
        var text = ddd.text;
    }else{
        var text = document.getSelection();
    }
    if (text.length > 0){
        tb_show('test', '/'+lng+'lightbox.php?placeValuesBefore=orphus='+encodeURIComponent(text)+'&TB_iframe=true&height=240&width=450&modal=true', 'null');
    }else{
        alert('Нужно выделить текст');
    }
});

function changeCheck(el)
/*
 функция смены вида и значения чекбокса
 el - span контейнер дял обычного чекбокса
 input - чекбокс
*/
{
	var el = el,
	input = el.find("input").eq(0);
	if(!input.attr("checked")) {
		el.css("background-position", "0 -17px");
		input.attr("checked", true)
	} else {
		el.css("background-position", "0 0");
		input.attr("checked", false)
	}
	return true;
}

function changeCheckStart(el)
/*
 если установлен атрибут checked, меняем вид чекбокса
*/
{
	var el = el,
	input = el.find("input").eq(0);
	if(input.attr("checked")) {
		el.css("background-position", "0 -17px");
	}
	return true;
}