
function logBookmark(page, site, url) {
	var data = { page: page, site: site };
	$.post("/bookmarks/log.htm", data);
	window.open(url);
	return false;
}

function updateUniqueName() {
	var firstName = document.getElementById('firstName').value;
	var lastName = document.getElementById('lastName').value;
	var urlStringField = document.getElementById('urlString');
	
	var recommendedUniqueName = firstName + '-' + lastName;
	
	urlStringField.value = recommendedUniqueName;
}

var countdownTimer;

function updateDeliveryCountdown() {
	var spanElement = document.getElementById('deliveryCountdownTimer');
	
	if (spanElement == null) {
		return;
	}
	
	var timer = spanElement.innerHTML.split(":");
	var hours = parseInt(timer[0]);
	var minutes = parseInt(removeLeadingZeros(timer[1]));
	var seconds = parseInt(removeLeadingZeros(timer[2]));
	
	if (hours == 0 && minutes == 0 && seconds == 0) {
		if (countdownTimer != undefined) {
			clearInterval(countdownTimer);
			return;
		}
	}
	seconds -= 1;
	if (seconds < 0) {
		seconds = 59
		minutes -= 1;
		if (minutes < 0) {
			minutes = 59
			hours -= 1;
		}
	}
	seconds = prependZero(seconds);
	minutes = prependZero(minutes);
	
	spanElement.innerHTML = hours + ":" + minutes + ":" + seconds;
	
	if (countdownTimer == undefined) {
		countdownTimer = setInterval('updateDeliveryCountdown()', 1000);
		return;
	}
	
	/*
	 * Remove leading zeros
	 */
	function removeLeadingZeros(i) {
		while (i.length > 1 && i.charAt(0) == "0") {
			i = i.substring(1, i.length);
		}
		return i;
	}
	
	/*
	 * Add a zero in front of numbers less than 10
	 */
	function prependZero(i) {
		if (i < 10) {
			i = "0" + i;
		}
		return i;
	}
}

/*
 * Facebox (for jQuery)
 * version: 1.2 (05/05/2008)
 * @requires jQuery v1.2 or later
 *
 * Examples at http://famspam.com/facebox/
 *
 * Licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
 *
 * Usage:
 *  
 *  jQuery(document).ready(function() {
 *    jQuery('a[rel*=facebox]').facebox() 
 *  })
 *
 *  <a href="#terms" rel="facebox">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="facebox">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="facebox">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 * 
 *    jQuery.facebox('some html')
 *
 *  The above will open a facebox with "some html" as the content.
 *    
 *    jQuery.facebox(function($) { 
 *      $.get('blah.html', function(data) { $.facebox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The facebox function can also display an ajax page or image:
 *  
 *    jQuery.facebox({ ajax: 'remote.html' })
 *    jQuery.facebox({ image: 'dude.jpg' })
 *
 *  Want to close the facebox?  Trigger the 'close.facebox' document event:
 *
 *    jQuery(document).trigger('close.facebox')
 *
 *  Facebox also has a bunch of other hooks:
 *
 *    loading.facebox
 *    beforeReveal.facebox
 *    reveal.facebox (aliased as 'afterReveal.facebox')
 *    init.facebox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
 *
 */
(function($) {
  $.facebox = function(data, klass) {
    $.facebox.loading()

    if (data.ajax) fillFaceboxFromAjax(data.ajax)
    else if (data.image) fillFaceboxFromImage(data.image)
    else if (data.div) fillFaceboxFromHref(data.div)
    else if ($.isFunction(data)) data.call($)
    else $.facebox.reveal(data, klass)
  }

  /*
   * Public, $.facebox methods
   */

  $.extend($.facebox, {
    settings: {
      opacity      : 0,
      overlay      : true,
      loadingImage : '',
      closeImage   : '',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      faceboxHtml  : '\
    <div id="facebox" style="display:none;"> \
      <div class="popup2"> \
        <table> \
          <tbody> \
            <tr> \
              <td class="ftl"/><td class="fb"/><td class="ftr"/> \
            </tr> \
            <tr> \
              <td class="fb"/> \
              <td class="body"> \
                <div class="content"> \
                </div> \
                <div class="footer"> \
                  <a href="#" class="close"> \
                    <img src="/media/images/81724-closelabel.gif" /> \
                  </a> \
                </div> \
              </td> \
              <td class="fb"/> \
            </tr> \
            <tr> \
              <td class="fbl"/><td class="fb"/><td class="fbr"/> \
            </tr> \
          </tbody> \
        </table> \
      </div> \
    </div>'
    },

    loading: function() {
      init()
      if ($('#facebox .loading').length == 1) return true
      showOverlay()

      $('#facebox .content').empty()
      $('#facebox .body').children().hide().end().
        append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>')

      $('#facebox').css({
        top:	getPageScroll()[1] + (getPageHeight() / 3),
        left:	385.5
      }).show()

      $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27) $.facebox.close()
        return true
      })
      $(document).trigger('loading.facebox')
    },
    
    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.facebox')
      if (klass) $('#facebox .content').addClass(klass)
      $('#facebox .content').append(data)
      $('#facebox .loading').remove()
      $('#facebox .body').children().fadeIn('normal')
      $('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 3))
      $(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
    },

    close: function() {
      $(document).trigger('close.facebox')
      return false
    
    }
  })
  $.fn.facebox = function(settings) {
    init(settings)

    function clickHandler() {
      $.facebox.loading(true)

      // support for rel="facebox.inline_popup" syntax, to add a class
      // also supports deprecated "facebox[.inline_popup]" syntax
      var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillFaceboxFromHref(this.href, klass)
      return false
    }

    return this.click(clickHandler)
  }
  function init(settings) {
    if ($.facebox.settings.inited) return true
    else $.facebox.settings.inited = true

    $(document).trigger('init.facebox')
    makeCompatible()

    var imageTypes = $.facebox.settings.imageTypes.join('|')
    $.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

    if (settings) $.extend($.facebox.settings, settings)
    $('body').append($.facebox.settings.faceboxHtml)

    var preload = [ new Image(), new Image() ]
    preload[0].src = $.facebox.settings.closeImage
    preload[1].src = $.facebox.settings.loadingImage

    $('#facebox').find('.fb:first, .fbl, .fbr, .ftl, .ftr').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#facebox .close').click($.facebox.close)
    $('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
  }
  
  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;	
    }
    return new Array(xScroll,yScroll) 
  }

  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }	
    return windowHeight
  }

  // Backwards compatibility
  function makeCompatible() {
    var $s = $.facebox.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      $.facebox.reveal($(target).clone().show(), klass)

    // image
    } else if (href.match($.facebox.settings.imageTypesRegexp)) {
      fillFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillFaceboxFromAjax(href, klass)
    }
  }

  function fillFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }

  function fillFaceboxFromAjax(href, klass) {
    $.get(href, function(data) { $.facebox.reveal(data, klass) })
  }

  function skipOverlay() {
    return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null 
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('facebox_overlay').length == 0) 
      $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')

    $('#facebox_overlay').hide().addClass("facebox_overlayBG")
      .css('opacity', $.facebox.settings.opacity)
      .click(function() { $(document).trigger('close.facebox') })
      .fadeIn(200)
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#facebox_overlay').fadeOut(200, function(){
      $("#facebox_overlay").removeClass("facebox_overlayBG")
      $("#facebox_overlay").addClass("facebox_hide") 
      $("#facebox_overlay").remove()
    })
    
    return false
  }
$(document).bind('close.facebox', function() {
    $(document).unbind('keydown.facebox')
    $('#facebox').fadeOut(function() {
      $('#facebox .content').removeClass().addClass('content')
      hideOverlay()
      $('#facebox .loading').remove()
    })
  })
})(jQuery);
function followCustomer(customerId, followCustomerRequest) {
	$.post('/taster/follow_customer.htm', { customerId: customerId, returnTo: followCustomerRequest }, function() {
		$('#info').parent().load(followCustomerRequest);
	});
}
function unfollowCustomer(customerId, followCustomerRequest) {
	$.post('/taster/unfollow_customer.htm', { customerId: customerId }, function() {
		$('#info').parent().load(followCustomerRequest);
	});
}

function newFollowCustomer(customerId, followCustomerRequest) {
	$.post('/taster/follow_customer.htm', { customerId: customerId, returnTo: followCustomerRequest }, function() {
		$('.followStatus').load();
	});
}
function newUnfollowCustomer(customerId, followCustomerRequest) {
	$.post('/taster/unfollow_customer.htm', { customerId: customerId }, function() {
		$('.followStatus').load();
	});
}

var expiryTimer;

function reminderCountdown() {
	
	var spanElement = document.getElementById('reminderCounter');
	
	if (spanElement == null) {
		
		return;
	}
	
	var timer = spanElement.innerHTML.split(":");
	
	var days = parseInt(timer[0]);
	var hours = parseInt(timer[1]); 
	var minutes = parseInt(removeLeadingZeros(timer[2]));
	var seconds = parseInt(removeLeadingZeros(timer[3]));
	var milliseconds = parseInt(removeLeadingZeros(timer[4]));
	
	if (days == 0 && hours == 0 && minutes == 0 && seconds == 0 && milliseconds == 0) {
		if (expiryTimer != undefined) {
			
			clearInterval(expiryTimer);
			return;
		}
	}
	
	milliseconds -= 1;
	if (milliseconds < 0) {
		milliseconds = 9;
		seconds -= 1;
		if (seconds < 0) {
			seconds = 59;
			minutes -= 1;
			if (minutes < 0) {
				minutes = 59;
				if (hours = 0) {
					hours = 23;
				}
				else {
					hours -= 1;
				}
				
			}
		}
	}
//	milliseconds = prependZero(milliseconds,100, "00");
	seconds = prependZero(seconds,10, "0");
	minutes = prependZero(minutes,10, "0");
	
	spanElement.innerHTML = days + ":" + hours + ":" + minutes + ":" + seconds + ":" + milliseconds;
	
	if (expiryTimer == undefined) {
		
		expiryTimer = setInterval('reminderCountdown()', 100);
		return;
	}
	function removeLeadingZeros(i) {
		while (i.length > 1 && i.charAt(0) == "0") {
			i = i.substring(1, i.length);
		}
		return i;
	}
	function prependZero(i, i2, i3) {
		if (i < i2) {
			i = i3 + i;
		}
		return i;
	}
	
}
function lookupAddress(query, ambiguityOptionId, config) {
	config			= config || {};
	var ambiguity 	= ambiguityOptionId || "",
		prefix		= config.elementPrefix || "the",
		onSuccess	= config.onSuccess || function(data, textStatus, jqXHR){},
		onComplete	= config.onComplete || function(jqXHR,settings){};
	$.ajax({
		url:		"/postcode/lookup.htm",
		data:		{elementPrefix: prefix, lookFor: query, ambiguityId: ambiguity},
		complete:	onComplete,
		success:	onSuccess
	});				
}
function lookupAddressByPostcode2(postcodeElementId, line1ElementId, line2ElementId, cityElementId, regionElementId) {
	var postcode = document.getElementById(postcodeElementId).value;
	var addressLine = document.getElementById(line1ElementId).value;
	
	if (postcode.length == 0) {
		alert("You must enter a postcode first!");
		return;
	}
	
	var lookFor = '';
	if (addressLine.length > 0){
		lookFor = addressLine + ',';
	}
	lookFor = lookFor + postcode;
	
	lookupAddress2(lookFor, '', postcodeElementId, line1ElementId, line2ElementId, cityElementId, regionElementId);
}
function lookupAddress2(lookFor, ambiguityId, postcodeElementId, line1ElementId, line2ElementId, cityElementId, regionElementId) {
	var params = {
		lookFor: lookFor,
		ambiguityId: ambiguityId,
		postcodeElementId: postcodeElementId,
		line1ElementId: line1ElementId,
		line2ElementId: line2ElementId,
		cityElementId: cityElementId,
		regionElementId: regionElementId
	};
	document.getElementById('addresslist').style.display = "none";
	
	$.get('/postcode/lookuppostcode2.htm', params, function(data) {
		var results = data.split('\n');
		if (results[0] == 'ADDRESS') {
			document.getElementById(line1ElementId).value = results[1];
			document.getElementById(line2ElementId).value = results[2];
			document.getElementById(cityElementId).value = results[3];
			document.getElementById(regionElementId).value = results[4];
			document.getElementById(postcodeElementId).value = results[5];
		}
		else {
	    	document.getElementById('addresslist').innerHTML = data;
	    	document.getElementById('addresslist').style.display = '';
		}
	}, 'html');
}
function refreshheaderbasket(open) {
	$('#headerbasket').load('/headerbasket.htm');
	$('#basketOpen').load('/headerbasketopen.htm', { open: open });
	
}
function refreshminibasket() {
	$('#miniBasket').load('/taster/minibasket.htm');
}
function refreshheaderaccount() {
	$('#headeraccount').load('/headeraccount.htm');
}
function addtobasket(productId, quantity) {
	$.post("/add_to_cart_ajax.htm", { productId: productId, quantity: quantity }, function(response) {
		if(response.onepage_checkout){
			window.location.replace("/onepage_checkout.htm");
		}
		else{
			$('#alertBar').html(response.productName + ' added to your basket').slideDown('slow');
			$('#alertBar').delay(1500).slideUp('slow');
			refreshheaderbasket(false);
			refreshminibasket();
			if (response.missingBottles == 0) {
				$('a.basketClosedCheckout').slideDown();
			}
			else {
				$('a.basketClosedCheckout').slideUp();
			}
		}
	}, "json");
}
function addtobasketwithtasting(productId, quantity, tastingId) {
	$.post("/add_to_cart_ajax.htm", { productId: productId, quantity: quantity, tastingId: tastingId }, function(response) {
		$('#alertBar').html(response.productName + ' added to your basket').slideDown('slow');
		$('#alertBar').delay(1500).slideUp('slow');
		
		refreshheaderbasket(false);
		refreshminibasket();
		if (response.missingBottles == 0) {
			$('a.basketClosedCheckout').slideDown();
		}
		else {
			$('a.basketClosedCheckout').slideUp();
		}
	}, "json");
}
function addOffertobasket(toDoId) {
	$.post("/add_offer_to_cart_ajax.htm", { toDoId: toDoId }, function(data) {
		if(data.alreadyInBasket=='true'){
			$('#alertBar').html('This offer is already in your basket').slideDown('slow');
			$('#alertBar').delay(1500).slideUp('slow');
		}
		else{
			$('#alertBar').html(data.productName + ' added to your basket').slideDown('slow');
			$('#alertBar').delay(1500).slideUp('slow');
		}
		refreshheaderbasket(false);
		refreshminibasket();		
	}, "json");
}
function removefrombasket(cartItemId, quantity) {
	$.post("/ajax/removefromcart.htm", { cartItemId: cartItemId, quantity: quantity }, function(response) {
		$('#alertBar').html(quantity + ' x ' +response.productName + ' removed to your basket').slideDown('slow');
		$('#alertBar').delay(1500).slideUp('slow');
		refreshheaderbasket(false);
		refreshminibasket();
		if (response.missingBottles == 0) {
			$('a.basketClosedCheckout').slideDown();
		}
		else {
			$('a.basketClosedCheckout').slideUp();
		}
	}, "json");
}
function bidCurrent(pitchId, quantity) {
	$('a#showBidConfirmation').hide();
	$('.disabled').show();
	$(".loading").animate({width: 'toggle'});
	$.post("/pitch/bidCurrent.htm", { pitchId: pitchId, quantity: quantity  }, function(response) {
		$("#result").html(response);
		$(".bidResult").animate({width: 'toggle'}).css('zIndex', 888);	
		$("#bidConfirmation").fadeOut();	
	}, "html");
	return false;
}
		
function leaveGroup(groupId) {
	$('#group' + groupId).fadeOut("slow");
	$('#alertBar').html(" You have successfully left the " + response.groupName + " group").slideDown('slow');
	$('#alertBar').delay(1500).slideUp('slow');
	return false;
}
function unfollowBuddy(buddyId) {
	$('#buddy' + buddyId).fadeOut("slow");
	$('#alertBar').html(" You are no longer following " + response.buddyName + " ").slideDown('slow');
	$('#alertBar').delay(1500).slideUp('slow');
	return false;	
}
function showOverlay() {
	document.getElementById('overlay').style.display = 'block';
	$("#overlay").fadeIn("slow"); 
	$("#welcome").fadeIn("slow"); 
	$("#welcome .inside").fadeIn("slow"); 
	return false;
}
function cleanSearchText(searchText) {
	var cleaned = searchText || "";
	cleaned = cleaned.replace(/\W/g, " ");
	cleaned = removeExcessSpaceFrom(cleaned);
	return cleaned;
}
function validateSearchText(searchText) {
	var cleaned = cleanSearchText(searchText);
	return cleaned.length > 0 ? cleaned : false;
}
function showSearchTextError(searchText) {
	alert("'" + searchText + "'  is not a valid search term.");
}
function removeExcessSpaceFrom(text) {
	var cleaned = text || "";
	cleaned = cleaned.replace(/\s+/g, " ");
	cleaned = cleaned.trim();
	return cleaned;
}
/*PORTED FROM NETWORKING*/
$(document).ready(function() {
	
	
	$("a.showLoginPopup").click(function(){
		var link = this.href;
		$(".panelSetup").css('zIndex',988);
		if (link == ""){
			link = location.pathname;
		}
		$('#loginPopupDiv, #loginOverlay2, .caseHorizon, #loginContentPopup').fadeIn("slow");
		$('#process').val(link);
		return false;		
	});
	
	
	$("a.btn-post").click(function(){
		var textField = document.getElementById('originalCommentId');
		
		if (textField != null) {
			textField.value = '';
		}
		$("#post-comment").slideToggle("slow");
		$("#post-naked").slideUp("slow");
		$(this).toggleClass("active");
		$("#commentTextArea").focus();
		return false;
	});
	$("a.viewthis").click(function(){ 
		$("#panel").fadeIn({ 
		  "width": "toggle", "opacity": 1 
		}, { duration: "slow" });
	});
	$(".icon").click(function(){ 
		$("#panel").fadeIn({ 
		  "width": "toggle", "opacity": 1 
		}, { duration: "slow" });
	}); 
	$("#panel a.closethis").click(function(){ 
		$("#panel").fadeOut({ 
		  "width": "toggle", "opacity": 1 
		}, { duration: "slow" });
	});	
	$('a.totop, a.anchorLink').click(function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
		&& location.hostname == this.hostname) {
		  var $target = $(this.hash);
		  $target = $target.length && $target
		  || $('[name=' + this.hash.slice(1) +']');
		  if ($target.length) {
			var targetOffset = $target.offset().top;
			$('html,body')
			.animate({scrollTop: targetOffset}, 1000);
		   return false;
		  }
		}
	  });
	
	$("a.showCaseContentsPopup3").click(function(){
		
		var productId = this.id;
		productId = productId.substring(10);
		$('#caseLoading').removeClass('loginLoading');
		$('#caseContentsPopup').removeClass('loginPopupHeight');
		$('#caseContentsPopup').addClass('casePopupHeight');
		$('#genericPopup, #overlay2, .caseHorizon, #caseContentsPopup, #caseLoading').fadeIn("slow");
		
		$.get('/cases/casePopup.htm',{productId : productId},  function(data) {
			  $('#caseProductContents').html(data);
			  $('#caseLoading').fadeOut("slow");
		});
		
		$('#bottleDetail1').show();
		
		return false;
	});
	$("a.showCaseContentsPopup").live('click', function(){
		$.fancybox.showActivity();
		var productId = this.id;
		productId = productId.substring(10);
		$.get('/cases/casePopup.htm',{productId : productId}, function(response){
			$.fancybox(response, {
				'autoScale'		: false,
				'overlayOpacity':	0.7,
				'transitionIn': 'fade',
				'transitionOut': 'fade',
				'overlayColor':	'black',
				'autoDimensions': true,
				'overlayShow':	true
			})	
		});
	});
	$("a.showGenericPopup").click(function(){
		$('#caseLoading').removeClass('loginLoading');
		$('#caseContentsPopup').removeClass('loginPopupHeight');
		$('#caseContentsPopup').addClass('casePopupHeight');
		$('#genericPopup, #overlay2, .caseHorizon, #caseContentsPopup, #caseLoading').fadeIn("slow");
		var htmlStr = $('#how').html();
		$('#caseProductContents').html(htmlStr);
		$('#caseLoading').fadeOut("slow");
		return false;
	});	
	$("form#sitesearch > input.go-button").click(function() {
		var searchTextField = $("form#sitesearch > input#freesearch"),
			rawSearchText,
			cleanedSearchText;
		if (searchTextField) {
			rawSearchText		= searchTextField.val();
			cleanedSearchText	= validateSearchText(rawSearchText); 
			if (!cleanedSearchText) {
				showSearchTextError(rawSearchText);
				return false;
			} else {
				searchTextField.val(cleanedSearchText);
			}
		}
		return true;
	});
});
function toggleEditMode(which) {
	switch (which) {
	case 'TASTER_PROFILE_IMAGE':
		toggleTextEditMode('tasterProfileImageDisplay', 'uploadPhoto', null);
		break;
	case 'TASTER_PROFILE_MESSAGE':
		toggleTextEditMode('tasterProfileMessageDisplay', 'tasterProfileMessageEdit', 'tasterProfileMessage');
		break;
	case 'TASTER_LIKES':
		for (var i = 0; i < 5; i++) {
			toggleTextEditMode('tasterLikesDisplay[' + i + ']', 'tasterLikes[' + i + ']', 'tasterLikes[' + i + ']');
			toggleElementVisibility('tasterLikesButton');
		}
		break;
	case 'DRINKING_BUDDY_MESSAGE':
		toggleTextEditMode('drinkingBuddyMessageDisplay', 'drinkingBuddyMessageEdit', 'drinkingBuddyMessage');
		break;
	case 'NAKED_ANGEL_MESSAGE':
		toggleTextEditMode('nakedAngelMessageDisplay', 'nakedAngelMessageEdit', 'nakedAngelMessage');
		break;
	}
}
function toggleTextEditMode(displayElementId, editElementId, textElementId) {
	var displayElement = document.getElementById(displayElementId);
	var editElement = document.getElementById(editElementId);

	if (editElement.style.display == 'none') {
		
		if (textElementId != null) {
			var textElement = document.getElementById(textElementId);
			textElement.value = displayElement.innerHTML;
		}
		displayElement.style.display = 'none';
		editElement.style.display = '';
	}
	else {
		displayElement.style.display = '';
		editElement.style.display = 'none';
	}
}
function toggleElementVisibility(elementId) {
	var element = document.getElementById(elementId);
	
	if (element.style.display == 'none') {
		element.style.display = '';
	}
	else {
		element.style.display = 'none';
	}
}
function uploadText(which) {
	var textElement;
	var displayElement;
	
	switch (which) {
	case 'TASTER_PROFILE_MESSAGE':
		textElement = document.getElementById('tasterProfileMessage');
		
		$.post("/taster/upload_text.htm", { text: textElement.value, name: 'taster_profile_message' }, function() {
			displayElement = document.getElementById('tasterProfileMessageDisplay');
			displayElement.innerHTML = textElement.value;
			toggleTextEditMode('tasterProfileMessageDisplay', 'tasterProfileMessageEdit', 'tasterProfileMessage');
		});
		break;
	case 'TASTER_LIKES':
		for (var i = 0; i < 5; i++) {
			textElement = document.getElementById('tasterLikes[' + i + ']');
			
			$.post("/taster/upload_text.htm", { text: textElement.value, name: 'taster_profile_favourite[' + i + ']' });
			
			// Assumes the above post was successful, not ideal
			
			displayElement = document.getElementById('tasterLikesDisplay[' + i + ']');
			displayElement.innerHTML = textElement.value;
			toggleTextEditMode('tasterLikesDisplay[' + i + ']', 'tasterLikes[' + i + ']', 'tasterLikes[' + i + ']');
			
			toggleElementVisibility('tasterLikesButton');
		}
		break;
	case 'DRINKING_BUDDY_MESSAGE':
		textElement = document.getElementById('drinkingBuddyMessage');
		
		$.post("/taster/upload_text.htm", { text: textElement.value, name: 'drinking_buddy_message' }, function() {
			displayElement = document.getElementById('drinkingBuddyMessageDisplay');
			displayElement.innerHTML = textElement.value;
			toggleTextEditMode('drinkingBuddyMessageDisplay', 'drinkingBuddyMessageEdit', 'drinkingBuddyMessage');
		});
		break;
	case 'NAKED_ANGEL_MESSAGE':
		textElement = document.getElementById('nakedAngelMessage');
		
		$.post("/taster/upload_text.htm", { text: textElement.value, name: 'naked_angel_message' }, function() {
			displayElement = document.getElementById('nakedAngelMessageDisplay');
			displayElement.innerHTML = textElement.value;
			toggleTextEditMode('nakedAngelMessageDisplay', 'nakedAngelMessageEdit', 'nakedAngelMessage');
		});
		break;
	}
}
function uploadPhoto() {
	var viewPhoto = document.getElementById('viewPhoto');
	var uploadPhoto = document.getElementById('uploadPhoto');
	viewPhoto.style.display = 'none';
	uploadPhoto.style.display = 'block';
	return false;
}
function replyToComment(id) {
	var originalCommentId = document.getElementById('originalCommentId');
	
	if (originalCommentId != null) {
		originalCommentId.value = id;
	}
	
	$("#post-comment").slideToggle("slow");
	$(this).toggleClass("active");
	$("#commentTextArea").focus();
	return false;
}
function wallPostSetPinned(wallPostId, pinned) {
	var form = document.getElementById('wallPostSetPinnedForm' + wallPostId);
	form.pinned.value = pinned;
	form.submit();
}
function toggleEditComment(which, index) {
	toggleTextEditMode(which + 'DisplayDiv[' + index + ']', which + 'EditDiv[' + index + ']', which + 'TextArea[' + index + ']');
}
function commentOnProduct(which, index, id) {
	switch (which) {
	case 'wine':
		rateProduct(id, null, null, null, which + 'TextArea[' + index + ']');
		break;
	case 'winemaker':
		rateProduct(null, id, null, null, which + 'TextArea[' + index + ']');
		break;
	case 'nakedStuff':
		rateProduct(null, null, id, null, which + 'TextArea[' + index + ']');
		break;
	}
	document.getElementById(which + 'DisplayDiv[' + index + ']').innerHTML = document.getElementById(which + 'TextArea[' + index + ']').value;
	toggleTextEditMode(which + 'DisplayDiv[' + index + ']', which + 'EditDiv[' + index + ']', which + 'TextArea[' + index + ']');
}
function rateProduct(productId, winemakerId, nakedStuffId, ratingElementId, commentElementId) {
	var rating = null;
	var comment = null;
	
	if (ratingElementId != null) {
		rating = document.getElementById(ratingElementId).value;
	}
	
	if (commentElementId != null) {
		comment = document.getElementById(commentElementId).value;
	}
	
	var parameters = new Object();
	
	if (productId != null) {
		parameters['productId'] = productId;
	}
	
	if (winemakerId != null) {
		parameters['winemakerId'] = winemakerId;
	}
	
	if (nakedStuffId != null) {
		parameters['nakedStuffId'] = nakedStuffId;
	}
	
	if (rating != null) {
		parameters['rating'] = rating;
	}
	
	if (comment != null) {
		parameters['comment'] = comment;
	}
	
	$.post("/taster/ajax_rate_product.htm",	parameters);
}
var DDSPEED = 10;
var DDTIMER = 15;

// main function to handle the mouse events //
function ddMenu(id,d){
  var h = document.getElementById(id + '-ddheader');
  var c = document.getElementById(id + '-ddcontent');
  clearInterval(c.timer);
  if(d == 1){
    clearTimeout(h.timer);
    if(c.maxh && c.maxh <= c.offsetHeight){return}
    else if(!c.maxh){
      c.style.display = 'block';
      c.style.height = 'auto';
      c.maxh = c.offsetHeight;
      c.style.height = '0px';
    }
    c.timer = setInterval(function(){ddSlide(c,1)},DDTIMER);
  }else{
    h.timer = setTimeout(function(){ddCollapse(c)},50);
  }
}
// collapse the menu //
function ddCollapse(c){
  c.timer = setInterval(function(){ddSlide(c,-1)},DDTIMER);
}
// cancel the collapse if a user rolls over the dropdown //
function cancelHide(id){
  var h = document.getElementById(id + '-ddheader');
  var c = document.getElementById(id + '-ddcontent');
  clearTimeout(h.timer);
  clearInterval(c.timer);
  if(c.offsetHeight < c.maxh){
    c.timer = setInterval(function(){ddSlide(c,1)},DDTIMER);
  }
}
// incrementally expand/contract the dropdown and change the opacity //
function ddSlide(c,d){
  var currh = c.offsetHeight;
  var dist;
  if(d == 1){
    dist = (Math.round((c.maxh - currh) / DDSPEED));
  }else{
    dist = (Math.round(currh / DDSPEED));
  }
  if(dist <= 1 && d == 1){
    dist = 1;
  }
  c.style.height = currh + (dist * d) + 'px';
  c.style.opacity = currh / c.maxh;
  c.style.filter = 'alpha(opacity=' + (currh * 100 / c.maxh) + ')';
  if((currh < 2 && d != 1) || (currh > (c.maxh - 2) && d == 1)){
    clearInterval(c.timer);
  }
}
function reviewRating(productRatingId, radioButton) {
	$.post("/taster/ajax_review_rating.htm", { productRatingId: productRatingId, useful: radioButton.value });
	radioButton.checked = true;
}
function setProfileVisibilty(radioButton) {
	$.post("/taster/ajax_profile_visibility.htm", { visible: radioButton.value });
	radioButton.checked = true;
}
function followTwitterUser(customerId) {
	$.ajax({
		type: "POST",
		url: "/taster/ajax_follow_twitter_user.htm",
		data: "customerId=" + customerId,
		success: function(data) {
			document.getElementById("twitterUserDiv").innerHTML = "You are following this user";
		},
		error: function(data) {
			document.getElementById("twitterUserDiv").innerHTML = "There was an error following this user";
		}
	});
}
function rateProductViaStar(spanId, productId, rating) {
	for (var i = 0; i < 5; i++) {
		$('#' + spanId + ' span').get(i).onmouseout = function() {
			highlightRatingStars(spanId, rating);
		};
	}
	$.post('/taster/ajax_rate_product.htm', { productId: productId, rating: rating });
}
function rateNakedStuffViaStar(spanId, nakedStuffId, rating) {
	for (var i = 0; i < 5; i++) {
		$('#' + spanId + ' span').get(i).onmouseout = function() {
			highlightRatingStars(spanId, rating);
		};
	}
	$.post('/taster/ajax_rate_product.htm', { nakedStuffId: nakedStuffId, rating: rating });
}





