// COPYRIGHT DENNY WONG PUI CHUNG 2009

// replaceAllByArray Function
// Usage:
// string.replaceAllByArray (regex regexpression, array/object replace_with[, function replace_with.function)]
//
// This is to tackle the problem of string.replace treat "$1" in replace_by as a string, and it does not get resolved until the whole string was resolved.
// This results in string.replace(/.+/, MyArray["$1"]) will result in "undefined", as the function tries to resolve MyArray["$1"] instead of the value of /.+/.
// 
// In string.replaceAllByArray, it accepts 2 forms of parameter in replaceArray:
//
// 1. replaceArray is ARRAY
// if replaceArray_function is undefined or non-String, replaceArray will be treated as Array. It searches for all occurence of the regexpression, and replace all with the value of MyArray[$1]. All secondary brackets are ignored.
//
// 2. replaceArray is FUNCTION
// Instead of an array, you can also replace all occurences with function($1), passing $1 as parameter. If function is localized in an object with reference to the "this" object, an additional parameter of the supposed context need to be passed as OBJECT to replaceArray_context. This is because functions are passed with value in parameters, that when ran in a different context the "this" object would not return the same object as expected.

String.prototype.replaceAllByArray = function (regexpression, replaceArray, replaceArray_context)
									{
										get_array_value = function (replaceArray, replaceArray_context, parameter)
															{
																if (typeof replaceArray == "function")
																{
																	return (typeof replaceArray_context == "undefined") ? replaceArray(parameter) : replaceArray.call(replaceArray_context, parameter);
																} else {
																	return replaceArray[parameter];
																}
															}
										var return_value = "";
										var temp_str = this;
										var matches = {};
										var array_value = null;
										
										while (temp_str.length != 0 && temp_str.search(regexpression) != -1)
										{
											matches = temp_str.match(regexpression);
											
											return_value += temp_str.substring(0,temp_str.indexOf(matches[0]));
											temp_str = temp_str.substring(temp_str.indexOf(matches[0])+matches[0].length, temp_str.length);
											
											array_value = get_array_value(replaceArray, replaceArray_context, matches[1]);
											
											return_value += ((typeof array_value != "undefined") && (array_value !== null)) ? array_value : matches[0];
										}
										return_value += temp_str;
										
										return return_value;
									}
