// JavaScript Document

function payPalClass( payPalForm, business )
{
	 var me = this;
	 var formName = payPalForm;
	 var formSel = $("form#"+formName);
  
    this.setOneTimePay = function()
	 {
		 $("#cmd", formSel).val("_xclick");
	 }
	 this.setRecurPay = function()
	 {
		 $("#cmd").val("_xclick-subscriptions");  // always set to a one time payment in paypal	 	
	 }
	 this.setBusinessIdentity = function( business )
	 {
    	 $("#business").val( business );
	 }
	 this.setItemName = function( name )
	 {
		 $("#item_name", formSel).val( name );
	 }
	 this.setItemNumber = function( num )
	 {
		 $("#item_number", formSel).val( num );
	 }
	 this.setAmount = function( num )
	 {
		 $("#amount", formSel).val( num );
	 }
	 this.setHandling = function( num )
	 {
		 $("#handling", formSel).val( num );
	 }
	 this.resetForm = function()
	 {
		 $(" input.clr", formSel ).val("");
	 }
	 this.setPageStyle = function( style )
	 {
		 $("#page_style").val( style );
	 }
	 this.doSubmit = function()
	 {
		 formSel.submit();
	 }
	 me.setBusinessIdentity( business );
}

var PayPal = null;

function formatCurrency( strValue )
{
	strValue = strValue.toString().replace( /[\$\,]/g,'');
	dblValue = parseFloat( strValue );
	
	blnSign = (dblValue == (dblValue = Math.abs( dblValue ) ) );
	dblValue = Math.floor( dblValue * 100 + 0.50000000001);
	intCents = dblValue % 100;
	strCents = intCents.toString();
	dblValue = Math.floor( dblValue/100).toString();
	if ( intCents < 10 )
	    strCents = "0" + strCents;
	for ( var i = 0; i < Math.floor( ( dblValue.length - ( 1 + i ) ) / 3 ); i++ ) {
       dblValue = dblValue.substr( 0, dblValue.length - ( 4 * i + 3  ) ) + ',' +
		            dblValue.substr( dblValue.length - ( 4 * i + 3 ));
   }
	return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents );
}

function clearWorksheet( ws )
{
	ws.find("input:not(:button)")    // get all input boxes
     .attr("value","")              // clear their values
	  .end()                         // start at the "table" level and...
	  .find(".subtotal")             // find all subtotals
	  .html( "" )
	  .end()
	  .find("input[type='checkbox']").attr("checked", null );                   // clear totals

	PayPal.resetForm();
	
}

var currentTable = null;
function setupTask( elem )
{
	 var worksheet = $( "."+elem.val()+"_tasksheet");
	 if ( currentTable != null  ) {
		 $(".tasks").hide();
		 clearWorksheet( worksheet );
	 }
	 currentTable = elem.val();
	 
	 PayPal.setOneTimePay();
	 
 	 updateGrandTotal( currentTable );
    worksheet.show();
}



function curTableSel()
{
	if ( currentTable == null )
	   return null;
	return $("table."+currentTable);
}

function nodollar( s )
{
	if ( s.length == 0 )
	   return "0";
	return s.replace( /[\$\,]/g, "" );
}

function sumSubTotals( table )
{
	 var gtotal = 0;
    var tablesel = $("table."+table);
	 $(".subtotal", tablesel ).each(
		 function() {
			 gtotal += parseFloat( nodollar( $(this).html() ) );
		 });
	 $(".allsubtotal", tablesel).html( formatCurrency( gtotal ) ) ;
	 return gtotal;
}

var payPalPcnt = 2.9/100;
var payPalTxCost = 0.30; // cents per transaction
var PayPalDiscount = 0.10; // 10%
var useChargeForPayPal = true;

function calcAndUpdatePayPalCost( table, total )
{
	var tablesel = $("table."+table);
   var pptotal = 0;
   if ( useChargeForPayPal ) {		
		pptotal = ( total == 0 ) ? 0 : ( ( total + payPalTxCost )/( 1 - payPalPcnt) ) - total;
	}
	else
	   pptotal = -(total * PayPalDiscount);
	$(".ppHandling", tablesel).html( formatCurrency( pptotal ) ) //"$"+ Math.round( pptotal * 100 )/100 );
	
	return pptotal;
	
}

function updateGrandTotal( table )
{
	 var tablesel = $("table."+table);	
	 var gTotal = sumSubTotals( table );
	 var ppHandling = calcAndUpdatePayPalCost( currentTable, gTotal );
	 $(".grandtotal", tablesel).html( formatCurrency( gTotal + ppHandling ) ); //"$"+Math.round( (gTotal+ppHandling) * 100 )/100 );
}

function updateSubTotal( elem )
{
	if ( currentTable == "monthly") {
		// compute family discount by multiplying counts of adults and children
		var $row = $("tr.fd", curTableSel() );
		var cadult = $("input#madults").val();
		if ( cadult == "")
		   cadult = 0;
		var cchild = $("input#mchild").val();
		if ( cchild == "" )
		   cchild = 0;
	   var total = parseInt( cchild ) + parseInt( cadult );
		var price = 0;
		if ( total >= 2 ) {
			price = parseFloat( nodollar( $row.find(".price").html() ) );											
		}
		else
		   total = 0;
      $row.find(".quantity").html( total );			
		$row.find(".subtotal").html( formatCurrency( total * price ) );
		
	}
	
	var parent = elem.parent().parent();
	
	var prices;
	var price;
	prices = $(parent).find(".price");
	if ( $(prices[0]).is(":input") ) {
		price = $(prices[0]).val();
	}
	else
   	price  = $(prices[0]).html();
	price = nodollar( price );
	
	var quantity;
	quantities = $(parent).find(".quantity");
	if ( $(quantities[0]).is(":input") ) {
		quantity = $(quantities[0]).val();
	}
	else 
	   quantity = $(quantities[0]).html();
		
	if ( quantity == "" )
	   quantity = 0;
	   
   var total = parseInt( quantity ) * parseFloat( price );
	
	$(".subtotal", parent ).html( formatCurrency( total ) ); //"$"+total );
	
	showPaymentDesc();
	
	updateGrandTotal( currentTable );
}

function generatePayPalDesc()
{
	var desc = "AOSA: ";
	var adultsel = "#sadults";   // assume start up
	var childsel = "#schild";   
	if ( currentTable == "monthly" ) {
		if ( $("input#recur").is(":checked") ) 
		   desc += "RECURRING PAYMENT for";
		else
   		desc += $("select#Month option:selected").html()+" dues payment for:  ";
		adultsel = "#madults";
		childsel = "#mchild";
	}
	else {
		desc += "startup dues for ";
	}
        	
	var $tablesel = curTableSel();
	var nadults = $( adultsel ).val();
	var nchild =  $( childsel ).val();
	var nsc =   $("tr.sc input.quantity", $tablesel).val();
	
	desc += (nadults > 0 ) ? nadults+" adult, " : "";
	desc += (nchild > 0 ) ? nchild+" child, " : "";
	desc += (nsc > 0 ) ? nsc+" scholarship, " : "";
	
	var lc = desc.lastIndexOf(",");
	desc = desc.substr( 0, lc);
	
	return desc;
}

function showPaymentDesc()
{
	var desc = generatePayPalDesc();
	$(".duesdesc").html( desc );

}

function payPayPal()
{
	
	var $tablesel = curTableSel();
	var amount = nodollar( $(".allsubtotal", $tablesel).html() );
	if ( amount <= 0 ){
		alert("There is nothing to payfor");
	   return;
	}
	PayPal.setAmount( amount );
	PayPal.setHandling( nodollar( $(".ppHandling", $tablesel).html() ) );
   PayPal.setItemName( generatePayPalDesc() );						
			
	if ( $("#recur", $tablesel).is(":checked") ) {
	   PayPal.setRecurPay();
	}
	else
	   PayPal.setOneTimePay();
						
	PayPal.doSubmit();
}

function invalid( msg )
{
	if ( msg == null || msg.length == 0 ) {
		$(".errors").html( msg ).hide(200);
	}
	else {
		$(".errors").html( msg ).show(200);
	}
}

var validOnChange = false;
function valid( force )
{
	
  
	if ( validOnChange == false && ( typeof force == "undefined" || force == false ) )
	   return;
		
	var $tablesel = curTableSel();
		
	var amount = nodollar( $(".allsubtotal", $tablesel).html() );
	if ( amount <= 0 ){		
	   invalid("Please fill out the form first!");
		validOnChange = true;
	   return false;
	}

	var nsc =  $("tr.sc input.quantity", $tablesel).val();
	if ( nsc && parseInt( nsc ) > 0 ) {
		var price = $("tr.sc input.price", $tablesel).val();
		if ( !price || ( price && parseInt( price ) == 0 ) ) {
			invalid("Scholarship is set but with no price!");
			validOnChange = true;
			return true;
		}
	}
	invalid("");
	return true;
}

function setupForDues()
{
	 $(".tasklist :input#task").click( function() { setupTask( $(this) ); } );	 
	 
	 $("select").change( showPaymentDesc ); 
	 $(":input.quantity").change( function() { updateSubTotal(  $(this) );  } );
	 $(":input.price").change( function() { updateSubTotal(  $(this) ); } );
	 $(":input").change( function() { valid(); showPaymentDesc(); } );
	 
	 $(".paynow").click( function() { if ( valid(true) ) payPayPal(); } );
	 
	 PayPal = new payPalClass( "paymentform", "sensei@aikidosa.org" );
	 PayPal.setPageStyle("AOSADues2");
	 
}

$contentReady.add( setupForDues );