/**
 * PHP Functions
 * 
 * This file contains Javascript equivalents of PHP functions
 */

/**
 * Repeat a string
 * @link http://php.net/manual/en/function.str-repeat.php
 * @param input string <p>
 * The string to be repeated.
 * </p>
 * @param multiplier int <p>
 * Number of time the input string should be
 * repeated.
 * </p>
 * <p>
 * multiplier has to be greater than or equal to 0.
 * If the multiplier is set to 0, the function
 * will return an empty string.
 * </p>
 * @return string the repeated string.
 */
function str_repeat(string, number) {
    result = "";
    for(var i=0; i<number; i++) {
        result += string;
    }
    return result;
}

/**
 * Count the number of substring occurrences
 * @link http://php.net/manual/en/function.substr-count.php
 * @param haystack string <p>
 * The string to search in
 * </p>
 * @param needle string <p>
 * The substring to search for (Note: only supports characters yet!)
 * </p>
 * @param offset int[optional] <p>
 * The offset where to start counting
 * </p>
 * @param length int[optional] <p>
 * The maximum length after the specified offset to search for the
 * substring. It outputs a warning if the offset plus the length is
 * greater than the haystack length.
 * </p>
 * @return int This functions returns an integer.
 */
function substr_count(haystack, needle, offset, length) {
    // Parse the input
    if (offset != undefined && length != undefined) {
        if (offset+length > haystack.length) {
            alert("Incorrect input");
        }
        haystack = haystack.substr(offset, length);
    } else if (offset != undefined) {
        haystack = haystack.substr(offset);
    } else if (length != undefined) {
        haystack = haystack.substr(0, length);
    }

    running = true;
    count = 0;
    while(running) {
        tmp = haystack.indexOf(needle);
        if (tmp == -1) {
            running = false;
        } else {
            haystack = haystack.substr(tmp+needle.length);
            count++;
        }
    }
    return count;
}
