//Rowntrees namespace

/*
HIGH

MEDIUM
• iOS support 
• Share and facebook buttons

LOW
• IE6 degrade - 4:00 hours 
*/

if($.browser.msie && $.browser.version < 7){
  $('#social').remove();
}

// Quick get element by ID
function gEBI(id){
  return document.getElementById(id);
}

//call google analytics on hash 
function fireGAEvent(hash)
{
  //_gaq.push(['_setAccount', 'UA-16835017-398']);
  _gaq.push(['_trackPageview', '/visitRoom/' + hash]);
}

var rowntrees = {
  //'Global' vars
  $window: $(window),
  panel : $('.panelContent'),
  $livePanes: $('section').filter(':has(.panelContent)'),
  iphone: false,

  //Initialisation function
  init : function() {

    this.device();
    this.panelManager.hidePanels();
    this.navigation.init(); 
    this.linkManager.init();
    this.panelManager.init();
    this.animationHandler.init();
    this.scrollHandler.init(); 
  },

  //Detect various devices we need to cater for
  device : function() {

    // If we are in IE6, sort out the menu hover state
    if($.browser.safari){ 
      rowntrees.viewport = $('body'); 
    } else { 
      rowntrees.viewport = $('html,body'); 
    }  
    
    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i))) {
      rowntrees.iphone = true;
    }
  },
  
  // ======================
  // = Navigation Handler =
  // ======================
  
  navigation: {
    init: function(){
      this.bindNavClicks();
      this.clickOnPanels();
      // If we are under ie6, fix the nav hover states
      if($.browser.msie && $.browser.version < 7){
        this.ie6.init();
      }
    },
    
    clickOnPanels : function() {
      rowntrees.$livePanes.bind('click', function(e){
        rowntrees.scrollHandler.scrollTo(this.id);
      });
    },
    
    bindNavClicks: function(){
      // Grab any internal hash links in the nav
      $scrollCollection = $('nav a[href*="#"]');

      $scrollCollection.click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        // Split the URL to get the hash, pass this to our scrollhandler
        // rowntrees.scrollHandler.scrollTo(this.href.split('#')[1]);
        rowntrees.linkManager.setHash(this.href.split('#')[1]);
      });

      // Grab our modal links
      $linkCollection = $('nav a[href^="./"]');
      
      $linkCollection.click(function(e){
        e.preventDefault();
        // rowntrees.modals.loadModal(this.href, this.className);
        rowntrees.linkManager.setModalHash(this.getAttribute('href'));
      });
      
    },
    
    ie6:{
      $nav: $('header'),
      
      init: function(){
        this.navigation();
        this.bindToScroll();
      },
      
      navigation: function(){
        var $sweetsMenu = $('li.products'),
          hoverstate = false;

        $sweetsMenu.hover(function(){
          if(hoverstate){
            $(this).stop(true).animate({
              height: 60
            });
            hoverstate = false;
          } else {
            $(this).stop(true).animate({
              height: 360
            });
            hoverstate = true;
          }
        });
      },
      
      navHideOnScrollStart: function(){
        rowntrees.navigation.ie6.$nav.stop().css({
          display: 'none'
        });
      },
      
      navShowOnScrollStop: function(){
        // Animate the scrollbar into view
        if(this.theTimeout){
          clearTimeout(this.theTimeout);
        }
        // Animate the scrollbar out
        this.theTimeout = setTimeout(function(){
          rowntrees.navigation.ie6.$nav.stop().css({
            display: 'block',
            position: 'absolute',
            top: rowntrees.scrollHandler.currentScrollPos - 200
          }).animate({
            top: rowntrees.scrollHandler.currentScrollPos
          });
        }, 800);
      },
      
      bindToScroll: function(){
        rowntrees.$window.bind('scrollstart', this.navHideOnScrollStart);
        rowntrees.$window.bind('scrollstop', this.navShowOnScrollStop);
      }
    } 
    
  },
  
  // ========================
  // = Modal Window Handler =
  // ========================
  
  modals: {
    currentModal: null,
    modalAnimating: false,
    modalOpen: false,
    modalVisible: true,
    _$modalFrame: $('#modalFrame'),
    $modalMask: $('#modalMask'),
    $modalLoader: $('#modalLoader'),
    modalReadyCallback: undefined,
    
    // Modal Loading animation (shown while awaiting iframe callback)
    loader : {  
      fadeIn: function(){
        // Show the loading animation
        rowntrees.modals.$modalLoader.stop(true).css({
          display: 'block',
          opacity: 0
        }).animate({
          opacity: 1
        }, 200);
      },
      fadeOut: function(){
        // Fade out the loader
        rowntrees.modals.$modalLoader.stop(true).animate({
          opacity: 0
        }, 200, function(){
          rowntrees.modals.$modalLoader.css({
            display: 'none'
          });
        });
      }
    },
    
    modalFrame: {
      slideIn: function(){
        
        if(rowntrees.iphone){
          var topPosition = rowntrees.scrollHandler.currentScrollPos + 30;

        } else {
          var theHeight = rowntrees.$window.height();
          // Scale to window height
          var topPosition = ~~((theHeight / 100) * 16) - 130;
        }
        
        rowntrees.modals._$modalFrame
        .stop(true)
        .show()
        .animate({
          top: topPosition
        },{
          duration: 1000, easing: "easeOutBounce", 
          complete : function(){
            rowntrees.modals.modalAnimating = false;
          }
        });
      },
      
      slideOut: function(callback){
        rowntrees.modals._$modalFrame.animate({
          top: -800
        },{
          duration: 300, 
          easing: "easeInSine", 
          complete: function() {

            $(this).css({
              top: -800,
              display: 'none'
            }).attr('src', 'about:blank');

            if(typeof(callback) === 'function'){
              callback.call();
            }
            _self.modalVisible = false;
          }
        });
      }
    },
    
    requestPageLoad: function(callback){
      this.modalVisible = false;
      this.loader.fadeIn();
      if($.browser.msie && $.browser.version <= 7){
        this._$modalFrame.stop(true).css({'display': 'none'});
          callback.call();
      } else {
        this._$modalFrame.stop(true).animate({'opacity': 0}, function(){
          callback.call();
        });
      }
    },
    
    modalReady : function(){
      var _self = rowntrees.modals,
        topPosition = 0;
      
      _self.loader.fadeOut();
      
      // If the modal is already open, we must have hit an internal modal link. In Which case, fade the modal in
      if(!_self.modalVisible){
        if($.browser.msie && $.browser.version <= 7){
          _self._$modalFrame.stop(true).css({'display': 'block'});
        } else {
          _self._$modalFrame.stop(true).animate({'opacity': 1});
        }
        
                

        _self.modalVisible = true;
      } else {

        if($.browser.msie && $.browser.version <= 7){
          var cssParams = {'display': 'block'};
        } else {
          var cssParams = {'opacity': 1};
        }

        _self._$modalFrame.css(cssParams);
        _self.modalFrame.slideIn();
        _self.modalVisible = true;
      }
    },
    
    closeModal : function(clear, callback, skipclose) {

      if($.browser.msie && $.browser.version < 7){
        this.currentPopup.close();
        return;
      }

      var _self = rowntrees.modals;
      
      _self.modalOpen = false;
      _self.currentModal = null;
      
      // Can skip the background mask if we are switching between modals
      if(!skipclose || rowntrees.iphone){
        _self.$modalMask.stop().animate({
          opacity: 0
        }, 400, function(){
          _self.$modalMask.css({
            display: 'none'
          });
        });
      }
      
      // Ensure we are looking at the callback
      if(typeof clear == 'function'){
        callback = clear;
        clear = undefined;
      }
      
      // Re-enable main window scroll
      rowntrees.scrollHandler.disableMainScroll(true);
      
      _self.modalFrame.slideOut(callback);
      
      // Clear the hash if set
      if(clear){
        rowntrees.linkManager.stripModalHash();
      }
    },
    
    //load the modal
    loadModal : function(url) {
            
      var _self = rowntrees.modals;
      
      function openModal(url, skipAnim) {
        
        // Set ugly modal windows for basic IE6 support (who still really cares tbh)
        if($.browser.msie && $.browser.version < 7){
          this.currentPopup = window.open(url,'name','height=680,width=830');
          rowntrees.linkManager.stripModalHash();
          return;
        }
        
        _self.modalAnimating = true;
        
        // Can skip the background mask if we are switching between modals
        if(!skipAnim || rowntrees.iphone){
          _self.$modalMask.css({
            display: 'block',
            opacity: 0
          }).stop().animate({
            opacity: 0.4
          }, 400);
        }
        
        // disable Scroll
        rowntrees.scrollHandler.disableMainScroll(false);
        
        _self.modalOpen = true;
        _self.currentModal = url;        
        
        _self.loader.fadeIn();
        
        // Now we need to await the callback from the iframe which will call the modalReady function above
        _self._$modalFrame.attr('src', url).css({
          display: 'block'
        });

      }


      if (_self.currentModal !== url && !_self.modalAnimating) {
        if (_self.modalOpen){
          _self.modalVisible = true;
          _self.modalAnimating = true;
          _self.closeModal(false, function(){
            openModal(url, true);
            _self.modalAnimating = false;
          }, true);
        } else {
          openModal(url);
        }    
      }    
    }
  },
  
  // ========================
  // = Panel Manager Object =
  // ========================  
  panelManager: {
    
    currentPanel: undefined,
    
    init: function(){
      this.hidePanels();
      this.bindClicks();
    },
    
    bindClicks: function(){
      var $modalRef = $('#main a[href*="./"]');
      
      $modalRef.click(function(e){
        e.preventDefault();
        e.stopPropagation();
        // Set the new hash from the href attribute (modalHash handler will sort out cross browser issues)  
        rowntrees.linkManager.setModalHash(this.getAttribute('href'));
      });
    },
    
    setPanel: function(panelName){
      
      if(this.currentPanel !== panelName){
        var $oldPanel = $('#' + this.currentPanel).find('.panelContent');
        var $newPanel = $('#' + panelName).find('.panelContent');
        // If css3 transitions are supported
        if(Modernizr.csstransitions){
          // Hide the old panel
          $oldPanel.animate({
            opacity: 0
          });
          // Reveal the new panel (odd usage is to work around css3 extentions)
          $newPanel.css({
            display: 'block',
            opacity: 0
          }).animate({
            opacity: 1
          });
        // Otherwise use those boring old jquery methods
        } else {
          $oldPanel.stop().fadeOut();
          $newPanel.stop().fadeIn();
        }
        
        // Set the $newPanel to be the $oldPanel
        this.currentPanel = panelName;
        
        // Update the page hash
        if(!rowntrees.linkManager.skipHashSet){
          rowntrees.linkManager.setHash(panelName);
        } else {
          // we have handled the initial hash, so no worries
          rowntrees.linkManager.skipHashSet = false;
        }
      }
    },

    hidePanels : function() {
      rowntrees.panel.hide();
    }
  },
  
  // =====================
  // = Animation Handler =
  // =====================
  animationHandler: {
    
    _sky1: gEBI('sky1'),
    _sky2: gEBI('sky2'),
    _sky3: gEBI('sky3'),
    
    _ground3: gEBI('ground3'),
    _ground2: gEBI('ground2'),
    _ground1: gEBI('ground1'),
    
    _fence: gEBI('fence'),
    
    _windowHeight: $(window).height(),
    
    init: function(){
      // ensure we update the paralax position as soon as the window is initialised
      this.fixBackgroundImages();
      this.parallaxAnimation(rowntrees.scrollHandler.currentScroll, true);
      // prevent alignment issues with the parallax if the user resizes the screen
      this.bindResizeEvent();
    },
    
    bindResizeEvent: function(){
      // This will ensure that the background paralax doesnt crop when the browser window is resized
      window.onresize = function(){
        rowntrees.animationHandler._windowHeight = $(window).height();
      };
    },
    
    fixBackgroundImages: function(){
      this._sky2.style.backgroundAttachment = 'fixed';
      this._sky1.style.backgroundAttachment = 'fixed';
    },
    
    parallaxAnimation: function(pos, force){
      
      function returnPosition(windowHeight, pos, adjuster, inertia){
        return ["50% ",~~(-((windowHeight + pos) - adjuster) * inertia),"px"].join('');
      }

      //sky middle layer
      if(pos < 1500 || force){
        this._sky2.style.backgroundPosition = returnPosition(this._windowHeight, pos, 900, 0.5);
      }
      
      // sky bottom layer
      if(pos < 2800 || force){
        this._sky1.style.backgroundPosition = returnPosition(this._windowHeight, pos, 1900, 0.3);
      }
      
      // If we are in view of the floor
      if(pos > 2000 || force){
        this._ground3.style.backgroundPosition = returnPosition(this._windowHeight, pos, 4500, 0.3);
        this._ground2.style.backgroundPosition = returnPosition(this._windowHeight, pos, 4300, 0.2);
        // this._ground3.style.backgroundPosition = returnPosition(this._windowHeight, pos, 2400, -0.2);
        // this._ground2.style.backgroundPosition = returnPosition(this._windowHeight, pos, 4000, -0.09);
      }
      
      if(pos > 2500 || force){
        this._fence.style.backgroundPosition = returnPosition(this._windowHeight, pos, 3853, 0.8);
      }
    }
  },
  
  // =========================
  // = Scroll Handler Object =
  // =========================
  
  scrollHandler: {
    _scrollInterval: null,
    animatingToPosition: false,
    checkVal: false,
    // duration between scroll checks
    _scrollInterval: 30,
    currentScrollPos: 0,
    // How far away the auto-scroll borders are
    _stickyScrollTolerance: 80,
    // How long it takes to register that scrolling has stopped (multiples of _scrollInterval)
    _scrollStopSensitivity: 15,
    //  After init contains map of panel heights for lookups
    _heightMap: {},
    // Default scroll time
    _scrollTime: 1000,
    scrolling: false,

    init: function(){
      this.buildHeightMap();
      this.bindScrollEvents();
      this.bindMouseWheelInterrupt();
    },
    
    disableMainScroll: function(enabled){
      if(rowntrees.iphone){
        this.iOsScrollingToggle(enabled);
      } else {
        this.desktopScrollingToggle(enabled);
      }
    },
    
    desktopScrollingToggle: function(enabled){
      
      var scrollTarget = $.browser.msie ? document : window;
      
      // This function will clear the animation event queue
      var mouseWheelHandler = function(e){
        // Failsafe for occasional firefox issues
        if(rowntrees.scrollHandler.checkVal){
          e.preventDefault();
          e.stopPropagation();
          return false;
        }
      };

      if(enabled){
        rowntrees.scrollHandler.checkVal = false;
        if (window.removeEventListener) window.removeEventListener('DOMMouseScroll', mouseWheelHandler, false);
        /** IE/Opera. */
        scrollTarget.onmousewheel = null;
      } else {
        rowntrees.scrollHandler.checkVal = true;
        // The following binds are used to trigger mouse input
        /** for Mozilla. */
        if (window.addEventListener) window.addEventListener('DOMMouseScroll', mouseWheelHandler, false);
        /** IE/Opera. */
        scrollTarget.onmousewheel = mouseWheelHandler;
      }
    },
    
    iOsScrollingToggle : function(enabled){
      function preventScroll(e){
        e.preventDefault();
        e.stopPropagation();
      }
      // This should prevent people from scrolling away from the modal window without closing it
      if(enabled){
        document.body.removeEventListener('touchmove',preventScroll,false);
      } else {
        document.body.addEventListener('touchmove',preventScroll,false);
      }
    },
    
    buildHeightMap: function(){
      // This function will create a lookup table for id's so that we can quickly scroll to their position without an offset lookup
      var _self = this;
      rowntrees.$livePanes.each(function(idx){
        _self._heightMap[this.id] = $(this).offset().top;
      });
    },
    
    currentScroll: function(){
      return rowntrees.$window.scrollTop();
    },
    
    bindMouseWheelInterrupt: function(){
      // This function will clear the animation event queue
      var mouseWheelHandler = function(e){
        rowntrees.viewport.stop(true);
      };
      
      // The following binds are used to trigger mouse input
      /** for Mozilla. */
      if (window.addEventListener) window.addEventListener('DOMMouseScroll', mouseWheelHandler, false);
      /** IE/Opera. */
      window.onmousewheel = document.onmousewheel = mouseWheelHandler;
    },
        
    scrollTo: function(id, callback, scrollTime){
      // If id isnt set, or isnt present in the heightMap, search the dom for this id
      
      var scrollTarget;
      
      if(this._heightMap[id]){
        scrollTarget = this._heightMap[id];
      } else {
        var $toCheck = $('#' + id).offset();
        scrollTarget = $toCheck && $toCheck.top;
      }

      //var scrollTarget = this._heightMap[id] ? this._heightMap[id] : $('#' + id).offset().top,
      // Test oir callback to see if its a number, if so, it should be scrollTime
      var newScrollTime = typeof(callback) === 'number' ? callback : scrollTime || this._scrollTime;
        // In which case, callback might not be a function, so lets ensure thats undefined now
        callback = typeof(callback) === 'function' ? callback : undefined;
      
      // if we have no scroll target, break out of this function
      if(!scrollTarget) return false;
      
      // Offset is should align the target floor to the center of the users screen
      var offset = (scrollTarget - ~~((rowntrees.$window.height() / 2) - 249.5));
      
      // Clear animation queue and animate to new position, call callback if present
      rowntrees.viewport.stop(true).animate({
        scrollTop: offset + 'px'
      }, newScrollTime, function(){
        if(callback){
          callback();
        }
      });
    },
    
    scrollToNearestPane: function(){
      
      _self = rowntrees.scrollHandler;
      
      var scrollPos = _self.currentScrollPos,
        firstTarget;
                
      // Get the nearest pane
      for(i in _self._heightMap){
        if(_self._heightMap[i] > scrollPos){
          firstTarget = i;
          break;
        }
      }
      
      // If we have a target, lets go!
      if(firstTarget){
        var distanceToFirst = scrollPos - _self._heightMap[firstTarget];
        rowntrees.panelManager.setPanel(firstTarget);
      }
    },
      
    bindScrollEvents : function() {
      
      var _self = this;
      
      // iPhone / iPad scroll handling
      function iOsScrollPoller(){
        // Set our scroll value for reference
        _self.currentScrollPos = rowntrees.$window.scrollTop();
        // Manually trigger our scroll stop event
        rowntrees.$window.trigger('scrollstop');
      }

      // desktop browser scroll handler
      function scrollPoller(){
        var newScrollPos = rowntrees.viewport[0].scrollTop;
        // Check to see if we need to animate the paralax
        if(this.lastScrollPos !== newScrollPos){
          this.scrollStopCount = 0;
          // If not scrolling
          if(!_self.scrolling){
            _self.scrolling = true;
            // trigger the scroll start event
            rowntrees.$window.trigger('scrollstart');
          }
          // Call animation
          _self.scrollingEvent(newScrollPos);
          _self.currentScrollPos = newScrollPos;
        } else {
          this.scrollStopCount += 1;
          if(this.scrollStopCount == _self._scrollStopSensitivity){
            rowntrees.$window.trigger('scrollstop');
            _self.scrolling = false;
          }  
        }
        // update the last scrolled position
        this.lastScrollPos = newScrollPos;
      }
      
      // Bind the interval that checks scroll position
      if(rowntrees.iphone){
        // bind a scroll handler
        rowntrees.$window.scroll(iOsScrollPoller);
      } else {
        // set up scroll polling
        this._scrollInterval = setInterval(scrollPoller, this._scrollInterval);
      }
            
      // Bind the custom events that will handle the scrolling start/stop
      rowntrees.$window.bind('scrollstop', this.scrollStop);
    },

    scrollingEvent: function(pos){
      if(!$.browser.msie){
        rowntrees.animationHandler.parallaxAnimation(pos);
      }
    },
    
    scrollStop: function(){
      // When the user stops scrolling, lets move to the nearest pane
      rowntrees.scrollHandler.scrollToNearestPane();
    }
  },
  
  // =======================================================
  // = Handle any link related functionality (hashing etc) =
  // =======================================================
  
  linkManager: {
    modalLink: false,
    // Holds timer for IE hashing
    hashTimer: null,
    // A holder for the last hash we were looking at
    oldHash: null,
    // Prevents the hash change from causing navigation
    skipHashSet: false,
    
    init: function(){
      this.bindHashChange();
      // Checks the hash on-load to ensure we scroll to the right location
      this.checkHashOnLoad();
    },
    
    generateModalHash: function(modalRef){
      // Change filter method per browser
      if($.browser.msie && $.browser.version <= 7){
        // Ie <7 will only return the full href property even when accessed via getAttribute, so we need to filter this out
        var base = window.location.href.substring(0, window.location.href.lastIndexOf("/"));
        modalRef = '/' + modalRef.replace(base,'');
      }
      
      // If no location has been set and a user quickly clicks a nav, we may have only a single hash or no hash. 
      // In which case, they will have been heading to the #welcome screen, so lets ensure they end up there while the modal initialises
      if(document.location.hash === '' || document.location.hash === '#'){
        var documentHash = '#welcome';
        // make sure the next event is overidden
        this.skipHashSet = true;
      } else {
        var documentHash = document.location.hash;
      }
      
      // Otherwise, we are all good, just do the filtering
      return documentHash + modalRef.replace(/./, '');
    },

    setModalHash: function(modalRef){
      // If there is a modal open, we need to remove its hash before we can procede      
      if(rowntrees.modals.modalOpen){
        this.stripModalHash();
      } 
      // Generate the new hash
      var newHash = this.generateModalHash(modalRef);
      
      this.setHash(newHash);
    },

    setHash: function(hash){
      // Remove the hash 'payload'
      var hash = hash.replace( /^#/, '' );
      
      fireGAEvent(hash);
      
      // Append a hash (hax)
      var node = $( '#' + hash );
      
      // remove the ID from the referenced hash (stop scroll)
      if ( node.length ) {
        node.attr( 'id', '' );
      }
      
      // Set the hash
      document.location.hash = hash;
    
      // re-apply the ID so the properties once again make sense
      if ( node.length ) {
        node.attr( 'id', hash );
      }
    },
    
    stripModalHash: function(){
      var newHash = document.location.hash.split('/',1)[0];
      this.setHash(newHash);
    },

    bindHashChange: function(){
      var _self = this;

      if($.browser.msie && $.browser.version <= 7){
        // set a timer to check for hash changes
        this.hashTimer = setInterval(function(){
          var newHash = document.location.hash;
          if (newHash !== _self.oldHash){
            _self.hashHandler();
          }
          _self.oldHash = newHash;
        }, 200);
      } else {
        rowntrees.$window.bind('hashchange', function(e) {
          e.preventDefault();
          _self.hashHandler();
        });      
      }
      
    },
    
    hashHandler: function(){
      
      var modalToLoad = false,
        currentHash = document.location.hash.replace( /^#/, '' );
      
      if(currentHash == ''){
        return;
      }
        
      var splitHash = currentHash.split('/');
      
      // If we have more than 1 element we have a split hash
      if(splitHash.length > 1) {
        // Set the currentHash to the first array item
        currentHash = splitHash[0];
        // Remove the first element of the array
        splitHash.shift();
        // Join the array together
        splitHash = splitHash.join('/');
        // append the local addition to setup the relative url
        modalToLoad = './' + splitHash;
      } else {
        // we dont need to skip
        this.skipHashSet = false;
        rowntrees.modals.modalOpen ? rowntrees.modals.closeModal('true') : 0;
      }
      
      // Only scroll to new panel if we are not on an iOs device
      if(!rowntrees.iphone){
        // Scroll to the new hash location
        rowntrees.scrollHandler.scrollTo(currentHash);
      }
      
      // If we had a split hash, then load up a modal from the split
      if(modalToLoad){
        rowntrees.modals.loadModal(modalToLoad,currentHash);
      }
      
    },

    checkHashOnLoad: function(){
      var _self = this;
      // If we are loading to the roof, or loading with no hash
      if((!document.location.hash || document.location.hash === '#roof') && !rowntrees.iphone){
        window.setTimeout(function(){
          // scroll to the bottom of the page unless we are on iOs
          rowntrees.scrollHandler.scrollTo('welcome', 6000);
        }, 500);
      } else {
        window.setTimeout(function(){
          _self.hashHandler();
          _self.skipHashSet = true;
        }, 0);
      }
    }
    
  },
  
  // ====================
  // = Image Pre-Loader =
  // ====================
  
  preloader: {
    
    $progressBar: $('#loadingbar').find('span'),
    $loadingBlock: $('#loading'),
    $loaderWrap: $('.rope'),
    
    init: function(){
      if($.browser.msie && $.browser.version < 7){
        this.ie6loader();
      }
      this.load();
      this.checkForLoad();
    },
    // Array of images that require pre-loading
    preloadArray: [
      '/media/3352/loaderBGtile.png',
      '/media/3357/loaderRope.jpg',
      '/media/3347/loaderBG.jpg',
      '/media/3657/sky1.png',
      '/media/3667/sky2.png',
      '/media/3677/sky3.png',
      '/media/3782/sky4.jpg',
      '/media/3142/exterior_roof.png',
      '/media/3147/exterior_rowntrees.png',
      '/media/3137/exterior_products.png',
      '/media/3132/exterior_floor3.png',
      '/media/3127/exterior_floor2.png',
      '/media/3122/exterior_floor1.png',
      '/media/3117/exterior_entrance.png',
      '/media/3317/inner_floor1.png',
      '/media/3327/inner_floor2.jpg',
      '/media/3332/inner_floor3.jpg',
      '/media/3337/inner_products.jpg',
      '/media/3342/inner_rowntrees.jpg',
      '/media/3282/ground1.png',
      '/media/3287/ground2.png',
      '/media/3292/ground3.png'
    ],
    // will be filled with loading images
    loadingImages: [],
    // holds our timer ref
    timer: null,
    
    ie6loader: function(){
      $('#container').css({
        display: 'none'
      });
      
      $('body').append('<p id="ie6load">Loading <span id="percentage">0%</span>, please wait</p>');
      this.$ie6percent = $('#percentage'); 
    },
    
    load: function(image){
      for(i in this.preloadArray){
        var newLoading = new Image();
        newLoading.src = this.preloadArray[i];
        this.loadingImages.push(newLoading);
      } 
    },
    
    checkForLoad: function(callback){
      _self = this;

      this.timer = setInterval(function(){

        var loadedCount = 0,
          icl = _self.loadingImages.length; 

        while(icl--){
          if (_self.loadingImages[icl].complete)
            loadedCount++;
        }

        // Update the loader progess
        _self.updateProgress(loadedCount, _self.loadingImages.length);
          
        if(loadedCount >= _self.loadingImages.length){
          clearInterval(_self.timer);
          _self.loadComplete();
        }
        
      }, 100);
    },
    // updates our progress bar
    updateProgress: function(loaded, totalToLoad){

      var loadPercent = (100/totalToLoad) * loaded;
      
      if($.browser.msie && $.browser.version < 7){
        this.$ie6percent.html(~~loadPercent + '%');
        return;
      }

      this.$progressBar[0].style.left = ~~((175/100) * loadPercent) + 'px';
    },
    // function is called when load is complete
    loadComplete: function(){
      // init when loaded
      if($.browser.msie && $.browser.version < 7){
        $('#container').css({
          display: 'block'
        });
        
        // This needs to fire after the init to ensure everything is calculated correctly
        rowntrees.init();

        $('#ie6load').remove();
        this.$loadingBlock.remove();

      } else {      
        rowntrees.init();
        
        // animate our and remove the loader
        this.$loadingBlock.animate({
          opacity: 0
        }, function(){
          $(this).remove();
        });
      }
    } 
  }
};

// Begin with the pre-loader
rowntrees.preloader.init();
