/*
 * Xml Tools
 * Tools vari Xml, JSON
 * 
 * Reference: jQuery
 * 
 */
 
/*  06/2008
 *	Aggiunge ai nodi la proprietà xml (come in IE)
 *
 *	Dato un nodo xml posso usare la proprietà .xml indifferentemente in IE e Firefox
 *  il metodo __defineGetter__ utilizzato è supportato al momento da Firefox, Opera 9.5, Safari 3 e Konqueror
 */ 
if (!window.xmlExtension && window.Element && 
	window.Element.prototype && 
	window.Element.prototype.__defineGetter__ && 
	typeof window.Element.prototype.xml=="undefined"){ 
	Element.prototype.__defineGetter__("xml", function () { 
		return (new XMLSerializer()).serializeToString(this); 
        }); 
window.xmlExtension = true;
} 

mpXml = new Object();

mpXml.LoadXml = function(xmlString){
	var xmlDoc = null;
	
	if (window.ActiveXObject) 
	{
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false;
		xmlDoc.loadXML(xmlString);
	}
	else if (window.DOMParser)
	{
		parser=new DOMParser();
		xmlDoc=parser.parseFromString(xmlString,"text/xml");
	}
	 if (typeof xmlDoc.selectNodes == 'undefined') {
		xmlDoc.selectSingleNode = function(xPath){return mpXml.evaluateXPath(xPath, xmlDoc)[0]}
		xmlDoc.selectNodes = function(xPath){return mpXml.evaluateXPath(xPath, xmlDoc)}
	}
	return xmlDoc;

}

mpXml.LoadXmlByUrl = function(_url){

   $.ajaxSetup({
	cache: false,
   async: false
   });

   var Request = $.get(_url);
   try{
   		var nt = Request.responseXML.nodeType!=undefined;
   		return Request.responseXML;
   }
   catch(e){
   		//alert(e)
   		//arriva qui se non riesce ad accedere al nodeType con l'eccezione: 
   		//	Permesso negato per ottenere la proprieta XMLDocument.nodeType
   		//l'eccezione accade solo con FireFox, ma NON in locale
   		parser=new DOMParser();
   		var xmlDoc=parser.parseFromString(Request.responseText, "text/xml");
   		if (typeof xmlDoc.selectNodes == 'undefined') {
			xmlDoc.selectSingleNode = function(xPath){return mpXml.evaluateXPath(xPath, xmlDoc)[0]}
			xmlDoc.selectNodes = function(xPath){return mpXml.evaluateXPath(xPath, xmlDoc)}
		}
		return xmlDoc;
   }
}

mpXml.evaluateXPath = function(xpathExpression, xmlNode) {
	
    if (typeof xmlNode.documentElement != 'undefined') {
        xmlNode = xmlNode.documentElement;
    }
    var exprResult;
    var tmpTest = [];
    
    if (typeof xmlNode.selectNodes != 'undefined') {
        exprResult = xmlNode.selectNodes(xpathExpression);
    }
    else if (typeof document.evaluate != 'undefined') {
        var tmpExpResult = xmlNode.ownerDocument.evaluate(xpathExpression, xmlNode, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
        exprResult = [];
        while (tmpNextNode = tmpExpResult.iterateNext()) {
            exprResult[exprResult.length] = tmpNextNode;
        }

    }

    return exprResult;
};

mpXml.nodeVal = function(xmlNode){
	try{
	if (xmlNode.textContent) 
		return xmlNode.textContent;
	else
		return xmlNode.nodeTypedValue;
	}
	catch(e){alert(e.message)}
}

/*
 * JSON Tools
 * Genera un documento xml da un oggetto JSON
 */
function json2xml(o, tab) {
   var toXml = function(v, name, ind) {
      var xml = "";
      if (v instanceof Array) {
         for (var i=0, n=v.length; i<n; i++)
            xml += ind + toXml(v[i], name, ind+"\t") + "\n";
      }
      else if (typeof(v) == "object") {
         var hasChild = false;
         xml += ind + "<" + name;
         for (var m in v) {
            if (m.charAt(0) == "@")
               xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
            else
               hasChild = true;
         }
         xml += hasChild ? ">" : "/>";
         if (hasChild) {
            for (var m in v) {
               if (m == "#text")
                  xml += v[m];
               else if (m == "#cdata")
                  xml += "<![CDATA[" + v[m] + "]]>";
               else if (m.charAt(0) != "@")
                  xml += toXml(v[m], m, ind+"\t");
            }
            xml += (xml.charAt(xml.length-1)=="\n"?ind:"") + "</" + name + ">";
         }
      }
      else {
         xml += ind + "<" + name + ">" + v.toString() +  "</" + name + ">";
      }
      return xml;
   }, xml="";
   for (var m in o)
      xml += toXml(o[m], m, "");
   return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, "");
}

/*
 * JSON Tools
 * Genera un oggetto JSON da un documento xml
 */
function xml2json(xml, tab) {
   var X = {
      toObj: function(xml) {
         var o = {};
         if (xml.nodeType==1) {   // element node ..
            if (xml.attributes.length)   // element with attributes  ..
               for (var i=0; i<xml.attributes.length; i++)
                  o["@"+xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue||"").toString();
            if (xml.firstChild) { // element has child nodes ..
               var textChild=0, cdataChild=0, hasElementChild=false;
               for (var n=xml.firstChild; n; n=n.nextSibling) {
                  if (n.nodeType==1) hasElementChild = true;
                  else if (n.nodeType==3 && n.nodeValue.match(/[^ \f\n\r\t\v]/)) textChild++; // non-whitespace text
                  else if (n.nodeType==4) cdataChild++; // cdata section node
               }
               if (hasElementChild) {
                  if (textChild < 2 && cdataChild < 2) { // structured element with evtl. a single text or/and cdata node ..
                     X.removeWhite(xml);
                     for (var n=xml.firstChild; n; n=n.nextSibling) {
                        if (n.nodeType == 3)  // text node
                           o["#text"] = X.escape(n.nodeValue);
                        else if (n.nodeType == 4)  // cdata node
                           o["#cdata"] = X.escape(n.nodeValue);
                        else if (o[n.nodeName]) {  // multiple occurence of element ..
                           if (o[n.nodeName] instanceof Array)
                              o[n.nodeName][o[n.nodeName].length] = X.toObj(n);
                           else
                              o[n.nodeName] = [o[n.nodeName], X.toObj(n)];
                        }
                        else  // first occurence of element..
                           o[n.nodeName] = X.toObj(n);
                     }
                  }
                  else { // mixed content
                     if (!xml.attributes.length)
                        o = X.escape(X.innerXml(xml));
                     else
                        o["#text"] = X.escape(X.innerXml(xml));
                  }
               }
               else if (textChild) { // pure text
                  if (!xml.attributes.length)
                     o = X.escape(X.innerXml(xml));
                  else
                     o["#text"] = X.escape(X.innerXml(xml));
               }
               else if (cdataChild) { // cdata
                  if (cdataChild > 1)
                     o = X.escape(X.innerXml(xml));
                  else
                     for (var n=xml.firstChild; n; n=n.nextSibling)
                        o["#cdata"] = X.escape(n.nodeValue);
               }
            }
            if (!xml.attributes.length && !xml.firstChild) o = null;
         }
         else if (xml.nodeType==9) { // document.node
            o = X.toObj(xml.documentElement);
         }
         else
            alert("unhandled node type: " + xml.nodeType);
         return o;
      },
      toJson: function(o, name, ind) {
         var json = name ? (""+name+"") : "";
         if (o instanceof Array) {
            for (var i=0,n=o.length; i<n; i++)
               o[i] = X.toJson(o[i], "", ind+"\t");
            json += (name?":[":"[") + (o.length > 1 ? ("\n"+ind+"\t"+o.join(",\n"+ind+"\t")+"\n"+ind) : o.join("")) + "]";
         }
         else if (o == null)
            json += (name&&":") + "null";
         else if (typeof(o) == "object") {
            var arr = [];
            for (var m in o)
               arr[arr.length] = X.toJson(o[m], m, ind+"\t");
            json += (name?":{":"{") + (arr.length > 1 ? ("\n"+ind+"\t"+arr.join(",\n"+ind+"\t")+"\n"+ind) : arr.join("")) + "}";
         }
         else if (typeof(o) == "string")
            json += (name&&":") + "\"" + o.toString() + "\"";
         else
            json += (name&&":") + o.toString();
         return json;
      },
      innerXml: function(node) {
         var s = ""
         if ("innerHTML" in node)
            s = node.innerHTML;
         else {
            var asXml = function(n) {
               var s = "";
               if (n.nodeType == 1) {
                  s += "<" + n.nodeName;
                  for (var i=0; i<n.attributes.length;i++)
                     s += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue||"").toString() + "\"";
                  if (n.firstChild) {
                     s += ">";
                     for (var c=n.firstChild; c; c=c.nextSibling)
                        s += asXml(c);
                     s += "</"+n.nodeName+">";
                  }
                  else
                     s += "/>";
               }
               else if (n.nodeType == 3)
                  s += n.nodeValue;
               else if (n.nodeType == 4)
                  s += "<![CDATA[" + n.nodeValue + "]]>";
               return s;
            };
            for (var c=node.firstChild; c; c=c.nextSibling)
               s += asXml(c);
         }
         return s;
      },
      escape: function(txt) {
         return txt.replace(/[\\]/g, "\\\\")
                   .replace(/[\"]/g, '\\"')
                   .replace(/[\n]/g, '\\n')
                   .replace(/[\r]/g, '\\r');
      },
      removeWhite: function(e) {
         e.normalize();
         for (var n = e.firstChild; n; ) {
            if (n.nodeType == 3) {  // text node
               if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) { // pure whitespace text node
                  var nxt = n.nextSibling;
                  e.removeChild(n);
                  n = nxt;
               }
               else
                  n = n.nextSibling;
            }
            else if (n.nodeType == 1) {  // element node
               X.removeWhite(n);
               n = n.nextSibling;
            }
            else                      // any other node
               n = n.nextSibling;
         }
         return e;
      }
   };
   if (xml.nodeType == 9) // document node
      xml = xml.documentElement;
   var json = X.toJson(X.toObj(X.removeWhite(xml)), xml.nodeName, "\t");
   return "{\n" + tab + (tab ? json.replace(/\t/g, tab) : json.replace(/\t|\n/g, "")) + "\n}";
}



(function ($) {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            'array': function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            'number': function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            'object': function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            'string': function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

	$.toJSON = function(v) {
		var f = isNaN(v) ? s[typeof v] : s['number'];
		if (f) return f(v);
	};
	
	$.parseJSON = function(v, safe) {
		if (safe === undefined) safe = $.parseJSON.safe;
		if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v))
			return undefined;
		return eval('('+v+')');
	};
	
	$.parseJSON.safe = false;

})(jQuery);

function jsTest() {
    var opt = {
        //title: 'Esecuzione codice javascript', 
        width: 600,
        height: 500,
        open: function(event, ui) {
            $(this).width("95%");
        },
        buttons: {
            'Chiudi': function() { $(this).dialog('close') },
            '_________Esegui_________': function() {
                try {
                    eval($(this).val())
                }
                catch (e) { alert(e.message) }
            }
        }
    }
    $("<textarea style='width: 100%; height: 100%'></textarea>").dialog(opt);
}

function mpIsNumeric(form_value) 
{ 
    if (form_value.match(/^\d+$/) == null) 
        return false; 
    else 
        return true; 
} 

function mpIsFloat_con_punto_e_virgola(form_value) 
{ 
    if (form_value.match(/^\d+([\.,]\d+)?$/) == null) 
        return false; 
    else 
        return true; 
} 

function mpIsFloat(form_value) 
{ 
    if (form_value.match(/^\d+(\,\d+)?$/) == null) 
        return false; 
    else 
        return true; 
}

function mpIsFloat_OLD(form_value) 
{ 
    if (form_value.match(/^\d+(\.\d+)?$/) == null) 
        return false; 
    else 
        return true; 
} 

function mpNullToString(val) 
{ 
    if (val==null) return "";
    else return val;
} 

//con alcuni formati schianta
//OK: 2009-10-01T00:00.0000000+02:00
//KO: 2009-10-01T00:00:00+02:00
Date.prototype.parseXmlDateHour = function (originalValue) {
	if (originalValue == null) return null;
	var _parsedDate = new Date();
	var _splittedDate = originalValue.split('T')[0].split('-');
	_parsedDate.setFullYear(_splittedDate[0], parseInt(_splittedDate[1], 10) - 1, _splittedDate[2]);
	var _splittedTime = originalValue.split('T')[1].split(':');
	_parsedDate.setHours(_splittedTime[0], _splittedTime[1], _splittedTime[2].split('.')[0]);
	return _parsedDate;
};

//TODO: valutare correttamente il fuso orario che ora è ignorato
Date.prototype.parseXmlDate = function (originalValue) {
	if (originalValue == null) return null;
	var _parsedDate = new Date();
	var _splittedDate = originalValue.split('T')[0].split('-');
	_parsedDate.setFullYear(_splittedDate[0], parseInt(_splittedDate[1], 10) - 1, _splittedDate[2]);
	var _splittedTime = originalValue.split('T')[1].split(':');
	_parsedDate.setHours(_splittedTime[0], _splittedTime[1], 0); //non mi interessano i secondi
	return _parsedDate;
};

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] == obj) {
            return true;
        }
    }
    return false;
}
