// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function remove_student_member(id) {
  Element.replace('student_'+id, '');
}

function select_student_type(type) {
  if (type == 'single') {
    $('student_single').style.display = 'block';
    $('student_group').style.display = 'none';
    $('student_results').style.display = 'block';
  } else {
    $('student_single').style.display = 'none';
    $('student_group').style.display = 'block';
    $('student_results').style.display = 'none';
  }
}

function select_unit_type(type) {
  if (type == 'single') {
    $('unit_single').style.display = 'block';
    $('unit_group').style.display = 'none';
    $('unit_results').style.display = 'block';
  } else {
    $('unit_single').style.display = 'none';
    $('unit_group').style.display = 'block';
    $('unit_results').style.display = 'none';
  }
}

function is_verification_code_valid(value) {
  return value && value.match(/^\d{6}$/);
}

function count_selected_enrolments(form_name) {
  var boxes = $(form_name).getElementsByClassName('radiobox');
  var sum = 0;
  for(var idx = 0; idx < boxes.length; idx++) {
    if (boxes[idx].id != 'terms' && boxes[idx].checked == true ) sum += 1;
  }
  return sum;
}

function confirm_sms_recipients() {
	if ($('should_send_sms').checked) {
		/* Count the recipients */
		count = parseInt($$('#visible_recipients li').length);
		if ($('recipients[all_students]') && $('recipients[all_students]').checked) {
			count += parseInt($F('all_students_count'));
		}
		if ($('recipients[all_trainers]') && $('recipients[all_trainers]').checked) {
			count += parseInt($F('all_trainers_count'));
		}
		price = (parseFloat(count) * 20.00)/100.00;
		return confirm("You are about to send " + count + " SMS messages totalling $" + roundNumber(price, 2) + " (+GST). Do you wish to proceed?");
	}
	return true;
}

function toggle_sms() {
	if ($('should_send_sms').checked) {
		$('subject_field').style.display = 'none';
		$('message_message_note').style.display = 'inline';
		FormHelpers.limiter._perform_limit($('message_message'));
	} else {
		$('message_message_limit').update('');
		$('subject_field').style.display = 'block';
		$('message_message_note').style.display = 'none';
	}
}

function roundNumber(num, dec) {
	var res = parseFloat(Math.round(num*Math.pow(10,dec))/Math.pow(10,dec));
	var split = res.toString().split('.');
	if (split[1].length == 1) {
		return res.toString() + "0";
	} else {
		return res;
	}
}

var FormHelpers = {

  checker: {

    all: function(button, style) {
      var checkboxes = $$(style);
      var checked = button.all_checked ? false : true;
      for(var i = 0, l = checkboxes.length; i < l; i++)
        checkboxes[i].checked = checked;
      button.all_checked = checked;
      button.update(checked ? 'Deselect all' : 'Select all');
    }

  },

  limiter: {

    CLASS_NAME_ERROR: 'form_limiter_error',
    CLASS_NAME_OK: 'form_limiter_ok',

    touch: function(field) {
      field = $(field);
      if(!field.limiter_touched) {
        field.observe('keyup', this._key_response.bind(this));
        field.observe('keydown', this._key_response.bind(this));
        field.limiter_touched = true;
      }
      return field;
    },

    maximum: function(field, max) {
      field = this.touch(field);
      field.maximum = parseInt(max);
      this._perform_limit(field);
    },

    minimum: function(field, min) {
      field = this.touch(field);
      field.minimum = parseInt(min);
      this._perform_limit(field);
    },

    _key_response: function(event) {
      this._perform_limit(Event.element(event));
    },

    _perform_limit: function(field) {
      if (!$('should_send_sms')) return;
      if (!$('should_send_sms').checked) return;
      var limiter = $(field.id + '_limit');
      var length = field.value.length;

      if(field.minimum)
        limiter.className = (length < field.minimum) ? this.CLASS_NAME_ERROR : this.CLASS_NAME_OK;

      // We check here to make sure the above validation didnt error.
      if((field.maximum && limiter.className == this.CLASS_NAME_OK) || (field.maximum && !field.minimum)) {
        if(length >= field.maximum) {
          limiter.className = this.CLASS_NAME_ERROR;
        } else {
          limiter.className = this.CLASS_NAME_OK;
        }
      }

      limiter.update(field.maximum - length);
    } 
  }
};

var AsyncUpload = window.AsyncUpload = {
  apply: function(selector, submit_selector) {
    jQuery.noConflict();
    jQuery(selector).val(null); // blank after reload
    jQuery(function(){
      jQuery(selector).bind("change", {submit_selector:submit_selector}, AsyncUpload.handleChanged);
    });
  },
  disableSubmit: function(submit_selector) {
    jQuery(submit_selector).attr('disabled', 'disabled');
    jQuery(submit_selector).css('cursor', 'wait');
    jQuery(submit_selector).attr('src', '/images/buttons/save_disabled.png');
  },
  enableSubmit: function(submit_selector) {
    jQuery(submit_selector).removeAttr('disabled');
    jQuery(submit_selector).css('cursor', '');
    jQuery(submit_selector).attr('src', '/images/buttons/save.png');
  },
  handleChanged: function(event) {
    var submit_selector = event.data.submit_selector;
    var input_id = jQuery(this).attr('id');
    // PROGRESS BAR GOES HERE!
    // Attach progress div
    jQuery("<div id=\""+ input_id + "_progress\"><image src='/images/spinner_small.gif'/>Uploading... while uploading, please do not navigate away from this page.</div>").insertBefore( jQuery('#'+input_id+'_note') );

    // Disable submit button until the upload completes
    AsyncUpload.disableSubmit(submit_selector);
    jQuery('#' + input_id + '_remove').hide();

    // Move the input to the async upload form
    jQuery("#async-file-upload-"+input_id).append(jQuery(this));

    // Submit the async upload form
    jQuery("#async-file-upload-"+input_id).ajaxSubmit({
      beforeSubmit: function(a,f,o) {
       o.dataType = 'json';
      },
      complete: function(xhr, textStatus) {
        AsyncUpload.uploadComplete(xhr, textStatus, submit_selector, input_id);
        if( jQuery('[id$=progress]').size() == 0 ) {
          AsyncUpload.enableSubmit(submit_selector);
        }
      }
    });
  },
  uploadComplete: function(xhr, textStatus, submit_selector, node_id) {
    try {
      var result = jQuery.parseJSON(xhr.responseText);

      jQuery.each(result, function(id,val) {
        node = jQuery("#answers_"+id+"_progress").parent();
        node.html(val);
        node.append("<br>");
        node.append('<span id="answers_'+id+'_wrapper"/>');
        node.append('<p class="file_upload_note" id="answers_'+id+'_note">Optimum file size should be less than 7MB</p>');
        document.getElementById('async-file-upload-answers_'+id).reset();
        node.children('#answers_'+id+'_wrapper').append(jQuery('#'+node_id));
      });
    } catch (e) { // TODO: specify exception
      alert('There was an error submitting the file.  Please try again later.');
      node = jQuery('#' + node_id + '_progress').parent();
      document.getElementById('async-file-upload-'+node_id).reset();
      node.children('#'+node_id+'_wrapper').append(jQuery('#'+node_id));
      jQuery('#' + node_id + '_progress').remove();
    }
    jQuery('#' + node_id + '_remove').show();
  }
};

