// the loading image in DOM
var loadingImg = $('<img src="/images/loading.gif" alt="Loading..." title="Loading..." width="16" height="16" />');

function SubmitForm(field) {
    field.form.submit();
}

function CheckAllCheckBoxes(form, name, checked) {
    if (arguments.length == 2) { checked = ''; }
    count = 0;

    $('#' + form + ' input:checkbox').each(function(index, input) {
        if ($(this).attr('name') == name) {
            if (checked === true || checked === false) {
                this.checked = checked;
            } else {
                this.checked = !this.checked;
            }
            if (this.checked) count++;
        }
    });

    if (checked) {
        return count-1;
    } else {
        return 0;
    }
}

function CountCheckBoxes(form, name) {
    count = 0;
    $('#' + form + ' input:checkbox').each(function(index, input) {
        if ($(this).attr('name') == name && this.checked == true) {
            count++;
        }
    });

    return count;
}

function OpenDialog(dialogDiv, width, height, populatePath, close) {
    if (OpenDialog.arguments.length == 4) close = false;
    dialog = $(dialogDiv).dialog({
        modal: true,
        autoOpen: false,
        width: width,
        height: height,
        minWidth: width,
        minHeight: height,
        overlay: true,
        position: ["center", 200],
        close: close,
        overlay: {
            opacity: 0.5,
            background: "black"
        }
    });

    dialog.html(loadingImg).append(' Loading...').dialog('open');

    if (populatePath) {
        $.get(populatePath, function(data) {
            if (data != '') dialog.html(data);
            else dialog.close();
        });
    }

    return dialog;
}

/*******
* Other useful functions
********/
function AddTableRow(tableID) {
    var returnData = new Array;
    returnData['cells'] = new Array;
    // pass every cell content as a futher arg
    var table = document.all ? document.all[tableID] : document.getElementById(tableID);

    if (arguments.length > 1) {
        var row = table.insertRow(table.rows.length);
        returnData['row'] = row;
        if (document.all) {
            for (var i = 1; i < arguments.length; i++) {
                var cell = row.insertCell(i - 1);
                if (typeof(arguments[i]) == 'object') {
                    cell.appendChild(arguments[i]);
                } else {
                    cell.innerHTML = arguments[i];
                }
                returnData['cells'][i - 1] = cell;
            }

        } else if (document.getElementById) {
            for (var i = arguments.length - 1; i >= 1; i--) {
                var cell = row.insertCell(arguments.length - 1 - i);
                if (typeof(arguments[arguments.length - i]) == 'object') {
                    cell.appendChild(arguments[arguments.length - i]);
                } else {
                    cell.innerHTML = arguments[arguments.length - i];
                }

                returnData['cells'][arguments.length - 1 - i] = cell;
            }
        }
    }

    return returnData;
}

// function returns a select element with the values sent to it
function CreateSelectElement(values, name, onChange, multiple, selected, id) {
    select = document.createElement('SELECT');
    select.setAttribute('name', name);
    if (CreateSelectElement.arguments.length == 6) {
        select.setAttribute('id', id);
    } else {
        select.setAttribute('id', name);
    }

    if (onChange != null) {
        eval('select.onchange = function() { ' + onChange + ' };');
    }

    if (CreateSelectElement.arguments.length >= 4 && multiple > 0) {
        select.setAttribute('multiple', 'multiple');
        select.setAttribute('size', multiple);
    } else {
        select.setAttribute('size', '1');
    }

    if (CreateSelectElement.arguments.length < 5) {
        selected = false;
    }

    for (y in values) {
        if (typeof(values[y]) == 'string') {
            var optionObject = new Option(values[y], y);
            var optionRank = select.options.length;
            select.options[optionRank] = optionObject;
            if (selected == y) select.selectedIndex = optionRank;
        }
    }

    return select;
}

function AuditCodeView(auditCodeId) {
    OpenWindow('/private/audit/code.php?audit_code_id=' + auditCodeId, 'auditCodeView', 'width=330,height=300,scrollbars=yes');
}

/** timeout **/
function OpenTimeoutDialog() {
    formHtml = '<p><strong>Your session is about to timeout.</strong> Please enter your password to continue using the Inflight Institute:</p>\
    <form method="post" action="/private/login.php" name="timeoutForm" onsubmit="return false;">\
        Password&nbsp;<input type="password" id="timeout_password" name="timeout_password"  size="30" maxlength="50" />\
        <p><input type="button" value="Submit" class="button" onclick="SubmitTimeoutDialog()" />&nbsp;&nbsp;<input type="button" name="c_user_action" value="Logout" class="button" onclick="location.href = \'/private/login.php?c_user_action=logout\';" /></p>\
        <input type="hidden" name="c_user_action" value="timeout_login" />\
    </form>';

    width = 400;
    height = 250;
    var timeoutDialog = $('#timeoutDialog').dialog({
        modal: true,
        autoOpen: true,
        stack: true,
        width: width,
        height: height,
        minWidth: width,
        minHeight: height,
        maxWidth: width,
        maxHeight: height,
        position: ["center", 200],
        closeOnEscape: false,
        overlay: {
            opacity: 0.5,
            background: "black"
        }
    }).html(formHtml).show();

    $('.ui-dialog-titlebar-close').hide();
    $('#timeout_password').focus();
}

function SubmitTimeoutDialog() {
    formValues = $('form[name="timeoutForm"]').serialize();
    $('#timeoutDialog').html(loadingImg).append(' Verifying Password...');
    $.post('/private/login.php', formValues, function(data) {
        if (data == 0) {
            $('#timeoutDialog').html('Password verification failed. Logging out.');
            location.href = '/private/login.php?c_user_action=logout';
        } else {
            $('#timeoutDialog').html('Password verification successful.').dialog('close').html('');
            StartLogoutTimers();
        }
    });
}

function StartLogoutTimers() {
    var timeoutDivTimer = setTimeout('OpenTimeoutDialog();', loginTimeout - 600000);
    var logoutTimer = setTimeout('location.href = "/private/login.php?c_user_action=logout"', loginTimeout);
}