(function($) {

  $(document).ready(function() {
	  //Product Page Swapper
	  var productNav = $('#product-nav li a');
	  var productContent = $('#product-info > div');
	  $('#product-nav li').first().addClass('active');
	  productContent.hide().first().show();
	  
	  productNav.click(function(event) {
	    event.preventDefault();
	    
	    if ($(this).closest('li').hasClass('active')) return;
	    else {
	      $('#product-nav li').removeClass('active');
	      $(this).closest('li').addClass('active');
	      productContent.hide().filter(this.hash).show();
	    }
	  });

	  //Only run on community page
	  if ($('body').hasClass('page-community')) {
		  //Inifite Scroll for Blog
		   $('.view-Blog').infinitescroll({
		    navSelector  : "ul.pager",
		    nextSelector : "ul.pager .pager-next a:first",
		    itemSelector : ".view-Blog > .view-content",
		    loadingImg   : "http://www.infinite-scroll.com/loading.gif",
		    loadingText  : "Loading more posts...",
		    animate      : true,
		    currPage     : 0,
		    extraScrollPx: 350,
		    donetext     : "<em>You have reached the end of the posts.</em>"
		  }, function() {
		    $('.pager').css('display','block');
		    $('.view-Blog').append($('.pager'));
		  });
		  
		  // unbind normal behavior. needs to occur after normal infinite scroll setup.
      $('.view-Blog').infinitescroll('binding','unbind');

      //Update pager text
      $('ul.pager .pager-next a:first').html('Load more posts');
      //Pager click
      $('ul.pager .pager-next a:first').click(function(event) {
        event.preventDefault();
        $('.view-Blog').infinitescroll('retrieve');        
      });
	  }
	  
	  

	  // Newsletter
	  var switchFields = $('.newsletter-signup ol li input[type="text"]', '#footer');
    switchFields.each(function (i) {
    	$(this).attr('value', this.title).css('color', '#999');
    });
    switchFields.focus(function() {
    	$(this).css('color', '#000');
    	if (this.value == 'Email Address' || this.value == 'Zip Code' || this.value == '') {
    		$(this).attr('value', '');
    	}
    });
    switchFields.blur(function() {
    	if (this.value == '') {
    		$(this).attr('value', this.title).css('color', '#999');
    	}
    });    
    $('#newsletter-form').submit(function() {    
      if ($('#iiilhd-iiilhd').attr('value').match(/[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g) == null) {
        alert("Please enter a valid email address.");
        return false;
      } else if ($('#ZipCode').attr('value').match(/^\d{5}$|^\d{5}-\d{4}$/) == null) {
        alert("Please enter a valid zip code.");
        return false;
      } else {return true;}
    });
    
    
    /*****************/
    /* Dropdown Menu */
    /*****************/
    var selectedOption = $('#dropdown h2 a');
    var optionList = $('#dropdown ul li a');    
    selectedOption.click(function(event) {
        event.preventDefault();
        $(this).closest('#dropdown').toggleClass('expanded');
    });    
    optionList.click(function(event) {
        selectedOption.text($(this).text());
        $(this).closest('#dropdown').removeClass('expanded');
    });
    var ua = navigator.userAgent,
    event = (ua.match(/iPad/i) || ua.match(/iPhone/i)) ? "touchstart" : "mouseup";
    var watchPopup = function(popup) {
    $(document).bind(event, function(element) {
        if ($(element.target).parents(popup).length == 0 ) {
            $(popup).removeClass('expanded');
            }
        });
    };
    watchPopup('#dropdown');
	  

    // Comment Form 
    $('.add-review').click(function(event){
      event.preventDefault();
      if($('#comment-form-container').hasClass('show')){
        $('#comment-form-container').removeClass("show").slideUp();
      } else {
        $('#comment-form-container').addClass("show").slideDown();        
      }
    });
    
    
    // Search Form
    $('#search-block-form input#edit-search-block-form--2').focus(function(){
      if($(this).val() == "Search Recipes, Tips, and More"){
        $(this).val("");
      };
    });
    $('#search-block-form input#edit-search-block-form--2').blur(function(){
      if($(this).val() == ""){
        $(this).val("Search Recipes, Tips, and More");
      };
    });
    
    // Recipe Share Button
    $('.share-trigger').click(function(event) {
        event.preventDefault();
        $(this).closest('#recipe-share').toggleClass('sharing');
    });    
    var watchPopup2 = function(popup) {
    $(document).bind(event, function(element) {
        if ($(element.target).parents(popup).length == 0 ) {
            $(popup).removeClass('sharing');
            }
        });
    };
    watchPopup2('#recipe-share');
	 
	  //Foodservice Form
    if ($('body').hasClass('page-node-590')) {
      var foodserviceForm = $('#subForm'),
          selectRep = $('form ol li #representative'),
          salesRepName = $('input#SalesRep'),
          salesRepTitle = $('input#SalesRepTitle'),
          salesRepPhone = $('input#SalesRepPhone'),
          salesRepEmail = $('input#SalesRepEmail'),
          salesRepImage = $('input#SalesRepImage'),
          repTitle = "",
          repPhone = "",
          repEmail = "";
          
           
      selectRep.change(function() {
        var selectText = $(this).val();
        
        switch (selectText) {
          case 'Matt Hamann': 
            repTitle = 'FID Business Development & Operations Coordinator',
            repPhone = '(925) 361-4443',
            repEmail = 'matt.hamann@challengedairy.com';
            break;
          case 'Victor Gutierrez': 
            repTitle = 'Branch Manager',
            repPhone = '(323) 724-3130 x5220',
            repEmail = 'victor.gutierrez@challengedairy.com';
            break;
          case 'Tom Ditto': 
            repTitle = 'Vice President Foodservice',
            repPhone = '(925) 828-6165 x4406',
            repEmail = 'tom.ditto@challengedairy.com';
            break;
          case 'Steve Azevedo': 
            repTitle = 'Branch Manager',
            repPhone = '(831) 384-0164 x5720',
            repEmail = 'steve.azevedo@challengedairy.com';
            break;
          case 'Scott Rennie': 
            repTitle = 'District Sales Manager',
            repPhone = '(510) 351-3600 x5453',
            repEmail = 'scott.rennie@challengedairy.com';
            break;
          case 'Scott Parr': 
            repTitle = 'Branch Manager',
            repPhone = '(209) 368-2494 x5620',
            repEmail = 'scott.parr@challengedairy.com';
            break;
          case 'Richard Pittman': 
            repTitle = 'District Sales Manager',
            repPhone = '(209) 368-2494 x5628',
            repEmail = 'richard.pittman@challengedairy.com';
            break;
          case 'Mike Walz': 
            repTitle = 'District Sales Manager',
            repPhone = '(510) 351-3600 x5455',
            repEmail = 'mike.walz@challengedairy.com';
            break;
          case 'Mark Battiston': 
            repTitle = 'District Sales Manager',
            repPhone = '(323) 724-3130 x5248',
            repEmail = 'mark.battiston@challengedairy.com';
            break;
          case 'Levi Newlin': 
            repTitle = 'District Sales Manager',
            repPhone = '(510) 351-3600 x5456',
            repEmail = 'levi.newlin@challengedairy.com';
            break;
          case 'Kevin Steitz': 
            repTitle = 'Brand Manager',
            repPhone = '(559) 266-9976 x5320',
            repEmail = 'kevin.steitz@challengedairy.com';
            break;
          case 'Jon Tate': 
            repTitle = 'District Sales Manager',
            repPhone = '(619) 297-3541 x5529',
            repEmail = 'jon.tate@challengedairy.com';
            break;
          case 'Joe Ronquillo': 
            repTitle = 'District Sales Manager',
            repPhone = '(323) 724-3130 x5250',
            repEmail = 'joe.ronquillo@challengedairy.com';
            break;
          case 'Jim Proud': 
            repTitle = 'Branch Manager',
            repPhone = '(805) 648-3351 x5820',
            repEmail = 'jim.proud@challengedairy.com';
            break;
          case 'Jerry McCulloch': 
            repTitle = 'District Sales Manager',
            repPhone = '(559) 266-9976 x5322',
            repEmail = 'jerry.mcculloch@challengedairy.com';
            break;
          case 'Grant Mayfield': 
            repTitle = 'District Sales Manager',
            repPhone = '(209) 368-2494 x5625',
            repEmail = 'grant.mayfield@challengedairy.com';
            break;
          case 'Don Smith': 
            repTitle = 'District Sales Manager',
            repPhone = '(805) 648-3351 x5823',
            repEmail = 'don.smith@challengedairy.com';
            break;
          case 'Dennis Albrecht': 
            repTitle = 'District Sales Manager',
            repPhone = '(619) 297-3541 x5524',
            repEmail = 'dennis.albrecht@challengedairy.com';
            break;
          case 'Dave Clare': 
            repTitle = 'Branch Manager',
            repPhone = '(510) 351-3600 x5420',
            repEmail = 'dave.clare@challengedairy.com';
            break;
          case 'Dan Argott': 
            repTitle = 'District Sales Manager',
            repPhone = '(323) 724-3130 x5247',
            repEmail = 'dan.argott@challengedairy.com';
            break;
          case 'Craig Terpening': 
            repTitle = 'Branch Manager',
            repPhone = '(805) 928-4470 x6420',
            repEmail = 'craig.terpening@challengedairy.com';
            break;
          case 'Chuck Beaty': 
            repTitle = 'Corp. Foodservice Sales Manager',
            repPhone = '(925) 828-6165 x4441',
            repEmail = 'chuck.beaty@challengedairy.com';
            break;
          case 'Brian Terrell': 
            repTitle = 'District Sales Manager',
            repPhone = '(323) 724-3130 x 5251',
            repEmail = 'brian.terrell@challengedairy.com';
            break;
          case 'Brian Beebe': 
            repTitle = 'District Sales Manager',
            repPhone = '(619) 297-3541 x5525',
            repEmail = 'brian.beebe@challengedairy.com';
            break;
          case 'Art Prendiz': 
            repTitle = 'Branch Manager',
            repPhone = '(619) 297-3541 x5520',
            repEmail = 'art.prendiz@challengedairy.com';
            break;
          case 'Anthony Cendejas': 
            repTitle = 'District Sales Manager',
            repPhone = '(323) 724-3130 x5249',
            repEmail = 'anthony.cendejas@challengedairy.com';
            break;
          default:
            repTitle = 'Vice President Foodservice',
            repPhone = '(925) 828-6165 x4406',
            repEmail = 'tom.ditto@challengedairy.com';
            break;
        }
        
        if (selectText == "") {
          selectText = "Tom Ditto";
        }
        
        salesRepName.val(selectText);
        salesRepTitle.val(repTitle);
        salesRepPhone.val(repPhone);
        salesRepEmail.val(repEmail);
        salesRepImage.val(selectText.toLowerCase().replace(' ', '-'));
        
      });
      
      foodserviceForm.submit(function() {    
        if ($('#name').val() == "") {
          alert("Please enter your full name.");
          return false;
        } else if ($('#okjmj-okjmj').attr('value').match(/[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g) == null) {
          alert("Please enter a valid email address.");
          return false;
        } else if ($('#ParentCustomer').val() == "") {
          alert("Please enter your company.");
          return false;
        } else if ($('#JobTitle').val() == "") {
          alert("Please enter your job title.");
          return false;
        } else if ($('#SalesRep').val() == "") {
          alert("Please select your representative.");
          return false;
        } else {return true;}
      });
    }
  
  });
  
  $(window).load(function() {
    //Only run on the recipe page
	  if ($('body').hasClass('page-node-280') || $('body').hasClass('front')) {
	    //Process noscript images
      $('noscript[data-large]').each(function(){
        if (screen.width > 480) {
          var tag = $(this);
          $('<a>', {href: tag.data('link')}).html($('<img>', {src: tag.data('large'), alt: tag.data('alt')})).insertAfter(tag);
        }
      });

	  
	    $('.flexslider').flexslider({
	      animation: ('ontouchstart' in document.documentElement) ? "slide" : "fade",
	      animationDuration: ('ontouchstart' in document.documentElement) ? 300 : 800,
        controlsContainer: '#slider-nav-container',
        animationLoop: true,
        start: function(slider) {
          slider.removeClass('loading');
          spinner.stop();
        }
      });
	  }
  });
  
})(jQuery);
