// Author: Josh Rosenbaum
// Company: InfoGears (www.infogears.com)
// Copyright InfoGears 2006.
// Date: 2006-04-21
// Version 0.2
// You can get access to this file from:
// http://www.infogears.com/cgi-bin/infogears/javascript_prevent_double_form_submit_click.html
//
// Feel free to contact us here:
// http://www.infogears.com/cgi-bin/infogears/contact.html
//
// Usage of this file is granted, however, you may not remove this header, and you
// may not distribute the file. If you want to place the code in another file, this
// header must remain with the code. Use the link above to access the latest version.
//
// Usage:
// <form name='xyzds'>
// <input value="Submit" onclick="return disable_double_click(this.form.name, this, 5000);" type="submit"> 
// </form>
// The 5000 is the time to disable for in milliseconds.
// Note that your form must be named. This may change in the future, though.



// Safe Protect -- This does not involve disabling the button, but instead stops the user from clicking
// twice by setting a global variable letting us know it has already been clicked.
var safe_protect_elements = new Object;
var safe_protect_timer_elements = new Object;
function disable_double_click(form_name, element, time_ms ){
  // We could use "form_name + element.name", but I thought it'd be better to disable all buttons marked
  // as safe on the form.
  var key = form_name;

  if (safe_protect_elements[key]){
    return false;
  }

  safe_protect_elements[key] = element;

  var time_left_secs = parseInt(time_ms/1000);
  var time_display = document.createElement("SPAN");
  safe_protect_timer_elements[key] = element.parentNode.insertBefore(time_display, element.nextSibling);
  safe_protect_timer_elements[key].innerHTML = "<font color='red'><b>(" + time_left_secs +")</b></font>";

  setTimeout("safe_protect_timer_display('" + key + "', " + time_ms + ")", '1000');
  setTimeout("enable_double_click('" + key + "')", time_ms);

  return true;
}

function safe_protect_timer_display(key, time_left_ms){
  if (!safe_protect_elements[key]){
    return false;
  }

  if (!safe_protect_timer_elements[key]){
    return false;
  }

  time_left_ms -= 1000;

  var time_left_secs = parseInt(time_left_ms/1000);
  var timer_display = safe_protect_timer_elements[key];
  timer_display.innerHTML = "<font color='red'><b>(" + time_left_secs +")</b></font>";
  if (time_left_ms > 1100){ // only go down to 1 second. go to 0 if we have a 100ms lee way.
    setTimeout("safe_protect_timer_display('" + key + "', " + time_left_ms + ")", '1000');
  }
  return true;
}

function enable_double_click(key){
  if (!key){
    return false;
  }

  if (safe_protect_elements[key]){
    var e = safe_protect_elements[key];
    var timer_display = safe_protect_timer_elements[key];
    if (timer_display){
      e.parentNode.removeChild(timer_display);
    }
    safe_protect_elements[key] = null;
  }
  
  return true;
}

