/* ===-----------=== Komanche 2.0 ===-----------===

           Copyright:     © 2004, CBA Consult ltda.
            Coded by:  Luiz Antonio B. Silva [Labs]
                      Todos os direitos reservados.

                http:         www.cbaconsult.com.br
                mail:   comercial@cbaconsult.com.br

   Biblioteca de (des)serialização de objetos no
   estilo "serialize()" do PHP.

-------------=== Vs. 1.0 - Fev/2004 | By Labs --=== */



// -----------------=== reportException()
/* Exibe mensagens de erro.
                                                     by Labs - 04/ 2004 */
function reportException(exception, msg){
    msg = (msg ? msg + "\n\n" : "");
    alert(msg + "Error: " + exception.name + "\n" + exception.message);
}


// -----------------=== serialize()
/* Serializa objetos.
                                                     by Labs - 04/2004 */
function serialize (v) {
    if (!isNaN (v) && v.__proto__ == Number.prototype) {
        v = Number (v);
    }
    
    var _encode = (_BROWSER_ == 'IE5' ? "escape" : "escape");
    
    switch (typeof(v)){
        //case Date :
       // case 'string'  : var enc_v = encode(v, 'base64');
       //                  return "s:" + enc_v.length + ":\"" + enc_v + "\";";
        case 'string'  : return "s:" + v.length + ":\"" + encode(v, _encode) + "\";";
        case 'boolean' : return "b:" + (v == true ? "1" : "0") + ";";
        case 'number'  : return (v % 1 == 0 ? "i:" : "d:") + v + ";";
        /*case Array   : var itens = "";
                       for (var item in v){
                            itens += serialize(item);
                            itens += serialize(v[item]);
                       }
                       return "a:" + v.length + ":{" + itens + "}";*/
        case 'object'  : var itens = ""; var c = 0;
                       for (var item in v){
                            itens += serialize(item);
                            itens += serialize(v[item]);
                            c++;
                       }
                       return "a:" + c + ":{" + itens + "}";
                       //return "O:8:\"stdClass\":" + c + ":{" + itens + "}";

        default: return;
    }
}


// -----------------=== showObject()
/* Recebe um string que pode ser transformado em objeto
   via eval, e o retorna.
                                                     by Labs - 04/2004 */

function showObject(obj, space) {
/*alert('oi'+result);
alert(showObject(result));
alert('ola'+result.erros);*/

for (var k in obj){
    alert(""+k+": " + unescape(obj[k]));

    if (obj[k].constructor == Object){
        for (var y in obj[k]){
            alert("  - "+y+": " + obj[k][y]);
        }
    }
}

  /*  var result;
    alert(result);
    for (var key in obj){
         result += space + " key: " + key + " - Value: " + obj[key];

         if (obj[key].constructor == Object){
             result += showObject(obj, space + "  ");
         }
    }
    alert(result);
    return result;*/
}


// -----------------=== toObject()
/* Recebe um string que pode ser transformado em objeto
   via eval, e o retorna.
                                                     by Labs - 04/2004 */
function toObject(str) {
    try {
        eval("var obj = " + str + ";");
        decodeObject(obj, 'escape');
        //showObject(obj);
        return obj;

    }catch(e){
        //reportException(e, 'Falha no recebimento do objeto.');
        return false;
    }
}


// -----------------=== unserialize()
/* Deserializa objetos.
                                                     by Labs - 04/2004 */
function unserialize(str) {
    var type, len, a, b, key, val;
    type = str.charAt(0);
    switch (type) {

        // String: s:7:"package";s:3696:"
        case 's' : _str = str.substr(2, 10);
                   len = _str.substr(0, _str.indexOf(':'));
                   a   = (str.substr((len.length)+4, len)).toString();
                   break;

        // Integer: i:2;
        case 'i' : len = str.substr(2, str.indexOf(';')-1);
                   a   = parseInt(len);
                   break;

        // Float: d:2;
        case 'd' : len = str.substr(2, str.indexOf(';')-1);
                   a   = parseInt(len);
                   break;

        // Boolean:
        case 'b' : len = str.substr(2, str.indexOf(';')-1); 
                   a   = ((len == "true") || (len == "1") || (len == 1) ? true : false);
                   break;

        // Array: a:3:{s:2:"um";s:3:"uns";i:0;a:2:{i:0;s:4:"tres";i:1;i:2;}i:1;s:4:"dois";}
        //     => array("um" => "uns", array("tres", 2), "dois");
        case 'a' : a = {};  //  <<== Retorna um objeto, na verdade.
                   var l = str.substr(2, 1);
                   str = str.substr(5, str.length);
                   for (var x=0;x<l;x++){
                       res = unserialize(str);
                       key = res[0];
                       val = unserialize(res[1]);
                       a[key] = val[0];
                       str = val[1];
                   }
                   str = str.substr(1, str.length);
                   break;

    }

    if (type != "a"){
        if (type != "s" && len) len = (len.length);
        str = str.substr(str.indexOf(";", len)+1);
    }

    return [a, str];
}



// ----------------=== Funçoes de encoding ===---------------- //
// As funções abaixo são utilizadas para formatação dos dados
// enviados e recebidos.


// -----------------=== encode()
/* Faz o encode de uma string.
                                                     by Labs - 02/2004 */
function encode(str, tipo){
    switch (tipo){
        case 'html'   : return encodeHTML(str);   break;
        case 'escape' : return escape(str);       break;
        case 'base64' : return base64Encode(str); break;
    }
}


// -----------------=== decode()
/* Faz o encode de uma string.
                                                     by Labs - 02/2004 */
function decode(str, tipo){
    switch (tipo){
        case 'html'   : return decodeHTML(str);   break;
        case 'escape' : return unescape(str);     break;
        case 'base64' : return base64Decode(str); break;
    }
}


// -----------------=== encodeObject()
/* Faz o encode recursivo de um objeto.
                                                     by Labs - 02/2004 */
function encodeObject(obj, tipo){
    for (var param in obj){
         var t = typeof(obj[param]);
         if (t == 'string'){
             obj[param] = encode(obj[param], tipo);

         } else if (t == 'object'){
             obj[param] = encodeObject(obj[param], tipo);
         }
    }
    return obj;
}


// -----------------=== decodeObject()
/* Faz o decode recursivo de um objeto.
                                                     by Labs - 02/2004 */
function decodeObject(obj, tipo){
    for (var param in obj){
         var t = typeof(obj[param]);
         if (t == 'string'){
             obj[param] = decode(obj[param], tipo);

         } else if (t == 'object'){
             obj[param] = decodeObject(obj[param], tipo);
         }
    }
    return obj;
}

