$(document).ready(function() {
    var issip = false;
    $('#slideshow .backward, #slideshow .forward').click(function() {
        if(issip) { return; }
        p = $('#slideshow .pictures');
        c = p.find('li:visible');
        next = $(this).hasClass('backward') ? c.prev('li') : c.next('li');
        if(!next.length) {
            next = $(this).hasClass('backward') ? p.find('li:last-child') : p.find('li:first-child') ;
        }
        c.removeClass('current');
        next.addClass('current');

        issip = true;
        next.show();
        c.fadeOut('normal', function() {
            issip = false;
        });
    });
    (function slideshow(f) {
        !f && !issip ? $('#slideshow .forward').click() : null;
        window.setTimeout(slideshow, 10000);
    })(1);

    $('.settlement-section .gallery-wrapper .gallery').each(function() {
        var that = $(this);
        that.find('.main img').load(function() {
            $(this).fadeTo('slow', 1);
        });
        that.find('ul li a').click(function() {
            m = that.find('.main img');
            h = this.href.replace(location.protocol + '//' + location.host, '');
            if(m.attr('src') != h) {
                that.find('.main img').fadeTo('slow', 0.1, function() { $(this).attr('src', h); });
                that.find('.current').removeClass('current');
                $(this).parent().addClass('current');
            }
            return false;
        });
    });

   $('#carousel .photos ul').jcarousel({
    	wrap: 'circular',
        scroll: 1,
        itemFirstInCallback: function(carousel, item, idx, stat) {
            $('#carousel .photos ul li a').fadeTo('fast', 0.5);
            (needle = $(item).next().find('a')).stop().fadeTo('fast', 1);
            $('#carousel .main img').attr('src', needle.attr('href'));
        },
        initCallback: function (carousel) {
            $('#carousel .photos ul li a').bind('click', function() {
                carousel.scroll($(this).parent().index());
                return false;
            });
            $('#carousel .main a, #carousel .zoom').click(function() {
                $('#carousel-big').each(function() {
                    if($.browser.msie) {
                        $(this).find('.background').keydown(hide_float_elements)
                        $(this).find('.carousel').keydown(hide_float_elements).each(function() {
                            $(this).css('left', ($(window).width() - 900 ) / 2);
                            $(this).css('top', 200);
                        });
                    }
                    $(this).fadeIn();
                    $(this).focus();
                });
                if(!$('#carousel-big .carousel .photos ul').data('jcarousel')) {
                    $('#carousel-big .carousel .photos ul').jcarousel({
                        wrap: 'circular',
                        scroll: 1,
                        itemFirstInCallback: function(carousel, item, idx, stat) {
                            if(stat == 'init') { return; }
                            c = (stat == 'prev' ? $(item).next().next().next() : $(item).next()).find('a').fadeTo('fast', 0.5);
                            f = $('#carousel .photos ul').data('jcarousel').first;
                            nc = c.attr('className');
                            $('#carousel .photos ul').each(function() {
                                f = $(this).data('jcarousel').first;
                                c = $(this).find('li').eq(f);
                                while(c.find('a').attr('className') != nc) {
                                    n = c[stat]();
                                    if(n.length == 0) {
                                        c = c.parent().find('li:' + (stat == 'prev' ? 'last':'first'));
                                    } else {
                                        c = n;
                                    }
                                }
                                $('#carousel .photos ul').data('jcarousel').scroll(c[stat]().index());
                            });
                            $(item).next().next().find('a').each(function() {
                                $(this).fadeTo('fast', 1);
                                $('#carousel-big .main img').attr('src', this.href);
                            });
                        },
                        initCallback: function (carousel) {
                            $('#carousel-big .photos ul li a').bind('click', function() {
                                return false;
                            });
                        }
                    });
                    if ($.browser.safari) {
                        $('#carousel-big .carousel .photos ul').data('jcarousel').setup();
                    }
                }
                $('#carousel .photos ul').each(function() {
                    c = $(this).find('li').eq($(this).data('jcarousel').first).find('a').attr('className');
                    i = $('#carousel-big .carousel .photos ul li a.' + c).parent().prev().index();
                    $('#carousel-big .carousel .photos ul').data('jcarousel').scroll(i);
                });
            });
        }
    });

    $('#carousel-big .carousel .close').click(function() {
        $('#carousel-big').fadeOut();
    });


    $('#city-selector').click(function() {
        $('#cities .content').each(function() {
            t = $(this);
            t.hasClass('expanded') ? t.removeClass('expanded') : t.addClass('expanded');
        });
    });

    $('#city-selector').mouseleave(function() {
        $(this).find('.content').removeClass('expanded');
    });

    $('#cities ul li a').click(function() {
        $.cookie('city', $(this).parent().attr('id').replace('city_', ''), { expires: 1000, path: '/' })
        window.location.href = window.location.href;
    });

    $('.settlement-section .big-map .close,.settlement-section .big-plan .close').click(function() {
        hide_float_elements();
    });

    $(document).keydown(function(e) { if(e.keyCode == 27) { hide_float_elements(); }});
    $('.settlement-section .big-map .background,.settlement-section .big-plan .background,#carousel-big .background').click(hide_float_elements);

    function hide_float_elements() {
        $('.settlement-section .big-map,#carousel-big,.settlement-section .big-plan')[$.browser.msie ? 'hide' : 'fadeOut']();
    }

    $('.settlement-section .plan a,.settlement-section .plan img').click(function() {
        $(this).parents('.settlement-section').find('.big-plan').each(function() {
            if($.browser.msie) {
                $(this).find('.background').keydown(hide_float_elements)
                $(this).find('.map').keydown(hide_float_elements).each(function() {
                    $(this).css('left', ($(window).width() - 800 ) / 2);
                    $(this).css('top', 200);
                });
            }
            $(this).fadeIn();
            $(this).focus();
        });
    });


    $('.settlement-section .location a,.settlement-section .location img').click(function() {
        if (GBrowserIsCompatible()) {

            $(this).parents('.settlement-section').find('.big-map').each(function() {
                if($.browser.msie) {
                    $(this).find('.background').keydown(hide_float_elements)
                    $(this).find('.map').keydown(hide_float_elements).each(function() {
                        $(this).css('left', ($(window).width() - 900 ) / 2);
                        $(this).css('top', 200);
                    });
                }
                $(this).fadeIn();
                $(this).focus();
            });
            md = $('#settlement_map');
            var map = new GMap2(md[0]);
            p = md.attr('rel').split(';');
            m = p[0].split(',');
            c = p[1].split(',');
            map.setCenter(new GLatLng(c[0], c[1]), parseInt(p[2]));
            map.setUIToDefault();

            i = new GIcon(G_DEFAULT_ICON);
            i.image = "/images/design/marker_yellowH.png";
            marker = new GMarker(new GLatLng(m[0], m[1]), { icon : i });
            map.addOverlay(marker);
        }
    });

    function slidefacts() {
        p = $('#company .facts ul');
        c = p.find('li:visible');
        next = c.next('li');
        if(!next.length) {
            next = p.find('li:first-child') ;
        }



        c.fadeOut('normal', function() {
            c.removeClass('current');
            next.addClass('current');
            next.fadeIn();
        });
        window.setTimeout(slidefacts, 10000);
    };
    window.setTimeout(slidefacts, 10000);


        ax_form = function (that) {
            $(that).ajaxForm({
                 url:  $(that).attr('action')
                ,dataType:  'json'
                ,success: function(r, s) {
                    if(r.errors) {
                        $(that).find('.error span').html('');
                        for(e = 0; e < r.errors.length; e++) {
                            f = r.errors[e].split('.');
                            $(that).find('[name="' + f[0] + '"]').parents('dl').children('.error').each(function() {
                                $(this).children('span').html($(this).children('.error-list').children('.' + f[1]).text());
                            });
                        }
                    } else {
                        if(r.location) {
                            location.href = r.location;
                        }
                    }
                }
            });
        };

    $('.contact-form .submit').click(function() {
        $(this).parents('form').submit();
    });

    $('.contact-form form').each(function() {
        defs = { name: 'Ваше имя', email: 'E-mail', message: 'Текст сообщения' };
        $(this).find('input,textarea').focus(function() {
            n = $(this).attr('name');
            if(defs[n] && $(this).val() == defs[n]) {
                $(this).val('');
            }
        }).focusout(function() {
            n = $(this).attr('name');
            if($(this).val() == '' && defs[n]) {
                $(this).val(defs[n]);
            }
        });
        $(this).submit(function() {
            elements = {};
            $(this).find('input,textarea').each(function() {
                n = $(this).attr('name');
                v = $(this).val();
                if(!defs[n] || v != defs[n]) {
                    elements[n] = v;
                }
            });
            var that = this;
            $.getJSON($(this).attr('action'), elements, function(r) {
                if(r.errors) {
                    $(that).find('.error span').html('');
                    for(e = 0; e < r.errors.length; e++) {
                        f = r.errors[e].split('.');
                        $(that).find('[name="' + f[0] + '"]').parents('dl').children('.error').each(function() {
                            $(this).children('span').html($(this).children('.error-list').children('.' + f[1]).text());
                        });
                    }
                } else {
                    if(r.message) {
                        $('.contact-form').fadeOut('fast', function() {
                            $(this).html(r.message).fadeIn();    
                        });


                    }
                }
            });
            return false;
        });
    });

    $('.contact-form .captcha-block-wrapper img').click(function() {
        t = $(this);
        t.attr('src', t.attr('src').split('?')[0] + '?r=' + Math.random());
    })

});
