(function($){$.fn.jCarouselLite=function(o){o=$.extend({btnPrev:null,btnNext:null,btnGo:null,mouseWheel:false,auto:null,speed:200,easing:null,vertical:false,circular:true,visible:3,start:0,scroll:1,beforeStart:null,afterEnd:null},o||{});return this.each(function(){var b=false,animCss=o.vertical?"top":"left",sizeCss=o.vertical?"height":"width";var c=$(this),ul=$("ul",c),tLi=$("li",ul),tl=tLi.size(),v=o.visible;if(o.circular){ul.prepend(tLi.slice(tl-v-1+1).clone()).append(tLi.slice(0,v).clone());o.start+=v}var f=$("li",ul),itemLength=f.size(),curr=o.start;c.css("visibility","visible");f.css({overflow:"hidden",float:o.vertical?"none":"left"});ul.css({margin:"0",padding:"0",position:"relative","list-style-type":"none","z-index":"1"});c.css({overflow:"hidden",position:"relative","z-index":"2",left:"0px"});var g=o.vertical?height(f):width(f);var h=g*itemLength;var j=g*v;f.css({width:f.width(),height:f.height()});ul.css(sizeCss,h+"px").css(animCss,-(curr*g));c.css(sizeCss,j+"px");if(o.btnPrev)$(o.btnPrev).click(function(){return go(curr-o.scroll)});if(o.btnNext)$(o.btnNext).click(function(){return go(curr+o.scroll)});if(o.btnGo)$.each(o.btnGo,function(i,a){$(a).click(function(){return go(o.circular?o.visible+i:i)})});if(o.mouseWheel&&c.mousewheel)c.mousewheel(function(e,d){return d>0?go(curr-o.scroll):go(curr+o.scroll)});if(o.auto)setInterval(function(){go(curr+o.scroll)},o.auto+o.speed);function vis(){return f.slice(curr).slice(0,v)};function go(a){if(!b){if(o.beforeStart)o.beforeStart.call(this,vis());if(o.circular){if(a<=o.start-v-1){ul.css(animCss,-((itemLength-(v*2))*g)+"px");curr=a==o.start-v-1?itemLength-(v*2)-1:itemLength-(v*2)-o.scroll}else if(a>=itemLength-v+1){ul.css(animCss,-((v)*g)+"px");curr=a==itemLength-v+1?v+1:v+o.scroll}else curr=a}else{if(a<0||a>itemLength-v)return;else curr=a}b=true;ul.animate(animCss=="left"?{left:-(curr*g)}:{top:-(curr*g)},o.speed,o.easing,function(){if(o.afterEnd)o.afterEnd.call(this,vis());b=false});if(!o.circular){$(o.btnPrev+","+o.btnNext).removeClass("disabled");$((curr-o.scroll<0&&o.btnPrev)||(curr+o.scroll>itemLength-v&&o.btnNext)||[]).addClass("disabled")}}return false}})};function css(a,b){return parseInt($.css(a[0],b))||0};function width(a){return a[0].offsetWidth+css(a,'marginLeft')+css(a,'marginRight')};function height(a){return a[0].offsetHeight+css(a,'marginTop')+css(a,'marginBottom')}})(jQuery);

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { 
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); 
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { 
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$(document).ready(function(){
    $('.plus').live('click',function(e){
        $(this).find('img').attr('src','/images/minus.gif');
        $(this).parent().next().show();
        i = $(this).parent('li').attr('rel');
        $.cookie('KUDIN_MENU_' + i, 1, {path:'/'});
        $(this).removeClass('plus').addClass('minus');
        e.preventDefault();
    });

    $('.minus').live('click',function(e){
        $(this).find('img').attr('src','/images/plus.gif');
        $(this).parent().next().hide();
        i = $(this).parent('li').attr('rel');
        $.cookie('KUDIN_MENU_' + i, null, {path:'/'});
        $(this).removeClass('minus').addClass('plus');
        e.preventDefault();
    });
    
        $(document).click(function(e){
        rmenu = $('#rmenu');        
        if ($(e.target).parents().filter('.nopad').length == 1) { 
            if (rmenu.css('display')=='none')
                { 
                   rmenu.css('margin-top', '-20px').show().css('opacity',0);
                     rmenu.animate({
                        'opacity': 1,
                        'margin-top': '-5px'
                      }, 400, function() {
                      
                      });
                }
            else {
                rmenu.hide(); 
                }
            return false;
        }
        else {
            if ($(e.target).filter(rmenu).length != 1)
                rmenu.hide();        
        }
    });
    
    
    
    
});

function search(ob) {
    query = $(ob).val();
    query = $.trim(query);
    if (query.length >= 2) {
        $.ajax({
            url: '/api/search.php',
            data: {q : query},
            dataType : "json",
            success: function( data ) {   
                $('.search-drop').html('');
                $.each(data, function(i, val) { 
                    $('.search-drop').append("<div class=\"item\">\n\
                        <div class=\"preview\"><a href='" + val['link'] + "'><img border=\"0\" src = \"" + val['image'] + "\"></a></div>\n\
                        <div class=\"description\"><p class=\"name\"><a href='" + val['link'] + "'>" + val['name'] + "</a></p><div class=\"price\">" + val['price_usd'] + " у.е.</div></div>\n\
                        </div>");
                });
                $('.search-drop').show();
            }
        });
    } else {
        close_search();
    }
}

function close_search() {
    $('.search-drop').fadeOut("def");
}


function sbmform(){
    query = $('.topsearch input').val();
    query = $.trim(query);
    
    if (query.length >= 1)
        location.href='/search/?q=' + query; 
}

function selChange(){
    opt = $('#fastnav option:selected').attr('rel');
    if (opt.length > 2){
        location.href=opt;
    } 
}

function add2basket(id){
    $.ajax({
        url: '/api/cart.php',
        data: {id : id},
        dataType: 'json',
        success: function( data ) {
                $('#topPanel').show().animate({
                    opacity: 0.98,
                    height: '100%'
                }, 550); 

                showData(data);
        } 
    });
         
    return false;
}

function closepanel(){ 
    $('#topPanel').animate({
        opacity: 0.1,
        height: '0px' 
    }, 350, function() {
        $(this).hide(); 
    });
return false;
}


function removefrombasket(id){
    $.ajax({
        url: '/api/removefrombasket.php',
        data: {id : id},
        dataType: 'json',
        success: function( data ) {
                $('#topPanel').show().animate({
                    opacity: 0.99,
                    height: '100%'
                }, 450); 
             showData(data);
        } 
    });
    return false;
}


function removefrombasket2(id){
    $.ajax({
        url: '/api/removefrombasket.php',
        data: {id : id},
        dataType: 'json',
        success: function( data ) {
              location.href='/cart/';
        } 
    });
    return false;
}


function showData(data){
    if (data == false)
        {
            closepanel();  
            $('#cart_block').html('Ваша корзина пуста<br> <a href="/catalog/">Выберите товар</a> и добавьте в заказ');
            return;
        }
    $('#cart_block').html(data['cart_block']);
        var co = data['products'].length;
    $('#topPanel').html('<p class=cart_text>' + data['text'] + '</p><a href="#" onclick="closepanel(); return false;"><img class="closeico" src="/images/closeico.png" border="0"></a><div class="lis"><div class="ls"></div></div>');
    $.each(data['products'], function(i, val) {
        $('.ls').append("<div class=\"item\">\n\
            <div class=\"preview\"><a href='" + val['link'] + "'><img border=\"0\" src = \"" + val['image'] + "\"></a></div>\n\
            <div class=\"description\"><p class=\"name\"><a href='" + val['link'] + "'>" + val['name'] + "</a><br><span class='rfb'>[<a href='#' onclick='removefrombasket(" + val['id'] + "); return false;'>удалить из корзины</a>]</span></p><div class=\"price\">" + val['price_usd'] + " у.е.</div></div>\n\
            </div>");
    });
    $('.ls').width(411 * co + 'px');
    $('#topPanel').append('<div class="bottomcart">Вы можете <a href="/cart/">оформить заказ прямо сейчас</a>, либо <a href="#" onclick="closepanel(); return false;">продолжить просмотр сайта</a>, чтобы вернуться к заказу позже</div>')
}


function zakazat(){

    $.ajax({
        dataType: 'json',
        url: '/api/zakaz.php',
        data: $('#zakaz').serialize(),
        success: function(data) {
            if(data=='ok'){
              $('#zakaz').hide();
                 $('#posd').show(); 
                 $('h2').text('Спасибо за заказ!')
             } else {
                 
             }
        } 
    });
    
    return false;
}


function zakazat2(){
    $.ajax({
        dataType: 'json',
        url: '/api/zakaz_1.php',
        data: $('#zakaz').serialize(),
        success: function(data) {
            if(data=='ok'){
              $('#zakaz').hide();
                 $('#posd').show(); 
                 $('h2').text('Спасибо за заказ!')
             } else {
                 
             }
        } 
    });
    return false;
}
