/* Surveys JS */

log = function (msg) { console.log(msg); };
Dom = YAHOO.util.Dom; Element = YAHOO.util.Element; Event = YAHOO.util.Event; Connect = YAHOO.util.Connect;
$ = Dom.get;

var f;

var AutoSurvey = function() {
  var f = null;
  return {
	 init : function() {
		f = $('survey');
		Dom.getElementsByClassName('grid','table',f, AutoSurvey.init_grid);
		Event.on(f,'submit',AutoSurvey.form_submit, f);
	 },
	 init_grid : function(g) {
		var total = g.getAttribute('total');
		var total_text = g.getAttribute('total_text');
		if (total != null) {
		  Dom.getElementsByClassName('number','input',g, function(input) {
			 Event.on(input,'change',AutoSurvey.input_change, g);
		  });
		  AutoSurvey.refresh_grid(g);
		}

	 },
	 form_submit : function (e, f) {
		Dom.getElementsByClassName('required','input',f, function(g) {
											  if (!g.checked) {
												 alert(g.getAttribute('message'));
												 Event.stopEvent(e);
											  }
		  });
		/*
		Dom.getElementsByClassName('percentage','table',f, function(g) {
		  var total = AutoSurvey.total_grid(g);
		  if (total != 100) {
			 alert('Please ensure that all percentages total to 100%.');
			 Event.stopEvent(e);
		  }
		});
		*/
	 },
	 input_change : function(e,g) {
		AutoSurvey.refresh_grid(g);
	 },
	 refresh_grid : function(g) {
		var total = AutoSurvey.total_grid(g);
		f[g.getAttribute('total')].value = AutoSurvey.format_number(total);
		$(g.getAttribute('total_text')).innerHTML = AutoSurvey.format_number(total);
	 },
	 total_grid : function(g) {
		var total = 0;
		Dom.getElementsByClassName('number','input',g, function(input) { total += AutoSurvey.get_number(input.value); });
		return total;
	 },
	 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;
	 },
	 format_money : function(v) {
		return "$ "+AutoSurvey.addCommas(v);
	 },
	 format_number: function(v) {
		return AutoSurvey.addCommas(v);
	 },
    get_number : function(v) {
		var fv = parseFloat(v.replace(/,/g,''));
		if (fv+'' == 'NaN') {
		  return 0;
		}
		return (v == '') ? 0 : fv;
	 }


  };
}();

Event.onDOMReady(AutoSurvey.init);



