// Copyright Acro Media Inc. 1998-2010, www.acromediainc.com

if (jQuery.browser.msie) {
  try {
    document.execCommand("BackgroundImageCache", false, true);
  } catch(err) {}
}

/**
 * Handler for the form redirection error.
 * 
 * Over riding this function because:
 * If a user clicks on a AHAH element and interupts that process by clicking something else a menu item etc..
 * the stock ahah.prototype.error function just blindly throws an error regardless of its status code. 
 * 
 */
Drupal.ahah.prototype.error = function (response, uri) {
  if(response.status == 200){
	  alert(Drupal.ahahError(response, uri));
  }
  
  // Resore the previous action and target to the form.
  $(this.element).parent('form').attr( { action: this.form_action, target: this.form_target} );
  // Remove the progress element.
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  if (this.progress.object) {
    this.progress.object.stopMonitoring();
  }
  // Undo hide.
  $(this.wrapper).show();
  // Re-enable the element.
  $(this.element).removeClass('progess-disabled').attr('disabled', false);
};

$(function() {
  
 //Copyright Year 
 $('#insertYear').html(new Date().getFullYear());
 
 // external links
 $("a[rel='external']").attr('target', '_blank');
 
 // add hover classes to elements for ie6 styling
 $('input:submit, .frontPageCTA .field-tagline, .bPrev, .bNext').mouseover( function() {
    $(this).addClass('hover');
  }).mouseout( function() {
    $(this).removeClass('hover');
  });
  
  // printer link on product pages  
  $('#printer_link').click( function() {
    url = location.href;
    if(url.indexOf('map') > -1 && url.indexOf('product') > -1){
      $(this).href('#');
      window.print();
      return false;
    }  
  });
  
  // navigation tabs on recipe pages
  $('.recipeInfoWindow .rTab').click( function() {
    $('.recipeInfoWindow.active').removeClass('active');

    $(this).parent().addClass('active');
  }).hover( function() {
    $(this).addClass('hover');
  }, function() {
    $(this).removeClass('hover');
  }); 
  
  // recipe pages    
  $('.rSubContent .rTitle').click( function() {
    $(this).parent().toggleClass('expanded');
  }).hover( function() {
    $(this).addClass('hover');
  }, function() {
    $(this).removeClass('hover');
  });
  
  // great pairings "last" node
  $('#rGreatPairings .rContent .node:last, #productPairings .pContent .node:last').addClass('last');
  
  
  // drupal edit tabs
  $('ul.tabs li').hover( function() {
    $(this).addClass('hover');
  }, function() {
    $(this).removeClass('hover');
  });
  
  // email to a friend form  
  initializeSendPageForm();
  $('.email_a_friend').click( function() {
    $('#send_page_popup').show();
    $(this).removeClass('hover');
  }).hover( function() {
    $(this).addClass('hover');
  }, function() {
    $(this).removeClass('hover');
  });
  
  //Email to Friend Position
  if ($('.email_a_friend').length > 0) {
	  var top = $('.email_a_friend').offset().top;
	  $('#send_page_popup').css('top', top);
	  if ($.browser.msie && $.browser.version.substring(0,1) === '6') {
		  $('#send_page_popup').bgiframe();
	  }
	  if ($.browser.opera) {
		  $('#send_page_popup').css('width', '245px');
		  $('#send_page_form_container').css('padding', '25px 5px 5px 5px');
	  }    
  }
  
  // Hides and shows glossary term listings
  $('.glossary-link').click( function() {
    $(this).parent().parent().toggleClass('active');
    $(this).parent().siblings('div.glossary-expandible').slideToggle("fast");
    return false;
  });
  
  // IE z-index fix for backend fieldsets
  if($.browser.msie){
    if($('#colLeft fieldset').length > 0){
      $('#colLeft fieldset').livequery(function() {
        var indexnumber = 10000;
          $('#colLeft fieldset').each(function() {
          if (indexnumber >= 1) {
            $(this).css("z-index",  indexnumber);
            indexnumber -= 1;
          }
        });
      });
    }
  }

  //Opera SKU Fix
  if ($.browser.opera) {
    $('#edit-product-sku-upc').addClass('operaFix');
  }

  //Print Page Fix
	$('#printer_link, .Agents_SuppliersWebsite a').attr("target", "_blank")

  // switch the z-index of the left and right columns when the search box is in focus
  $('#keyword_fullsite').focus(function() {
    $('#colLeft').css('z-index', '10');
    $('#colRight').css('z-index', '11');
  });
  
  $('#keyword_fullsite').blur(function() {
      $('#colLeft').css('z-index', '11');
      $('#colRight').css('z-index', '10');
  });    
  
});

//When focus is set on the search box remove the text
site_wide_search_initialize = function(){
  var defaultText = 'Enter keyword, SKU or UPC';
  var clear_search_example = function(){
    var element = $(this).find('#keyword_fullsite');
    if(element.val() == defaultText){
      element.val('');
    }
  }

  var clear_search_example_focus = function(){
    if($(this).val() == defaultText){
      $(this).val('');
      $(this).removeClass('defaultText');
    }
  }
    
  var clear_search_example_blur = function() {
    if($(this).val() == ''){
      $(this).val(defaultText);
      $(this).addClass('defaultText');
    }
  }

  $('#bcls-search-form .form-item #keyword_fullsite').focus(clear_search_example_focus).blur(clear_search_example_blur);
}


//loops through the form elements and determines if "clear search" needs to be there.
clear_search = function(){
	  var clear_select = false;
	  var clear_search = false;
	  var clear_check = false;
	  var clear_per_page = false;
	  var clear_sort = false;
	  var clear_views = false;
	  
	  $('#clear_search').hide();
	  //loop through all select lists on the form, if anything is selected, show clear search  
	  $('#bcls-catalog-filters-form select').each( function() {		  
		  if($(this).val() != "all" && $(this).attr('name') != 'sort results by' && $(this).attr('name') != 'results per page'){
			  clear_select = true;
		  }
	  });
	  
	  //loop around checkboxes
	  $('#bcls-catalog-filters-form input').each( function() {
		  if($(this).attr('type') == "checkbox"){			  
			  if($(this).attr('checked') == true){
				  clear_check = true;
			  }
		  }
	  });
	  
	  //check sort by results drop down
	  if($('#product-catalogue-results-header #sortResults select').val() != "1"){
		  clear_sort = true;
	  }
		
	  //check sort per page drop down
	  if($('#product-catalogue-results-header #sortPerPage select').val() != "20"){
		  clear_per_page = true;
	  }
	  
	  //check view
	  if($('#bcls-catalog-filters-form').length){
		  var list = $('#productCatalogueViews #edit-list-view').attr('class');
		  if(list.indexOf('active') == -1){		  
			  clear_views = true;
		  }
	  }
	  
	  //check keyword field
	  if($('#keyword_fullsite').val() != "Enter keyword, SKU or UPC"){
		  clear_search = true;
	  }  
	  
	  if(clear_search || clear_select || clear_check || clear_per_page || clear_sort || clear_views){
		  $('#clear_search').show();
	  }
}

//searches the provided url for the keyword and send it back, or returns nothing
//stores the keyword in the full site keyword text field
get_keyword_from_url = function(url){	
  var keyword = "";
  if(url.indexOf('#') >= 0 || url.indexOf('?') >= 0){		
	var short_url = url.substr(url.indexOf('?') + 1);
	if(url.indexOf('#') >= 0){		  
		short_url = url.substr(url.indexOf('#') + 1);
	}	  
	var data_set = short_url.split("&");
	var comma = "";	  
	for(var i=0; i<data_set.length; i++){
	  var values = data_set[i].split("=");
	  if((values[0] == 'keyword' || values[0] == 'filter0' || values[0] == 'keys') && (values[1] != '')){
		keyword = decodeURIComponent(values[1]);
	  }
	}	
  }
  
  //sets the keyword if found
  if(keyword != ''){
    $('#keyword_fullsite').val(keyword);
    $('#keyword_fullsite').removeClass('defaultText');
  }    
  
  return keyword
}

//initialization functions for the site wide search
$(function() {
  site_wide_search_initialize();	
  checkSearchRadios();
  
  //if a keyword is provided in the URL, populate the site search input with it
  var url = decodeURIComponent(location.href);
  get_keyword_from_url(url);
  url = '';

  //needs to be placed here, after the keyword has been placed into the full site keyword search box.
  clear_search();  
  
  //when the users changes the site wide drop down, set a cookie
  $.cookie("search_for_value", 'product');
  $('#search_by_type').change(function(){
	var search_for_value = $('#search_by_type').val();
	$.cookie("search_for_value", search_for_value);
	checkSearchRadios();
    return false;
  });
  
  //on the product catalogue page, we don't want to resubmit the page, so we use ahah
  $('#bcls-search-form').submit(function(){
	  url = location.href;
	  var query = '';
	  //if the user is on the product page, use AHAH to submit the form
	  if(url.indexOf('product-catalogue') > -1 && $('#search_by_type').val() == 'product'){		  
		  if($('#keyword_fullsite').val() == "Enter keyword, SKU or UPC"){
			  $('#edit-keyword').val('');
		  }
		  else{
			  $('#edit-keyword').val($('#keyword_fullsite').val());  
		  }
		  
		  if($('#edit-product-sku-upc').is(':checked')){
			  get_sku_upc($('#keyword_fullsite').val());
		  }
		  else{
			  $('#edit-type').change();
		  }
		  return false;
	  }
	  return true;
  });
});


/** calls php function to determine if sku exists
*/
function get_sku_upc(keyword){
  request = $.ajax({
    type: "POST",
    url: '/product-catalogue/get_sku_upc',
    dataType: "html",
    data: 'keyword=' + keyword,
    success: function(data){
      request = null;
	  if(data.indexOf('found_sku') > -1){
		var nid = data.substring(data.indexOf(':nid(') + 5);				
		var url = 'http://' + window.location.hostname + '/node/' + nid;
		window.location = url;	
	  }
	  else{
		$('#product-catalogue-results').empty();
		$('#product-catalogue-results').append(data);
	  }
  	}
  });
}

// when a letter is clicked, if there is no text in the text field, reset the filter0 to = ''
$( function() {
  $('.glossary-characters a').click(function(){
    var button = $(this);
    var href = button.attr('href');
    if(button[0].innerHTML != "*" && $('.content .view-glossary .view-filters .form-text').val() == ''){
      var newURL = 'beverage-terms?filter0=&filter1=' + button[0].innerHTML;
      window.location = newURL;
      return false;
    }
  });
});


switchedToMapView = false;
// Store Node
$( function() {
  $('.storeInfoWindow .sTab').click( function() {
    $('.storeInfoWindow.active').removeClass('active');

    $(this).parent().addClass('active');
  }).hover( function() {
    $(this).addClass('hover');
  }, function() {
    $(this).removeClass('hover');
  });

  $('#storeStoreLocator .sTab').click( function() {
  if(!switchedToMapView){
      storeLocatorManager.switchToMapView();
      switchedToMapView = true;
  }
  });
});

// Send Page stuff
initializeSendPageForm = function() {
  $('#send-page-form').submit(submitSendPage);
  $('.send_page_close').click( function() {
    $('#send_page_popup').hide();
    $('#send_page_messages').hide();
  }).hover( function() {
    $(this).addClass('hover');
  }, function() {
    $(this).removeClass('hover');
  });
};

submitSendPage = function() {
  var formArguments = {
    send_page_mail_subject :$("#edit-send-page-mail-subject").val(),
    send_page_mail_from :$("#edit-send-page-mail-from").val(),
    send_page_mail_from_name :$("#edit-send-page-mail-from-name").val(),
    send_page_mail_to :$("#edit-send-page-mail-to").val(),
    send_page_mail_body :$("#edit-send-page-mail-body").val(),
    form_id :$("#edit-send-page-form").val(),
    send_page_title :$("#edit-send-page-title").val(),
    send_page_path :$("#edit-send-page-path").val()
  };
  
  sendPage(formArguments);
 
  return false;
}

request = null;
sendPage = function(serializedForm){
	request = $.ajax({
		type: "POST",
		url: "/send_page",
		data: serializedForm,
		dataType: "html",
		success: function(data){
			request = null;
			$('#send_page_form_container').empty();
			$('#send_page_form_container').append(data);
			initializeSendPageForm();
			closeWindow();
		}
	});
};

closeWindow = function() {
  setTimeout("resetSendPageForm()", 3000);
}


resetSendPageForm = function() {
  $('#send_page_popup').hide();
  $('#send_page_messages').hide();
  
  return false;
}

// Determines whether the SKU checkbox, food/product radios, or nothing, should be displayed in the search box
function checkSearchRadios() {
  skuBox = $('#bcls-search-form #edit-product-sku-upc').parent().parent();
  recipeRadios = $('#bcls-search-form input[type=radio]').parent().parent().parent();  
  
  if($('#search_by_type').val() == 'product'){
    $(recipeRadios).hide();
    $(skuBox).show();
  }
  else if($('#search_by_type').val() == 'recipe'){
    $(skuBox).hide();
    $(recipeRadios).show();
  }
  else{
    $(skuBox).hide();
    $(recipeRadios).hide();
  }
}

// Homepage CTA arrows
$(function(){
	$('#homeContentArea .views-field-field-front-cta-tagline-value a').append("<img src='/sites/all/themes/bcliquor/graphics/arrow_red.gif' width='8' height='7' alt='' />");
});

// Taste magazine text replacement
$(function(){
	$('.taste-archive-listings .views-field-field-taste-magazine-pdf-fid a').text("PDF");
});

// FAQ Mods
$(function(){
	
	var i = 1;
	$('.faq-question-answer').each(function(){
		$(this).before('<div class="faq-question-number">' + i + '</div>');
		i++;
	});
	
	// Add Q: Beside each question
	$('<span>Q:</span>').prependTo('.faq-question a');
	
	// Add A: beside each answer
	$('.faq-answer p:first-child').each(function() {
		$(this).prepend('<span>A:</span>');
	});
	
	//on click, add a class, loop through other FAQ's and remove that class first tho
	$(".faq-question a").click(function(){
		var $this = $(this);
		if( $this.is('.open') ) {			
			$('.faq-question a').each(function() {
				if($('.faq-question a').hasClass('open')){
					$('.faq-question a').removeClass('open');
				}
			});
			$this.removeClass('open');
		}
		else {					
			$('.faq-question a').each(function() {
				if($('.faq-question a').hasClass('open')){
					$('.faq-question a').removeClass('open');
				}
			});
			$this.addClass('open');
		}
	});
});

// Taste Sliders
$(document).ready(function() {
	
	//Consultants Choice Slider
	$("#consultants_choice .item-list").scrollable({
		globalNav: true,
		next: "#consultants_choice .bNext",
		prev: "#consultants_choice .bPrev"
	});
	
	//Product Slider
	$("#taste_product_queue .item-list").scrollable({
		globalNav: true,
		next: "#taste_product_queue .bNext",
		prev: "#taste_product_queue .bPrev"
	});
	
	//Drink Slider
	$("#taste_featured_cocktails .item-list").scrollable({
		globalNav: true,
		next: "#taste_featured_cocktails .bNext",
		prev: "#taste_featured_cocktails .bPrev"
	});
	
	//Drink Slider
	$("#tasteHomepageBannersCont .item-list").scrollable({ circular: true }).autoscroll({ interval: 5000 });

});

// Combine Recipe Stuff
$(document).ready(function() {
	$('#taste_featured_recipes .view-nodequeue-2 .views-row').each(function() {
		$(this).find('.views-field-title, .views-field-field-cooking-time-value, .views-field-field-recipe-serving-size-value, .views-field-body, .views-field-view-node').wrapAll("<div class=\"recipeContent\" />");
		$(this).find('.views-field-title-1, .views-field-field-image-cache-fid').wrapAll("<div class=\"recipePairing\" />");
	});
});

// Consultant Stuff
$(document).ready(function() {
	
	//Consultants Choice Slider
	$("#consultants_choice .item-list").scrollable({
		globalNav: true,
		next: "#consultants_choice .bNext",
		prev: "#consultants_choice .bPrev"
	});
	
	//Combine Consultants Choice Product Info
	$('.view-taste-magazine-consultant-choice .views-row').each(function() {
		$(this).find('.views-field-price, .views-field-stock-number, .views-field-country-name').wrapAll("<div class=\"consultantProductInfo\" />");
	});
	
	//Combine fields into div container
	$('#meetConsultantsCont .views-row').each(function() {
		$(this).find('.views-field-field-consultant-profile-image-fid, .views-field-title-1, .views-field-title, .views-field-body, .views-field-field-consultant-wset-level-value').wrapAll("<div class=\"consultantPopCont\" />");
	});
	
	// Popup Container
	$("#meetConsultantsCont .views-row .consultantPopCont").prepend("<a href='#' class='closeBtn'>Close</a>");
	$('#meetConsultantsCont .views-row').each(function() {
		var that =  $(this);
		$(that).find('.views-field-title-2 .field-content').hover(function() {
      
      // close any existing popups
      $('#meetConsultantsCont .views-row .consultantPopCont.open').fadeOut('normal');
      $('#meetConsultantsCont .views-row .consultantPopCont.open').removeClass('open');
      
			$(that).find('.consultantPopCont').fadeIn('normal');
			$(that).find('.consultantPopCont').addClass('open')
			return false;	
		});
		// Close Container
		$(that).find(".closeBtn").click(function() {
			$(that).find(".consultantPopCont").fadeOut('normal');
			$(that).find('.consultantPopCont').removeClass('open')
			return false;
		});
	});
	
});

//Perfect Pairings
function pairingRecommend() {
	
	//Perfect Pairings Slider
	$("#pairingRecommendCont .item-list").scrollable({
		globalNav: true,
		next: "#pairingRecommendCont .bNext",
		prev: "#pairingRecommendCont .bPrev"
	});
		
	
};

//Tabs
$(document).ready(function() {
	$("#tabsCont").tabs("#panelsCont > div");
});

//Previous Issues
$(document).ready(function() {
	Cufon.replace('.tasteYearCont h3, .tasteYearCont .views-field-title');
	$('.tasteYearCont:first .tasteIssuesCont').css('display', 'block');
	$('.tasteYearCont:first .teasteYearBtn').addClass('open');
	$('.tasteYearCont').each(function() {
		$(this).find('.teasteYearBtn').click(function() {
			$(this).parent().find('.tasteIssuesCont').toggle('normal');
			var $this = $(this);
			if( $(this).is('.open') ) {
				$this.removeClass('open');
			}
			else {
				$this.addClass('open');
			}
			return false;
		});
	});
});

//Ask Expert
$(document).ready(function() {
	$('#askExpertRecentQuestions .views-row').each(function() {
		var that =  $(this);
		$(that).find('.views-field-title a').click(function() {
			$(that).find('.views-field-body').toggle('normal');
			return false;
		});
	});
});


//IE Z-index 
$(function() {
	var zIndexNumber = 100;
	$('#meetConsultantsCont .expanderCont').each(function() {
		$(this).css('zIndex', zIndexNumber);
		zIndexNumber -= 1;
	});
	if($.browser.msie && $.browser.version=="6.0") {
		$('#meetConsultantsCont').css("padding-bottom", "120");
	}
});

//Slide Show Functions for Taste Homepage CTA
function slideShow() {
	//Set the opacity of all images to 0
	$('#tasteSlides a').css({opacity: 0.0});
	 
	//Get the first image and display it (set it to full opacity)
	$('#tasteSlides a:first').animate({opacity: 1}, 500);
	 
	//Set the caption background to semi-transparent
	$('#tasteSlides .caption').css({opacity: 1});

	//Resize the width of the caption according to the image width
	$('#tasteSlides .caption').css({width: $('#tasteSlides a').find('img').css('width')});
	 
	$('#tasteSlides .content').html($('#tasteSlides a:first').find('img').attr('rel')).animate({opacity: 1}, 500);
	Cufon.replace('.caption h3');
	setInterval('tasteSlides()', 7000);
}

function tasteSlides() {
	//if no IMGs have the show class, grab the first image
	var current = ($('#tasteSlides a.show')?  $('#tasteSlides a.show') : $('#tasteSlides a:first'));

	//Get next image, if it reached the end of the slideshow, rotate it back to the first image
	var next = ((current.next().length) ? ((current.next().hasClass('caption'))? $('#tasteSlides a:first') :current.next()) : $('#tasteSlides a:first'));   
	 
	//Get next image caption
	var caption = next.find('img').attr('rel'); 
	 
	//Set the fade in effect for the next image, show class has higher z-index
	next.css({opacity: 0.0})
	.addClass('show')
	.animate({opacity: 1.0}, 1000);

	//Hide the current image
	current.animate({opacity: 0.0}, 1000)
	.removeClass('show');
	 
	//Set the opacity to 0 and height to 1px
	$('#tasteSlides .caption').animate({opacity: 0 }, { queue:false, duration:500 }).animate({opacity: 0}, { queue:true, duration:500, complete: function() { $('#tasteSlides .content').html(caption); Cufon.replace('.caption h3'); } });
	
	//Animate the caption, opacity to 1 and heigth to 3px
	$('#tasteSlides .caption').animate({opacity: 1},500 ).animate({opacity: 1},500 );
	
}

function closeTip(nid){
	$("#tooltip"+nid).hide();
	$("#allUPCS"+nid).toggleClass('active');
}

function openTip(nid){
	var button = $("#allUPCS"+nid);
	var tip = $("#tooltip"+nid);

	if(tip.is(":visible")){
		closeTip(nid)
	}
	else{
		$(tip).css('position', 'absolute');

		var position = $(button).position();
		var top = position.top - ($(tip).height() / 2);
		var left = position.left + 15;

		$(tip).css('top', top);
		$(tip).css('left', left);

		$(tip).show();
		$(button).toggleClass('active');
	}
}

$(function(){
	$('body').click(function(event) {
		if (!$(event.target).closest('.tooltip, .allUPCSButton').length) {
			$(".tooltip").hide();
			$(".allUPCSButton").removeClass('active');
		}
	});
});

function tastingNotes(nid){
	$("#tastingNote"+nid).slideToggle();
	$("#tasteArrow"+nid).toggle();
}
