/**
 * xml을 결과로 받는 서버프로그램을 호출, 응답, xslt와 매칭하는 기능을 하는 클래스
 * @param xmlURL xml make servlet url
 * @param xslURL server xsl url
 * @return
 */
function XSLTHelper( xmlURL, xslURL  ) {
   this.xmlURL = xmlURL;
   this.xslURL = xslURL;
}

XSLTHelper.isXSLTSupported = function() {
   return (window.XMLHttpRequest && window.XSLTProcessor ) ||
          XSLTHelper.isIEXmlSupported();
}

XSLTHelper.isIEXmlSupported = function() {
   if ( ! window.ActiveXObject )
      return false;
   try { new ActiveXObject("Microsoft.XMLDOM");  return true; }
   catch(err) { return false; }
}

XSLTHelper.prototype = { 

   loadView: function(container, body) {
      if ( ! XSLTHelper.isXSLTSupported() )  
         return;

      this.xmlDocument   = null;
      this.xslStyleSheet = null;
      this.container     = $(container);

      
      new Ajax.Request( this.xmlURL,
                        {parameters : body,
    	  				onComplete: this.setXMLDocument.bind(this)} );
      
      new Ajax.Request( this.xslURL,
                        {method: "GET",
                        onComplete: this.setXSLDocument.bind(this)} );
   },

   setXMLDocument: function(request) {
      this.xmlDocument = request.responseXML;
      this.updateViewIfDocumentsLoaded();
   },

   setXSLDocument: function(request) {
      this.xslStyleSheet = request.responseXML;
      this.updateViewIfDocumentsLoaded();
   },

   updateViewIfDocumentsLoaded: function() {
      if ( this.xmlDocument == null || this.xslStyleSheet == null )
         return;
      this.updateView();
   },

   updateView: function () {
      if ( ! XSLTHelper.isXSLTSupported() )
         return;

     if ( window.XMLHttpRequest && window.XSLTProcessor )
         this.updateViewMozilla();
     else if ( window.ActiveXObject )
         this.updateViewIE();
     else 
    	 this.showMessage("Internet Explorer and FireFox only");
   },

   updateViewMozilla: function() {
	  //this.showMessage("FF");
      var xsltProcessor = new XSLTProcessor();
      xsltProcessor.importStylesheet(this.xslStyleSheet);
      var fragment = xsltProcessor.transformToFragment(this.xmlDocument, document);

      this.container.innerHTML = "";
      this.container.appendChild(fragment);
   },

   updateViewIE: function(container) {
	  //this.showMessage("IE");
	  var strHtml = this.xmlDocument.transformNode(this.xslStyleSheet);
	  strHtml = strHtml.replaceAll("&lt;", "<");
	  strHtml = strHtml.replaceAll("&gt;", ">");
      this.container.innerHTML = strHtml
   },
   
   showMessage: function(msg) {
	   alert(msg);
   }

}
