/*******************************************************************************
 * 
 * Author: Justin Samuel <justin /at/ justinsamuel /dot/ com>
 * Date: 2008-04-25
 * License: GPL
 * 
 * General utilities for descrack.
 * 
 ******************************************************************************/

/*
 * Create and return a new XMLHttpRequest instance.
 */
function createXHR(stateChangeFunction) {
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
        xhr = new XMLHttpRequest();
        if (xhr.overrideMimeType) {
            xhr.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
           try {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
           } catch (e) {}
        }
    }
    if (!xhr) {
        throw new Error("Can't create XMLHttpRequest instance.");
    }
    xhr.onreadystatechange = stateChangeFunction;
    return xhr;
}

/*
 * Strip non-directory suffix from file name.
 */
function dirname(path) {
    return path.match( /.*\// );
}

/*
 * Do whatever needs to be done with otherwise unhandled exceptions.
 */
function handleException(e) {
    logError(dump(e, '<br />'));
}

/*
 * Returns a string of the names and values of all of the object's properties.
 */
function dump(obj, lineSeparator) {
    text = '';
    for (var i in obj) {
       text += i + ' = ' + obj[i] + lineSeparator;
    }
    return text;
}

/*
 * Compares two arrays of equal length. Returns true if contents of elements
 * at each corresponding index are equal, false otherwise.
 */
function arraysAreEqual(a1, a2) {
    var i;
    for (i = 0; i < a1.length; i++) {
        if (a1[i] != a2[i]) {
            return false;
        }
    }
    return true;
}

/*
 * Print an array of 8 numbers that have values between 0-255 as a string in the
 * format '0xXXXXXXXXXXXXXXXX'.
 */
function decByteToHexString(arr) {
	var hexstring = '0x';
    for (i = 0; i < arr.length; i++) {
        var tempstring = arr[i].toString(16);
        var padcount = 2 - tempstring.length;
        var padstring = '';
        while (padcount > 0) {
            padstring += '0';
            padcount--;
        }
        hexstring += padstring + tempstring;
    }
    return hexstring;
}
