$(document).ready(function() {

    $(".switch div").hover(function() {
       $(this).addClass('selected');
    }, function() {
       $(this).removeClass('selected');
    }).click(function() {
       $('.switch div').removeClass('clicked');
       $(this).addClass('clicked');
       if ($(this).hasClass('on-vehicle')) {
            $('.maps>img').hide();
            $('.drag-container').show();

            $( ".drrr" ).draggable({ containment: 'parent' });
            $( ".drrr" ).draggable( "enable" );
            $( ".drrr" ).css({left: 221, top: 354});
        } else {
            $( ".drrr" ).draggable( "disable" );
            $('.drag-container').hide();
            $('.maps>img').show();
       };
    });

    // только для главной страницы
    $('.animated-index').each(function() {

        setTimeout(function() {
            $('.logo').fadeIn(300, function() {
                $('#content').find('h1, p').slideDown(100);
                setTimeout(function() {
                    $('#footer .left').slideDown(200, function() {
                        $('#footer .right').slideDown(200);
                        setTimeout(function() {
                            $('.background-switcher').fadeIn(600, function() {
                                $('.annotation-container.first').fadeIn(600);
                                setTimeout(function() {
                                    $('.hor-navigation').slideDown(100, function() {
                                        $('.menuitem', this).each(function(i) {
                                            (function(menuitem, delay) {
                                                setTimeout(function() {
                                                    $(menuitem).show();
                                                }, delay);
                                            })(this, (i+1)*100);
                                        });
                                    });
                                }, 600);
                            });
                        }, 400);
                    });
                }, 200);
            });
        }, 500);
    });

    $('.annotation-container > div').hover(function() {
        $('h3', this).css({color: "#0E7D3C"});
    }, function() {
        $('h3', this).css({color: ""});
    });


    $('.background-switcher').each(function() {
        /*var bg = $(this);
        var current = 0;
        var centerWidth = 900;
        var itemWidth = 300;
        var offset = 0;
        var ann = $('.annotation-container');
        var count = ann.length;

        bg.css({
            'background-position':  '0px 0px',
            //'background-repeat': 'no-repeat',
            cursor: 'pointer'
        });

        function setOffset(value) {
            value = Math.round(value);
            offset = value;
            bg.css({
                'background-position':  offset+'px 0px'
            });
        }

        function animateOffset(value) {
            value = Math.round(value);
            offset = value;
            bg.animate({
                backgroundPosition:  offset+'px 0px'
            }, 600); // , 'easeOutBack'
        }

        function applyWindowSize() {
            setOffset( ($(window).width() - centerWidth) / 2 - current*itemWidth);
        }

        $(window).resize(function() {
            applyWindowSize();
        });
        applyWindowSize();

        bg.click(function(e) {
            if ($(":animated").length) {
                return false;
            }
            var N = Math.ceil((e.clientX - offset) / itemWidth) - 1;
            if (N == current) {
                return false;
            }
            current = N;
            var number = current % count;
            if (number < 0) {
                number += count;
            }
            ann.filter(':visible').fadeOut(function() {
                $('#annotation-container-' + number).fadeIn();
            });
            animateOffset(($(window).width() - centerWidth) / 2 - current*itemWidth);
        });*/

        var self = this;

        var fps = 12;
        var pxPerSec = 40;
        var pxPerFrame = pxPerSec / fps;

        var freezeTime = 3000;

        var speed = 0;
        var offset = 0;

        var centerWidth = 900;
        var itemWidth = 300;

        var bg = $(this);
        var ann = $('.annotation-container');
        var count = ann.length;

        var stopping = false;
        var clickJob = false;
        var freezed = false;
        var scrolling = 0;

        var box = {
            width: $(window).width()
        }

        function isiPad() {

            return (
                (navigator.platform.indexOf("iPhone") != -1) ||
                (navigator.platform.indexOf("iPad") != -1) ||
                (navigator.platform.indexOf("iPod") != -1)
            );
        }

        function applyWindowSize() {
            var newWidth = $(window).width();
            offset += (newWidth - box.width) / 2;
            box.width = newWidth;
        }

        offset = ($(window).width() - centerWidth) / 2;

        $(window).resize(function() {
            applyWindowSize();
        });

        applyWindowSize();
        $(bg).css({'background-position': offset+'px 0'}, 500);

        function wheelHandler(N)
        {
            scrolling++;

            var wing = (box.width - centerWidth) / 2;

            var currentOffset = parseFloat($(self).css('background-position'));

            var newOffset = wing + Math.round((currentOffset - N*itemWidth - wing) / itemWidth) * itemWidth;

            offset = newOffset;

            $(self).stop().animate({'background-position': newOffset+'px 0'}, 500);
            setTimeout(function() {
                scrolling--;
            }, 500);
        }

        function clickHandler(e, x) {
            if (clickJob || scrolling) {
                return;
            }

            clickJob = true;
            speed = 0;

            var N = Math.ceil((x - offset) / itemWidth) - 1;
            var number = N % count;
            if (number < 0) {
                number += count;
            }

            freezed = true;

            var inF = function() {
                var cnt = $('#annotation-container-' + number);
                var hovered = false;
                cnt.unbind('hover mouseover mouseout').hover(function() {
                    hovered = true;
                }, function() {
                    cnt.fadeOut(function() {
                        freezed = false;
                    });
                });

                cnt.fadeIn(function() {
                    setTimeout(function() {
                        if (cnt.filter(':visible') && !hovered) {
                            freezed = false;
                        }
                        if (!hovered) {
                            cnt.fadeOut();
                        }
                        speed = 0;
                    }, freezeTime);
                });
            }

            var toOut = ann.filter(':visible');
            if (toOut.length) {
                toOut.hide();
            }
            inF();



            var newOffset = (box.width - centerWidth) / 2 - N*itemWidth;
            offset = newOffset;

            bg.animate({
                backgroundPosition: newOffset+'px 0'
            }, 500, function() {
                clickJob = false;
            });
        }

        if (isiPad()) {
             $(this)
                .bind('swipe', function(e, start, stop) {
                    if (freezed || clickJob) {
                        return;
                    }

                    var delta = start.coords[0] - stop.coords[0];
                    delta *= 1.5;
                    var absDelta = Math.abs(delta);
                    var sign = delta > 0;

                    wheelHandler(Math.ceil(absDelta / itemWidth) * (sign ? 1 : -1));
                })
                /*.bind('swipeleft', function() {
                    if (freezed || clickJob) {
                        return;
                    }



                    //wheelHandler(3);

                    return false;
                })
                .bind('swiperight', function() {
                    if (freezed || clickJob) {
                        return;
                    }

                    //wheelHandler(-3);

                    return false;
                })*/
                .bind('tap', function(e) {

                    clickHandler(e, e.start.coords[0]);

                    return false;
                });
        } else {
            $(this)
                .mousewheel(function(objEvent, intDelta) {
                    if (freezed || clickJob) {
                        return;
                    }

                    var N = 3;
                    if (intDelta > 0) {
                        var N = -N;
                    }

                    wheelHandler(N);

                    return false;
                })
                .mousemove(function(e) {
                    var sideWidth = box.width / 2;
                    var rigthSideOffset = box.width-sideWidth;

                    if (e.clientX < sideWidth) {
                        speed = 1 - e.clientX / sideWidth;
                    } else if (e.clientX > rigthSideOffset) {
                        speed = - (e.clientX - rigthSideOffset) / (box.width - rigthSideOffset);
                    } else {
                        speed = 0;
                    }
                })
                .hover(function(e) {
                    stopping = false;
                }, function(e) {
                    stopping = true;
                })
                .click(function(e) {
                    clickHandler(e, e.clientX);
                });

            setInterval(function() {
                if (clickJob || freezed || scrolling) {
                    return;
                }
                offset += speed * pxPerFrame;
                bg.css({
                    backgroundPosition:  offset+'px 0px'
                }, 600);

                if (stopping) {
                    newSpeed = speed / 1.05;
                    if (Math.abs(newSpeed) < 0.01) {
                        newSpeed = 0;
                    }
                    speed = newSpeed;
                }

            }, fps);

        }
    });



    $('.catalog .card').each(function() {
        var imageBlock = $('.image-block');
        var buttons = $('.list-container-small a', this);

        buttons.click(function() {

            if ($('div:animated', imageBlock).length) {
                return false;
            }

            var button = $(this);
            var img = $('img', button);

            if (img.hasClass('selected')) {
                return false;
            }

            $('img', buttons).attr({
                'src': '/i/markers/s-unsel.gif'
            }).removeClass('selected');

            img.attr({
                'src': '/i/markers/s-sel.gif'
            }).addClass('selected');

            imageBlock.children('div').filter(':visible').fadeOut(function() {
                $(button.attr('href')).fadeIn();
            });

            /*image.fadeOut(function() {
                $(this).attr({
                    src: button.attr('href'),
                }).removeAttr('height').fadeIn();
            });*/


            return false;
        });

        /*image.click(function() {
            var next = $('.selected', buttons).parent().next();
            if (next.length) {
                next.click();
            } else {
                buttons.eq(0).click();
            }
        }).css({cursor: 'pointer'});*/
    });

/*catalog-hover*/
    function porfolioWorkHover(selector) {
        $(selector).hover(function() {
            $('.text',this).show();
        }, function() {
            $('.text',this).hide();
        })
        .click(function() {
            if (!$(this).hasClass('block-listing')) {
                window.location = $('a', this).attr('href');
                return false;
            };
        });
    }
    porfolioWorkHover(".catalog .list > div > div");


    $('.portfolio-index').each(function() {

        var annotationCategories = $('.list > .category', this);
        var pagerCategories = $('.list-container .category', this)

        $(pagerCategories).each(function(index) {
            var category = parseInt($(this).attr('id').replace('category-', ''));
            var annotationCategory = annotationCategories.eq(index);

            var pageButtons = $('img', this);

            $('#category-'+category+'-page-1').addClass('loaded');

            pageButtons.click(function() {

                if ($(':animated', annotationCategory).length) {
                    return false;
                }

                var button = $(this);

                pageButtons.attr('src', '/i/markers/l-unsel.gif').removeClass('selected');
                $(this).attr('src', '/i/markers/l-sel.gif').addClass('selected');

                var page = parseInt($(this).attr('id').replace('category-'+category+'-page-', ''));

                if (button.hasClass('loaded')) {

                    annotationCategory.children(':not(.page-'+page+')').fadeOut(300);
                    setTimeout(function() {
                        annotationCategory.children('.page-'+page).fadeIn();
                    }, 300);

                } else {

                    button.addClass('loaded');
                    $.get('/portfolio/indexAjax', {category: category, page: page}, function(html) {

                        var newElements = $(html).filter('div');
                        porfolioWorkHover(newElements);

                        annotationCategory.children(':not(.page-'+page+')').fadeOut(300);
                        setTimeout(function() {
                            newElements.hide();
                            annotationCategory.append(newElements);
                            annotationCategory.children('.page-'+page).fadeIn();
                        }, 300);


                    });
                }

            });
        });

    });


    /*slider-navi*/
    $(".hor-navigation-inner").each(function() {
        var self = this;
        var slider = $('.slider', self);

        function sumWidth(e) {
            var w = 0;
            $(e).each(function() {
                w += $(this).width();
            });
            return w;
        }

        $(".left", self).click(function() {
            if (slider.is(':animated')) {
                return;
            }
            var tds = $("td", slider);
            var length = tds.length;
            var last3 = $("td", slider).slice(length-3);
            var last3width = sumWidth(last3);
            slider.css({
                marginLeft: -last3width
            });
            $('td:first', slider).before(last3);
            slider.animate({marginLeft: 0}, 2500);
        });

        $(".right", self).click(function() {
            if (slider.is(':animated')) {
                return;
            }
            var tds = $("td", slider);
            var length = tds.length;
            var first3 = $("td", slider).slice(0, 3);
            var first3width = sumWidth(first3);
            slider.animate({marginLeft: -first3width}, 2500, function() {
                $('td:last', slider).after(first3);
                $(this).css({marginLeft: 0});
            });
        });

        $(".left, .right", self).hover(function() {
            $(this).click();
        }, function() {

        });
    });





/*hor-navi*/

    $(".hor-navigation div div")
        .hover(function() {

                 $(this).addClass('selected');

        }, function() {
                 if (!$(this).hasClass('static')) {
                        $(this).removeClass('selected');
                         };
        })

        .click(function()
                        {
                      window.location = $('a', this).attr('href');
                      return false;
        });
});
