﻿var disabled_imagegalleryused_event=false;
var imgc=0;
var tip=null;
var  uploadcancel=false;
var  parent_fabric_dragging=false;
var dragendtimer=null;
var currentfabriccanvas=null;

var printdpi=300; //180
var dpi=96;
var JPGQ=0.95;

var fileindex=-1;
var NoSetGUIObjProps=false;
var clickmode='NULL';  //ADMIN/EDIT/FILL
var cropper=null;
var showimausedindicator=true;


var resourcecache=new Array();



// Used to detect whether the users browser is an mobile browser
function isMobile() {
    ///<summary>Detecting whether the browser is a mobile browser or desktop browser</summary>
    ///<returns>A boolean value indicating whether the browser is a mobile browser or not</returns>

    if (sessionStorage.desktop) // desktop storage 
        return false;
    else if (localStorage.mobile) // mobile storage
        return true;

    // alternative
    mobile = ['iphone','ipad','android','blackberry','nokia','opera mini','windows mobile','windows phone','iemobile','tablet','mobi']; 
    var ua=navigator.userAgent.toLowerCase();
    for (var i in mobile) if (ua.indexOf(mobile[i]) > -1) return true;

    // nothing found.. assume desktop
    return false;
}

function findresourcecache(id){
  for(var i=0;i<resourcecache.length;i++){
   var c=resourcecache[i];
   if(c.id==id){
     return c;
   }
  }
 return null;
}

function addresourceache(id,url,onadd,data){

       var p=window.location.href.indexOf(".dll");
       var baseurl=window.location.href.substring(0,p+4)+'/';

       if((url.indexOf("http")==0)||(url.indexOf("data:image")==0)){
          baseurl='';
       }


  loadImage(
          baseurl+url,
          function (img) {
            var c=new Object();
             c.url=url;
             c.id=id;
             c.img=img;
            resourcecache.push(c);
            onadd(c,data);
          },
          {
             canvas: true,
             orientation:true
           }
        );
}

function handleFileSelect(evt) {
    var files = evt.files; 
    var files = event.target.files, i = 0, j = files.length, file, reader;
    Lobs2=new Array();
     for (var i=0;i<currentfabriccanvas.Lobs.length;i++){
      var o=currentfabriccanvas.Lobs[i];
      Lobs2.push(o);
     }
   
   var  volem_imas=0;
    var o2=findobjbyclass('image',Lobs2,false);
    if(o2==null){ //no queda cap imatge buida
    // clearimage();
     volem_imas=numobjsbyclass('image',Lobs2);
    }else{
     volem_imas=numimasempty(Lobs2);
    }
   if(volem_imas==0){
     alert('No hay más imágenes para seleccionar');
     return;
   }
   if (j> volem_imas){
     alert('selecciona solo '+volem_imas+' imágenes');
     return;
   }

    for (i = 0; i < j; i += 1) {
      file = files[i];
        loadImage(
          file,
          function (img) {
            var o2=findobjbyclass('image',Lobs2,true);
            o2.image=img.toDataURL('image/jpeg', JPGQ);
            o2.load();       
         },
         {
           maxWidth: 800,
           maxHeight: 800,
           minWidth: 100,
           minHeight: 100,
           canvas: true,
           orientation:true
         }
        )

   //   };
}
//    for (i = 0; i < j; i += 1) {
//        file = files[i];
//        file.reader.readAsDataURL(file);
//    }
}





  function BrowseFiles() {

    Lobs2=new Array();
     for (var i=0;i<currentfabriccanvas.Lobs.length;i++){
      var o=currentfabriccanvas.Lobs[i];
      Lobs2.push(o);
     }  
     if(numimasempty(Lobs2)>1)
      var ima = document.getElementById('filefield')
    else
       var ima = document.getElementById('filefieldsingle');
     ima.click();
   }
  function BrowseFile() {
     var ima = document.getElementById('filefieldsingle');
     ima.click();
   }


function getuniquestring() { 
    // http://www.ietf.org/rfc/rfc4122.txt 
    var s = []; 
    var hexDigits = "0123456789abcdef"; 
    for (var i = 0; i < 36; i++) { 
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); 
    } 
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010 
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01 
    s[8] = s[13] = s[18] = s[23] = "-"; 
 
    var uuid = s.join(""); 
    return uuid; 
} 

function uncrop(save){
 var  imagec = document.getElementById('imagecropper');
 imagec.style.visibility='hidden';
 if(save){
   var image=currentfabriccanvas.findobjbyid(cropper.imageid);
   var c=cropper.getCropBoxData();
   var c2=cropper.getCanvasData();
   image.cropdata.x=((c.left-c2.left)/c2.width);
   image.cropdata.y=((c.top-c2.top)/c2.height);
   image.cropdata.w=(c.width/c2.width);
   image.cropdata.h=(c.height/c2.height);   
   image.cropdata.a=cropper.getData().rotate;
   image.crop(false);

   var str1='w='+image.cropdata.w;
   var str2='h='+image.cropdata.h;
   var str3='x='+image.cropdata.x;
   var str4='y='+image.cropdata.y;
   var str5='id='+image.fileid;
   var str6='fileid='+cropper.imageid;
   var str7='fit='+image.cropdata.fit;
   var str8='colormode='+image.cropdata.colormode;

   ajaxRequest(MainmForm.form,'oncropped',[str1,str2,str3,str4,str5,str6,str7,str8]);
 }else{
  var image=currentfabriccanvas.findobjbyid(cropper.imageid);
  image.cropdata.fit=initfit;
  image.cropdata.colormode=initcolormode;

}
 cropper.destroy();
 cropper=null;
}


function cropinvertratio(){
 cropper.setAspectRatio(cropper.h/cropper.w);
 var t=cropper.w;
 cropper.w=cropper.h;
 cropper.h=t;
}

function colormode(c){
 var image=currentfabriccanvas.findobjbyid(cropper.imageid);
 image.cropdata.colormode=c; 
 if(c==2)
  cropper.cropBox.style.filter="grayscale(100%)";
 if(c==1)
  cropper.cropBox.style.filter="sepia(100%)";
 if(c==0)
  cropper.cropBox.style.filter="";

}


function cropinvertfit(containerw,containerh){
 var image=currentfabriccanvas.findobjbyid(cropper.imageid);
 image.cropdata.fit=!image.cropdata.fit; 
 var  imagec = document.getElementById('imagecropper');
 imagec.style.visibility='hidden';
 cropper.enable();  
 cropgranted(cropper.imageid,cropper.w,cropper.h,containerw,containerh);
}


function imagetourl(image,mime){
  var  canvas = document.getElementById('canvascropper');
  canvas.width=image.naturalWidth;
  canvas.height=image.naturalHeight;

  var ctx = canvas.getContext('2d',{ willReadFrequently: true });

  if(mime=='image/png')
   ctx.fillStyle = 'transparent'
 else
   ctx.fillStyle = 'white';

  ctx.fillRect(0, 0,canvas.width,canvas.height);

  ctx.drawImage(image,0,0);

  return canvas.toDataURL(mime, JPGQ); //'image/jpeg'

}


 function FitImage(image,w,h,mime){

  var r=h/w;
  w=image.naturalWidth;
  h=w*r;

  var w2=0;
  var h2=0;
  if(w>h){
     h2=h;
     w2=h2*(image.naturalWidth/image.naturalHeight); 
     if(w2>w){
      w2=w;
      h2=w2*(image.naturalHeight/image.naturalWidth); 
     }
  }else{
     w2=w;
     h2=w2*(image.naturalHeight/image.naturalWidth); 
     if(h2>h){
      h2=h;
      w2=h2*(image.naturalWidth/image.naturalHeight); 
     }
  } 
  var  canvas = document.getElementById('canvascropper');
  canvas.width=w;
  canvas.height=h;
  var ctx = canvas.getContext('2d',{ willReadFrequently: true });
  if(mime=='image/png')
   ctx.fillStyle = 'transparent'
  else
   ctx.fillStyle = 'white';

  ctx.fillRect(0, 0,w,h);
  var ofx=(w-w2)/2;
  var ofy=(h-h2)/2;

  ctx.drawImage(image,0,0,image.naturalWidth,image.naturalHeight,ofx,ofy,w2,h2);
  return canvas.toDataURL(mime, JPGQ);  //'image/jpeg'
} 

function initcrop(id,w,h,containerw,containerh){
var image=currentfabriccanvas.findobjbyid(id);

 initfit=image.cropdata.fit;
 initcolormode=image.cropdata.colormode;

 cropgranted(id,w,h,containerw,containerh);

 var str7='fit='+image.cropdata.fit;
 var str8='colormode='+image.cropdata.colormode;

 ajaxRequest(MainmForm.form,'oninitcropinfo',[str7,str8]);

}


function extractUrlResourceext(url){
 if(url=='')
  return '';
 var i=url.lastIndexOf('.');
 var ext=url.substring(i); 
 return ext;
  
}

function cropgranted(id,w,h,containerw,containerh){


var image=currentfabriccanvas.findobjbyid(id);
var  imagec = document.getElementById('imagecropper');

 var file=findfilebyid(image.fileid);

 if(file!=null){
  var mime=file.type;//'image/jpeg';
 }else{ //llegim projecte de disc
  if(extractUrlResourceext(image.image)=='.jpg')
   var mime='image/jpeg'
  if(extractUrlResourceext(image.image)=='.png')
   var mime='image/png';
 }


imagec.style.width=containerw+'px';
imagec.style.height=containerh+'px';
imagec.width=containerw;
imagec.height=containerh;

var o=new Object();
image.cropdata.a=0;
if(image.cropdata.a==0){
 o.x=Math.round(image.ima.width*image.cropdata.x);
 o.y=Math.round(image.ima.height*image.cropdata.y);
 o.width=Math.round(image.ima.width*image.cropdata.w)-2;
 o.height=Math.round(image.ima.height*image.cropdata.h)-2;
}else{
 o.x=Math.round(image.ima.height*image.cropdata.x);
 o.y=Math.round(image.ima.width*image.cropdata.y);
 o.width=Math.round(image.ima.height*image.cropdata.w)-2;
 o.height=Math.round(image.ima.width*image.cropdata.h)-2;
}
o.rotate=image.cropdata.a;

o.scaleX=1;
o.scaleY=1;

imagec.onerror=function(){
 alert('error');
}

imagec.onload=function(){
  imagec.onload=null;
  if(image.cropdata.fit){
    var fiturl=FitImage(imagec,w,h,mime);  
    if(cropper==null) 
      imagec.src=fiturl;
    if(image.cropdata.a==0){
     o.x=0;
     o.y=0;
     o.width=imagec.naturalWidth;
     o.height=imagec.naturalHeight;
    }else{
     o.x=0
     o.y=0;
     o.width=imagec.naturalHeight;
     o.height=imagec.naturalWidth;
    }
  }

if(cropper!=null){ 
 if(image.cropdata.fit)
  cropper.replace(fiturl)
 else{
  cropper.replace(imagetourl(imagec,mime));
}

 return;
}
cropper = new Cropper(imagec, {
  center:false,
 autoCrop:true,
  autoCropArea:1,
  movable:true,
  zoomable:true,
   rotable:false,
  scalable:true,
zoomOnTouch:true,
zoomOnWheel:true,
cropBoxResizable:false,
cropBoxMovable:false,
toggleDragModeOnDblclick:false,
  dragMode:"move",
  checkOrientation:false,
  data:o,
  aspectRatio: w / h,
  viewMode:1,
ready: function() {

 if(image.cropdata.colormode==2)
  cropper.cropBox.style.filter="grayscale(100%)";
 if(image.cropdata.colormode==1)
  cropper.cropBox.style.filter="sepia(100%)";
 if(image.cropdata.colormode==0)
  cropper.cropBox.style.filter="";


   imagec.style.visibility='visible';
   if(!image.cropdata.fit){
     cropper.enable();  
   }else{
    cropper.reset();
    cropper.disable();  
  
   }
   

    },
  crop(event) {
  //  console.log(event.detail.x);
  //    console.log(event.detail.y);
  //    console.log(event.detail.width);
  //    console.log(event.detail.height);
  //    console.log(event.detail.rotate);
  //    console.log(event.detail.scaleX);
  //    console.log(event.detail.scaleY);
  },
});
cropper.imageid=id;
cropper.w=w;
cropper.h=h;
}

imagec.src = '';
imagec.src=image.image;
}


function crop(id,w,h){
var  imagec = document.getElementById('imagecropper');
 imagec.style.visibility='hidden';
    var str1='id='+id;
    var str2='w='+w;
    var str3='h='+h;
    ajaxRequest(MainmForm.form,'croprequest',[str1,str2,str3]);    
}

function  incfileref(fileid){
 for (var i=0;i<imasrefs.length;i++){
  var r=imasrefs[i];
  if(r.fileid==fileid){
    r.count++;
    return;
  }
 }
 var r=new Object();
 r.fileid=fileid;
 r.count=1;
 imasrefs.push(r);
}

function  decfileref(fileid){
 for (var i=0;i<imasrefs.length;i++){
  var r=imasrefs[i];
  if(r.fileid==fileid){
    r.count--;
    if(r.count==0){
     imasrefs.splice(i, 1);
    }  
    return;
  }
 }
}

function  getfileref(fileid){
 for (var i=0;i<imasrefs.length;i++){
  var r=imasrefs[i];
//console.log('imasref:'+r.fileid);
  if(r.fileid==fileid){
    return r.count;
    return;
  }
 }
  return 0;
}



imgempty=new Image();

var canvascrop=document.createElement('canvas');  

imgblank=document.createElement('canvas');  
imgblank.width=10;
imgblank.height=10;
var ctx = imgblank.getContext('2d',{ willReadFrequently: true });
ctx.fillStyle = "white";
ctx.fillRect(0, 0, 10, 10);


imgclipart=document.createElement('canvas');  
imgclipart.width=10;
imgclipart.height=10;
var ctx = imgblank.getContext('2d',{ willReadFrequently: true });
ctx.fillStyle = "silver";
ctx.fillRect(0, 0, 10, 10);



var fileimas=new Array();
var imasrefs=new Array();
var downloadqueue=new Array();




function setimasused(){
  for(var i=0;i<fileimas.length;i++){
   var file=fileimas[i];
   var p=file.unipanel;
   if ((getfileref(file.id)>0)&&(showimausedindicator)){
     p.show();
   }else{
     p.hide();
   }
  }  
}


function getimaunused(from){
  for(var i=from;i<fileimas.length;i++){
   var file=fileimas[i];
 //  var p=file.unipanel;
   if (getfileref(file.id)==0){
     return i;
   }
  }  
  return -1;
}



function LoadFileToFabric(o2,index){
   if(index==-1)
     return;
   o2.stopanimation();
   var file=fileimas[index];
   o2.load(file);     

   var i=getimaunused(index+1);
   if(i!=-1){
    var str='fi='+file.id;
    if(disabled_imagegalleryused_event==false)
     ajaxRequest(MainmForm.form,'imagegalleryused',[str]);    
   }
}


function loadbig(fileid,ima,dims,disabled){
  var file=findfilebyid(fileid);
  var mime=file.type;//'image/jpeg';
  loadImage(
          file,
          function (img) {
            var filter='';
            if(disabled)
             filter='filter:opacity(30%);';
            ima.setHtml('<img style="'+filter+'object-fit: cover;width:'+dims+'px;height:'+dims+'px" src="'+img.toDataURL(mime, JPGQ)+'" height="59px" width="59px" />');          
         },
         {
           maxWidth: 300,
           maxHeight: 300,
           minWidth: 1,
           minHeight: 1,
           canvas:true,
           orientation:true
         }
        )
}

function findfilebyid(fileid){
  for (var i=0;i<fileimas.length;i++){
    var file=fileimas[i];
    if(file.id==fileid){
     return file;     
    }   
  }
  return null;
}

function removefilebyid(fileid){
//console.log('removefilebyid:'+fileid);
  for (var i=0;i<fileimas.length;i++){
    var file=fileimas[i];
    if(file.id==fileid){
//     console.log('removefilebyid:found!');

     fileimas.splice(i, 1);
     break;
    }   
  }

}


function postthumb(urlthumb,orientation,imgc,data,ima,fileid,filter){

    if(orientation==8){
     ima.setHtml('<img onerror="window.URL.revokeObjectURL(this.src);_onloaderror(this);" onload="_onload('+imgc+');window.URL.revokeObjectURL(this.src);" data-fileid="'+fileid+'" id="ima'+imgc+'" 	style="'+filter+'transform: rotate(-90deg);object-fit: cover;width:'+data.dims+'px;height:'+data.dims+'px" src="'+urlthumb+'" height="'+data.dims+'px" width="'+data.dims+'px" />');
    }
    else{
     if(orientation==6){
      ima.setHtml('<img onerror="window.URL.revokeObjectURL(this.src);_onloaderror(this);" onload="_onload('+imgc+');window.URL.revokeObjectURL(this.src);" data-fileid="'+fileid+'" id="ima'+imgc+'" 	style="'+filter+'transform: rotate(90deg);object-fit: cover;width:'+data.dims+'px;height:'+data.dims+'px" src="'+urlthumb+'" height="'+data.dims+'px" width="'+data.dims+'px" />');
     }
     else{
      ima.setHtml('<img onerror="window.URL.revokeObjectURL(this.src);_onloaderror(this);" onload="_onload('+imgc+');window.URL.revokeObjectURL(this.src);" data-fileid="'+fileid+'" id="ima'+imgc+'" 	style="'+filter+'object-fit: cover;width:'+data.dims+'px;height:'+data.dims+'px" src="'+urlthumb+'" height="'+data.dims+'px" width="'+data.dims+'px" />');
     }
    }

}

function LoadFileToUniImage(ima,panel,fileid,dims,disabled){
 fileid=decodeURIComponent(fileid);
 var file=findfilebyid(fileid);
 file.uniima=ima;
 file.unipanel=panel;

 if(file.url!=null){ //imagen revelado quan llegim projecte guardat
  var o=new Object();
   o.ima=ima;
   o.fileid=fileid;
   o.dims=dims;
   o.file=file;
    var filter='';
    if(disabled)
     filter='filter:opacity(30%);';

   ima.setHtml('<img onload="_onload('+imgc+')" id="ima'+imgc+'" style="'+filter+'object-fit: cover;width:'+dims+'px;height:'+dims+'px" src="'+file.url+'" height="'+'59px'+'px" width="'+'59px'+'px" />');
   imgc++; 
   return;
 }

 
 if(file.hasthumb){
  var o=new Object();
  o.ima=ima;
  o.fileid=fileid;
  o.dims=dims;
  o.file=file;
  o.disabled=disabled;
  ima.o=o; 

  loadImage.parseMetaData(
   file,
   function (data) {
    var filter='';
    if(disabled)
     filter='filter:opacity(30%);';
    var exif = data.exif;
    var orientation =data.file.orientation;
    var thumbnail = exif && exif.get('Thumbnail');
    var blob = thumbnail && thumbnail.get('Blob');
    if(typeof blob!='undefined'){
     postthumb(window.URL.createObjectURL(blob),orientation,imgc,data,ima,fileid,filter);
    }
    else{
    // exifr.thumbnailUrl(file).then( urlthumb => postthumb(urlthumb,orientation,imgc,data,ima,fileid,filter));
      loadbig(fileid,ima,dims,disabled);
    }

    imgc++;
   },
   {
 //    maxMetaDataSize: 262144000,
     disableImageHead: false
   },o 
  );
 }else{
  loadbig(fileid,ima,dims,disabled);
 }
}

function _onloaderror(i){
 var fileid=i.getAttribute('data-fileid');
// console.log('load thumb error');

// fileid=decodeURIComponent(fileid);
 var file=findfilebyid(fileid);
 loadbig(fileid,file.uniima,file.uniima.o.dims,file.uniima.o.disabled);

// const ima = document.getElementById('ima'+imgc);



}


function _onload(c){
const image = document.getElementById('ima'+c);
return;
const cropper = new Cropper(image, {
  aspectRatio: 16 / 9,
  crop(event) {
//    console.log(event.detail.x);
//    console.log(event.detail.y);
//    console.log(event.detail.width);
//    console.log(event.detail.height);
//    console.log(event.detail.rotate);
//    console.log(event.detail.scaleX);
//    console.log(event.detail.scaleY);
  },
});

}


function upload(id,filename,pagew,pageh){
  var pw=(pagew/2.54)*printdpi; //quan ocupa en pix
  var ph=(pageh/2.54)*printdpi; //quan ocupa en pix       
  var file=findfilebyid(id);
  loadImage(
          file,
          function (img) {         
           var str1='id='+id;
           var str2='filename='+filename;
           var str3='data='+img.toDataURL('image/jpeg', JPGQ);
           downloadqueue.splice(0,1);
           ajaxRequest(MainmForm.form,'imagesave',[str1,str2,str3]);       
        //   startdownload();
          },
          {
             maxWidth: Math.max(pw,ph),
             maxHeight: Math.max(pw,ph),
             minWidth: 100,
             minHeight: 100,
             canvas: true,
             orientation:true
           }
        );
}


function pngParser(buffer) {

  var  width= -1;         
  var   height= -1;         
  var error=true;
  var  dimstrobades=false;

  var view = new DataView(buffer),
      len = buffer.byteLength,
      magic1, magic2,
      chunks = [],
      size, fourCC, crc, offset,
      pos = 0;  // current offset in buffer ("file")

  // check header
  magic1 = view.getUint32(pos); pos += 4;
  magic2 = view.getUint32(pos); pos += 4;



  if (magic1 === 0x89504E47 && magic2 === 0x0D0A1A0A) {
    error=false;
    // parse chunks
    while (pos < len) {

      // chunk header
      size = view.getUint32(pos);
      fourCC = getFourCC(view.getUint32(pos + 4));

      if(fourCC=="IHDR"){
       width= view.getUint32(pos + 8);         
       height= view.getUint32(pos + 12);         
       dimstrobades=true;
       //console.log(width+'x'+height);
      }


      // data offset
      offset = pos + 8;
      pos = offset + size;

      // crc
      crc = view.getUint32(pos);
      pos += 4;

      // store chunk
      chunks.push({
        fourCC: fourCC,
        size: size,
        offset: offset,
        crc: crc
      })
    }

    return {chunks: chunks,w:width,h:height,found:dimstrobades,error:error}
  } 
  else {
      return {error: "Not a PNG file."}
  }

  function getFourCC(int) {
    var c = String.fromCharCode;
    return c(int >>> 24) + c(int >>> 16 & 0xff) + c(int >>> 8 & 0xff) + c(int & 0xff);
  }
}


function readfilejpegdims(file,o,f){
   var fr=new FileReader();
   fr.o=o;
   fr.f=f;
   fr.onload=function(event) {
     var found=false;
     var w=-1;
     var h=-1;    
     var error=false;
     try{
       if(file.type=='image/png'){
         
	 var info = pngParser(this.result);
              fr.f(fr.o,info.found,info.w,info.h,info.error);

	  // parse each chunk here...
	//  for (var i = 0, chunks = info.chunks, chunk; chunk = chunks[i++];) {
	//    console.log("CHUNK : " + chunk.fourCC);
	//    console.log("SIZE  : " + chunk.size + " bytes");
	//    console.log("OFFSET: " + chunk.offset + " bytes");
	//    console.log("CRC   : 0x" + (chunk.crc>>>0).toString(16).toUpperCase());
	//    console.log("-------------------------------");
	//  }
 
          return;
       }



       var uInt8Array = new DataView(this.result);    
       var c=2; 
       var b=uInt8Array.getUint8(c);
        c++;
       var n=uInt8Array.byteLength;
       while((c<n)&&(b==255)){
         var b=uInt8Array.getUint8(c);
         c++;
         if((b==0xC0)||(b==0xC1)||(b==0xC2)||(b==0xC3)){
            found=true;
            c=c+3;
            var h=uInt8Array.getUint16(c);
            c=c+2;
            var w=uInt8Array.getUint16(c);
            c=c+1;
            var bitdepth=uInt8Array.getUint8(c);
            c=c+1;
            break;
         }else
         if(b==0xFF){
          var b=uInt8Array.getUint8(c);
           c++; 
         }else           
         if((b==0xD0)||(b==0xD1)||(b==0xD2)||(b==0xD3)||(b==0xD4)||(b==0xD5)||(b==0xD6)||(b==0xD7)||(b==0xD8)||(b==0xD9)||(b==0x01)){
           c++; 
           var b=uInt8Array.getUint8(c);
           c++; 
         }else{
           var w=uInt8Array.getUint16(c);
           c=c+w; 
           var b=uInt8Array.getUint8(c);
           c++; 
         }           
       }
     } catch (er) {
       console.error(er);
       error=true; 
     }
     fr.f(fr.o,found,w,h,error);
   }  //fi onload
   fr.readAsArrayBuffer(file);
}

function readfileexifjpegdims(file,o,f){
 var o2=new Object();
  o2.o=o;
  o2.f=f;

 if(f.type=='image/png'){
     data.f( data.o,false,1,1,-1,false);        
     return; 
 }

 loadImage.parseMetaData(
  file,
  function (data) {

    if (typeof data.exif=='undefined'){          
      data.f( data.o,false,1,1,-1,false);        
     return;
    }
    var thumb=data.exif.get('Thumbnail');
    var hasthumb=(typeof thumb!='undefined');

    var exifIFD = data.exif && data.exif.get('Exif')
    if (exifIFD) {
      // A specific Exif IFD tag value:
      var  pdX=exifIFD.get('PixelXDimension');
      var  pdY=exifIFD.get('PixelYDimension');
      if ((typeof pdX=='undefined')||(typeof pdY=='undefined')){
       data.f( data.o,false,1,1,-1,hasthumb);        
       return;
      }
    }else{
     data.f( data.o,false,1,1,-1,hasthumb);        
     return;   
   }

   var orientation=data.exif.get('Orientation');

    var w=pdX;
    var h=pdY;
    data.f( data.o,true,w,h,orientation,hasthumb);        
  },
  {
    //    maxMetaDataSize: 0,
    disableImageHead: false,
  },o2
 );
}

function getjpegdims(files,c,ongetteddims,form){

    var str1='count='+files.length;
    var str2='current='+c;
    ajaxRequest(form,'imagesselected2_work',[str1,str2]);       


 if(c==files.length){
   ongetteddims(files,form);
   return;
 }
 var file=files[c];
 var o=new Object();
 o.file=file;
 o.file.error=false;
 o.file.orientation=-1;
 o.file.hasthumb=false;
 o.files=files;
 o.c=c;
 o.ongetteddims=ongetteddims;


 readfilejpegdims(file,o,function(data,found,w,h,error){
    if(error){
      data.file.error=true;
      getjpegdims(data.files,data.c+1,data.ongetteddims,form);       
      return; 
    } 
    if(found){ 
     data.file.width=w;
     data.file.height=h;
     readfileexifjpegdims(data.file,data,function(data,found,w,h,orientation,hasthumb){
       data.file.hasthumb=hasthumb; 
       if(found){
        if((orientation==6)||(orientation==8)){ 
         data.file.orientation=orientation;
         var t=data.file.width;
         data.file.width=data.file.height;
         data.file.height=t;
        }
       }
       getjpegdims(data.files,data.c+1,data.ongetteddims,form);       
     });
   }else{  //not found
     readfileexifjpegdims(file,o,function(data,found,w,h,orientation,hasthumb){
       data.file.hasthumb=hasthumb;  
       if(found){
        data.file.orientation=orientation;
        if((orientation==6)||(orientation==8)){ //'right-top'
         data.file.width=h;
         data.file.height=w;
        }else{
         data.file.width=w;
         data.file.height=h;
        }
       }else{
        data.file.width=1;
        data.file.height=1;
       }
       getjpegdims(data.files,data.c+1,data.ongetteddims,form);
     });
   }
 });
};

function ongetteddims(files,form){
 var i = 0, j = files.length, file;
    var str='<xml>';
    for (i = 0; i < j; i += 1) {
        file = files[i];
        var fileid=file.name+file.lastModified+file.size+file.width+file.height;
        if(findfilebyid(fileid)==null){
         file.id=fileid;
         file.url=null;
         file.uniima=null;
         file.unipanel=null;
         str=str+'<file id="'+encodeURIComponent(file.id)+'" w="'+file.width+'" h="'+file.height+'" error="'+file.error+'" date="'+file.lastModified+'" path="'+file.webkitRelativePath+'" />';
         fileimas.push(file);
        }
    }
    str=str+'</xml>';   
    var str1='xml='+str;
    ajaxRequest(form,'imagesselected2',[str1]);       

   //reset
    var ima = document.getElementById('filefield2');
    if(ima!=null)
     ima.value="";
    var ima = document.getElementById('filefield3');
    if(ima!=null)
     ima.value="";


}

function convertheic2jpeg(lin,l,onend,cc,total){        
    
//const reader = new FileReader();
//reader.onload = function(e) {
  //  const blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
    var file=lin.pop();
    //let blob = new Blob(await file.arrayBuffer());
    //const blob = async (file) => new Blob([new Uint8Array(await file.arrayBuffer())], {type: file.type2});
    const blob = new Blob([file],{type: file.type2})
    //console.log(blob);
    
    
    var str1='count='+total;
    var str2='current='+cc;
    ajaxRequest(MainmForm.form,'imagesselected3_work',[str1,str2]);       
    
    
    heic2any({ blob,toType: "image/jpeg",quality: 0.8 })
              .then((conversionResult) => {
                 var file2 = new File([conversionResult], file.name);                  
                 file2.lastModified=file.lastModified; 
                 l.push(file2);
                if(lin.length==0){
                    onend();
                }else{
                    convertheic2jpeg(lin,l,onend,cc+1,total)
                }
              })
             .catch((e) => {
                  // alert(e.message); 
                  if(lin.length==0){
                    onend();
                  }else{
                    convertheic2jpeg(lin,l,onend,cc+1,total);
                  }
                // see error handling section
             });
//};
//var file=lin.pop;
//reader.readAsArrayBuffer(file);              
}

function getExtension(path) {
    var basename = path.split(/[\\/]/).pop(),  // extract file name from full path ...
                                               // (supports `\\` and `/` separators)
        pos = basename.lastIndexOf(".");       // get last position of `.`

    if (basename === "" || pos < 1)            // if file name is empty or ...
        return "";                             //  `.` not found (-1) or comes first (0)

    return basename.slice(pos + 1);            // extract extension ignoring `.`
}

function handleFileSelect2(evt) {

    var files = evt.files; 
    var files = event.target.files;
     var  j = files.length;
    if(j==0)
      return;
    var l=new Array();
    var lconvert=new Array();
    for (var i=0;i<files.length;i++){
      var f=files[i];
      console.log(f.type);
      f.type2=f.type;
//alert(f.type);
      if(f.type2==''){
        if(getExtension(f.name).toLowerCase()=='heic'){            
            f.type2='image/heic';//heif
        }          
      }
      if((f.type2=='image/jpeg')||(f.type2=='image/png')||(f.type2=='image/heic')){
        if(f.size> 0){        
            if(f.type2=='image/heic') {
             lconvert.push(f);
            }
            else{
             l.push(f);
            }
        }
      }
    }
    
    if(lconvert==0){
     var str1='count='+l.length;
     ajaxRequest(MainmForm.form,'imagesselected2_pre',[str1]);       
     getjpegdims(l,0,ongetteddims,MainmForm.form);    
    }else{      
      var str1='count='+lconvert.length;
      ajaxRequest(MainmForm.form,'imagesselected3_pre',[str1]);               
      convertheic2jpeg(lconvert,l,function(){
       //var str1='count='+l.length;
       //ajaxRequest(MainmForm.form,'imagesselected2_pre',[str1]);       
       getjpegdims(l,0,ongetteddims,MainmForm.form);              
      },0,lconvert.length);
    }
}


function handleFileSelectbackoffice(evt) {

    var files = evt.files; 
    var files = event.target.files;
     var  j = files.length;
    if(j==0)
      return;
    var l=new Array();
    for (var i=0;i<files.length;i++){
      var f=files[i];
      if((f.type=='image/jpeg')||(f.type=='image/png'))
        if(f.size> 0)
          l.push(f);
    }

//    var str1='count='+l.length;
    //ajaxRequest(frmbackoffice.form,'imagesselected2_pre',[str1]);       

    getjpegdims(l,0,ongetteddims,frmbackoffice.form);    
}


function Resetfilerefs(){
 imasrefs=new Array();
}

   
function ResetFilesGallery() {
 fileimas=new Array();
}

function BrowseFilesGallery() {
     var ima = document.getElementById('filefield2');
     ima.click();
};

function BrowseFileGallery() {
     var ima = document.getElementById('filefieldsingle');
     ima.click();
};

function BrowseDirectoriesGallery() {
     var ima = document.getElementById('filefield3');
     ima.click();
};



