function check_cart_empty(){
    var cart_items_count = parseFloat($('#crt').html());
    if (cart_items_count == 0 || cart_items_count < 0){
        document.location = '/shopping-cart/';
    }
}

$(document).ready(function(){

    var anc = window.location.hash.replace("#","");
    var _tmp = anc.split('A');
    if(_tmp[0] == 'C'){
        if(_tmp[1] > 0){
            _tmp[1] = '' + _tmp[1];
            var offset = $('#CA117').offset();
            $('#content').scrollTop(offset.top);
        }else{
            var offset = $('#C0').offset();
            $('#content').scrollTop(offset.top);
        }
    }

    var seealso_show = 0;
	var last_seealso = '';
	var timeout_id;

    $('#adm_saclose').click(function(){
        //$('#seealso').val('');
        $('#seealso_bl').css({'display': 'none'});
    });

    function add_product_related(o){
        //var m_count = $('.mblock', $('#prelated')).size();
        var m_count = $('input[name=m_count]').val();

        if(m_count < 5){
            var productID = $('input[name=productID]').val();
            var tmp = $(o).parent().attr('id').split('prel');
            var relatedID = tmp[1];

            $.post(www +'ajax_admin.php', {'add_product_related': productID, 'relatedID': relatedID}, function(xml){
                $(o).parent().addClass('g');
                $('input[name=m_count]').val(++m_count);
            });
        }
        return false;
    }

    function del_product_related(o){
        var productID = $('input[name=productID]').val();
        var tmp = $(o).attr('id').split('pdel');
        var relatedID = tmp[1];
        var m_count = $('input[name=m_count]').val();

        $.post(www +'ajax_admin.php', {'del_product_related': productID, 'relatedID': relatedID}, function(xml){
            $('.sa'+relatedID).remove();
            $('input[name=m_count]').val(--m_count);
            return false;
        });
    }

    $('.seealso_del').click(function(){
        del_product_related(this);
    });

	$('#seealso').keyup(function(){
	    var searchstring = $(this).val();
	    if (searchstring.length > 2 && last_seealso != searchstring) {
            var productID = $('input[name=productID]').val();
		    clearTimeout(timeout_id);
			timeout_id = setTimeout(function(){
			    $.post(www +'ajax.php', {'search_seealso': searchstring, 'productID': productID}, function(xml){
				    var html = '';
					$(xml).find('p').each(function(){
                        var rel = $(this).find('rel').text();
					    html += '<div class="bl'+(rel == 1 ? ' g' : '')+'" id="prel'+$(this).find('productID').text()+'"><div class="img"><img src="'+$(this).find('img').text()+'" /></div><a href="/'+lng+$(this).find('href').text()+'">'+$(this).find('name').text()+'</a><span>Издательство(а): </span><b>'+$(this).find('pub').text()+'</b><br /><span>Автор(ы): </span><b>'+$(this).find('authors').text()+'</b><br /><span>Цена: </span><b>'+$(this).find('price').text()+' UAH</b><div class="add">Добавить</div></div>';
					});
					$('#seealso_bl').html(html);


                    $('.add', $('#seealso_bl')).bind('click', function(){
                        add_product_related(this);
                    });

				});
				last_seealso = searchstring;
				$('#seealso_bl').fadeIn("fast");
			}, 800);
		}
	}).focus(function(){
        $('#seealso_bl').css({'display': 'block'});
    });

    /*.mouseover(function() {
				if ($('#search').val() != '' && $('a', $('#help_search')).size() > 0) {
					$('#help_search').stop().css('opacity', 1).css('display', 'block');
					seealso_show = 1;
				}
			}
		).mouseout(function() {
				$('#help_search').fadeOut("fast");
				seealso_show = 0;
			}
		).focus(function(){
        if ($(this).val() == $(this).attr('title')){
            $(this).val('');
        }
        }).blur(function(){
            if ($(this).val() == ''){
                $(this).val($(this).attr('title'));
            }
        });    */
          /*
        $('._eop').click(function(){
            var p = $(this).parent();
            var optionID = $(this).attr('title');

            $(this).after('<input type="text" id="_eop'+optionID+'" value="" class="_eopt" /><div class="_ceop">[C]</div><div class="_seop">[S]</div>');
            $('._ceop', $(p)).bind('click', function(){
                _ceop(this);
                return false
            });

            $('._seop', $(p)).bind('click', function(){
                _seop(this);
                return false
            });

            $('._eop', $(p)).css({'display': 'none'});
        });

        function _ceop(o){
            var p = $(o).parent();
            $('._seop', $(p)).remove();
            $('._eopt', $(p)).remove();
            $(o).remove();
            $('._eop', $(p)).css({'display': 'block'});
            return false;
        }

        function _seop(o){
            var p = $(o).parent();
            alert($('._eopt').val());
        }   */

        function rgdelphn(o){
            var n = $('.phn').size();

            var _tmp = $(o).attr('class').split('rgdelphn n');
            var k = _tmp[1];

            if(n == 3){
                var p = $(o).prev();
                $(p).prev().remove();
                $(p).remove();
                $(o).remove();

                if(k == 2){
                   $('.n3').removeClass('n3').addClass('n2');
                }

                p = $('.n2').prev();
                $('.n2').remove();
                $(p).after('<div id="rgaddphn" class="n'+(n-1)+'"></div>');

                $('#rgaddphn').bind('click', function(){
                    rgaddphn(this);
                    return false;
                });
            }
        }

        function rgaddphn(o){
            var n = $('.phn').size();
            var k = n;

            var _tmp = $(o).attr('class').split('n');
            var k = _tmp[1];

            if(n < 3){
                var s = '<div class="label">'+getConstant('TMPL_FORM_PHONE')+'</div><div class="input phn"><input type="text" name="phones[]" value="" /></div></div>';

                if(k == 1){
                    s += '<div id="rgaddphn" class="n'+(++k)+'"></div>';
                }else if(k == 2){
                    s += '<div class="rgdelphn n'+(++k)+'"></div>';
                }

                $(o).after(s);

                if(n == 1){
                    $(o).remove();
                    $('#rgaddphn').bind('click', function(){
                        rgaddphn(this);
                        return false;
                    });
                }else if(n == 2){
                    var p = $('.n'+n).prev();
                    $('.n'+n).remove();
                    $(p).after('<div class="rgdelphn n'+n+'"></div>');
                    $('.n'+n+',.n'+k).bind('click', function(){
                        rgdelphn(this);
                        return false;
                    });
                }
            }
        }

        $('#rgaddphn').click(function(){
            rgaddphn(this);
            return false;
        });

        $('.rgdelphn').click(function(){
            rgdelphn(this);
            return false;
        });

        $('div', $('#slmethods')).mouseover(function(){
            $(this).addClass('a');
        }).mouseout(function(){
            $(this).removeClass('a');
        }).click(function(){
            if(!$(this).hasClass('chk')){
                var tmp = $(this).attr('id').split('i');
                var ID = tmp[1];
                $('.chk .s', $('#slmethods')).remove();
                $('.chk', $('#slmethods')).removeClass('chk');
                $(this).addClass('chk');
                $('#value').val(ID);
                $(this).append("<a href='#' onClick='document.slmethods.submit(); return false;' class='s'>"+getConstant('CONTINUE_BUTTON')+"</a>");
            }
        });

        ///files
        $('.jplayer').each(function(){
            var tmp = $(this).attr('id').split('__');
            var playerID = tmp[1];

            $(this).jPlayer({
          		ready: function () {
          			$(this).jPlayer("setMedia", {
          				mp3: www + "media.php?fileID=" + playerID
          			});
          		},
                  cssSelectorAncestor: "", // Remove the ancestor css selector clause
                  cssSelector: {
                    play: "#player_play__" + playerID,
                    pause: "#player_pause__" + playerID
                    // The other defaults remain unchanged
                  },
          		swfPath: www + "js",
          		supplied: "mp3"
          	});

            $(this).bind($.jPlayer.event.play, function() { // Bind an event handler to the instance's play event.
              $(this).jPlayer("pauseOthers"); // pause all players except this one.
            });
        });

        $('#select_all_files').click(function(){
            var total_price = 0;

            $('.row .c6').each(function(){
                total_price += parseFloat($(this).html().replace(global_cc, ''));
            });

            if(this.checked){
                $('.c2 input').attr({'checked': 'checked'});
                $('#total_price_selected').html(get_price_with_currency(sprintf('%.2f', total_price)));
                $('#form_total_price').val(get_price_with_currency(sprintf('%.2f', total_price)));
            }else{
                $('.c2 input').removeAttr('checked');
                $('#total_price_selected').html('0.00');
                $('#form_total_price').val('0.00');
            }
        });

        $('.select_this').click(function(){
            var total_price = parseFloat($('#total_price_selected').html().replace(global_cc, ''));

            //function get_price_with_currency(p) {

            if(this.checked){
                $(this).attr({'checked': 'checked'});
                total_price += parseFloat($('.c6', $(this).parent().parent()).html().replace(global_cc, ''));
                $('#total_price_selected').html(get_price_with_currency(sprintf('%.2f', total_price)));
                $('#form_total_price').val(sprintf('%.2f', total_price));
            }else{
                $(this).removeAttr('checked');
                total_price -= parseFloat($('.c6', $(this).parent().parent()).html().replace(global_cc, ''));
                $('#total_price_selected').html(get_price_with_currency(sprintf('%.2f', total_price)));
                $('#form_total_price').val(sprintf('%.2f', total_price));
            }
        });

        $('#buy_selected').click(function(){
           $('#buy_form').submit();
           return false;
        });

        //shopping_cart_files
        function refresh_scfc(xml){
            var tpwd = $(xml).find('td').text();
            var tpdp = $(xml).find('dp').text();
            $('#scfi_fc').html($(xml).find('fc').text());
            $('#scfi_tp').html($(xml).find('tp').text());
            $('#scfi_dp').html(tpdp);
            $('#scfi_td').html(tpwd);
            if ($('#scftpwd').length) {
                $('#scftpwd').html(tpwd);
            }
            if ($('#scftdp').length) {
                $('#scftdp').html(tpdp);
            }
        }

        languages = {};

        function getConstant(c){
            if(languages[c]){
                out = languages[c];
            }else{
                out = $.ajax({
                          url: www + 'ajx.php',
                          global: false,
                          async: false,
                          type: "GET",
                          data: ({'constant': c, 'lng': lng.replace('/', ''), 'ajx': 1}),
                          dataType: "text"
                       }).responseText;
                languages[c] = out;
            }

            return out;
        }

        function editComment(o){
            var text = '';

            if(!o.hasClass('null')){
                text = $('div', o).html();
            }

            o.html("<textarea cols='16' rows='2'>"+text+"</textarea><a href='#' class='cancel'>" + getConstant('STRING_CANCEL') + "</a><a href='#' class='comment_save'>" + getConstant('STRING_SAVE') + "</a>");
            $('.comment_save', o).bind('click', function(){
                var _tmp = o.attr('id').split('comment');
                var itemID = _tmp[1];

                var vl = $('textarea', $('#comment'+itemID))[0].value;

                $.get("/ajx_sc.php", {'sc': 'savecomment', 'itemID': itemID, 'text': vl, 'ajx': 1}, function(){
                    var out = '';
                    if(vl.length > 0){
                        out = getConstant('STRING_SCDL_NOTIFY') + "&nbsp;<div>" + vl + "</div>";
                        if(o.hasClass('null')){
                            o.removeClass('null');
                        }
                    }else{
                        out = getConstant('STRING_SCDL_NOTIFY') + "&nbsp;<div>" + getConstant('STRING_SCDL_NOTIFY2') + "</div>";
                        if(!o.hasClass('null')){
                            o.addClass('null');
                        }
                    }

                    o.html(out + "&nbsp;<a href='#' class='edit'>" + getConstant('STRING_EDIT') + "</a>");

                    $('.edit', o).bind('click', function(){
                        editComment(o);
                        return false;
                    });
    			});
                return false;
            });
            $('.cancel', o).bind('click', function(){
                var out = getConstant('STRING_SCDL_NOTIFY') + "&nbsp;";
                if(text == ''){
                    out += "<div>" + getConstant('STRING_SCDL_NOTIFY2') + "</div>";
                }else{
                    out += "<div>" + text + "</div>";
                }

                o.html(out + "&nbsp;<a href='#' class='edit'>" + getConstant('STRING_EDIT') + "</a>");

                $('.edit', o).bind('click', function(){
                    editComment(o);
                    return false;
                });
                return false;
            });

            return false;
        }


        $('.icnt .edit', $('#cart2')).click(function(){
             var o = $(this).parent();
             $(this).bind('click', editComment(o));
             return false;
        });

        $('.comment_save', $('#cart2')).click(function(){

        });

        $('.remove', $('#scfc')).click(function(){
            $(this).parent().parent().parent().parent().css("background-color","#ffafaf");
            var _tmp = $(this).parent().parent().parent().parent().attr('id').split('f');
            var fileID = _tmp[1];

            $.get("/ajx_scf.php", {'scf': 'delfile', 'fileID': fileID, 'ajx': 1}, function(xml){
                refresh_scfc(xml);
                $('#f'+fileID).remove();

                var statusID = $(xml).find('statusID').text();
                var scfw = parseInt($('#scfw').html());
                var scfr = parseInt($('#scfr').html());
                if(statusID == 1){
                    $('#scfw').html(--scfw);
                }else{
                    $('#scfr').html(--scfw);
                }
			});
            return false;
        });

        $('.wait', $('#scfc')).click(function(){
            $(this).parent().parent().parent().parent().css("background-color","#ffafaf");
            var _tmp = $(this).parent().parent().parent().parent().attr('id').split('f');
            var fileID = _tmp[1];

            $.get("/ajx_scf.php", {'scf': 'waitfile', 'fileID': fileID, 'ajx': 1}, function(xml){
                refresh_scfc(xml);
                $('#f'+fileID).remove();
                var scfw = parseInt($('#scfw').html());
                var scfr = parseInt($('#scfr').html());
                $('#scfw').html(++scfw);
                $('#scfr').html(--scfr);
			});
            return false;
        });

        $('.ready', $('#scfc')).click(function(){
            $(this).parent().parent().parent().parent().css("background-color","#ffafaf");
            var _tmp = $(this).parent().parent().parent().parent().attr('id').split('f');
            var fileID = _tmp[1];

            $.get("/ajx_scf.php", {'scf': 'readfile', 'fileID': fileID, 'ajx': 1}, function(xml){
                refresh_scfc(xml);
                $('#f'+fileID).remove();
                var scfw = parseInt($('#scfw').html());
                var scfr = parseInt($('#scfr').html());
                $('#scfw').html(--scfw);
                $('#scfr').html(++scfr);
			});
            return false;
        });
        ///

        //p rate
        $('.cu', $('.cm_rate')).click(function(){
            var _tmp = $(this).parent().parent().attr('id').split('c');
            var commentID = _tmp[1];
            $.get("/ajax.php", {'plus_comment_rate': commentID, 'ajx': 1}, function(out){
                if(out != '0'){
                    var cval = $('#vu'+commentID).html();
                    $('#vu'+commentID).html(++cval);
                    if(out == 2){
                        cval = $('#vd'+commentID).html();
                        $('#vd'+commentID).html(--cval);
                    }
                }
            });
        });

        $('.cd', $('.cm_rate')).click(function(){
            var _tmp = $(this).parent().parent().attr('id').split('c');
            var commentID = _tmp[1];
            $.get("/ajax.php", {'minus_comment_rate': commentID, 'ajx': 1}, function(out){
                if(out != '0'){
                    var cval = $('#vd'+commentID).html();
                    $('#vd'+commentID).html(++cval);
                    if(out == 2){
                        cval = $('#vu'+commentID).html();
                        $('#vu'+commentID).html(--cval);
                    }
                }
            });
        });

        //скрины продукта
        $('.product_screens a').click(function(){
            var tmp = $('img', $(this)).attr('src').split('/');
            $('.product_cscreen').html('<img src="'+$('#url').val()+'images/screens/'+$('#categoryID').val()+'/'+tmp[tmp.length-1]+'" />');
            //$('.product_cscreen img').attr({src:$('#url').val()+'images/screens/'+$('#categoryID').val()+'/'+tmp[tmp.length-1]});
            return false;
        });

        //кол-во товаров на странице
        $('.perpage').change(function(){
            $.get("/ajax.php", {'products_per_page': $(this).val(), 'ajx': 1}, function(){
                document.location = document.location;
            });
        });

        $('span', $('.faq')).click(function(){
            $(this).parent().children('div').toggle('normal');
            return false;
        });

        //p-page, bdelay
        $('.bdelay').click(function(){
            o = $(this);
            var tmp = $(this).attr('id').split('p');
            var productID = tmp[1];
            $.get('/index.php', {'wait_to_order_new': productID, 'ajx': 1}, function(r){
                if(r){
                    o.html(r);
                }
			});
            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,#scfswch').click(function(){
            var ob = $(this).parent().next();
            if (!$(ob).hasClass('open'))
                $(ob).addClass('open').animate({height: 'show'}, 'fast');
            else
                $(ob).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;
			}
		).focus(function(){
        if ($(this).val() == $(this).attr('title')){
            $(this).val('');
        }
        }).blur(function(){
            if ($(this).val() == ''){
                $(this).val($(this).attr('title'));
            }
        });

		$("#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();
                var phncc = '';

                if(id == 176){
                    phncc = '+7';
                }else if(id == 220){
                    phncc = '+380';
                }

                $('#phn0').val(phncc);

				$.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 = "/biography/187.html";
			}
		);

		$(".quaranty_block div").click(function()
			{
				document.location = "/biography/272.html";
			}
		);

		//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;
}
