// Fixed Windows 98 IE 5.0 problem method Array.prototype.push not implemented
if(!Array.prototype.push) Array.prototype.push=function(sItem){this[this.length]=sItem;};
// Struct of rc4 key
function rc4Key()
{
	this.state=new Array(256);
	this.x;
	this.y;
}
// Swap byte key state function
function swap_Byte(state,i,index)
{
	var swapByte=state[i];
	state[i]=state[index];
	state[index]=swapByte;
}
// Made array functions
function madeArrayEncrypt(sText)
{
	var sValues=new Array();
	for(var i=0;i<sText.length;i++)
	{
		sValues.push(sText.charCodeAt(i)&0x00FF);								//Low part
		sValues.push((sText.charCodeAt(i)&0xFF00)/0x100);				//High part
	}
	return sValues;
}
/*function madeArrayDecrypt(sCypher)
{
	var aValues=new Array();
	for(var i=0;i<sCypher.length;i+=2)
		aValues.push(h2d(sCypher.charAt(i)+sCypher.charAt(i+1)));
	return aValues;
}*/
// Prepare keys and decrypt/encrypt rc4 array
function prepare_Key(keyData,key)
{
	for(var i=0;i<256;i++)
		key.state[i]=i;
	key.x=0;
	key.y=0;
	var index1=0,index2=0,aKeyValue=new Array();
	for(i=0;i<keyData.length;i++)
	{
		aKeyValue.push(keyData.charCodeAt(i)&0x00FF);						//Low part
		aKeyValue.push((keyData.charCodeAt(i)&0xFF00)/0x100);		//High part
	}
	for(i=0;i<256;i++)
	{
		index2=(aKeyValue[index1]+key.state[i]+index2)%256;
		swap_Byte(key.state,i,index2);
		index1=(index1+1)%aKeyValue.length;
	}
}
function rc4(aValues,key)
{
	var xorIndex,aCypher=new Array();
	for(i=0;i<aValues.length;i++)
	{
		key.x=(key.x+1)%256;
		key.y=(key.state[key.x]+key.y)%256;
		swap_Byte(key.state,key.x,key.y);
		xorIndex=key.state[key.x]+((key.state[key.y])%256);
		while(xorIndex>255)
			xorIndex-=256;
		aCypher.push(aValues[i]^key.state[xorIndex]);
	}
	return aCypher;
}
// Encrypt/Decrypt final methods
function encode(sPlain,sKey)
{
	sKey = String(sKey);
	var k=new rc4Key();
	prepare_Key(sKey,k);
	var aResult=rc4(madeArrayEncrypt(sPlain),k);
	var aCypher=new Array();
	for(var i=0;i<aResult.length;i++)
		aCypher.push(hexLength(d2h(aResult[i]),2));
	return '23'+aCypher.join('');	// Add 23 in the two first bytes of cyphertext for specifying RC4 algorithm
}
/*function decode(sCypher,sKey)
{
	sKey = String(sKey);
	var k=new rc4Key();
	prepare_Key(sKey,k);
	var aResult=rc4(madeArrayDecrypt(sCypher.substring(2)),k);
	var aDecrypt=new Array();
	for(var i=0;i<aResult.length;i+=2)
		aDecrypt.push(String.fromCharCode((aResult[i+1]*0x100)+aResult[i]));	// High byte and low byte
	return aDecrypt.join('');
}*/
// Hexadecimal converters
var _hD='0123456789ABCDEF';
function d2h(d)
{
	var h=_hD.substr(d&15,1);
	while(d>15)
	{
		d>>=4;
		h=_hD.substr(d&15,1)+h;
	}
	return h;
}
function h2d(h)
{
	return parseInt(h,16);
}
function hexLength(sNum,nLength)
{
	while(sNum.length<nLength)
		sNum='0'+sNum;
	return sNum;
}