function $t(term){
  document.write(TinaSu.getTerm(term));
}

var TinaSu = {
  rootDir: "/",
  MAIN_MENU: 0, /* Constants for each menu panel state */
  SUB_MENU:  1,
  PAGE_MENU: 2,
  MENU_TIMEOUT: 1000,
  _smallScreen: false,
  _defaultMenuPanel: this.MAIN_MENU,
  _animation: { menu: false },
  _parsedMenu: "",
  _subMenus: [],
  _subMenuDisplayNames: [],
  _activeSubMenuIndex: -1,
  _menuPanelTimeout: null,
  currentMenuPanel: 0,
  id: "", // unique identifier for this page.

  cubic: function(pos) {
    pos /= 0.5;
    return pos<1 ? 
            0.5*pos*pos*pos : 
            0.5*((pos-2)*(pos-2)*(pos-2)+2);
  },

  /* @param id unique name to identify current page
   * @param currentPanel(optional) load given panel instead of main
   */
  initialize: function(id){
    TinaSu.id     = id;
    TinaSu.parseMenu();

    if(Engine.isMSIE) TinaSu.enableIESupport();
    Event.observe(window,'resize',TinaSu.redraw);
    TinaSu.redraw();

    /* Load specified menu panel if necessary */
    if( arguments[1] && 
        arguments[1] != this._defaultMenuPanel) {
      this._defaultMenuPanel = arguments[1];
      if( this._activeSubMenuIndex>-1 && 
          this._defaultMenuPanel==this.SUB_MENU) {
        TinaSu.openSubmenu(this._activeSubMenuIndex,{animation:false});
      } else {
        TinaSu.showMenuPanel(this._defaultMenuPanel,{animation:false});
      }
    }
    if(this._activeSubMenuIndex > -1) {
      this._renderSubMenu(this._activeSubMenuIndex);
    }

    /* Setup timers to restore menu */
    ['menu-left','menu-right'].each(function(side){
      if($(side)){
        /* bindAsEventListener: The returned function 
         * will have the current event object as its argument. */
        Event.observe(side,'mouseout',this.startMenuPanelTimeout.bindAsEventListener(this));
        Event.observe(side,'mousemove',this.clearMenuPanelTimeout.bindAsEventListener(this));
      }
    }.bind(this));

/*    
    
    // Clicking on the logo in the bottom (any image)
    // will take you back to the start
    if($('logo') && !$('logo').hasClassName('noscroll'))
      Event.observe('logo','click',function(){new Effect.HScrollTo(0)}); 
*/    
    // Setup Spacer Control between all the browse pages.
    $$('div.spacer-column').each(
      function(s,i) {
        Event.observe(s, 'click', function(event) {
          TinaSu.spacerEvent ? 
            TinaSu.spacerEvent(i, Event.localPointer(event)[0]<33 ? 
                                  1 : -1) : 
            new Effect.HScroll(Event.localPointer(event)[0]<33 ? 
                               821 : -821);
        });
        // Update mouseover hover styles
        Event.observe(s, 'mousemove', function(event){
          var d = Event.localPointer(event)[0]<33 
                    ? '-'+Browse.MENU_MARGIN_WIDTH 
                    : '-'+Browse.MENU_MARGIN_WIDTH*2;
          s.style.backgroundPosition = d + 'px 0px';
        });
        Event.observe(s,'mouseout',function(event){
          s.style.backgroundPosition = '0px 0px';
        });
      }
    );
    
    if(Engine.isMSIE){
      $$('a').each(
        function(n){ n.hidefocus = 'hidefocus' }
      );
    }
  }, // End Initialize

  parseMenu: function() {
    function _renderItem(item){
      var cl = (TinaSu.id == item.id) ? ['active'] : [];
      if(item.klass) cl.push(item.klass);
      var c = '';
      var url = "http://" + location.host + item.url;
      if(item.secure) {
        url = "https://" + location.host + item.url;
      } 
      if(cl.length>0) c = ' class="'+cl.join(' ')+'"';
      TinaSu._parsedMenu += '<p><a href="'+url+'"'+c+'>'
                        +  item.name.escapeHTML().gsub(/\n/,'<br/>').gsub(/\s/,'&nbsp;')+'</a></p>';
    }
    function _renderSubmenuItem(item){
      if(TinaSu.id == item.id){
        TinaSu._activeSubMenuIndex = currentSubMenuIndex;
      }
      var cl = (TinaSu.id == item.id) ? ['active'] : [];
      if(item.klass) cl.push(item.klass);
      var c = '';
      if(cl.length>0) c = ' class="'+cl.join(' ')+'"';
      
      TinaSu._subMenus[currentSubMenuIndex] += '<p><a href="http://' + location.host + item.url+'"'+c+'>'+item.name.escapeHTML().gsub(/\n/,'<br/>').gsub(/\s/,'&nbsp;')+'</a></p>';
    }
    function _renderSubmenu(submenu){
      currentSubMenuIndex++;
      TinaSu._subMenus.push('');
      
      var cl = ['submenu'];
      if(submenu.klass) cl.push(submenu.klass);
      var displayName = submenu.name.escapeHTML().gsub(/\s/,'&nbsp;');
      
      TinaSu._parsedMenu += '<p><a class="'+cl.join(' ')+'" href="#" onclick="TinaSu.openSubmenu('+currentSubMenuIndex+'); return false">'+displayName+'</a></p>';
      TinaSu._subMenuDisplayNames[currentSubMenuIndex] = displayName;
      if(submenu.item) submenu.item.each(_renderSubmenuItem);
    }
    function _renderList(list){
      if(list.item)    list.item.each(_renderItem);
      if(list.submenu) list.submenu.each(_renderSubmenu);
    }
    function _renderBlock(block){
      if(block.item) block.item.each(_renderItem);
      if(block.list) block.list.each(_renderList);
      TinaSu._parsedMenu += "<br style='line-height:1.5em'/>";
    }

    // Start parseMenu
    var currentSubMenuIndex = -1;
    
    TinaSu._parsedMenu = '';
    TinaSu._menu.block.each(_renderBlock);

    ['menu-left','menu-right'].each(function(side){
      if($(side+'-main')) $(side+'-main').update(TinaSu._parsedMenu);
    });
  }, //end parseMenu

  _renderSubMenu: function( subMenuIndex ){

    var subMenuAction = "";
    if (BROWSE_LAYOUT_TYPE && BROWSE_LAYOUT_TYPE == 'gallery') {
        subMenuAction =
        '<ul class="actions">'+
        '  <li><a href="#" onclick="Browse.turnPage(1); return false">'+
        this._menu.term['first page'] +
        '</a>'+
        '  </li>'+
        '  <li><a href="#" onclick="Browse.turnPage('+
        (BROWSE_PAGES+1) +
        '); return false">'+
        this._menu.term.overview +                            
        '</a>'+
        '  </li>'+
        '</ul>';
    }

    if($('menu-left-submenu')) {
      $('menu-left-submenu').update(
        '<div class="title">'+ 
        this._subMenuDisplayNames[subMenuIndex]+':</div>'+
        this._subMenus[subMenuIndex]+
        subMenuAction +
        '<p class="level-up"><a href="#" onclick="TinaSu.showMenuPanel(TinaSu.MAIN_MENU);return false">' +
        this._menu.term.main +
        '</a></p>'
      );
    }
    if($('menu-right-submenu')) {
      $('menu-right-submenu').update(
        '<div class="title">'+ 
        this._subMenuDisplayNames[subMenuIndex]+':</div>'+
        this._subMenus[subMenuIndex]+
        subMenuAction +
      '<p class="level-up"><a href="#" onclick="TinaSu.showMenuPanel(TinaSu.MAIN_MENU);return false">' +
      this._menu.term.main +
      '</a></p>'
      );
    }
  },

  /* @param panel a number representing the current menu navigation
   * state. 0 means show the main menu, 
   *        1 means show sub menu,
   *        2 means show page menu.
   * @param options(optional) hash of key value pairs,
   *        currently supporting animation and restore.
   */
  showMenuPanel: function(panel){
    if(TinaSu._animation.menu) return;
    
    var options =  Object.extend({
      animation: true,
      restore:   false
    }, arguments[1] || {});
        
    if(options.restore && this._activeSubMenuIndex > -1) {
      this._renderSubMenu(this._activeSubMenuIndex);
    }

    /* Move menu panel without animation */
    if(!options.animation){
      if($('menu-left-scroll')) {
        var leftPx = -$('menu-left').offsetWidth * panel + 'px';
        $('menu-left-scroll').style.left = leftPx;
        $('menu-left-background').style.left = leftPx;
      }
      if($('menu-right-scroll')) {
        var rightPx = -$('menu-right').offsetWidth * (2-panel) + 'px';
        $('menu-right-scroll').style.left = rightPx;
        $('menu-right-background').style.left = rightPx;
      }
      TinaSu.currentMenuPanel = panel;
      return;
    }
    
    TinaSu._animation.menu = true;
    if($('menu-left-scroll')) {
       new Effect.Move('menu-left-scroll',{ 
         x: -(panel-TinaSu.currentMenuPanel)*$('menu-left').offsetWidth,
         transition: TinaSu.cubic, 
         duration: 0.6,
         afterUpdate: function(){
           $('menu-left-background').style.left = 
                   $('menu-left-scroll').style.left;
           },
         afterFinish: function(){
           TinaSu.currentMenuPanel = panel;
           TinaSu._animation.menu = false;
         }
       });
    }
    if($('menu-right-scroll')) {
       new Effect.Move('menu-right-scroll',{ 
         x: (panel-TinaSu.currentMenuPanel)*$('menu-right').offsetWidth,
         transition: TinaSu.cubic, 
         duration: 0.6,
         afterUpdate: function(){
           $('menu-right-background').style.left =
                   $('menu-right-scroll').style.left;
           },
         afterFinish: function(){
           TinaSu.currentMenuPanel = panel;
           TinaSu._animation.menu = false;
         }
       });
    }
  }, /* showMenuPanel */

  openSubmenu: function( subMenuIndex ){
    if(this._animation.menu) return;
    if($('menu-left-submenu')) {
      $('menu-left-submenu').update(
        this._subMenus[subMenuIndex]+
        '<p class="level-up"><a href="#" '+
        'onclick="TinaSu.showMenuPanel(TinaSu.MAIN_MENU);return false">' +
        this._menu.term.main +
        '</a></p>'
      );
    }
    if($('menu-right-submenu')) {
      $('menu-right-submenu').update(
        this._subMenus[subMenuIndex]+
        '<p class="level-up"><a href="#" '+
        'onclick="TinaSu.showMenuPanel(TinaSu.MAIN_MENU);return false">' +
        this._menu.term.main +
        '</a></p>'
      );
    }
    TinaSu.showMenuPanel(TinaSu.SUB_MENU,arguments[1]||null);
  },

  redraw: function(){
    var scrollLeft = Position.scrollX();
    var height     = Position.getPageSize().window.height;
/**  
    $('logo').setStyle({ top: ((height-Browse.MENU_HEIGHT)/2)+(TinaSu._smallScreen ? 400 : 492)+'px' });
    if($('layout').offsetLeft > 0) $('logo').setStyle({
      marginLeft: $('layout').offsetLeft-68-22+'px'
    });
*/
    if($('thumbs-icon'))
      $('thumbs-icon').setStyle({ top: ((height-Browse.MENU_HEIGHT)/2)+492+'px' });
   
    var t = (height-Browse.MENU_HEIGHT)/2;
    $('layout').setStyle({top:(t<0?0:t-10)+'px'});
  },

  setSpacerEvent: function(callback){
    TinaSu.spacerEvent = callback;
  },

  enableIESupport: function(){
    TinaSu.redraw = function(){
      var scrollLeft = Position.scrollX();
      var height     = Position.getPageSize().window.height;
/*      
      if($('layout').offsetLeft > 0) $('logo').setStyle({
        marginLeft: $('layout').offsetLeft+'px'
      });
      
      $('logo').setStyle({
        top:  ((Position.getPageSize().window.height-Browse.MENU_HEIGHT)/2)+(TinaSu._smallScreen ? 400 : 492)+'px',
        left: (Position.scrollX()+36)+'px'
      });
*/            
      var t = (height-Browse.MENU_HEIGHT)/2;
      $('layout').setStyle({top:(t<0?0:t)+'px'});
    }
    $('page-body').addClassName('ie6');
/*
    Event.observe(window,'scroll',function(){
      $('logo').setStyle({
        top:  ((Position.getPageSize().window.height-Browse.MENU_HEIGHT)/2)+(TinaSu._smallScreen ? 400 : 492)+'px',
        left: (Position.scrollX()+36)+'px'
      });
    });
*/
  },
  startMenuPanelTimeout: function(event) {
    if($('menu-left')) {
      var p = Event.localPointer(event,'menu-left');
      if(p[0]>0 && p[0]<Browse.MENU_WIDTH && p[1]>0 && p[1]<Browse.MENU_HEIGHT) return;
    }
    if($('menu-right')) {
      var p = Event.localPointer(event,'menu-right');
      if(p[0]>0 && p[0]<Browse.MENU_WIDTH && p[1]>0 && p[1]<Browse.MENU_HEIGHT) return;
    }
    this.clearMenuPanelTimeout();
    if (typeof(TinaSu._defaultMenuPanel) == 'undefined') {
            TinaSu._defaultMenuPanel = TinaSu.MAIN_MENU;
    }
    this._menuPanelTimeout = setTimeout( 
      function(){ 
        TinaSu.showMenuPanel(TinaSu._defaultMenuPanel,{restore:true}) 
      }, TinaSu.MENU_TIMEOUT
    );
  }, /* end enableIESupport() */

  clearMenuPanelTimeout: function(){
    if(this._menuPanelTimeout) {
      clearTimeout(this._menuPanelTimeout);
      this._menuPanelTimeout = null
    }
  },

  getTerm: function(term) {
/*          if (typeof this._menu == "undefined" || typeof this._menu.term == "undefined") {return "NONE";} */
    return this._menu.term[term] || '!('+term+')';
  },

  setMenu: function(menu){
    this._menu = menu;
  }
}; /* End TinaSu */

var Browse = {
    _tfx: null, // TODO Better Name
    _sfx: null, // TODO Better Name
    _loaded: false,
    _pos: [],
    _loaderTimeout: 0,
    MENU_WIDTH: 227, /* 236*/
    FIRST_PAGE_LEFT: 292, /* 301 */
    MENU_HEIGHT: 475,
    MENU_MARGIN_WIDTH: 65, /* Width for the controls between pages */
    PAGE_WIDTH: 750,
    PAGE_N_CONTROL_WIDTH: 750+65, // size of each page panel + 
                                  // its controls
    MENU_N_MARGIN_WIDTH: 292, // Size of menu panel and side margin

    initialize: function() {

      this.options = Object.extend({
        hasOutlines: false
      }, arguments[0] || {});
      
/* NEAT but we don't need. Inserting tags to contain details and other prep of details.      
      $$('div.catalog-page').each( function(p,idx){
        new Insertion.Bottom(p.down('div.lightbox'),
          '<div class="panel1-background"> </div>'+
          '<div class="panel2-background"> </div>'+
          '<div class="panel3-background"> </div>');
        p.down('div.details-button').hide().down('div.content').update(TinaSu.getTerm('show outlines'));
      });
*/      
      Browse.cachePagePositions();
      Event.observe(window, 'resize', Browse.cachePagePositions);
    },

    cachePagePositions: function() {
      Browse._pos = [];
      Position.prepare();
      $$('div.catalog-page').each(function(p,idx){
        var pos = Position.page(p);
        pos.push(pos[0]+Browse.PAGE_WIDTH);
        pos.push(pos[1]+Browse.MENU_HEIGHT);
        Browse._pos.push(pos);
      });
    },

    /* @param page - the page number to focus on
     * @return true iff page turning successed
     */
    turnPage: function( page ) {
      if(!Browse._loaded) return;
      if(Browse._tfx && Browse._sfx==page) return;
      var w = Position.getPageSize().window.width;
      var p = Browse.FIRST_PAGE_LEFT 
              + (Browse.PAGE_WIDTH + Browse.MENU_MARGIN_WIDTH)
              * (page - 1);
      if(Browse._tfx) Browse._tfx.cancel();
      Browse._sfx = page;
      var d = (p - (w - Browse.PAGE_WIDTH)/2) - Position.scrollX();
      if(d == 0) return false;
      Browse._tfx = new Effect.HScrollTo((p - (w - Browse.PAGE_WIDTH)/2),{
        duration: (Math.log(Math.abs(d*d))/10),
        transition: TinaSu.cubic,
        afterFinish: function(){Browse._tfx = null}
      });
      return true;
    },

    loadVisiblePages: function(){

      if(!Browse._loaded) return;
      if(Browse._loaderTimeout) clearTimeout(Browse._loaderTimeout);

      Browse._loaderTimeout = setTimeout( function() {
        // p is the horizontal position(px) in the browser 
        // page where the current viewable area starts.
        var p = window.pageXOffset || 
                document.documentElement.scrollLeft || 
                document.body.scrollLeft || 0;
        // Size of the current window.
        var w = Position.getPageSize().window.width; 
        // Parts that are viewable horizontally are pixels
        // between p and p+w

        // Go through each catalog page index and get a list of pages
        // that needs to be visual
        var visibles = [];
        $R(1, BROWSE_PAGES).each( function(i) {

          // x is the horizontal position(px) where 
          // image number i starts
          var x = Browse.MENU_N_MARGIN_WIDTH + 
                  (i-1) * Browse.PAGE_N_CONTROL_WIDTH;
          
          // if the current image starts within viewable. add this.
          if(x>p && x<(p+w)) visibles.push(i);
          // if the next image starts within viewable. add current image.
          if((x+Browse.PAGE_WIDTH)>p && 
             (x+Browse.PAGE_WIDTH)<(p+w)) visibles.push(i);
        }); 

        visibles.each( function(i) {
          // Only load images that have not been loaded 
          if( $('page_'+i).hasClassName('loaded') ) {
            return;
          }
          $('page_'+i).addClassName('loading');

          // Ajax call to load the image
          Loader.load( BROWSE_URL + i + BROWSE_EXT, {

            onComplete: function(img) {

              $('image_'+i).setOpacity(0);
              setTimeout( function(){
                $('image_'+i).src = img;
                new Effect.Opacity( 'image_'+i,
                {   from: 0.0,
                    to:   1.0,
                    afterFinish: function() {
                      $('page_'+i).addClassName('loaded').removeClassName('loading') 
                    } // afterFinish
                });   // Effect.Opacity
              }, 1);  // setTimeout
            }         // onComplete
          });         // Loader.load
        }); // loop through list of  visibles

        var lastImageStartX = Browse.MENU_N_MARGIN_WIDTH + 
                              BROWSE_PAGES*Browse.PAGE_N_CONTROL_WIDTH;
        // Load thumbnails if the start of the last image is visible.
        if( lastImageStartX<(p+w) ) {
          $R(1, BROWSE_PAGES).each( function(i) {
            Loader.load( BROWSE_URL + i + '-small' + BROWSE_EXT,{
              onComplete:function(img){
                $('thumb_'+i).setOpacity(0);
                $('thumb_'+i).src = img;
                new Effect.Opacity('thumb_'+i,{from:0.0,to:1.0});
              }
            });
          });
        }
      }, 250); // Browse._loaderTimeout
    } // loadVisiblePages
};

/*document.write('<script type="text/javascript" src="'+TinaSu.rootDir+'json/menu.js"></script>');*/
document.write('<script type="text/javascript" src="http://www.tinasu.com/json/menu.js"></script>');

/* mailing list */
var ml = {
        SUCCESS: 1,
        FAILURE: 0,
        submit: function() {
                var email = $('email').value;
                if (email == "") {
                        alert("Please enter an email address.");
                        return false;
                }
                var params = "email="+email;
                ml.request = new Ajax.Request(
                   "/ajax/mailinglist.php",
                   {
                        method:      'get',
                        parameters:  params,
                        asynchronous:true,
                        evalScripts: true,
                        onComplete:  ml.remoteUpdateHandleOnComplete,
                        onFailure:   ml.remoteUpdateHandleOnFailure,
                        onException: ml.remoteUpdateHandleOnException
                   }
                );
        },
        remoteUpdateHandleOnFailure: function(request) {
                alert("failure " + request.responseText);
        },
        remoteUpdateHandleOnExecption: function(request) {
                alert("expeption" + request.responseText);
        },
        remoteUpdateHandleOnComplete: function(request) {
                ml.request = 0;
                var result = eval('(' + request.responseText + ')');
                if (result.code == ml.SUCCESS) {
                        hideElement('email');
                        hideElement('submit');
                        hideElement('formErrorMsg');
                        showElement('formSuccessMsg');
                } else {
                        $('formErrorMsg').innerHTML = result.msg;
                        hideElement('formSuccessMsg');
                        showElement('formErrorMsg');
                }
        }
};

var intro = {
        totalImages:  4,
        currentImage: 3,
        imagesDir:    "/images/splash/",
        isFirstImg:   true,

        getNextImage: function() {
                var imageNum = intro.currentImage;
                if (intro.currentImage == intro.totalImages) {
                        imageNum = 1;
                } else {
                        imageNum++;
                }
                return imageNum;
        },
        init: function() {
                for(var i=1; i<=intro.totalImages; i++) {
                        var imgName = "introImg" + i;
                        $(imgName).src = intro.imagesDir + i + ".jpg";
                }
                intro.setTimer();
        },
        setTimer: function() {
                setTimeout("intro.changeImage()", 3500);
        },
        changeImage: function() {
                var newNum = this.getNextImage();
                var curNum = this.currentImage;
                this.currentImage = newNum;
                
                if (intro.isFirstImg) {
                        curNum = 0;
                        intro.isFirstImg = false;
                }

                var currentName = "introImgDiv" + curNum;
                var newName     = "introImgDiv" + newNum;

                Effect.Fade(currentName);
                Effect.Appear(newName);
                intro.setTimer();
        }
};

function hideElement( elementId ) {
        var elem = $(elementId);
        if (elem) {
                elem.style.display = 'none';
                elem.style.visibility = 'hidden';
        }
}

function showElement( elementId ) {
        var elem = $(elementId);
        if (elem) {
                elem.style.display = '';
                elem.style.visibility = 'visible';
        }
}

function rand ( n ) {
  return ( Math.floor ( Math.random ( ) * n + 1 ) );
}
