var UCIAA = {};

UCIAA.PHP = {};

UCIAA.PHP.number_format = function(number, decimals, dec_point, thousands_sep) {
	var n = !isFinite(+number) ? 0 : +number, 
	prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
	sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
	dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
	s = '',
	toFixedFix = function (n, prec) {
		var k = Math.pow(10, prec);
		return '' + Math.round(n * k) / k;
	};
	s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
	if (s[0].length > 3)
	{
		s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
	}
	if ((s[1] || '').length < prec)
	{
		s[1] = s[1] || '';
		s[1] += new Array(prec - s[1].length + 1).join('0');
	}
	return s.join(dec);
}
UCIAA.PHP.mstime=function(){return (new Date().getTime());};
UCIAA.PHP.time=function(){return Math.round(UCIAA.PHP.mstime()/1000.0);};


UCIAA.MoneyTicker = Class.create({},{
	initialize: function(){
		this.options = Object.extend({
			container: null,
			startamount: 20000,
			updatefrequency: 2
		}, arguments[0] || { });
		this.currentamount = this.options.startamount;
		this.options.container = $(this.options.container);
		this.updater = new PeriodicalExecuter(this.runTimer.bind(this), this.options.updatefrequency);
	},
	updateTicker: function(){
		this.options.container.update("$"+UCIAA.PHP.number_format(this.currentamount)+"!");
	},
	runTimer: function(pe){
		this.getMoneyAmount();
	},
	getMoneyAmount: function(){
		this.currentamount = parseInt(this.currentamount)+Math.floor(Math.random()*100);	
		this.updateTicker();
	}
});





UCIAA.DonationScroller = Class.create({},{
	
	initialize: function(){
	
		this.options = Object.extend({
			container: null,
			causename: "CAUSE",
			groupid: 0,
			subgroupid: 0,
			decay: 2,
			numdonations:10,
			frequency: 30,
			asof: 0,
			chartdiv:null
		}, arguments[0] || { });
		
		this.options.container = $(this.options.container);
		this.options.chartdiv = $(this.options.chartdiv);
		this.fakeelm = new Element('div');
		
		this.donationslist = new Array();
		
		this.updateRequest = new Ajax.PeriodicalUpdater(this.fakeelm, this.buildURL(),{
			method:'get',
			decay:this.options.decay,
			frequency:this.options.frequency,
			onSuccess:this.requestCallback.bind(this)
		});
	},
	
	buildURL: function(){
		return '/ajax/latest_donations.php?gid='+this.options.groupid+'&sgid='+this.options.subgroupid+'&asof='+this.options.asof;
	},
	
	requestCallback: function(resp){
		// update the url so that we send our "as of" time (so we arent resending a whole array)
		this.options.asof = resp.responseJSON.asof;
		this.updateRequest.url = this.buildURL();
		
		// push the new donations onto the front
		if(resp.responseJSON.donations.length>0)
		{
			for(var i=0;i<resp.responseJSON.donations.length;i++)
			{
				this.donationslist.unshift(resp.responseJSON.donations[i]);
			}
		}
		
		// if we have too many, pop some off
		if(this.donationslist.length>this.options.numdonations)
		{
			var shiftoff = this.donationslist.length - this.options.numdonations;
			for(var j=0;j<shiftoff;j++)
			{
				this.donationslist.pop();
			}
		}
		
		// draw the list
		this.drawDonationList();
	},
	
	drawDonationList: function(){
		if(this.donationslist.length>0)
		{
			var list = new Element('ul').addClassName("nobullet").addClassName("donationlist");
			
			for(var i=0;i<this.donationslist.length;i++)
			{	
				var listitem = new Element('li');
				listitem.update("<b>"+this.donationslist[i].person+"</b> just gave <b>$"+UCIAA.PHP.number_format(this.donationslist[i].amount,2)+"</b> to support "+this.options.causename);
				list.insert(listitem);
			}
			this.options.container.update(list);
		}
		else
		{
			this.options.container.update();
		}
	}
});


UCIAA.SGRegister = Class.create({},{
	
	initialize: function(){
		
		this.options = Object.extend({
			groupid: 0
		}, arguments[0] || { });

		
		this.radios = $$('input.jtype_radio');
		this.jtdivs = $$('div.jtype_div');
		
		for(var i=0;i<this.radios.size();i++)
		{
			this.radios[i].observe('change',this.onRadioChange.bindAsEventListener(this));
		}
		
		this.newgroupurltb = $('newgroup_url');
		this.newgroup_check = $('subgroupurl_check');
		
		this.newgroupurltb.observe('keyup', this.checkNewGroupURL.bindAsEventListener(this));
		
	},
	
	checkNewGroupURL: function(event){
		var url = this.newgroupurltb.value;
		
		if(url.length<=4)
		{
			this.newgroup_check.update(" ");
			return;
		}
		
		this.sendSGUrlCheck(url);
	},
	
	sendSGUrlCheck: function(url){
		new Ajax.Request('/ajax_check_subgroup_url.php?gid='+this.options.groupid+'&url='+encodeURIComponent(url),{
			method:'get',
			onSuccess: this.sgUrlCheckOK.bind(this),
			onFailure: this.sgUrlCheckFAIL.bind(this)
		});
	},
	sgUrlCheckOK: function(resp){
		this.newgroup_check.update(new Element('b').addClassName("green").update(resp.responseText+" is available"));
	},
	sgUrlCheckFAIL: function(resp){
		this.newgroup_check.update(new Element('b').addClassName("red").update(resp.responseText+" is already taken"));
	},
	
	onRadioChange: function(event){
		for(var i=0;i<this.jtdivs.size();i++)
		{
			this.jtdivs[i].hide();
		}
		
		for(var i=0;i<this.radios.size();i++)
		{
			if(this.radios[i].checked==1)
			{
				var id = this.radios[i].readAttribute("jtypeshow");
				if(id.length>0)
				{
					$(id).show();
				}
			}
		}
	}
	
});



UCIAA.Countdown = Class.create({},{
	initialize: function(){
		
		this.options = Object.extend({
			goaldate: group_start_date,//"02/25/2011 6:00 PM",
			runevery: 1,//seconds
			//displayFormat: "%%D%%days, %%H%%hours, %%M%%minutes, %%S%%seconds.",
			displayFormat: "%%D%% days, %%H%% hours, %%M%% minutes, %%S%% seconds",
			container: null
		}, arguments[0] || { });
		
		this.options.container = $(this.options.container);
		this.timer = new PeriodicalExecuter(this.updateTimer.bind(this),this.options.runevery);
		
		this.dthen = new Date(this.options.goaldate);
		this.dnow = new Date();
		if(false)
		{
			this.ddiff = new Date(this.dnow-this.dthen);
		}
		else
		{
			this.ddiff = new Date(this.dthen-this.dnow);
		}
		this.gsecs = Math.floor(this.ddiff.valueOf()/1000);
		
		this.updateTimer();
		
	},
	
	calcage: function(num1, num2) {
		return "<b>" + (((Math.floor(this.gsecs/num1))%num2).toString()) + "</b>";
		//return (((Math.floor(this.gsecs/num1))%num2).toString());
	},
	
	updateTimer: function(){
		
		var DisplayStr = this.options.displayFormat.replace(/%%D%%/g, this.calcage(86400,100000));
  		DisplayStr = DisplayStr.replace(/%%H%%/g, this.calcage(3600,24));
  		DisplayStr = DisplayStr.replace(/%%M%%/g, this.calcage(60,60));
  		DisplayStr = DisplayStr.replace(/%%S%%/g, this.calcage(1,60));
		this.gsecs = this.gsecs - this.options.runevery;
		this.options.container.update(DisplayStr);
	}


});

document.observe("dom:loaded", function() {
var countdownNode = $('countdown');
if(countdownNode!=null) {
	new UCIAA.Countdown({
		container:'countdown'
	});
}
});

// TODO: Add an if #countdown exists, then just setup this contstructor automatically


UCIAA.DonateValidate = Class.create({},{
	initialize: function(){
		
		this.options = Object.extend({
			amount_var: 'ccAmount',
			amount_tb: 'other_amount',
			submitbutton: 'donate_submit',
			radioClass: 'donateRadio',
			container: null
		}, arguments[0] || { });
	
		this.options.amount_var = $(this.options.amount_var);
		this.options.amount_tb = $(this.options.amount_tb);
		this.options.submitbutton = $(this.options.submitbutton);
		
		
		this.options.submitbutton.observe('click',this.submitButtonClick.bindAsEventListener(this));
		
		this.radio_buttons = $$('input.'+this.options.radioClass);
		
		this.standard_buttons = new Array();
		this.other_radio_button = null;
		
		// Find the "other" one
		for(var i=0;i<this.radio_buttons.size();i++)
		{
			if(this.radio_buttons[i].value=="OTHER")
			{
				this.other_radio_button = this.radio_buttons[i];
			}
			else
			{
				this.standard_buttons.push(this.radio_buttons[i]);
			}
		}
		
		this.other_radio_button.observe('change',this.otherRadioChange.bindAsEventListener(this));
		this.options.amount_tb.observe('focus',this.focusOtherBox.bindAsEventListener(this));
		this.options.amount_tb.observe('keypress',this.typeInOtherBox.bindAsEventListener(this));
		
		
		// Bind the clicks for all other radio buttons
		for(var i=0;i<this.standard_buttons.size();i++)
		{
			this.standard_buttons[i].observe('change', this.standardRadioChange.bindAsEventListener(this));
		}
	},
	
	standardRadioChange: function(event){
		if(event.element().checked==1)
		{
			this.options.amount_var.value = event.element().value;
			//console.log("setting donation to "+this.options.amount_var.value);
		}
	},
	
	typeInOtherBox: function(event){
		if( (event.charCode>=48 && event.charCode<=57) || event.charCode==46 || event.keyCode>0 )
		{
			/*Let these thru, they are valid numbers, ., escape codes*/
			//this.options.amount_var.value = this.options.amount_tb.value;
		}
		else
		{
			event.stop();
		}
		//console.log(event);
	},
	focusOtherBox: function(event){
		this.other_radio_button.checked = 1;
	},
	
	otherRadioChange: function(event){
		if(this.other_radio_button.checked==1)
		{
			this.options.amount_var.value = this.options.amount_tb.value;
			
			this.options.amount_tb.select();
		}
	},
	
	submitButtonClick: function(event){
	
		if(this.other_radio_button.checked==1)
		{
			this.options.amount_var.value = this.options.amount_tb.value;
		}
	
		if(/^[0-9]+\.[0-9]+$/.test(this.options.amount_var.value))
		{
			if(parseFloat(this.options.amount_var.value)<5.0)
			{
				event.stop();
				alert("Your donation amount must be greater than $5.00");
			}
		}
		else if(/^[0-9]+$/.test(this.options.amount_var.value))
		{
			if(parseInt(this.options.amount_var.value)<5)
			{
				event.stop();
				alert("Your donation amount must be greater than $5.00");
			}
		}
		else
		{
			event.stop();
			alert("You must select a donation amount.");
		}
	}
});




/*
UCIAA.DonorHonorRoll = Class.create({},{
	
	initialize: function(){
	
		this.options = Object.extend({
			container: null,
			causename: "CAUSE",
			groupid: 0,
			decay: 2,
			numdonations:10,
			frequency: 30,
			asof: 0,
			chartdiv:null
		}, arguments[0] || { });
		
		this.options.container = $(this.options.container);
		this.options.chartdiv = $(this.options.chartdiv);
		this.fakeelm = new Element('div');
		
		this.donationslist = new Array();
		
		this.updateRequest = new Ajax.PeriodicalUpdater(this.fakeelm, this.buildURL(),{
			method:'get',
			decay:this.options.decay,
			frequency:this.options.frequency,
			onSuccess:this.requestCallback.bind(this)
		});
	},
	
	buildURL: function(){
		return '/ajax/donor_honor_roll.php?gid='+this.options.groupid+'&asof='+this.options.asof;
	},
	
	requestCallback: function(resp){
		// update the url so that we send our "as of" time (so we arent resending a whole array)
		this.options.asof = resp.responseJSON.asof;
		this.updateRequest.url = this.buildURL();
		
		// push the new donations onto the front
		if(resp.responseJSON.donations.length>0)
		{
			for(var i=0;i<resp.responseJSON.donations.length;i++)
			{
				this.donationslist.unshift(resp.responseJSON.donations[i]);
			}
		}
		
		// if we have too many, pop some off
		if(this.donationslist.length>this.options.numdonations)
		{
			var shiftoff = this.donationslist.length - this.options.numdonations;
			for(var j=0;j<shiftoff;j++)
			{
				this.donationslist.pop();
			}
		}
		
		// draw the list
		this.drawDonationList();
	},
	
	drawDonationList: function(){
		if(this.donationslist.length>0)
		{
			var list = new Element('ul').addClassName("nobullet").addClassName("donationlist");
			
			for(var i=0;i<this.donationslist.length;i++)
			{	
				var listitem = new Element('li');
				listitem.update("<b>"+this.donationslist[i].person+"</b> just gave <b>$"+UCIAA.PHP.number_format(this.donationslist[i].amount,2)+"</b> to support "+this.options.causename);
				list.insert(listitem);
			}
			this.options.container.update(list);
		}
		else
		{
			this.options.container.update();
		}
	}
});

*/




