/* WebVentures miscellaneous JS functions 200710
Created TJR @ WebVentures Pty Ltd. */

function clear_confirm() {
var reply=confirm("Do you really want to delete your shopping basket and close this shopping session?\nSelect OK to delete your basket and contents or Cancel to continue shopping.");
if (reply==true) {
    window.location="/bookshop/action/BasketClear";
  } else {
    window.location="/bookshop/basket/continue.html";
  }
}



function emailValidate( field ) {
  if (field.value.length < 3) {
    alert('You have not entered an email address: '+field.value);
    return false;
  } else if(!isValidEmail(field.value)) { 
    alert('You have not entered a correctly formatted email address: '+field.value); 
      field.focus() 
      return false; 
   } 
}

//function name: isValidEmail
//Parameters: str - string of email to be validated
//Description: Basic format check that there is a dot in the text 
// but not at first character and
// that the @ symbol is present but not at the first char
// and that a dot comes after the @.
// First check for no comma or space which is an easy typo.
function isValidEmail(str) {
  if (str.length < 6) return false;
//  str = str.trim();
  if (str.indexOf(",") > -1 || str.indexOf(" ") > -1) return false;
  var firstDot = str.indexOf(".");
  var atPos = str.indexOf("@");
  var lastDot = str.lastIndexOf(".");  // look for dot after @
  return (firstDot > 0 && atPos > 0 && lastDot > atPos);
}




function selectNewMember() {
  $("#output1").replaceWith('<div id="output1"><p>Please enter a member number to retrieve.</p><label class="left">Member Number <span class="req large">*</span></label><input class="formbox short flL" type="text" name="member_id" id="member_id" value="" onkeyup="checkLength(this, 7)" /><div class="clear">&nbsp;</div><label class="left">&nbsp;</label><input type="submit" name="Select" value="Select Member" class="submit_button padTop" /></div>');
}


var overLimit = 0;
var max_attempts = 1; // warning on second attempt
/**
  Checks the length of a form element (normally textarea), and if the length is more than the maximum characters,
  it truncates it.   A warning is also given after max_attempts at exceeding the limit.
  @param	textarea	the textarea to check (as a DOM object - recommended "this").
  @param	maxLength	the maximum number of characters.
  @date	2009-08-18
  @author	Tristan Roberts - WebVentures.
*/

function checkLength(textarea, maxLength) {
  if (textarea.value.length > maxLength) {
    textarea.value = textarea.value.substring(0, maxLength);
    if (overLimit > max_attempts) {
      alert('Sorry, please enter a maximum of ' + maxLength + ' characters.');
    }
    overLimit++;
  }
}

function adviseWrap(textarea, maxLength) {
  if (textarea.value.length > maxLength) {
    textarea.value = textarea.value.substring(0, maxLength);
    if (overLimit > max_attempts) {
      alert('Sorry, a maximum of ' + maxLength + ' characters is possible.  Please use the next field for overflow text.');
    }
    overLimit++;
  }
}

/**
	Expands a textarea as the user types to avoid scrollbars.
	@author	Tristan Roberts, WebVentures (http://web.tristanroberts.name)
	@date	2010-04-01
	@param	selector	A jQuery-compatible selector of the textarea.
*/
function expandTextarea( selector ) {
	while ( selector.scrollTop() != 0 ) {
		var height = selector.height( );
		selector.css( "height", ( height + 15 ) + "px" );
	}
}

/*
 *	Expand upon key up on the textarea.
 */
$( document ).ready( function( ) {
	$( "textarea" ).keyup( function( e ) {
		expandTextarea( $( this ) );
	} );
} );

/**
  Alters the form action and submits the form.
  Use this to recalculate the Freight charges specifically when the delivery Country is changed.
  @date	2009-09-02
  @author	CVL - WebVentures.
*/

function recalculate() {
  var x=document.getElementById("order_conf");
  x.action = "/bookshop/action_so/CustomerOrderRecalculate";
  x.submit();
}

/**
Check T&Cs are accepted (with checkbox) or declined
*/
function acceptTerms(supplier) {
  $("#terms").attr("action", "/bookshop/action_so/CustomerOrder?TC_accepted=" + supplier);
  $("#terms").attr("method", "POST");

  if ($('#TOS_agreed').attr('checked')) {
    $("#terms").submit();
    modal('modalWindow');
  } else {
    alert('Please check the box to signify that you accept the Terms of Service.');
    $("#terms").attr("action", "/bookshop/action_so/CustomerOrder");
    $("#terms").submit();
  }
  return false;
}

function declineTerms(supplier) {
  $("#terms").attr("action", "/bookshop/action_so/CustomerOrder?TC_refused=" + supplier);
  $("#terms").attr("method", "POST");
  $("#terms").submit();
  modal('modalWindow');
  return false;
}

function printIt(printThis) {
  var win = window.open();
  //alert(win.document);
  win.document.title = "Terms Of Use";
  //alert(printThis);
  
  var doc = win.document;
	if(win.contentDocument)
	  doc = win.contentDocument;
	else if(win.contentWindow)
		doc = win.contentWindow.document;
  
	doc.open();
	doc.writeln(printThis);
	doc.close();

  win.print();
  win.close();
 // return false;
}

function printUrl(url) {
 location=url;
 print();
}


/**
  Alters the form action and submits the form.
  Use this to recalculate the voucher values when voucher IDs are entered.
  @date	2011-02-11
  @author	CVL - WebVentures.
*/

function recalculate_voucher() {
  var x=document.getElementById("order_conf");
  x.action = "/bookshop/action_so/CustomerOrderRecalculate?_entry_=VoucherAdd";
  x.submit();
}

/**
  Alters the form action and submits the form.
  Use this to recalculate the voucher values when voucher IDs are entered.
  @date	2011-02-11
  @author	CVL - WebVentures.
*/


function recalculate_credit() {
  var x=document.getElementById("order_conf");
  x.action = "/bookshop/action_so/CustomerOrderRecalculate?_entry_=MemberCreditAdd";
  x.submit();
}

/** Restart the order process because something changed. 
This will clean any previously entered payment instruments so customer 
is starting with a clean slate. 
  @date	2011-03-11
  @author	CVL - WebVentures.
*/
var order ="/bookshop/action/CustomerOrder";
function restart_order() {
  window.location = order;
}


/**
  Alters the form action and submits the form.
  Use this to recalculate the voucher values when voucher IDs are entered.
  @date	2011-03-11
  @author	CVL - WebVentures.
*/


function confirm_voucher_amount() {
  var x=document.getElementById("add_value");
  x.action = "/bookshop/action/MyVouchers/rq/VoucherPurchase";
  x.submit();
}

/**
  Alters the form action and submits the form.
  Use this to display the voucher values when voucher IDs are entered.
  @date	2011-03-11
  @author	CVL - WebVentures.
*/


function display_voucher_amount() {
  var x=document.getElementById("add_value");
  x.action = "/bookshop/action/MyVouchers/rq/VoucherBalance";
  x.submit();
}

function encode_utf8( s )
{
  return unescape( encodeURIComponent( s ) );
}

function decode_utf8( s )
{
  return decodeURIComponent( escape( s ) );
}


function removeBook(volumeId) {
  var my_url = "/bookshop/ajax?_next_page_=MyLibrary&request=remove_book&volumeId="+volumeId;
  var my_id = "#" + volumeId;
  $.ajax({
    type : "GET",
    url : my_url,
    dataType : "json",
		async : false,
    success : function( data ) {
      window.location = "/bookshop/action_so/ProfileLogin?GoogleLibrary=1";
    }
  });
}
    
    

/** AJAX eBook Email Form for use with jQuery.
Display an interim message while waiting for the confirmation of email resend to occur.
Modified: CVL, WebVentures  071210
*/

$(document).ready(function() { 
    
    
    var eBook_receipt_options = { 
        target:        '#receipt_conf',
        beforeSubmit:  clearMessage
    }; 

    $('#ebook_receipt').ajaxForm(eBook_receipt_options); 

    
    var stock_receipt_options = { 
        target:        '#receipt_conf',
        beforeSubmit:  clearMessage
    }; 

    $('#stock_receipt').ajaxForm(stock_receipt_options); 

    
    var membership_receipt_options = { 
        target:        '#receipt_conf',
        beforeSubmit:  clearMessage
    }; 

    $('#membership_receipt').ajaxForm(membership_receipt_options); 

    
    var voucher_image_options = { 
        target:        '#receipt_conf',
        beforeSubmit:  clearMessage
    }; 

    $('#voucher_image').ajaxForm(voucher_image_options); 
 

  function clearMessage() {
          $("#email_message").replaceWith('<p id=\"email_message\">Sending email ... </p>');
  }

  

/** AJAX Order Form submit for use with jQuery.
Display an interim message while waiting for the confirmation of order to occur.
Modified: CVL, WebVentures  071210
*/


  var order_conf_options = { 
    target:  '#page_replace',
    url:  '/bookshop/ajax?_next_page_=OrderReceipt&_secure_=true&_new_=false',
    beforeSubmit:  clearButton,
    resetForm:  true        // reset the form after successful submit 
  }; 

  $('#order_conf').ajaxForm(order_conf_options); 


});

function clearButton() {
  $("#submit_button").replaceWith('<p id="submit_button"><img src="/page_images/ajax-loader.gif"><strong> Processing your order.&nbsp;&nbsp;&nbsp;Please wait for your receipt ... </strong></p>');
}


