//-------------------------------------------
//    jQuery:  Initialisation.  Put all your calls in here
//-------------------------------------------

$('html').addClass('js');
var imagePopupActive = false;
$(document).ready(function(){
  initCarousels();
  //$('html').removeClass('js');
  //textboxDefault('input#bookSearch', 'keyword/book title/author/ISBN');
  //textboxDefault('input#bookSearch404', 'keyword/book title/author/ISBN');
 
  
  addToBasket();
  basketCheckoutButton();
  formatSelector();
  addToNewsletter();
  addToWishlist();
  emailNotInStock();
  showMiniBasket();
  // contactUs();
  //cardSwitcher();
  showHideCardAddress();
  noPostcode('select#countryCode', 'input#postCode');
  initMeetTheAuthor();
  openNewWindow(); //facebook links get overwritten later.
  openChat(); // Livechat
  addClassGooglePreviewButton();
  checkoutSingleSubmit();
  //defaultFocus();
  GWOeventTracking();

  setTextAreaMaxLength();
  windowifyLinks();

  ajaxableLinks();

	$(".image.large").click( function() {
        if($("#large_image_popup").attr("src")){
            return false;
        }else{
	    if(!$('#is_noImage').length) // Large no jacket images should not be accessible
	    {
		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 initMeetTheAuthor(){
	//typeof('undefined' ! = renderMta)
	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 )
{
  //alert( "Setting focus to: " + fieldId );
  $( "#" + fieldId ).focus();
}

//function defaultFocus ()
//{
//    $('#bookSearch').focus();
//    $('.fullBook .linkSurround.button.buy a').focus();
//    $('.fullBook input#EMWBISemail').focus();
//    $('#account.logIn input#username').focus();
//    $('input#reviewTitle').focus();
//    $('tfoot button.checkout.GB').focus();
//    $('input#contactEmail').focus();
//    $('.summary.loggedIn input#cardCcv').focus();
//    $('#changeDetails input#firstName').focus();
//    $('input#currentPassword').focus();
//    $('input#userImage').focus();
//    $('input#referenceName').focus();
//    $('input#reference').focus();
//    $('input#orderNumber').focus();

//}

function roundAmazonCorners()
{
  //<p class="priceBlock alternative amazonPrice">
  $('.priceBlock.alternative.amazonPrice').corner();
}

function initCarousels()
{
	//console.log( "Loading Carousels...");

	$('.address .mycarousel').jcarousel({
		scroll: 1,
		moduleWidth: 290,
		rows:4,
		cols:10,
		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'
	});

	//console.log( "Carousels Loaded OK" );
}


function updateNext( carousel )
{
	//carousel.first += carousel.options.scroll;
	updateScrollValue( carousel );
}

function updatePrev( carousel )
{
	updateScrollValue( carousel );
}


function loadMore( carousel )
{
	//console.log( "Loading more...?" );
}


function mycarousel_itemLoadCallback(carousel, state)
{	//return;
	var carId = carousel.list.attr("id");
	var carData = carId.split( ':' );
	//	console.log( "Id size = " + carData[0] );
	//	console.log( "Initial size = " + carousel.size() );
	//	console.log( "Cache id = " + carData[1] );
	carousel.size( carData[1] );
	carousel.cacheId = carData[0];
	//	console.log( "Final size = " + carousel.size() );
	//	console.log( "Final cache = " + carousel.cacheId );

	//console.log( "Current First = " + carousel.first );
	//console.log( "Current Last = " +  ( carousel.first + ( carousel.options.rows * carousel.options.cols ) - 1 ) );



    // Check if the requested items already exist
    //if (carousel.has(carousel.first, carousel.last)) {
	if( undefined != carousel.fakeLast )
	{
		var nextLiFirst = carousel.fakeLast;
		var nextLiLast = nextLiFirst + carousel.options.scroll;
		//console.log( "LI Pos to Load First = " + nextLiFirst );
		//console.log( "LI Pos to Load Last = " + nextLiLast );

		if( carousel.has( nextLiFirst, nextLiLast ) )
		{
			//console.log( "Carousel has items index: " + nextLiFirst + " to " +nextLiLast );
			//console.log( "Unlocking" );
			carousel.unlock();
			return;
		}
	}
	else
	{
		var nextLiFirst = carousel.list.children('li').size();
		//console.log( "Undefined LI Pos to Load First = " + nextLiFirst );
	}

	// Calculate which items we actually want to show based on dimensions
	var firstMod = ( carousel.first + ( carousel.options.rows * carousel.options.cols ) );
	var lastMod = firstMod + ( carousel.options.scroll * carousel.options.rows ) - 1;

	//firstMod += carousel.options.rows;
	//console.log( "First module load id = " + firstMod );
	//console.log( "Last module load id = " + lastMod );
	//console.log( "Size = " + carousel.size() );

	if( firstMod <= carousel.size() )
	{
		// Perform the ajax call
		$.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();
	//	console.log( "Nothing to load");
	//updateScrollValue( caoursel );

	//console.log( "Unlocking" );

}

function mycarousel_itemAddCallback( carousel, moduleHtml, nextLiFirst )
{	//return;
	//var firstMod = ( carousel.first + ( carousel.options.rows * carousel.options.cols ) );
	//var insertPos = carousel.fakeFirst + carousel.options.cols;
	var insertPos = nextLiFirst;
	//console.log( "LI Insert Pos = " + insertPos );


	var extendCount = 0;
	var addHtml = '';

	//console.log( "Items to add: " + moduleHtml.length );
	//console.log( "Rows :" + carousel.options.rows );

	var additionIndex = 0;
	$.each( moduleHtml, function(i, val) {
		//debugger;
		//console.log( "Adding item at position: " + ( firstMod + i ) );
		addHtml += val;
		extendCount++;

		//console.log( "Count = " + extendCount + " Mod = " + ( extendCount % carousel.options.rows ) );
		if( 0 == ( extendCount % carousel.options.rows ) || ( extendCount == moduleHtml.length ) )
		{
			carousel.add( insertPos + additionIndex, addHtml );
			//console.log( "Added li at position: (i= " + additionIndex + ")" + ( insertPos + additionIndex ) );
			addHtml = '';
			additionIndex++;
		}
	} );

	//console.log( "Container = " + carousel.container );

	/*var matches = carousel.list.children();
	$.each( matches,
		function myfunc (i, data)
		{
			//console.log( "Item: " + i + "->" + data );
		}
	);*/


	/*var cName = carousel.className('jcarousel-item-placeholder');
	var matches = carousel.list.children();
	$.each( matches,
		function myfunc (i, data)
		{
			var placeholder = stristr( data.className, 'placeholder' );
			if( placeholder.length > 0 )
			{
				alert("Invalid item : " + i + " -> " + data.className );
				carousel.remove( i + 1 );
			}
		}
	);*/

	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 )
{ //return;
	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 step = carousel.options.scroll * carousel.options.rows;

	//console.log( "size = :" + carousel.size() );
	/*
	if( 1 != step )
	{
		if( firstMod > 1 )
			firstMod = ( carousel.first * step ) - 1;
	}*/

	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() );

	//console.log("[Update Scroll]First:"+firstMod+" Last:"+lastMod);
	//console.log( "Updated Scroll Value")
}



function updateScrollValue_old( carousel )
{
	//console.log( "---------------------------" );

	// Grab count of items in carousel
	var li = carousel.size(); //carousel.list.children('li');
	//				console.log( "Last:" + this.last );
	//console.log( "Size:" + li );
	//console.log( "LI Length = " + li.length );

	var contentBlock = carousel.list.parent().parent().parent().parent();
	//console.log( "Found contentBlock parent with class: " + contentBlock.attr('class') );

	var scrollValue = contentBlock.children('.scrollValue');
	//console.log( "Found scrollValue with class of: " + scrollValue.attr('class' ) + " Len: " + scrollValue.length );

	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;
	//console.log( "Rows = " + carousel.options.rows + " Cols = " + carousel.options.cols );
	//console.log( "Modules Visible: " + modsVisible );

	var lastMod = firstMod + modsVisible - 1;
	if( lastMod > li.length )
		lastMod = li.length;

	first.text( firstMod );
	last.text( lastMod );
	count.text( li );
	//count.text( li.length );


	//console.log( "Found first item with value: " + first.text() );
}









