/*PROXY-AJAX-INICIO*/
function PRINTERAJAXProxy() {
  this.url = 'http://127.0.0.1:47907/func/';
}

PRINTERAJAXProxy.prototype.isActive = function() {
        if(!this._isActive) {              
           try {
             this._isActive = this.remoteCall('PING', {}, false) == 'PONG';
           } catch (e) {           
             this._isActive = false;                                                                                                                    
           }        
        }
	return this._isActive;
}

PRINTERAJAXProxy.prototype.l2sPRINTERInit = function() {
	return true;
}

PRINTERAJAXProxy.prototype.l2sPrinterGetPrintersList = function() {
	return this.remoteCall('l2sPrinterGetPrintersList', {}, false);
}

PRINTERAJAXProxy.prototype.l2sPrinterPrintPDF = function(pdfRef, copies, printerName, renderEngine, sync) {
	return this.remoteCall('l2sPrinterPrintPDF', {
		pdfRef: pdfRef,
		copies: copies,
		printerName: printerName,
		renderEngine: renderEngine,
		sync: sync
	}, !sync);
}

PRINTERAJAXProxy.prototype.l2sPrinterPrintTEXT2 = function(rawText, printerName, mode, sync) {
	return this.remoteCall('l2sPrinterPrintTEXT2', {
		rawText: rawText,
		printerName: printerName,
  		mode: mode,
		sync: sync
	}, !sync);
}

PRINTERAJAXProxy.prototype.l2sPrinterPrintTEXT3 = function(rawText, base64, printerName, mode, sync) {
	return this.remoteCall('l2sPrinterPrintTEXT3', {
		rawText: rawText,
                base64: base64,
		printerName: printerName,
  		mode: mode,
		sync: sync
	}, !sync);
}

PRINTERAJAXProxy.prototype.newHTTPObject = function(name, values) { 
  if (typeof XMLHttpRequest != 'undefined') { 
    return new XMLHttpRequest(); 
  } 
  try { 
    return new ActiveXObject("Msxml2.XMLHTTP"); 
  } catch (e) { 
    try { 
      return new ActiveXObject("Microsoft.XMLHTTP"); 
    } catch (e) {} 
  } 
  return false; 
}

PRINTERAJAXProxy.prototype.remoteCall = function(name, values, async) {
	var http = this.newHTTPObject();
	http.open('POST', this.url + name, async);
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");           
        http.setRequestHeader("X-Referer", window.location.href);
	var pEncoded = '';
	for(key in values) {
                var value = values[key];                     
                if(value == null) {
                  //value = '';
                  continue;                
                } else {
                  value = encodeURIComponent(value)                
                }
		pEncoded += key.replace(/%20/g, '+') + '=' + value + '&';
	}

        try {
   	  http.send(pEncoded);
	  var content = http.responseText;
          if(http.status > 299) throw 'ERRO: ' + content;
  	  return content;
        } catch (e) {
          throw 'Falha na comunicação com o Agente de IMPRESSÃO.';        
        }
}

/*PROXY-AJAX-FIM*/

function _l2sPRINTERGetProxy(connector) {
    if(!document.l2sPRINTERapp) {      
      var _PRINTERAJAXProxy = new PRINTERAJAXProxy();
      _l2sPRINTERShowAgentStatusShow('Forçando conexão com o Agente de comunicação com a IMPRESSORA...');
      if(_PRINTERAJAXProxy.isActive()) {
	   document.l2sPRINTERapp = _PRINTERAJAXProxy;   
           _l2sPRINTERShowAgentStatusShow(false);        
		window._l2sPRINTERapp_delay = 0;
		return document.l2sPRINTERapp;
      } else {
         throw 'O Agente de comunicação com a IMPRESSORA NÃO foi inicializado.';
      }  
    
    } else if(_l2sPRINTERCheckAgentIsActive()) {
       return document.l2sPRINTERapp;
    }
    throw 'Aguarde o Agente de comunicação com a IMPRESSORA ainda está carregando...';
}

function _l2sPRINTERShowAgentStatusShow(show) {
  var divStatus = document.getElementById('_l2sPRINTERappStatus');
  if(divStatus) {
	divStatus.style.display = show ? 'block' : 'none'; 
  }
}

function _l2sPRINTERShowAgentStatus(message) {                   
   var textTag = document.getElementById('_l2sPRINTERappStatusText');
   if(textTag) {
	textTag.innerHTML = message;
       _l2sPRINTERShowAgentStatusShow(true);
   } else {
	var divStatus = document.createElement(IE ? '<div id="_l2sPRINTERappStatus" >' : 'div');
	divStatus.id = '_l2sPRINTERappStatus';
	divStatus.onclick = function () { _l2sPRINTERShowAgentStatusShow(false); };
	divStatus.style.position = 'absolute';
        divStatus.style.margin = 0; 
        divStatus.style.padding = 0;
        divStatus.style.top = 0;
        divStatus.style.left = 0; 
        divStatus.style.right = 0;
        divStatus.style.bottom = 0;
        divStatus.style.backgroundColor = 'rgba(0, 0, 0, 0.14)';
        divStatus.style.zIndex = 999991;
	divStatus.innerHTML = '<div style="width: 400px; background-color: #fff; position: absolute; margin: 0 auto; right: 0; left: 0; top: 40%; padding: 20px; border-radius: 3px; z-index: 999992; text-align: center;"> <span id="_l2sPRINTERappStatusText" style="font-family: Calibri; color: #5F5D5D; font-weight: bold; font-size: 18px;">Aguardando o Agente carregar...</span> </div>';
	document.body.appendChild(divStatus);
  }     
}

function _l2sPRINTERCheckAppletIsSupported()
{      
  var resutl = null;
  // Walk through the full list of mime types.
  for( var i=0,size=navigator.mimeTypes.length; i<size; i++ )
  {
      // The jpi-version is the plug-in version.  This is the best
      // version to use.
      if( (resutl = navigator.mimeTypes[i].type.match(/^application\/x-java-applet;jpi-version=(.*)$/)) !== null )
          return true;
  }
  return false;
}

function _l2sPRINTERCheckAgentIsActive() {
 var result = false;
 try{
   result = document.l2sPRINTERapp.isActive();
 } catch (e) {     
    result = false;
 }       
 return result;
}

function _l2sSEFAZCheckAgent() {
	window._l2sSEFAZapp_delay--;
   if(window._l2sSEFAZapp_delay <= 0) {  
      _l2sSEFAZShowAgentStatusShow(false);
        return false;      
   }
   if(document.l2sSEFAZappAPPLET) {        
     try{
      window._l2sSEFAZapp_delay--;  
      if(document.l2sSEFAZappAPPLET && l2sSEFAZappAPPLET.isActive && document.l2sSEFAZappAPPLET.isActive()) {   
		 document.l2sSEFAZapp = document.l2sSEFAZappAPPLET;
        _l2sSEFAZShowAgentStatusShow(false);
        return true;    
      }
     } catch (e) {           
        document.l2sSEFAZapp = false;    
        window._l2sSEFAZapplet = false;    
        _l2sSEFAZShowAgentStatus('O Applet não foi carregado. Verifique o suporte ao Java: <a href="http://www.java.com/" target="_NEW">HTTP://www.java.com/</a>, ou instale nosso agente de comunicação.');
     }      
   }    
   _l2sSEFAZShowAgentStatus('Aguardando a carga do Agente (' + window._l2sSEFAZapp_delay + ')');
   setTimeout(_l2sSEFAZCheckAgent, 1000);
   return false;
}

function _l2sPRINTERCheckAgent() {
   window._l2sPRINTERapp_delay--;  
   if((window._l2sPRINTERapp_delay == 32) || (window._l2sPRINTERapp_delay == 16) || (window._l2sPRINTERapp_delay == 1)) {
      var _PRINTERAJAXProxy = new PRINTERAJAXProxy();
      _l2sPRINTERShowAgentStatus('Verificando o Agente de comunicação com a IMPRESSORA...');
      if(_PRINTERAJAXProxy.isActive()) {
		document.l2sPRINTERapp = _PRINTERAJAXProxy;   
           _l2sPRINTERShowAgentStatusShow(false);
		   return true;
      }
   }
   
   if(window._l2sPRINTERapp_delay <= 0) {
      var _PRINTERAJAXProxy = new PRINTERAJAXProxy();
      _l2sPRINTERShowAgentStatus('Conectando com o Agente de comunicação com a IMPRESSORA...');
      if(_PRINTERAJAXProxy.isActive()) {
		document.l2sPRINTERapp = _PRINTERAJAXProxy;   
           _l2sPRINTERShowAgentStatusShow(false);
		   return true;
      } else {
        return false;      
      }
   }
   if(document.l2sPRINTERappAPPLET) {        
     try{
      
      if(document.l2sPRINTERappAPPLET && document.l2sPRINTERappAPPLET.isActive()) {   
	  document.l2sPRINTERapp = document.l2sPRINTERappAPPLET;
        _l2sPRINTERShowAgentStatusShow(false);
        return true;    
      } else {
        _l2sPRINTERShowAgentStatus('Aguardando a carga do Agente de IMPRESSÃO (' + window._l2sPRINTERapp_delay + ')');
         setTimeout(_l2sPRINTERCheckAgent, 1000);
      }
     } catch (e) {           
        document.l2sPRINTERapp = false;    
        window._l2sPRINTERapplet = false;
     }
   }    
   _l2sPRINTERShowAgentStatus('Aguardando a carga do Agente de IMPRESSÃO (' + window._l2sPRINTERapp_delay + ')');
   setTimeout(_l2sPRINTERCheckAgent, 1000);
   return false;
}

function _l2sPRINTERCheckAgentAndInit() {
  if(document.l2sPRINTERapp) {
     try{
      window._l2sPRINTERapp_delay--;            
      if((window._l2sPRINTERapp_delay <= 0) || document.l2sPRINTERapp.isActive()) {         
        _l2sPRINTERShowAgentStatusShow(false);
        document.l2sPRINTERapp.l2sPRINTERInit();
      
        return true;    
      } else {
        _l2sPRINTERShowAgentStatus('Aguardando a carga do Agente (' + window._l2sPRINTERapp_delay + ')');
         setTimeout(_l2sPRINTERCheckAgentAndInit, 1000);
      }
     } catch (e) {           
        document.l2sPRINTERapp = false;    
        window._l2sPRINTERapplet = false;                           
        _l2sPRINTERShowAgentStatus('O Applet não foi carregado. Verifique o suporte ao Java: <a href="http://www.java.com/" target="_NEW">HTTP://www.java.com/</a>, ou instale nosso agente de comunicação.');
     }
   }
}

function l2sPrinterInit() {
    window._l2sPRINTERapp_delay = 35;
    var id = 'l2sPRINTERappAPPLET';           
                          
    if(document.l2sPRINTERapp) {
      if(!_l2sPRINTERCheckAgentIsActive()) {      
         alert('O Agente de comunicação com IMPRESSORA ainda não foi inicializado.');         
         return;
      }
                         
      var r = _l2sPRINTERGetProxy(null).l2sPRINTERInit();
      return r;
    }                                                    

    if(!_l2sPRINTERCheckAppletIsSupported()) {    
        //Tenta usar o agente de comunicação
		document.l2sPRINTERapp = new PRINTERAJAXProxy();
		_l2sPRINTERShowAgentStatus('Conectando com o Agente de comunicação com a IMPRESSORA.');
		setTimeout(_l2sPRINTERCheckAgentAndInit, 1000);
		return document.l2sPRINTERapp;
    }
    var jarFile = 'apps/l2sPRINTERappV2_0_0.jar';      
    var printerApplet;
    if (IE) {
      printerApplet = document.createElement("<applet name='" + id + "' id='" + id + "' archive='" + jarFile + "' code='br.com.l2software.api.printer.PRINTERApplet.class'>");
    } else {
      printerApplet = document.createElement("applet");
    }    
    printerApplet.setAttribute("name", "l2sPRINTERappAPPLET");    
    printerApplet.setAttribute("width", 1);
    printerApplet.setAttribute("height", 1);    
    printerApplet.setAttribute("permissions", 'all-permissions');    
    printerApplet.setAttribute("archive", jarFile);    
    printerApplet.setAttribute("code", 'br.com.l2software.api.printer.PRINTERApplet.class');    
    printerApplet.style.left = 0;
    printerApplet.style.top = 0;
    printerApplet.style.width = '1px';
    printerApplet.style.height = '1px';
    printerApplet.style.backgroundColor = "#FFFFFF";
    
    printerApplet.id = id;
    printerApplet.name = id;
    document.body.appendChild(printerApplet);
    window._l2sPRINTERapplet = eval(id);    

    _l2sPRINTERShowAgentStatus('Carregando o Applet de comunicação com a IMPRESSORA.');
    setTimeout(_l2sPRINTERCheckAgent, 1000);
    return printerApplet;
}



/* HTTP://www.l2maker.com.br/ */