$('html').addClass('js');
var imagePopupActive = false;
$(document).ready(function(){
  initCarousels();
  textboxDefault('input#newsletterEmailAddress', 'email address');
  $('input#newsletterEmailAddress').val('email address');
  currencySelector();
  addToBasket();
  basketCheckoutButton();
  formatSelector();
  addToNewsletter();
  addToWishlist();
  emailNotInStock();
  showMiniBasket();
  showHideCardAddress();
  noPostcode('select#countryCode', 'input#postCode');
  initMeetTheAuthor();
  openNewWindow();
  openChat();
  addClassGooglePreviewButton();
  checkoutSingleSubmit();
  GWOeventTracking();

  setTextAreaMaxLength();
  windowifyLinks();

  ajaxableLinks();

	$(".image.large a").click( function() {
        if($("#large_image_popup").attr("src")){
            return false;
        }else{
	    if(!$('#is_noImage').length)
	    {
		var the_span = $(".image.large a:first");
		var the_href = the_span.attr('href');
		var the_alt = the_span.find('img').attr('alt');
		var imageUrl = '<img id="large_image_popup" src="' + the_href + '" alt="' + the_alt + '" width="400" height="430"/><div>' + the_alt + '</div>';

		  $.weeboxs.open(imageUrl
		    ,{contentType:'get',
			title:'Large Image',
			position: 'center',
			modal: false,
			height:460,
			width: 435,
			showCancel: false,
			showOk: false,
			showButton: false,
			animate:true,
			clickClose: false,
			showTitle: true
                    }
		);
	    }
        }
		return false;
	})
});

function basketCheckoutButton() {
	$('.hideButton').removeClass('hideButton');
}

function openNewWindow(){
  $('a.blank').click(function(){
    window.open(this.href);
    return false;
    });
}

function openChat() {
	$('a.livechat').click(function(){
		chatWin = window.open(this.href, 'Live Chat', 'scrollbars=no,menubar=no,resizable=1,location=no,screenX=100,screenY=100,width=600,height=700');
		chatWin.focus();
		return false;
	});

}

function initMeetTheAuthor(){
	if('undefined' != typeof(displayMta) && displayMta)
		renderMta();

	$("#MTAPopup").css("display", "none");
	$('#openMeetTheAuthor').click(function(){
		$("#MTAPopup").show("fast");
		return false;
	});

    $('a#closeMeetTheAuthor').click(function(){
        $("#MTAPopup").hide("fast");
	so.write("flashcontent");
        return false;
    });
}

function setFieldFocus( fieldId )
{
  $( "#" + fieldId ).focus();
}

function roundAmazonCorners()
{
  $('.priceBlock.alternative.amazonPrice').corner();
}

function initCarousels()
{
	$('.address .mycarousel').jcarousel({
		scroll: 1,
		moduleWidth: 290,
		rows:1,
		cols:2,
		itemLoadCallback: mycarousel_itemLoadCallback,
		buttonNextCallback: updateScrollValue,
        buttonPrevCallback: updateScrollValue,
		animation: 'slow'
	});

	$('.columns1 .scroll.mycarousel').jcarousel({
		scroll: 1,
		moduleWidth: 680,
		rows:1,
		cols:1,
		itemLoadCallback: mycarousel_itemLoadCallback,
		buttonNextCallback: updateScrollValue,
        buttonPrevCallback: updateScrollValue,
		animation: 'slow'
	});

	$('.columns2.rows2 .scroll.mycarousel').jcarousel({
		scroll: 1,
		moduleWidth: 340,
		rows:2,
		cols:2,
		itemLoadCallback: mycarousel_itemLoadCallback,
		buttonNextCallback: updateScrollValue,
		buttonPrevCallback: updateScrollValue,
		itemVisibleOutCallback: updateScrollValue,
		animation: 'slow'
	});

	$('.columns2.rows1 .scroll.mycarousel').jcarousel({
		scroll: 2,
		moduleWidth: 340,
		rows:1,
		cols:2,
		itemLoadCallback: mycarousel_itemLoadCallback,
		buttonNextCallback: updateScrollValue,
        buttonPrevCallback: updateScrollValue,
		animation: 'slow'
	});

	$('.columns5.rows1 .scroll.mycarousel').jcarousel({
		scroll: 5,
		moduleWidth: 137,
		rows:1,
		cols:5,
		itemLoadCallback: mycarousel_itemLoadCallback,
		buttonNextCallback: updateScrollValue,
        buttonPrevCallback: updateScrollValue,
		animation: 'slow'
	});
}


function updateNext( carousel )
{
	updateScrollValue( carousel );
}

function updatePrev( carousel )
{
	updateScrollValue( carousel );
}


function loadMore( carousel )
{

}


function mycarousel_itemLoadCallback(carousel, state)
{
	var carId = carousel.list.attr("id");
	var carData = carId.split( ':' );
	carousel.size( carData[1] );
	carousel.cacheId = carData[0];

	if( undefined != carousel.fakeLast )
	{
		var nextLiFirst = carousel.fakeLast;
		var nextLiLast = nextLiFirst + carousel.options.scroll;

		if( carousel.has( nextLiFirst, nextLiLast ) )
		{
			carousel.unlock();
			return;
		}
	}
	else
	{
		var nextLiFirst = carousel.list.children('li').size();
	}

	var firstMod = ( carousel.first + ( carousel.options.rows * carousel.options.cols ) );
	var lastMod = firstMod + ( carousel.options.scroll * carousel.options.rows ) - 1;

	if( firstMod <= carousel.size() )
	{
		$.ajax({
			dataType: 'json',
			url: '/load/data',
			type: 'GET',

			data: {
				first: firstMod,
				last: lastMod,
				cacheId: carousel.cacheId
			},

			success: function( moduleHtml ) {
				mycarousel_itemAddCallback( carousel, moduleHtml, nextLiFirst+1 )
				carousel.unlock();

				addToBasket();
			},

			error: function(XMLHttpRequest, textStatus, errorThrown) {
				var msg = '';
				if (textStatus == 'timeout') {
					msg = 'Our server is taking too long to respond.';
				} else {
					msg = 'An error has occurred.!';
				}
				carousel.unlock();
			}
		});
	}
	else {
		carousel.unlock();
	}

}

function mycarousel_itemAddCallback( carousel, moduleHtml, nextLiFirst )
{
	var insertPos = nextLiFirst;
	var extendCount = 0;
	var addHtml = '';
	var additionIndex = 0;
	$.each( moduleHtml, function(i, val) {
		addHtml += val;
		extendCount++;
		if( 0 == ( extendCount % carousel.options.rows ) || ( extendCount == moduleHtml.length ) )
		{
			carousel.add( insertPos + additionIndex, addHtml );
			addHtml = '';
			additionIndex++;
		}
	} );
	var realExtend = extendCount / carousel.options.rows;
	carousel.extend( realExtend );
}


function stristr( haystack, needle, bool ) {
    var pos = 0;

    haystack += '';
    pos = haystack.toLowerCase().indexOf( (needle+'').toLowerCase() );
    if( pos == -1 ){
        return false;
    } else{
        if( bool ){
            return haystack.substr( 0, pos );
        } else{
            return haystack.slice( pos );
        }
    }
}




function updateScrollValue( carousel )
{
	var contentBlock = carousel.list.parent().parent().parent().parent();
	var scrollValue = contentBlock.children('.scrollValue');
	var first = scrollValue.children(":eq(0)");
	var last = scrollValue.children(":eq(1)");
	var count = scrollValue.children(":eq(2)");
	var firstMod = carousel.first;
	var modsVisible = carousel.options.rows * carousel.options.cols;
	var lastMod = firstMod + modsVisible - 1;
	if( lastMod > carousel.size() )
		lastMod = carousel.size();

	first.text( firstMod );
	last.text( lastMod );
	count.text( carousel.size() );
}



function updateScrollValue_old( carousel )
{
	var li = carousel.size();
	var contentBlock = carousel.list.parent().parent().parent().parent();
	var scrollValue = contentBlock.children('.scrollValue');
	var first = scrollValue.children(":eq(1)");
	var last = scrollValue.children(":eq(2)");
	var count = scrollValue.children(":eq(3)");
	var firstMod = carousel.first;
	var step = carousel.options.rows;

	if( 1 != carousel.options.rows )
	{
		if( firstMod > 1 )
			firstMod = ( carousel.first * step ) - 1;
	}

	var modsVisible = carousel.options.rows * carousel.options.cols;

	var lastMod = firstMod + modsVisible - 1;
	if( lastMod > li.length )
		lastMod = li.length;

	first.text( firstMod );
	last.text( lastMod );
	count.text( li );
}

function textboxDefault(selector, defaultText) {
  $(selector).focus(function() {
    if (defaultText == $(this).val()) {
      $(this).val('');
    }
  });

  $(selector).blur(function() {
    if ('' == $(this).val()) {
      $(this).val(defaultText);
    }
  });
}

function currencySelector() {
  $('select#selectCurrency').change(function() {
    $('form#currencySelection').submit();
  });
}

function formatSelector() {
	var addToBasketPopup = $('<div id="addToBasketPopup" class="popUp"><h4 /><a class="close" name="close"> x </a><p /></div>');
	$("#selectFormat").hide();
	$("input[name^='format']:radio").click(function() {
		$("input[name^='format']:radio").attr("disabled", true);
		closeBasketPopup();
		$(addToBasketPopup).insertAfter('#miniBasket');
		$(addToBasketPopup).find('a.close').click(function() {
			closeBasketPopup();
		});
		$(addToBasketPopup).find('span.linkSurround.more').click(function() {
			closeBasketPopup();
		});
		$(addToBasketPopup).css({
			top: $('span.button.buy a').offset().top + $('span.button.buy a').height() + 'px',
			left: $('span.button.buy a').parent().offset().left - ($('span.button.buy a').parent().width() / 2) + 'px'
		});
        $(addToBasketPopup).show().find('h4').text('Please wait');
        $(addToBasketPopup).find('p').html('Updating the price for the format you selected.');

		$.ajax({
			dataType: 'json',
			url: formatUrl + this.value,
			type: 'GET',
			beforeSend: function() {
				$(addToBasketPopup).show().find('h4').text('Please wait');
				$(addToBasketPopup).find('p').html('Updating the price for the format you selected');
			},
			success: function(data) {
				$("input[name^='format']:radio").removeAttr("disabled");
				$('body').bind('click', closeBasketPopup);
				if (!data.error) {
					$("#format_" + data.formatCode).attr("checked", true);
					$("#priceBlock").html(data.priceBlock);
					$('span.button.buy a').attr("href", data.basketUrl);
					if (data.compatible) {
						$("#notCompatible").html("");
					} else {
						$("#notCompatible").html("<p>You can buy this eBook however it may not be compatible with the device you've selected.</p>")
					}
					closeBasketPopup();
				} else {
					$(addToBasketPopup).show().find('h4').text('Error');
					$(addToBasketPopup).find('p').html('<span class="popUpText">' + data.errorMessage + '</span>');
					scrollToView('div#addToBasketPopup', 250);
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				var msg = '';
				if (textStatus == 'timeout') {
					msg = 'Our server is taking too long to respond. Please try to select the format again.';
				} else {
					msg = 'An error has occurred. Please try to select the format again.';
				}
				$("input[name^='format']:radio").removeAttr("disabled");
				$('body').bind('click', closeBasketPopup);
				$(addToBasketPopup).show().find('h4').text('Error');
				$(addToBasketPopup).find('p').html(msg);
				scrollToView('div#addToBasketPopup', 250);
			}
		});
		return false;
	});
}

function addToBasket() {
  $.ajaxSetup({
    global: false,
    type: 'GET',
    timeout: 15000
  });
  var addToBasketPopup = $('<div id="addToBasketPopup" class="popUp"><h4 /><a class="close" name="close"> x </a><p /></div>');


  $('span.button.buy a').unbind('click');

  $('span.button.buy a').click(function() {
    $(addToBasketPopup).insertAfter('#miniBasket');
    $(addToBasketPopup).find('a.close').click(function() {
      closeBasketPopup();
    });
    $(addToBasketPopup).find('span.linkSurround.more').click(function() {
      closeBasketPopup();
    });
    $(addToBasketPopup).css({
      top: $(this).offset().top + $(this).height() + 'px',
      left: $(this).parent().offset().left - ($(this).parent().width() / 2) + 'px'
    });

    $.ajax({
      dataType: 'json',
      url: $(this).attr('href') + '?call=ajax',
      type: 'GET',
      beforeSend: function() {
        $(addToBasketPopup).show().find('h4').text('Please wait');
        $(addToBasketPopup).find('p').html('');
      },
      success: function(data) {
        $('body').bind('click', closeBasketPopup);
        if (!data.error) {
          $(addToBasketPopup).show().find('h4').text('Item added to your basket');
          $(addToBasketPopup).find('p').html('<span class="popUpText">You have ' + data.info.numItems + ' item' + ((data.info.numItems > 1) ? 's' : '') + ' in your basket</span>\n<span class="popUpText totalCost"><strong>Total cost: ' + data.currency + '<span class="totalNum">' + data.info.basketTotal + '</span></strong></span>\n<span class="linkSurround button checkout"><a href="/basket"><em>Basket/checkout</em></a></span>\n<span class="linkSeperator" title="Link seperator ">|</span>\n<span class="linkSurround button more"><a name="Continue shopping"><em>Continue shopping</em></a></span>');
          $(addToBasketPopup).find('p  span.totalCost strong span.totalNum').format({format:"#,###.00", locale:"gb"});
          scrollToView('div#addToBasketPopup', 250);
          // Update the mini basket
          updateMiniBasket(data);
        } else {
          $(addToBasketPopup).show().find('h4').text('Insufficient Stock');
          $(addToBasketPopup).find('p').html('<span class="popUpText">' + data.errorMessage + '</span>\n<span class="popUpText">You have ' + data.info.numItems + ' item' + ((data.info.numItems > 1) ? 's' : '') + ' in your basket</span>\n<span class="popUpText totalCost"><strong>Total cost: ' + data.currency + '<span class="totalNum">' +data.info.basketTotal + '</span></strong></span>\n<span class="linkSurround button checkout"><a href="/basket"><em>Basket/checkout</em></a></span>\n<span class="linkSeperator" title="Link seperator ">|</span>\n<span class="linkSurround button more"><a name="Continue shopping"><em>Continue shopping</em></a></span>');
          $(addToBasketPopup).find('p  span.totalCost strong span.totalNum').format({format:"#,###.00", locale:"gb"});
          scrollToView('div#addToBasketPopup', 250);
          updateMiniBasket(data);
        }

					$("#addToBasketPopup .linkSurround.checkout a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Route to basket', 'basket - popup')}catch(err){}return true;
					});

					$("#addToBasketPopup .linkSurround.more a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Route to basket', 'continue shopping - popup')}catch(err){}return true;
					});
					$("#addToBasketPopup a.close").unbind('click').click(function(){
						try{pageTracker._trackEvent('Route to basket', 'close - popup')}catch(err){}return true;
					});
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        var msg = '';
        if (textStatus == 'timeout') {
          msg = 'Our server is taking too long to respond. Your item may still have been added to your basket, you may want to check!';
        } else {
          msg = 'An error has occurred. Your item may still have been added to your basket, you may want to check!';
        }
        $('body').bind('click', closeBasketPopup);
        $(addToBasketPopup).show().find('h4').text('Error');
        $(addToBasketPopup).find('p').html(msg);
        scrollToView('div#addToBasketPopup', 250);
      }
    });
    return false;
  });
					$("div.module.fullBook p.priceBlock .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Full book', 'Add to basket')}catch(err){}return true;
					});
					$("div.module.fullBook p.priceBlock.preOrder .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Full book', 'Pre order')}catch(err){}return true;
					});
					$("div.module.fullBook div.priceBlock button#notifyMe").click(function(){
						try{pageTracker._trackEvent('Full book', 'Notify')}catch(err){}return true;
					});
					$("div.module.fullBook p.priceBlock.abe .linkSurround.button.abe a").click(function(){
						try{pageTracker._trackEvent('Full book', 'Save item')}catch(err){}return true;
					});
					$("div.module.fullBook #otherFormats a").click(function(){
						try{pageTracker._trackEvent('Full book', 'Also available', $("div.module.fullBook #otherFormats a").val())}catch(err){}return true;
					});
					$("#content.bookFull div.contentBlock.columns5 div.module.bookSmall p.priceBlock .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Add to basket', 'Full book')}catch(err){}return true;
					});
					$("#content.bookFull div.contentBlock.columns5 div.module.bookSmall p.priceBlock.preOrder .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Pre order', 'Full book')}catch(err){}return true;
					});
					$("#content.bookFull div.contentBlock.columns5 div.module.bookSmall p.priceBlock.abe .linkSurround.button.abe a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Notify', 'Full book')}catch(err){}return true;
					});
					$("#content.bookFull div.contentBlock.columns5 div.module.bookSmall p.priceBlock .linkSurround.button.email a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Abe', 'Full book')}catch(err){}return true;
					});
					$("#content.bookFull div.contentBlock.columns5 div.module.bookSmall .linkSurround.image a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Image link', 'Full book')}catch(err){}return true;
					});
					$("#content.bookFull div.contentBlock.columns5 div.module.bookSmall h3 a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Title link', 'Full book')}catch(err){}return true;
					});
					$("#content.home div.contentBlock.columns2.rows2 div.module.bookSmall p.priceBlock .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Add to basket', 'Homepage')}catch(err){}return true;
					});
					$("#content.home div.contentBlock.columns2.rows2 div.module.bookSmall p.priceBlock.preOrder .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Pre order', 'Homepage')}catch(err){}return true;
					});
					$("#content.home div.contentBlock.columns2.rows2 div.module.bookSmall p.priceBlock.abe .linkSurround.button.abe a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Notify', 'Homepage')}catch(err){}return true;
					});
					$("#content.home div.contentBlock.columns2.rows2 div.module.bookSmall p.priceBlock .linkSurround.button.email a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Abe', 'Homepage')}catch(err){}return true;
					});
					$("#content.home div.contentBlock.columns2.rows2 div.module.bookSmall .linkSurround.image a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Image link', 'Homepage')}catch(err){}return true;
					});
					$("#content.home div.contentBlock.columns2.rows2 div.module.bookSmall span.linkSurround.more a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'More link', 'Homepage')}catch(err){}return true;
					});
					$("#content.home div.contentBlock.columns2.rows2 div.module.bookSmall h3 a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Title link', 'Homepage')}catch(err){}return true;
					});
					$("#content.home div.contentBlock.columns5 div.module.bookSmall p.priceBlock .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Add to basket', 'Homepage')}catch(err){}return true;
					});
					$("#content.home div.contentBlock.columns5 div.module.bookSmall p.priceBlock.preOrder .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Pre order', 'Homepage')}catch(err){}return true;
					});
					$("#content.home div.contentBlock.columns5 div.module.bookSmall p.priceBlock.abe .linkSurround.button.abe a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Notify', 'Homepage')}catch(err){}return true;
					});
					$("#content.home div.contentBlock.columns5 div.module.bookSmall p.priceBlock .linkSurround.button.email a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Abe', 'Homepage')}catch(err){}return true;
					});
					$("#content.home div.contentBlock.columns5 div.module.bookSmall .linkSurround.image a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Image link', 'Homepage')}catch(err){}return true;
					});
					$("#content.home div.contentBlock.columns5 div.module.bookSmall h3 a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Title link', 'Homepage')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns2.rows1 div.module.bookSmall p.priceBlock .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 1-row', 'Add to basket', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns2.rows1 div.module.bookSmall p.priceBlock.preOrder .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 1-row', 'Pre order', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns2.rows1 div.module.bookSmall p.priceBlock.abe .linkSurround.button.abe a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 1-row', 'Notify', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns2.rows1 div.module.bookSmall p.priceBlock .linkSurround.button.email a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 1-row', 'Abe', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns2.rows1 div.module.bookSmall .linkSurround.image a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 1-row', 'Image link', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns2.rows1 div.module.bookSmall span.linkSurround.more a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 1-row', 'More link', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns2.rows1 div.module.bookSmall h3 a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 1-row', 'Title link', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns2.rows2 div.module.bookSmall p.priceBlock .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Add to basket', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns2.rows2 div.module.bookSmall p.priceBlock.preOrder .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Pre order', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns2.rows2 div.module.bookSmall p.priceBlock.abe .linkSurround.button.abe a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Notify', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns2.rows2 div.module.bookSmall p.priceBlock .linkSurround.button.email a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Abe', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns2.rows2 div.module.bookSmall .linkSurround.image a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Image link', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns2.rows2 div.module.bookSmall span.linkSurround.more a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'More link', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns2.rows2 div.module.bookSmall h3 a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Title link', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns5 div.module.bookSmall p.priceBlock .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Add to basket', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns5 div.module.bookSmall p.priceBlock.preOrder .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Pre order', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns5 div.module.bookSmall p.priceBlock.abe .linkSurround.button.abe a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Notify', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns5 div.module.bookSmall p.priceBlock .linkSurround.button.email a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Abe', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns5 div.module.bookSmall .linkSurround.image a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Image link', 'Category')}catch(err){}return true;
					});
					$("#content.categories div.contentBlock.columns5 div.module.bookSmall h3 a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Title link', 'Category')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows1 div.module.bookSmall p.priceBlock .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 1-row', 'Add to basket', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows1 div.module.bookSmall p.priceBlock.preOrder .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 1-row', 'Pre order', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows1 div.module.bookSmall p.priceBlock.abe .linkSurround.button.abe a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 1-row', 'Notify', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows1 div.module.bookSmall p.priceBlock .linkSurround.button.email a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 1-row', 'Abe', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows1 div.module.bookSmall .linkSurround.image a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 1-row', 'Image link', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows1 div.module.bookSmall span.linkSurround.more a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 1-row', 'More link', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows1 div.module.bookSmall h3 a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 1-row', 'Title link', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows2 div.module.bookSmall p.priceBlock .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Add to basket', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows2 div.module.bookSmall p.priceBlock.preOrder .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Pre order', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows2 div.module.bookSmall p.priceBlock.abe .linkSurround.button.abe a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Notify', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows2 div.module.bookSmall p.priceBlock .linkSurround.button.email a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Abe', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows2 div.module.bookSmall .linkSurround.image a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Image link', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows2 div.module.bookSmall span.linkSurround.more a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'More link', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows2 div.module.bookSmall h3 a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 2-rows', 'Title link', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows5 div.module.bookSmall p.priceBlock .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 5-rows', 'Add to basket', 'Bestsellers UK')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows5 div.module.bookSmall p.priceBlock.preOrder .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 5-rows', 'Pre order', 'Bestsellers UK')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows5 div.module.bookSmall p.priceBlock.abe .linkSurround.button.abe a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 5-rows', 'Notify', 'Bestsellers UK')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows5 div.module.bookSmall p.priceBlock .linkSurround.button.email a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 5-rows', 'Abe', 'Bestsellers UK')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows5 div.module.bookSmall .linkSurround.image a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 5-rows', 'Image link', 'Bestsellers UK')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows5 div.module.bookSmall span.linkSurround.more a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 5-rows', 'More link', 'Bestsellers UK')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns2.rows5 div.module.bookSmall h3 a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 5-rows', 'Title link', 'Bestsellers UK')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns5 div.module.bookSmall p.priceBlock .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Add to basket', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns5 div.module.bookSmall p.priceBlock.preOrder .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Pre order', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns5 div.module.bookSmall p.priceBlock.abe .linkSurround.button.abe a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Notify', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns5 div.module.bookSmall p.priceBlock .linkSurround.button.email a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Abe', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns5 div.module.bookSmall .linkSurround.image a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Image link', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.bestsellers div.contentBlock.columns5 div.module.bookSmall h3 a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Title link', 'Bestsellers')}catch(err){}return true;
					});
					$("#content.searchResults div.contentBlock.columns2.rows10 div.module.bookSmall p.priceBlock .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 10-rows', 'Add to basket', 'Search results')}catch(err){}return true;
					});
					$("#content.searchResults div.contentBlock.columns2.rows10 div.module.bookSmall p.priceBlock.preOrder .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 10-rows', 'Pre order', 'Search results')}catch(err){}return true;
					});
					$("#content.searchResults div.contentBlock.columns2.rows10 div.module.bookSmall p.priceBlock.abe .linkSurround.button.abe a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 10-rows', 'Notify', 'Search results')}catch(err){}return true;
					});
					$("#content.searchResults div.contentBlock.columns2.rows10 div.module.bookSmall p.priceBlock .linkSurround.button.email a").click(function(){
						try{pageTracker._trackEvent('Block 2-cols 10-rows', 'Abe', 'Search results')}catch(err){}return true;
					});
	//				image link
					$("#content.searchResults div.contentBlock.columns2.rows10 div.module.bookSmall .linkSurround.image a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 10-rows', 'Image link', 'Search results')}catch(err){}return true;
					});
					$("#content.searchResults div.contentBlock.columns2.rows10 div.module.bookSmall span.linkSurround.more a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 10-rows', 'More link', 'Search results')}catch(err){}return true;
					});
					$("#content.searchResults div.contentBlock.columns2.rows10 div.module.bookSmall h3 a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 2-cols 10-rows', 'Title link', 'Search results')}catch(err){}return true;
					});
					$("#content.searchResults div.contentBlock.columns5 div.module.bookSmall p.priceBlock .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Add to basket', 'Search results')}catch(err){}return true;
					});
					$("#content.searchResults div.contentBlock.columns5 div.module.bookSmall p.priceBlock.preOrder .linkSurround.button.buy a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Pre order', 'Search results')}catch(err){}return true;
					});
					$("#content.searchResults div.contentBlock.columns5 div.module.bookSmall p.priceBlock.abe .linkSurround.button.abe a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Notify', 'Search results')}catch(err){}return true;
					});
					$("#content.searchResults div.contentBlock.columns5 div.module.bookSmall p.priceBlock .linkSurround.button.email a").click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Abe', 'Search results')}catch(err){}return true;
					});
					$("#content.searchResults div.contentBlock.columns5 div.module.bookSmall .linkSurround.image a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Image link', 'Search results')}catch(err){}return true;
					});
					$("#content.searchResults div.contentBlock.columns5 div.module.bookSmall h3 a").unbind('click').click(function(){
						try{pageTracker._trackEvent('Block 5-cols', 'Title link', 'Search results')}catch(err){}return true;
					});

}

function closeBasketPopup() {
  $('div#addToBasketPopup').hide();
  $('body').unbind('click', closeBasketPopup);
}

function updateMiniBasket(data) {
  var basketItems = $('#basketView tbody');
  basketItems.empty();
  var currencyCode = data.currency;
  var currencyCodeSmall = data.currencySmall;
  $(data.items).each(function(i) {
    var itemRow = $('<tr />');
    var quantity = $('<td class="miniBasketquantity" headers="miniBasketquantity">' + this.quantity + '</td>');
    var title = $('<td class="miniBasketbookDetails" headers="miniBasketbookDetails"><a href="/browse/book/isbn/' + this.isbn13 + '" title="See book details ">' + this.title + '</a></td>')
    var price = $('<td class="miniBasketprice" headers="miniBasketprice">' + currencyCodeSmall + this.basketTotal + '</td>');
    itemRow.append(quantity).append(title).append(price);
    basketItems.append(itemRow);
  });

  $('#basketView tfoot td span.totalItems a').html(data.info.numItems + ((1 == data.info.numItems) ? ' item' : ' items'));
  $('#basketView tfoot td span.basketTotal a').html('<strong><span class="accessibility">Total </span>' + currencyCode +'<span class="miniBasketTotalNum">' + data.info.basketTotal + '</span></strong>');
  $().find('td  span.basketTotal strong span.miniBasketTotalNum').format({format:"#,###.00", locale:"gb"});
}

function noPostcode(countryField, postcodeField) {
  $('span.noPostcode span').hide();
  $('span.noPostcode').hide();

  var currentCountry = $(countryField + ' option:selected').val();
  if ('GB' != currentCountry && 'US' != currentCountry) {
    $('span.noPostcode').show();
  }

  $(countryField).change(function() {
    var country = $(countryField + ' option:selected').val();
    if ('GB' == country || 'US' == country) {
      $('span.noPostcode').hide();
    } else {
      $('span.noPostcode').show();
    }
  });

  $('span.noPostcode a').click(function() {
    $('span.noPostcode span').show();
    $(this).parent().parent().find(postcodeField).val('NO POSTCODE');
    return false;
  });
}

function showMiniBasket() {
  $('div#basketView #miniBasketItems caption span').hover(
    function() {
      $('div#basketView').addClass('show');
    },
    function() {}
  );
  $('div#basketView').hover(
    function() {},
    function() {
      $('div#basketView').removeClass('show');
    }
  );
}

function addToWishlist() {
  $.ajaxSetup({
    global: false,
    type: 'GET',
    timeout: 15000
  });
  var addToWishlistPopup = $('<div id="addToWishlistPopup" class="popUp"><h4 /><a class="close" name="close"> x </a><p /></div>');

  $('span.button.wishList.loggedin a').click(function() {

    $(addToWishlistPopup).insertAfter('#miniBasket');
    $(addToWishlistPopup).find('a.close').click(function() {
      closeWishlistPopup();
    });

    $(addToWishlistPopup).css({
      top: $(this).offset().top + $(this).height() + 12 + 'px',
      left: $(this).parent().offset().left - ($(this).parent().width() / 2) + 'px'
    });

    $.ajax({
      dataType: 'json',
      type: 'GET',
      url: $(this).attr('href'),
      beforeSend: function() {
        $(addToWishlistPopup).show().find('h4').text('Please wait');
        $(addToWishlistPopup).find('p').html('');
      },
      success: function(data) {
        $('body').bind('click', closeWishlistPopup);
        $(addToWishlistPopup).show().find('h4').text(data.title);
        $(addToWishlistPopup).find('p').html(data.message);
        scrollToView('div#addToWishlistPopup', 250);
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        var msg = '';
        if (textStatus == 'timeout') {
          msg = 'Our server is taking too long to respond. Your item may still have been added to your wishlist, you may want to check!';
        } else {
          msg = 'An error has occurred. Your item may still have been added to your wishlist, you may want to check!';
        }
        $('body').bind('click', closeWishlistPopup);
        $(addToWishlistPopup).show().find('h4').text('Error');
        $(addToWishlistPopup).find('p').html(msg);
        scrollToView('div#addToWishlistPopup', 250);
      }
    });
    return false;
  });
}

function closeWishlistPopup() {
  $('div#addToWishlistPopup').remove();
  $('body').unbind('click', closeWishlistPopup);
}

function scrollToView(selector, duration) {
  if (duration == null || duration == 0) duration = 1;
  var winScrollPos = $(window).scrollTop() + $(window).height();
  var elBottomPos = $(selector).offset().top + $(selector).height() + 50;
  if (elBottomPos > winScrollPos) {
    var scrollToVal = (elBottomPos - $(window).height());
    $('html,body').animate({scrollTop: scrollToVal}, duration);
  }
}

function om_emailWhenInStock(pIsbn){

  $.weeboxs.open('/browse/emailnotinstock?isbn13='+ pIsbn + '&js_enabled=true' ,
    {contentType:'ajax',
    title:'Email when back in stock',
    position: 'center',
    modal: true,
    height:200,
    width:500,

    showCancel: false,
    showOk: false,
    showButton: false,
    clickClose: true
    }

    );

}

function om_submitEmailWhenInStock(baseUrl,isbn13,email){

  $('#js_enabled').val('true');

  $.ajax({
  type: "POST",
  url: baseUrl + "/browse/emailnotinstock",
  data: {email: email, isbn13: isbn13, js_enabled: $('#js_enabled').val()},
  success: function(data) {

    $('#contact_formWBackInStock').html("<div id='message'></div>");
    $('#message').append(data)
    .append("<small>click outside of this box to cancel</small>")
    .hide()
    .fadeIn(1500, function() {
    $('#message').append("");
    });
  }
  },"json");
  return false;
}

function addToNewsletter() {
  $.ajaxSetup({
    global: false,
    type: 'POST',
    timeout: 15000
  });
  var addToNewsletterPopup = $('<div id="addToNewsletterPopup" class="popUp"><h4 /><a class="close" name="close"> x </a><p /></div>');


  $('button#emailSubscribe').click(function() {

    $(addToNewsletterPopup).insertBefore('#newsletterSignUp');
    $(addToNewsletterPopup).find('a.close').click(function() {
      closeNewsletterPopup();
    });

    $(addToNewsletterPopup).css({
      top: $(this).offset().top + $(this).height() + 12 + 'px',
      left: $(this).parent().offset().left - 0
    });

    $.ajax({
      dataType: 'json',
      type: 'GET',
      url: '/newsletter/add?newsletterEmailAddress='+ encodeURIComponent($('#newsletterEmailAddress').val()),
      beforeSend: function() {
        $(addToNewsletterPopup).show().find('h4').text('Please wait');
        $(addToNewsletterPopup).find('p').html('');
      },
      success: function(data) {
        $('body').bind('click', closeNewsletterPopup);

        if( 0 == data.outcome){
          $(addToNewsletterPopup).show().find('h4').text('Error');
          $(addToNewsletterPopup).find('p').html('Sorry that isn\'t a valid e-mail address, please try again.<br/><br/>Were you trying to search for <a href="/search?searchTerm='+ data.email +'&search=search">'+ data.email +'</a>?');
        }
        if( 1 == data.outcome){
          $(addToNewsletterPopup).show().find('h4').text('Thank you');
          $(addToNewsletterPopup).find('p').html('Thank you - we\'ve added you to the newsletter.');
        }
        if( 2 == data.outcome){
          $(addToNewsletterPopup).show().find('h4').text('Already a member');
          $(addToNewsletterPopup).find('p').html('You\'re already on our newsletter list, if you\'d like to edit your contact preferences you can in <a href="/account/contact">Your account</a>.');
        }

        scrollToView('div#addToNewsletterPopup', 250);

      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        var msg = '';
        if (textStatus == 'timeout') {
          msg = 'Our server is taking too long to respond.';
        } else {
          msg = 'Sorry, we seem to have experienced an error, this has been reported and we\'ll fix it.';
        }
        $('body').bind('click', closeNewsletterPopup);
        $(addToNewsletterPopup).show().find('h4').text('Error');
        $(addToNewsletterPopup).find('p').html(msg);
        scrollToView('div#addToNewsletterPopup', 250);
      }
    });
    return false;
  });
}

function closeNewsletterPopup() {
  $('div#addToNewsletterPopup').remove();
  $('body').unbind('click', closeNewsletterPopup);
}

function emailNotInStock() {
  $.ajaxSetup({
    global: false,
    type: 'POST',
    timeout: 15000
  });
  var emailNotInStockPopup = $('<div id="emailNotInStockPopup" class="popUp"><h4 /><a class="close" name="close"> x </a><p /></div>');


  $('button#notifyMe').click(function() {
    $(emailNotInStockPopup).insertAfter('#miniBasket');
    $(emailNotInStockPopup).find('a.close').click(function() {
      closeEmailNotInStockPopup();
    });

    $(emailNotInStockPopup).css({
      top: $(this).offset().top + $(this).height() + 'px',
      left: $(this).offset().left - ($(this).width() / 2) + 'px'
    });

    $.ajax({
      dataType: 'json',
      type: 'GET',
      url: '/browse/emailnotinstock/?EMWBISemail='+ $('#EMWBISemail').val()+'&EMWBISisbn='+$('#EMWBISisbn').val(),
      beforeSend: function() {
        $(emailNotInStockPopup).show().find('h4').text('Please wait');
        $(emailNotInStockPopup).find('p').html('');
      },
      success: function(data) {
        $('body').bind('click', closeEmailNotInStockPopup);

        if( 0 == data.outcome){
          $(emailNotInStockPopup).show().find('h4').text('Error');
          $(emailNotInStockPopup).find('p').html('Please provide a valid email.');
        }
        if( 2 == data.outcome){
          $(emailNotInStockPopup).show().find('h4').text('Thank you');
          $(emailNotInStockPopup).find('p').html('We will contact you when this item is back in stock.');
        }
        if( 1 == data.outcome){
          $(emailNotInStockPopup).show().find('h4').text('Thank you');
          $(emailNotInStockPopup).find('p').html('We have renewed your request to contact you when this item is back in stock');
        }

        scrollToView('div#emailNotInStockPopup', 250);

      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        var msg = '';
        if (textStatus == 'timeout') {
          msg = 'Our server is taking too long to respond.';
        } else {
          msg = 'An error has occurred.';
        }
        $('body').bind('click', closeEmailNotInStockPopup);
        $(emailNotInStockPopup).show().find('h3').text('Error');
        $(emailNotInStockPopup).find('p').html(msg);
        scrollToView('div#emailNotInStockPopup', 250);
      }
    });
    return false;
  });
}

function closeEmailNotInStockPopup() {
  $('div#emailNotInStockPopup').remove();
  $('body').unbind('click', closeEmailNotInStockPopup);
}

function contactUs() {
  $.ajaxSetup({
    global: false,
    type: 'POST',
    timeout: 15000
  });

  var addToContactUsPopup = $('<div id="addToContactUsPopup" class="popUp"><h4 /><a class="close" name="close"> x </a><p /></div>');

  $('button#contactUs').click(function() {
    $(addToContactUsPopup).insertAfter('#miniBasket');
    $(addToContactUsPopup).find('a.close').click(function() {
      closeContactUsPopup();
    });

    $(addToContactUsPopup).css({
      top: $(this).offset().top + $(this).height() + 12 + 'px',
      left: $(this).parent().offset().left - 0
    });

    $.ajax({
      dataType: 'json',
      type: 'GET',
      url: '/contactus/index/?fullName='+ $('#fullName').val()
                     +'&emailAddress='+encodeURIComponent($('#emailAddress').val())
                   +'&phoneNumber='+encodeURIComponent($('#phoneNumber').val())
                   +'&orderNumber='+encodeURIComponent($('#orderNumber').val())
                   +'&ReciveNewsLetter='+encodeURIComponent($('input[@name=ReciveNewsLetter]:checked').val())
                   +'&queryType='+encodeURIComponent($('#queryType').val())
                   +'&contactUsMessage='+encodeURIComponent($('#contactUsMessage').val())
                   +'&ContactUs=ContactUs'
                   +'&postCode='+encodeURIComponent($('#postCode').val()),
      beforeSend: function() {
        $(addToContactUsPopup).show().find('h4').text('Please wait');
        $(addToContactUsPopup).find('p').html('');
      },
      success: function(data) {
        $('body').bind('click', closeContactUsPopup);

        if( 1 == data.outcome){
          $('#fullName').val('');
          $('#emailAddress').val('');
          $('#phoneNumber').val('');
          $('#orderNumber').val('');
          $('input[@name=ReciveNewsLetter][@value=yes]').attr("checked","checked");
          $('#queryType').val('');
          $('#contactUsMessage').val('');
          $('#postCode').val('');

          $(addToContactUsPopup).show().find('h4').text('Thank you');
          $(addToContactUsPopup).find('p').html('Thank you - your message has been sent successfully.');
        }
        if( 8 == data.outcome){
          $(addToContactUsPopup).show().find('h4').text('Invalid Email');
          $(addToContactUsPopup).find('p').html('Invalid Info - Please provide your email Or<br /> check email entered.');
        }
        if( 5 == data.outcome || 7 == data.outcome ){
          $(addToContactUsPopup).show().find('h4').text('Missing Email or Phone');
          $(addToContactUsPopup).find('p').html('Missing Info - Please provide either your email or phone number.');
        }
        if( 6 == data.outcome){
          $(addToContactUsPopup).show().find('h4').text('Missing Message');
          $(addToContactUsPopup).find('p').html('Missing Message - Please type in the message you would like to send.');
        }

        scrollToView('div#addToContactUsPopup', 250);

      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        var msg = '';
        if (textStatus == 'timeout') {
          msg = 'Our server is taking too long to respond.';
        } else {
          msg = 'An error has occurred.';
        }
        $('body').bind('click', closeContactUsPopup);
        $(addToContactUsPopup).show().find('h4').text('Error');
        $(addToContactUsPopup).find('p').html(msg);
        scrollToView('div#addToContactUsPopup', 250);
      }
    });
    return false;
  });
}

function closeContactUsPopup() {
  $('div#addToContactUsPopup').remove();
  $('body').unbind('click', closeContactUsPopup);
}

function showHideCardAddress() {
  if ('old' == $('input#oldAddressSelected:checked').val()) {
    $('#newCardAddress').hide();
  } else {
    $('#newCardAddress').show();
  }
  $('input[@name="addressChoiceSelected"]').click(function() {
    ($('input[@name="addressChoiceSelected"]:checked').val() == 'old') ? $("#newCardAddress").slideUp('fast') : $("#newCardAddress").slideDown('fast');
  });
}

function addClassGooglePreviewButton() {
	$('span#__GBS_Button0').wrap('<div id="googlePreview"></div>');
}

function checkoutSingleSubmit()
{
	$("#checkoutForm").submit(function() {
		$("button.confirmOrder").each(function() {
			$(this).replaceWith("<span class='processing'>processing, please wait...</span>");
		});
	});

	$('.confirmOrder .button.order').click(function() {
		$('.confirmOrder .button.order').each(function() {
			$(this).replaceWith("<span class='processing'>processing, please wait...</span>");
		});
	});
}

function setTextAreaMaxLength ()
{
	if ($("body.raf #frmMessage").length)
	{
		var charsRemaining = 200 - $("body.raf #frmMessage").val().length;
		$('#charsRemaining').html(charsRemaining.toString());
		if (charsRemaining < 0)
		{
			$('#charsRemaining').css('color', 'red');
		}
		else
		{
			$('#charsRemaining').css('color', 'black');
		}

		var countText = function() {
			var charsRemaining = 200 - $(this).val().length;
			$('#charsRemaining').html(charsRemaining.toString());
			if (charsRemaining < 0)
			{
				$('#charsRemaining').css('color', 'red');
			}
			else
			{
				$('#charsRemaining').css('color', 'black');
			}
		};

		$("body.raf #frmMessage").bind('change keyup paste click', countText);
	}
}

$(function() {
    $("strong.expand").toggler();
	$("p.expand").toggler();
});

function windowifyLinks()
{
	$('.blank480').unbind('click');
	$('.blank480').click(function(){
    window.open(this.href, null,'height=480,width=640');
    return false;
    });
}


function ajaxableLinks()
{
	$('a.ajaxable').unbind('click');
	$('a.ajaxable').click(function(e) {
		e.preventDefault();
		link = $(this).attr("href");
		$(this).hide();
		$('.ajaxable_complete', $(this).parent()).show();
		$.ajax( {url: link});
	});
}

function GWOeventTracking()
{
    $(".linkSurround.button.wishList a").click(function(){
		try{pageTracker._trackEvent('Wishlist', 'Save item')}catch(err){}return true;
    });
    $(".linkSurround.button.amazon a").click(function(){
		try{pageTracker._trackEvent('Amazon link', 'buy', button_image)}catch(err){}return true;
    });
				$("#content.bookFull div.contentBlock.columns1 span.tab a").click(function(){
					try{pageTracker._trackEvent('Block 1-cols', 'tab', 'Full book')}catch(err){}return true;
				});
				$("#content.bookFull div.contentBlock.columns5 span.tab a").click(function(){
					try{pageTracker._trackEvent('Block 5-cols', 'tab', 'Full book')}catch(err){}return true;
				});
				$("#content.bookFull div.contentBlock.columns5 .jcarousel-next").click(function(){
					try{pageTracker._trackEvent('Block 5-cols', 'arrow right', 'Full book')}catch(err){}return true;
				});
				$("#content.bookFull div.contentBlock.columns5  .jcarousel-prev").click(function(){
					try{pageTracker._trackEvent('Block 5-cols', 'arrow left', 'Full book')}catch(err){}return true;
				});
				$("#content.home div.contentBlock.columns1 span.tab a").click(function(){
					try{pageTracker._trackEvent('Block 1-col', 'tab', 'Homepage')}catch(err){}return true;
				});
				$("#content.home div.contentBlock.columns2.rows2 span.tab a").click(function(){
					try{pageTracker._trackEvent('Block 2-cols 2-rows', 'tab', 'Homepage')}catch(err){}return true;
				});
				$("#content.home div.contentBlock.columns2.rows2 .jcarousel-next").click(function(){
					try{pageTracker._trackEvent('Block 2-cols 2-rows', 'arrow right', 'Homepage')}catch(err){}return true;
				});
				$("#content.home div.contentBlock.columns2.rows2 .jcarousel-prev").click(function(){
					try{pageTracker._trackEvent('Block 2-cols 2-rows', 'arrow left', 'Homepage')}catch(err){}return true;
				});
				$("#content.home div.contentBlock.columns5 span.tab a").click(function(){
					try{pageTracker._trackEvent('Block 5-cols', 'tab', 'Homepage')}catch(err){}return true;
				});
				$("#content.home div.contentBlock.columns5 .jcarousel-next").click(function(){
					try{pageTracker._trackEvent('Block 5-cols', 'arrow right', 'Homepage')}catch(err){}return true;
				});
				$("#content.home div.contentBlock.columns5 .jcarousel-prev").click(function(){
					try{pageTracker._trackEvent('Block 5-cols', 'arrow left', 'Homepage')}catch(err){}return true;
				});
				$("#content.categories div.contentBlock.columns2.rows1 span.tab a").click(function(){
					try{pageTracker._trackEvent('Block 2-cols 1-row', 'tab', 'Category')}catch(err){}return true;
				});
				$("#content.categories div.contentBlock.columns2.rows1 .jcarousel-next").click(function(){
					try{pageTracker._trackEvent('Block 2-cols 1-row', 'arrow right', 'Category')}catch(err){}return true;
				});
				$("#content.categories div.contentBlock.columns2.rows1  .jcarousel-prev").click(function(){
					try{pageTracker._trackEvent('Block 2-cols 1-row', 'arrow left', 'Category')}catch(err){}return true;
				});
				$("#content.categories div.contentBlock.columns2.rows2 span.tab a").click(function(){
					try{pageTracker._trackEvent('Block 2-cols 2-rows', 'tab', 'Category')}catch(err){}return true;
				});
				$("#content.categories div.contentBlock.columns2.rows2 .jcarousel-next").click(function(){
					try{pageTracker._trackEvent('Block 2-cols 2-rows', 'arrow right', 'Category')}catch(err){}return true;
				});
				$("#content.categories div.contentBlock.columns2.rows2  .jcarousel-prev").click(function(){
					try{pageTracker._trackEvent('Block 2-cols 2-rows', 'arrow left', 'Category')}catch(err){}return true;
				});
				$("#content.categories div.contentBlock.columns5 span.tab a").click(function(){
					try{pageTracker._trackEvent('Block 5-cols', 'tab', 'Category')}catch(err){}return true;
				});
				$("#content.categories div.contentBlock.columns5 .jcarousel-next").click(function(){
					try{pageTracker._trackEvent('Block 5-cols', 'arrow right', 'Category')}catch(err){}return true;
				});
				$("#content.categories div.contentBlock.columns5  .jcarousel-prev").click(function(){
					try{pageTracker._trackEvent('Block 5-cols', 'arrow left', 'Category')}catch(err){}return true;
				});
				$("#content.bestsellers div.contentBlock.columns2.rows1 span.tab a").click(function(){
					try{pageTracker._trackEvent('Block 2-cols 1-row', 'tab', 'Bestsellers')}catch(err){}return true;
				});
				$("#content.bestsellers div.contentBlock.columns2.rows1 .jcarousel-next").click(function(){
					try{pageTracker._trackEvent('Block 2-cols 1-row', 'arrow right', 'Bestsellers')}catch(err){}return true;
				});
				$("#content.bestsellers div.contentBlock.columns2.rows1  .jcarousel-prev").click(function(){
					try{pageTracker._trackEvent('Block 2-cols 1-row', 'arrow left', 'Bestsellers')}catch(err){}return true;
				});
				$("#content.bestsellers div.contentBlock.columns2.rows2 span.tab a").click(function(){
					try{pageTracker._trackEvent('Block 2-cols 2-rows', 'tab', 'Bestsellers')}catch(err){}return true;
				});
				$("#content.bestsellers div.contentBlock.columns2.rows2 .jcarousel-next").click(function(){
					try{pageTracker._trackEvent('Block 2-cols 2-rows', 'arrow right', 'Bestsellers')}catch(err){}return true;
				});
				$("#content.bestsellers div.contentBlock.columns2.rows2  .jcarousel-prev").click(function(){
					try{pageTracker._trackEvent('Block 2-cols 2-rows', 'arrow left', 'Bestsellers')}catch(err){}return true;
				});
				$("#content.bestsellers div.contentBlock.columns5 span.tab a").click(function(){
					try{pageTracker._trackEvent('Block 5-cols', 'tab', 'Bestsellers')}catch(err){}return true;
				});
				$("#content.bestsellers div.contentBlock.columns5 .jcarousel-next").click(function(){
					try{pageTracker._trackEvent('Block 5-cols', 'arrow right', 'Bestsellers')}catch(err){}return true;
				});
				$("#content.bestsellers div.contentBlock.columns5  .jcarousel-prev").click(function(){
					try{pageTracker._trackEvent('Block 5-cols', 'arrow left', 'Bestsellers')}catch(err){}return true;
				});
				$("#content.searchResults div.contentBlock.columns5 span.tab a").click(function(){
					try{pageTracker._trackEvent('Block 5-cols', 'tab', 'Search results')}catch(err){}return true;
				});
				$("#content.searchResults div.contentBlock.columns5 .jcarousel-next").click(function(){
					try{pageTracker._trackEvent('Block 5-cols', 'arrow right', 'Search results')}catch(err){}return true;
				});
				$("#content.searchResults div.contentBlock.columns5  .jcarousel-prev").click(function(){
					try{pageTracker._trackEvent('Block 5-cols', 'arrow left', 'Search results')}catch(err){}return true;
				});
		$("#miniBasket .linkSurround.checkout a").click(function(){
			try{pageTracker._trackEvent('Route to basket', 'basket - header')}catch(err){}return true;
		});
}
