/**
 * Check if a dom element exists
 * @extend jQuery
 */
if (typeof jQuery !== "undefined") {
    jQuery.fn.exists = function() {
        return jQuery(this).length > 0;
    }
}

/**
 * Return a random number within a given range
 *
 * @param string min Start number.
 * @param string max End number.
 * @return int Random integral.
 */
function randRange(min, max) {
    var randomNum = Math.round(Math.random()*(max-min))+min;
    return randomNum;
}

/**
 * Return/Log function name
 *
 * @return string Function name.
 */
function getFunctionName(str) {
    if (typeof str != "string") {
        str.callee.toString();
    }
    str = str.match(/function\s*([\w\$]*)\s*\(/);
    str = "Fn " + str[1]+ "()";
    return str;
}  

/**
 * Return/Log function name
 *
 * @return string Function name.
 */
function getFunctionName(str) {
    if (typeof str != "string") {
        str.callee.toString();
    }
    str = str.match(/function\s*([\w\$]*)\s*\(/);
    str = "Fn " + str[1]+ "()";
    //return str;
    debug(str);
}

/**
 * Trim a string
 * Based on trim12
 *
 * @param string str The string to trim.
 * @return string Function name.
 */
function trim(str) {
  var str = str.replace(/^\s\s*/, ''),
  ws = /\s/,
  i = str.length;
  while (ws.test(str.charAt(i = i-1)));
  return str.slice(0, i + 1);
}

/**
 * Compare two array
 *
 * @param array x First array
 * @param array y Second array
 * @return boolean Compare result
 */
function compareArray(x, y) {
    if (x === y) { //For reference types: returns true if x and y points to same object
        return true;
    }
    if (x.length != y.length) {
        return false;
    }
    for (key in x) {
        if (x[key] !== y[key]) { //!== So that the the values are not converted while comparison
            return false;
        }
    }
    return true;
}

/**
 * Find Array index by value
 *
 * @param * value The value to search.
 * @return int Array index.
 */
Array.prototype.findIndex = function(value) {
    for (var i=0; i < this.length; i++) {
        // use === to check for Matches. ie., identical (===), ;
        if (this[i] == value) {
            return i;
        }
    }
    return "";
}

/**
 * Debug a message to javascript console
 *
 * @param string message The message
 * @param string mode Logging mode
 */
function debug(message, mode) {
    if (typeof mode === "undefined") mode = "log";
    if (!window.log) return false;
    switch (mode) {
        case "log":
            console.log(message);
        break;
        case "info":
            console.info(message);
        break;
        case "error":
            console.error(message);
        break;
    }
};
