function toggle_checkboxes(toggle, pattern) {
  var match = /ids.*/;
  if(pattern){ match = pattern; }

  var active_form = toggle.form;
  for(x = 0; x < active_form.length; x++){
    if(active_form[x].type == 'checkbox'){
      if(active_form[x].name.search(match) >= 0 && active_form[x].name != toggle.name){
        if (toggle.checked == true) {
          active_form[x].setAttribute('checked', 'checked');
        } else {
          active_form[x].removeAttribute('checked');
        }
      }
    }
  }
}

function validate_redemption(arv){
  value = $('value').value;
  arv = (arv/100).toFixed(2);
  if (value.match(/[a-zA-Z]/)) {
    alert("The price you entered is invalid. Price must be numeric.");
    $('value').value = arv;
    return false;
  } else if(value != arv){
    if(!confirm("Are you sure this is the correct amount? Assumed Redemption Value for this coupon is $"+arv)){
      return false;
    }
  }
  $('mr_form').submit();
}

function save_coupon(anchor){
  anchor.onclick = "#";
  var link = anchor.href;
  anchor.href = "#";
  new Ajax.Request(link, {asynchronous:true, evalScripts:true}); return false;
}

function pop_and_resize(url) {
  var ideal_width, ideal_height;
  var actual_width, actual_height;
  ideal_width = 970;
  ideal_height = 800;
  if(screen.availWidth < ideal_width) { 
    actual_width =  screen.availWidth;
  } else {
    actual_width =  ideal_width;
  }
  if(screen.availHeight < ideal_height) { 
    actual_height =  screen.availHeight;
  } else {
    actual_height =  ideal_height;
  }
  window.open(url ,'_blank','width=' + actual_width + ',height=' + actual_height + ',menubar=yes,toolbar=yes,resizable=yes,scrollbars=yes');
}

// TODO : multiline matching does not work (javascript only; ruby works)
// TODO : multi wrappers don't work; *_word_* _*word*_, etc.
  function $format_as_html(text) {
    return simple_format( encode_markup(text) )
  }

function encode_markup(text) {
  // text = text.replace(/<.*?>/gm, ''); // Used instead of Prototype's escapeHTML function as this caused newline characters to disappear IE
  text = text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  return text.replace(/\(R\)/g, "&#174;").replace(/\(TM\)/g, "&#8482;").replace(/(^| )\[(.+?)\]( |$|\r\n|\n)/gm, '$1<span class="no-wrap">$2</span>$3').replace(/(^| )\*(.+?)\*( |$|\r\n|\n)/gm, '$1<strong>$2</strong>$3').replace(/(^| )_(.+?)_( |$|\r\n|\n)/gm, '$1<em>$2</em>$3')
}

function simple_format(text) {
  text = text.replace(/\(CR\)/g, "\n"); // Make it backwards compatible with old method of formatting line breaks
  new_text = text.replace(/\r\n?/g, "\n").replace(/\n\n+/g, "</p>\n\n<p>").replace(/([^\n]\n)(?=[^\n])/g, '$1<br />');
  return "<p>" + new_text + "</p>"
}

