
$(function(){


	var dropZone = document.getElementById('input');
	if (dropZone!=null)
	{
  	dropZone.addEventListener('dragover', handleDragOver, false);
  	dropZone.addEventListener('drop', handleFileSelect, false);
	}
});

function fillTextArea(evt) 
{
	var files = document.getElementById('inFile').files;
	var file = files[0];
	var reader = new FileReader();

	// If we use onloadend, we need to check the readyState.
	reader.onloadend = function(evt) 
	{
		if (evt.target.readyState == FileReader.DONE) 
		{ // DONE == 2
			document.getElementById('taContent').value = evt.target.result;
		}//if (evt.target.readyState == FileReader.DONE) 
	};//reader.onloadend = function(evt) 
	reader.readAsText(files[0],"UTF-8");
}//fillTextArea(evt) 

function handleFileSelect(evt) {
    evt.stopPropagation();
    evt.preventDefault();

    var files = evt.dataTransfer.files; // FileList object.
	
    var reader = new FileReader();  
    reader.onload = function(event) {            
         document.getElementById('input').value = event.target.result;
    }        
    
 
   show=new NLPDownload(function (data) { 
     document.getElementById('input').value=data.substr(0,10000);
     $("#spinner").hide();
   });
   
   conv=new NLP('any2txt',show);
   $("#spinner").show();
   
   
   var data = event.dataTransfer.getData("text/plain");
   if (data!="")
     res=NLPURLupload(data,conv);
   else
    res=NLPuploadfile(files[0],conv);
   if (res==false) $("#spinner").hide();
    
	
  }

  function handleDragOver(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
  }

function getObjectClass(obj){
   if (typeof obj != "object" || obj === null) return false;
   else return /(\w+)\(/.exec(obj.constructor.toString())[1];}
   
function NLPuploadfile(file,next) {
   what="/nlprest/base/upload/";
   //console.log("Uploading bin.."+file+" "+ getObjectClass(file));
   if (getObjectClass(file)!="File") return false;
     var _next=next;
   _next.filename=file.name;
   $.ajax({type:"POST",url:what,
	       data: file,
		   cache: false,
		   contentType:"binary/octet-stream",
		   processData: false,
		   cache: false,		 
           success: function(res) {		   
				
				//console.log(" finished with "+res);
				if (_next!==null)
					_next.input=res;
				   _next.process();
				},
				
	
		   error:function(jqXHR, exception) {nlp_error(jqXHR,exception);return;},
		   async:true
           });
}		   
  
function NLPURLupload(url,next) {
   what="/nlprest/base/uploadurl/";
   //console.log("Uploading from URL "+url);
   var _next=next;
   _next.filename="input";
   
   var data = { "url": url
			};
	//console.log("A:"+JSON.stringify(data));		
   $.ajax({type:"POST",url:what,
			contentType:'application/json',
			data: JSON.stringify(data),
		   cache: false,
		   processData: false,
           success: function(res) {		   
				
				//console.log(" finished with "+res);
				if (_next!==null)
					_next.input=res;
				   _next.process();
				},
		   error:function(jqXHR, exception) {nlp_error(jqXHR,exception);return;},
		   async:true
           });
}

  
function NLPupload(text,next) {
   what="/nlprest/base/upload/";
   console.log("Uploading.."+text);
   var _next=next;
   _next.filename="input";
   $.ajax({type:"POST",url:what,
	       data: text,
		   cache: false,
		   contentType:"application/text",
		   processData: false,
		   cache: false,
		   
           success: function(res) {		   
				
				//console.log(" finished with "+res);
				if (_next!==null)
					_next.input=res;
				   _next.process();
				},
		   error:function(jqXHR, exception) {nlp_error(jqXHR,exception);return;},
		   async:true
           });
}
 
function NLPENGINE(xml,onfinish,onerror,onupdate)
 { 
   if (!onfinish) onfinish=null; 
   if (!onerror) onerror=null; 
   if (!onupdate) onupdate=null; 
   
   this.onfinish=onfinish;
   this.onerror=onerror; 
   this.onupdate=onupdate; 
   this.taskID="";
   this.timeout=1000;
   this.log=true;
   this.stoprocessing=false;
   if (xml) this.start(xml);   
   
 }

 NLPENGINE.prototype.start=function (xml) {
   what="/nlpengine/e/startTask";
   
    
   //console.log("NLPEngine starting with ");
   _this=this;
   $.ajax({type:"POST",url:what,
	       processData: false,
		   cache: false,
		   contentType: "application/xml",			 
		   data:  xml,
		   dataType: "text",
           success: function(res) {		   
				_this.taskID=res;
				//console.log("Get taskID "+_this.taskID);
  			  setTimeout(function() {_this.check();},_this.timeout);
				
			  },
		   error:function(jqXHR, exception) {nlp_error(jqXHR,exception);return;},
		   async:true
           });
}

NLPENGINE.prototype.check=function () {
   what="/nlpengine/e/getJSONStatus/"+this.taskID;
   
   //console.log("NLPENGINE checking "+this.taskID);
   var _this=this;
   $.ajax({type:"GET",url:what,
	       processData: false,
		   cache: false,
		   contentType: false,			 
           success: function(result) {		
                 //console.log("Got: " +json);
				 //result=JSON.parse(json);
                 if (result["status"]=="DONE")
                 {				 
				_this.finished=true;
				 result=result["value"];
				if (_this.log) console.log("NLPENGINE finished ");
				if (_this.onfinish!=null)
	
				   _this.onfinish(result);
				
                }
                else				
				if (result["status"]=="ERROR")
				{  if (_this.onerror!=null)
				        _this.onerror(result["value"]) ;
					else	
				       {  $("#spinner").hide();
					   alert(' '+result["value"]);
					   	
					   return;
					   
					   }
				} 
				else
				{     var progress=result["value"];
				if (_this.onupdate!=null)
				        _this.onupdate(progress) ;
				else		
				  if (_this.log) console.log("    Progress "+progress);
				
				_this.timeout=_this.timeout*2;
				if (_this.timeout>4000) _this.timeout=4000;
				if (!_this.stoprocessing)
				setTimeout(function() {_this.check();}, _this.timeout); 
				}
				
			  },
		   error:function(jqXHR, exception) {nlp_error(jqXHR,exception);return;},
		   async:true
           });
}


  
function NLP(name,next,options)
 { this.name=name;
    if (!options) options=null; 
   this.options=options;
   this.next=next;  
   if (next!=null)
       next.registerPrev(this);   
   this.log=true;
   this.finished=false;
   this.resultid="";
 }
 
 NLP.prototype.setinput=function(input,filename)
 { this.input=input;
   this.filename=filename;
 }
 NLP.prototype.registerPrev=function(nlp)
 { this.input=nlp;
 }
 
 NLP.prototype.getInputFileID=function ()
 { if (typeof this.input=='string')
   return this.input;
   else 
     return this.input.resultid;
 }
 NLP.prototype.process=function () {
   what="/nlprest/base/startTask/"+this.name+"/"+this.getInputFileID();
   if (this.options!==null) what=what+"/"+this.options;
   
   //console.log(this.name+" staring with "+this.filename);
   this.timeout=100;
   var _this=this;
   $.ajax({type:"GET",url:what,
	       processData: false,
		   cache: false,
		   contentType: false,			 
           success: function(res) {		   
				_this.resultid=res;
				
				setTimeout(function() {_this.check(res);},_this.timeout);
			  },
		   error:function(jqXHR, exception) {nlp_error(jqXHR,exception);return;},
		   async:true
           });
}

NLP.prototype.check=function () {
   what="/nlprest/base/getStatus/"+this.resultid;
   //if (this.options!==null) what=what+"/"+this.options;
   //console.log(what);
   //console.log(this.name+" checking "+this.filename);
   var _this=this;
   $.ajax({type:"GET",url:what,
	       processData: false,
		   cache: false,
		   contentType: false,			 
           success: function(json) {		
                 
				 result=JSON.parse(json);
                 if (result["status"]=="DONE")
                 {				 
				_this.finished=true;
				_this.resultid=result["value"];
				if (_this.log) console.log(_this.name+" finished with "+_this.filename+": "+_this.resultid);
				if (_this.next!==null && _this.next!== undefined)
				{
				   _this.next.filename=_this.filename;
				   _this.next.process();
				} 
                }
                else				
				if (result["status"]=="ERROR")
				{ alert("Blad: "+result["value"]);return;
				} 
				else
				{    _this.timeout=_this.timeout*2;
				if (_this.timeout>2000) _this.timeout=2000;
				setTimeout(function() {_this.check();}, _this.timeout); 
				}
				
			  },
		   error:function(jqXHR, exception) {nlp_error(jqXHR,exception);return;},
		   async:true
           });
}
 
 function NLPZIP(name,next)
 { 
   NLP.call(this,name,next);
   this.input=new Array();
 }

NLPZIP.prototype=Object.create(NLP.prototype);
NLPZIP.prototype.constructor = NLPZIP;
 
NLPZIP.prototype.registerPrev=function(nlp)
{ this.input.push(nlp);
} 
 
NLPZIP.prototype.process=function () {
   
   inputready=true;
   if (this.input.length<=0) 
   { inputready=false;
   }
   var datajson=new Object();
   datajson.id=new Array();
   datajson.name=new Array();
   data=new Array();
   for (i=0;i<this.input.length; i++)
   {  nlp=this.input[i];
      if (!nlp.finished) 
      {  inputready=false;
	     break;
	  }
	
	 datajson.id[i]=nlp.resultid;
	 datajson.name[i]=nlp.filename;
   }
   if (!inputready)
   { if (this.log) console.log("Inputs not yet ready"); 
	   return;
   }
   what="/nlprest/base/"+this.name+"/";

   _this=this;
     $.ajax({type:"POST",url:what,
	       data: JSON.stringify(datajson),
		   cache: false,
		   contentType:"application/json",	
		   processData: false,		   
           success: function(res) {		   
				_this.finished=true;
				_this.resultid=res;
				if (_this.log) console.log(_this.name+" finished with "+_this.resultid);
				if (_this.next!=null)
				_this.next.process();
				},
		   error:function(jqXHR, exception) {nlp_error(jqXHR,exception);return;},
		   async:true
           });
  
     
   
}   

function NLPDownload(onfinish)
 { 
   NLP.call(this,"show",null);
   this.onfinish=onfinish;
   //$("#result").val("");
 }

NLPDownload.prototype=Object.create(NLP.prototype);
NLPDownload.prototype.constructor = NLPDownload;


NLPDownload.prototype.process=function () {
   what="/nlprest/base/downloadbin/"+this.getInputFileID();
   //console.log(this.name+" staring with: "+what);
   _this=this;
    $.ajax({type:"GET",url:what,
	       processData: false,
		   cache: false,
		   contentType: false,		
		   //dataType: "xml",
           success: function(data) {		   
		            if (_this.onfinish!=null) _this.onfinish(data);
					if (_this.log) console.log(_this.name+" finished.");
			  },
		   error:function(jqXHR, exception) {nlp_error(jqXHR,exception);return;},
		   async:true
           });
   
   
 } 
	


		 
		 function nlp_error(jqXHR, exception) {
		 $("#spinner").hide();
            if (jqXHR.status === 0) {
                alert('Not connect.\n Verify Network.');
            } else if (jqXHR.status == 404) {
                alert('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                alert('Time out error.');
            } else if (exception === 'abort') {
               alert('Ajax request aborted.');
            } else {
                alert('Uncaught Error.\n' + jqXHR.responseText);
            }
			throw "Ajax error";
        } 
 
 function CCL2HTML(ccl)
  { var res="";
    xmlDoc = $.parseXML( ccl )
    $xml = $( xmlDoc )
	var chunks = xmlDoc.getElementsByTagName("chunk") ;
	
	for ( var i0 = 0; i0 < chunks.length ; i0++ ) 
	{  var sentences = chunks[i0].getElementsByTagName("sentence");
	   
       for ( var i1 = 0; i1 < sentences.length ; i1++ ) 
	   { sen=sentences[i1];
	      annsvalue=[];
	     var toks=sen.getElementsByTagName("tok");
	     for (var j=0;j<toks.length;j++)
	     {  node=toks[j];
		    space="";
			if (node.previousSibling!=null && node.previousSibling.previousSibling!=null && node.previousSibling.previousSibling.nodeName!='ns')
		       space=" ";
			
			anns=node.getElementsByTagName("ann"); 
			prefix="";
			safix="";
			for (var i4=0;i4<anns.length;i4++)
		    { ann=anns[i4];
			  val=ann.childNodes[0].nodeValue;
			  nam=ann.getAttribute('chan');
			  //console.log(nam+' = '+val);
			  if (annsvalue[nam]!==val)
			  {  if (val==0)
			     { if (annsvalue[nam] !=null && annsvalue[nam]!==0)
				   safix=safix+"</span>";
				 }
				 else
			      prefix=prefix+"<span class='"+nam+"' title='"+nam+"'>";
			  }
			  
			  annsvalue[nam]=val;
			}
		    
			//prefix=prefix+"<span class='nameentity' title='"+node.getAttribute('chan')+"'>";
			res=res+safix+space+prefix+node.childNodes[1].childNodes[0].nodeValue;
			
			//check if nospace is not used
			//if (node.nextSibling!=null && node.nextSibling.nextSibling!=null && node.nextSibling.nextSibling.nodeName!='ns')
		    //    res=res+' ';
		 } 
	  }
	   for (var key in annsvalue)
	   {  if (annsvalue[key]!==0)
	      res=res+"</span>";
		 }
	  res=res+"<br>";
	}
	return res;
  }
  
 function lex2HTML(ccl)
  { var res="";
    xmlDoc = $.parseXML( ccl )
    $xml = $( xmlDoc )
	var chunks = xmlDoc.getElementsByTagName("chunk") ;
	for ( var i0 = 0; i0 < chunks.length ; i0++ ) 
	{  var sentences = chunks[i0].getElementsByTagName("sentence");
       for ( var i1 = 0; i1 < sentences.length ; i1++ ) 
	   { sen=sentences[i1];
	      annsvalue=[];
	     var toks=sen.getElementsByTagName("tok");
	     for (var j=0;j<toks.length;j++)
	     {  node=toks[j];
		    space="";
			if (node.previousSibling!=null && node.previousSibling.previousSibling!=null && node.previousSibling.previousSibling.nodeName!='ns')
		       space=" ";
			bases=node.getElementsByTagName("base");
			ctags=node.getElementsByTagName("ctag");
			
			prefix="<span class='lex' title='"+bases[0].childNodes[0].nodeValue+" "+ctags[0].childNodes[0].nodeValue+"'>";
			res=res+space+prefix+node.childNodes[1].childNodes[0].nodeValue+"</span>";
			
			//check if nospace is not used
			//if (node.nextSibling!=null && node.nextSibling.nextSibling!=null && node.nextSibling.nextSibling.nodeName!='ns')
		    //    res=res+' ';
		 } 
	  }
	  res=res+"<br>";
	}
	return res;
  }
 
 
  String.prototype.countWords = function(){
  return this.split(/\s+/).length;
}




	  function SaveToDisk(strData, strFileName, strMimeType) {
    var D = document,
        A = arguments,
        a = D.createElement("a"),
        d = A[0],
        n = A[1],
        t = A[2] || "text/plain";

    //build download link:
    a.href = "data:" + strMimeType + "charset=utf-8," + escape(strData);


    if (window.MSBlobBuilder) { // IE10
        var bb = new MSBlobBuilder();
        bb.append(strData);
        return navigator.msSaveBlob(bb, strFileName);
    } /* end if(window.MSBlobBuilder) */



    if ('download' in a) { //FF20, CH19
        a.setAttribute("download", n);
        a.innerHTML = "downloading...";
        D.body.appendChild(a);
        setTimeout(function() {
            var e = D.createEvent("MouseEvents");
            e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            a.dispatchEvent(e);
            D.body.removeChild(a);
        }, 66);
        return true;
    }; /* end if('download' in a) */



    //do iframe dataURL download: (older W3)
    var f = D.createElement("iframe");
    D.body.appendChild(f);
    f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
    setTimeout(function() {
        D.body.removeChild(f);
    }, 333);
    return true;
}