//image swap time
var timeIn = 300;
var timeOut = 300;

function flashReady() {
  Controller.initFlash();
} // flashReady()

var cheeseCounter = 0;
function handlePreloadCheese(item){
  cheeseCounter--;
  if(cheeseCounter == 0){
    //alert('cheese done');
    Controller.cheeseInit = true;
    Controller.kickstart();
  }
}

var sandwichCounter = 0;
function handlePreloadSandwich(item){
  sandwichCounter--;
  if(sandwichCounter == 0){
    //alert('sandwich done');
    Controller.sandwichInit = true;
    Controller.kickstart();
  }
}

$(document).ready(function(){
setTimeout(function(){
  $(document.body).fadeIn(500, function(){
    Cheeses = new ItemContainer('cheeses');
    Sandwiches = new ItemContainer('sandwiches');
  
    Cheeses.processXML(cheese_xml);
    Sandwiches.processXML(sandwich_xml);
    
    $('a[id]').each(function(event) {
      var a_id = $(this).attr('id');
    
      for (var i = 0; i < linkMappings.length; i++) {
      var mapping = linkMappings[i];
    
      for (var l = 0; l < mapping.map.length; l++) {
        if (a_id == mapping.map[l].id) {
    
        var map = mapping.map[l];
        if(mapping['jsFunction'] != null)
          $(this).bind(mapping.event, map, mapping['jsFunction']);
        if(mapping['swfFunction'] != null)
          $(this).bind(mapping.event, map, mapping['swfFunction']);  
        break;
        }
      } // for mappin gs
    
      } // for mapping group
    }); // a[id] click
  
    $('#index, #directory').fadeOut();
    
    $(".tooltip-popup a").hover(function() {
      $('.tooltip-popup').css('position', 'relative');
      $(this).next("em").stop(true, true).animate({opacity: "show", top: "-80"}, "fast");
    }, function() {
      $(this).next("em").animate({opacity: "hide", top: "-90"}, "fast", function(){
        $('.tooltip-popup').css('position', '');
      });
    });
    
    
    cheeseCounter++; //lock open
/*
    Cheeses.each(function(item){
      cheeseCounter++;
      item.loadMedium(handlePreloadCheese);
    });
*/  
    handlePreloadCheese(); //release
    
    sandwichCounter++; //lock open
    Sandwiches.each(function(item){
      if(item.loadDetail){
        sandwichCounter++;
        item.loadDetail(handlePreloadSandwich);
      }
    });
    handlePreloadSandwich(); //release
  
    $('a').focus(function(){
      $(this).blur();
    });  
  
    Subscribe.init();
    SendToFriend.init();
    TshirtEntry.init();
    
    $('a.sandwichDirectoryLink').click(handleSandwichDirectoryClick);
    $('a.cheeseIndexSandwich').click(handleCheeseindexsandwichClick);
    $('a.cheesedirect').click(handleCheeseDirectIndexClick);
    
    
    var cookingTips = new TipScroller('tipscooking');
    var cheeseTips = new TipScroller('tipscheese');
    var breadTips = new TipScroller('tipsbread');
    
    TopNav.init();
    TipsController.tipsArr = [cookingTips, cheeseTips, breadTips];
    
    $('.instructioninput').each(function(){
      $(this).attr('originalval', $(this).val());
      $(this).focus(function(){
        if($(this).val() == $(this).attr('originalval')){
          $(this).val('');
        }
      });
      
      $(this).blur(function(){
        if($(this).val() == '')
          $(this).val($(this).attr('originalval'));
      });
    });
    
    $('#moreFields').click(function() {
      $('#ingredientList input:last').after('<input type="text" class="text formingredient" name="ingredients[]" tabindex="' + (parseInt($('#ingredientList input:last').attr('tabindex')) + 1) + '" />');
  //      $('#containerShadRight').css({'visibility':'hidden'});
      return false;
    });
    
    $('.commonover').mouseover(handleCommonOverSound);
  
    //flashReady();
  });
}, 3000);
}); // document.ready

function handleCheeseindexsandwichClick(e){
    var sand_num = $(this).attr('rel');
    if (Sandwiches.hasNumber(sand_num)) {
      //trackEvent('Cheese Index: '+ '(' + $('h3', $(this).prevAll('.cheesedirect')[0]).html() + ') ' + $(this).html());
    
      simClick = ['link' + sand_num];
      Controller.trySimClick();
      $('a#navindex').mouseleave();
    }
    return false;
}
function handleCheeseDirectIndexClick(e){
  var cheesename = $(this).attr('rel');
  if(Cheeses.hasItem(cheesename)){
    trackEvent('Cheese Index: '+ $('h3', this).html());
    
    handleCheeseDirect(cheesename);
    $('a#navindex').mouseleave();
  }
  return false;
}
function handleSandwichDirectoryClick(e){
  //trackEvent('Sandwich Directory: ' + $('h3', this).html());

  var sand_num = $(this).attr('rel');
  simClick = ['link' + sand_num];
  Controller.trySimClick();
  $('a#navdirectory').mouseleave();
  return false;
}

Controller = {
  flashInit: false,
  sandwichInit: false,
  cheeseInit: false,
  focusPage: 'homecontainer',
  currentPage: 'whiteoverlay',
  isLocked: false,
  cheese: null,
  isInit: false,
  navigateCallback: null,
  
  lastCheck: null,
  
  initFlash: function(){
    Controller.flashInit = true;
    
    Controller.kickstart();
  },
  
  kickstart: function(){
    if(Controller.sandwichInit && Controller.cheeseInit && !Controller.isInit){
      if(!AudioSupport.Flash() || Controller.flashInit){
        Controller.isInit = true;
      
        if (!Controller.trySimClick()) {
          Controller.navigateTo(Controller.focusPage);
        }
        
        setTimeout(function(){
          /*
          Sandwiches.each(function(item){
            if(item.loadDetail){
              item.loadDetail();
            }
          });
          */
          Cheeses.each(function(item){
            preloadVoice(item.getAudio());
          });
          
          Cheeses.each(function(item){
            item.loadMedium();
          });
          Sandwiches.each(function(item){
            item.loadMedium();
          });

        }, 6000);
      }
    }
  },

  navigateTo: function(page){
    if(Controller.currentPage != page && !Controller.isLocked){
    
      if( !( (Controller.currentPage == 'slidecontainer' && page == 'recipecontainer') || (Controller.currentPage == 'recipecontainer' && page == 'slidecontainer') ) )
        killAudio();
        
      $('.contentcontainer').fadeOut(300, function(){
        if(this.id == Controller.currentPage){
          $(this).css('display', 'none');
          
          if(typeof Controller.navigateCallback == 'function'){
            Controller.navigateCallback();
            Controller.navigateCallback = null;
          }
          
          Controller.revealPage(page);

        }
      });
      
      return true;
    }else{
      return false;
    }
  },
  
  revealPage: function(page){
    if(!Controller.isLocked){
      
      Controller.currentPage = page;
      
      Slideshow.fixButtons();
      
      $('#'+page).fadeIn(300, function(){
        Controller.trySimClick();
      });
    } else {
      setTimeout("Controller.revealPage('"+page+"')", 300);
    }
  },
  
  enableRelease: function(){
    this.isLocked = true;
  },
  
  release: function(){
    this.isLocked = false;
  },
  
  trySimClick: function() {
    if (simClick.length > 0) {
      $('#'+simClick.pop()).click();
      return true;
    } else {
      Controller.contentLoaded();
      return false;
    }
  },
  contentLoaded: function() {
    Controller.enableRightShadow(true, null);
    $('#'+Controller.currentPage+' .wrapper,#'+Controller.currentPage+' .detailRight').each(function() {
      if ($(this).css('display') != 'none') {
          Controller.lastCheck = this;
        if (Controller.checkOverflow(this)) {
          Controller.enableRightShadow(false, this);
        }
      }
    });
  },
  checkOverflow: function(el) {
    var curOverflow = el.style.overflow;
    if (!curOverflow || curOverflow === "visible") {
       el.style.overflow = "hidden";
    }
  
    var isOverflowing = el.clientWidth < el.scrollWidth || el.clientHeight < el.scrollHeight;
  
    el.style.overflow = curOverflow;
  
    return isOverflowing;
  },
  enableRightShadow: function(showIt, obj) {
    if (showIt) {
      //$('#containerShadRight').show();
    $('#containerShadRight').animate({top: 10, height: 443}, 50);
    } else {
      //$('#containerShadRight').hide();
    $('#containerShadRight').animate({top: obj.clientHeight+4, height: 29}, 50);
    }
  }
}; // Controller

SlideDetail = {
  isHidden: true,
  callback: null,
  
  fadeOut: function(callback){
    SlideDetail.callback = callback;
  
    var slidedetail = $('#slidedetailtable')[0];
    $(slidedetail).animate({'opacity': 0}, 400, function(){
      SlideDetail.isHidden = true;
      if(typeof SlideDetail.callback == 'function'){
        SlideDetail.callback();
        SlideDetail.callback = null;
      }
    });

  },
  
  fadeIn: function(){
    SlideDetail.callback = null;
    
    $('#slidedetailtable').animate({'opacity': 0}, 0, function(){
      $('#slidedetailtable').delay(200).animate({'opacity': 1}, 400, function(){
        SlideDetail.isHidden = false;
      });
    });
  },

  hide: function(callback){
    SlideDetail.callback = callback;
    
    var slidedetail = $('#slidedetail')[0];
    $(slidedetail).animate({'bottom': -$(slidedetail).outerHeight()}, 800, function(){
      SlideDetail.isHidden = true;
      if(typeof SlideDetail.callback == 'function'){
        SlideDetail.callback();
        SlideDetail.callback = null;
      }
    });
  },
  show: function(){
    SlideDetail.callback = null;

    $('#slidedetail').animate({'bottom': 0}, 800, function(){
      SlideDetail.isHidden = false;
    });
  },

  build: function(itemName){

    if(Sandwiches.hasItem(itemName)){
      var item = Sandwiches.getItem(itemName);
      document.title = item.label + ' | Grilled Cheese Academy';
      $('#metatitle').attr('content', document.title);
      $('#metadescription').attr('content', item.short);
      $('#linkimage').attr('href', 'http://www.grilledcheeseacademy.com'+item.medium);
      
      var html = '';
      html += '<table id="slidedetailtable"><tr><td valign="middle">';
      html += '<a href="#" onclick="playVoice(Slideshow.sandwich.getAudio());"><img src="/images/audioIcon.gif" alt="audio" border="0" class="audioIcon" /></a>';
      html += '<a href="#" id="slidedetailsandwichlabel" onclick="$(\'#link'+item.number+'\').click();"><span>'+item.label+'</span></a></td> ';
      html += '<td valign="middle"><a id="sandwichlink" href="#">View Recipe</a></td> ';
      for(var i=0; i<item.relations.length; i++){
        if(Cheeses.hasItem(item.relations[i])){
          var cheese = Cheeses.getItem(item.relations[i]);
          html += '<td valign="middle"><a id="cheeselink'+i+'" href="#">'+cheese.label+'</a></td> ';
        }
      }
      html += '<td valign="middle" class="noBorder"><div class="btnShare"><a target="_blank" href="http://www.facebook.com/sharer.php?u='+encodeURIComponent('http://www.grilledcheeseacademy.com/'+item.name)+'&t='+encodeURIComponent(document.title)+'">Share on Facebook</a></div>';
      html += '<div class="btnTweet"><a target="_blank" href="http://twitter.com?status='+encodeURIComponent(item.twitter+' http://grilledcheeseacademy.com/'+item.name)+'">Tweet This</a></div>';
      html += '<div class="btnBuzz"><a target="_blank" href="http://www.google.com/reader/link?url='+encodeURIComponent('http://www.grilledcheeseacademy.com/'+item.name)+'&title='+encodeURIComponent(document.title)+'&snippet='+encodeURIComponent('<img src="http://www.grilledcheeseacademy.com'+item.medium+'" /><h3 style="margin-bottom:5px;">'+item.label+'</h3>'+item.short)+'&srcUrl='+encodeURIComponent('http://www.grilledcheeseacademy.com')+'&srcTitle=Grilled%20Cheese%20Academy'+'">Buzz This</a></div></td></tr></table>';
      html += '<div style="clear:both;"></div>';
      
      $('#slidedetail').html(html);
      $('#slidedetailsandwichlabel').mouseover(handleCommonOverSound);
      $('#sandwichlink').click(function(){ handleRecipeClick(itemName); });
      $('#sandwichlink').mouseover(handleCommonOverSound);
      $('#cheeselink0').click(function(){ handleCheeseClick(0,item.relations[0]); });
      $('#cheeselink0').mouseover(handleCommonOverSound);
      $('#cheeselink1').click(function(){ handleCheeseClick(1,item.relations[1]); });
      $('#cheeselink1').mouseover(handleCommonOverSound);
    }else{
      var html = "\
        <span>Item Missing</span> |\
        <a href=\"#\">View Recipe</a> |\
        <a href=\"#\">Cheese 1</a> |\
        <a href=\"#\">Cheese 2</a> |\
        <a href=\"#\">Facebook</a>\
        <a href=\"#\">Twitter</a>\
        <div style=\"clear:both;\"></div>";

      $('#slidedetail').html(html);        
    }
  }
};

Slideshow = {
  containerID: 'slidecontainer',
  currentIndexLbl: 0,
  sandwich: null,
  currentImg: null,
  newImg: null,
  isAnimating: false,
  fromIndex: null,
  
  blinkTo: function(index){
    if(Sandwiches.hasNumber(index)){
      var sandwich = Sandwiches.getItemByNumber(index);
      Slideshow.sandwich = sandwich;

      preloadVoice(Slideshow.sandwich.getAudio());
    
      Slideshow.isAnimating = true;
      Controller.enableRelease();
      
      SlideDetail.hide();

      trackEvent('Slideshow: ' + sandwich.label);

      Slideshow.currentIndexLbl = index;
            
      var newImg = new Image();
      $(newImg).load(Slideshow.doBlink);
      Slideshow.newImg = newImg;
      newImg.src = sandwich.detail;

    }
  },

  doBlink: function(){
    if(!SlideDetail.isHidden){
      setTimeout(Slideshow.doBlink, 300);
    }else{      
      SlideDetail.build(Slideshow.sandwich.name);
      SlideDetail.show();
      
      var copyImg = new Image();
      copyImg.src = Slideshow.sandwich.detail;
    
      $('#'+this.containerID+' > img').remove();
      $('#imgwrapper').css('width', 0);
      $('#imgwrapper').empty().append(copyImg);
      $('#'+Slideshow.containerID).append(Slideshow.newImg);
      
      if(Slideshow.currentIndexLbl != Slideshow.fromIndex)
        playVoice(Slideshow.sandwich.getAudio());
      Slideshow.fromIndex = null;
      
      Controller.release();
      Slideshow.isAnimating = false;
    }
  },
  
  reverseTransitionTo: function(index){
    if(Sandwiches.hasNumber(index) && this.currentIndexLbl != index && !Slideshow.isAnimating){
      Slideshow.sandwich = Sandwiches.getItemByNumber(index);
      
      killAudio();
      preloadVoice(Slideshow.sandwich.getAudio());
      
      this.isAnimating = true;
      Controller.enableRelease();
    
      this.currentIndexLbl = index;
      Slideshow.fixButtons();
      
      trackEvent('Slideshow: ' + this.sandwich.label);
  
      var oldImg = $('#imgwrapper img');
       $('#'+this.containerID+' > img').remove();
      this.currentImg = oldImg;
      
      var newImg = new Image();
      this.newImg = $(newImg);
      $(newImg).load(this.doReverseTransition);

      $('#'+this.containerID).append(newImg);
      
      $('#imgwrapper').animate({'width':917, 'opacity':1},0, function(){
        //SlideDetail.hide();
        SlideDetail.fadeOut(Slideshow.buildAndFadeDetail);
        newImg.src = Slideshow.sandwich.detail;
      });

  
    }else if(Slideshow.currentIndexLbl == index && !Slideshow.isAnimating){
      SlideDetail.show();
    }
  },
  
  doReverseTransition: function(e){
    var oldImg = Slideshow.currentImg;
  
    if(oldImg.length > 0){
      var wrapper = $('#imgwrapper');
      
      playImbedSound('superswish');
      
      $(wrapper).animate({'width':0, 'opacity':0}, 2200, function(){
        //$(oldImg).remove();
        var copyImg = new Image();
        copyImg.src = Slideshow.sandwich.detail;
        $('#imgwrapper').empty().append(copyImg);
        
        //if(Controller.currentPage == 'slidecontainer')
          playVoice(Slideshow.sandwich.getAudio());
        Controller.release();
        Controller.trySimClick();
        Slideshow.isAnimating = false;
      });
    }else{
      SlideDetail.build(Slideshow.sandwich.name);
      SlideDetail.show();
      
      Slideshow.isAnimating = false;
      playVoice(Slideshow.sandwich.getAudio());
    }
  },

  transitionTo: function(index){
    if(Sandwiches.hasNumber(index) && this.currentIndexLbl != index && !Slideshow.isAnimating){
      Slideshow.sandwich = Sandwiches.getItemByNumber(index);
      
      killAudio();
      preloadVoice(Slideshow.sandwich.getAudio());
      
      this.isAnimating = true;
      Controller.enableRelease();
    
      this.currentIndexLbl = index;
      Slideshow.fixButtons();
  
      trackEvent('Slideshow: ' + this.sandwich.label);
  
      var oldImg = $('#'+this.containerID+' > img');
      this.currentImg = oldImg;
      $(oldImg).css('z-index', 4);
      
      var newImg = new Image();
      this.newImg = $(newImg);
      $(newImg).load(this.doTransition);

      $('#'+this.containerID).append(newImg);
      
      var copyImg = new Image();
      copyImg.src = Slideshow.sandwich.detail;
      
      $('#imgwrapper').animate({'width':0, 'opacity':1},0, function(){
        $('#imgwrapper').empty().append(copyImg);

        SlideDetail.fadeOut(Slideshow.buildAndFadeDetail);
        newImg.src = Slideshow.sandwich.detail;
      });

  
    }else if(Slideshow.currentIndexLbl == index && !Slideshow.isAnimating){
      SlideDetail.show();
    }
  },

  doTransition: function(e){
    var oldImg = Slideshow.currentImg;
  
    if(oldImg.length > 0){
      var wrapper = $('#imgwrapper');

      playImbedSound('superswish');

      $(wrapper).animate({'width':917}, 2200, function(){
        $(oldImg).remove();
        
        //if(Controller.currentPage == 'slidecontainer')
          playVoice(Slideshow.sandwich.getAudio());
        Controller.release();
        Controller.trySimClick();
        Slideshow.isAnimating = false;
      });
      $(oldImg).animate({'opacity': 0}, 2000);

    }else{
      SlideDetail.build(Slideshow.sandwich.name);
      SlideDetail.show();
      
      Slideshow.isAnimating = false;
      playVoice(Slideshow.sandwich.getAudio());
    }
  },
  
  buildAndFadeDetail: function(){
    SlideDetail.build(Slideshow.sandwich.name);
    SlideDetail.fadeIn();
  },
  
  left: function(){
    if(Slideshow.currentIndexLbl > 1){
      $('#link'+(Slideshow.currentIndexLbl-1)).click();
    }
  },
  
  right: function(){
    if(Slideshow.currentIndexLbl < 30){
      $('#link'+(Slideshow.currentIndexLbl+1)).click();
    }
  },
  
  fixButtons: function(){
    if(Slideshow.currentIndexLbl < 2){
      $('#slideleft').fadeOut(200);
    }else{
      $('#slideleft').fadeIn(200);
    }
    
    if(Slideshow.currentIndexLbl > 29){
      $('#slideright').fadeOut(200);
    }else{
      $('#slideright').fadeIn(200);
    }
  }
};


function setItemActive(add, remove){
  $(remove).removeClass('active');
  $(add).addClass('active');
}

function handlePageNavClick(e){
  var useTarget = this;
  var setTitle = false;
  var tracker = false;
  
  switch(this.id){
    case 'mainlogo': 
    case 'link0':
      setTitle = 'Grilled Cheese Academy';
      useTarget = '#link0';
      
      tracker = 'Home';
      break;
    default:
      setTitle = 'Grilled Cheese Academy';
      useTarget = this; break;
  }

  switch(e.data.param){
    case 'tipscontainer':
      tracker = 'Tips';
      
      setTitle = 'Tips | Grilled Cheese Academy';
      TipsController.reset();
      break;

    case 'submitcontainer':
      tracker = 'Submit Recipe';
    
      setTitle = 'Submit Recipe | Grilled Cheese Academy';
      break;
    case 'gallerycontainer':
      tracker = 'Gallery';
    
      setTitle = 'Gallery | Grilled Cheese Academy';
      Gallery.reset();
      break;
    case 'pantrycontainer':
      tracker = 'Pantry';
    
      setTitle = 'Pantry | Grilled Cheese Academy';
      break;
    case 'sendtofriendcontainer':
      tracker = 'Send to Friend';
    
      setTitle = 'Send to Friend | Grilled Cheese Academy';
      break;
    case 'sendtofriendthankyoucontainer':
      tracker = 'Send to Friend: Thank You';
    
      setTitle = 'Thank You | Grilled Cheese Academy';
      break;
    case 'tshirtentrythankyoucontainer':
      tracker = 'T-Shirt Entry: Thank You';
      
      setTitle = 'Thank You | Grilled Cheese Academy';
      break;
  }

  if(Controller.navigateTo(e.data.param)) {
    killAudio();
  
    if(tracker !== false)
      trackEvent(tracker);
  
    setItemActive(useTarget, '#indexselecter a, .navitems a');
    SlideDetail.hide();
    if(setTitle != false)
      document.title = setTitle;
  }
  
  return false;

}

function handleIndexClick(e){
  if(!Slideshow.isAnimating){
    if(this.id == 'viewsandwiches'){
      setItemActive('#link1', '#indexselecter a, .navitems a');
    }else{
      setItemActive(this, '#indexselecter a, .navitems a');
    }
    
    if(Controller.currentPage == 'recipecontainer')
      Slideshow.fromIndex = Slideshow.currentIndexLbl;

    if(!Controller.navigateTo('slidecontainer')){
      if(Slideshow.currentIndexLbl < e.data.param)
        Slideshow.transitionTo(e.data.param);
      else
        Slideshow.reverseTransitionTo(e.data.param);
    }
    else{
      Slideshow.blinkTo(e.data.param);
    }
  }
  return false;
}

function handleRecipeClick(itemName){
  if(Sandwiches.hasItem(itemName)){
    var sandwich = Sandwiches.getItem(itemName);
    
    if(Controller.navigateTo('recipecontainer')){
      trackEvent('Recipe: '+sandwich.label);
    
      Controller.enableRelease();
      $('#sandwichlink').addClass('active');
      $('#cheeselink0').removeClass('active');
      $('#cheeselink1').removeClass('active');
      
      $('#sandwichlabel').html(sandwich.label);
      $('#sandwichmedium')[0].src = sandwich.medium;
      $('#shortdescription').html(sandwich.short);
      $('#cookingdirections').html('<h3>Cooking Directions</h3>'+sandwich.directions);
      $('#sandwichprint')[0].href = '/pdf/'+sandwich.pdf;
      
      var i=0;
      for(; i<sandwich.relations.length && i < 2; i++){
        if(Cheeses.hasItem(sandwich.relations[i])){
          var cheese = Cheeses.getItem(sandwich.relations[i]);
          $('#sandwichcheese'+i)[0].src = cheese.thumb;
          $('#sandwichcheese'+i)[0].alt = cheese.label;
          $('#sandwichcheeselink'+i)[0].href = 'javascript:handleCheeseClick('+i+', \''+cheese.name+'\');';
          $('#sandwichcheeselink'+i).css('display', '');
        }
      }

      if(i == 1){
        $('#sandwichcheeselink1').css('display', 'none');
      }
      
      var list = '<ul id="sandwichingredients">';
      for(var i=0; i<sandwich.ingredients.length; i++){
        list += "<li>" + sandwich.ingredients[i] + '</li>';
      }
      list += '</ul>';
      $('#ingredientlist').html(list);
      
      Controller.release();
      
      if(Controller.currentPage != 'slidecontainer')
        playVoice(sandwich.getAudio());
    }
  }
}


function handleCheeseClick(index, itemName) {
try{
  var id = '#cheesecontainer'+index;
  if(Cheeses.hasItem(itemName)){
    var cheese = Cheeses.getItem(itemName);
    
    if(Controller.navigateTo('cheesecontainer'+index)){  
      trackEvent('Cheese: '+ '('+ Slideshow.sandwich.label +') ' +cheese.label);

      Controller.enableRelease();
      $('#sandwichlink').removeClass('active');
      $('#cheeselink'+index).addClass('active');
      $('#cheeselink'+(index==0?'1':'0')).removeClass('active');
      
      
      $(id+' .cheeselabel').html(cheese.label);
      $(id+' .cheesemedium')[0].src = cheese.medium;
      $(id+' .description').html(cheese.description);
      $(id+' .goeswith').html(cheese.goeswith);
      $(id+' .flavor').html(cheese.flavor);
      $(id+' .pairswith').html(cheese.pairswith);
      
      $(id+' .cheeseprint')[0].href = '/pdf/'+Slideshow.sandwich.pdf;
      
      var relations = '';
      if(cheese.relations.length > 1){
        relations += '<strong>Also featured on:</strong><br />';
        var first = true;
        var realcount = 0;
        for(var i=0; i<cheese.relations.length; i++){
          if(Sandwiches.hasItem(cheese.relations[i]) && Slideshow.sandwich.name != cheese.relations[i]){
            var sandwich = Sandwiches.getItem(cheese.relations[i]);
            relations += '<div style="clear:both;"></div>';
            relations += '<a href="#" onclick="$(\'#link'+sandwich.number+'\').click();" class="featureThumb"><img src="'+sandwich.thumb+'" border="0" alt="'+sandwich.label+'" /><br />'+sandwich.label+'</a>';
          }
        }
      }
      $(id+' .relations').html(relations);
    
      Controller.cheese = cheese;
      playVoice(cheese.getAudio());
      Controller.release();
    }
  }
}catch(e){}
}

function handleCheeseDirect(itemName) {
try{
  if(Cheeses.hasItem(itemName)){
    SlideDetail.hide();

    if(Controller.navigateTo('cheesedirectcontainer')){
      Controller.enableRelease();
      
      buildCheeseDirect(itemName);
    }else{
      //hack
      Controller.currentPage = null;
      Controller.navigateCallback = function(){ buildCheeseDirect(itemName); }
      Controller.navigateTo('cheesedirectcontainer');
      Controller.enableRelease();
      Controller.currentPage = 'cheesedirectcontainer';
    }
  }
}catch(e){}
}

function buildCheeseDirect(itemName){
  var id = '#cheesedirectcontainer';

  var cheese = Cheeses.getItem(itemName);      

  setItemActive(this, '#indexselecter a, .navitems a');
  document.title = cheese.label + ' | Grilled Cheese Academy';

  $(id+' .cheeselabel').html(cheese.label);
  $(id+' .cheesemedium')[0].src = cheese.medium;
  $(id+' .description').html(cheese.description);
  $(id+' .goeswith').html(cheese.goeswith);
  $(id+' .flavor').html(cheese.flavor);
  $(id+' .pairswith').html(cheese.pairswith);
  
  var relations = '';
  relations += '<strong>Featured on:</strong><br />';
  var first = true;
  for(var i=0; i<cheese.relations.length; i++){
    var sandwich = Sandwiches.getItem(cheese.relations[i]);
    if(i==0){
      $(id+' .cheeseprint')[0].href = '/pdf/'+cheese.pdf;
    }

    relations += '<div style="clear:both;"></div>';
    relations += '<a href="#" onclick="$(\'#link'+sandwich.number+'\').click();" class="featureThumb"><img src="'+sandwich.thumb+'" border="0" alt="'+sandwich.label+'" /><br />'+sandwich.label+'</a>';
  }

  $(id+' .relations').html(relations);

  Controller.cheese = cheese;
  playVoice(cheese.getAudio());
  Controller.release();
}


var AudioSupport = {
  _flash_supported: undefined,
  _html5_supported: undefined,
  
  Flash: function() {
    if (this._flash_supported === undefined) {
      if (swfobject) {
        var flash_ver = swfobject.getFlashPlayerVersion();
        if (flash_ver && flash_ver.major && flash_ver.major >= 9) {
          this._flash_supported = true;
        } else {
          this._flash_supported = false;
        }
      } else {
        // hmmm, why'd that happen?
        this._flash_supported = false;
      }
    }
    return this._flash_supported;
  }, // Flash()
  HTML5: function() {
    if (this._html5_supported === undefined) {
      try {
        var audio = new Audio();
        if (typeof audio.canPlayType === "function" && audio.canPlayType('audio/ogg') !== "") {
          this._html5_supported = true;
          
          $(audio).attr('id','htmlaudio');
          $('body').append(audio);
          
          $('#htmlaudio').bind("load", undefined, function() {
            $('#htmlaudio').unbind('load');
            $('#htmlaudio').bind("load", undefined, function() {
              $('#htmlaudio')[0].play();
            });
          });
          
          audio.src = sample_ogg;
          audio.load();
        } else {
          this._html5_supported = false;
        }
      } catch(e) {
        this._html5_supported = false;
      }
    }
    return this._html5_supported;
  } // HTML5()
}; // AudioSupport

function killAudio() {
  if(Controller.flashInit) {
    if (AudioSupport.Flash()) {
      if (typeof $('#flashaudio')[0].killAudio === 'function') {
        $('#flashaudio')[0].killAudio();
      }
    } else if (AudioSupport.HTML5()) {
      var audio = $('#htmlaudio')[0];
      if (audio) {
        audio.pause();
      }
    } else {
      // No sound options
    }
  }
} // killAudio()

function playVoice(path) {
  try{
    if(Controller.flashInit) {
    if (AudioSupport.Flash()) {  
      if ($('#flashaudio')[0].playAudio) {
      $('#flashaudio')[0].playAudio(path, path);
      }
    } else if (AudioSupport.HTML5()) {
      var audio = $('#htmlaudio')[0];
      if (audio) {
      audio.pause();
      audio.src = path;
      audio.load();
      }
    } else {
      // No sound options
    }
    }
  }catch(e){}
} // playVoice()

function preloadVoice(path){
  try{
    if(Controller.flashInit) {
    if (AudioSupport.Flash()) {  
      if ($('#flashaudio')[0].preloadAudio) {
      $('#flashaudio')[0].preloadAudio(path, path);
      }
    }
    }
  }catch(e){}
}

function handleCommonOverSound(e){
  playImbedSound('sb1');
}

function playImbedSound(lbl){
  if(Controller.flashInit) {
    if (AudioSupport.Flash()) {  
      if ($('#flashaudio')[0].playAudioChannel) {
        $('#flashaudio')[0].playAudioChannel(lbl);
      }
    } else if (AudioSupport.HTML5()) {
      var audio = $('#htmlaudio')[0];
      if (audio) {
        audio.pause();
        audio.src = e.data.param;
        audio.load();
      }
    } else {
      // No sound options
    }
  }
}

/*
function playOverSound(e){
  if(Controller.flashInit) {
    if (AudioSupport.Flash()) {  
      if ($('#flashaudio')[0].playAudioChannel) {
        $('#flashaudio')[0].playAudioChannel(e.data.param);
      }
    } else if (AudioSupport.HTML5()) {
      var audio = $('#htmlaudio')[0];
      if (audio) {
        audio.pause();
        audio.src = e.data.param;
        audio.load();
      }
    } else {
      // No sound options
    }
  }
} // playOverSound
*/

var linkMappings = [
/*
{
  event: 'mouseover',
  swfFunction: playOverSound,
  map: [
  {id: 'link1', param: 'sb1'},
  {id: 'link2', param: 'sb2'},
  {id: 'link3', param: 'sb3'},
  {id: 'link4', param: 'sb4'},
  {id: 'link5', param: 'sb1'},
  {id: 'link6', param: 'sb2'},
  {id: 'link7', param: 'sb3'},
  {id: 'link8', param: 'sb4'},
  {id: 'link9', param: 'sb1'}
  ]
},*/
{
  event: 'click',
  jsFunction: handlePageNavClick,
  map: [
    {id: 'link0', param: 'homecontainer'},
    {id: 'link31', param: 'tipscontainer'},
    {id: 'link32', param: 'pantrycontainer'},
    {id: 'linksubmit', param: 'submitcontainer'},
    {id: 'linkgallery', param: 'gallerycontainer'},
    {id: 'mainlogo', param: 'homecontainer'},
    {id: 'sendtofriend', param: 'sendtofriendcontainer'}
  ]
},
{
  event: 'click',
  jsFunction: handleIndexClick,
  map: [
  {id: 'viewsandwiches', param: 1},
  {id: 'link1', param: 1},
  {id: 'link2', param: 2},
  {id: 'link3', param: 3},
  {id: 'link4', param: 4},
  {id: 'link5', param: 5},
  {id: 'link6', param: 6},
  {id: 'link7', param: 7},
  {id: 'link8', param: 8},
  {id: 'link9', param: 9},
  {id: 'link10', param: 10},
  {id: 'link11', param: 11},
  {id: 'link12', param: 12},
  {id: 'link13', param: 13},
  {id: 'link14', param: 14},
  {id: 'link15', param: 15},
  {id: 'link16', param: 16},
  {id: 'link17', param: 17},
  {id: 'link18', param: 18},
  {id: 'link19', param: 19},
  {id: 'link20', param: 20},
  {id: 'link21', param: 21},
  {id: 'link22', param: 22},
  {id: 'link23', param: 23},
  {id: 'link24', param: 24},
  {id: 'link25', param: 25},
  {id: 'link26', param: 26},
  {id: 'link27', param: 27},
  {id: 'link28', param: 28},
  {id: 'link29', param: 29},
  {id: 'link30', param: 30}
  ]
}
]; // link mappings

var TopNav = {
  currentFocus: null,
  navDir: null,
  directory: null,
  navIndex: null,
  index: null,
  
  outTimer: null,

  init: function(){
    this.navDir = $('#navdirectory');
    this.directory = $('#directory');
    this.navIndex = $('#navindex');
    this.index = $('#index');
    
    this.navDir.mouseenter(TopNav.focusItem);
    this.navDir.mouseleave(TopNav.timeClose);
    this.directory.mouseenter(TopNav.stop);
    this.directory.mouseleave(TopNav.doClose);
    
    this.navIndex.mouseenter(TopNav.focusItem);
    this.navIndex.mouseleave(TopNav.timeClose);
    this.index.mouseenter(TopNav.stop);
    this.index.mouseleave(TopNav.doClose);
  },
  
  focusItem: function(e){
    TopNav.stop();
    
    TopNav.navDir.removeClass('active');
    TopNav.navIndex.removeClass('active');
    $(this).addClass('active');
    
    TopNav.directory.stop(true, true);
    TopNav.index.stop(true, true);
    switch(this.id){
      case 'navdirectory':
      case 'directory':
        TopNav.directory.fadeIn(250);
        TopNav.index.fadeOut(250);
        break;
      case 'navindex':
      case 'index':
        TopNav.index.fadeIn(250, function(){
          TopNav.directory.fadeOut(250);
        });
        break;
    }
  },
  
  timeClose: function(e){
    TopNav.stop();
    TopNav.outTimer = setTimeout(TopNav.doClose, 100);
  },
  
  doClose: function(){
    TopNav.navDir.removeClass('active');
    TopNav.navIndex.removeClass('active');
    TopNav.index.fadeOut(250);
    TopNav.directory.fadeOut(250);
  },
  
  stop: function(){
    if(TopNav.outTimer !== null){
      clearTimeout(TopNav.outTimer);
    }
    TopNav.outTimer = null;
  }

}

var TipsController = {
  tipsArr: null,
  currentSet: 'tipslanding',
  
  focusTips: function (id){
    if(TipsController.currentSet != id){

      $('#'+TipsController.currentSet).hide(200, function(){
        for(var i=0; i<TipsController.tipsArr.length; i++){
          TipsController.tipsArr[i].reset();
          
        }
        TipsController.currentSet = id;
        TipsController.setCap(id);
        $('#'+id).show(200);
      });
    }
  },
  
  reset: function(){
    //TipsController.focusTips('tipslanding');
    $('#'+TipsController.currentSet).hide();
    for(var i=0; i<TipsController.tipsArr.length; i++){
      TipsController.tipsArr[i].reset();      
    }
    TipsController.currentSet = 'tipslanding';
    TipsController.setCap();
    $('#tipslanding').show();
  },
  
  setCap: function(label){
    var useclass = '';
    var useid = '';
    var offset = 90;
    
    if(label != undefined)
      trackEvent('Tips: '+label);
    
    switch(label){
      case 'tipscheese':
        offset = 0;
        useid = '#cheesetab';
      break;
      case 'tipsbread':
        offset = -84;
        useid = '#buttertab';
      break;
      case 'tipscooking':
        offset = -167;
        useid = '#cookingtab';
      break;
    }
    $('#tipscap').css('background-position', '0px '+offset+'px');
    $('#tipscap a').removeClass('active');
    if(useid != '')
      $(useid).addClass('active');
  }

}

  
TipScroller = function(id){
  this.id = id;
  this.wrapper = $('#'+id+' .tips');
  this.count = $('#'+id+' .tip').length;  

  this.wrapper.css('width', this.offset*this.count);
}
TipScroller.prototype = {
  id: null,
  wrapper: null,
  index: 0,
  count: 0,
  offset: 398,
  
  next: function(){
    if(this.index < this.count-1){
      this.index += 1;
      
      trackEvent('Tips: '+this.id + ' - next (' + this.index + ')');
      
      var holdthis = this;
      this.wrapper.animate({'opacity':0}, 200, function(){
        holdthis.wrapper.animate({'left': -holdthis.index * holdthis.offset}, 200, function(){
          holdthis.wrapper.animate({'opacity':1}, 100);
          holdthis.buildLinks();
        });
      });
    }
  },
  previous: function(){
    if(this.index > 0){
      this.index -= 1;
      
      trackEvent('Tips: '+this.id + ' - previous (' + this.index + ')');
      
      var holdthis = this;
      this.wrapper.animate({'opacity':0}, 200, function(){
        holdthis.wrapper.animate({'left': -holdthis.index * holdthis.offset}, 200, function(){
          holdthis.wrapper.animate({'opacity':1}, 100);
          holdthis.buildLinks();
        });
      });

    }  
  },
  
  buildLinks: function(){
    var div = $('#'+this.id+' .tipslinkscontainer');
    var html = '';
    var jsPath = 'TipsController.tipsArr['+this.getIndex()+']';
    
    if(this.index > 0){
      html += '<a href="javascript:'+jsPath+'.previous();">&lt; Previous</a> &nbsp;';
    }else{
      html += '<span class="dead">&lt; Previous</span> &nbsp;';
    }
    
    //if(this.index > 0 && this.index < this.count-1){
      html += ' | ';
    //}
    
    if(this.index < this.count-1){
      html += '&nbsp; <a href="javascript:'+jsPath+'.next();">Next &gt;</a>';
    }else{
      html += '&nbsp; <span class="dead">Next &gt;</span>';
    }
    div.html(html);
  },
  
  reset: function(){
    this.index = 0;
    this.wrapper.animate({'left': 0}, 0);
    
    this.buildLinks();
  },

  getIndex: function(){
    return jQuery.inArray(this, TipsController.tipsArr);
  }  
}

Gallery = {
  _debug: false,
  
  unhideCommentQuery: '/api/comments/unhide',
  hideCommentQuery: '/api/comments/hide',
  reportCommentQuery: '/api/comments/report',
  addFavoriteQuery: '/api/recipes/fav',
  removeFavoriteQuery: '/api/recipes/unfav',
  hideImageQuery: '/api/recipes/hide',
  unhideImageQuery: '/api/recipes/unhide',
  banUserQuery: '/api/users/ban',
  unbanUserQuery: '/api/users/unban',
  userQuery: '/api/session/view',
  resetQuery: '/api/recipes/list',
  listQuery: '/api/recipes/list',
  voteQuery: '/api/recipes/vote',
  viewUserQuery: '/api/users/view',
  viewRecipeQuery: '/api/recipes/view',
  addCommentQuery: '/api/comments/create',
  galleryWrapper: '#gallerycontainer .wrapper',
  innerGalleryWrapper: '#gallery',
  userGalleryWrapper: '#userGallery',
  currentUser: null,
  isAdmin: false,
  viewingRecipeIdx: -1,
  
  hidden: false,
  hideCallback: null,
  useWrapper: null,
  
  galleryData: {  "params":{    "max":8,    "start":0,    "sort":"votes",    "userids":[],    "search":"",    "favonly":false,    "showall":false  },    "success":true,  "recipes":{    "total":90,        "records":[      {        "id":"7",        "userid":"1285257796",        "title":"title 5",        "ingredients":["ingred1"],        "description":"desc",        "instructions":"prep",        "favorite":false,        "hidden":false,        "created":"2010-02-24 13:19:17",        "user":{          "currentlocation":"",          "firstname":"Robert",          "lastname":"Lasseter",          "name":"Robert Lasseter",          "sex":"male",          "uid":"1285257796",          "picsquare":"http:\/\/profile.ak.fbcdn.net\/v227\/1287\/73\/q1285257796_5531.jpg",          "locale":"en_US",          "profileurl":"http:\/\/www.facebook.com\/profile.php?id=1285257796"        }      },      {        "id":"6",        "userid":"1285257796",        "title":"title 4",        "ingredients":["ingred"],        "description":"desc",        "instructions":"prep inst",        "favorite":false,        "hidden":false,        "created":"2010-02-24 13:10:46",        "user":{          "currentlocation":"",          "firstname":"Robert",          "lastname":"Lasseter",          "name":"Robert Lasseter",          "sex":"male",          "uid":"1285257796",          "picsquare":"http:\/\/profile.ak.fbcdn.net\/v227\/1287\/73\/q1285257796_5531.jpg",          "locale":"en_US",          "profileurl":"http:\/\/www.facebook.com\/profile.php?id=1285257796"        }      },      {        "id":"3",        "userid":"1285257796",        "title":"Test Title",        "ingredients":["ingred1",        "ingred2"],        "description":"desc",        "instructions":"preg",        "favorite":false,        "hidden":false,        "created":"0000-00-00 00:00:00",        "user":{          "currentlocation":"",          "firstname":"Robert",          "lastname":"Lasseter",          "name":"Robert Lasseter",          "sex":"male",          "uid":"1285257796",          "picsquare":"http:\/\/profile.ak.fbcdn.net\/v227\/1287\/73\/q1285257796_5531.jpg",          "locale":"en_US",          "profileurl":"http:\/\/www.facebook.com\/profile.php?id=1285257796"        }      },      {        "id":"7",        "userid":"1285257796",        "title":"title 5",        "ingredients":["ingred1"],        "description":"desc",        "instructions":"prep",        "favorite":false,        "hidden":false,        "created":"2010-02-24 13:19:17",        "user":{          "currentlocation":"",          "firstname":"Robert",          "lastname":"Lasseter",          "name":"Robert Lasseter",          "sex":"male",          "uid":"1285257796",          "picsquare":"http:\/\/profile.ak.fbcdn.net\/v227\/1287\/73\/q1285257796_5531.jpg",          "locale":"en_US",          "profileurl":"http:\/\/www.facebook.com\/profile.php?id=1285257796"        }      },      {        "id":"6",        "userid":"1285257796",        "title":"title 4",        "ingredients":["ingred"],        "description":"desc",        "instructions":"prep inst",        "favorite":false,        "hidden":false,        "created":"2010-02-24 13:10:46",        "user":{          "currentlocation":"",          "firstname":"Robert",          "lastname":"Lasseter",          "name":"Robert Lasseter",          "sex":"male",          "uid":"1285257796",          "picsquare":"http:\/\/profile.ak.fbcdn.net\/v227\/1287\/73\/q1285257796_5531.jpg",          "locale":"en_US",          "profileurl":"http:\/\/www.facebook.com\/profile.php?id=1285257796"        }      },      {        "id":"3",        "userid":"1285257796",        "title":"Test Title",        "ingredients":["ingred1",        "ingred2"],        "description":"desc",        "instructions":"preg",        "favorite":false,        "hidden":false,        "created":"0000-00-00 00:00:00",        "user":{          "currentlocation":"",          "firstname":"Robert",          "lastname":"Lasseter",          "name":"Robert Lasseter",          "sex":"male",          "uid":"1285257796",          "picsquare":"http:\/\/profile.ak.fbcdn.net\/v227\/1287\/73\/q1285257796_5531.jpg",          "locale":"en_US",          "profileurl":"http:\/\/www.facebook.com\/profile.php?id=1285257796"        }      },      {        "id":"7",        "userid":"1285257796",        "title":"title 5",        "ingredients":["ingred1"],        "description":"desc",        "instructions":"prep",        "favorite":false,        "hidden":false,        "created":"2010-02-24 13:19:17",        "user":{          "currentlocation":"",          "firstname":"Robert",          "lastname":"Lasseter",          "name":"Robert Lasseter",          "sex":"male",          "uid":"1285257796",          "picsquare":"http:\/\/profile.ak.fbcdn.net\/v227\/1287\/73\/q1285257796_5531.jpg",          "locale":"en_US",          "profileurl":"http:\/\/www.facebook.com\/profile.php?id=1285257796"        }      },      {        "id":"6",        "userid":"1285257796",        "title":"title 4",        "ingredients":["ingred"],        "description":"desc",        "instructions":"prep inst",        "favorite":false,        "hidden":false,        "created":"2010-02-24 13:10:46",        "user":{          "currentlocation":"",          "firstname":"Robert",          "lastname":"Lasseter",          "name":"Robert Lasseter",          "sex":"male",          "uid":"1285257796",          "picsquare":"http:\/\/profile.ak.fbcdn.net\/v227\/1287\/73\/q1285257796_5531.jpg",          "locale":"en_US",          "profileurl":"http:\/\/www.facebook.com\/profile.php?id=1285257796"        }      }    ]  }},
  userData: {  "params":{    "id":"1285257796",    "max":8,    "start":0,    "sort":"votes",    "search":"",    "favonly":false,    "showall":false  },    "success":true,  "user":{    "currentlocation":"",    "firstname":"Robert",    "lastname":"Lasseter",    "name":"Robert Lasseter",    "sex":"male",    "uid":"1285257796",    "picsquare":"http:\/\/profile.ak.fbcdn.net\/v227\/1287\/73\/q1285257796_5531.jpg",    "locale":"en_US",    "profileurl":"http:\/\/www.facebook.com\/profile.php?id=1285257796",    "recipes":{      "total":75,      "records":[        {          "id":"7",          "userid":"1285257796",          "title":"title 5",          "ingredients":["ingred1"],          "description":"desc",          "instructions":"prep",          "favorite":false,          "hidden":false,          "created":"2010-02-24 13:19:17"        },        {          "id":"6",          "userid":"1285257796",          "title":"title 4",          "ingredients":["ingred"],          "description":"desc",          "instructions":"prep inst",          "favorite":false,          "hidden":false,          "created":"2010-02-24 13:10:46"        },        {          "id":"3",          "userid":"1285257796",          "title":"Test Title",          "ingredients":["ingred1",          "ingred2"],          "description":"desc",          "instructions":"preg",          "favorite":false,          "hidden":false,          "created":"0000-00-00 00:00:00"        },        {          "id":"7",          "userid":"1285257796",          "title":"title 5",          "ingredients":["ingred1"],          "description":"desc",          "instructions":"prep",          "favorite":false,          "hidden":false,          "created":"2010-02-24 13:19:17"        },        {          "id":"6",          "userid":"1285257796",          "title":"title 4",          "ingredients":["ingred"],          "description":"desc",          "instructions":"prep inst",          "favorite":false,          "hidden":false,          "created":"2010-02-24 13:10:46"        },        {          "id":"3",          "userid":"1285257796",          "title":"Test Title",          "ingredients":["ingred1",          "ingred2"],          "description":"desc",          "instructions":"preg",          "favorite":false,          "hidden":false,          "created":"0000-00-00 00:00:00"        },        {          "id":"3",          "userid":"1285257796",          "title":"Test Title",          "ingredients":["ingred1",          "ingred2"],          "description":"desc",          "instructions":"preg",          "favorite":false,          "hidden":false,          "created":"0000-00-00 00:00:00"        },        {          "id":"3",          "userid":"1285257796",          "title":"Test Title",          "ingredients":["ingred1",          "ingred2"],          "description":"desc",          "instructions":"preg",          "favorite":false,          "hidden":false,          "created":"0000-00-00 00:00:00"        }      ]    }  }},
  recipeData: {"params":{"id":3},"success":true,"recipe":{"id":"3","userid":"1285257796","title":"Test Title","ingredients":["ingred1","ingred2"],"description":"desc","instructions":"preg","favorite":false,"hidden":false,"created":"0000-00-00 00:00:00","user": {"currentlocation": "","firstname": "Robert","lastname": "Lasseter","name": "Robert Lasseter","sex": "","uid": "1285257796","picsquare": "http:\/\/profile.ak.fbcdn.net\/v227\/1287\/73\/q1285257796_5531.jpg","locale": "en_US","profileurl": "http:\/\/www.facebook.com\/people\/Robert-Lasseter\/1285257796"}}},
  recipeList: {},
  backData: {},
  backFunction: undefined,
  backWrapper: '',
  backPage: 0,
  
  navHistory: [],
  
  searchResults: [],
  
  lastQuery: {
    "max":8,
    "start":0,
    "sort":"votes",
    "userids":[],
    "search":"",
    "favonly":false,
    "showall":false
  },
  lastResponse: {},
  
  updateUser: function(){
    $.getJSON(Gallery.userQuery, Gallery._updateUser);
  },
  _updateUser: function(data){
    Gallery.currentUser = data;
    Gallery.isAdmin = data.isadmin;
  },

  reset: function(){
    Gallery.startPageChange(Gallery.galleryWrapper);
    Gallery.backWrapper = Gallery.galleryWrapper;
    if(!Gallery._debug){
      Gallery.updateUser();
      if(Gallery.jumpId != null){
        $.getJSON(Gallery.resetQuery+'?id='+Gallery.jumpId, Gallery.handleJump);
        Gallery.jumpId = null;
      }else{
        $.getJSON(Gallery.resetQuery + '?sort=' + Gallery.lastQuery.sort, Gallery.buildMain);
      }
    }else{
      Gallery.buildMain(Gallery.galleryData);
    }
  },
  
  handleJump: function(data){
    if(data.success){
      Gallery.recipeList = data.recipes;
      Gallery.focusSandwich(0);
    }else{
      $('#mainlogo').click();
    }
  },
  
  banUser: function(id){
    Gallery.startPageChange(Gallery.galleryWrapper);
    $.getJSON(Gallery.banUserQuery+'?id='+id, function(){
      Gallery.focusUser(id);
    });
  },
  unbanUser: function(id){
    Gallery.startPageChange(Gallery.galleryWrapper);
    $.getJSON(Gallery.unbanUserQuery+'?id='+id, function(){
      Gallery.focusUser(id);
    });
  },
  hideImage: function(id){
    Gallery.startPageChange(Gallery.galleryWrapper);
    $.getJSON(Gallery.hideImageQuery+'?id='+id, function(){
      Gallery.focusUser(Gallery.lastQuery.id);
    });  
  },
  unhideImage: function(id){
    Gallery.startPageChange(Gallery.galleryWrapper);
    $.getJSON(Gallery.unhideImageQuery+'?id='+id, function(){
      Gallery.focusUser(Gallery.lastQuery.id);
    });
  },
  detailHideImage: function(id){
    Gallery.startPageChange(Gallery.galleryWrapper);
    $.getJSON(Gallery.hideImageQuery+'?id='+id, function(){
      if(Gallery.recipeList.records[Gallery.viewingRecipeIdx]){
        Gallery.recipeList.records[Gallery.viewingRecipeIdx].hidden = true;
      }
      Gallery.focusSandwich(Gallery.viewingRecipeIdx);
    });  
  },
  detailUnhideImage: function(id){
    Gallery.startPageChange(Gallery.galleryWrapper);
    $.getJSON(Gallery.unhideImageQuery+'?id='+id, function(){
      if(Gallery.recipeList.records[Gallery.viewingRecipeIdx]){
        Gallery.recipeList.records[Gallery.viewingRecipeIdx].hidden = false;
      }
      Gallery.focusSandwich(Gallery.viewingRecipeIdx);
    });
  },
  addFavorite: function(id){
    Gallery.startPageChange(Gallery.galleryWrapper);
    $.getJSON(Gallery.addFavoriteQuery+'?id='+id, function(){
      Gallery.focusUser(Gallery.lastQuery.id);
    });
  },
  removeFavorite: function(id){
    Gallery.startPageChange(Gallery.galleryWrapper);
    $.getJSON(Gallery.removeFavoriteQuery+'?id='+id, function(){
      Gallery.focusUser(Gallery.lastQuery.id);
    });
  },
  hideComment: function(id){
    $.getJSON(Gallery.hideCommentQuery+'?id='+id, function(data){
      if(data.success){
        var comment = $('#recipeComment'+id);
        comment.css('background-color', '#ff5555');
        $('.hidecomment', comment[0]).html('<a href="#" onclick="Gallery.unhideComment('+id+');">unhide</a>');
      }else{
        alert('hide failed');
      }
    });
  },
  unhideComment: function(id){
    $.getJSON(Gallery.unhideCommentQuery+'?id='+id, function(data){
      if(data.success){
        var comment = $('#recipeComment'+id);
        comment.css('background-color', '');
        $('.hidecomment', comment[0]).html('<a href="#" onclick="Gallery.hideComment('+id+');">hide</a>');
      }else{
        alert('unhide failed');
      }
    });
  },
  
  reportComment: function(id){
    $.getJSON(Gallery.reportCommentQuery+'?id='+id, function(data){
      var report = $('#recipeComment'+id+' .reportcomment')
      report.html('reported');
      report.css('color', '#ff5555');
    });
  },
  
  sortGallery: function(type){
    Gallery.lastQuery.sort = type;
    Gallery.lastQuery.userids = '';
    Gallery.lastQuery.start = '0';
    //Gallery.lastQuery.max = '0';
    
    Gallery.startPageChange(Gallery.galleryWrapper);
    Gallery.backWrapper = Gallery.galleryWrapper;
    $.getJSON(Gallery.listQuery+Gallery.getQueryString(), Gallery.buildMain);
  },
  filterGallery: function(type){
    switch(type){
      case 'friends':
        var useIds = Gallery.currentUser.friendids;
        useIds.push(Gallery.currentUser.userid);
        Gallery.lastQuery.userids = useIds.join(',');
        Gallery.lastQuery.favonly = false;
        break;
      case 'favorites':
        Gallery.lastQuery.favonly = true;
        Gallery.lastQuery.userids = '';
        break;
      default:
        Gallery.lastQuery.userids = '';
        Gallery.lastQuery.favonly = false;
        break;
    }
    Gallery.lastQuery.start = '0';
    //Gallery.lastQuery.max = '0';
    
    Gallery.startPageChange(Gallery.galleryWrapper);
    $.getJSON(Gallery.listQuery+Gallery.getQueryString(), Gallery.buildMain);
  },
  searchGallery: function(txt){
    Gallery.startPageChange(Gallery.galleryWrapper);
    $.getJSON(Gallery.listQuery+'?search='+txt, Gallery.buildMain);
  },
  adminGallery: function(){
    Gallery.startPageChange(Gallery.galleryWrapper);
    $.getJSON(Gallery.listQuery+'?showall=true', Gallery.buildMain);
  },
  pageInfo: function() {
    var obj = Gallery.lastResponse;
    
    var firstNum = Gallery.lastQuery.start + 1;
    var lastNum = Gallery.lastQuery.start+obj.recipes.records.length;

    if(lastNum > obj.recipes.total) lastNum = obj.recipes.total;
    if(firstNum > lastNum) firstNum = lastNum;
    
    var totalPages = Math.ceil(obj.recipes.total / 8);
    var currentPage = Math.floor(firstNum/8);
    
    if (currentPage == 0) {
      jQuery('#prevPageArrow').addClass('hidden');
    } else {
      jQuery('#prevPageArrow').removeClass('hidden');
    }
    if (currentPage == totalPages - 1 || totalPages == 0) {
      jQuery('#nextPageArrow').addClass('hidden');
    } else {
      jQuery('#nextPageArrow').removeClass('hidden');
    }
    
    return {'current':currentPage,'total':totalPages};
  },
  nextPage: function() {
    var pages = Gallery.pageInfo();
    Gallery.galleryPage(pages.current+1);
    return false;
  },
  prevPage: function() {
    var pages = Gallery.pageInfo();
    Gallery.galleryPage(pages.current-1);
    return false;
  },
  galleryPage: function(index){
    Gallery.startPageChange(Gallery.innerGalleryWrapper);
    Gallery.lastQuery.start = index * Gallery.lastQuery.max;

    if (Gallery.navHistory.length > 1) {
      Gallery.navHistory[Gallery.navHistory.length - 1]['page'] = Gallery.lastQuery.start;
    }
    
    if(!Gallery._debug) {
      $.getJSON(Gallery.listQuery+Gallery.getQueryString(), Gallery._galleryPage);
    }else{
      Gallery._galleryPage(Gallery.galleryData);
    }
  },
  
  nextSandwich: function() {
    var new_idx = this.viewingRecipeIdx + 1;
    if (new_idx < this.searchResults.length) {
      this.focusSandwich(new_idx);
    }
  },
  prevSandwich: function() {
    var new_idx = this.viewingRecipeIdx - 1;
    if (new_idx >= 0) {
      this.focusSandwich(new_idx);
    }
  },
  
  focusSandwich: function(idx){
    if (!Gallery._debug) {
      if (idx >= 0 && idx < Gallery.recipeList.records.length) {
        Gallery.startPageChange(Gallery.galleryWrapper);
        var fsr = {
          recipe: Gallery.recipeList.records[idx],
          count: Gallery.recipeList.records.length,
          index: idx
        }
        this.viewingRecipeIdx = idx;
        Gallery.buildRecipe(fsr);
      }
    } else {
      Gallery.buildRecipe(Gallery.recipeData);
    }
  },
  
  focusUser: function(id){
    Gallery.startPageChange(Gallery.galleryWrapper);
    if(!Gallery._debug){
      Gallery.updateUser();
      $.getJSON(Gallery.viewUserQuery+'?id='+id, Gallery.buildUser);
    }else{
      Gallery.buildUser(Gallery.userData);
    }
  },
  userPage: function(index){
    Gallery.startPageChange(Gallery.userGalleryWrapper);
    Gallery.lastQuery.start = index * Gallery.lastQuery.max;
    //Gallery.backPage = Gallery.lastQuery.start;
    Gallery.navHistory[Gallery.navHistory.length - 1]['page'] = Gallery.lastQuery.start;
    
    if(!Gallery._debug){
      $.getJSON(Gallery.viewUserQuery+Gallery.getQueryString(), Gallery._userPage);
    }else{
      Gallery._userPage(Gallery.userData);
    }
  },
  
  buildRecipe: function(data) {
    var html = '';
    
    Gallery.lastResponse = data;
    
    if (Gallery.hidden) {
      Gallery.navHistory.push({'data':data,'function':Gallery.buildRecipe});
      
      data.recipeCount = Gallery.searchResults.length;
      html = tmpl("recipe_tmpl", data);
      trackEvent("Viewing recipe ID:" + data.recipe.id + ", " + data.recipe.title);
      $(Gallery.galleryWrapper).html(html);
      $('#leaveComment').focus(function() {
        if (this.value == 'Write a comment...') {
          this.value = '';
        }
      }).blur(function() {
        if (this.value.length < 1) {
          this.value = 'Write a comment...';
        }
      });
      //$('#addComment').submit(function() {
      //  Gallery.addComment(data.recipe.id);
      //});
      
      Gallery.endPageChange('gallerycontainer .wrapper');
    } else if (!Gallery.hidden) {
      Gallery.hideCallback = (function(){ Gallery.buildRecipe(data); });
    }
  },
  facebookLoginCallback: function() {
    trackEvent("Logged into Facebook");
    $('#recipelogin').remove();
    $('#likeBlock').hide().show(300);
    Gallery.updateUser();
  },
  buildUser: function(data){
    Gallery.lastResponse = data;
    
    if(data.success == true && Gallery.hidden){
      
      Gallery.navHistory.push({'data':data,'function':Gallery.buildUser});
      //Gallery.backData = data;
      //Gallery.backFunction = Gallery.buildUser;
      
      obj = data;
      data.recipeCount = Gallery.searchResults.length;
      Gallery.lastQuery = obj.params;
      
      var adminLink = '';
      if(Gallery.isAdmin && !obj.user.userbanned){
        adminLink = '<span class="adminOnly"><a href="#" onclick="Gallery.banUser('+obj.user.uid+');">ban user</a>(administrator only)</span>';
      }else if(Gallery.isAdmin && obj.user.userbanned){
        adminLink = '<span class="adminOnly"><a href="#" onclick="Gallery.unbanUser('+obj.user.uid+');">unban user</a>(administrator only)</span>';
      }
      
      var banStyle = '';
      if(obj.user.userbanned){
        banStyle = 'padding:2px;background-color:red;';
      }
      
      var firstNum = obj.params.start + 1;
      var lastNum = obj.params.start+obj.user.recipes.records.length;
      
      if(firstNum > lastNum) firstNum = lastNum;
      
      var totalPages = Math.ceil(obj.user.recipes.total / 8);
      var currentPage = Math.floor(firstNum/8);

      var pagination = Gallery.buildPagination(currentPage, totalPages, 'Gallery.userPage');
      
      var user = obj.user;
      var html = '';
      html += "<div id=\"galleryHeader\"> \
        <div id=\"gallerycrumb\"> \
          <p>Sandwiches: <span id=\"firstnumber\">"+firstNum+"</span>-<span id=\"lastnumber\">"+lastNum+"</span> of "+user.recipes.total+adminLink+"</p> \
        </div> \
        <div id=\"pagination\">"+pagination+"</div> \
        <div style=\"clear:both;\"></div> \
      </div> \
      <div style=\"clear:both;\"></div> \
       \
      <div id=\"userGalleryWrap\"> \
        <h1>"+(user.picsquare!=''?"<img style=\""+banStyle+"\" src=\""+user.picsquare+"\" />":'')+user.firstname+' '+user.lastname+"</h1> \
         \
        <div id=\"userGallery\">";
      
      Gallery.searchResults = [];
      Gallery.recipeList = user.recipes;
      for (i = 0; i < user.recipes; i++) {
        Gallery.searchResults.push(user.recipes[i].id);
      }
      
      html += Gallery.getUserThumbs(user.recipes);
      
      html +=  '</div><div style="clear:both;"></div></div>';

      $(Gallery.galleryWrapper).html(html);
      Gallery.endPageChange('gallerycontainer .wrapper');
    }else if(!Gallery.hidden){
      Gallery.hideCallback = (function(){ Gallery.buildUser(data); });
    }
  },
  
  buildMain: function(data){
    Gallery.lastResponse = data;

    if(data.success == true && Gallery.hidden){
      
      Gallery.navHistory.push({'data':data,'function':Gallery.buildMain});
      //Gallery.backData = data;
      //Gallery.backFunction = Gallery.buildMain;
      
      obj = data;
  
      Gallery.searchResults = [];
      Gallery.recipeList = data.recipes;
      for (i = 0; i < data.recipes.records.length; i++) {
        Gallery.searchResults.push(data.recipes.records[i].id);
      }
  
      Gallery.lastQuery = obj.params;

      var adminLink = '';
      if(Gallery.isAdmin){
        adminLink = "<span class=\"adminOnly\"><a href=\"#\" onclick=\"Gallery.adminGallery();\">view all</a>(administrator only)</span>";
      }
      
      var firstNum = obj.params.start + 1;
      var lastNum = obj.params.start+obj.recipes.records.length;

      if(lastNum > obj.recipes.total) lastNum = obj.recipes.total;
      if(firstNum > lastNum) firstNum = lastNum;
      
      var totalPages = Math.ceil(obj.recipes.total / 8);
      var currentPage = Math.floor(firstNum/8);

      var pagination = Gallery.buildPagination(currentPage, totalPages, 'Gallery.galleryPage');
      
      var filterItems = '';
      if(Gallery.lastQuery.userids == undefined || Gallery.lastQuery.userids == ''){
        filterItems += '<a href="#" class="browseBy" onclick="Gallery.filterGallery(\'friends\');">Friends</a>';
      } else {
        filterItems += '<a href="#" class="browseBy selected" onclick="Gallery.filterGallery(\'none\');">Friends</a>';
      }

      if(Gallery.lastQuery.favonly == undefined || Gallery.lastQuery.favonly == false){
        filterItems += '<a href="#" class="browseBy" onclick="Gallery.filterGallery(\'favorites\');">Favorites</a>';
      } else {
        filterItems += '<a href="#" class="browseBy selected" onclick="Gallery.filterGallery(\'none\');">Favorites</a>';
      }
      
      var sortItem = 'recent';
      if(Gallery.lastQuery.sort == 'votes')
        sortItem = 'votes';
      
      var sortLinks = '';

      var votes_class = sortItem == 'votes' ? ' selected' : '';
      sortLinks += "<a href=\"#\" onclick=\"Gallery.sortGallery('votes')\" class=\"browseBy" + votes_class + "\" >Most Popular</a>";

      var created_class = sortItem != 'votes' ? ' selected' : '';
      sortLinks += "<a href=\"#\" onclick=\"Gallery.sortGallery('created');\" class=\"browseBy" + created_class + "\">Most Recent</a>";
      
      var html = '';
      html +=  "<div id=\"galleryHeader\"> \
          <div id=\"gallerycrumb\"> \
            <p>Sandwiches: <span id=\"firstnumber\">"+firstNum+"</span>-<span id=\"lastnumber\">"+lastNum+"</span> of "+obj.recipes.total+adminLink+"</p> \
             \
          </div> \
             \
          <div id=\"pagination\"> \
            "+pagination+" \
          </div> \
              <div style=\"clear:both;\"></div> \
        </div> \
        <div style=\"clear:both;\"></div> \
        <table id=\"galleryNav\"> \
          <tr> \
            <td><h1>gallery of deliciousness</h1></td> \
            <td class=\"sortItems\"> \
              <span class=\"sortBy\">Browse By:</span> "+sortLinks+"\
            <!--</td> \
            <td class=\"sortItems\"> \
              <span class=\"sortBy\">Filter By:</span>--> "+filterItems+" \
            </td> \
            <td style=\"text-align: right;\"> \
              <form id=\"gallerysearchform\" onsubmit=\"$('#gallerysubmitsearch').click(); return false;\"> \
                <input type=\"text\" tabindex=\"1\" name=\"gallerysearch\" id=\"gallerysearch\" value=\""+Gallery.lastQuery.search+"\"/> \
                <a href=\"#\" id=\"gallerysubmitsearch\" onclick=\"Gallery.searchGallery($('#gallerysearch')[0].value);\" class=\"last\">Search</a> \
              </form> \
            </td> \
          </tr> \
        </table> \
        </div>";
      
      Gallery.recipeList = obj.recipes;
      
      var prevPageClass = (currentPage == 0) ? ' hidden' : '';
      var nextPageClass = (currentPage == totalPages - 1 || totalPages == 0) ? ' hidden' : '';
      
      html += '<table style="width:910px;height:360px;"><tr><td style="width: 42px; text-align: right;" id="leftArrowColumn"><a href="#" onclick="Gallery.prevPage();" class="nextPrevArrows' + prevPageClass + '" id="prevPageArrow"></a><div style="clear:both;"></div></td><td>';
      html += '<div id="gallery">';
      html += Gallery.getGalleryThumbs(obj.recipes);
      html += '<div style="clear:both;"></div></div>';
      html += '</td><td style="width: 42px; text-align: left;" id="rightArrowColumn"><a href="#" onclick="Gallery.nextPage();" class="nextPrevArrows' + nextPageClass + '" id="nextPageArrow"></a><div style="clear:both;"></div></td></tr></table>';
 
      Gallery.pageInfo();
 
      $(Gallery.galleryWrapper).html(html);
      Gallery.endPageChange('gallerycontainer .wrapper');
    }else if(!Gallery.hidden){
      Gallery.hideCallback = (function(){ Gallery.buildMain(data); });
    }
  },
  
  _galleryPage: function(data){
    if(data.success == true && Gallery.hidden){
      obj = data;
      Gallery.lastQuery = obj.params;
      
      Gallery.pageInfo();
      
      Gallery.navHistory.push({'data':data,'function':Gallery.buildMain});
      //Gallery.backData = data;
      //Gallery.backFunction = Gallery.buildMain; //Gallery._galleryPage;
      
      Gallery.searchResults = [];
      Gallery.recipeList = data.recipes;
      for (i = 0; i < data.recipes.records.length; i++) {
        Gallery.searchResults.push(data.recipes.records[i].id);
      }
      
      var firstNum = obj.params.start + 1;
      var lastNum = obj.params.start+obj.recipes.records.length;

      if(lastNum > obj.recipes.total) lastNum = obj.recipes.total;
      if(firstNum > lastNum) firstNum = lastNum;
      
      var totalPages = Math.ceil(obj.recipes.total / 8);
      var currentPage = Math.floor(firstNum/8);
      
      $('#firstnumber').html(firstNum);
      $('#lastnumber').html(lastNum);
      $('#pagination').html(Gallery.buildPagination(currentPage, totalPages, 'Gallery.galleryPage'));
      
      $(Gallery.innerGalleryWrapper).html(Gallery.getGalleryThumbs(data.recipes));
      Gallery.endPageChange('gallerycontainer .wrapper');

    }else if(!Gallery.hidden){
      Gallery.hideCallback = (function(){ Gallery._galleryPage(data); });
    }
  },
  
  _userPage: function(data){
    if(data.success == true && Gallery.hidden){
      obj = data;
      Gallery.lastQuery = obj.params;
      
      Gallery.pageInfo();
      
      Gallery.navHistory.push({'data':data,'function':Gallery.buildUser});
      //Gallery.backData = data;
      //Gallery.backFunction = Gallery.buildUser;
      
      var firstNum = obj.params.start + 1;
      var lastNum = obj.params.start+obj.user.recipes.records.length;

      if(lastNum > obj.user.recipes.total) lastNum = obj.user.recipes.total;
      if(firstNum > lastNum) firstNum = lastNum;
      
      var totalPages = Math.ceil(obj.user.recipes.total / 8);
      var currentPage = Math.floor(firstNum/8);
      
      $('#firstnumber').html(firstNum);
      $('#lastnumber').html(lastNum);
      $('#pagination').html(Gallery.buildPagination(currentPage, totalPages, 'Gallery.userPage'));
      
      $(Gallery.userGalleryWrapper).html(Gallery.getUserThumbs(data.user.recipes));
      Gallery.endPageChange('gallerycontainer .wrapper');

    }else if(!Gallery.hidden){
      Gallery.hideCallback = (function(){ Gallery._userPage(data); });
    }
  },
  
  getGalleryThumbs: function(recipes){
    var html = '';

    Gallery.searchResults = [];
    Gallery.recipeList = recipes;
    for (i = 0; i < recipes.records.length; i++) {
      Gallery.searchResults.push(recipes.records[i].id);
    }

    var length = recipes.records.length;
    for(var i=0; i<length && i<8; i++){
      if(i == 4){
        html += '<div style="clear:both;"></div>';
      }
      var thisObj = recipes.records[i];
      
      var bgStyle = '';
      if(Gallery.isAdmin){
        if(thisObj.favorite){
          bgStyle = "background-color:gold;";
        }
      
        if(thisObj.hidden || thisObj.banned){
          bgStyle = "background-color:#ff5555;";
        }
      }
      
      html += '<div class="thumb" style="'+bgStyle+'">';
      html += '<a href="javascript:Gallery.focusSandwich('+(i)+');"><img src="/image?width=165&height=114&id='+ thisObj.id +'"/><br />';
      html += '<span class="sandwichname">'+thisObj.title+'</span></a>';
      html += '<a class="profile" href="#" onclick="Gallery.focusUser('+thisObj.userid+');">'+thisObj.user.firstname + ' ' + thisObj.user.lastname+'</a>';
      html += '</div>';
    }
    html += '<div style="clear:both;"></div>';
    return html;
  },
  getUserThumbs: function(recipes){
    var html = '';
    var length = recipes.records.length;
    
    Gallery.searchResults = [];
    Gallery.recipeList = recipes;
    for (i = 0; i < recipes.records.length; i++) {
      Gallery.searchResults.push(recipes.records[i].id);
    }
    
    for(var i=0; i<length && i<8; i++){
      if(i == 4){
        html += '<div style="clear:both;"></div>';
      }
      var thisObj = recipes.records[i];
      
      var bgStyle = '';
      
      if(Gallery.isAdmin){
        if(thisObj.favorite){
          bgStyle = "background-color:gold;";
        }
        
        if(thisObj.hidden){
          bgStyle = "background-color:#ff5555;";
        }
      }
      
      html += '<div class="thumb" style="'+bgStyle+'">';
      //html += '<a href="javascript:Gallery.focusSandwich('+thisObj.id+');"><img src="/image?width=165&height=114&id='+ thisObj.id +'"/><br />';
      html += '<a href="javascript:Gallery.focusSandwich('+(i)+');"><img src="/image?width=165&height=114&id='+ thisObj.id +'"/><br />';
      html += '<span class="sandwichname">'+thisObj.title+'</span></a>';
      //html += '<a class="profile" href="javascript:Gallery.focusUser('+user.uid+');">'+user.name+'</a>';
      if(Gallery.isAdmin){
        html+= '<a href="/submitrecipe?editid='+thisObj.id+'" class="profile">Edit</a>';
        html += '<br />';
        if(thisObj.hidden){
          html+= '<a href="#" class="profile" onclick="Gallery.unhideImage('+thisObj.id+');">Unhide</a>';
        }else{
          html+= '<a href="#" class="profile" onclick="Gallery.hideImage('+thisObj.id+');">Hide</a>';
        }
        html += '<br />';
        if(thisObj.favorite){
          html+= '<a href="#" class="profile" onclick="Gallery.removeFavorite('+thisObj.id+');">Remove Favorite</a>';
        }else{
          html+= '<a href="#" class="profile" onclick="Gallery.addFavorite('+thisObj.id+');">Make Favorite</a>';
        }
      }
      html += '</div>';
    }
    html += '<div style="clear:both;"></div>';
    return html;
  },
  
  startPageChange: function(useWrapper){
    Gallery.useWrapper = useWrapper;
    $(Gallery.useWrapper).animate({opacity:0}, 400, function(){
      Gallery.hidden = true;
      if(typeof Gallery.hideCallback == 'function'){
        Gallery.hideCallback();
      }
      Gallery.hideCallback = null;
    });
  },
  endPageChange: function(container) {
    $(Gallery.useWrapper).animate({opacity:1}, 400, function(){
      
      Gallery.hidden = false;
      if (container != null) {
        if (Controller.checkOverflow($('#' + container)[0])) {
          Controller.enableRightShadow(false, $('#' + container)[0]);
        } else {
          Controller.enableRightShadow(true, $('#' + container)[0]);
        }
      }
    });
  },
  
  getQueryString: function(){
    var qString = '?';
    var first = true;
    for(key in Gallery.lastQuery){
      if(!first)
        qString += '&';
      else
        first = false;
        
      qString += key + '=' + Gallery.lastQuery[key].toString();
    }
    return qString;
  },
  
  buildPagination: function(currentPage, totalPages, callback){
    var pagination = 'Page <span class="active">' + (currentPage + 1) + '</span> of ' + totalPages + ' &nbsp;&nbsp;&nbsp;'; //(Gallery.navHistory.length > 1 ? '<a href="javascript:Gallery.goBack(1);">Back</a>&nbsp;&nbsp; ' : '');
    if(totalPages > 1){
      if(currentPage > 2)
        pagination += '<a href="javascript:'+callback+'(0);">&lt; First</a>. . .';
        
      var count = 0;
      if(totalPages > 5){
        var i = currentPage-2;
        if(i > totalPages-5)
          i = totalPages-5;
      }else{
        var i = 0;
      }
      for( ; count<5 && i<totalPages; i++){
        if(i>=0){
          if(i != currentPage)
            pagination += ' <a href="javascript:'+callback+'('+i+');">'+(i+1)+'</a> ';
          else
            pagination += ' <a href="javascript:'+callback+'('+i+');"><span class="active">'+(i+1)+'</span></a> ';
          count++;
        }
      }
      
      if(currentPage < totalPages-3 && totalPages > 5)
        pagination += '. . .<a href="javascript:'+callback+'('+(totalPages-1)+');">Last &gt;</a>';
    }
    return pagination;
  },
  voteForRecipe: function(recipeID) {
    $.getJSON(Gallery.voteQuery, {'id': recipeID}, Gallery.voteCast);
  },
  voteCast: function(data) {
    trackEvent("Voted for ID:" + data.params.id);
    $('#likeBlock').fadeOut(300, function() {
      $('#likeBlock').remove();
      if (data.success) {
        $('#likeQty').html(data.votes);
      }
    });
  },
  addComment: function(recipeID) {
    $.getJSON(Gallery.addCommentQuery, {'recipeid': recipeID, 'comment': $('#leaveComment').val()}, Gallery.commentAdded);
    return false;
  },
  commentAdded: function(data) {
    if (data.success) {
      $('#justComments').prepend(tmpl('recipe_comment_tmpl', data.comment));
      $('#recipeComment' + data.comment.id).hide().show(300);
      trackEvent("Added comment to ID:" + data.params.recipeid + ", " + data.params.comment);
      $('#leaveComment').val('Comment added!');
      setTimeout(function() { $('#leaveComment').val('Write a comment...'); }, 2500);
    } else {
      $('#leaveComment').val(data.message);
      Dialog.show('Error', data.message);
    }
  },
  goBack: function(skip) {
    if (typeof skip !== 'undefined') {
      for (var i = 0; i < skip; i++) {
        Gallery.navHistory.pop();
      }
    }
    
    if (Gallery.navHistory.length > 0) {
      var histObj = Gallery.navHistory.pop();
      
      if (histObj.hasOwnProperty('page')) {
        Gallery.lastQuery.start = histObj['page'];
      }
      
      Gallery.hideCallback = function() { histObj['function'](histObj['data']); }
      Gallery.startPageChange(Gallery.galleryWrapper);
    }
    
    //if (typeof Gallery.backFunction === 'function') {
    //  
    //  if (typeof Gallery.backPage != 'undefined') {
    //    Gallery.lastQuery.start = Gallery.backPage;
    //    Gallery.backPage = undefined;
    //  }
    //  
    //  Gallery.hideCallback = function() { Gallery.backFunction(Gallery.backData); }
    //  Gallery.startPageChange(Gallery.galleryWrapper);
    //}
  }
}; // Gallery()


Subscribe = {
  wrapper: null,
  formDefault: '',
  submitPath: '/subscribe',
  
  init: function(){
    this.wrapper = $('#updateswrapper');
    this.formDefault = $('#updatesforminput').val();
  
    $('#updatesbtn').click(Subscribe.showForm);
    $('#updatesforminput').focus(Subscribe.cleanInput);
    $('#updatesforminput').blur(Subscribe.resetInput);
    $('#updatesform').submit(Subscribe.submitForm);
  },
  
  showForm: function(){
    var wrapper = $(Subscribe.wrapper);
    wrapper.animate({'width':1}, 1000, function(){
      $('#updatesinvitewrapper').css('display', 'none');
      $('#updatessubmitwrapper').css('display','block');
      $(wrapper).animate({'width':190}, 1000);
    });
  },
  
  cleanInput: function(){
    if($('#updatesforminput').val() == Subscribe.formDefault){
      $('#updatesforminput').val('');
      $(this).css('background','');
    }
  },
  resetInput: function(){
    if($('#updatesforminput').val() == '')
      $('#updatesforminput').val(Subscribe.formDefault);  
  },
  
  submitForm: function(){
    if(Subscribe.validateForm()){
      $.post(Subscribe.submitPath, {updatesforminput:$('#updatesforminput').val()}, function(data) {
        if(data.success == true){
          var wrapper = $(Subscribe.wrapper);
          wrapper.animate({'width':1}, 1000, function(){
            $('#updatessubmitwrapper').css('display','none');
            $('#updatesthanks').css('display', 'block');
            $(wrapper).animate({'width':215}, 1000);
            
            setTimeout(Subscribe.resetForm, 6000);
          });
        }else{
          $('#updatesforminput').css('background', '#ffaaaa');
        }
      }, 'json');
    }
    return false;
  },
  
  validateForm: function(){
    if($.trim($('#updatesforminput').val()).indexOf('@') > 0){
      $('#updatesforminput').css('background', '');
      return true;
    }else{
      $('#updatesforminput').css('background', '#ffaaaa');
      return false;
    }
    return false;
  },
  
  resetForm: function(){
    $('#updatesforminput').val(Subscribe.formDefault);
    
    var wrapper = $(Subscribe.wrapper);
    wrapper.animate({'width':1}, 1000, function(){
      $('#updatesthanks').css('display','none');
      $('#updatesinvitewrapper').css('display', 'block');
      $(wrapper).animate({'width':140}, 1000);
    });
  }
}

SendToFriend = {
  submitPath: '/api/sendtofriend/sendtofriend',
  formVals: null,
  
  init: function(){
    $('#sendtofriendform').submit(SendToFriend.submit);
  },
  
  submit: function(){
    if(SendToFriend.validate()){
      $.post(SendToFriend.submitPath, SendToFriend.formVals, function(data){
        if(data.success == true){
          handlePageNavClick({data: {param: 'sendtofriendthankyoucontainer'}});
  
          setTimeout(SendToFriend.thankyouEjection, 5000);
          
          $('#sendtofriendform input').each(function(){
            $(this).val($(this).attr('originalval'));
          });
        }else{
          alert(data.message);
        }
      }, 'json');    
    }
    return false;
  },
  
  validate: function(){
    if(validateSubmission(document.getElementById('sendtofriendform'))){
      var form = $('#sendtofriendform');
    
      SendToFriend.formVals = {
        recipientname: $('#recipientname', form).val(),
        recipientemail: $('#recipientemail', form).val(),
        sendername: $('#sendername', form).val(),
        senderemail: $('#senderemail', form).val()
      };
      return true;
    }else {
      return false;
    }
  },
  
  thankyouEjection: function(){
    if(Controller.currentPage == 'sendtofriendthankyoucontainer'){
      $('#link1').click();
    }
  }
}

TshirtEntry = {
  submitPath: '/api/entry/tshirt',
  formVals: null,
  
  init: function(){
    //$('#tshirtentryform').submit(TshirtEntry.submit);
  },
  
  submit: function(){
    if(TshirtEntry.validate()){
      $.post(TshirtEntry.submitPath, TshirtEntry.formVals, function(data){
        if(data.success){
          handlePageNavClick({data: {param: 'tshirtentrythankyoucontainer'}});
          
          setTimeout(TshirtEntry.thankyouEjection, 5000);
          
          $('#tshirtentryform input').each(function(){
            $(this).val('');
          });
          $('#tshirtentryform select').each(function(){
            this.selectedIndex = 0;
          });
        }else{
          alert(data.message);
        }
      }, 'json');
    }
    return false;
  },
  
  validate: function(){
    if(validateSubmission(document.getElementById('tshirtentryform'))){
      var form = $('#tshirtentryform');

      TshirtEntry.formVals = {
        firstname: $('#firstname', form).val(),
        lastname: $('#lastname', form).val(),
        email: $('#emailaddy', form).val(),
        confirmemail: $('#emailconfirm', form).val(),
        address1: $('#address1', form).val(),
        address2: $('#address2', form).val(),
        city: $('#city', form).val(),
        state: $('#state', form).val(),
        zip: $('#zip', form).val(),
        gender: $('#tshirtgender', form).val(),
        size: $('#tshirtsize', form).val(),
        signup: $('#news', form)[0].checked
      };
      return true;
    }
    return false;
  },
  
  thankyouEjection: function(){
    if(Controller.currentPage == 'tshirtentrythankyoucontainer'){
      $('#link1').click();
    }
  }
}

function validateSubmission(form){
  var ret = true;

  $('.formtext', form).each(function(){
    if($.trim($(this).val()) == ''){
      $(this).css('background', '#ffaaaa');
      ret = false;
    }else{
      $(this).css('background', '');
    }
  });
  
  $('.instructioninput', form).each(function(){
    if($.trim($(this).attr('originalval')) == $.trim($(this).val())  ){
      $(this).css('background', '#ffaaaa');
      ret = false;
    }else{
      $(this).css('background', '');
    }  
  });
  
  var checkSet = new Array();
  $('.formemail', form).each(function(){
    var rel = $(this).attr('rel');
    if(rel != '' && $('#'+rel).length > 0){
      if($(this).val() == $('#'+rel).val()){
        $(this).css('background-color', '');
      }else{
        $(this).css('background-color', '#ffaaaa');
        ret = false;
      }
    }else{
      if($(this).val().indexOf('@') > 0){
        $(this).css('background-color', '');
      }else{
        $(this).css('background-color', '#ffaaaa');
        ret = false;
      }
    }
  });
  
  var hasIngredient = false;
  var ingredients = $('.formingredient', form);
  if(ingredients.length > 0){
    ingredients.each(function(){
      if($.trim($(this).val()) != ''){
        hasIngredient = true;
      }
    });
    if(!hasIngredient){
      $(ingredients[0]).css('background', '#ffaaaa');
      ret = false;
    }else{
      $(ingredients[0]).css('background', '');
    }
  }
  
  var legal = $('#legal', form);
  if(legal.length > 0){
    if($(legal).attr('checked') == false){
      $('#legalLabel', form).css('color', 'red');
      ret = false;
    }else{
      $('#legalLabel', form).css('color', '');
    }
  }
  
  var image_upload = $('#sandwichImage', form);
  if (image_upload.length > 0) {
    if ($(image_upload).val().trim() == '') {
      $('#fileWrapper', form).css('background-color', '#ffaaaa');
      ret = false;
    } else {
      $('#fileWrapper', form).css('background-color', '');
    }
  }
  
  
  $('.formzip', form).each(function(){
    var val = parseInt($(this).val());

    if(val < 1000 || val > 99999 || isNaN(val)){
      $(this).css('background', '#ffaaaa');
      ret = false;
    }else{
      $(this).css('background', '');
    }
  });

  return ret;
}


function trackEvent(evt) {
try{
  if(gaTracker != undefined) {
    try {
      gaTracker._trackEvent('action', 'click', evt);
    } catch(err) {
      if (typeof console === 'object') {
        //console.log(err.message);
      }
    }
  } else {
    if (typeof console === 'object') {
      //console.log('GA Tracker Invalid');
    }
  }
  
  if (typeof console === 'object') {
    //console.log(evt);
  }
}catch(e){}
}

Dialog = {
  show: function(title, body) {
    $('#dialogContainer').remove();
    $('#dialogHolder').html(tmpl('dialog_tmpl', {'title':title,'body':body}))
    $('#dialogContainer').hide().show(300);
    return false;
  },
  hide: function() {
    $('#dialogContainer').hide(300, function() {
      $(this).remove();
    });
    return false;
  }
}
