var BudgetForm = Class.create();

BudgetForm.prototype = {
	
	initialize: function(el) {	
		
		var ad_format_class = '.ad_format';
		var budgetTable = $('budget');
		var budgetSelf  = $('budget_self');
		var impressionsSelf = $('impressions_self');
		var pleaseSelect = $('please_select');
		var minimumBudget = $('minimum_budget');
		var me = this;
		
		this.minimumBudget = minimumBudget.innerHTML; // Dollars
		this.current_price = 0;
		this.budgetTable   = budgetTable;
		this.budgetSelf    = budgetSelf;
		this.pleaseSelect  = pleaseSelect;
		
		var onlickFunction = function(event) {
			var clicked = Event.element(event);
			me.current_price = parseInt(clicked.readAttribute('rel'));
			me.updatePrices(me.current_price);
			
			if (!budgetTable.visible()) {
				budgetTable.show();
				pleaseSelect.hide();
			}
		};
			
		$$(ad_format_class).each(function(i) {
			i.observe('click', onlickFunction);
		});
		
		budgetSelf.observe('keyup', function(event) {
			var budgetSelf = parseFloat(Event.element(event).value);
			if (budgetSelf >= me.minimumBudget && !isNaN(budgetSelf)) {
				impressionsSelf.update(me.addCommas(Math.floor(budgetSelf / me.current_price * 1000)));
			} else {
				impressionsSelf.update("____");
			}
		});
		
		budgetSelf.observe('focus', function(event) {
			$('user_defined').checked = 'checked';
		});
		
	},
	
	updatePrices: function(price) {
		
		var impressions;
		
		this.budgetTable.down('tbody').childElements().each(function(tr) {
			
			// piss off if there's no input in this row
			if (!tr.down('input')) return;
			
			// this is hopefully "User defined"
			if (isNaN(parseInt(tr.down('input').value))) {
				if (parseInt($F('budget_self')) >= this.minimumBudget) {
					tr.down('span').update(Math.floor($F('budget_self') / price * 1000));
				}
				return;
			}
			
			impressions = tr.down('input').value;
			tr.down('span').update(impressions * price / 1000);
		}.bind(this));
	},
	
	addCommas: function(nStr) {
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	}
	
}


Event.observe(window, "load", function() {	
	// Setup form handler
	new BudgetForm;
});