$(document).ready(function() {

    $('.prequest').live('click',function(){
        requestOnClick('price',$(this));
    });

    $('#callrequest').click(function(){
        requestOnClick('call',$(this));
    });

    requestOnClick = function(type, that) {
        var $this = that;
        if (type == 'price') {
            var model = $this.attr('data-model');
            var pid = $this.attr('data-pid');
            var prWindow = $('#hiddendiv .price-request-block').clone();
            prWindow.find('.productid').val(pid);
            prWindow.find('.model').html(model);
        } else if (type == 'call') {
            var prWindow = $('#hiddendiv .call-request-block').clone();
        }
        var ci = prWindow.find('.input.capt img');
        ci.attr('src',ci.attr('src').split('?')[0]+'?'+parseInt(Math.random()*10000));
        $over = $('#overlay').clone();
        $over.click(function(){ prWindow.remove(); $(this).remove(); })
                .appendTo('body');
        prWindow.find('.close').click(function(){ prWindow.remove(); $over.remove(); return false; });
        prWindow.find('.sendPR').click(function(){ ajaxRequest(ci,$(this).closest('.'+type+'-request-block'),$over); return false; });
        prWindow.appendTo('body');
        return false;
    };

    ajaxRequest = function(ci,$this,$over) {
        ci = $this.find('.input.capt img');
        $.post(
            __WWWHOST+'action.php',
            $this.find('form').serialize(),
            function(d){
                ci.attr('src',ci.attr('src').split('?')[0]+'?'+parseInt(Math.random()*10000));
                var errs = [];
                if ( $(d).find('error').length > 0 ) {
                    $(d).find('error').each(function(){
                        errs.push($(this).text());
                    });
                    $this.find('.errors').css('padding','5px').html(errs.join('<br>'));
                } else {
                    var header = $this.find('.header');
                    var close = $this.find('.close').html();
                    header.html('<a href="#" class="close">'+close+'</a>Ваш запрос успешно отправлен!<br>');
                    $this.html(header);
                    $this.find('.close').click(function(){ $this.remove(); $over.remove(); return false; });
                }
            }
        );
    };


    $('a.tocart').live('click',function(e){
        var pid = $(this).attr('data-pid');
        if ($('#pcount').length)
            var pcount = $('#pcount').val();
        else
            var pcount = 1;
        addToCart(pid, pcount, [e.pageX,e.pageY]);
        return false;
    });

	$('#searchform .button, .searchline .sbutton').click(function(){
        $(this).closest('form').submit();
        return false;
    });
    $('#searchform input, .searchline input').focus(function(){
        if ($(this).val()=='Введите запрос')
            $(this).val('');
    });
    $('#searchform input, .searchline input').blur(function(){
        if ($(this).val()=='' || $(this).val()==' ')
            $(this).val('Введите запрос');
    });
    $('#contents').tabs();
    $('#ptabs').tabs();
    $('#ctabs').tabs();

    updateCart = function() {
        ans = jQuery.ajax({
            type: 'GET',
            url: __WWWHOST+'one.php',
            data: {
                __one_a: 'Basket',
                __one_b: 'Basket'
            },
            dataType: 'html',
            error: function(r,s,e) { /*alert(r.responseText);*/ },
            success: function(data) {
                $('#basket_container').html(data);
            }
        });
    }

    var bodyClick = function() {
        clearTimeout(_cto);
        $('.added-to-cart-block.shown').fadeOut('fast');
        $('body').unbind('click',bodyClick);
    };

    addToCart = function(pid,pcount,coord) {
        var ans = jQuery.ajax({
			type: "GET",
			url: __WWWHOST+'action.php',
			data: {
				mode: 'ajax',
				action: 'Cart',
				Cart_method: 'add',
				Cart_id: pid,
                Cart_count: pcount
			},
			dataType: 'xml',
			error: function(r,s,e) { /*alert(r.responseText); alert('[AJAX Error0] '+e);*/ },
			success: function(xml) {
				updateCart();
                $('.added-to-cart-block.shown').remove();
                if (coord) {
                    _cto = null;
                    clearTimeout(_cto);
                    _cto = setTimeout(function(){ bodyClick() },5000);
                    var w = $('#hiddendiv').find('.added-to-cart-block').clone()
                        .css({'left': coord[0]-88,'top': coord[1]-55})
                        .addClass('shown').hide().appendTo('body').fadeIn('fast');
                     $('body').bind('click',bodyClick);
                }
			}
		});
    }

    if ($.fn.lightBox) {
        $('a.lightbox').lightBox({
            overlayBgColor: '#000',
            overlayOpacity: 0.6,
            imageLoading: __TMPLPATH+'img/lightbox/run.gif',
            imageBtnClose: __TMPLPATH+'img/lightbox/close.gif',
            imageBtnPrev: __TMPLPATH+'img/lightbox/prev.gif',
            imageBtnNext: __TMPLPATH+'img/lightbox/next.gif',
            containerResizeSpeed: 350,
            txtImage: 'Изображение',
            txtOf: 'из'
        });
    }

    $('.nojsbutton').hide();
    $('#place-order').css('display', 'block');

    dedMove = function() {
        $('#ded').animate({backgroundPosition: '-25% 0'},7000,'linear',function(){
            $('#ded').css({backgroundPosition: '125% 0'});
            setTimeout(dedMove,2000);
        });
    };

    //dedMove();

});
