/* 
 	. Created by Lis/2k1. rev# 24.8.2 : 11:49:25
	------------------------------------
	. (c) Reservation Art, 2002
*/

// CVSinfo
// $Id: cSerialize.js,v 1.2 2002/11/26 01:31:26 lis Exp $
// $Revision: 1.2 $
// $Name:  $

function cSerialize() {
	this.Serialize = function( iPValue ) {
		var result = "";
		switch( typeof( iPValue ) ) {
			case "number" : 
				result = "n:" + iPValue + ";";
				break;
			case "string" :
				result = "s:"
					+ iPValue.replace( /;/, "\\;" ) 
					+ ";"; 
				break;
			case "object" :
				if (iPValue instanceof Array ) {
					var avs = new Array();
					for( v in iPValue ) {
						avs.push( this.Serialize( v ) + this.Serialize( iPValue[v] ) );
					}
					result = "a:"
						+ "{" + avs.join("") + "}";
					break;
				} else if (iPValue == null ) {
					result = "l:;"
					break;
				}
			default :
				alert("Unsupported type for seralization!");
		}
		return( result );
	}
	this.Unserialize = function( iSValue ) {
		var i;
		var rnd = "-\b\c%ds" + Math.random() + "\b\c%ds-";
		iSValue = iSValue.replace( /\\;/, rnd );
			
		var re = /^([asn]):\{?(.*)[;\}]$/
		if (!re.exec(iSValue)) {
			alert( "Incorrectly serialized object!" );
			return(null);
		}
		var type = RegExp.$1;
		var value = RegExp.$2;
		switch( type ) {
			case "n" :
				return( parseInt( value ) );
				break;
			case "s" :
				return( "" + value.replace( new RegExp( rnd ), ";" ) );
				break; 
			case "a" :
				var result = new Array();
				var r = value.match( /([ns]:.*?;|a:\{.+?\})/g );
				if ( r == null ) 
					return( result );
				
				var a = new Array();
				for(i=0; typeof( r[i] ) != "undefined"; i++ ) a[i] = r[i];

				if ( (a.length/2) != Math.round(a.length/2) )
					alert("error in array format!");

				for (var i=0; i< a.length; i+=2 ) {
					var index = this.Unserialize( a[i].replace( new RegExp(rnd), "\\;") );
					var value = this.Unserialize( a[i+1].replace( new RegExp(rnd), "\\;") );
					result[index] = value; 
				}
				
				return( result );
				break;
			case "l" :
				return( null );
			default :
				alert("Unknown serialized type!");
		}
	}
	return( this );
}
