/**
/* @see https://gist.github.com/797120/7176db676f1e0e20d7c23933f9fc655c2f120c58 */
$.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;
};



/**
 * Arcadia JS
 *
 */
 
(function($) {
    
    // Arcadia object
    arcadia = {
        
        _mainHidden : false,
    
        init: function() {
            
            arcadia.bg.init();
            
            $(window).resize(function() {
                arcadia.bg.determineSizes();
            });
            
            // Bind left and right to change the background images
            $(document).keydown(function(e){
                
                // Left
                if (e.keyCode == 37) { 
                   arcadia.bg.prev();
                   return false;
                }
                
                // Right
                if (e.keyCode == 39) { 
                   arcadia.bg.next();
                   return false;
                }
                
                // Up/Down
                if (e.keyCode == 38 || e.keyCode == 40) { 
                   arcadia.toggleContent();
                   return false;
                }
            });
            
            // Video Replacements
            $('#video_thumbs a').click(function() {
                player = document.getElementById('video_default_object');
                player.sendEvent("LOAD", {
                    "file": $(this).attr('href'),
                    "image": $(this).attr('rel')
                });
                
                return false;
            });
            
            // Newsletter
            nsd = $('#newsletterSignupInput').val();
            $('#newsletterSignupInput').focus(function() {
                if($(this).val() == nsd) {
                    $(this).val("");
                }
                $('#newsletterInfo').slideDown(50);
            }).blur(function() {
                if($(this).val() == '') {
                    $(this).val(nsd);
                }
                $('#newsletterInfo').slideUp(50);
            });
            
            
            // Panorama Replacements
            $('.panoramas-ul a').click(function() {
                var sop = new SWFObject($(this).attr('href'), 'flash_panorama', 540, 330, "9");
                sop.addParam("wmode", "opaque");
                sop.write('video_panorama');
                
                return false;
            });
            
            // Twitter most recent feed
            $(".tweet").tweet({
                username: "A_rcadia",
                join_text: "auto",
                avatar_size: 32,
                template: function(i){
                    return i["text"] + ' - ' + i['tweet_relative_time'];
                },
                count: 1,
                auto_join_text_default: "we said,", 
                auto_join_text_ed: "we",
                auto_join_text_ing: "we were",
                auto_join_text_reply: "we replied to",
                auto_join_text_url: "we were checking out",
                loading_text: "loading our most recent tweet..."
            }).bind("empty", function() {
                $(this).append("We have no recent tweets.");
            });
            
            // Menu
            $('#menu>li').hover(function() {
                if($('ul', this).length > 0) {
                    $('ul', this).show();
                    if(arcadia._mainHidden == false) {
                        $('.content').fadeTo(0, 0.3);
                    }
                }
            }, function() {
                if($('ul', this).length > 0) {
                    $('ul', this).hide();
                    if(arcadia._mainHidden == false) {
                        $('.content').fadeTo(0, 1);
                    }
                }
            });
            
        },
        
        
        toggleContent: function(duration, amount) {
            
            if(this._mainHidden) {
                $('.content').slideDown(200);
                $('#topMinSection').removeClass('active');
                this._mainHidden = false;
            } else {
                $('.content').slideUp(200);
                $('#topMinSection').addClass('active');
                this._mainHidden = true;
            }
        }
    
    };
    
    arcadia.bg = {
        
        currentImage        : 0,
        imageCount          : 0,
        wWidth              : 0,
        wHeight             : 0,
        autoTimer           : null,
        
        init: function() {

            _ = this;
            
            this.determineSizes();
            
            $('.backgroundTotalImages').html(this.imageCount);
            
            if(this.imageCount < 2) {
                $('#topImageSection').hide();
            }
            
            // Once the first image has loaded, load the rest
            $('#backgrounds img:nth-child(1)').imagesLoaded(function() {
                
                if(_.imageCount > 1) {
                    _.loadNextImage(2);
                    _.resetTimer();
                }
            });
        },
        
        resetTimer: function() {
            
            clearInterval(this.autoTimer);
            
            // Set the timeout to switch images
            this.autoTimer = setInterval(function() {
                arcadia.bg.next();
            }, 10000);
        },
        
        determineSizes: function() {
            
            _ = this;
            
            // Whats the size of the window?
            rootEl  = ("onorientationchange" in window) ? $(document) : $(window);
            
            wWidth  = rootEl.width();
            wHeight = rootEl.height();
            
            // Stop ie going mental!
            if(this.wWidth != wWidth || this.wHeight != wHeight) {
            
                this.wWidth         = wWidth;
                this.wHeight        = wHeight;
                this.imageCount     = 0;
                this.currentImage   = 0;
                
                $('#backgrounds img').each(function(i, el) {
                    
                    el = $(el);
                    
                    bgCss = {
                        left: 0,
                        top: 0
                    };
                    
                    // Determine the widths and ratios of the image
                    imgWidth  = el.attr('width');
                    imgHeight = el.attr('height');
                    
                    imgRatio  = imgWidth / imgHeight;
                    
                    bgWidth   = wWidth;
                    bgHeight  = bgWidth / imgRatio
                    
                    if(bgHeight > wHeight) {
                        bgOffset = (bgHeight - wHeight) / 2;
                        $.extend(bgCss, {
                            top: '-' + bgOffset + "px"
                        });
                    } else {
                        bgHeight = wHeight;
                        bgWidth = bgHeight * imgRatio;
                        bgOffset = (bgWidth - wWidth) / 2;
                        $.extend(bgCss, {
                            left: '-' + bgOffset + "px"
                        });
                    }
                    
                    el.width(bgWidth);
                    el.height(bgHeight);
                    el.css(bgCss);
                    
                    _.imageCount++;
                    
                    // If this is the first image, load it...
                    if(_.imageCount == 1) {
                        _.gotoImage(1);
                    }
                    
                });
            }
        },
        
        loadNextImage: function(which) {
            el = $('#backgrounds img:nth-child(' + which + ')');
            el.attr('src', el.attr('rel'));
            
            if(which <= this.imageCount) {
                $('#backgrounds img:nth-child(' + which + ')').imagesLoaded(function() {
                    arcadia.bg.loadNextImage(which + 1);
                });
            }
        },
        
        gotoImage: function (imageNumber) {
            
            // Hide/Show the images
            if(0 !== this.currentImage) {
                elRemove = $('#backgrounds img:nth-child(' + this.currentImage + ')');
                elShow   = $('#backgrounds img:nth-child(' + imageNumber + ')');
                
                elRemove.fadeOut(600, function() {
                    elShow.fadeIn(600);
                });
            } else {
                elShow   = $('#backgrounds img:nth-child(' + imageNumber + ')');
                elShow.fadeIn(600);
            }
            
            
            // Update
            $('.backgroundCurrentImage').html(imageNumber);
            
            if(this.imageCount > 1) {
                this.resetTimer();
            }
            this.currentImage = imageNumber;
        },
        
        prev: function() {
            
            n = (this.currentImage <= 1)
              ? this.imageCount
              : this.currentImage - 1;
            
            this.gotoImage(n);
        },
        
        next: function() {
            
            n = (this.currentImage >= this.imageCount)
              ? 1
              : this.currentImage + 1;
            
            this.gotoImage(n);
        }
    }
    
    $(function() { arcadia.init(); })
    
})(jQuery);
