(function() {
    var cl = function(o) {
        if (window.console) console.log(o);
    };
    var ltIE9 = function() {
        return $('html').hasClass('ielt9');
    };
    var preloading = {
        init: function() {
            var cache = [];
            var argsLen = arguments.length;
            for ( var i = argsLen; i--;) {
                var cacheImg = document.createElement('img');
                cacheImg.src = arguments[i];
                cache.push(cacheImg);
            }
        }
    };
    var removeEmptyP = function(sel) {
        var $p = $(sel);
        $p.each(function() {
            var $this = $(this);
            var p = $.trim($this.text()).replace('/\s+/gi', '');
            if ( !p.length ) $this.hide();
        });
    };
    var setupGoogleMap = {
        init: function() {
            var latLng = new google.maps.LatLng(60.379495,5.338668);
            var myOptions = {
                zoom: 14,
                center: latLng,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                mapTypeControlOptions: {
                    mapTypeIds: []
                }
            };
            var $placeholder = $('.bottom').find('.google-map'); // jQuery element
            var map = new google.maps.Map($placeholder[0], myOptions); // DOM element as argument
            var marker = new google.maps.Marker({
                position: latLng,
                map: map,
                title:"Kunstskolen i Bergen"
            });
            var content = '<div class="info-window darkest-gray">Kunstskolen i Bergen, <br>M&oslash;llendalsveien 8,<br> 5009 Bergen<br><a class="orange" target="_blank" href="http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=Kunstskolen+i+Bergen+Kib,+M%C3%B8llendalsveien+8,+Kronstad,+Norge&aq=0&sll=60.379495,5.338668&sspn=0.007944,0.020449&g=M%C3%B8llendalsveien+8,+Kronstad,+Norge&ie=UTF8&hq=Kunstskolen+i+Bergen+Kib,&hnear=M%C3%B8llendalsveien+8,+5009+Bergen,+Hordaland,+Norway&ll=60.379636,5.338669&spn=0.007943,0.020449&z=16&iwloc=A">St&oslash;rre kart</a></div>';
            var infowindow = new google.maps.InfoWindow({
                content: content
            });
            google.maps.event.addListener(marker, 'click', function() {
              infowindow.open(map,marker);
            });
        }
    };
    var setupTop = {
        cycleSettings: {
            next: '.top',
            pager: '.social-wrapper .pager',
            pagerAnchorBuilder: function(idx, slide) {
                return '<span class="sprite relative sprite-' + idx +'"></span>';
            },
            pause: 0,
            timeout: 0
        },
        $images: $(),
        init: function() {
            this.$fadeshowWrapper = $('.top');
            this.$fadeshowContainer = this.$fadeshowWrapper.find('.fadeshow');
            if ( !this.$fadeshowWrapper.length ) return;
            setupTop.initHide();

            // Assigning images
            this.$images = this.$fadeshowContainer.find('.image img');
            if ( !this.hasImages() ) return;

            var $window = $(window);
            this.setWrapperHeight();
            $window.load(function() {
                setupTop.initFadeshow();
                setupTop.scaleContent();
            });
            $window.resize(function() {
                setupTop.scaleContent();
            });
        },
        setWrapperHeight: function() {
            var wHeight = $(window).height();
            this.$fadeshowWrapper.css({
                height: Math.floor(0.65 * wHeight)
            });
        },
        initFadeshow: function() {
            var that = this;
            that.getImageDimensions();
            this.$fadeshowContainer.css('visibility','visible');

            if ( this.$fadeshowContainer.children().length > 1 ) {
                this.$fadeshowContainer.cycle(that.cycleSettings);
            }
        },
        initHide: function() {
            this.$fadeshowContainer.css('visibility','hidden');
        },
        getImageDimensions: function() {
            this.$images.each(function() {
                var $img = $(this);
                $img.css({
                    top: '-1000px',
                    display: 'block',
                    opacity: '1'
                });
                $img.data('width', $img.width());
                $img.data('height', $img.height());
            });
        },
        hasImages: function() {
            return this.$images.length > 0;
        },
        scaleContent: function() {

            this.setWrapperHeight();
            var $wrapper = this.$fadeshowWrapper;
            var wHeight = $wrapper.height();
            var wWidth = $wrapper.width();
            var wRatio =  wHeight/wWidth;
            this.$images.each(function() {
                var $img = $(this);
                var iHeight = $img.data('height') || 0;
                var iWidth = $img.data('width') || 0;
                var iRatio =  iHeight/iWidth;

                if ( iRatio > wRatio ) {
                    var topPosition = -Math.floor( ( wWidth * iRatio - wHeight ) / 2 );
                    $img.css({ height: 'auto', top: topPosition, width: wWidth });
                } else {
                    var leftPosition = -Math.floor( ( wHeight / iRatio - wWidth ) / 2 );
                    $img.css({ height: wHeight, left: leftPosition, top: '0', width: 'auto' });
                }
            });
        }
    };
    var setupVideo = {
        init: function() {
            var $el = $('div.movie').find('a');
            if ( !$el.length ) return;
            // $el.fancybox();

            $el.click(function() {

                $.fancybox({
                    'padding'       : 0,
                    'byline'        : false,
                    'title'         : false,
                    'autoScale'     : false,
                    'transitionIn'  : 'none',
                    'transitionOut' : 'none',
                    'width'         : 800,
                    'height'        : 450,
                    'href'          : this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1'),
                    'type'          : 'swf'
                });

                return false;
            });
        }
    };
    var setupMiniFadeshow = {
        fadeshowContainer: '.miniFadeshow',
        pagerContainer: '.miniFadeshow-wrapper .pager',
        cycleSettings: {
            pager: '',
            pagerAnchorBuilder: function(idx, slide) {
                return '<span class="sprite sprite-' + idx +'"></span>';
            },
            pause: 0,
            timeout: 0
        },
        init: function() {
            var $fadeshowContainer = $(this.fadeshowContainer);
            var that = this;
            if ( !$fadeshowContainer.length ) return;
            var count = 0;
            $fadeshowContainer.each(function() {
                var $this = $(this);
                if ($this.children().length > 1 ) {
                    var pagerId = 'pager-' + ++count;
                    $this.next().find('.pager').attr('id', pagerId);
                    that.cycleSettings.pager = that.pagerContainer + '#' + pagerId;
                    that.cycleSettings.next = $('#' + pagerId).parent().prev();
                    $this.cycle(that.cycleSettings);
                }
            });
        }
    };
    var skew = {
        init: function() {
            this.$body = $('body');
            this.$fadeshowContainer = $('.top');
            this.$submenuContainer = $('.submenu-wrapper');
            this.adjustSubpageSkewIE();
            if ( !this.$fadeshowContainer.length ) return;

            // Container for added content
            this.$container = $('<div/>', {
                className: 'added-visuals'
            });

            // TODO Add all generated code to $container before insertion
            this.$body.append(this.$container);
            this.createSkewedOverlay();
            this.addDropShadow();
        },
        addDropShadow: function() {
            var $dropShadowWrapper = $('<div/>', {
                className: 'drop-shadow relative oh'
            });
            var $dropLeft = $('<div/>', {
                className: 'left light-gray-bg float-left box-rotate-back'
            });
            var $dropRight = $('<div/>', {
                className: 'right light-gray-bg float-right box-rotate-back'
            });
            $dropShadowWrapper.append($dropLeft, $dropRight);
            this.$skewedOverlay.append($dropShadowWrapper);
        },
        adjustSubpageSkewIE: function() {
            if ( !this.$submenuContainer.length ) return;
            if ( ltIE9() ) {
                $('.submenu-wrapper').find('.box-rotate').css({
                    top: '-100%'
                });
            }
        },
        createSkewedOverlay: function() {
            if ( !this.$fadeshowContainer.length ) return;

            this.$skewedOverlay = this.$container.find('.skewed');
            if ( !this.$skewedOverlay.length) {
                this.$skewedOverlay = $('<div/>', {
                    className: 'skewed box-rotate light-gray-bg'
                });
                this.$container.append(this.$skewedOverlay);
            }
            var tan = 0.13;
            var fadeshowBottom = this.$fadeshowContainer.position().top + this.$fadeshowContainer.height();
            var windowWidth = $(window).width();
            var overlayHeight = Math.ceil(tan * windowWidth);


            this.$skewedOverlay.addClass('absolute');
            var topPos;
            if ( ltIE9() ) {
                topPos = fadeshowBottom - Math.ceil(1.5*overlayHeight);
                $('.main-wrapper').css({
                    marginTop: '-200px'
                });
            }
            else  {
                topPos = fadeshowBottom - Math.ceil(overlayHeight/2);
            }
            this.$skewedOverlay.css({
                    top: Math.floor(topPos)
            });
        }
    };
    var utils = {
        addClassToGroup: function(arg) {
            if ( !arg.$container.length ) return;
            arg.$container.find(arg.selector).addClass(arg.cl);
        }
    };
    var generateSubmenu = {
        init: function() {
            this.$container = $('.submenu');
            if ( !this.$container.length > 0 ) return;
            this.$elements = $('h2').not('.no-sub');
            this.buildMenu();
            this.scrollable();
        },
        buildMenu: function() {
            var $ul = $('<ul/>');
            if (this.$elements.length <= 1) return;
            this.$elements.each(function() {
                var $this = $(this);
                var $link = $('<a/>').html($this.html());
                $link.attr('href', '#' + $this.attr('id'));
                $ul.append($('<li class="float-left ls-none"/>').append($link));
            });
            this.$container.append($ul);
        },
        scrollable: function() {
            // Updated according to http://www.zachstronaut.com/posts/2009/01/18/jquery-smooth-scroll-bugs.html
            var filterPath = function(string) {
                return string
                        .replace(/^\//,'')
                        .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
                        .replace(/\/$/,'');
            };
            var locationPath = filterPath(location.pathname);
            var $links = this.$container.find('a');
            $links.each(function() {
                var thisPath = filterPath(this.pathname) || locationPath;
                if ( locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/, '')) {
                    if ( $(this.hash).length) {
                        $(this).click(function(e) {
                            e.preventDefault();
                            var target = this.hash;
                            var targetOffset = $(target).offset().top - 40;
                            $('html, body').animate({
                                scrollTop: targetOffset
                            }, 800,
                            function() {
                                // location.hash = target;
                            });
                        });
                    }
                }
            });
        }
    };
    var persons = {
        init: function() {
            // this.setupOverlay();
            this.adjust();
        },
        setupOverlay: function() {
            var $images = $('.person img');
            if ( !$images.length ) return;
            var $overlay = $('<div/>', {
                className: 'overlay absolute'
            });
            $images.before($overlay);
            $('.movie').find('.overlay').hover(function() {
                $(this).addClass('hover');
            }, function() {
                $(this).removeClass('hover');
            });
        },
        adjust: function() {
            var $persons = $('div.person');
            var groupCount = 0;
            $persons.each(function() {
                var $this = $(this);
                var $next = $this.next();
                var $prev = $this.prev();
                if ( $next.hasClass('person') || $prev.hasClass('person')) {
                    $this.addClass('group-' + groupCount);
                    if (!$next.hasClass('person')) groupCount++;
                }
            });
            var cnt = 0;
            while ( cnt <= groupCount ) {
                $('.group-' + cnt).wrapAll('<div class="oh"/>');
                cnt++;
            }
        }
    };
    $(document).ready(function() {
        var path = '/media/css/img/';
        preloading.init(path + 'play-hover.png', path + 'sirkel_bilderamme.png', path + 'KIB-sprite.png');
        setupGoogleMap.init();
        skew.init();
        setupTop.init();
        setupMiniFadeshow.init();
        setupVideo.init();
        generateSubmenu.init();
        removeEmptyP('.ielt9 .three-column p, .ie9 .three-column p');

        // Truncate characters for website urls
        var $elements = $('.website-url a');
        $elements.each(function() {
            var $this = $(this);
            var text = $this.text();
            if ( text.length > 30 ) {
                var substr = text.substring(0, 30);
                $this.text(substr + '…');
            }
        });
        var $container = $('.lower');
        var $frontpageContainer = $('.forside').find('.block');
        persons.init();
        utils.addClassToGroup({
            $container: $frontpageContainer,
            selector: 'div.person:nth-child(3n-1), div.person:nth-child(3n-2)',
            cl: 'right-spacing-42'
        });
        utils.addClassToGroup({
            $container: $frontpageContainer,
            selector: 'div.person:nth-child(4n)',
            cl: 'cb'
        });
        utils.addClassToGroup({
            $container: $container,
            selector: 'div.person:nth-child(2n-1)',
            cl: 'right-spacing-42'
        });
        utils.addClassToGroup({
            $container: $container,
            selector: 'div.person:gt(0):nth-child(2n-1)',
            cl: 'cb'
        });
    });
    $(window).load(function() {
        skew.createSkewedOverlay();
    });
    $(window).resize(function() {
        skew.createSkewedOverlay();
    });
})();

