var debug_mode = false;
var request_type = "GET";
var request_uri = "/main.php?a=";
var pwInterval;

function debug(text) {
    if (debug_mode)
        alert("RSD: " + text)
}

function init_xmlhttp() {
    debug("init_xmlhttp() called..")

    var A;
    try {
        A=new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            A=new ActiveXObject("Microsoft.XMLHTTP");
        } catch (oc) {
            A=null;
        }
    }
    if(!A && typeof XMLHttpRequest != "undefined")
        A = new XMLHttpRequest();
    if (!A)
        debug("Could not create connection object.");
    return A;
}


function show_wait_cursor() {
    create_please_wait();
    show_please_wait();
    document.body.style.cursor = "progress";
}

function show_default_cursor() {
    hide_please_wait();
    document.body.style.cursor = "default";
}

function rand_str() {
    var chars = "0123456789abcdefghiklmnopqrstuvwxyz";
    var string_length = 8;
    var randomstring = '';
    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    return randomstring;
}

function call_remote(func_name, args, callback, func_request_type) {
    var i, x, n;
    var uri;
    var post_data;
    var local_request_type;

    show_wait_cursor();

    if (func_request_type)
        local_request_type = func_request_type;
    else
        local_request_type = request_type;

    uri = request_uri  + escape(func_name);
    if (local_request_type == "GET") {
        for (i = 0; i < args.length; i++) {
            argvar = args[i].substring(0,args[i].indexOf("="));
            argval = args[i].substring(args[i].indexOf("=")+1);
            uri = uri + "&" + argvar + "=" + encodeURIParam(argval);
        }
        post_data = null;
    } else {
        for (i = 0; i < args.length; i++) {
            argvar = args[i].substring(0,args[i].indexOf("="));
            argval = args[i].substring(args[i].indexOf("=")+1);
            post_data = post_data != null ? post_data + "&" : '';
            post_data = post_data + argvar + "=" + encodeURIParam(argval);
        }
    }
    uri = uri  + '&rstr=' + rand_str();

    x = init_xmlhttp();
    x.open(local_request_type, uri, true);
    if (local_request_type == "POST") {
        x.setRequestHeader("Method", "POST " + uri + " HTTP/1.1");
        x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");// charset=utf-8");
    }
    x.onreadystatechange = function() {
        if (x.readyState != 4)
            return;
        debug("received " + x.responseText);

        var data;
        data = x.responseText;
        show_default_cursor();
        if (data == "") {
            //alert("Error: no data");
        } else {
            callback(data, args);
        }
    }
    x.send(post_data);
    //alert(func_name + " uri = " + uri + "/post = " + post_data);
    debug(func_name + " uri = " + uri + "/post = " + post_data);
    debug(func_name + " waiting..");
    delete x;
}

function set_div(divid, html) {
    if (document.getElementById) { // DOM3 = IE5, NS6
        document.getElementById(divid).innerHTML = html;
    } else {
        if (document.layers) {
            document.divid.innerHTML = html;
        } else {
            document.all.divid.innerHTML = html;
        }
    }
}

function show_div(divid) {
    if (document.getElementById) { // DOM3 = IE5, NS6
        document.getElementById(divid).style.visibility = 'visible';
    } else {
        if (document.layers) {
            document.divid.style.visibility = 'visible';
        } else {
            document.all.divid.style.visibility = 'visible';
        }
    }
}

function hide_div(divid) {
    if (document.getElementById) { // DOM3 = IE5, NS6
        document.getElementById(divid).style.visibility = 'hidden';
    } else {
        if (document.layers) {
            document.divid.style.visibility = 'hidden';
        } else {
            document.all.divid.style.visibility = 'hidden';
        }
    }
}

function debug_array(array) {
    alertTxt = 'Array has ' + array.length + ' elements:\n';
    for(i=0; i < array.length; i++) {
        alertTxt += ' - ' + array[i] + '\n';
    }
    alert(alertTxt);
}

function process_form(form) {
    args = Array();
    for(i = 0; i < form.elements.length; i++) {
        element = form.elements[i];
        if ( element.type == 'select-one') {
            args.push(element.name + '=' + element.options[element.selectedIndex].value);
        } else if ( element.type == 'checkbox' || element.type == 'radio' ) {
            if ( element.checked ) {
                args.push(element.name + '=' + element.value);
            }
        } else {
            args.push(element.name + '=' + element.value);
        }
    }
    return args;
}

function create_please_wait() {
    if (!document.getElementById('please_wait')) {
        var x = document.createElement('span');
        x.id  = 'please_wait';
        x.innerHTML = ' Please Wait... ';

        x.style['position']        = 'absolute';
        x.style['visibility']      = 'hidden';
        x.style['backgroundColor'] = '#FF0000';
        x.style['color']           = '#FFFFFF';
        x.style['border']          = '1px #000000 solid';
        x.style['padding']         = '1px';
        x.style['fontWeight']      = 'bold';

        document.body.appendChild(x);
        position_please_wait();
    }
}

function position_please_wait(){
    var y_offset = 1;
    var x_offset = 4;
    var pw = document.getElementById('please_wait');
    var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
    var dsocleft = document.all ? iebody.scrollLeft : pageXOffset;
    var dsoctop = document.all ? iebody.scrollTop : pageYOffset;

    if (document.all || document.getElementById){
        pw.style.left = parseInt(dsocleft) + x_offset + "px";
        pw.style.top = dsoctop + y_offset + "px";
    }
}

function show_please_wait() {
    position_please_wait();
    pwInterval = setInterval("position_please_wait()", 100);
    document.getElementById('please_wait').style.visibility='visible';
}

function hide_please_wait() {
    position_please_wait();
    clearInterval(pwInterval);
    document.getElementById('please_wait').style.visibility='hidden';
}


/*
 * UTF8 utility functions.
 * support legacy browser javascript.
 */

function utf8(wide) {
  var c, s;
  var enc = "";
  var i = 0;
  while(i<wide.length) {
    c= wide.charCodeAt(i++);
    // handle UTF-16 surrogates
    if (c>=0xDC00 && c<0xE000) continue;
    if (c>=0xD800 && c<0xDC00) {
      if (i>=wide.length) continue;
      s= wide.charCodeAt(i++);
      if (s<0xDC00 || c>=0xDE00) continue;
      c= ((c-0xD800)<<10)+(s-0xDC00)+0x10000;
    }
    // output value
    if (c<0x80) enc += String.fromCharCode(c);
    else if (c<0x800) enc += String.fromCharCode(0xC0+(c>>6),0x80+(c&0x3F));
    else if (c<0x10000) enc += String.fromCharCode(0xE0+(c>>12),0x80+(c>>6&0x3F),0x80+(c&0x3F));
    else enc += String.fromCharCode(0xF0+(c>>18),0x80+(c>>12&0x3F),0x80+(c>>6&0x3F),0x80+(c&0x3F));
  }
  return enc;
}

var hexchars = "0123456789ABCDEF";

function toHex(n) {
  return hexchars.charAt(n>>4)+hexchars.charAt(n & 0xF);
}

var okURIchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";

function encodeURIComponentNew(s) {
  var s = utf8(s);
  var c;
  var enc = "";
  for (var i= 0; i<s.length; i++) {
    if (okURIchars.indexOf(s.charAt(i))==-1)
      enc += "%"+toHex(s.charCodeAt(i));
    else
      enc += s.charAt(i);
  }
  return enc;
}

function encodeURIParam(fld)
{
    if (fld == "") return "";
    var encodedField = "";
    var s = fld;
    if (typeof encodeURIComponent == "function")
    {
        // Use JavaScript built-in function
        // IE 5.5+ and Netscape 6+ and Mozilla
        encodedField = encodeURIComponent(s);
    }
    else
    {
        // Need to mimic the JavaScript version
        // Netscape 4 and IE 4 and IE 5.0
        encodedField = encodeURIComponentNew(s);
    }
    return encodedField;
}
