/*
 * File: main.js
 * Description: Main Javascript functionality for the site
 */

 // Global
var loading_graphic = '<img src="/assets/style/images/ajax-loader.gif" alt="loading"/>&nbsp;';

var basket_count = 0;

// for debugging:
var log;
if (window.console && console.log){
	log = console.log;
}else{
	log = function (data){};
}

// -----------------------------------------------------------------------------
// Function: initHumanTest
// Description: Attaches listeners to registration/login forms for spam prevention
// -----------------------------------------------------------------------------
function initHumanTest()
{

	var myForms = $('form#new_user, form#form_login, form#form_login_singlebox');

	for (var i=0; i< myForms.length; i++) {

		$('input',myForms[i]).bind('focus', markAsHuman);
		$('input',myForms[i]).bind('click', markAsHuman);
  }
}

function markAsHuman(event){

	// get the form this element is in
	var form_id = $(event.target).closest('form').attr('id');

	$('#' + form_id + '_iamhuman').val('iamhumaniamnotspam');
}

// ------------------------------------
// Function: getCurrentBasketPrice
// Description: setter
// ------------------------------------
function setCurrentBasketPrice($basket, new_price)
{

	if(isNaN(new_price)){
		new_price = Number(new_price);
	}

  $("#basket_price", $basket).text("£"+new_price.toFixed(2));
}

// ------------------------------------
// Function: setCurrentBasketCount
// Description: setter
// ------------------------------------
function setCurrentBasketCount($basket, count)
{
  $("#basket_count", $basket).text(count);
}

// ------------------------------------
// Function: showPurchaseDetails
// Description: Show an purchased item in the basket
// ------------------------------------
function showPurchaseDetails($basket, chapter_num, chapter_price, all_chapters_added, chapters_added, license_duration, isAdded, pageX, pageY)
{

	$('#added_item #added_book_title').text($("#book_details h1").text());
	$('#added_item img').attr('src',$("#book_details img").attr('src'));
	$('#added_item img').attr('alt',$("#book_details img").attr('alt'));

	if(isAdded){
		$('#added_item #transaction_type').text('ADDED');
	}else{
		$('#added_item #transaction_type').text('REMOVED');
	}

	if(chapter_num){
		$('#added_item #added_chapter_type').text('Chapter Number');
		$('#added_item #added_chapter_num').text(chapter_num);
	}
	if(isAdded && all_chapters_added){
		$('#added_item #added_chapter_type').text('Chapters Added');
		$('#added_item #added_chapter_num').text(chapters_added);
	}
	if(!isAdded && all_chapters_added){
		$('#added_item #added_chapter_type').text('Chapters Removed');
		$('#added_item #added_chapter_num').text(chapters_added);
	}

	$('#added_item #added_license').text(license_duration+' months');
	$('#added_item #added_price').text(chapter_price.toFixed(2));

	// position it
	var height = $('#added_item').height() + 10;
  var width = $('#added_item').width() + 10 ;
  //calculating offset for displaying popup message
  leftVal = pageX-(width)+"px";
  topVal = pageY-(height)+"px";


	$('#added_item').css('left',leftVal).css('top',topVal);

	$("#added_item").stop(true,false).fadeIn('fast');

	if (typeof Flexpaper !== "undefined") {
			$('#get_access').addClass('basket');
	}

	setTimeout(function(){
		close_basket_item_added();
	}, 4000);

}

// ----------------------------------
// Function: close_basket_item_added
// Description: Handle animation on adding to basket
// ----------------------------------
function close_basket_item_added()
{
	// if on the book reader page, then after hiding the div, also hide the Get Access div
	if (typeof Flexpaper !== "undefined") {
		$('#added_item').clearQueue().slideUp('fast',function(){
				$('#get_access').slideUp('fast');
		});
	}else{
		$('#added_item').clearQueue().slideUp('fast');
	}
}

// ------------------------------------
// Function: addToBasket
// Description: Handle adding to basket
// ------------------------------------
function addToBasket(chapter_id, book_id, license_duration, add_remaining_chapters, pageX, pageY)
{
	var site_base = Config.base_url;

  // Send to Controller
  $.ajax({url: site_base + "basket/ajax_add_to_basket",
		type: "POST",
		dataType: "json",
		data: {
						 add_remaining_chapters:add_remaining_chapters,
						 chapter_id: chapter_id,
						 book_id:book_id,
						 length: license_duration
					 },
		success: function(data)
						 {
							 if(data.result=='ok'){

								 $basket = $('#basket');

								 // change the visuals to show what's in the basket
								 // Book added
								 if(data.chapter_id==null){

									 // Set the chapters for the selected license to be purchased
									 $('.buy_chapter_btn[data-license='+data.cart_item_license+']').addClass('checked');
									 $('.buy_chapter_btn[data-license!='+data.cart_item_license+']').removeClass('checked');


									 $('.buy_book_btn[data-license='+data.cart_item_license+']').addClass('checked');
									 $('.buy_book_btn[data-license!='+data.cart_item_license+']').removeClass('checked');

								 }
								 // Chapter added
								 else
								 {

								 	 // Have we received the message to prompt the user to add the whole ebook to the basket?
								 	 // This happens if the value of the chapters in the cart is now greater than the whole ebook price
								 	 if(data.prompt_whole_ebook_purchase){

								 	 	 // set the saving amount
								 	 	 $('.amount_saved_value').html(data.whole_ebook_saving);
								 	 	 // Trigger the modal
								 	 	 $.fn.colorbox({
												inline:true,
												href:'#basket_save_money_form_dialog',
												returnFocus:false,
												overlayClose:false,
												escKey:false,
												onLoad:function(){

													$('#basket_save_money a#save_money_yes').unbind('click');
													$('#basket_save_money a#save_money_yes').bind('click',function(event) {

															addToBasket(0, data.book_id, data.cart_item_license, 1);

															event.preventDefault();
															$.fn.colorbox.close();
													});
												}

										});
								 	 }


								 	 $('.buy_chapter_btn[data-license='+data.cart_item_license+'][data-chapter_id='+data.chapter_id+']').addClass('checked');
								 	 $('.buy_chapter_btn[data-license!='+data.cart_item_license+'][data-chapter_id='+data.chapter_id+']').removeClass('checked');

									 // the book options must be unchecked once chapter buying is selected
									 $('.buy_book_btn').removeClass('checked');
								 }

								 setCurrentBasketCount($basket, data.cart_total_items);
								 setCurrentBasketPrice($basket, data.cart_total_price);
								 showPurchaseDetails($basket, data.chapter_num, data.cart_item_price, data.all_chapters_added, data.chapters_added, license_duration, true, pageX, pageY);

							 }else{
								 alert("Something went wrong and we couldn't add your item to the basket!");
							 }
						 },
		error: function(data)
						{
							//log(data);
						}
  });

}

// ----------------------------------------
// Function: removeFromBasket
// Description: Handle removing from basket
// ----------------------------------------
function removeFromBasket(chapter_id, book_id, license_duration, remove_all_chapters, pageX, pageY)
{
	var site_base = Config.base_url;

  // Send to Controller via ajax
  $.ajax({url: site_base + "basket/ajax_remove_from_basket",
          type: "POST",
          dataType: "json",
          data: {
									remove_all_chapters:remove_all_chapters,
									chapter_id:chapter_id,
									book_id:book_id,
                  length: license_duration
                },
          success: function(data)
                   {
                     if(data.result=='ok'){

                     	 $basket = $('#basket');

											 // Book removed - update the page visuals
											 if(data.chapter_id==null || data.chapter_id==0){

													// Re-show the prices of the chapters for the selected license
													$('.buy_chapter_btn[data-license='+license_duration+']').removeClass('checked');
													$('.buy_chapter_btn[data-license!='+license_duration+']').removeClass('deactivated');
													$('.buy_book_btn[data-license='+data.cart_item_license+']').removeClass('checked');
											 }
											 // Chapter removed - update the page visuals
											 else
											 {
												 $('.buy_chapter_btn[data-license='+data.cart_item_license+'][data-chapter_id='+data.chapter_id+']').removeClass('checked');

												 $('.buy_book_btn[data-license='+data.cart_item_license+']').removeClass('checked');
											 }

											 setCurrentBasketCount($basket, data.cart_total_items);
											 setCurrentBasketPrice($basket, data.cart_total_price);
											 showPurchaseDetails($basket, data.chapter_num, Number(data.cart_item_price), data.all_chapters_removed, data.chapters_removed, license_duration, false, pageX, pageY);

                     }else{
                     	 alert('error');
                     }
                   },
          error: function(data)
                  {
                    //log(data);
                  }
        });
}

// -------------------------------------------
// Add to basket / book clicked
// -------------------------------------------
function buyBookClicked(event)
{
	var data = event.data;

	event.preventDefault();
	event.stopPropagation();

	book_id = $('#book_details').attr('data-book_id');
	license_duration = $(this).attr('data-license');
	chapter_id = 0;

	if(data.once_only == true && $(this).hasClass('checked')){
		alert('This book is already in your basket');
	}else{
		// if we're adding the whole book (6 or 12) then we empty the basket first as some
		// chapters might be in it already
		if (!$(this).hasClass("checked")){
			addToBasket(chapter_id, book_id, license_duration, 1, event.pageX, event.pageY);
		}else{
			removeFromBasket(chapter_id, book_id, license_duration, 1, event.pageX, event.pageY);
		}
	}
}
// -------------------------------------------
// Add to basket / price click
// -------------------------------------------
function buyChapterClicked(event)
{
	event.preventDefault();
	event.stopPropagation();

	book_id = $('#book_details').attr('data-book_id');
	chapter_id = $(this).attr('data-chapter_id');
	license_duration = $(this).attr('data-license');
	empty_basket_first = false;

	// not in the basket
	if (!$(this).hasClass("checked"))
	{
		addToBasket(chapter_id, book_id, license_duration, 0, event.pageX, event.pageY);
	}
	// already in the basket - remove it
	else
	{
		removeFromBasket(chapter_id, book_id, license_duration,0, event.pageX, event.pageY);
	}
	//$(this).toggleClass('checked');
}


// -----------------------------------------------------------------------------
// Function: initPricing
// Description: Handles the UI interaction of the pricing module
// -----------------------------------------------------------------------------
function initPricing()
{

	// Read tooltips
	$('#chapter_pricing tr.owned td.popout').tooltip({
		tip:'#read_chapter_tooltip',
		delay:0,
		relative:true,
		position:'top right',
		offset:[5,-20]
	});

	// print limit tooltip
	$('#print_limit').tooltip({
		tip:'#print_limit_tooltip',
		delay:0,
		relative:true,
		position:'bottom right',
		offset:[130,-40]
	});

	// Liverpool library tooltip
	$('#liverpool_library').tooltip({
		tip:'#liverpool_library_tooltip',
		delay:0,
		relative:true,
		position:'bottom right',
		offset:[120,-40]
	});

	// Show more chapters button for when whole ebook is in effect
	$('#view_more_chapters').click(function(e){
			e.preventDefault();

			$('#chapter_pricing tr.hidden').toggle();

			if($('#view_more_chapters').hasClass('showing_more')){
				$(this).text('View more chapters');
				$(this).removeClass('showing_more');
			}else{
				$(this).text('View less chapters');
				$(this).addClass('showing_more');
			}


	});


	/* Initialise the events - some buttons might be deactivated */
	$('#chapter_pricing .buy_chapter_btn:not(.deactivated)').live('click',buyChapterClicked);
	$('#chapter_pricing .buy_book_btn:not(.deactivated)').live('click',{once_only:false},buyBookClicked);
	$('#book_add_to_basket .buy_book_btn:not(.deactivated)').live('click',{once_only:true},buyBookClicked);

	$('.buy_chapter_btn.deactivated').live('click',function(e){
			e.preventDefault();
	});
	$('.buy_book_btn.deactivated').live('click',function(e){
			e.preventDefault();
	});

}

// -----------------------------------------------------------------------------
// Function: initBasketTable
// Description: Handles the Basket Table - hover overs and previews
// -----------------------------------------------------------------------------
function initBasketTable(basket_table)
{
	$(basket_table + ' #apply_promotion_button').click(function(e){
			e.preventDefault();
			$('#promotion_form').submit();
	});

  basket_table += " ";

  // Handle "show preview button" effect
  $(basket_table + "tbody td:not(.no_preview)").mouseover(
  function()
  {
    //$(this).prev("td.preview").text("click to read chapter");
    $(basket_table + "tbody tr.active").removeClass("active"); //  remove active from existing row
    $(this).parent("tr").addClass("active"); // add active to the parent row
  });

  $(basket_table + "tbody tr.active").live("mouseout",
  function()
  {
    //console.log("off active row");
    $(basket_table + "tbody tr.active").removeClass("active"); //  remove active from existing row
  });

  // Keep cursor as default when hover over preview site
  /*$(basket_table + "tbody tr td, "+basket_table + "tbody tr td a").mouseover( function(event) {
	$(this).css({"cursor": "default"});
  });
  // Prevent preview lightbox for basket
  $(basket_table + "tbody tr td a").live("click", function(event) {
    event.preventDefault();
  });*/

}

// -----------------------------------------------------------------------------
// Function: initPromotionHandler
// Description: Handles the promotion codes
// -----------------------------------------------------------------------------
function initPromotionHandler()
{
  $('#promotion').blur(function() {
    $that = this;
    // length check
    if ($(this).val().length)
    {
      $('#promotion_response').remove();

      promo_text = '<div id="promotion_response" class="loading">'+loading_graphic+'</div>';
      $(promo_text).insertAfter('#promotion');

      // get promotion code from db
      $.post('/basket/ajax_get_promotion_details',
           {
             code: $($that).val()
           },
         function (response_data)
         {
           // remove eisting promotion response
           $('#promotion_response').remove();

           if (response_data.result_code == 'success')
           {
             $('<div id="promotion_response" class="discount">Total Discount: -£'+response_data.discount+'</div>').insertAfter('#promotion');
           }
           else
           {
             promo_text = '<div id="promotion_response" class="error">'+response_data.message+'</div>';
             $(promo_text).insertAfter('#promotion');
           }
         },
         'json');
    }
    // show discount and total price
  });
}

// -----------------------------------------------------------------------------
// Function: initGatewaysForm
// Description: Changes action to which payment gateways form is submitted to
//              dependent on gateway selected by user
// -----------------------------------------------------------------------------
function initGatewaysForm(selector){

  var Form = {
    form:    $(selector),
    radios:  $(selector).find('p.gateway input[type="radio"]'),
    update:  function() {
      var radio_checked = this.radios.filter(':checked');

      // Disable all hidden fields
      this.form.find("input[type='hidden']").attr('disabled', true);

      // Enable hidden fields for selected gateway
      radio_checked.parents('p[data-action]').find("input[type='hidden']").attr('disabled', false);

      // Set form action to that of selected gateway
      radio_checked.parents('form').attr('action', radio_checked.parents('p[data-action]').attr('data-action'));
    }
  };

  Form.update();
  Form.radios.change(function() {
    Form.update();
  });
}

// -----------------------------------------------------------------------------
// Function: initBookCitations
// Description: Handles the book citations event
// -----------------------------------------------------------------------------
function initBookCitations()
{
  // set up copy to clipboard functionality
  /*copy_clip.setHandCursor(true);
  copy_clip.glue('copy_citation', 'copy_citation_container');
  copy_clip.hide();*/

  // handle the get citation value
  $('#get_citation').click(function(event) {

    var citation_type = $('.citation_body #format select').val();

    if (citation_type != '')
    {
      // get data for citations
      var author = $('#book_details .author').html();
      var year = $('#book_details .date').html();
      var title = $('#book_details h1').html();
      var printed_location = $('#book_details .where_published span').html();
      var publisher = $('#book_details .publisher span').html();
      var page_range = $('#citation_page_range input').val();
      var pp_test = new RegExp('[0-9]+-[0-9]+', 'g');
      var p_test = new RegExp('[0-9]+', 'g');
      if (!pp_test.test(page_range) && !p_test.test(page_range))
      {
        page_range = '';
      }
      var citation_str = '';

      // prepare the citation string
      switch (citation_type)
      {
        case 'Harvard':
          citation_str = author + ' (' + year + ').' + ' ' + title + ', ' + printed_location + ": " + publisher;

          if (page_range != null)
          {
            citation_str += ' pp. ' + page_range;
          }
          break;
        default:citation_str = 'default';
      }

      // add copy text
      var copy_clip = new ZeroClipboard.Client();
      copy_clip.setHandCursor(true);
      copy_clip.setText(citation_str);

      // remove any existing copy clip
      $('#cclip').remove();

      // add the copy clip
      $('#copy_citation').after('<div id="cclip">');
      $('#cclip').append(copy_clip.getHTML(126, 24));

      // display
      $('#citation_result #the_citation').html(citation_str);
      $('#citation_result').css('opacity', 1);
    }
    event.preventDefault();
    return false;
  });

}

// -----------------------------------------------------------------------------
// Function: initSynopsis
// Description: Handles the Synopsis expand/collapse
// -----------------------------------------------------------------------------
function initSynopsis(synopsis_control, synopsis)
{
  synopsis_control += " ";
  $(synopsis_control + "a").click(function() {
    if ($(this).text() == "Hide")
    {
      $(this).text("Show");
      $(synopsis).slideUp("fast");
    }
    else
    {
      $(this).text("Hide");
      $(synopsis).slideDown("fast");
    }

    return false;
  });
}

// -----------------------------------------------------------------------------
// Function: initBookListActions
// Description: Handles the Book List actions
// -----------------------------------------------------------------------------
function initBookListActions(book_list)
{
  book_list += " ";

  // read book drop down
  $(book_list + ".book_actions > ul > li > a").click(function(event) {

  		if(!$('body').hasClass('reader_no_chapters')){
			event.preventDefault();

			// drop down the list if it's up
			$dropdown = $(this).parent().children("ul");
			if ($($dropdown).hasClass("open"))
			{
				$($dropdown).slideUp("fast").removeClass("open");
				$($dropdown).parents(".book_list_item").removeClass("current");
			}
			else
			{
				// close any existing menus
				$(book_list + ".book_actions .open").slideUp("fast").removeClass("open");

				// open the clicked on menu
				$($dropdown).addClass("open").slideDown("fast");
				$($dropdown).parents(".book_list_item").addClass("current");

				// set z-index of parent .book_list_item above that of its siblings
				$(this).parents('.book_list_item').css('z-index', 1).siblings().css('z-index', 0);
			}

			// stop event propagation back to body
			event.stopPropagation();

			return false;
		}
  });

  // add close functionality
  $('body').bind("click.booklistaction", function() {
    $open_items = $(book_list + ".book_actions .open");

    if ($open_items)
    {
      $open_items.slideUp("fast").removeClass("open");
    }
  });
}

// -----------------------------------------------------------------------------
// Function: initRequestBook
// Description: Handles the Request Book actions
// -----------------------------------------------------------------------------
function initRequestBook()
{

	// Book scroller tooltips - truncate prior to showing
		/*$('.request_book a').hover(function(e){
				$('#book_request_tooltip .line1').text("Click to request this book and we'll notify you when it's available!");
		});*/


		// Book request tooltips
		if($('.request_book').length> 0){

			$('li.request_book, span.request_book').tooltip({
				tip:'#book_request_tooltip',
				delay:0,
				relative:false,
				position:'top left',
				offset: [10,10]
			});
			// Book request tooltips
			$('li.requested_book, span.request_book').tooltip({
				tip:'#book_requested_tooltip',
				delay:0,
				relative:false,
				position:'top left',
				offset: [10,10]
			});


			$(".request_book a:not(.requested_book)").click(function(event) {

				$(this).parent().addClass("requested_book").removeClass("request_book");

				alocation = $(this).attr('href');

				$.post(alocation,
							 {
								 slug: 'test'
							 },
						 function (data)
						 {

							 $('#request_notification').slideDown().delay('5000').slideUp();

						 });

				event.preventDefault();
				return false;
			});
		}

}


// -----------------------------------------------------------------------------
// Function: initSearch
// Description: inits the search - and autosearch
// -----------------------------------------------------------------------------
function initSearch()
{

	// style hover on submit button
	$('#searchbox_search_submit').hover(
		function(){
			$(this).addClass('hover');
		},
		function(){
			$(this).removeClass('hover');
		}
	);

  // Clear/restore default value
  var search_default_value = '';
  $('#search_term').focus(function() {
    // if default value not stored, then store
    if (search_default_value == '')
    {
      search_default_value = $(this).val();
    }

    // clear input if default value present
    if ($(this).val() == search_default_value)
    {
      $(this).val('');
    }

    // add blur event
    $(this).blur(function() {
      if ($(this).val() == '')
      {
        $(this).val(search_default_value);
      }
    });
  });

  // Clear/restore default value
  search_default_value = Config.search_default_value;

  $('#searchbook_term').focus(function() {
    // if default value not stored, then store
    if (search_default_value == '')
    {
      search_default_value = $(this).val();
    }

    // clear input if default value present
    if ($(this).val() == search_default_value)
    {
      $(this).val('');
    }

    // add blur event
    $(this).blur(function() {
      if ($(this).val() == '')
      {
        $(this).val(search_default_value);
      }
    });
  });

  // set up autocomplete
  var cache = {};

  $("#search_term, #searchbook_term").autocomplete({
			source: function (request, response) {
        if ( request.term in cache )
        {
          response( cache[ request.term ] );
          return;
        }

        if(this.element.hasClass('preview_searchfield')){
        	controller = 'preview';
        }else{
        	controller = 'book';
        }

        $.post("/"+controller+"/autocomplete/15",
               {
                 term: request.term
               },
               function(data)
               {
                 // return the response
                 response(data);
               },
               'json');
      },
      focus: function(event, ui) {
      	var selectedObj = ui.item;

      	// $('#searchbook_term').val(selectedObj.label);
		var searchStr = selectedObj.label.replace(/<strong>/g, '');
		searchStr = searchStr.replace(/<\/strong>/g, '');
		$('#searchbook_term').val(searchStr);
      	event.preventDefault();
      },
      select: function(event, ui) {
      	var selectedObj = ui.item;

      	window.location = selectedObj.value;
				return false;
			},
			minLength: 3
		});

	// Submit the search when changind dropdowns
	$('#searchform #per_page, #searchform #sortby').change(function() {
			$("#searchform").submit();
	});

}

function getURLSegment(url, segment) {
	var segments = url.toString();
    segments = segments.split('/');
	if (segments[segment] != undefined) {
        return segments[segment];
    }
    return 'nothing';
}

// -----------------------------------------------------------------------------
// Function: initSearchPagination
// Description: inits the pagination links in book search
// -----------------------------------------------------------------------------
function initSearchPagination()
{
	$("#pagination_booksearch a").click(function(e) {
		e.preventDefault();

		seg = getURLSegment($(this).attr('href'), 5);
		$("#search_page").val(seg);

		$("#searchform").attr("action", $(this).attr('href'));
		$("#searchform").submit();

	});

}

function got_started(){

	$.post('/auth/got_started');

	// N.B. We don't care what the response is, we assume it worked and close the dialogue
  $.fn.colorbox.close();

  $('#getting_started').removeClass('auto_show');

}


// -----------------------------------------------------------------------------
// Function: initDialogs
// Description: inits dialog lightboxes
// -----------------------------------------------------------------------------
function initDialogs()
{
  // Any links that are an internal anchor that point to a div which has the .dialog
  // class set will render target div in a lightbox when clicked instead of the
  // default browser behaviour of scrolling to the element in question.
  // If the URL includes the anchor, the dialog will be shown as soon as the page
  // has loaded. This allows people to link to dialogs.
  /*$("a.modal_link[href^='#']").colorbox({
    inline:     function() { return $(this).attr('href').charAt(0) == '#' && $($(this).attr('href')).hasClass('dialog'); },
    href:       function() { return $(this).attr('href'); },
    open:       function() { return window.location.hash == $(this).attr('href'); },
    onLoad: function(){ console.log($(this)); console.log(window.location.hash + ' ' + $(this).attr('href'));  }
  });*/

  if($('#getting_started').hasClass('got_started')){
  	auto_show = false;
  }else{
  	auto_show = true;
  }

  $("a.modal_link[href='#getting_started']").colorbox({
    inline:     function() { return $(this).attr('href').charAt(0) == '#' && $($(this).attr('href')).hasClass('dialog'); },
    href:       function() { return $(this).attr('href'); },
    open:       false,
    onClosed:		function() { got_started(); }
  });

  $("a.modal_link[href='#citations_form']").colorbox({
    inline:     function() { return $(this).attr('href').charAt(0) == '#' && $($(this).attr('href')).hasClass('dialog'); },
    href:       function() { return $(this).attr('href'); },
    open:       function() { return window.location.hash == $(this).attr('href'); }
  });


  $("a.modal_link[href='#homepage_video']").colorbox({
    inline:     function() { return $(this).attr('href').charAt(0) == '#' && $($(this).attr('href')).hasClass('dialog'); },
    href:       function() { return $(this).attr('href'); },
    open:       false,
    close: "close"
  });

  // Remove anchor hash from URL in location bar when closing dialog
  $(document).bind('cbox_closed', function(){
    window.location.hash = '';
  });

  // init the 'chapters removed from basket' modal - if it's on the page
  if($('#basket_chapters_removed_form_dialog').length > 0){
		$.fn.colorbox({
				inline:true,
				href:'#basket_chapters_removed_form_dialog',
				returnFocus:false,
				overlayClose:false,
				escKey:false,
				onLoad:function(){

					$('#basket_chapters_removed a#chapters_removed_ok').bind('click',function(event) {

							event.preventDefault();
							$.fn.colorbox.close();
					});
				},
				onComplete:function(){

					$('#basket_chapters_removed_form_dialog').closest('div#cboxContent').addClass('no_close_button');

				}
		});
	}

	$('#login_sign_up').click(function(event){
			event.preventDefault();
			$('#btn_sign_up a').trigger('click');
	});

	// If we're on the 'getting_started' url, trigger the getting started dialog
	if(location.pathname == '/getting_started' && auto_show){
		$('a.getting_started_link').trigger('click');
	}

}



// -----------------------------------------------------------------------------
// Function: initGettingStarted
// Description: inits the pissoffifier on the Getting Started Lightbox dialogue
// -----------------------------------------------------------------------------
function initGettingStarted()
{
  $('.dialog#getting_started .pissoffifier a').click(function(event) {
    event.preventDefault();
    got_started();
  });

  $('#close_getting_started').click(function(event){
  		event.preventDefault();
  		$.fn.colorbox.close();
  });

}

// -----------------------------------------------------------------------------
// Function: initBasketSaveMoney
// Description: inits the modal shown on the basket if buying chapters valued
// greater than the value of the whole ebook
// -----------------------------------------------------------------------------
function initBasketSaveMoney()
{
	if($('#basket_save_money').length){
		$('#basket_save_money a#save_money_no').click(function(event) {
			$.fn.colorbox.close();
			event.preventDefault();
		});
	}

}

function resetBookList(booklist)
{
  $(booklist + " ul").html('');
}


function init_div_heights(){

	sidebar_height = $('#categories.sidebar').innerHeight();
	content_height = $('#content').innerHeight();

	// just to make sure the sidebar height doesn't exceed the main content div
	if(parseInt(content_height-30)  < parseInt(sidebar_height)){
		$('#content').css('min-height',sidebar_height + 30);
	}
}

function init_guidance_boxes()
{
  $('p .guidance').hide(); // do not hide if on page page_accountstudent_personal

  $('input, select').focus(function()
  {
    $(this).parent().find('.guidance').show();
  });

  $('input, select, textarea').blur(function()
  {
    $(this).parent().find('.guidance').hide();
  });
}


function initialise_university_autocomplete(label_input, value_input){

	var cache = {};
	$(label_input).autocomplete({
		source: function (request, response) {
			if ( request.term in cache )
        	{
        	  response( cache[ request.term ] );
        	  return;
			}

		$.post("/preview/uni_autocomplete",
			{ term: request.term },
				function(data) {
				// return the response
				response(data);
			},
			'json');
     	},
		focus: function(event, ui) {
			var selectedObj = ui.item;

			$(label_input).val(selectedObj.label);
			event.preventDefault();
		},
		select: function(event, ui) {
			var selectedObj = ui.item;
			$(label_input).val(selectedObj.label);
			$(value_input).val(selectedObj.value);

			if( selectedObj.value == "0" ) {
				$("#cboxLoadedContent").height($("#cboxLoadedContent").height()+40);
				$("#new_uni_block").show();
			}else {
				if( $("#new_uni_block").is(":hidden") ) {
					// Do nothing
				}else {
					$("#new_uni_block").hide();
					$("#cboxLoadedContent").height($("#cboxLoadedContent").height()-40);
				}
			}

			return false;
		},
		minLength: 3
	});

}

function initCategoriesSidebar(){

	$('#categories_slider h2').click(function(e){

			if($('#root_categories_list').is(':visible')){
				$('#root_categories_list').slideUp();
				$('#categories_slider h2 a').removeClass('open');
			}else{
				$('#root_categories_list').slideDown();
				$('#categories_slider h2 a').addClass('open');
			}
	});

	$('#close_categories a').click(function(e){
			e.preventDefault();
			$('#root_categories_list').slideUp();
	});

}

var docViewer;

function getDocViewer(){
		if(docViewer)
				return docViewer;
		else if(window.FlexPaperViewer)
				return window.FlexPaperViewer;
		else if(document.FlexPaperViewer)
	return document.FlexPaperViewer;
		else
	return null;
}

function initReader(){

	// Chapter TOC
	$('#chapter_slider h2').click(function(e){

			e.preventDefault();

			if($('#table_of_contents').is(':visible')){
				$('#table_of_contents').slideUp();
				$('#chapter_slider h2 a').removeClass('open');
				$('#chapter_slider h2').removeClass('open')
			}else{
				$('#table_of_contents').slideDown();
				$('#chapter_slider h2 a').addClass('open');
				$('#chapter_slider h2').addClass('open');
			}
	});

	$('#table_of_contents a.toc_item').click(function(e){
			e.preventDefault();

			$('#get_access').slideUp();

			$('#table_of_contents a').removeClass('active');
			$(this).addClass('active');

			getDocViewer().gotoPage($(this).attr('data-start_page'));
			//$FlexPaper().gotoPage($(this).attr('data-start_page'));

			$('#table_of_contents').slideUp();

	});

	// Get access
	$('a.btn_show_access_options').click(function(e){

			e.preventDefault();

			if($('#get_access').is(':visible')){
				$('#get_access').slideUp();
			}else{
				$('#get_access').slideDown();
			}
	});


	// Reader Help
	$('#get_access a.btn_cancel').click(function(e){
			e.preventDefault();
			$('#get_access').slideUp();
	});


	// Add to basket buttons for chapters that are not owned
	$('#get_access a.btn_reader_buy_6m').click(function(event){
			event.preventDefault();
			if(!$('#get_access').hasClass('basket')){
				addToBasket(current_chapter_id, Flexpaper.book_id, 6, 0, event.pageX, event.pageY);
				$('#table_of_contents a.toc_item[data-chapter_id='+current_chapter_id+']').addClass('basket');
			}
	});
	$('#get_access a.btn_reader_buy_12m').click(function(event){
			event.preventDefault();
			if(!$('#get_access').hasClass('basket')){
				addToBasket(current_chapter_id, Flexpaper.book_id, 12, 0, event.pageX, event.pageY);
				$('#table_of_contents a.toc_item[data-chapter_id='+current_chapter_id+']').addClass('basket');
			}
	});

	// Add to basket buttons for book that are not owned
	$('#get_access a.btn_reader_buy_book_6m').click(function(event){
			event.preventDefault();
			if(!$('#get_access').hasClass('basket')){
				addToBasket(0, Flexpaper.book_id, 6, 1, event.pageX, event.pageY);
				$('#table_of_contents a.toc_item').addClass('basket');
			}
	});
	$('#get_access a.btn_reader_buy_book_12m').click(function(event){
			event.preventDefault();
			if(!$('#get_access').hasClass('basket')){
				addToBasket(0, Flexpaper.book_id, 12, 1, event.pageX, event.pageY);
				$('#table_of_contents a.toc_item').addClass('basket');
			}
	});


}

function initCourseDataNotification(){

	$('#course_data_notification #close').click(function(e){

			e.preventDefault();

			// get promotion code from db
      $.post('/auth/hide_course_data_notification',{},
         function (response)
         {
         	 if(response.result=='ok'){
						 $('#course_data_notification').slideUp();
					 }
         },
         'json');
	});
}

function initLibrarySort(){

	if($('#library_sort').length){

		$('#sort_field').change(function() {
			$('#library_sort').attr('action',Config.base_url+'library');
			$('#library_sort').submit();
		});


		$('#pagination a').click(function(e){
				e.preventDefault();
				$('#sort_submit').val(0);
				$('#library_sort').attr('action',$(this).attr('href')).submit();
		});
	}

}

// Set Library book list items to be the same height as the heightest one
function initLibraryItems(){

	var maxHeight = Math.max.apply(null, $(".library_book_list_item").map(function (){
			return $(this).height();
	}).get());

	$('.library_book_list_item').height(maxHeight);

}

/* -------------------- */
/* document ready state */
/* -------------------- */
$(document).ready(function() {

	var wordpress = $('body').hasClass('wordpress');

	if(!wordpress){

		// Jtextfill elements
		if($('.jtextfill').length){
			$('.jtextfill.reader_title').textfill({ maxFontPixels: 20, minFontPixels: 16, innerTag: 'h1' });
		}

		// Studnt course data notification
		if($('#course_data_notification').length){
			initCourseDataNotification();
		}

		initDialogs();

		// Init basket 'save money' dialog if on the book details page
		initBasketSaveMoney();

		// sidebar
		initCategoriesSidebar();

		// Book reader and associated
		initReader();

		initSearch();

		// getting started dialog
		initGettingStarted();

		// book details
		initSynopsis('#book_desc_control', '#book_desc');
		if($('#chapter_pricing').size()){
			initPricing();
		}

		// basket
		if($('#basket_table').length){
			initBasketTable('#basket_table');
		}

		// checkout
		initGatewaysForm('form#gateways');

		initRequestBook();
		initBookCitations();
		initBookListActions('#book_list');

		init_guidance_boxes();

		initLibrarySort();

		initLibraryItems();

		// Preview tooltips
		$('.preview_link').tooltip({
			tip:'#preview_chapter_tooltip',
			delay:0,
			relative:true,
			position:'top right',
			offset:[5,-20]
		});

	}

	initHumanTest();

	init_div_heights();

  initSearchPagination();

  // Clear focus on some form elements
	$('.focus_clear').focus(function(e){

		if($(this).attr('data-default') !== undefined){

			if($(this).val()==$(this).attr('data-default')){
				$(this).val('');
			}
			if($(this).html()==$(this).attr('data-default')){
				$(this).html('');
			}

		}
	});
	$('.focus_clear').blur(function(e){

		if($(this).attr('data-default') !== undefined){

			if($(this).val()==''){
				$(this).val($(this).attr('data-default'));
			}
			if($(this).html()==''){
				$(this).html($(this).attr('data-default'));
			}

		}
	});


} );

