(function($){
    var $images = null;
    var $activeImage = null;
    var margins = {top:'0',left:'0'}

    var setBodyHeight = function(){
        $header = $('.frontpage div.page div.head');
        $body = $('.frontpage div.page div.body');
        if($('.frontpage .content').is(':hidden') || $(window).height() > parseInt($body.css('min-height'))){
            var headHeight = 0;
            if($header.is(':visible')){
                headHeight = $header.height();
            }
            $body.height($(window).height()-headHeight).css('min-height','0');//.css('overflow','hidden');
        }

        var contentHeight = $(window).height()-$('.head').height()-80;
        $('.frontpage div.page div.body div.main div.content').height(contentHeight);
    }

    var loadImages = function(callback){
        var $loader = $('<img class="ajax-loader2" width="128" height="15" alt="Laster bilder" />').hide().appendTo('body');
        $('.frontpage div.page div.body .main').fadeOut('normal',function(){
            $loader.load(function(){
                $(this).fadeIn('fast',function(){
                    $('.image-mode .frontpage_image a.image').each(function(){
                        var $anchor = $(this);
                        var options = $.parseJSON($anchor.attr('rel'));
                        var src = $anchor.attr('href');
                        var $image = $('<img class="'+options['class']+'" width="'+options.width+'" height="'+options.height+'" alt="" />');
                        $image.load(function(){
                            $anchor.replaceWith($(this));
                            if(this === $('.image-mode .frontpage_image:last img').get(0)){
                                $images = $('.image-mode .frontpage_image');
                                $activeImage = $('.image-mode .frontpage_image:first');
                                $('.image-mode .frontpage_image:first').removeClass('hidden');
                                $('.image-mode .frontpage_image:not(:first)').removeClass('hidden').hide();
                                $('.image-mode .frontpage_image').each(function(i){
                                    var $imageInfo = $(this).find('.image-info').appendTo('.image-mode').removeClass('hidden').hide();
                                    $(this).data('image-info',$imageInfo);
                                });
                                //$('.image-mode .image-info').removeClass('hidden').hide();

                                $('.image-mode').removeClass('hidden');
                                $('.frontpage').css('background','');
                                callback();
                                $loader.remove();

                                $(window).resize(function(){
                                    setBodyHeight();
                                    $activeImage
                                        .setImageBorder()
                                        .centerImage()
                                        .positionImageText();
                                     margins = $activeImage.getMaxPosition();
                                });
                            }
                        });
                        $image.attr('src',src);
                    });
                });
            });
            $loader.attr('src','/css/elm/ajax-loader2.gif');
        });
    }

    var activateImageMode = function(e){
        e.preventDefault();
        $('body, .page .body').css('overflow','hidden');

        setBodyHeight();

        $activeImage
            .setImageBorder()
            .centerImage()
            .positionImageText();


        $('.body').addKeyNavigation();
        $('.image-mode .img_nav').addBorderScrolling();

        margins = $activeImage.getMaxPosition();


        $images.draggable({
            containment: 'parent',
            delay:10,
            time:{start:0,stop:0},
            start:function(e,ui){
                $(this).stop();
                $(this).data('start',new Date().getTime());
                $('.img_nav').hide();
            },
            stop:function(e,ui){
                var timespan = (new Date().getTime() - $(this).data('start'));
                var top = ui.position.top + Math.round((ui.position.top-ui.originalPosition.top)/(timespan/100));
                var left = ui.position.left + Math.round((ui.position.left-ui.originalPosition.left)/(timespan/100));
                $('.img_nav').show();
                if(timespan < 500){
                    if(top < 0){
                        top = 0;
                    }

                    if(top > margins.top){
                        top = margins.top;
                    }

                    if(left < 0){
                        left = 0;
                    }

                    if(left > margins.left){
                        left = margins.left;
                    }

                    $(this).stop().animate({
                        top:top,
                        left:left
                    },1000-timespan,'easeOutQuad');
                }
            }
        });

        $('.image-mode .image-info').draggable({
            containment: '.body',
            cursor: 'move',
            delay:100
        });

        $images.mousedown(function(){
             $(this).stop();
        });

        $('.img_nav').show();
        $(this).unbind('click');

        $('.frontpage div.page div.body .main:first').fadeOut('normal',function(){
            $activeImage
                .showStars()
                .positionInfo()
                .showInfo(true);
            //$activeImage.delay(4000,'hidetools').activateHideToolsOnInactive();
            $('.image-mode .prev, .image-mode .next, .image-mode .back').fadeTo(200,0.75);
            $('.image-mode .prev, .image-mode .next, .image-mode .back').hover(
                function(){
                    $(this).stop(true,true).fadeTo(200,1);
                    $(this).css('z-index','10');
                },
                function(){
                    $(this).stop(true,true).fadeTo(200,0.75);
                    $(this).css('z-index','');
                }
            );
        });

        $(window).addImageScroll();
    }

    var inactivateImageMode = function(e){
        e.preventDefault();
        $(window).unbind('mousewheel');
        $images.disableHideToolsOnInactive();
        $images.draggable('destroy');
        $activeImage.animateToCenter();
        $('body').css('overflow','visible');
        $('.image-mode .prev, .image-mode .next, .image-mode .back, .image-mode .star, .image-mode .text').fadeOut();
        $('.frontpage div.page div.body .main').fadeIn();
        $('.opening-hours').click(activateImageMode);
    };


    $.fn.fadeTo = function(speed,to,callback){
        return $(this).each(function(){
            var from = $(this).css('opacity');
            if(from == undefined){
                from = 1;
            }
             if(!$.browser.msie || ($.browser.msie && to > from)){
                 $(this).animate({opacity: to}, speed, function() {
                    if (to > 0 && $.browser.msie)
                        this.style.removeAttribute('filter');

                    if ($.isFunction(callback))
                        callback();
                });
             }
        });

    }

    $.fn.addImageScroll = function(){
        var thread;
        var onStop = function(){
            $('.img_nav').show();
        };

        
        var scrollImage = function(e,delta){
            e.preventDefault();
            $images.stop();
            var top = parseInt($activeImage.css('top'))+parseInt(delta*10);
            $('.img_nav').hide();
            if(delta > 0){
                if(top <= parseInt(margins.top)){
                    $activeImage.css('top',top+'px');
                }
            }else{
                if(top > 0){
                    $activeImage.css('top',top+'px');
                }
            }
            clearTimeout(thread);
            thread = setTimeout(onStop,500);
        };
        return $(this).each(function(){
            $(this).mousewheel(scrollImage);
        });
    }

    $.fn.addBorderScrolling = function(){
        var thread,offset,left,top, speedX, speedY;

        var animateImage = function(delay,position){
           var moveImage = function(){
               top += position.top;
               left += position.left;

               delay += 10;

               if(left < 0){
                   left = 0;
                   $('.nav_right_right').hide();
               }

               if(left > margins.left){
                   left = margins.left;
                   $('.nav_left_left').hide();
               }

               if(top > margins.top){
                   top = margins.top;
                   $('.nav_top_top').hide();
               }

               if(top < 0){
                   $('.nav_bottom_bottom').hide();
                   top = 0;
               }

               $activeImage.css({
                   top:top+'px',
                   left:left+'px'
               });

               
           }
           clearInterval(thread);
           thread = setInterval(moveImage,delay);
        }

        $(this).mouseenter(function(){
            $images.stop();
        });

        $(this).mousemove($.throttle(180,true,function(e){
            top = parseInt($activeImage.css('top'));
            left = parseInt($activeImage.css('left'));
            var speed = 20;
            var distance = {top:0,left:0}
            var width = parseInt($(this).width());
            var height = parseInt($(this).height());
            var divident = 10;
            offset = $(this).offset();
            speedX = e.pageX-offset.left;
            speedY = e.pageY-offset.top;
            $('.img_nav').show();
            
            if($(this).hasClass('nav_left_left')){
                distance.left = Math.round((width-speedX)/divident);
                distance.top = 0;
            }
            if($(this).hasClass('nav_top_left')){
                distance.left = Math.round((width-speedX)/divident);
                distance.top = Math.round((height-speedY)/divident);
            }
            if($(this).hasClass('nav_top_top')){
                distance.left = 0;
                distance.top = Math.round((height-speedY)/divident);
            }
            if($(this).hasClass('nav_bottom_left')){
                distance.left = Math.round((width-speedX)/divident);
                distance.top = -Math.round(speedY/divident);
            }
            if($(this).hasClass('nav_bottom_bottom')){
               distance.left = 0;
               distance.top = -Math.round((speedY)/divident);
            }
            if($(this).hasClass('nav_top_right')){
               distance.left = -Math.round(speedX/divident);
               distance.top = Math.round((height-speedY)/divident);
            }
            if($(this).hasClass('nav_right_right')){
               distance.left = -Math.round(speedX/divident);
               distance.top = 0;
            }
            if($(this).hasClass('nav_bottom_right')){
               distance.left = -Math.round(speedX/divident);
               distance.top = -Math.round(speedY/divident);
            }
            animateImage(speed,distance);
        }));

        $(this).mouseleave(function(e){
            clearInterval(thread);
        });
        
        return $(this);
    }

    $.fn.activateHideToolsOnInactive = function(){
        return $(this).each(function(){
            var $image = $(this);
            
            var onmousestop = function() {
                $image.find('.star, .text').fadeOut(1000);
                $('.image-mode .next, .image-mode .prev, .image-mode .back').fadeOut(1000);
            };

            var thread = setTimeout(onmousestop, 6000);
            $image.data('thread',thread);

            
            $(this).mousemove(function(){
                $(this).find('.star').fadeIn('fast');
                $('.image-mode .next, .image-mode .prev, .image-mode .back').fadeIn('fast');
                clearTimeout(thread);
                thread = setTimeout(onmousestop, 6000);
            });
        });
    }

    $.fn.disableHideToolsOnInactive = function(){
        return $(this).each(function(){
            if($(this).data('thread') != undefined){
                 clearTimeout($(this).data('thread'));
            }
            $(this).unbind('mousemove');
        });
    }

    $.fn.animateToCenter = function(){
        var centerPosition = {};
        return $(this).each(function(){
            centerPosition = $(this).getCenterPosition();
            $(this).animate({top:(centerPosition.top*2)+'px',left:centerPosition.left+'px'},500);

        });
    }

    $.fn.positionInfo = function(){
        return $(this).each(function(){
            var $imageInfo = $(this).data('image-info');
            var defaultPosition = $imageInfo.data('default-position');
            if(defaultPosition == undefined){
                $imageInfo.data('default-position',{top:'167px',left:'150px'});
            }else{
                $imageInfo.css({
                    top:defaultPosition.top,
                    left:defaultPosition.left
                });
            }
        });
    }

    $.fn.showInfo = function(open){
        var minHeight = 15;
        var minWidth = 150;
        var width,height;
        if(open === undefined){
            open = false;
        }
        return $(this).each(function(){
            var $imageInfo = $(this).data('image-info');
            if($imageInfo.data('default-height') == undefined){
                $imageInfo.data('default-height',$imageInfo.height());
                $imageInfo.data('default-width',$imageInfo.width());
                
            }

            var openInfo = function($imageInfo){
                $imageInfo.find('h2 span').text('+');
                $imageInfo.stop().animate({
                    height:$imageInfo.data('default-height'),
                    width:$imageInfo.data('default-width')
                },400,'easeOutQuad');

                $imageInfo.data('open',true);
            }

            var closeInfo = function($imageInfo){
                 $imageInfo.find('h2 span').html('&minus;');
                 $imageInfo.stop().animate({
                    height:minHeight,
                    width:minWidth
                },400,'easeOutQuad');
                $imageInfo.data('open',false);
            }

            $imageInfo.data('open',false);
            $imageInfo.height(minHeight);
            $imageInfo.width(minWidth);

            $imageInfo.click(function(e){
                if($imageInfo.data('open')){
                    closeInfo($(this));
                }else{
                    openInfo($(this));
                }
            });


            
            $imageInfo.fadeIn(1000,function(){
                /*if(open){
                    openInfo();
                }*/
            });
            
        });
    }

    $.fn.hideInfo = function(){
        return $(this).each(function(){
            $(this).data('image-info').fadeOut(200);
        });
    }

    $.fn.hideStars = function(){
        $(this).find('.image_point .star, .image_point .text').hide();
        return $(this);
    }

    $.fn.showStars = function(){
        var $next;
        var showStar = function($imagePoint){
            $next = $imagePoint.next();
            $imagePoint.find('.star').fadeIn('fast',function(){
                if($next.length > 0){
                    showStar($next);
                }
            });
        }
        return $(this).each(function(){
            showStar($(this).find('.image_point:first'));
        });
    }

    $.fn.setImageBorder = function(){
        var imageWidth = 0;
        var imageHeight = 0;
        var windowWidth = 0;
        var windowHeight = 0;
        var borderWidth = 0;
        var borderHeight = 0;
        return $(this).each(function(){
            imageWidth = $(this).width();
            imageHeight = $(this).height();
            windowWidth = $(window).width();
            windowHeight = $(window).height()-$('.frontpage div.page div.head').height();
            borderWidth = (2*imageWidth)-windowWidth;
            borderHeight = (2*imageHeight)-windowHeight;
            $('.frontpage .border')
                .width(borderWidth)
                .height(borderHeight)
                .css({
                    position:'absolute',
                    left:'50%',
                    top:'50%',
                    marginLeft:'-'+parseInt(borderWidth/2)+'px',
                    marginTop:'-'+parseInt(borderHeight/2)+'px'
                }); 
        });
    }

    $.fn.getCenterPosition = function(){
        var top = 0;
        var left = 0;
        $(this).each(function(){
            top = parseInt(($(this).closest('.border').height()/2)-($(this).height()/2));
            left = parseInt(($(this).closest('.border').width()/2)-($(this).width()/2));
        });
        return {top:top,left:left}
    }

    $.fn.centerImage = function(){
        var position;
        return $(this).each(function(){
            position = $(this).getCenterPosition();
            $(this).css({
                top:(position.top*2)+'px',
                left:position.left+'px',
                marginLeft:'0'
            })
        });
    }

    $.fn.getMaxPosition = function(){
        var position;
        $(this).each(function(){
            position = $(this).getCenterPosition();
        });
        return {top:(position.top*2),left:(position.left*2)}
    }

    $.fn.moveToViewport = function(){
        var offset, width, height, bottom, right;
        var position;
        var windowWidth = $(window).width();
        var windowHeight = $(window).height()-parseInt($('.frontpage .head').height());
        return $(this).each(function(){
            position = {};
            offset = $(this).offset();
            width = parseInt($(this).find('.text').width())+parseInt($(this).find('.text').css('left'))+20;
            height = parseInt($(this).find('.text').height())+parseInt($(this).find('.text').css('top'))+20;
            right = parseInt(offset.left)+width;
            bottom = parseInt(offset.top)+height;
            if(bottom > windowHeight){
                position.top = parseInt($activeImage.css('top'))-height;
                if(position.top < 0){
                    position.top = 0;
                }
            }

            if(right > windowWidth){
                position.left = parseInt($activeImage.css('left'))-width;
                if(position.left < 0){
                    position.left = 0;
                }
            }

            $activeImage.animate(position,400,'easeOutQuad');
        });
    }

    $.fn.swapImages = function($next){
        $(this).each(function(){
            $(this).hideInfo()
            $(this).animate(
                {opacity:'0'},
                400,
                'easeOutQuad',
                function(){
                    $(this).hide();
                    $(this).disableHideToolsOnInactive();
                    $next
                        .setImageBorder()
                        .centerImage()
                        .positionInfo()
                        .hideStars()
                        .css({opacity:'0'})
                        .show()
                        .animate(
                            {opacity:'1'},
                            400,
                            'easeOutQuad',
                            function(){
                                $(this).positionImageText();
                                $(this).showInfo();
                                $(this).showStars();
                            }
                        );
                    margins = $next.getMaxPosition();
                }
            );
        });
        return $next;
    }

    $.fn.positionImageText = function(){
        return $(this).each(function(){
            var maxBottom = parseInt($(this).height());
            var maxRight = parseInt($(this).width());
            $(this).find('.image_point').each(function(){
                var $imagePoint = $(this);
                var $textBox = $(this).find('.text');
                var positionBottom = parseInt($imagePoint.css('top'))+parseInt($textBox.css('top'))+parseInt($textBox.height());
                var positionRight = parseInt($imagePoint.css('left'))+parseInt($textBox.css('left'))+parseInt($textBox.width());
                if(positionBottom > maxBottom){
                    $(this).addClass('flip-horizontal');
                }
                if(positionRight > maxRight){
                    $(this).addClass('flip-vertical');
                }
            });
        });
    }

    $.fn.addKeyNavigation = function(){
        var delta = 125;
        return $(this).each(function(){
            $(document).keypress(function(e){
                var top = parseInt($activeImage.css('top'));
                var left = parseInt($activeImage.css('left'));
                var key = e.which;
                if(key == 0){key = e.keyCode};
                switch(key){
                    case 37: //left
                    case 100: //left
                         left += delta;
                         if((left+delta) > margins.left){
                            left = margins.left;
                         }
                         break;
                    case 38: //up
                    case 104: //up
                         top += delta;
                         if((top+delta) > margins.top){
                            top = margins.top;
                         }
                         break;
                    case 39: //right
                    case 102: //right
                        left -= delta;
                        if((left-delta) < 0){
                            left = 0;
                        }
                        break;
                    case 40: //down
                    case 98: //down
                        top -= delta;
                        if((top-delta) < 0){
                            top = 0;
                        }
                        break;
                   case 99: //page down
                   case 34: //page down
                       top = 0;
                       break;
                   case 105: //page up
                   case 33: //page down
                       top = margins.top;
                       break;
                   case 36: //home
                   case 103: //home
                       left = margins.left;
                       break;
                   case 35: //end
                   case 97: //end
                       left = 0;
                       break;
                   case 101: //center
                       top = margins.top;
                       left = margins.left/2;
                       break;
                }
                $activeImage.stop().animate(
                    {top:top,left:left},
                    500,
                    'easeOutQuad'
                );
            });
        });
    }

    var initImageMode = function(){
        if($('.image-mode').is('div')){
            $('.image-mode .image_point .hidden').removeClass('hidden').hide();
            $('.image-mode .next, .image-mode .prev').removeClass('hidden').css('opacity',0);
            $('.img_nav').removeClass('hidden');

            setBodyHeight();


            $(window).resize(setBodyHeight);

            $('.image-mode .image_point .star').data('open',false);

            $('.image-mode .image_point .star').click(function(){
                $('.image-mode .image_point .star')
                    .not(this)
                    .data('open',false)
                    .css('z-index','')
                    .siblings('.text')
                    .hide();

                if($(this).data('open')){
                    $(this).parent().css('z-index','');
                    $(this).data('open',false);
                    $(this).parent()
                        .find('.text')
                            .stop(true,true)
                            .fadeOut();
                }else{
                    $(this).parent().css('z-index','10');
                    $(this).data('open',true);
                    $(this).parent()
                        .moveToViewport()
                        .find('.text')
                            .stop(true,true)
                            .fadeIn();
                }
            });
            $('.frontpage .gallery .banner').click(function(e){
                e.preventDefault();
                loadImages(function(){
                    activateImageMode(e);
                });
            });

            if(location.href.indexOf('galleri') > 0){
                $('.frontpage .gallery .banner').trigger('click');
            }

            $('.image-mode .next').click(function(e){
                e.preventDefault();
                var $next;
                if($activeImage.next().length > 0){
                    $next = $activeImage.next();
                }else{
                    $next = $('.image-mode .frontpage_image:first');
                }
                $activeImage = $activeImage.swapImages($next);
            });

            $('.image-mode .prev').click(function(e){
                e.preventDefault();
                var $prev;
                if($activeImage.prev().length > 0){
                     $prev = $activeImage.prev();
                }else{
                    $prev = $('.image-mode .frontpage_image:last');
                }

                $activeImage = $activeImage.swapImages($prev);
            });

            $('.image-mode .back').click(inactivateImageMode);
        }
    }

    $(document).ready(function(e){
        setBodyHeight();
        if(!($.browser.msie &&  parseInt($.browser.version) == 6)){
            initImageMode();
        }
    });
})(jQuery);