jQuery(document).ready(function() {
    var isIE = jQuery.browser.msie;

    // Menu animation
    jQuery('#menu li').hover(function(){jQuery(this).find('.spotlight').fadeIn();}, function(){jQuery(this).find('.spotlight').fadeOut();});

    // Initialize fancybox galery if needed
    jQuery('a.fancy').fancybox({'overlayColor'	:	'#000', 'autoScale':false, 'centerOnScroll':true, 'onStart':function(){expandFfancy();}, 'onClosed':function(){shrinkFfancy();}});


    function expandFfancy(){
        jQuery('#body').height(1400);
    }

    function shrinkFfancy(){
        jQuery('#body').css('height', 'auto');
        jQuery('#background').height(jQuery('#container').height());
    }

    // Gallery

    var slides = [];
    var slideInterval = 5000;
    var animDuration = 1000;
    var slideCount = jQuery('#galleryList li').size();
    var currentSlide = 0;
    var timerId = null;
    var isAnimating = 0;

    function galleryInit(){

        //  Large slide
        slides = [];
        currentSlide = 0;
        slideCount = jQuery("#galleryList li").size();
        clearTimeout(timerId);// = null;

        if(slideCount){

            jQuery("#galleryList li").each(function() {
                slides.push(jQuery(this).html())
            });

            //  Remove unwanted pics from the list
            jQuery("#galleryList li:not(:first)").remove();

            // Set caption txt
            jQuery("#caption").html(jQuery("#galleryList li:first img").attr('alt'));

            // Show the caption
            jQuery("#caption").animate({marginTop: '-30px'}, {duration: 500, easing: 'jswing', complete: function(){
                isAnimating = 0;
                //  If more than one pictures, create buttons for selecting slides
                if(slideCount>1){

                    timerId = setTimeout(function(){changeSlide(1, 1);}, slideInterval );

                }
            }});
        }
    }

    galleryInit();

    function changeSlide(changeTo, direction){

        if(!isAnimating){

            isAnimating = 1;

            if(direction==1){
                jQuery("#galleryList").append('<li>' + slides[changeTo] + '</li>');
                var animateMargin = '-346px';
            }else{
                jQuery("#galleryList").prepend('<li>' + slides[changeTo] + '</li>').css('marginLeft', '-346px');
                var animateMargin = '0px';
            }

            jQuery("#caption").animate({marginTop: '0px'}, 300, function(){

                jQuery("#galleryList").animate({marginLeft: animateMargin}, 1000, function(){

                    // Remove hidden slides and adjust the margin
                    if(direction==1){
                        jQuery("#galleryList li:first").remove();
                        jQuery("#galleryList").css('marginLeft', 0);
                    }else{
                        jQuery("#galleryList li:last").remove();
                    }

                    //alert(jQuery('#galleryList li').size());

                    // Set caption txt
                    jQuery("#caption").html(jQuery("#galleryList li:first img").attr('alt'));

                    // Show the caption
                    jQuery("#caption").animate({marginTop: '-30px'}, {duration: 500, easing: 'jswing', complete: function(){

                        currentSlide = changeTo;

                        if(currentSlide==(slideCount-1)){
                            changeTo=0;
                        }else{changeTo++;}
                        //alert(changeTo);
                        clearTimeout(timerId);
                        timerId = setTimeout(function(){changeSlide(changeTo, 1);}, slideInterval );

                        isAnimating = 0;

                    }});
                });

            });
        }
    }

    jQuery('#leftArrow').live('click', function(){

        var changeTo;
        clearTimeout(timerId);

        if(currentSlide==0){
            changeTo = slideCount-1;
        }else{
            changeTo = currentSlide-1;
        }

        changeSlide(changeTo, -1);

    });

    jQuery('#rightArrow').live('click', function(){

        var changeTo;
        clearTimeout(timerId);

        if(currentSlide==(slideCount-1)){
            changeTo = 0;
        }else{
            changeTo = currentSlide+1;
        }

        changeSlide(changeTo, 1);
    });



    //  Menu clicked & ajax loading

    var currentPage = 'esileht';

    jQuery('#menu li, #shortcuts a, #submenu a, .ajax-link').live('click', function(){

        var clicked = jQuery(this);
        var href = clicked.find('a').attr('href');

        if(href==null){
            href = clicked.attr('href');
        }
        //alert(jQuery('#txtContainer').height());

        // Fix the container heigt at what it is right now
        jQuery('#txtContainer').height(jQuery('#txtContainer').height());

        // Fade the loading icon in
        jQuery('#loader').fadeIn(200);

        // Fade container out and load new content from a href attribute
        jQuery('#loadContainer').fadeOut(500, function(){
            jQuery('#loadContainer').load(href + ' #loadContainer', function(){

                jQuery('#loadContainer').fadeIn(500, function(){
                    // Fade the loading icon out
                    jQuery('#loader').fadeOut(200);

                    //jQuery('#galleria').galleria();

                    // Animate the container height to show all the content also modify #background height to fit
                    jQuery("#txtContainer").animate({height: jQuery('#loadContainer').height()}, 400, function(){resizeBackground();});

                    jQuery('#loadContainer a.fancy').fancybox({'overlayColor':'#000', 'autoScale':false, 'onStart':function(){expandFfancy();}, 'onCleanup':function(){shrinkFfancy();}});

                    // Initialize any galleries on page (if any)
                    galleryInit();
                    jQuery('#slideshow').xsGallery();

                    // Initialize fancybox gallery if needed
                    //jQuery('#galleria a.fancy').fancybox({'overlayColor':'#000', 'autoScale':true, 'centerOnScroll':true});


                    if(clicked.attr('id') == 'kontakt'){
                        initializeGmap();
                    }
                });

            });
        });

        currentPage = clicked.attr('id');

        return false;

    });



    // Background switcher


    var backgrounds = ['1.jpg', '12.jpg', '11.jpg', '5.jpg'];
    var backAnimation = 1500; // Animation duration
    var backSwitchInterval = 7000;  // Background switch interval
    var backInterval = null;

    function resizeBackground(){

        jQuery('#background').height(jQuery('#container').height());

    }

    function switchBackground(switchTo){

        clearInterval(backInterval);

        var switchNext = (switchTo==(backgrounds.length-1))? 0 : switchTo+1;

        var randomUrl = '';

        if(isIE){
            randomUrl = '?random=' + (new Date()).getTime();
        }

        // Insert preloaded image after it finishes loading
        jQuery('<img />').attr('src', siteurl +'/wp-content/themes/saareerek/images/back/'+ backgrounds[switchTo] + randomUrl).load(function(){

        if(jQuery('#background').is(':hidden')){

            resizeBackground();

            jQuery('#background').css('background-image', 'url('+ siteurl +'/wp-content/themes/saareerek/images/back/'+ backgrounds[switchTo] +')').fadeIn(backAnimation, function(){

                backInterval = setInterval(function() {switchBackground(switchNext);}, backSwitchInterval);

            });

        }else{
            jQuery('html').css('background-image', 'url('+ siteurl +'/wp-content/themes/saareerek/images/back/'+ backgrounds[switchTo] +')');
            jQuery('#background').fadeOut(backAnimation, function(){

                backInterval = setInterval(function() {switchBackground(switchNext);}, backSwitchInterval);

            });
        }

        });

    }

    backInterval = setInterval(function() {switchBackground(1);}, backSwitchInterval);

    // Tehtud tööd galerii
    jQuery('#slideshow').xsGallery();

    if(jQuery('#mapWrapper').size()>0){
        initializeGmap();
    }

    var randomUrl = '';
    if(isIE){
        randomUrl = '?random=' + (new Date()).getTime();
    }

    // Insert preloaded image after it finishes loading
    jQuery('<img />').attr('src', siteurl +'/wp-content/themes/saareerek/images/logo.png' + randomUrl).load(function(){
        // Logo animation
        jQuery('#logo').animate({marginTop: "0px"},{duration: 1000, easing: 'easeOutBounce'});
    });

});

