Gla = {};


/**
 * Main Section
 *
 */
Gla.Main = {
    
    
    /** Current Background image **/
    currentImage: 1,
    
    /** Is MSIE6? **/
    isMSIE: false,
    
    _toggleTextOnMenu : false,
    
    
    /**
     * Dom Ready
     *
     */
    init : function () {
        
        // Alrighty theeen, display: none on all images in the body-background
        // untill all images are loaded...
        $('#body-background img[rel=1]').imagesLoaded(function() {
            $('#body-background img[rel=1]').show();
        });
        
        $('#pageBody').show();
        
        _ = this;
        
        // Is IE6?
        _.isMSIE = /MSIE 6/i.test(navigator.userAgent);
        if(!_.isMSIE) {
            
            // Easy background resize...
            $("#body-background").ezBgResize();
            
            $(window).bind("resize", function(){
                $("#body-background").ezBgResize();
            });
        } else {
            sc = $("#body-background img").attr('src');
            $('body').css('backgroundImage', 'url("' + sc + '")');
            $('#body-background').hide();
            
            $('#wrapper').hide();
        }
        
        
        $('#bgCounter span').hide();
        $('#bgCounter span[rel=1]').show();
        
        
        // Replace all fonts that might need to be replaced
        this.initFontReplacements();
        
        // Fade the blocks
        $('#homepageBlocks .block').fadeTo(0, 0.9);
        
        setTimeout(function() {
            $('#homepageBlocks .block').stop().fadeTo(1500, 0);
            
            $('#homepageBlocks .block').hover(function() {
                $(this).stop().fadeTo(800, 0.9);
            }, function() {
                $(this).stop().fadeTo(800, 0);
            });
        }, 7000);
        
        
        
    },
    
    
    /**
     * Font replacements
     *
     */
    initFontReplacements : function () {
        
        // Menus
        $('#menu a').each(function(){
            $(this).html('<img src="/fontme?text=' + escape($(this).text()) + '&style=text" />');
        });
        
        
        // Top level menus
        $('.elementz p').each(function(){
            $(this).html('<img src="/fontme?text=' + escape($(this).text()) + '&style=text" />');
        });
    },
    
    
    toggleTextClick: function () {
        if(this._toggleTextOnMenu === false) {
            this._toggleTextOnMenu = true;
        } else {
            this._toggleTextOnMenu = false;
        }
        
        this.toggleText();
    },
    
    
    toggleText: function(todoWhat, speed) {
        
        if(typeof speed == 'undefined') {
            speed = 100;
        }
        
        if(todoWhat == 'hide') {
            $('#pageBody').slideUp(speed);
            $('#toggleText').addClass('active');
        } else if (todoWhat == 'show') {
            $('#pageBody').slideDown(speed);
            $('#toggleText').removeClass('active');
        } else {
            $('#pageBody').slideToggle(speed);
            $('#toggleText').toggleClass('active');
        }
        
    },
    
    contactUs: function() {
        
        /*if($('#toggleText').length > 0) {
            if($('#toggleText').hasClass('active')) {
                this.toggleText('show');
                $('#contactInner').slideUp(100);
            } else {
                this.toggleText('hide');
                $('#contactInner').slideDown(100);
            }
        } else {*/
            $('#contactInner').slideToggle(100);
        //}
        
    },
    
    
    
    /**
     * Changes the background image
     *
     */
    bgSwitch: function (direction, wImage)
    {
        // Remove the background loading
        $('body').css('background-image', 'none');
        
        _ = this;
        
        if (typeof direction == 'undefined') {
            direction = 'next';
        }
        
        
        switch (direction) {
            
            case 'next':
                
                // Check that the next one exists
                if($('#body-background img[rel=' + (_.currentImage + 1)  + ']').length > 0) {
                    
                    // There is a next image, flip it brother!
                    $('#body-background img[rel=' + _.currentImage + ']').fadeOut(250);
                    $('#body-background img[rel=' + (++_.currentImage)  + ']').fadeIn(250);
                    
                    //$("#body-background").ezBgResize();
                    
                }
                
                else {
                    
                    // No Next exist. Go back to 1
                    _.bgSwitch('specific', 1);
                    
                }
                
                _.updateBackground();
                
                break;
            
            
            case 'back':
                
                // Check that a previous one exists
                // Check that the next one exists
                if($('#body-background img[rel='  + (_.currentImage - 1)  + ']').length > 0) {
                    
                    // There is a previous image, flip it brother!
                    $('#body-background img[rel=' + _.currentImage  + ']').fadeOut(250);
                    $('#body-background img[rel=' + (--_.currentImage) + ']').fadeIn(250);
                    
                    //$("#body-background").ezBgResize();
                    
                }
                else {
                    // No previous exist, goto the highest one
                    _.bgSwitch('specific', $('#body-background-count').attr('rel'));
                    
                }
                
                // Update image
                _.updateBackground();
                
                break;
            
            case 'specific':
                
                // There is a next image, flip it brother!
                $('#body-background img[rel=' + _.currentImage + ']').fadeOut(250);
                $('#body-background img[rel=' + wImage  + ']').fadeIn(250);
                
                _.currentImage = wImage;
                
                // Update image
                _.updateBackground();
                
                break;
            
        }
        
    },
    
    /**
     * Updates the text 1 of 5, 1 of 5 etc etc
     *
     */
    updateBackground: function()
    {
        $('#bgCounter span').hide();
        $('#bgCounter span[rel=' + this.currentImage + ']').show();
    }
}



/**
 * Menu Object
 *
 */
Gla.Menu = {
    
    activeMenus : {
        'one'   : false,
        'two'   : false,
        'three' : false
    },
    
    activeMenu  : null,
    
    activeItem  : null,
    
    activeLevel : 'none',
    
    
    
    // ---
    completeMenu : null,
    
    
    hoverTimer : null,
    
    mouseInside: false,
    
    activeMouseOver : null,
    
    isFading: null,
    
    isIE : false,
    
    
    /**
     * Menu Object
     *
     */
    init : function () {
        
        $('#menuWrapper').fadeTo(0,0.85);
        $('#menuWrapper').fadeTo(0,0.85);
        
        _this = this;
        
        // Hide the menu
        this.completeMenu = $('#mainMenu').remove();
        
        if($.browser.msie) {
            _this.isIE = true;
        }
        
        // Apply all events
        this.applyDefaultEvents();
    },
    
    
    
    
    /**
     * Applies events to the menu
     *
     */
    applyDefaultEvents : function() {
        _this = this;
        
        // Apply mouseout events
        $('.topmenu-item a').hover(function() {
            
            if($(this).html() != '') {
                if(Gla.Main._toggleTextOnMenu == true) {
                    Gla.Main.toggleText('hide', 10);
                }
            }
            
            if(!_this.isFading) {
                _this.openMenu($(this).attr('rel'), $(this).attr('href'));
            
                _this.activeMenu = $(this).parents('.topLevel').attr('id').replace(/topmenu_/, '');
                _this.activeItem = $(this).parents('.topLevel').find('ul > li');
                
                _this.checkMenu();
            }
            
            $(this).hide();
        }, function() {
            $(this).show();
        });
        
        
    },
    
    
    
    /**
     * Applies the recurring events
     *
     */
    applyRecurringEvents: function () {
        _this = this;
        
        $('#menuWrapper ul li').die('mouseenter').live('mouseenter', function() {
            
            $('a', this).addClass('cHover');
            _this.activeMenu = $(this).parents('.topLevel').attr('id').replace(/topmenu_/, '');
            _this.activeItem = $(this);
            _this.checkMenu();
            clearTimeout(_this.hoverTimer);
            
        });
        
        $('#menuWrapper ul li').die('mouseleave').live('mouseleave', function() {
            
            $('a', this).removeClass('cHover');
            _this.hoverTimer = setTimeout(function() {
                _this.closeMenu('one');
            }, 500);
        });
        
    },
    
    
    /**
     * Opens a menu
     *
     * @param level string          Level to open
     * @param id    string|null     Selector of level of menu to open
     */
    openMenu : function (openLevel, levelSelector) {
        
        _this = this;
        
        // Clone the part of the menu we want
        appender = $(levelSelector, this.completeMenu).clone().children();
        
        // Remove any uls within
        appender.each(function() {
            $('ul', this).remove();
        });
        
        _this.isFading = true;
        
        // Push into the menu for that level
        $('#topmenu_' + openLevel + ' ul')
        .hide()
        .empty()
        .append(appender);

        if(_this.isIE) {
            t = 0;
        } else {
            t = 200;
        }
        if(this.activeLevel != openLevel) {
            $('#topmenu_' + openLevel + ' ul').fadeIn(t, function() {
                _this.isFading = false;
            });
        } else {
            $('#topmenu_' + openLevel + ' ul').show();
            _this.isFading = false;
        }
        
        
        // Let us know which menu is active
        this.activeMenus[openLevel] = true;
        this.activeLevel = openLevel;
        
        this.applyRecurringEvents();
        
        return this;
        
    },
    
    
    checkMenu: function() {
        _this = this;
        
        elRel = _this.activeItem.attr('rel');
        
        // Find the active menu and open the next one
        nextMenu = _this.toWord(_this.toInt(_this.activeMenu) + 1);
        
        if(typeof elRel != 'undefined') {
            subMenus = $('#menu-' + elRel, _this.completeMenu);
        
            if(typeof subMenus != 'undefined') {
                //console.log(subMenus);
                
                if(nextMenu != 'none') {
                    _this.openMenu(nextMenu, '#menu-' + elRel);
                } else {
                    _this.closeMenu(nextMenu);
                }
            } else {
                _this.closeMenu(nextMenu);
            }
        
        } else {
            _this.closeMenu(nextMenu);
        }
        
    },
    
    
    /**
     * Closes a menu
     *
     */
    closeMenu : function (menu) {
        
        $('#topmenu_' + menu + ' ul').empty();
        
        if(menu == 'one') {
            
            if(Gla.Main._toggleTextOnMenu == true) {
                Gla.Main.toggleText('show', 10);
            }
            
            $('#topmenu_two ul').empty();
            $('#topmenu_three ul').empty();;
            _this.activeLevel = 'none';
        }
        
        if(menu == 'two') {
            $('#topmenu_three ul').empty();;
            _this.activeLevel = 'none';
        }
        
        
        return this;
    },
    
    
    toInt : function(letter) {
        switch(letter) {
            case 'one':
                return 1;
            case 'two':
                return 2;
            case 'three':
                return 3;
            default:
                return 0;
        }
    },
    
    toWord : function(conv) {
        switch(conv) {
            case 1:
                return 'one';
            case 2:
                return 'two';
            case 3:
                return 'three';
            default:
                return 'none';
        }
    }
    
}






$(document).ready(function() {
    
    // Init the main gla object
    Gla.Main.init();
    
    // Init the menu object
    Gla.Menu.init();
});




// $('img.photo',this).imagesLoaded(myFunction)
// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images

// mit license. paul irish. 2010.
// webkit fix from Oren Solomianik. thx!

// callback function is passed the last image to load
//   as an argument, and the collection as `this`


$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len   = elems.length;
      
  elems.bind('load',function(){
      if (--len <= 0){ callback.call(elems,this); }
  }).each(function(){
     // cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
        this.src = src;
     }  
  }); 

  return this;
};

