﻿
/* ---------------- URL Encode ---------------- */

function URLEncode(unencodedValue)
{
	/* Copyright (c) 2006 Mathias Bank (http://www.mathias-bank.de)
     * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
     * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
     * 
     * Thanks to Hinnerk Ruemenapf - http://hinnerk.ruemenapf.de/ for bug reporting and fixing.
     */

	// The Javascript escape and unescape functions do not correspond with what browsers actually do...
	var SAFECHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.!~*'()";
	var HEX = "0123456789ABCDEF";

	var plaintext = unencodedValue;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";	// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
                //cannot be encoded using standard URL encoding. (URL encoding only supports 8-bit characters.) A space (+) will be substituted.
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};

