dojo.provide("parus.xml");

if (!parus) parus = {};

if (!parus.xml) dojo.mixin(parus, {
  xml: {}
});

dojo.mixin(parus.xml, {

  _escape: function(s) {
    s = s.split("&").join("&amp;");
    s = s.split(">").join("&gt;");
    s = s.split("<").join("&lt;");
    s = s.split(String.fromCharCode(34)).join("&quot;");
    return s;
  },

  toXml: function(it) {

    if (it === undefined) {
      return "undefined";
    }
    var objtype = typeof it;
    if (objtype == "number") {
      return (isNaN(it) ? "" : it) + "";
    };
    if (objtype == "boolean") {
      return it + "";
    }
    if (it === null) {
      return "";
    }
    if (dojo.isString(it)) {
      return parus.xml._escape(it);
    };

    var recurse = arguments.callee;

    if (dojo.isArray(it)) {
      var res = dojo.map(it, function(obj) {
        var val = recurse(obj);
        if (typeof val != "string") {
          val = "undefined";
        }
        return val;
      });
      return res.join("");
    }


    var output = [];
    var key;

    for (key in it) {
      var keyStr, val;
      if (typeof key == "number") {
        keyStr = isNaN(key) ? "" : key;
      } else if (typeof key == "string") {
        keyStr = parus.xml._escape(key);
      } else {
        continue;
      }
      var item = it[key];
      val = recurse(item);
      if (typeof val != "string") {
        continue;
      }


      var attrs = [];

      if (dojo.isArray(item)) for (var arrKey in item) if (item.hasOwnProperty(arrKey) && !arrKey.match(/^\d+$/)) attrs.push(arrKey + "=" + String.fromCharCode(34) + parus.xml._escape(recurse(item[arrKey])) + String.fromCharCode(34));

      output.push("<" + keyStr + (attrs.length ? " " + attrs.join(" ") : "") + ">" + val + "</" + keyStr + ">");
    }

    return output.join("");

  },

  fromXml: function(xml, it) {

    if (!it) it = {};

    if (xml.attributes) for (var i = 0; i < xml.attributes.length; i++) it[xml.attributes[i].nodeName] = xml.attributes[i].nodeValue;

    for (var i = 0; i < xml.childNodes.length; i++) {
      if (xml.childNodes[i]) {
        if (xml.childNodes[i].nodeType != 3) {
          var childInfo = arguments.callee(xml.childNodes[i], {});
          if (it[xml.childNodes[i].nodeName]) it[xml.childNodes[i].nodeName].push(childInfo);
          else it[xml.childNodes[i].nodeName] = [childInfo];
        }
        else {
          var s = (!dojo.isIE || dojo.isIE >= 10) ? xml.childNodes[i].textContent : xml.childNodes[i].text
          if (s && dojo.string.trim(s)) it["#text"] = s;
        }
      }
    }

    return it;

  }

});