if(history.pushState != undefined){
    try {
        var evt = document.createEvent("PopStateEvent");
        evt.initPopStateEvent("popstate", false, false, {});
        window.dispatchEvent(evt);
    }catch(e){

    };
}

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
    def: 'easeOutQuad',
    swing: function (x, t, b, c, d) {
        return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
    },
    easeInQuad: function (x, t, b, c, d) {
        return c*(t/=d)*t + b;
    },
    easeOutQuad: function (x, t, b, c, d) {
        return -c *(t/=d)*(t-2) + b;
    },
    easeInOutQuad: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t + b;
        return -c/2 * ((--t)*(t-2) - 1) + b;
    },
    easeInCubic: function (x, t, b, c, d) {
        return c*(t/=d)*t*t + b;
    },
    easeOutCubic: function (x, t, b, c, d) {
        return c*((t=t/d-1)*t*t + 1) + b;
    },
    easeInOutCubic: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t*t + b;
        return c/2*((t-=2)*t*t + 2) + b;
    },
    easeInQuart: function (x, t, b, c, d) {
        return c*(t/=d)*t*t*t + b;
    },
    easeOutQuart: function (x, t, b, c, d) {
        return -c * ((t=t/d-1)*t*t*t - 1) + b;
    },
    easeInOutQuart: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
        return -c/2 * ((t-=2)*t*t*t - 2) + b;
    },
    easeInQuint: function (x, t, b, c, d) {
        return c*(t/=d)*t*t*t*t + b;
    },
    easeOutQuint: function (x, t, b, c, d) {
        return c*((t=t/d-1)*t*t*t*t + 1) + b;
    },
    easeInOutQuint: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
        return c/2*((t-=2)*t*t*t*t + 2) + b;
    },
    easeInSine: function (x, t, b, c, d) {
        return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
    },
    easeOutSine: function (x, t, b, c, d) {
        return c * Math.sin(t/d * (Math.PI/2)) + b;
    },
    easeInOutSine: function (x, t, b, c, d) {
        return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
    },
    easeInExpo: function (x, t, b, c, d) {
        return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
    },
    easeOutExpo: function (x, t, b, c, d) {
        return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
    },
    easeInOutExpo: function (x, t, b, c, d) {
        if (t==0) return b;
        if (t==d) return b+c;
        if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
        return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
    },
    easeInCirc: function (x, t, b, c, d) {
        return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
    },
    easeOutCirc: function (x, t, b, c, d) {
        return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
    },
    easeInOutCirc: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
        return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
    },
    easeInElastic: function (x, t, b, c, d) {
        var s=1.70158;
        var p=0;
        var a=c;
        if (t==0) return b;
        if ((t/=d)==1) return b+c;
        if (!p) p=d*.3;
        if (a < Math.abs(c)) {
            a=c;
            var s=p/4;
        }
        else var s = p/(2*Math.PI) * Math.asin (c/a);
        return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
    },
    easeOutElastic: function (x, t, b, c, d) {
        var s=1.70158;
        var p=0;
        var a=c;
        if (t==0) return b;
        if ((t/=d)==1) return b+c;
        if (!p) p=d*.3;
        if (a < Math.abs(c)) {
            a=c;
            var s=p/4;
        }
        else var s = p/(2*Math.PI) * Math.asin (c/a);
        return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
    },
    easeInOutElastic: function (x, t, b, c, d) {
        var s=1.70158;
        var p=0;
        var a=c;
        if (t==0) return b;
        if ((t/=d/2)==2) return b+c;
        if (!p) p=d*(.3*1.5);
        if (a < Math.abs(c)) {
            a=c;
            var s=p/4;
        }
        else var s = p/(2*Math.PI) * Math.asin (c/a);
        if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
        return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
    },
    easeInBack: function (x, t, b, c, d, s) {
        if (s == undefined) s = 1.70158;
        return c*(t/=d)*t*((s+1)*t - s) + b;
    },
    easeOutBack: function (x, t, b, c, d, s) {
        if (s == undefined) s = 1.70158;
        return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
    },
    easeInOutBack: function (x, t, b, c, d, s) {
        if (s == undefined) s = 1.70158;
        if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
        return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
    },
    easeInBounce: function (x, t, b, c, d) {
        return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
    },
    easeOutBounce: function (x, t, b, c, d) {
        if ((t/=d) < (1/2.75)) {
            return c*(7.5625*t*t) + b;
        } else if (t < (2/2.75)) {
            return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
        } else if (t < (2.5/2.75)) {
            return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
        } else {
            return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
        }
    },
    easeInOutBounce: function (x, t, b, c, d) {
        if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
        return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
    }
});

if(history.pushState == undefined){
    history.pushState = function(state,title,url){
        window.location.hash = url;
    };
    $.support.history = {
        pushState: false
    }
}else{
    $.support.history = {
        pushState: true
    }
}

(function(c){function p(){var d,a={height:h.innerHeight,width:h.innerWidth};if(!a.height&&((d=i.compatMode)||!c.support.boxModel))d=d==="CSS1Compat"?k:i.body,a={height:d.clientHeight,width:d.clientWidth};return a}var m={},e,a,i=document,h=window,k=i.documentElement,j=c.expando;c.event.special.inview={add:function(a){m[a.guid+"-"+this[j]]={data:a,$element:c(this)}},remove:function(a){try{delete m[a.guid+"-"+this[j]]}catch(c){}}};c(h).bind("scroll resize",function(){e=a=null});setInterval(function(){var d=
c(),j,l=0;c.each(m,function(a,b){var c=b.data.selector,e=b.$element;d=d.add(c?e.find(c):e)});if(j=d.length){e=e||p();for(a=a||{top:h.pageYOffset||k.scrollTop||i.body.scrollTop,left:h.pageXOffset||k.scrollLeft||i.body.scrollLeft};l<j;l++)if(c.contains(k,d[l])){var g=c(d[l]),f={height:g.height(),width:g.width()},b=g.offset(),n=g.data("inview"),o;if(!a||!e)break;b.top+f.height>a.top&&b.top<a.top+e.height&&b.left+f.width>a.left&&b.left<a.left+e.width?(o=a.left>b.left?"right":a.left+e.width<b.left+f.width?
"left":"both",f=a.top>b.top?"bottom":a.top+e.height<b.top+f.height?"top":"both",b=o+"-"+f,(!n||n!==b)&&g.data("inview",b).trigger("inview",[!0,o,f])):n&&g.data("inview",!1).trigger("inview",[!1])}}},250)})(jQuery);

(function($,$M){
    var $loader = null;
    var updateMediaQueries = function(){
        var width = $(window).width();
        var height = $(window).height();

        $('.cell img').css('top','');
        $('.cell img').css('left','');
        $('.cell img').css('width','');
        $('.cell img').css('height','');
        $('.cell img').css('margin-top','');
        $('.cell img').css('margin-left','');
        //
        $('.cell').css('width','');
        var frameWidth = $('.frame').width();
        var cellWidth = Math.ceil($('.cell:first').width());
        var cols = Math.ceil(frameWidth/cellWidth);
        if(cols == 4){
            cols = 3;
        }

        if($.browser.mozilla){
            if(cols == 3){
                $('.cell').width(Math.floor((frameWidth/cols)));
                $('.cell:nth-child(3n-1)').width(Math.ceil((frameWidth/cols)));
            }

            $('.cell').each(function(){
                var width = $(this).width();
                var height = $(this).height();
                $(this).find('.img, .work-detail').width(width);
                $(this).find('.img, .work-detail').height(height);
            });
        }

        $('html').removeClass(function(i, c){
            var remove = '';
            var classes = $.trim(c);
            classes = classes.split(' ');
            for(var i in classes){
                if(classes[i].substring(0,3) == 'mq-'){
                    remove += classes[i]+' ';
                }
            }
            return remove;
        });
        
        if(!$M.mq('only all and (min-height: 960px)')){
            if(height >= 960){
                $('html').addClass('mq-min-height-960');
            }
        }
        if(!$M.mq('only all and (min-width: 1281px)')){
            if(width >= 1281){
                $('html').addClass('mq-min-width-1281');
            }
        }
        if(!$M.mq('only all and (max-width: 960px) and (min-width: 640px)')){
            if(width >= 640 && width <= 960){
                $('html').addClass('mq-width-640-to-960');
            }
        }
        if(!$M.mq('only all and (max-width: 640px) and (min-width: 320px)')){
            if(width >= 320 && width <= 640){
                $('html').addClass('mq-width-320-to-640');
            }
        }
        if(!$M.mq('only all and (max-width: 320px)')){
            if(width <= 320){
                $('html').addClass('mq-max-width-320');
            }
        }
    };

    $.fn.loader = function(options){
        var settings = $.extend({
            type: 'stripe',
            frames: 10,
            speed: 200
        }, options, true);

        return this.each(function(i){
            var $loader = $(this);
            var frameWidth = $(this).width();
            var currentFrame = 0;
            var end = settings.frames-1;
            var $line = $(this).find('span');
            var max = $line.width();
            var min = 5;
            var i;
            $line.width(min);

            var animateMovie = function(){
                currentFrame++;
                if(currentFrame > end){
                    currentFrame = 0;
                }
                var left = currentFrame*frameWidth;
                $loader.css('background-position',(-left)+'px 0px');
            };

            var animateStripe = function(width){
                width += 2;
                if(width > max){
                    width = min;
                }
                $line.width(width);
            };



            this.start = function(){
                var width = min;
                clearInterval(i);
                $loader.show();
                i = setInterval(function(){
                    if(settings.type == 'stripe'){
                        animateStripe(width);
                    }else{
                        animateMovie();
                    }

                },settings.speed);
            }

            this.stop = function(){
                $loader.hide();
                clearInterval(i);
            }
        });
    };

    $.fn.navigation = function(){
        return this.each(function(){
            var $nav = $(this);
            var buisy = false;
            var state = {};

            var showNewPage = function($prevPage, $newPage, dir){
                var prevDir = $prevPage.data('dir');
                var newDir = $newPage.data('dir');
                var overflow = $newPage.data('overflow');
                    overflow = (overflow == undefined)?'hidden':overflow;

                $('html').removeClass('hidden visible');

                var fly = function(){
                    var aksel = {
                        moveIn: {
                            top: '0%'
                        },
                        moveOut: {
                            top: '100%'
                        }
                    };

                    var page = {
                        moveIn: {
                            top: '0%'
                        },
                        moveOut: {
                            top: '-100%'
                        }
                    };


                    aksel.moveIn[newDir] = '0%';
                    aksel.moveOut[prevDir] = '100%';

                    page.moveIn[newDir] = '0%';
                    page.moveOut[prevDir] = '-100%';

                    if(prevDir == 'page'){
                        $prevPage.addClass('moving-out').css({
                            right: 'auto',
                            left: 0
                        }).animate({
                           left: '100%'
                        },800,function(){
                            $(this).removeClass('active').css({
                                right: '',
                                left: ''
                            }).remove();
                        });
                    }else{
                        $prevPage.find('.aksel').addClass('moving-out').animate(aksel.moveOut,600,'easeInOutQuad',function(){
                            $(this).removeClass('moving-out').removeClass('active').css({
                                top: '',
                                left: '',
                                right: ''
                            });
                        });

                        $prevPage.animate(page.moveOut,800,'easeInOutQuad',function(){
                            $(this).css({
                                top: '',
                                left: '',
                                right: ''
                            }).removeClass('active');
                            $prevPage.remove();
                        });
                    }


                    $newPage.show().delay(600).animate(page.moveIn,1000,'easeInOutQuad',function(){
                        $(this).css({
                            top: '',
                            left: '',
                            right: ''
                        }).addClass('active');
                    });

                    if($newPage.get(0)){
                        $newPage.find('.aksel').addClass('moving-in').delay(1000).animate(aksel.moveIn,600,'easeInOutQuad',function(){
                            $(this).css({
                                top: '',
                                left: '',
                                right: ''
                            }).addClass('active').removeClass('moving-in');
                            if(!$newPage.is('#home')){
                                $('html').removeClass('homepage');
                            }
                            $('html').addClass(overflow);
                            buisy = false;
                        });
                    }else{
                        buisy = false;
                    }
                };

                var slideRight = function(){
                    $prevPage.addClass('moving-out').css({
                        right: 'auto',
                        left: 0
                    }).animate({
                       left: '-100%'
                    },800,function(){
                        $(this).removeClass('active').css({
                            right: '',
                            left: ''
                        }).remove();
                    });

                    $newPage.addClass('active').css({
                        right: 'auto',
                        left: '100%'
                    }).show().animate({
                       left: '0%'
                    },800,function(){
                        $(this).addClass('active').css({
                            right: '',
                            left: ''
                        });
                        $('html').addClass(overflow);
                         buisy = false;
                    });
                };

                var slideLeft = function(){
                    $prevPage.addClass('moving-out').css({
                        right: 'auto',
                        left: 0
                    }).animate({
                       left: '100%'
                    },800,function(){
                        $(this).removeClass('active').css({
                            right: '',
                            left: ''
                        }).remove();
                    });

                    $newPage.addClass('active').css({
                        right: 'auto',
                        left: '-100%'
                    }).show().animate({
                       left: '0%'
                    },800,function(){
                        $(this).addClass('active').css({
                            right: '',
                            left: ''
                        });
                        $('html').addClass(overflow);
                         buisy = false;
                    });
                };

                if(dir){
                    if(dir == 'right'){
                        slideRight();
                    }else{
                        slideLeft();
                    }
                }else{
                    if(newDir == 'page'){
                        slideRight();
                    }else{
                        fly();
                    }
                }
                
            };

            var loadPage = function(href, par1){
                var id = href.replace(/\//gi,'');
                var $newPage = $('#'+id);
                var $prevPage = $('.page.active');
                var $content = $('.frame > .content');
                var menuHref = href.replace(/(\/.*)\/(.*)/,'$1');
                var callback = function(){};
                var dir = null;

                if(typeof par1 == 'function'){
                    callback = par1;
                }
                if(typeof par1 == 'object' && par1.dir){
                    dir = par1.dir;
                }
                $nav.find('li').removeClass('active');

                $('.menu a[href="'+menuHref+'"]').closest('li').addClass('active');
                if( $newPage.length > 0 ){
                    buisy = true;
                    showNewPage($prevPage, $newPage, dir);
                    callback();
                }else {
                    $.get(href,function(data){
                        $newPage = $(data);
                        $content.append($newPage);
                        showNewPage($prevPage, $newPage, dir);
                        callback();
                        $('.static-google-map').staticGoogleMap();
						twitterLoadAndInit();
                        $('.image-frame img').cropImage();
                        _gaq.push(['_trackPageview', href]);
                    });
                }
            };

            var hompageAnimation = function(){
                $('#home .aksel').css({
                    top: '-50%',
                    left: '-50%'
                }).animate({
                    top: '0%',
                    left: '0%'
                },400,'easeInOutQuad',function(){
                    $(this).css({
                        top: '',
                        left: ''
                    });
                });
            };

            if($('html').is('.homepage')){
                hompageAnimation();
            }

            $nav.find('a:not(.no-ajax)').click(function(e){
                e.preventDefault();
                var $a = $(this);
                var href = $(this).attr('href');
                var id = href.replace("/",'');
                var title = $(this).text();
                state.dir = '';
                if(!$('#'+id).is(':visible') && !buisy){
                    buisy = true;
                    history.pushState({id:id, title: title},null,href);
                    $(window).trigger('pushstate');
                }
            });

            $('.logo').click(function(e){
                e.preventDefault();
                var href = $(this).attr('href');
                var id = 'home';
                var title = 'Aksel Lund Svindal';
                state.dir = '';
                if(!$('#'+id).is(':visible') && !buisy){
                    buisy = true;
                    history.pushState({id:id, title: title},null,'/home');
                    $(window).trigger('pushstate');
                }
            });

            $('.js-more').live('click',function(e){
                e.preventDefault();
                var href = $(this).attr('href');
                var dir = $(this).data('dir');
                var id = href.replace(/\//gi,'');
                state.dir = '';
                if($('#'+id).get(0) == undefined){
                    var title = $(this).data('title');
                    state = {id:id, title: title};
                    if(dir){
                        state.dir = dir;
                    }
                    window.history.pushState(state,null,href);
                    $(window).trigger('pushstate');
                }
            });

            $(document).ready(function(){
                if(!$.support.history.pushState){
                    var href = window.location.hash.replace('#','');
                    if(href.length > 0){
                        loadPage(href);
                    }
                }
            });

            $.address.change(function(){
                if(!$.support.history.pushState){
                    var href = window.location.hash.replace('#','');
                    if(href.length > 1){
                        loadPage(href);
                    }
                }
            });

            $(window).bind('pushstate',function(e){
                if($.support.history.pushState){
                    var href = location.pathname;
                    var data = {};
                    if(href.length < 1 || href == '/'){
                        href = '/home';
                    }

                    if(window.history.state == undefined){
                        data = state;
                    }else{
                        data = history.state;
                    }
                    
                    loadPage(href,data);
                }
            });


            $(window).bind('popstate',function(e){
                if(e.originalEvent.state){
                    window.location.href = location.pathname;
                }
            });
        });
    };

    $.fn.mediagallery = function(options){
        return this.each(function(){
            var settings = $.extend({
                gutterWidth: 10,
                columns: 4
            },options,true);

            var margins = settings.gutterWidth*(settings.columns-1);
            var $gallery = $(this);
            var $lightbox = $('.lightbox');
            var $view = $lightbox.find('.view');
            var $next = $lightbox.find('.next');
            var $prev = $lightbox.find('.prev').hide();
            var $first = $gallery.find('>li:first');
            var $last = $gallery.find('>li:last');
            var $close = $lightbox.find('.close').hide();
            var $img = $view.find('.img').hide();
            var $video = $view.find('.video').hide();
            var $h1 = $view.find('h1');
            var $h2 = $view.find('h2');
            var $pages = $lightbox.find('.pages');
            var callback = function(){};
            var $active = null;
            var page = 1;

            var setWidth = function(){
                $gallery.css('width','');
                var columnWidth = Math.floor(($gallery.width()-margins)/settings.columns);
                var width = columnWidth*settings.columns+margins;
                $gallery.width(width);
                $gallery.find('.item').width(columnWidth);
                return columnWidth;
            }

            var positionView = function($elm){
                var width = $elm.width();
                var height = $elm.height();
                var windowWidth = $(window).width();
                var windowHeight = $(window).height();

                var ratio = width/height;

                var marginLeft = Math.floor((width/2));
                var marginTop = Math.floor((height/2));

                $view.css({
                    width: width,
                    height: height,
                    marginTop: -marginTop,
                    marginLeft: -marginLeft
                });
            }

            var showImage = function($elm){
                var src = $elm.find('a').attr('href');
                $view.animate({
                    opacity: 0
                },400,function(){
                    callback = function(){};
                    $video.hide();
                    $img.show();
                    loadImage(src);
                    $active = $elm;
                });
            };

            var showVideo = function($elm){
                var src = $elm.find('a').attr('href');
                $view.animate({
                    opacity: 0
                },400,function(){
                    callback = function(){};
                    $img.hide();
                    $video.show();
                    loadVideo(src);
                    $active = $elm;
                });
            }

            var resolveNavigation = function($elm){
                if($elm.get(0) == $elm.parent().find('li:visible:first').get(0)){
                    $prev.fadeOut().hide();
                }else{
                    $prev.fadeIn();
                }

                if($elm.get(0) == $elm.parent().find('li:visible:last').get(0)){
                    $next.fadeOut();
                }else{
                    $next.fadeIn();
                }
            };

            var resolvePaging = function($elm){
                var $all = $elm.parent().find('li:visible');
                $pages.find('.current').text($all.index($elm)+1);
            }

            var loadImage = function(src){
                $img.html('').css('opacity',0).show();
                $('<img alt="" />').load(function(){
                    if($(this).width() > 0){
                        positionView($(this));
                        var $li = $active.closest('li');
                        $h1.text($li.find('h1').text());
                        $h2.text($li.find('h2').text());
                        $img.css('opacity',1);
                        $view.animate({
                            opacity: 1
                        });
                        callback();
                    }
                })
                .attr('src',src)
                .appendTo($img);
            };

            var loadVideo = function(src){
                $video.load(src,function(){
                    $(this).find('iframe').load(function(){
                        positionView($(this));
                        $view.animate({
                            opacity: 1
                        });
                    });
                });
            };

            var initMasonry = function(){
                $gallery.masonry({
                    gutterWidth: 9,
                    columnWidth: setWidth(),
                    isAnimated: true,
                    itemSelector: '.item:visible'
                });
            };

            if($gallery.find('li').length <= 1){
                $next.hide();
            }

            $gallery.delegate(".image", "click", function(e){
                e.preventDefault();
                var src = $(this).attr('href');
                var $lightbox = $('.lightbox');
                $active = $(this).closest('li');
                resolveNavigation($active);
                resolvePaging($active);
                if($(this).data('type') == 'image'){
                    $video.hide();
                    $lightbox.show();
                    loadImage(src);
                }else{
                    $video.show();
                    $img.hide();
                    $lightbox.show();
                    loadVideo(src);
                }

                $('html').addClass('lightbox-on');
            });

            $prev.click(function(e){
                e.preventDefault();
                var $prev = $active.prevAll(':visible:first');
                resolveNavigation($prev);
                resolvePaging($prev);
                if($prev.find('a').data('type') == 'image'){
                    showImage($prev);
                }else{
                    showVideo($prev);
                }
            });

            $next.click(function(e){
                e.preventDefault();
                var $next = $active.nextAll(':visible:first');
                resolveNavigation($next);
                resolvePaging($next);
                if($next.find('a').data('type') == 'image'){
                    showImage($next);
                }else{
                    showVideo($next);
                }
                if($next.find('~li').length <= 3){
                    $('.media-paging').trigger('click');
                }
            });

            $('.lightbox .view').live('hover',function(e){
                if (e.type == 'mouseenter') {
                     e.preventDefault();
                    $(this).find('.close').stop(true,true).delay(200).fadeIn();
                }

                if (e.type == 'mouseleave') {
                    e.preventDefault();
                    $(this).find('.close').stop(true,true).delay(200).fadeOut();
                }
            });

            $close.click(function(e){
                e.preventDefault();
                $(this).closest('.lightbox').fadeOut(400,function(){
                    $('html').removeClass('lightbox-on');
                });
            });

            $('.lightbox').click(function(e){
                var $target = $(e.target);
                if($target.is('.lightbox')){
                    $close.trigger('click');
                }
            });

            $('.media-paging').click(function(e){
                e.preventDefault();
                var url = $(this).attr('href');
                url = url.replace(/^(.*\/)(\d)$/i,"$1"+(page+1));
                $.get(url,function(result){
                    var $newElems = $( result );
                    if($newElems.length > 0){
                        $('.medias').imagesLoaded(function(){
                            $gallery.masonry( 'appended', $newElems, true );
                            $(window).trigger('resize');
                        });
                        $gallery.append( $newElems );
                        page++;
                    }
                });
            });

            $('.media-paging').bind('inview', function(e,visible){
                if(visible == true){
                    $('.media-paging').trigger('click');
                }else{
                    
                }
            });

            var imagesLoaded = false;
            $('.medias').imagesLoaded(function(){
                imagesLoaded = true;
                initMasonry();
            });

            setTimeout(function(){
                if(!imagesLoaded){
                    initMasonry();
                }
            },400);

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

    $.fn.timer = function(){
        return this.each(function(){
            var $loader = $(this).hide();
            var h = 0;
            var s = 0;
            var m = 0;
            var $hun = $loader.find('.hun');
            var $sec = $loader.find('.sec');
            var $min = $loader.find('.min');
            var i = null;
            var t = null;

            var reset = function(){
                h = 0;
                s = 0;
                m = 0;
                $hun.text('0');
                $sec.text('00');
                $min.text('00');
            };

            this.start = function(){
                t = setTimeout(function(){
                    reset();
                    $loader.show();
                    i = setInterval(function(){
                        if(++h == 10){
                            h = 0;
                            if(++s == 60){
                                s = 0;
                                if(++m == 60){
                                    clearInterval(i);
                                }
                                if(m < 10){
                                    $min.text('0'+m);
                                }else{
                                    $min.text(m);
                                }

                            }
                            if(s < 10){
                                $sec.text('0'+s);
                            }else{
                                $sec.text(s);
                            }

                        }
                        $hun.text(h);
                    },100);
                },1000);
            };
            
            this.stop = function(){
                clearTimeout(t);
                $loader.fadeOut(400,function(){
                    clearInterval(i);
                });
            };
        });
    };

    $.fn.googlemap = function(){
        return this.each(function(){
            var $map = $(this);
            var longitude = $map.data('longitude');
            var latitude = $map.data('latitude');
            var $markers = $map.find('.marker');
            var center = new google.maps.LatLng(latitude, longitude);
            var myOptions = {
              zoom: 6,
              center: center,
              mapTypeControl: true,
              mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.DEFAULT,
                position: google.maps.ControlPosition.TOP_CENTER
              },
              disableDefaultUI: true,
              zoomControl: false,
              mapTypeId: google.maps.MapTypeId.SATELLITE
            };
            var map = new google.maps.Map(
                $map.get(0),
                myOptions);

            $markers.each(function(){
                var infowindow = new InfoBox({
                    boxStyle: {
                        marginLeft: '27px',
                        marginBottom: '12px',
                        padding: '8px 10px 12px 10px',
                        minHeight: '26px',
                        background: '#fff'
                    },
                    closeBoxURL: '/css/elm/google-close.gif',
                    alignBottom: true,
                    closeBoxMargin: "0 0 0 0",
                    content: $(this).html()
                });

                var marker = new google.maps.Marker({
                    map:map,
                    draggable: false,
                    animation: google.maps.Animation.DROP,
                    position: new google.maps.LatLng($(this).data('latitude'), $(this).data('longitude')),
                    icon: '/css/elm/google_pin.png',
                    shadow: '/css/elm/google_pin_shadow.png',
                    title: $(this).find('h1').text()
                });

                google.maps.event.addListener(marker, 'mouseover', function() {
                    infowindow.open(map,marker);
                });
                google.maps.event.addListener(marker, 'mouseout', function() {
                    infowindow.close(map,marker);
                });
                if($(this).is('.open')){
                    infowindow.open(map,marker);
                }
            });

            $map.parent().find('.zoom-in').click(function(e){
                e.preventDefault();
                var zoom = map.getZoom();
                zoom++;
                map.setZoom(zoom);
                zoom = map.getZoom();
            });

            $map.parent().find('.zoom-out').click(function(e){
                e.preventDefault();
                var zoom = map.getZoom();
                zoom--;
                if(zoom < 3){
                    zoom = 3;
                }
                map.setZoom(zoom);
                zoom = map.getZoom();
            });

        });
    };

    $.fn.staticGoogleMap = function(){
        return this.each(function(){
            var $container = $(this);
            var longitude = $container.data('longitude');
            var latitude = $container.data('latitude');
            var src = 'http://maps.googleapis.com/maps/api/staticmap?center='+latitude+','+longitude+'&zoom=10&size='+$container.width()+'x'+$container.height()+'&maptype=satellite&sensor=false&scale=1';
            var $img = $('<img />');
                $img.load(function(){
                    $container.append($img);
                });
                $img.attr('src',src);
        });
    };
	
	/* asynkron lasting av twitters widgetbibliotek, samt vår initialisering av widget  */
	var twitterLoadAndInit = function(){
		if ($("#twitter-feed").length > 0){
			$.getScript("http://widgets.twimg.com/j/2/widget.js", function(){
				$.getScript("/js/twitter.js");
			});
		}
	};

    $.fn.cropImage = function(){
        return this.each(function(){
            var $img = $(this);
            var $frame = $img.parent();
            var crop = function(){
                $frame.css({
                    width: '',
                    height: ''
                });
                if($img.width() > $img.height()){
                    $img.css({
                        left: '0',
                        width: '100%',
                        height: 'auto'
                    });
                    $frame.height($img.height());
                }else{
                    $img.css({
                        top: '50%',
                        width: '100%',
                        height: 'auto'
                    }).css({
                        marginTop: -($img.height()/2)
                    });
                }
            };

            $img.load(function(){
                crop();
            }).load();
        });
    };

    $.fn.sponsorZoom = function(){
        return this.click(function(e){
            e.preventDefault();
            var url = $(this).attr('href');
            $.get(url,function(response){
                var $lightbox = $(response).hide();
                var $view = $lightbox.find('.view');
                $lightbox.find('.close').click(function(e){
                    e.preventDefault();
                    $lightbox.fadeOut(400,function(){
                        $lightbox.remove();
                    });
                });
                $('body').append($lightbox);

                $lightbox.find('img').load(function(){
                    $lightbox.fadeIn();
                    var $img = $(this);
                    var height = $(this).height();
                    var width = $(this).width();
                    var maxHeight = $(window).height()-80;
                    var maxWidth = $(window).width()-80;

                    if(width > maxWidth){
                        $img.css({
                            width: maxWidth,
                            height: 'auto'
                        });

                        height = $img.height();
                        width = $img.width();
                    }

                    if(height > maxHeight){
                        $img.css({
                            width:'auto',
                            height: maxHeight
                        });
                        
                        height = $img.height();
                        width = $img.width();
                    }

                    $view.css({
                        position: 'absolute',
                        marginTop: -($img.height()/2),
                        marginLeft: -($img.width()/2),
                        width: $img.width(),
                        height: $img.height(),
                        top: '50%',
                        left: '50%'
                    });
                });

            });
        });
    };

    $(document).ready(function(){
        if(!$('html').is('.media, .full-map')){
            $('.js .menu').navigation();
        }

        $('.header .menu li a').hover(function(){
            if(!$(this).is('.active')){
                var $elm = $(this).find('span:first');
                $elm.stop(true,true).delay(50).animate({
                    marginTop: 0
                },400,'easeInOutCubic',function(){
                    $(this).css('margin-top',-18);
                });
            }
        },function(){});

        $('.medias').mediagallery({
            gutterWidth: 9,
            columns: 3
        });

        $('.to-top').live('click',function(e){
            e.preventDefault();
            $('html, body').animate({scrollTop:0}, 'slow');
        });

        $('.googlemap').googlemap();
        $('.static-google-map').staticGoogleMap();
        $('.image-frame img').cropImage();
        $('.sponsor-zoom').sponsorZoom();
		
		twitterLoadAndInit();
		
    });
})(jQuery);
