var animated = 0;

function next()
{
    if (animated != 1)
    {
        var elm = $('#inner .elm').eq('0');
        animated = 1;

        $('#inner').animate({marginLeft: '-284px'},
            500,
            function(){
                $(elm).remove();
                $('#inner').css('marginLeft', '-142px');
                $('#inner').append(elm);
                animated = 0;
            });
    }
}

function prev()
{
    if (animated != 1)
    {
        animated = 1;

        var num = $('#inner .elm').length - 1;
        var elm = $('#inner .elm').eq(num);

        $('#inner').animate(
            {marginLeft: '0px'},
            500,
            function(){

                $(elm).remove();
                $('#inner').prepend(elm);
                $('#inner').css('marginLeft', '-142px');
                animated = 0;
            });
    }
}

function myAlert( text,type )
{
        setTimeout(
        function(){
            $('.message').slideUp('slow');
            $('.message').html('');
        },5000);

        $('.message').css('display','block').html('<div class='+ type +'><div class=top></div><p>'+ text +'</p></div><div class=bottom'+ type +'></div>');
}

function addToCart(id, amountGood, layoutDiff, thisObj)
{
    var layoutFile = '';
    
    $('.layoutFile').each(function(){
        layoutFile += $(this).val() + ',';
    });

//alert(layoutDiff);
//return false;
    $.getJSON(
        "/goods/",
        {act:"addTocart", id:id, amountGood:amountGood, layout:layoutDiff, layoutFile:layoutFile, comments:$('#comments').val()},
        function(data){
            if( data[0] == 'noerrors' )
            {
                $('#cartAmount').text( data[1] );
                $('#cartSum').text( data[2] );
                $('#uploadResult').html('');
                myAlert('Товар добавлен в корзину', 'ok');
            }else{
                myAlert('Ошибка сохранения товара', 'err');
            }
        }
    );    
}

function addToCartPhotos()
{
    var amount = [];
    var i = 0;
    var err = '';
    $('.amountPhotos').each(function(){
            amount[i] = $(this).val() + '||' + $(this).attr('rel') + '||'+
                $(this).parent().parent().parent().parent().parent().attr('rel');
            i++;

            if( parseInt($(this).val()) <= 0 || !Number($(this).val()) )
                err = 'Введите числовое значение';
    });

    if( err )
    {
        myAlert(err, 'err');
        return false;
    }
    
    $.getJSON(
        '/photos/',
        {act:'addToCartPhotos', 'amount[]':amount},
        function(data)
        {
            if( data[0] == 'noerrors' )
            {
                cartSum = parseFloat(data[2]);
                photoSum = parseFloat(data[3]);
                $('#cartAmount').text( data[1] );
                $('#cartSum').text( cartSum.toFixed(2) );
                $('#photoSum').text( photoSum.toFixed(2) );
                myAlert('Товар добавлен в корзину', 'ok');
            }else{
                myAlert('Ошибка сохранения товара', 'err');
            }
        }
    );

}

function reCount()
{
//    $('#cartSum').text( $.cookie('totalPrice') );
//    $('#cartSum2').text( $.cookie('totalPrice') );
//    var discount = $('#cartDiscount').text();
//    var price = $.cookie('totalPrice') / 100 * (100 - parseInt(discount));
//    $('#cartSumWithDiscount').text( price.toFixed(2) );
    
    var cartGoods = new Array();
    var typeGood = new Array();
    i = 0;

    $('.countcheckbox').each(function(){

        num = parseInt( Math.abs($(this).val()));
        if (num ==0 || !num) num = 1;

        cartGoods[i] = Array( num, $(this).attr('rel') );
        typeGood[i] = $(this).parent().attr('rel');

        i++;
    });

    $.getJSON(
        '/cart/',
        {'act':'recount', 'cartGoodsAjax[]':cartGoods, 'typeGood[]':typeGood },
        function(data)
        {
            if(data == 1)
                window.location.reload();
        }
    );

    //window.location.reload();
}

$(document).ready(function(){
	var num = $('#inner .elm').length * 142 + 142;
	$('#inner').css('width', num + 'px');

       $('.serviceTitle').click(function()
        {
            if( $(this).next().css('display') == 'block' )
            {
                return false;
            }

            var closedMenus = new Array();
            var clicked = $('.serviceTitle').index(this);

            i = 0;
            $('.leftBar ul').slideUp();
            $.cookie("closedMenus", null,{ path: '/'});

            $(this).next().slideToggle('fast',
                function(){
                    $('.serviceTitle').each(function(){
                        //create array for cookie opened menus
                        if( i == clicked ) {
                            closedMenus[i] = 1;
                            $(this).children('img').attr('src', 'images/leftbarArrowDown.jpg');
                        }else{
                            closedMenus[i] = 0;
                            $(this).children('img').attr('src', 'images/leftbarArrow.jpg');
                        }
                        i++;
                    });


                    $.cookie("closedMenus", closedMenus,{ path: '/', expires: 1500 });
                }
            );
        });
});

$(document).ready(function(){

    var mouse_x = 0;
    var mouse_y = 0;
    //получили координаты краев
    var prev_x = $(".wrap").offset().left;
    var next_x = prev_x + 641;
    var ref = '';
    $('.outer').mousemove(function(e){
        //получаем координаты мышки
        mouse_x = e.pageX;
        mouse_y = e.pageY;
        if( next_x - mouse_x > 0 && next_x - mouse_x < 155 && mouse_y > 210 && mouse_y < 335)
        {
            //ref = setInterval(function(){next();}, 1000);
            next();
        }else if( mouse_x - prev_x < 200 && mouse_x - prev_x > 0 && mouse_y > 210 && mouse_y < 335)
        {
            //ref = setInterval(function(){prev();},1000);
            prev();
        }
        //clearInterval(ref);
    });

    $('.elm').hover(
        function(e){ref=''; ref = setInterval(function(){next();}, 1500);},
        function(e){clearInterval(ref);}
    );

//    $('.topLots').hover(
//        function(e){
//            //ref == '';
//            //вычислить координаты и если че. запускать ту или иную функцию.
//            $().mousemove(function(e){
//                //получаем координаты мышки
//                mouse_x = e.pageX;
//                mouse_y = e.pageY;
//                if( next_x - mouse_x > 0 && next_x - mouse_x < 155 && mouse_y > 210 && mouse_y < 335)
//                {
//                    //if( !ref )
//                        ref = setInterval(function(){next();}, 1000);
//                    //next();
//
//                }else if( mouse_x - prev_x < 200 && mouse_x - prev_x > 0 && mouse_y > 210 && mouse_y < 335)
//                {
//                    //if( !ref )
//                        ref = setInterval(function(){prev();},1000);
//                    //prev();
//                    //alert('prev');
//                }
//           });
//           //console.log( mouse_y+'-'+mouse_x );
//
//        },
//        function(){
//            //остановить все.
//            clearInterval(ref);
//        }
//    );

    $('.btnPrev').hover(
        function(){
            ref = setInterval(function(){prev();},500);
        },
        function(){
            clearInterval(ref);
        }
    );
    $('.btnNext').hover(
        function(){
            ref = setInterval(function(){next();}, 500);
        },
        function(){
            clearInterval(ref);
        }
    );


    // установить по центру пункты меню
    $('.topMenu a').each(function(){
        $(this).css({ paddingTop: ((43 - $(this).children('.linkInner').height())/2)+'px', height: 43-((43 - $(this).children('.linkInner').height())/2)+'px' });
        
    });
});
