(function ($){
    $('body').removeClass('nojs').addClass('js');
    
    var startCarousel = $('#carousel');
    var imageCount = $('img', startCarousel).length;
    startCarousel.length ? startCarousel.nivoSlider({
        effect: 'fade',
        pauseTime: 4000,
        pauseOnHover: true,
        controlNav: false,
        startSlide: Math.floor( Math.random() * imageCount ),
        
        // bug wenn die bilder nicht richtig geladen werden, wird #carousel nur 20px hoch..
        afterLoad: function () {
            startCarousel.css({
                height: '487px'
            });
        }
    }) : false;
    
    var  subcarousel = $('#subcarousel');
    if ( subcarousel.length ) {
         subcarousel.nivoSlider({
            effect: 'fade',
            pauseTime: 3000,
            pauseOnHover: false,
            keyboardNav: false,
            controlNav: false,
            directionNav: false
        });
    }
    
    var galeries = $('.inline-gallery');
    var i        = 1;
    var rel      = '';
    if ( galeries.length ) {
        galeries.each(function () {
            $this = $(this);
            rel = 'galerie_' + i++;
            $('a', this).attr('rel', rel);
        });
    }
    $('a[rel^=galerie]').fancybox({
        'type': 'image',
        'titlePosition' 	: 'over',
		'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
		    return '<span id="fancybox-title-over"><span style="color: #aaa;">Bild ' +  (currentIndex + 1) + ' von ' + currentArray.length + '</span> ' + title + '</span>';
		}
    });
    
    var room = $('#room-configurator');
    if ( room.length ) {
        var configurator = function () {
            var cfg       = ROOMCONFIG_DATA, 
                basePath  = BASE_URI + 'addons/modules/configurator/img/',
                imgCache  = {},
                images    = $('<div id="image-holder"></div>'),
                imageHide = $('<div id="image-hide"></div>'),
                floorBox  = $('#floor'),
                roomBox   = $('#room'),
                seatingBox = $('#seating'),
                
                init = function () {
                    resetForm();
                    imageHide.appendTo(images);
                    images.appendTo(room);
                    loadImages();
                    fillFloorBox();
                    attachEvents();
                },
                
                attachEvents = function () {
                    floorBox.change(function(){
                        resetForm();
                        setImages();
                        var value = this.value;
                        if ( !value ) {
                            return;
                        }
                        fillRoomBox();
                    });
                    
                    roomBox.change(function(){
                        var value = $(this).val();
                        if ( value ) {
                            fillSeatingBox();
                        } else {
                            seatingBox.attr('disabled', true).html('<option value="">Bestuhlung wählen</option>');
                        }
                        setImages();
                    });
                    
                    seatingBox.change(function(){
                        setImages();
                    });
                }
                
                resetForm = function () {
                    roomBox.attr('disabled', true).html('<option value="">Raum wählen</option>');                    
                    seatingBox.attr('disabled', true).html('<option value="">Bestuhlung wählen</option>');
                },
                
                setImages = function () {
                    resetImages();
                    var floor = floorBox.val(),
                        room  = roomBox.val(),
                        seating = seatingBox.val();
                    if ( floor ) {
                        displayImg(floor + '.png');
                    }
                    if ( room ) {
                        displayImg(floor + '/' + room + '.png');
                    }
                    if ( seating ) {
                        displayImg(floor + '/' + room + '_' + seating + '.png');
                    }
                },
                
                fillFloorBox = function () {
                    iterate(cfg, function (kEtage, vEtage){
                        floorBox . append('<option value="'+ kEtage +'">' + vEtage.title + '</option>');
                    });
                },
                fillRoomBox = function () {
                    var value = floorBox.val();
                    if ( !value ) {
                        return false;
                    }
                    iterate(cfg[value].rooms, function (kRoom, vRoom){
                        roomBox . append('<option value="'+ kRoom +'">' + vRoom.title + '</option>');
                    });
                    roomBox.removeAttr('disabled');
                },
                fillSeatingBox = function () {
                    seatingBox.attr('disabled', true).html('<option value="">Bestuhlung wählen</option>');
                    var floor = floorBox.val();
                    if ( !floor ) {
                        console.log(1);
                        return false;
                    }
                    var room = roomBox.val();
                    if ( !room ) {
                        console.log(2);
                        return false;
                    }
                    iterate(cfg[floor].rooms[room].types, function (kSeating, vSeating){
                        seatingBox . append('<option value="'+ kSeating +'">' + vSeating.title + '</option>');
                    });
                    seatingBox.removeAttr('disabled');
                },
                
                // lädt alle bilder 
                loadImages = function () {
                    iterate(cfg, function (kEtage, vEtage){
                        loadImg(vEtage.image, 1);
                        iterate(this.rooms, function (){
                            loadImg(kEtage + '/' + this.image, 2);
                            iterate(this.types, function (){
                                loadImg(kEtage + '/' + this.image, 3);
                            });
                        });
                    });
                },
                
                displayImg = function ( rel_path ) {
                    imgCache[rel_path][0].style.zIndex = imgCache[rel_path].data('level');
                },
                
                resetImages = function () {
                    iterate(imgCache, function () {
                        this[0].style.zIndex = -1;
                    });
                }
                
                // zeigt ein bild an, läd nach wenn der index noch nicht im cache liegt
                loadImg = function ( rel_path, level ) {
                    if ( typeof imgCache[rel_path] === 'undefined' ) {
                        var img = $('<img>');
                        img[0].src = basePath + rel_path;
                        img.data('level', level);
                        img.appendTo(images);
                        imgCache[rel_path] = img;
                    }
                },
                                  
                // geht jedes element durch und wendet den callback an
                iterate = function (elem, func) {
                    $.each(elem, func);
                }
                
            return {
                init: init
            }
        }();
        configurator.init();
    }
    
    
    
})(jQuery);
