// run this function when the contents of the body have been rendered
function onBodyReady() {
   
   setupExternalLinks();   
   setupTips();
}

///////////////////////////////////////////////////////////////////////////////
// Utilities
///////////////////////////////////////////////////////////////////////////////

// set up Array's indexOf function if it's missing
if (!Array.indexOf) {
   Array.prototype.indexOf = function (obj, start) {
      for (var i = (start || 0); i < this.length; i++) {
         if (this[i] == obj) {
            return i;
         }
      }
      return -1;
   }
}

// return the cookie list as an Array; null if non-existent
function getCookieList(cookieName) {
   
   var list = ($.cookie(cookieName));
   list = list ? list.split(',') : null;
   return list;
}

// add a value to a cookie list; created if non-existent
function addToCookieList(cookieName, value) {
   
   var list = getCookieList(cookieName);
   if (!list)
      list = new Array();
      
   // don't add if it's aleady in the list
   if (list.indexOf(value) < 0) {
   
      list.push(value);
      $.cookie(cookieName, list.join(','), { path: '/' })
   }
}

// remove a value from a cookie list; ignored if non-existent
function removeFromCookieList(cookieName, value) {
   
   var list = getCookieList(cookieName);
   if (!list)
      return;
   
   // don't do anything if it's not in the list
   var i = list.indexOf(value);
   if (i >= 0) {
      
      list.splice(i, 1);
      $.cookie(cookieName, list.join(','), { path: '/' })
   }
}

///////////////////////////////////////////////////////////////////////////////
// Registration and Setup
///////////////////////////////////////////////////////////////////////////////

// set up collapsible navigation handlers
function registerNavigationHandlers() {
   
   // get the lists of opened and closed nav ids and apply their values
   var opened = getCookieList('nav-opened');
   var closed = getCookieList('nav-closed');
   var i = 0;
   var label = null;
   if (opened) {
      for (i = 0; i < opened.length; i++) {
         label = $('a#' + opened[i]);
         if (label.length) {
            if (!label.parent().hasClass('open'))
               label.parent().addClass('open');
         }
      }
   }
   if (closed) {
      for (i = 0; i < closed.length; i++) {
         label = $('a#' + closed[i]);
         if (label.length) {
            if (label.parent().hasClass('open'))
               label.parent().removeClass('open');
         }
      }
   }
   
   // close any non-opened uls in the nav
   $('ul#nav li[class!=open] a.label').each(function() {
      // slide up
      $(this).siblings('ul').slideUp(0);
   });
   
   // register clicks on the labels
   $('ul#nav li a.label').click(function() {
      
      // toggle states
      var neighbor = $(this).siblings('ul');
      neighbor.slideToggle();
      neighbor.parent().toggleClass('open');
      
      // store open / closed states
      var id = $(this).attr('id');
      if (neighbor.parent().hasClass('open')) {
         if (id) {
            removeFromCookieList('nav-closed', id);
            addToCookieList('nav-opened', id);
         }
      } else {
         if (id) {
            removeFromCookieList('nav-opened', id);
            addToCookieList('nav-closed', id);
         }
      }
      
      // that's all
      return false;
   });
}

// make external links open in another window / tab
function setupExternalLinks() {
   
   $('a.external-link').attr('target', '_blank');
}

// fade in the flash message
function showFlashMessages() {
   
   $('#flash-messages').fadeOut(0);
   $('#flash-messages').fadeIn('slow');
}



// set up different types of tips
function setupTip(tag, type) {
   
   // which side should we render on (left by default)
   var side = $(tag).hasClass('right') ? 'right' : 'left';
   
   $(tag).qtip({
      content: {
         url: '/tips' + $(tag).attr('href')
      },
      title: {
         text: false,
         button: false
      },
      position: {
         corner: {
            target: side == 'left' ? 'leftMiddle' : 'rightMiddle',
            tooltip: side == 'left' ? 'rightTop' : 'leftTop'
         }
      },
      show: {
         delay: 400,
         solo: true,
         effect: {
            type: 'fade',
            length: 100
         }
      },
      hide: {
         fixed: true
      },
      style: {
         width: 300,
         padding: 8,
         border: {
            width: 3,
            radius: 5,
            color: "#555"
         },
         tip: {
            corner: side == 'left' ? 'rightTop' : 'leftTop',
            size: {
               x: 20,
               y: 15
            }
         },
         classes: {
            content: 'content tip ' + type
         }
      }
   });
   
   // register callbacks
   var api = $(tag).qtip("api");
   
   // set the content to a loading spinner
   api.beforeContentLoad = function() {
      
      this.elements.content.html('<p><img style="border:none;" src="/elements/img/tip-loading.gif" alt="" />Loading...</p>');
   }
}

// set up a drink tip on the given <a> tag
function setupDrinkTip(tag) {
   
   // set up the tip
   setupTip(tag, 'drink');
   
   // register callbacks
   var api = $(tag).qtip("api");
   
   // destroy the tip on hide for leanness' sake
   api.onHide = function() {
      
      var tag = this.elements.target;
      this.destroy();
      setupDrinkTip(tag);
   }
}

// set up an ingrdient tip on the given <a> tag
// side can be one of 'left' or 'right'
function setupIngredientTip(tag) {
   
   // set up the tip
   setupTip(tag, 'ingredient');
   
   // register callbacks
   var api = $(tag).qtip("api");
   
   // destroy the tip on hide for leanness' sake
   api.onHide = function() {
      
      var tag = this.elements.target;
      this.destroy();
      setupIngredientTip(tag);
   }
}

// set up a glassware tip on the given <a> tag
// side can be one of 'left' or 'right'
function setupGlasswareTip(tag) {
   
   // setup the tip
   setupTip(tag, 'glassware');
   
   // register callbacks
   var api = $(tag).qtip("api");
   
   // destroy the tip on hide for leanness' sake
   api.onHide = function() {
      
      var tag = this.elements.target;
      this.destroy();
      setupGlasswareTip(tag);
   }
}

// set up a barware tip on the given <a> tag
// side can be one of 'left' or 'right'
function setupBarwareTip(tag) {
   
   // set up the tip
   setupTip(tag, 'barware');
   
   // register callbacks
   var api = $(tag).qtip("api");
   
   // destroy the tip on hide for leanness' sake
   api.onHide = function() {
      
      var tag = this.elements.target;
      this.destroy();
      setupBarwareTip(tag);
   }
}

function setupTips() {
   
   $('a.tip-drink').each(function() {
      setupDrinkTip(this);
   });
   $('a.tip-ingredient').each(function() {
      setupIngredientTip(this);
   });
   $('a.tip-glassware').each(function() {
      setupGlasswareTip(this);
   });
   $('a.tip-barware').each(function() {
      setupBarwareTip(this);
   });
}
