function escape(str) {
    if(typeof(str) == "string") {
        str = str.replace(/&/g, "&amp;");
        str = str.replace(/"/g, "&quot;");
        str = str.replace(/'/g, "&#039;");
        str = str.replace(/</g, "&lt;");
        str = str.replace(/>/g, "&gt;");
    }
    return str;
}

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 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();
}

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

$(document).ready(function(){
    $.ajaxSetup({
        error: function(x,e){
            if(x.status==0) {
                // Do nothing, this results in bad popups if changing pages fast
            } else if(x.status==404) {
                alert('Requested URL not found.');
            } else if(x.status==302) {
                window.location = x.responseText;
            } else if(x.status==500) {
                if(x.responseText == 'Bad Token') {
                    alert('Page timeout.  Please reload the page.');
                } else {
                    alert('Internal Server Error.');
                }
            } else if(e=='parsererror') {
                alert('Error.\nParsing request failed.');
            } else if(e=='timeout') {
                alert('Request Time out.');
            } else {
                alert('Unknow Error.\n'+x.responseText);
            }
        }
    });
});

