// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function comment_approve(id,link) {
  var comment_approve = new Request.HTML ({
    url: link,
    update: 'comment_' + id,
    method: 'get'
  }).send();
}

function comment_unapprove(id,link) {
  var comment_unapprove = new Request.HTML ({
    url: link,
    update: 'comment_' + id,
    method: 'get'
  }).send();
}

window.addEvent('domready', function(){
  milkbox.changeOptions({topPosition:100});
});

Request.prototype._send = Request.prototype.send
Request.implement({

  auth_token: function(){
    return AUTH_TOKEN;
  },

  // This is more verbose than is ideal, but I don't see a better place
  // to hook this functionality in
  send: function(options){
    var type = $type(options);
    if (type == 'string' || type == 'element') options = {data: options};

    var old = this.options;
    options = $extend({data: old.data, url: old.url, method: old.method}, options);

    switch ($type(options.data)){
      case 'element': options.data = $(options.data).toQueryString(); break;
      case 'object': case 'hash': options.data = Hash.toQueryString(options.data);
    }

    // If this isn't a get request add the authenticity_token
    if (options.method != 'get' || options.method != 'GET')
      options.data = options.data+'&authenticity_token='+this.auth_token();
    
    // Call the original send
    this._send(options)
  }

});

Element.implement({
	flash: function(to,from,reps,prop,dur) {
		
		//defaults
		if(!reps) { reps = 1; }
		if(!prop) { prop = 'background-color'; }
		if(!dur) { dur = 250; }
		
		//create effect
		var effect = new Fx.Tween(this, {
				duration: dur,
				link: 'chain'
			})
		
		//do it!
		for(x = 1; x <= reps; x++)
		{
			effect.start(prop,from,to).start(prop,to,from);
		}
	}
});

function start_giving() {
  $('giving_link').set('html', 'START GIVING');
}

function give_now() {
  $('giving_link').set('html', 'GIVE NOW');
}
function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function split_donations(amount,type) {
  var cnt = countAllFunds();
  //remove non numerics
  amount = strip(amount);
  if (type == 'one_time') {
    $$('form#payment_form input.amount').each(function(e) {
      e.value = roundNumber(amount/cnt,2);
    });
  }
  if (type == 'hour_a_month') {
    $$('form#payment_form input.amount').each(function(e) {
      e.value = roundNumber((amount*12)/cnt,2);
    });
  }
  if (type == 'pledge') {
    $$('form#payment_form input.amount').each(function(e) {
      e.value = roundNumber((amount*26)/cnt,2);
    });
  }
  //this is used to handle a round off case induced by this method
  if(cnt > 1 && (cnt%2) == 1 && ((100*amount)%cnt) != 0) {
    e = $$('form#payment_form input.amount').getRandom();
    e.value = roundNumber(parseFloat(e.value)+0.01,2)
  } 
  if (cnt > 1 && (cnt%2) == 0 && ((100*amount)%cnt) != 0) {
    e = $$('form#payment_form input.amount').getRandom();
    e.value = roundNumber(parseFloat(e.value)-0.01,2)
  }
}

function donationMachine() {
  var one_time = $('payment_one_time');
  var hourly_rate = $('payment_hourly_rate');
  var pledge_select = $('payment_pledge_select');
  var pledge_other = $('payment_pledge_other');
  var credit_amount = $('payment_credit_amount');
  //add the event for the one time form
  if (one_time) {
    one_time.addEvent('blur',function(event) {
      split_donations(one_time.value,'one_time')
      paymentTotal();
    });
  }
  //add the event for the hourly rate form
  if (hourly_rate) {
    hourly_rate.addEvent('blur',function(event) {
      split_donations(hourly_rate.value,'hour_a_month')
      paymentTotal();
    });
  }
  //add the event for the 2009 pledge deduction form
  if (pledge_select) {
    pledge_select.addEvent('change',function(event) {
      //first clear the other field
      pledge_other.value = '';
      split_donations(pledge_select.value,'pledge');
      paymentTotal();
    });
    pledge_other.addEvent('blur',function(event) {
      //clear the drop down
      pledge_select.value = "";
      split_donations(pledge_other.value,'pledge')
      paymentTotal();
    });
  }
  //add the event for credit cards
  if (credit_amount) {
    credit_amount.addEvent('blur',function(event) {
      split_donations(credit_amount.value,'one_time')
      paymentTotal();
    });
  }
}
//remove all non-numeric values
function strip(input) {
  return input.replace(/[^0-9.]/g,'');
}

function countAllFunds() {
  var countFunds = 0;
  $$('form#payment_form input.amount').each(function(e) {
    countFunds += 1;
  });
  return countFunds
}

function paymentTotal() {
  var total = 0.00;
  $$('form#payment_form input.amount').each(function(e) {
    if (parseFloat(e.value)) {
      total += parseFloat(e.value);
    }
  });
  $('payment_total').value = roundNumber(total,2);
}

function clear_amounts() {
  $$('form#payment_form input.amount').each(function(e) {
    e.value = "";
  });
}

window.addEvent('domready', function() {
  var pform = $('payment_form');
  if (pform) {
    //by default add the donation events they will be re-added upon HTML updates
    donationMachine();
    pform.addEvent('submit', paymentTotal);
  }
  $$('form#payment_form input.amount').each(function(e) {
    e.addEvent('blur', function(event) {
      paymentTotal();
    });
  });
  var honor_of_fields = $('honor_extras');
  $$('input.honor_radio').each(function(e) {
    e.addEvent('focus', function() {
      if (honor_of_fields) {
        honor_of_fields.setStyle('display', 'block')
      }
    });  
  })
});

window.addEvent('domready', function() {
  var whatsthis = $('whatsthis');
  if (whatsthis) {
    $('whatsthis').addEvents({
	    'mouseenter': function(){
		    // Always sets the duration of the tween to 1000 ms and a bouncing transition
		    // And then tweens the height of the element
		    this.set('tween', {
			    duration: 1000,
			    transition: Fx.Transitions.Bounce.easeOut // This could have been also 'bounce:out'
		    }).tween('height', '100px');
	    },
	    'mouseleave': function(){
		    // Resets the tween and changes the element back to its original size
		    this.set('tween', {}).tween('height', '15px');
	    }
    });  
  }
});

window.addEvent('domready', function() {
  var CartDetailsReq = new Request.HTML({update:'cart_details'}).get('/contributions/cart')
  $$('input.clicker').each(function(e) {
    e.addEvent('click', function(ev) {
      if (e.checked) {
        var add_req = new Request.HTML({
          url:'/contributions/add',
          update:'cart_details',
          onComplete: function() {
            give_now();
            $('cart_details').flash('#b3ba24', '#f6f7e3', 3);
          }
        }).get({add:e.id});
      } else {
        var add_req = new Request.HTML({
          url:'/contributions/remove',
          update:'cart_details'
        }).get({add:e.id});
      }
    });
  });
});

