$(document).ready(function(){
  
  var divTimeout = 5000;

  if ( $('#lunchMoneyBalance').html() )
  {
    var currentLm = intVal( $('#lunchMoneyBalance').html().replace('L$','').replace(/,/g,'') - 0 );
    var maxDailyLimit = intVal( $('#maxDailyLimit').html().replace('L$','').replace(/,/g,'') - 0 );
    var vipDailyLimit = $('#vipDailyLimit').text();
    var todaysContribution = intVal( $('#todaysContribution').html().replace('L$','').replace(/,/g,'') - 0 );
    var currentLimit = intVal( $('#currentLimit').html().replace('L$','').replace(/,/g,'') - 0 );
  }

  $('input.causeUnitAmount').each( function() {   
    $(this).attr('tabindex', $('input').index(this) + 1 );
  });

  //How it Works show/hide
  $('span.howItWorks').click(function(){
    $('div.howItWorks').slideToggle( 'slow' );
  });

  //Slide up/down for about links
  $("a.aboutLink").click(function() {
    var causeName = $(this).parents('.causeContainer').attr('id');
    $('.longDescription').each( function(){
      if ( $(this).parents('.causeContainer').attr('id') != causeName )
      {
        $(this).fadeOut('fast');
      }
    });
    $('#' + causeName + ' .longDescription').slideToggle('slow');
    return false;
  });

  $('a.closeWindow').click(function() {
    var causeName = $(this).parents('.causeContainer').attr('id');
    $('#' + causeName + ' .longDescription').slideUp('slow');
    return false;
  });
  
  $('.statsHeaderCause a').click(function(){
    jumpToCause( $(this).attr('href').replace('/#', '') );
    return false;
  });


  $('a[href="#submitAnchor"]').click( function() {
    $( document ).scrollTop( $('a[name="submitAnchor"]').offset().top );
    return false;
  });

  //yyy this needs to work for name based as opposed to number based 
  if ( window.location.hash.indexOf('#') == 0 )
  {
    var causeName = window.location.hash.replace('#', '');
    if ( causeName != 'submitAnchor' )
    {
      jumpToCause( causeName );
   }
  }
  else
  {
    //Show Initial Bubble and focus on the first element  
    $('div.caption:first').show();
    $('div.causeJumper:first').show();
    $('input.causeUnitAmount:first').focus();
  }

  //Update page contents with current L$
  $('#lunchMoneyBalance').html( 'L$' + formatNumber( currentLm ) );
  $('#currentLimit').html( 'L$' + formatNumber( currentLimit ) );

  //On input focus  
  $("input.causeUnitAmount").focus(function () {
    var causeName = $(this).parents('.causeContainer').attr('id');

    //Hide all displayed bubbles
    $('.caption').hide();

    //Show the bubble for the selected cause
    $( '#' + causeName + ' .caption' ).fadeIn('slow');

    $('div.causeJumper').hide();
    $( '#' + causeName + ' .causeJumper').show();

    // Hide all previous cause errors
    hideAllCauseErrors();

  //Update currentLimit & totalTally when key is released
  }).bind('keydown keyup change', function(){

    var causeName = $(this).parents('.causeContainer').attr('id');
    var unitCost = $('#' + causeName + ' .unitInfoContainer .price').html().replace('L$','').replace(/,/g,'') - 0;
    var units = $(this).val().replace(/,/g,'') - 0; 

    //Tally the results
    var totalTallyAmount = 0;

    $('.causeContainer').each(function() {
      var currentCause = $(this).attr('id');
      var currentCost = $( '#' + currentCause + ' .unitInfoContainer .price').text().replace('L$','').replace(/,/g,'') - 0;;
      var currentUnits = $( '#' + currentCause + ' input.causeUnitAmount').val().replace(/,/g,'') - 0;
      amount = currentCost * currentUnits;
      totalTallyAmount += amount;
      currentUnits = 0;
      currentCost = 0;
    });

    if ( !$('div.notLoggedIn').html() )
    {
      if (totalTallyAmount <= currentLimit) {		
        if ( units > 0 )
        {
          $(this).val(formatNumber(units));
        }
        else
        {
          $(this).val('');
        }
        $( '#' + causeName + ' .causeInput .price' ).text( 'L$' + formatNumber( unitCost * units ) );
      } 
      else 
      {
        var maxUnits = intVal( (currentLimit - totalTallyAmount) / unitCost);
        var cost = unitCost * units;
				
			
        $(this).val( formatNumber( maxUnits + units ) );
        $( '#' + causeName + ' .causeInput .price' ).text( 'L$' + formatNumber( unitCost * ( maxUnits + units ) ) );
				
        var errMessage = '';
        //var errMessage = 'You may not give more than L$' + formatNumber( maxDailyLimit ) + ' in a single day. Your current Lunch Money Balance is L$' +  formatNumber( currentLm ) + '. You have donated L$' + formatNumber( todaysContribution ) + ' today and the current donation you are trying to make would cost L$' + formatNumber( totalTallyAmount ) + '.';   
	
        if ( totalTallyAmount + todaysContribution > maxDailyLimit  )
        {
          errMessage = 'The donation amount of L$' + formatNumber(totalTallyAmount);
          if (todaysContribution > 0 )
          {
            ' plus the L$' +  formatNumber( todaysContribution ) + ' you already donated today';
          } 

          errMessage += ' exceeds the maximum daily contribution amount of L$' + formatNumber( maxDailyLimit ) + '.';
          if ( $('div#vipAd').length == 1 )
          {
            errMessage += '<br/><br/><a href="' + VIP_SOA_URL + '" class="vipBuyLink">Give up to ' + vipDailyLimit + ' million per day!<br/>';
            if ( $('div#isEligibleForFreeTrial').length > 0 )
            {
              errMessage += $('div#freeTrialWording').text() + '</a>';
            }
            else
            {
              errMessage += 'Join the VIP Club!</a>';
            }
            divTimeout = 10000;
          }
        }
	
        if ( totalTallyAmount > currentLm )
        {
          errMessage = 'The donation amount of L$' + formatNumber(totalTallyAmount) +  ' exceeds your current Lunch Money balance of L$' + formatNumber(currentLm) + '.';
        }
	
        if ( errMessage == '' )
        {
          errMessage = 'Please input a valid donation amount!';
        }
        hideAllCauseErrors();

        $( '#' + causeName + ' .errorBox').html( errMessage ).show(); 
        setTimeout( '$("#' + causeName + ' .errorBox").hide();' , divTimeout);
        totalTallyAmount = totalTallyAmount + (maxUnits * unitCost) - 0;
      }
    } 
    else
    {
      hideAllCauseErrors();
      $( '#' + causeName + ' .errorBox').html('To donate to causes, you must be registered with myYearbook. Please <a href="' + $("#registerLink").attr('href') +'">register</a> or <a href="' + $("#loginLink").attr('href') +'">log in</a>').show();
      setTimeout('$("#' + causeName + ' .errorBox").hide();', divTimeout);
      $(this).val('');     
      totalTallyAmount = 0;
    }
		
    $('#totalTally').html('L$' + formatNumber(totalTallyAmount));
    $('#currentLimit').html('L$' + formatNumber(currentLimit - ( totalTallyAmount - 0 ) ) );

  });

  function formatNumber(nStr)
  {
    nStr = nStr + '';
	  
    // Remove leading zeros from nStr
    var leadingZeroRegx = /^0\d/;
    nStr = nStr.replace(leadingZeroRegx, '');

    // Remove non numericals from nStr
    var nonNumericalRegx = /[^0-9-]/g ;
    nStr = nStr.replace(nonNumericalRegx, '');

    var strLen = nStr.length;
    var newStr = '';
    var c = 0;
    for ( var i = strLen; i > 0; i-- )
    {
      c += 1;
      newStr = nStr.substring( i - 1, i ) + newStr;
	    
      if ( c % 3 == 0 && i != 1 )
      {
        newStr = ',' + newStr;
      } 
    }
    return newStr;
  }
	
  function intVal( mixed_var, base ) 
  {
    var tmp;
    if( typeof( mixed_var ) == 'string' )
    {
      tmp = parseInt(mixed_var*1);
      if(isNaN(tmp) || !isFinite(tmp))
      {
        return 0;
      } else{
        return tmp.toString(base || 10);
      }
    } 
    else if( typeof( mixed_var ) == 'number' && isFinite(mixed_var) )
    {
      return Math.floor(mixed_var)
    } else{
      return 0;
    }
  }
});

function hideAllCauseErrors()
{
  $('div.errorBox').hide('');
}

function jumpToCause( cause )
{
  $( document ).scrollTop( $( '#' + cause ).offset().top );
  $('.causeContainer#' + cause + ' input.causeUnitAmount').focus().click();
  $('.causeContainer#' + cause + ' .caption').show();
  $('.causeContainer#' + cause + ' .causeJumper').show();
}
