var g_popup_handles = new Array();
var g_do_upload = false;

function openPopup(popupName, popupURL, popupOptions, no_auto_close) {

    var width, height, left, top;
    var skip_centering = 0;
    if (popupOptions) {
        var pairs = new Array();
        var nv = new Array();
        var i, name;
        pairs = popupOptions.split(',');
        for (i=0; i<pairs.length; i++) {
            nv = pairs[i].split('=');
            name = nv[0].toLowerCase();
            if (name == 'width') { width = nv[1]; }
            else if (name == 'height') { height = nv[1]; }
            else if (name == 'left') { left = nv[1]; }
            else if (name == 'top') { top = nv[1]; }
        }
    }

    var coords = auto_position_coords(width, height, left, top);

    if (width == undefined) { popupOptions += ',width=' + coords.width; }
    if (height == undefined) { popupOptions += ',height=' + coords.height; }
    if (left == undefined) { popupOptions += ',left=' + coords.left; }
    if (top == undefined) { popupOptions += ',top=' + coords.top; }

    var wHandle = window.open(popupURL, popupName, popupOptions);
    wHandle.focus();

    if (! no_auto_close) {
        g_popup_handles[g_popup_handles.length] = wHandle;
        close_popups_handler();
    }

    return wHandle;

}

function auto_position_coords (width, height, left, top) {
    var w, h, x, y;
    if (typeof(window.innerWidth) == 'number') { // non IE
        // .top needed for frames
        w = window.top.innerWidth;
        h = window.top.innerHeight;
        x = window.screenX;
        y = window.screenY + (window.top.outerHeight - window.top.innerHeight) - 50;
    }
    else { // IE
        //IE 6+ in 'standards compliant mode'
        if (document.documentElement) {
            w = document.documentElement.clientWidth;
            h = document.documentElement.clientHeight;
        }
        //IE 4 compatible
        else if (document.body) {
            w = document.body.clientWidth;
            h = document.body.clientHeight;
        }
        x = window.screenLeft;
        y = window.screenTop;
    }
    var coords = new Object();
    if (width == undefined) { coords.width = Math.round(w * 0.8); }
    else                    { coords.width = width; }
    if (height == undefined) { coords.height = Math.round(h * 0.8); }
    else                     { coords.height = height; }
    if (left == undefined) {
        width = width || coords.width;
        coords.left = Math.round((w/2)-(width/2)) + x;
    }
    if (top == undefined) {
        height = height || coords.height;
        coords.top = Math.round((h/2)-(height/2)) + y;
    }
    return coords;
}

function confirmMsg(msg) {
    var ret = false;
    if (window.confirm(msg)) { ret = true; }
    return ret;
}

// Limit the number of chars entered into textarea
function limitChars(e, textarea, max_chars) {
    var key;
    if (navigator.appName.indexOf("Microsoft") != -1) {
        key = event.keyCode;
    }
    else {
        key = e.which;
    }
    // Accept backspace as a valid key press
    if ((textarea.value.length >= max_chars) && (key != 8) && (key != '')) {
        return false;
    }
    else {
        return true;
    }
}

function countChars(textarea, char_counter) {
    char_counter.value = textarea.value.length;
}

function bc_submit (form) {
    var bc = document.getElementById('BC');
    if (! (bc)) {
        bc = document.createElement('input');
        bc.type = 'submit';
        bc.id   = 'BC';
        bc.name = 'BC';
        bc.style.display = 'none';
        document.form1.appendChild(bc);
    }
    bc.value = form;
    bc.click();
}

function set_cookie (name, value, expires, path, domain, secure) {
    var expires_date;
    if (expires) {
        // Days
        expires = expires * 1000 * 60 * 60 * 24;
        var today = new Date();
        today.setTime( today.getTime() );
        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" : "");
}

function read_cookie (name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
    }
    return null;
}

function getAjaxReqObj () {
    var http_request = false;
    if (window.XMLHttpRequest) {
        http_request = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }
    return http_request;
}

function setupAjaxReqObjForPost (http_request, params) {
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http_request.setRequestHeader("Content-length", params.length);
    if (! document.all) {  //for IE6
        http_request.setRequestHeader("Connection", "close");
    }
}

function ajax_cb_default () {
    if (http_request.readyState == 4) {
        delete http_request['onreadystatechange'];
        document.body.style.cursor='default';
        if (http_request.status != 200) {
            alert('There was a problem with the request, please try again.  (HTTP code:  ' +  http_request.status + ')');
        }
    }
}

function find_children_by_id (e, re) {
    return _find_children(e, re, 'id');
}

function find_children_by_name (e, re) {
    return _find_children(e, re, 'name');
}

function _find_children (e, re, id_name) {

    var children = new Array();

    var value = (id_name == 'id') ? e.id : e.name;

    if (re.test(value)) {
        children[children.length] = e;
    }
//    else {
        if (e.hasChildNodes()) {
            var found;
            var child_nodes = e.childNodes;
            for (var i=0; i<child_nodes.length; i++) {
                found = _find_children(child_nodes[i], re, id_name);
                if (found && found.length) {
                    for (var j=0; j<found.length; j++) {
                        children[children.length] = found[j];
                    }
                }
            }
    
        }
//    }

    return children;

}

function set_form_submit_link () {
    var field, value;

    for (var i=0; i < arguments.length; i+=2) {
        field = arguments[i];
        value = arguments[i+1];
        document.form1.elements[field].value = value;
    }

    document.form1.submit();

}

// close does not work in ie if content-type of popup = pdf
//function close_popups_handler () { addEvent(window, "unload", close_popups); }
function close_popups_handler () { if (g_popup_handles.length == 1) { addEvent(window, "unload", close_popups); } }
function close_popups () {
    for (var i=0; i<g_popup_handles.length; i++) {
        if (! g_popup_handles[i].closed) { g_popup_handles[i].close(); }
    }
}

function addEvent( obj, type, fn ) {
    if (obj.addEventListener) {
        obj.addEventListener( type, fn, false );
    }
    else if (obj.attachEvent) {
        obj["e"+type+fn] = fn;
        obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
        obj.attachEvent( "on"+type, obj[type+fn] );
    }
    else {
        obj["on"+type] = obj["e"+type+fn];
    }
}

function select_all_options (select_list) {
    for (var i=0; i<select_list.options.length; i++) {
        select_list.options[i].selected = true;
    }
}

function mv_select_option (from, to) {

    var curr_name, option, j, value, name;

    for (var i=from.options.length-1; i>=0; i--) {

        if (from.options[i].selected) {

            value = from.options[i].value;
            name  = from.options[i].text;
            curr_name = name.toLowerCase();
        
            from.options[i] = null;

            for (j=0; j<to.options.length; j++) {
                if (curr_name < to.options[j].text.toLowerCase()) { break; }
            }

            option = document.createElement('option');
            to.insertBefore(option, to.options[j]);

            // ie - set option value and text after element is added
            option.value = value;
            option.text  = name;

            // ie will not expand width of the select box for new options
            // created via the DOM's createElement function.  Create a temporary
            // blank option, then immediately remove it.  This forces the
            // select list to expand its width properly.
            if (document.all) {
                to.options[to.options.length] = new Option('', '');
                to.options[to.options.length-1].removeNode();
            }

        }

    }

}

function disable_file_inputs_unless_upload () {
    var inputs = document.form1.getElementsByTagName('input');
    for (var i=0; i<inputs.length; i++) {
        if ((inputs[i].type == 'file') && (! g_do_upload)) {
            inputs[i].disabled = true;
        }
    }
    if (g_do_upload) { g_do_upload = false; }
}

function enable_file_inputs () {
    var inputs = document.form1.getElementsByTagName('input');
    for (var i=0; i<inputs.length; i++) {
        if ((inputs[i].type == 'file') && inputs[i].disabled) {
            inputs[i].disabled = false;
        }
    }
}

function swapImage(imgName, newImage) {
    document.images[imgName].src = newImage.src;
}

function element_checked (element, value) {
    var checked = false;
    for (var i=0; i<element.length; i++) {
        if (element[i].checked && (element[i].value == value)) {
            checked = true;
            break;
        }
    }
    return checked;
}

function display_div (div_id, show, init) {
    if (show) {
        if (init) { document.getElementById(div_id).style.display = 'block'; }
        else { animatedcollapse.show(div_id); }
    }
    else {
        if (init) { document.getElementById(div_id).style.display = 'none'; }
        else { animatedcollapse.hide(div_id); }
    }
}

function get_xy (obj) {
    var xy = [0,0];
    while(obj) {
        xy[0] += obj.offsetLeft;
        xy[1] += obj.offsetTop;
        obj = obj.offsetParent || null;
    }
    return xy;
}
