/*
 * All functions in the file are JavaScript functions written to emulate standard php functions
 */

function urlencode(str)
{
	var histogram = {}, tmp_arr = [];
	var ret = str.toString();

	var replacer = function(search, replace, str)
	{
		var tmp_arr = [];
		tmp_arr = str.split(search);
		return tmp_arr.join(replace);
	};
	
	// The histogram is identical to the one in urldecode.
	histogram["'"]   = '%27';
	histogram['(']   = '%28';
	histogram[')']   = '%29';
	histogram['*']   = '%2A';
	histogram['~']   = '%7E';
	histogram['!']   = '%21';
	histogram['%20'] = '+';
	
	// Begin with encodeURIComponent, which most resembles PHP's encoding functions
	ret = encodeURIComponent(ret);
	
	for(search in histogram)
	{
		replace = histogram[search];
		ret = replacer(search, replace, ret); // Custom replace. No regexing
	}

	// Uppercase for full PHP compatibility
	return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2)
	{
		return "%"+m2.toUpperCase();
	});
	
	return ret;
}

function urldecode(str)
{
	var histogram = {};
	var ret = str.toString();
	
	var replacer = function(search, replace, str)
	{
		var tmp_arr = [];
		tmp_arr = str.split(search);
		return tmp_arr.join(replace);
	};
	
	// The histogram is identical to the one in urlencode.
	histogram["'"]   = '%27';
	histogram['(']   = '%28';
	histogram[')']   = '%29';
	histogram['*']   = '%2A';
	histogram['~']   = '%7E';
	histogram['!']   = '%21';
	histogram['%20'] = '+';
 
	for(replace in histogram)
	{
		search = histogram[replace]; // Switch order when decoding
		ret = replacer(search, replace, ret); // Custom replace. No regexing
	}
	
	// End with decodeURIComponent, which most resembles PHP's encoding functions
	ret = decodeURIComponent(ret);
 
	return ret;
}

function sleep(seconds)
{
    var start = new Date().getTime();
    while(new Date() < start + seconds * 1000);
    return 0;
}
