/// <reference path="jquery-1.4.1-vsdoc.js" />

HERSHEYS.Kitchens = {};

if (!SITE_PREFIX) var SITE_PREFIX = '/en'

HERSHEYS.Kitchens.loginCallback = function(){    
  window.location.href = SITE_PREFIX+'/recipes/my-kitchen.aspx';
};

HERSHEYS.Kitchens.doKitchensFlyout = function(){
	
	$('.mykitchen-link').toggleClass('selected');
    $('.my-kitchen-fly').toggle('slide', 1000);

	if ($('.mykitchen-link').hasClass('selected')){
		HERSHEYS.Kitchens.Analytics.track('flyout');
	}
	
}


HERSHEYS.Kitchens.initializations = {

    /* HOMEPAGE */
    'recipes': function () {



    },

    /* ETC */

  'recipes/my-kitchen/submit-tips' : function(){
    
	function log(event, data, formatted) { $("<li>").html( !data ? "No match!" : "Selected: " + formatted).appendTo("#result"); }
    function formatItem(row) { return "<img src='/en/recipes/Image.ashx?type=submittedphoto&id=" + row[0] + "&s=sm' class='l' style='width: 50px; margin-right: 10px' />"  + "<strong>" + row[1] + "</strong>"; }
    function formatResult(row) { return row[1]; }

    $(".recipe_name_autocomplete").autocomplete('/en/recipes/AjaxServices.ashx?method=recipeautocomplete', {
		width: 289,
		multiple: false,
		matchContains: true,
		formatItem: formatItem,
		formatResult: formatResult
    }).result(function(event, item) {
		$('.txtRecipeId').attr('value', item[0]);
	});  
  },
  'recipes/promotions/iconic-recipe/rules' : function(){ HERSHEYS.Kitchens.loginCallback = function(){ window.location.href = '/recipes/promotions/iconic-recipe/vote.aspx'};},
  'recipes/promotions/iconic-recipe/prizes' : function(){ HERSHEYS.Kitchens.loginCallback = function(){ window.location.href = '/recipes/promotions/iconic-recipe/vote.aspx'};},
  'recipes/promotions/iconic-recipe' : function(){ HERSHEYS.Kitchens.loginCallback = function(){ window.location.href = '/recipes/promotions/iconic-recipe/vote.aspx'};},  
  'recipes/promotions/iconic-recipe/vote' : function(){
    
    HERSHEYS.Kitchens.loginCallback = function(){ window.location.href = '/recipes/promotions/iconic-recipe/vote.aspx'};
    
    if ($.cookie('iconicRecipeID')){
      
        setTimeout(function(){
        $('.recipe-link a[href^=/recipes/' + $.cookie('iconicRecipeID') +']').click();
      }, 200);
    }
  },
  'recipes/my-kitchen/my-grocery-list' : function(){
    
    $('.asset_list span a').bind('click', function(){
      $(this).parents('li').hide('puff', 1000);
      $(this).hide();
    });
  },
  'recipes/my-kitchen/my-recipe-box' : function(){
    
    $('.recipe_box_wrap a.remove').bind('click', function(){
      $(this).parents('.recipe_box_wrap').hide('puff', 1000);
      $(this).hide();
    });  
  }

};

HERSHEYS.Utility.doPageInits(HERSHEYS.Kitchens.initializations);


HERSHEYS.Kitchens.Analytics = {};

HERSHEYS.Kitchens.Analytics.track = function(which, data){
  var s = s_gi(s_account);
  s.templtv = s.linkTrackVars;          /*Saving the original state of the variables*/
  s.templte = s.linkTrackEvents;         /*Saving the original state of the variables*/
  
  switch(which){

    case 'submitTip':
      /* recipeID, if present. */
      var recipeID = data;
      s.linkTrackVars = "events,eVar37,eVar39,eVar10,prop27,prop28,prop30,products";      /*Defining the list of variables that will be sent in the server call*/
      s.products      = ';' + recipeID;
      s.eVar10        = s.prop30 = recipeID;
      s.eVar37        = s.prop27 = 'tipsubmit';
      s.eVar39        = s.prop28 = '[loggedIn]';
      s.events        = s.linkTrackEvents = 'event17';
      s.tl(true,'o','tip submission');   /*Server call */
          break;

    case 'submitRecipe':
    /* nothing to pass */
      s.linkTrackVars = "events,eVar37,eVar39,prop27,prop28";      /*Defining the list of variables that will be sent in the server call*/
      s.eVar37        = s.prop27 = 'recipesubmit';
      s.eVar39        = s.prop28 = '[loggedIn]';
      s.events        = s.linkTrackEvents = 'event17';
      s.tl(true,'o','recipe submission');   /* Server call */
    break;

    case 'saveRecipeBox':
    /* recipeID */
      var recipeID = data;
      s.linkTrackVars = "events,eVar39,eVar10,prop28,prop30,products";      /*Defining the list of variables that will be sent in the server call*/
      s.products      = ';' + recipeID
      s.eVar10        = s.prop30 = recipeID
      s.eVar39        = s.prop28 = '[loggedIn]';
      s.events        = s.linkTrackEvents = 'event6';
      s.tl(true,'o','recipe save');   /*Server call*/          
      break;
      
    case 'voteForRecipe':
    /* recipeID */
      var recipeID = data;
      s.linkTrackVars = "events,eVar39,eVar37,prop28,prop27,products";      /*Defining the list of variables that will be sent in the server call*/
      s.products      = ';' + recipeID;
      s.eVar37        = s.prop27 = 'IconicPromoVote:' + recipeID;
      s.eVar39        = s.prop28 = '[loggedIn]';
      s.events        = s.linkTrackEvents = 'event17';
      s.tl(true,'o','iconic promo recipe vote');   /*Server call*/          
      break;
    
    case 'addToGroceryList':
    /* recipeID */
    var recipeID = data;
                 s.linkTrackVars = "events,eVar39,eVar10,prop28,prop30,products";      /*Defining the list of variables that will be sent in the server call*/
                 s.products      = ';' + recipeID;
                 s.eVar10        = s.prop30          = recipeID;
                 s.eVar39        = s.prop28          = '[loggedIn]';
                 s.events        = s.linkTrackEvents = 'scAdd';
                 s.tl(true,'o','recipe add to grocery list');   /*Server call */
                break;
    
    case 'rateRecipe':
    /* recipeID */
    var recipeID = data;
                s.linkTrackVars = "events,eVar39,eVar37,prop27,prop28,products";      /*Defining the list of variables that will be sent in the server call*/
                s.products      = ';' + recipeID;
                s.eVar37        = s.prop27          = 'RateaRecipe:' + recipeID;
                s.eVar39        = s.prop28          = '[loggedIn]';
                s.events        = s.linkTrackEvents = 'event17';
                s.tl(true,'o','rate recipe');   /*Server call */                
                break;
    
    case 'nutritionalView':
    /* recipeID */
    var recipeID = data;
                s.linkTrackVars = "events,eVar39,eVar10,prop30,prop28,products";      /*Defining the list of variables that will be sent in the server call*/
                s.products      = ';' + recipeID
                s.eVar10        = s.prop30          = recipeID
                s.eVar39        = s.prop28          = HERSHEYS.IsLoggedIn ? '[loggedIn]' : '[unknown]';
                s.events        = s.linkTrackEvents = 'event11';
                s.tl(true,'o','nutrition view');   /*Server call */                     
                break;
    
    case 'addNoteToRecipe':
    /* nothing to pass- ideally we'd know which recipe is saved, but they are all on the same page... */
                s.linkTrackVars = "events,eVar39,eVar37,prop27,prop28";      /*Defining the list of variables that will be sent in the server call*/
                s.eVar37        = s.prop27          = 'addnotestorecipe:' + recipeID /* if recipe ID is possible, if not, just pass string */
                s.eVar39        = s.prop28          = '[loggedIn]';
                s.events        = s.linkTrackEvents = 'event17';
                s.tl(true,'o','add note to recipe');   /*Server call */               
                break;
    
    case 'removeRecipeFromBox':
    /* recipeID */
      var recipeID = data;
      s.linkTrackVars = "events,eVar36,eVar10,eVar39,prop26,prop28,prop30,products";      /*Defining the list of variables that will be sent in the server call*/
      s.products      = ';' + recipeID;
      s.eVar36        = s.prop26          = 'Recipes:removefromrecipebox'
      s.eVar10        = s.prop30          = recipeID;
      s.eVar39        = s.prop28          = '[loggedIn]';
      s.events        = s.linkTrackEvents = 'event16';
      s.tl(true,'o','remove recipe from box');   /*Server call */
            break;
    
    case 'removeRecipeFromGrocery':
    /* recipeID */
      var recipeID = data;
      s.linkTrackVars = "events,eVar36,eVar10,eVar39,prop26,prop28,prop30,products";      /*Defining the list of variables that will be sent in the server call*/
      s.products      = ';' + recipeID;
      s.eVar36        = s.prop26          = 'Recipes:removefromrecipebox'
      s.eVar10        = s.prop30          = recipeID;
      s.eVar39        = s.prop28          = '[loggedIn]';
      s.events        = s.linkTrackEvents = 'event16';
      s.tl(true,'o','remove recipe from box');   /*Server call */               
      break;
    
    case 'saveToLibrary':
      s.linkTrackVars = "events,eVar36,eVar39,eVar37,prop26,prop27,prop28,products";      /*Defining the list of variables that will be sent in the server call*/
      s.eVar36        = s.prop26          = 'Recipes:howto:hosting cookie exchange';
      s.eVar37        = s.prop27          = 'Recipes:howto:hosting cookie exchange:savetolibrary';
      s.eVar39        = s.prop28          = HERSHEYS.IsLoggedIn ? '[loggedIn]' : '[unknown]';
      s.events        = s.linkTrackEvents = 'event16,event18';
      s.tl(true,'o','save to library');   /*Server call */
      break;
    
    case 'share':
    
      var source = data;  
      
      if (typeof OMNITURE_RECIPE_ID != 'undefined'){
          s.linkTrackVars = "events,eVar39,eVar36,prop26,prop28,products";      /*Defining the list of variables that will be sent in the server call*/
          s.products      = ';' + OMNITURE_RECIPE_ID;
          s.eVar39        = s.prop28          = '[loggedIn]';
          s.eVar36        = s.prop26          = 'Sharerecipe:[' + source + ']';
          s.events        = s.linkTrackEvents = 'event7,event16';
          s.tl(true,'o','recipe share');   /*Server call */
      }else{
          s.linkTrackVars = "events,eVar39,eVar36,prop26,prop27,prop28,products";      /*Defining the list of variables that will be sent in the server call*/
          s.products      = ';' + recipeID;
          s.eVar39        = s.prop28          = HERSHEYS.IsLoggedIn ? '[loggedIn]' : '[unknown]';
          s.eVar36        = s.prop26          = 'Recipes:howto:hosting cookie exchange';
          s.eVar37        = s.prop27          = 'Recipes:howto:hosting cookie exchange:savetolibrary';
          s.events        = s.linkTrackEvents = 'event18,event16';
          s.tl(true,'o','page share');   /*Server call */
      }
            
    break;
    
	case 'flyout':
                        
      break;

    case 'login':
      s.linkTrackVars = "events,eVar39,prop28";      /*Defining the list of variables that will be sent in the server call*/
      s.eVar39        = s.prop28          = '[loggedIn]';
      s.events        = s.linkTrackEvents = 'event19';
      s.tl(true,'o','login');   /*Server call */                     
      break;
    
    case 'inviteFriend':
      /* Start vs Complete */
      var action = data;
      if (action == 'start'){
                        s.linkTrackVars = "events,eVar36,eVar39,prop26,prop28";      /*Defining the list of variables that will be sent in the server call*/
                        s.eVar36        = s.prop26          = 'Recipe:invite friend';
                        s.eVar39        = s.prop28          = HERSHEYS.IsLoggedIn ? '[loggedIn]' : '[unknown]';
                        s.events        = s.linkTrackEvents = 'event15';
                        s.tl(true,'o','invite friend start');   /*Server call */                     
                
      }else if (action == 'complete'){
                        s.linkTrackVars = "events,eVar36,eVar39,prop16,prop28";      /*Defining the list of variables that will be sent in the server call*/
                        s.eVar36        = s.prop26          = 'Recipe:invite friend';
                        s.eVar39        = s.prop28          = HERSHEYS.IsLoggedIn ? '[loggedIn]' : '[unknown]';
                        s.events        = s.linkTrackEvents = 'event16';
                        s.tl(true,'o','invite friend complete');   /*Server call */
      }
      break;
      
    case 'recipeFilter':
      /* filter type, filter */
      var filterType = data.type.toLowerCase();
      var filterName = data.name.toLowerCase();
      s.linkTrackVars = "events,eVar5,eVar1,prop18,prop32";      /*Defining the list of variables that will be sent in the server call*/
      s.eVar1         = s.prop18          = 'filterType' + ':' + 'filterName';
      s.eVar5         = s.prop32          = '[recipe filters]';
      s.events        = s.linkTrackEvents = 'event1';
      s.tl(true,'o','recipe filters');   /*Server call */
            break;  
  }
  
  if (s.templtv) {
    s.linkTrackVars = s.templtv;    /*reassigning the variables to the original state */
  }

  if (s.templte) {
    s.linkTrackEvents = s.templte;   /*reassigning the variables to the original state */
  }  
};

/* Keep this as false, when you popup a recipe set to true.
  This way we know when we load a recipe deeplinked (ie no popup),
  we disable further popus
*/
  
HERSHEYS.Kitchens.DEEP_LINKED_RECIPE = false;
HERSHEYS.Kitchens.DOING_POPUP = false;

HERSHEYS.Kitchens.initDetailPage = function(){
  
  // tabs
    var tabContainers = $('.tab-wrap > div, #tab7, #tab8');

    $('.tabs li a').bind('click', function () {
        tabContainers.hide().filter(this.hash).show();
        $('.tabs li a').removeClass('selected');
        $(this).addClass('selected');
        return false;
    }).filter(':first').click();
  
  $('.rating-link a').bind('click', function () {
    $('#tab1,#tab2,#tab3,#tab5,#tab6,#tab7').hide();
    $('#tab4').show();
    return false;
  });
  $('.comment-links .see_comments').bind('click', function () {
    $('#tab1,#tab2,#tab3,#tab4,#tab6,#tab7').hide();
    $('#tab5').show();
    return false;
  });
  $('.comment-links .make_comment').bind('click', function () {
    $('#tab1,#tab2,#tab3,#tab4,#tab5,#tab7').hide();
    $('#tab6').show();
    return false;
  });
  $('.recipe_back').bind('click', function () {
    $('#tab4,#tab5,#tab6,#tab7,#tab8').hide();
    $('#tab1').show();
    $('#tab-recipe a').addClass('selected');
    $('#tab-tips a,#tab-techniques a').removeClass('selected');
    return false;
  });
  
  $('#blog-link').bind('click', function(){
    
    tabContainers.hide();
    $('#tab8').show();
    return false;
    
  });
  
  // social media
    $('.recipe-tools li.share-link').hover(function () {
        $('.recipe-tools li ul').addClass('show');
    }, function () {
        $('.recipe-tools li ul').removeClass('show');
    });
  
  $('#lnkSaveRecipe').bind('click', function(){

      var _this = $(this);
      
      var recipeID =  $(this).attr('recipeid');
      
      if (!recipeID) recipeID = $(this).parent().attr('recipeid');
      
      HERSHEYS.Services.saveToRecipeBox({
        'recipeID' : recipeID,

        'success' : function(returns){
          
          HERSHEYS.Kitchens.Analytics.track('saveRecipeBox', recipeID);
          
          _this.html('Recipe Saved!');
          $('p.myrecipes-link').show();
        },
        'failure' : function(){
          
          HERSHEYS.Kitchens.loginCallback = function(){
            HERSHEYS.Kitchens.doKitchensFlyout();
            _this.click();
           };
          
           HERSHEYS.Kitchens.doKitchensFlyout();
        
        }
      });
      
      return false;
    
  });
  
  $('.addToGroceryList').bind('click', function(){
    
      var _this = $(this);
      var recipeID =  $(this).attr('recipeid');
      
      if (!recipeID) recipeID = $(this).parent().attr('recipeid');
      
      HERSHEYS.Services.addToGroceryList({
        
        'recipeID' : recipeID,

        'success' : function(returns){
          HERSHEYS.Kitchens.Analytics.track('addToGroceryList', recipeID);
          _this.html('Added to Groceries!');
        },
        'failure' : function(){
          
          HERSHEYS.Kitchens.loginCallback = function(){
            HERSHEYS.Kitchens.doKitchensFlyout();
            _this.click();
           };
          
            HERSHEYS.Kitchens.doKitchensFlyout();
          }
      });
      
      return false;
    
  });
  
  /* PAGINATION HANDLER - todo: clean up a bit and combine into one function to handle both tips and recipes */
  
      $('#tip_pagaination_wrapper .tips-sort-prev').unbind().bind('click', function(){
  
        var pageNumber   = $(this).attr('pageNumber') || 1;
        var recipeID   = OMNITURE_RECIPE_ID;
        var orderBY    = $('#tip_pagaination_wrapper .sortby a.active').attr('title') == 'Newest' ? 'false' :'true';
        var pageSize  = 5;
        var nextPage   = (pageNumber * 1) - 1;
          $(this).attr("pageNumber", nextPage);
  
        if (nextPage === 0)
             $('#tip_pagaination_wrapper .tips-sort-prev').css('visibility', 'hidden');

        $('#tip_pagaination_wrapper .tips-sort-next').attr("pageNumber", pageNumber + 1);
          $('#tip_pagaination_wrapper .tips-sort-next').css('visibility', 'visible');

        $('.tip').css({'opacity' : .5});

        $.getJSON('/en/recipes/AjaxServices.ashx?method=gettips&recipeid=' + recipeID + '&page=' + pageNumber + '&pagesize=' + pageSize + '&orderby=' + orderBY, function(data){
            var hasMore = data.hasmore;
            var html = data.html;

          $('.tip').remove();
             $('#tab2').append(html);

        });
    
        return false;
      });
  
      $('#tip_pagaination_wrapper .tips-sort-next').unbind().bind('click', function(){
        var pageNumber   = $(this).attr('pageNumber') || 2;
        var recipeID   = OMNITURE_RECIPE_ID;
        var orderBY    = $('#tip_pagaination_wrapper .sortby a.active').attr('title') == 'Newest' ? 'false' :'true';
        var pageSize  = 5;
        var nextPage   = (pageNumber * 1) + 1;
        
        $(this).attr("pageNumber", nextPage);

        $('#tip_pagaination_wrapper .tips-sort-prev').attr("pageNumber", nextPage - 2);
        $('#tip_pagaination_wrapper .tips-sort-prev').css('visibility', 'visible');
        $('.tip').css({'opacity' : .5});


        $.getJSON('/en/recipes/AjaxServices.ashx?method=gettips&recipeid=' + recipeID + '&page=' + pageNumber + '&pagesize=' + pageSize + '&orderby=' + orderBY, function(data){
            var hasMore = data.hasmore;
            var html = data.html;

          $('.tip').remove();
            $('#tab2').append(html);
              if (hasMore == 'false'){
                $('#tip_pagaination_wrapper .tips-sort-next').css('visibility', 'hidden');
            }else{
                $('#tip_pagaination_wrapper .tips-sort-next').css('visibility', 'visible');
            }
        });
        return false;
      });
      
      $('#reviews_pagaination_wrapper .tips-sort-prev').unbind().bind('click', function(){
  
        var pageNumber   = $(this).attr('pageNumber') || 1;
        var recipeID   = OMNITURE_RECIPE_ID;
        var orderBY    = $('#reviews_pagaination_wrapper .sortby a.active').attr('title') == 'Newest' ? 'false' :'true';
        var pageSize  = 5;
        var nextPage   = (pageNumber * 1) - 1;
          $(this).attr("pageNumber", nextPage);
  
        if (nextPage === 0)
             $('#reviews_pagaination_wrapper .tips-sort-prev').css('visibility', 'hidden');

        $('#reviews_pagaination_wrapper .tips-sort-next').attr("pageNumber", pageNumber + 1);
          $('#reviews_pagaination_wrapper .tips-sort-next').css('visibility', 'visible');

        $('.review').css({'opacity' : .5});

        $.getJSON('/en/recipes/AjaxServices.ashx?method=getcomments&recipeid=' + recipeID + '&page=' + pageNumber + '&pagesize=' + pageSize + '&orderby=' + orderBY, function(data){
            var hasMore = data.hasmore;
            var html = data.html;

          $('.review').remove();
             $('#tab5').append(html);

        });
    
        return false;
      });
  
      $('#reviews_pagaination_wrapper .tips-sort-next').unbind().bind('click', function(){
        var pageNumber   = $(this).attr('pageNumber') || 2;
        var recipeID   = OMNITURE_RECIPE_ID;
        var orderBY    = $('#reviews_pagaination_wrapper .sortby a.active').attr('title') == 'Newest' ? 'false' :'true';
        var pageSize  = 5;
        var nextPage   = (pageNumber * 1) + 1;
        $(this).attr("pageNumber", nextPage);

        $('#reviews_pagaination_wrapper .tips-sort-prev').attr("pageNumber", nextPage - 2);
        $('#reviews_pagaination_wrapper .tips-sort-prev').css('visibility', 'visible');
        $('.review').css({'opacity' : .5});


        $.getJSON('/en/recipes/AjaxServices.ashx?method=getcomments&recipeid=' + recipeID + '&page=' + pageNumber + '&pagesize=' + pageSize + '&orderby=' + orderBY, function(data){
            var hasMore = data.hasmore;
            var html = data.html;

          $('.review').remove();
            $('#tab5').append(html);
              if (hasMore == 'false'){
                $('#reviews_pagaination_wrapper .tips-sort-next').css('visibility', 'hidden');
            }else{
                $('#reviews_pagaination_wrapper .tips-sort-next').css('visibility', 'visible');
            }
        });
        return false;
      });
      
      $('.pagination_wrapper span.sortby a').live('click', function(){

          if ($(this).hasClass('active')) return false;
          $(this).siblings().removeClass('active');
          $(this).addClass('active');
      
         $(this).parents('.pagination_wrapper').find('.tips-sort-next').attr('pagenumber', 2);
          $(this).parents('.pagination_wrapper').find('.tips-sort-prev').attr('pagenumber', 1).click();

          return false;

      });
      
      /* Any link with a class of sharethis will trigger a fancybox share dialogue */
      $('a.sharethis').bind('click', function(e){

          //We need to hold onto the initial state of the form popup so we can continously do the find and replace for new popups
          
          var popContent = $(this).attr("href");
          
          
          $("#email-link").show();
          
          if($('body').hasClass('iconic-recipe') && $('body').hasClass('landing')){
            $("#email-link").hide();
          }
          
          /*if($(e.target).hasClass("button_share")){
            $("#email-link").hide();
          }*/
          
          if (typeof HERSHEYS.Kitchens.saveShareFormState == 'undefined'){
            HERSHEYS.Kitchens.saveShareFormState = $('#share_modal').html();
          }

          $('#share_modal').html(HERSHEYS.Kitchens.saveShareFormState);

          var title = $(this).attr('title') || document.title;
          var url = $(this).attr('pageurl') || window.location.href;

          if ($(this).attr('recipeid') != ''){
            $('#share_modal #email-link, #sendToFriend').attr('recipeid', $(this).attr('recipeid'));//.show();
          }

          $('.share_list a[id!=email-link]').each(function(){

            var href = $(this).attr('href');

            href = href.replace('[REPLACE_TITLE]', title).replace('[REPLACE_URL]', url);
            $(this).attr('href', encodeURI(href));

          });
          
          if(IS_MOBILE){
            $.fancybox(
                //$('#share_modal').html(),
                {
                  'href' : popContent,
                  'transitionIn'    : 'elastic',
                  'transitionOut'    : 'elastic'
                }
            );
          }else{
            $.fancybox(
                //$('#share_modal').html(),
                {
                  'href' : popContent,
                  'transitionIn'    : 'elastic',
                  'transitionOut'    : 'elastic',
                  'scrolling'     : 'no'
                }
            );
          }
          return false;
    });
    $('a.popup, .similar-recipes a').unbind().bind('click', function(){
      /* If we are deeplinked, don't do the popup, just go to the page */
      if (HERSHEYS.Kitchens.DEEP_LINKED_RECIPE) return true;


      HERSHEYS.Kitchens.doingPopup = true;

      var that = $(this);
      HERSHEYS.Kitchens.tempScrollSave = $('html,body').scrollTop();
      

      $('html').animate({scrollTop:0}, 500, "easeInOutQuad", function(){
        HERSHEYS.Kitchens.doPopup(that.attr('href'));
      });
      
        return false;

    });
    //bind star ratings to go to review tab on recipe detail
    $(".recipe-assets .rating span").unbind().bind("click",function(e){
      ratingClicked = e.target.nodeName;
      $(this).parent().parent().find(".recipe-link a").click();
    });
    $('#recipe_detail_transparency, #detail-close').bind('click', function(){
        $.cookie('iconicRecipeID', null);
      /* Fade out the wrapper and the transparency */
        $('#recipe_detail_popup_wrapper').fadeOut(500, function(){ $('#recipe_detail_popup_wrapper #recipe_detail_content').html(''); });
        $('#recipe_detail_transparency').fadeOut(500);

      /* After that, return window scroll position UNLESS the person has scrolled down the page already */
      if ($('html,body').scrollTop() == 0){  
        setTimeout(function(){
          $('html,body').animate({scrollTop:HERSHEYS.Kitchens.tempScrollSave}, 300, "easeInOutQuad");    
        }, 500);
      }

    });

    $('.submit_recipe_review').bind('click', function(){

        var _this = $(this);  

        var recipeID = $(this).attr('recipeid');

        HERSHEYS.Services.reviewRecipe({

          'recipeID'       : recipeID,
          'reviewtext'     : $('.rate_entry textarea').attr('value') || '',
          'overallrating'    : $('#rate_overall input:checked').attr('value') || 0,
          'tasterating'     : $('#rate_taste input:checked').attr('value') || 0,
          'difficultyrating'   : $('#rate_difficulty input:checked').attr('value') || 0,
          'apperancerating'  : $('#rate_appearance input:checked').attr('value') || 0,

          'success' : function(returns){
            HERSHEYS.Kitchens.Analytics.track('rateRecipe', recipeID);
            $('#tab6').hide();
            $('#tab7').show();
          },
          'failure' : function(){

            HERSHEYS.Kitchens.loginCallback = function(){
              HERSHEYS.Kitchens.doKitchensFlyout();
              _this.click();
             };

             HERSHEYS.Kitchens.doKitchensFlyout();
          }
        });

        return false;

    });
  
    $('#vote_for_recipe_link').bind('click', function(){
      
      if ($('.recipe-container').hasClass("voted") || $('.recipe-container').hasClass("great-success") || $('.recipe-container').hasClass("castingVote")) return false;
      
      var _this = $(this);
      
      if (HERSHEYS.IsLoggedIn){
        
        $('.recipe-container').addClass('castingVote');
        
        var recipeID = $(this).attr('recipeid') || 'unknown';
        
        $.ajax({
          type: "POST",
          data: $.toJSON({recipeId : recipeID , prId : CURRENT_PROMOTION_ID || 'unknown'}),
          dataType: "json",
          url: '/services/Promotions.asmx/RegisterRecipeVote',
          contentType: "application/json; charset=utf-8",
          success : function(data){
            
            webserviceReturn = data.d;

            if (webserviceReturn.status){              
              $('.recipe-container').removeClass('castingVote');
              $('.recipe-container').addClass(webserviceReturn.text);
            
              HERSHEYS.Kitchens.Analytics.track('voteForRecipe', recipeID);
            
              $('#detail-close').bind('click', function(){
                window.location.href = '/recipes/promotions/iconic-recipe/vote.aspx';
              });
              

            }else{
              alert(webserviceReturn.text);
              }
          },
          error: function(data){
            alert("There was an error submitting your request");
          }
          
        });
        
      }else{
        $.cookie('iconicRecipeID',$(this).attr('recipeid'));
        $('#leftnav_signup_link').attr('href', SITE_PREFIX + '/recipes/sign-up.aspx?ReturnUrl=/recipes/promotions/iconic-recipe/vote.aspx%3Fpvr=1');
        
        HERSHEYS.Kitchens.loginCallback = function(){
          HERSHEYS.Kitchens.doKitchensFlyout();
          _this.click();
         };
        
         HERSHEYS.Kitchens.doKitchensFlyout();
        
      }
    
      return false;
    });
};

var ratingClicked;
HERSHEYS.Kitchens.doPopup = function (which) {

    $('#recipe_detail_transparency').fadeTo("slow", 0.8);

    if ($('#recipe_detail_popup_wrapper #recipe_detail_content').html() != '') {
        $('#recipe_detail_popup_wrapper #recipe_detail_content').html('');
    }

    var re = /[id]+\=(\d+)/i;
    //if (which.indexOf('?id=') != -1) {
    if (re.test(which)) {

        var match = re.exec(which);
        var recipeID = match[1];

        /*var pieceOne = which.split('?id=');

        if (pieceOne.length === 1) return false;

        var recipeID = pieceOne[1];*/


    } else {

        var pieceOne = which.split('/recipes/');

        if (pieceOne.length === 1) return false;

        var recipeID = pieceOne[1].split('/')[0];
        //recipeID = recipeID.split('=')[1];

    }



    HERSHEYS.Kitchens.DOING_POPUP = true;


    $('#recipe_detail_popup_wrapper #recipe_detail_content').load(SITE_PREFIX + '/recipes/recipe-detail-popup.aspx?id=' + recipeID, function () {

        HERSHEYS.globalBinds();
        HERSHEYS.Kitchens.initDetailPage();

        $('#recipe_detail_popup_wrapper').fadeIn();

        if (typeof OMNITURE_RECIPE_ID == 'undefined') return true;

        HERSHEYS.Analytics.trackRecipeView({
            'recipeID': OMNITURE_RECIPE_ID,
            'associatedProducts': OMNITURE_ASSOCIATED_PRODUCTS
        });

        if (ratingClicked == "IMG") {
            $(".rating-link a").click();
            ratingClicked = "";
        }

        if ($.cookie('iconicRecipeID')) {
            $.cookie('iconicRecipeID', null);
            $('#vote_for_recipe_link').click();
        }

    });
};


$(document).ready(function () {

    var targetLocation;

    /* add return path to the left nav signup link */
    $('#leftnav_signup_link').attr('href', SITE_PREFIX + '/recipes/sign-up.aspx?ReturnUrl=' + window.location.href + '%3Fsr=1');

    /* For iconic recipe promotion, we need to set the login continuation to be the vote page */
    $('a.irs_mykitchen_link, li.irs_mykitchen_link a').bind('click', function () {

        HERSHEYS.Kitchens.loginCallback = function () { window.location.href = SITE_PREFIX + '/recipes/promotions/iconic-recipe/vote.aspx' };

        $('#leftnav_signup_link').attr('href', SITE_PREFIX + '/recipes/sign-up.aspx?ReturnUrl=/recipes/promotions/iconic-recipe/vote.aspx%3Fpur=1');

        HERSHEYS.Kitchens.doKitchensFlyout();
        return false;

    });

    /* Enable leaving notice binding */
    HERSHEYS.Utility.leavingNotice({
        'transparency': HERSHEYS.transparency,
        'title': 'HERSHEYS KITCHENS'
    });

    //$('form:first').attr('action', window.location.href);

    /* Bind login forms to ajax version */
    $('.sign-in .action .btn, .loginButtonSubmit').bind('click', function () {

        HERSHEYS.Services.login({
            'username': $('.sign-in input:eq(0)').attr('value'),
            'password': $('.sign-in input:eq(1)').attr('value'),
            'keepLoggedIn': $('.sign-in input:eq(2)').attr('checked'),

            'success': function (returns) {
                $('.sign-in span.error').remove();
                $('.sign-in .forms').fadeOut().html('<span class="success">Welcome, ' + returns['username'] + '!</span>').fadeIn();
                $('.sign-in .forgot').attr('visibility', 'hidden');

                HERSHEYS.Kitchens.Analytics.track('login');

                setTimeout(function () {
                    $('.top_login_link').html('Logout');
                    $('.loggedInFullNav').slideDown();
                    $('.loginLeftNavButton').hide();
                    HERSHEYS.Kitchens.loginCallback();
                }, 1000);
                if (targetLocation) {
                    window.location = targetLocation;
                    targetLocation = '';
                }
            },
            'failure': function () {
                $('.sign-in .inner').effect('shake', 150);
                $('.sign-in span.error').remove();
                $('.sign-in .forms').prepend('<span class="error">Incorrect Username / Password</span>');
            }
        });

        return false;
    });

    /* Bind the enter key to the submit button instead of the full form submission */
    $('.sign-in input:eq(0), .sign-in input:eq(1)').keydown(function (event) {
        if (event.keyCode == 13) {
            $('.sign-in .action .btn, .loginButtonSubmit').click();
            return false;
        }
    });


    /* BIND SHOW OF LOGIN LINKS */
    $('.mykitchen-link').bind('click', function () {

        HERSHEYS.Kitchens.doKitchensFlyout();
        return false;

    });
    $('.top_login_link').bind('click', function () {

        if ($(this).html() == 'Logout') return true;

        HERSHEYS.Kitchens.doKitchensFlyout();
        return false;

    });

    /* ADD FORM ELEMENTS FOR SEND TO FRIEND */
    $(".add").bind('click', function () {
        $(".add_friends").append("<li class='add_friend'><label for='friend_name'>Your Friend's Name:</label><input type='text' name='friend_name' class='txt med' /></li><li class='add_email'><label for='friend_email'>Your Friend's Email:</label><input type='text' name='friend_email' class='txt med' /></li>");
        $.fancybox.resize();
        return false;
    });

    /* ADD FORM ELEMENTS FOR SUBMIT RECIPE */
    $(".enter_ingredient .add").bind('click', function () {

        $('.ingredients_table').append('<tr>' + $('.ingredients_table tr:last').html() + '</tr>');

        $('.ingredients_table tr:last input').each(function (i, v) {

            var name = $(this).attr('name').split('_');
            var number = (name[1] * 1) + 1;

            $(this).attr('name', name[0] + '_' + number);

        });

        return false;
    });

    $('.close_modal').bind('click', function () {

        $('.mykitchen-link').removeClass('selected');
        $(this).parents('.my-kitchen-fly').fadeOut();

        $.cookie('iconicRecipeID', null);

        return false;
    });

    /* Invite Friends Modal Popup Binds */
    $('#addAnotherFriend').live('click', function () {

        var newRow = $('#add_friends li:last').html();
        $('#add_friends').append(newRow);
        $('#add_friends li:last input').attr('value', '');
        $.fancybox.resize();
    });

    $('#sendToFriend').live('click', function () {

        var _this = $(this);

        var names = [];
        var emails = [];
        var yourName = [];
        var yourEmail = [];

        $('#invite_friends_form .add_friends li input[name=friend_name]').each(function () {
            names.push($(this).attr('value'));
        });

        $('#invite_friends_form .add_friends li input[name=friend_email]').each(function () {
            emails.push($(this).attr('value'));
        });

        $('#invite_friends_form input[name=name]').each(function () {
            yourName.push($(this).attr('value'));
        });

        $('#invite_friends_form input[name=email]').each(function () {
            yourEmail.push($(this).attr('value'));
        });

        var emailList = emails.join(',');
        var nameList = names.join(',');
        var yourName = yourName.join(',');
        var yourEmail = yourEmail.join(',');
        var comment = $('#invite_friends_form #comment').attr('value');

        HERSHEYS.Services.inviteFriends({

            'name': yourName,
            'email': yourEmail,
            'friendName': nameList,
            'friendEmail': emailList,
            'comment': comment,

            'success': function (returns) {

                $('#invite_friends_form').hide();
                $('#invite_friends_sucess').show();
                $.fancybox.resize();

                HERSHEYS.Kitchens.Analytics.track('inviteFriends', 'complete');

            },
            'failure': function () {

                HERSHEYS.Kitchens.loginCallback = function () {
                    HERSHEYS.Kitchens.doKitchensFlyout();
                    _this.click();
                };

                HERSHEYS.Kitchens.doKitchensFlyout();
            }

        });

        return false;

    });


    $('#sendRecipeToFriend').live('click', function () {

        var _this = $(this);

        /*var names = [];
        var emails = [];
        var yourName = [];
        var yourEmail = [];
    
        $('input[name=friend_name]').each(function(){
        names.push($(this).attr('value'));
        });
  
        $('input[name=friend_email]').each(function(){
        emails.push($(this).attr('value'));
        });
  
        $('input[name=name]').each(function(){
        yourName.push($(this).attr('value'));
        });
    
        $('input[name=email]').each(function(){
        yourEmail.push($(this).attr('value'));
        });

        var emailList = emails.join(',');
        var nameList = names.join(',');
        var yourName = yourName.join(',');
        var yourEmail = yourEmail.join(',');
        var comment = $('#invite_friends_form #comment').attr('value');*/

        var yourName = $("input#yourName").val(),
      yourEmail = $("input#yourEmail").val(),
      nameList = $("input#friendName").val(),
      emailList = $("input#friendEmail").val(),
      recipeID = ($(".sharethis").attr('recipeid')) ? $(".sharethis").attr('recipeid') : 0,
      articlePath = window.location.href,
      src = 'kitchens';


        if (recipeID && recipeID != 0) {
            HERSHEYS.Services.shareRecipe({
                'name': yourName,
                'email': yourEmail,
                'friendname': nameList,
                'friendemail': emailList,
                'recipeid': recipeID,
                'src': src ? src : false,

                'success': function (returns) {

                    $('#share_recipe .modal_form').hide();
                    //$('#share_recipe .modal_form input').attr("value","");
                    $('#share_recipe .modal_success').show();
                    $.fancybox.resize();

                    HERSHEYS.Kitchens.Analytics.track('shareRecipe', 'complete');

                },
                'failure': function () {

                    HERSHEYS.Kitchens.loginCallback = function () {
                        HERSHEYS.Kitchens.doKitchensFlyout();
                        _this.click();
                    };

                    HERSHEYS.Kitchens.doKitchensFlyout();
                }

            });
            //if it doesn't have a recipe ID, use share as article
        } else if (recipeID == 0 || recipeID == "") {
            HERSHEYS.Services.shareArticle({
                'name': yourName,
                'email': yourEmail,
                'friendname': nameList,
                'friendemail': emailList,
                'articlepath': articlePath,
                //'src'  : src ? src : false,

                'success': function (returns) {

                    $('#share_recipe .modal_form').hide();
                    //$('#share_recipe .modal_form input').attr("value","");
                    $('#share_recipe .modal_success').show();
                    $.fancybox.resize();

                    HERSHEYS.Kitchens.Analytics.track('shareArticle', 'complete');

                },
                'failure': function () {

                    HERSHEYS.Kitchens.loginCallback = function () {
                        HERSHEYS.Kitchens.doKitchensFlyout();
                        _this.click();
                    };

                    HERSHEYS.Kitchens.doKitchensFlyout();
                }

            });
        }

        return false;

    });


    HERSHEYS.Kitchens.autoCompleteCallbacks = {

        recipes: {
            url: '/en/recipes/AjaxServices.ashx?method=recipeautocomplete',
            log: function (event, data, formatted) {
                return "No match!";
            },
            formatItem: function (row) {
                return "<img src='/en/recipes/Image.ashx?type=submittedphoto&id=" + row[0] + "&s=sm' class='l' style='width: 50px; margin-right: 10px' />" + "<strong>" + row[1] + "</strong>";
            },
            formatResult: function (row) {
                return row[1];
            }
        },
        tips: {
            url: '/en/recipes/AjaxServices.ashx?method=tipsautocomplete',
            log: function (event, data, formatted) {
                return "No match!";
            },
            formatItem: function (row) {
                return "<strong>" + row[1] + "</strong>";
            },
            formatResult: function (row) {
                return row[1];
            }
        }

    }

    /* Function called, inline, by fancy dropdown up top toggle recipe/tip autocomplete. Has to be inline so that fancy drop down works */
    HERSHEYS.Kitchens.swapAutoComplete = function (which) {
        $('.topSearchText').hide();
        $('.' + which + 'Autocomplete').show();
    }

    $(".search-controls input.recipeAutocomplete").autocomplete(HERSHEYS.Kitchens.autoCompleteCallbacks.recipes.url, {
        width: 224,
        selectFirst: false,
        multiple: false,
        matchContains: true,
        formatItem: HERSHEYS.Kitchens.autoCompleteCallbacks.recipes.formatItem,
        formatResult: HERSHEYS.Kitchens.autoCompleteCallbacks.recipes.formatResult
    }).result(function (event, item) {
        if (HERSHEYS.Kitchens.DEEP_LINKED_RECIPE || $('body').hasClass('iconic-recipe')) {
            window.location.href = SITE_PREFIX + '/recipes/' + item[0] + '/details.aspx';
        } else {
            var url = SITE_PREFIX + '/recipes/recipe-detail-popup.aspx?ID=' + item[0];
            $('#recipe_detail_transparency').fadeTo("slow", 0.8);

            HERSHEYS.Kitchens.DOING_POPUP = true;

            $('#recipe_detail_popup_wrapper #recipe_detail_content').load(url, function () {
                HERSHEYS.globalBinds();
                HERSHEYS.Kitchens.initDetailPage();
                $('#recipe_detail_popup_wrapper').fadeIn();
            });
        }
    });

    $(".search-controls input.tipsAutocomplete").autocomplete(HERSHEYS.Kitchens.autoCompleteCallbacks.tips.url, {
        width: 224,
        selectFirst: false,
        multiple: false,
        matchContains: true,
        formatItem: HERSHEYS.Kitchens.autoCompleteCallbacks.tips.formatItem,
        formatResult: HERSHEYS.Kitchens.autoCompleteCallbacks.tips.formatResult
    }).result(function (event, item) {
        var url = SITE_PREFIX + '/recipes/how-to/baking-tip-library.aspx?id=' + item[0];
        window.location = url;
    });


    HERSHEYS.Kitchens.initDetailPage();
    HERSHEYS.KitchensSignup.init('#kitchensSignup');

    // stylish select
    $("#filter-select").sSelect();
    $("#content .locator_wrap select").sSelect().resetSS();

    // grid rollovers
    $('.viewby-grid li,.viewby-large li').hover(function () {
        $(this).addClass('show');
    }, function () {
        $(this).removeClass('show');
    });

    // hide exclude terms in search filters
    $('.exclude_hide').bind('click', function () {
        $('.exclude').hide('slow');
        $(this).parents('.search_term').hide('blind', 400);
    });

    // show or hide search filter lists
    $('.filter_head').bind('click', function () {
        $(this).next('.filter_list').toggle('slow');
        $(this).toggleClass('close');
        return false;
    });

    // show/hide recipe/tip submit forms
    //$('.tip_form').hide();
    $('.sr').bind('click', function () {
        $('.recipe_form').show();
        $('.tip_form').hide();
    });
    $('.st').bind('click', function () {
        $('.tip_form').show();
        $('.recipe_form').hide();
    });

    // toggle tip text on my recipes page
    $('.mr_expand').bind('click', function () {
        $(this).next('.tip_text').toggleClass('open');
        $(this).toggleClass('close');
        $(this).parent('.mt_list li').toggleClass('open');
        //$('.tip_text').toggleClass('open');
        //$('.mr_expand a').toggleClass('close');
        //$('.mt_list li').toggleClass('open');
        return false;
    });


    /* Any link with "checklogin" as a class should first see if the variable holding login state is true, and if not, prompt login then continue on */
    $('.checklogin').live('click', function (e) {
        var _this = $(this);

        targetLocation = e.target;

        if (HERSHEYS.IsLoggedIn) {

        } else {
            HERSHEYS.Kitchens.loginCallback = function () {
                HERSHEYS.Kitchens.doKitchensFlyout();
                _this.click();
            };

            HERSHEYS.Kitchens.doKitchensFlyout();

            return false;
        }
    });

    /* Any link with .confirm, popup a window asking if they are sure, using the text from the title attribute */
    $('a.confirm').bind('click', function () {

        var answer = confirm($(this).attr('title'));
        if (answer) {
            return true;
        }
        else {
            return false;
        }
    });

    $('#email-link').live('click', function (e) {
        var popContent = $(this).attr("href");
        shareRecipeID = $(this).attr("recipeid");
        $(".modal_success").hide();
        $.fancybox(
        //$("#share_recipe_pop").html(),
    {
    'href': popContent,
    'autoDimensions': false,
    'width': 550,
    'height': 242,
    'onComplete': function () {
        $('#fancybox-inner #share_options').hide();
        $('#fancybox-inner #share_recipe .modal_form').show();
    }
});

        return false;

    });

    /* Analytics BINDS */

    $('#submit_tip_form .btn').live('click', function () {
        var recipeID = $('.txtRecipeId').attr('value');
        HERSHEYS.Kitchens.Analytics.track('submitTip', recipeID);
    });
    $('#submit_recipe_form .btn').live('click', function () {
        HERSHEYS.Kitchens.Analytics.track('submitRecipe', recipeID);
    });
    $('.nutrition-link a').live('click', function () {
        HERSHEYS.Kitchens.Analytics.track('nutritionalView', OMNITURE_RECIPE_ID);
    });
    $('.save_recipe_box_button').live('click', function () {
        HERSHEYS.Kitchens.Analytics.track('addNoteToRecipe');
    });
    $('.recipe_box_wrap a.remove').live('click', function () {
        var recipeID = $(this).parents('recipe_wrapper').attr('recipeid');
        HERSHEYS.Kitchens.Analytics.track('removeRecipeFromBox', recipeID);
    });
    $('.grocery_subgroup a.remove').live('click', function () {
        var recipeID = $(this).parents('recipe_wrapper').attr('recipeid');
        HERSHEYS.Kitchens.Analytics.track('removeRecipeFromGrocery', recipeID);
    });
    $('.cookie-exchange-hosting .save-link a.checklogin').live('click', function () {
        HERSHEYS.Kitchens.Analytics.track('saveToLibrary');
    });
    $('.share-links-kitchens').live('click', function () {
        HERSHEYS.Kitchens.Analytics.track('share', $(this).attr('id'));
    });
    $('#invite_friends_link').live('click', function () {
        HERSHEYS.Kitchens.Analytics.track('inviteFriends', 'start');
    });
    $('.recipe_filter_panel input:not(.go_submit)').bind('click', function () {
        var filterType = $(this).parents('.refine_wrap').attr('id').split('filter_by_')[1];
        var filterName = $(this).siblings('label:first').html();
        HERSHEYS.Kitchens.Analytics.track('recipeFilter', { type: filterType, name: filterName });
    });






});

// suckerfish functions for IE
sfHover = function () {
    var sfEls = document.getElementById("nav").getElementsByTagName("li");
    for (var i = 0; i < sfEls.length; i++) {
        sfEls[i].onmouseover = function () {
            this.className += " sfhover";
        }
        sfEls[i].onmouseout = function () {
            this.className = this.className.replace(new RegExp(" sfhover\\b"), "");
        }
    }

    $("#nav-kitchen li").bind('mouseover', function () {
        $(this).addClass('sfhover');
    }).bind('mouseout', function () {
        $(this).removeClass('sfhover');
    });

}
if (window.attachEvent) window.attachEvent("onload", sfHover);
