function textCounter (field, countfield, maxlimit) {
      if (field.value.length > maxlimit) {
        field.value = field.value.substring(0, maxlimit);
      } else { 
        countfield.value = maxlimit - field.value.length;
      }
}

function addOption(selectId, val, txt) {
    var objOption = new Option(txt, val);
    document.getElementById(selectId).options.add(objOption);
}

function rewrite(text, target, validchars, separator) {
    var str = "";
    var i;
    var exp_reg = new RegExp("[" + validchars + separator + "]");
    var exp_reg_space = new RegExp("[ ]");
    text.toString();
    for (i=0; i < text.length; i++) {
        if (exp_reg.test(text.charAt(i))) {
            str = str+text.charAt(i);
        } else {
            if (exp_reg_space.test(text.charAt(i))) {
                if (str.charAt(str.length-1) != separator) {
                    str = str + separator;
                }
            }
        }
    }
    if (str.charAt(str.length-1) == separator) str = str.substr(0, str.length-1);
    document.getElementById(target).value = str.toLowerCase();
}

function newWindowWrite(title,content,width,height) {
    top.consoleRef = window.open('','myconsole',
        'width='+width+',height='+height
        +',menubar=0'
        +',toolbar=1'
        +',status=0'
        +',scrollbars=1'
        +',resizable=1'
    )
    top.consoleRef.document.writeln(
        '<html><head><title>'+title+'</title></head>'
        +'<body bgcolor=white onLoad="self.focus()">'
        +content
        +'</body></html>'
    )
    top.consoleRef.document.close()
}

function newWindow (mypage,myname,w,h,features) {
    if(screen.width) {
          var winl = (screen.width-w)/2;
          var wint = (screen.height-h)/2;
      } else {
          winl = 0;wint =0;
      }

      if (winl < 0) winl = 0;
      if (wint < 0) wint = 0;

      var settings = 'height=' + h + ',';
      settings += 'width=' + w + ',';
      settings += 'top=' + wint + ',';
      settings += 'left=' + winl + ',';
      settings += features;
      settings += ' scrollbars=yes ';

      win = window.open(mypage,myname,settings);

      win.window.focus();
}

function count_words(element,counter_element){
    var y=element.value;
    var r = 0;
    a=y.replace(/\s/g,' ');
    a=a.split(' ');
    for (z=0; z<a.length; z++) {
        if (a[z].length > 0) r++;
    }
    counter_element.value=r;
}

var timer_handles = [];    
function set_timer(id,code,time) {
    if(id in timer_handles) {
        clearTimeout(timer_handles[id]);
    }
    timer_handles[id] = setTimeout(code,time)
}


function checkAll(field) {
    var checked_value = field[0].checked;
    for (i=0; i<field.length; i++) {
        field[i].checked = !checked_value;
    }
}
