/**
* Set a cookie
* @param string cookie name
* @param string cookie value
* @param string cookie expiration counter in days
* @param string cookie path
* @param string cookie domain
* @param bool secure?
*/
function setCookie( name, value, expires, path, domain, secure ) {
 var today = new Date();
 today.setTime( today.getTime() );
 if ( expires ) {
  expires = expires * 1000 * 60 * 60 * 24;
 }
 var expires_date = new Date( today.getTime() + (expires) );
 document.cookie = name+"="+escape( value ) +
  ( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) +
  ( ( path ) ? ";path=" + path : "" ) +
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ( ( secure ) ? ";secure" : "" );
}

/**
* Get a cookie value
* @param string cookie name
*/
function getCookie( name ) {
 var start = document.cookie.indexOf( name + "=" );
 var len = start + name.length + 1;
 if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
  return null;
 }
 if ( start == -1 ) return null;
 var end = document.cookie.indexOf( ";", len );
 if ( end == -1 ) end = document.cookie.length;
 return unescape( document.cookie.substring( len, end ) );
}

/**
* Remebers form inputs after you fill them in
* @param string a prefix to prepend to all cookie names. (prevent naming conflicts)
*/
function rememberFormInputs(form_id, prefix) {
 // get a reference to the form element with id 'form_test'
 var form = document.getElementById(form_id);
 // get all child input elements of the form
 var els = document.getElementsByTagName('input');
 // iterate through all form child input elements
 for (var i = 0; i < els.length; i++) {
  // this is the element with index of i
  var el = els.item(i);
  // make sure this is a text input field
  if (el.type == 'text') {
  
   // event handler to catch onblur events
   // it sets the cookie values each time you move out of an input field
   el.onblur = function() {
    // this is the name of the input field
    var name = this.name;
    // this is the value of the input field
    var value = this.value;
    // set the cookie
    setCookie( prefix + name, value);
    alert('setCookie: '+name + ' = '+value);
   };
   
   // this inserts all the remembered cookie values into the input fields
   var old_value = getCookie(prefix + el.name);
   if (old_value && old_value != '') {
    alert('old value remembered: '+old_value);
    el.value = old_value;
   }
  }
 }
}

// function will be run after window/document loads
window.onload = function() {
 rememberFormInputs('form', 'input-' ,'select-', 'option-', 'textarea-');
}

// overload alert
function alert(str) {
 var el = document.getElementById('alert');
 if (el) {
  el.value += str+"\r\n";
 }
}


