var normalchk;
$(document).ready(function () {
  //alert("heeeeeeeey");
  //button for click INPUT file
  //button id=selpic
  //INPUT file id=upload
  ////savercroper
  $(".inspic").click(function () {
    // alert($(this).prev().attr('id'));
    //alert("tttttttttttttttttttt"); 
    $(this).prev().trigger('click');
  });
  //after select file and change INPUT file data
  $('.upload').change(function (e) {
      var self=this;
  //check filereader and send image to crroper canvas
       if (typeof (FileReader) != "undefined") {
            if($("#normalimg").css("display")=="block"){
                  normalchk="N";
            }else{
                normalchk="";
            }

        if (self.files && self.files[0]) {
          var reader = new FileReader();
           reader.onload = function (e) {
            //check filereader and send image to crroper canvas
              //$("#croper_picpro").children().eq(1).attr("src", e.target.result );
              if($("#normalimg").css("display")=="block"){
                  $("#imageN").attr("src", e.target.result );
              }else{
                  if (cropper!=undefined){
                      //  cropme();
                      rescrop(e.target.result);
                  }else{
                      //alert("cropper not set!");
                      
                  }
              }
              //cropme();
              //send image to crroper canvas
              $("#upax"+normalchk).css("visibility","visible");
              $("#upaxOne"+normalchk).css("visibility","visible");
              
              $("#cancleax"+normalchk).css("visibility","visible");
              
              $(".inspic").each(function(){

                  $(this).css("visibility","hidden");
              });
// $("#savercroper").val($(self).attr("id"));
           };
           reader.readAsDataURL(self.files[0]);
         }else{
           //alert("عکس را انتخاب کنید");
           $("#upax"+normalchk).css("visibility","hidden");
           $("#upaxOne"+normalchk).css("visibility","hidden");
           $("#cancleax"+normalchk).css("visibility","hidden");
           $(".inspic"+normalchk).each(function(){

            $(this).css("visibility","visible");
          });
          $("#upax"+normalchk).css("cursor","default");
          $("#upaxOne"+normalchk).css("cursor","default");
          cropper.destroy();
         }
       } else {
         //alert("مرورگر شما از امکانات HTML5 پشتیبانی نمی نماید.");
       }
       //alert("oooooooookkkkkkkkkkkk");
  });

  $("#cancleax").click(function(){
        clearcancleax("");
    cropper.destroy();
    $("#croper_picpro img").attr("src","");
    $("#croper_picpro img").css("background-color","#fff");
  });
  $("#cancleaxN").click(function(){
        clearcancleax("N");
    cropper.destroy();
    $("#croper_picpro img").attr("src","");
    $("#croper_picpro img").css("background-color","#fff");
  });
  function clearcancleax(a){
      
    $("#cancleax"+a).css("visibility","hidden");
    $("#upaxOne"+a).css("visibility","hidden");
    $("#upax"+a).css("visibility","hidden");

    $(".inspic").each(function(){
      $(this).css("visibility","visible");
    });
  }


  $("#submitmelk").click(async function(){
       var reg=$(this).attr("data-regist");
       $(".upload").each(function(){

         if($(this).parent().css("background-image")!="none"){
           setBlob(this,"image/jpeg");
         }
       }).promise().done(function(){ajaxcall(reg);});
 });
 $("#upax").click(async function(){
   //alert("ffffffffffffffff");
      formdata=new FormData(frmAX);
      if($("#image").attr("src")){
        var imageBlob = await new Promise(resolve => cropper.getCroppedCanvas({width: width_out,height: height_out}).toBlob(resolve, 'image/jpeg'));
        var idish=$("#savercroper").val();
        $("#"+idish).parent().css("background-image", "url("+ cropper.getCroppedCanvas({width: width_out,height: height_out}).toDataURL('image/jpeg') + ")");
        $("#"+idish).next().next().next().text(cropper.getCroppedCanvas({width: width_out,height: height_out}).toDataURL('image/jpeg').replace(/^data:image\/(png|jpeg);base64,/, ""));
    }
  });
  $("#upaxOne").click(async function(){
    if($("#image").attr("src")){
      //alert("11111111111111");
      var imagedata =  cropper.getCroppedCanvas({width: width_out,height: height_out}).toDataURL('image/jpeg').replace(/^data:image\/(png|jpeg);base64,/, "") ;
      //alert(JSON.stringify(imagedata));
      await setBlobfullONE("upload","image/jpeg",imagedata);
      // let x=document.getElementById("frmAX").action;
      //  alert(x);
      var formdata=new FormData(frmAX);
      // if(formdata.has("ax")){
      //   //formdata.delete("ax");
      //   alert("yyyyyyyyyyyyyyyyyyyeeeeeeeeeeeesssssssssssssssssssss");
      // }
      // if(formdata.has("id")){
      //   //formdata.delete("ax");
      //   alert("yyyyyyyyyyyyyyyyyyyeeeeeeeeeeeesssssssssssssssssssss22222222222222222222222");
      // }
      //alert("formdata");
       //alert(JSON.stringify(formdata));
       var result=await jqajax(myurl_ins,formdata,"post","loader");
       show_imgcrop(result);
      }
      //alert("dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd");
});
async function ajaxcall(reg){
  //alert("All was done");
  var formdata=new FormData(frmAX);
//   if(reg==0){
//    var result=await jqajax("/melk/new/case/",formdata,"post","loader");
//  }else{
//    var result=await jqajax("/cp/melk/new/case",formdata,"post","loader");
//  }
  show_imgcrop(result);
}



    cropme(uprate,downrate);
    //alert("bbbbbbb");
});
function cropme(uprate,downrate){
 const image = document.getElementById('image');
  cropper = new Cropper(image, {
       dragMode: 'move',
       aspectRatio: uprate/downrate,
       viewMode: 3,
dragMode: 'move',
autoCropArea: 1,
restore: false,
modal: false,
guides: false,
highlight: false,
cropBoxMovable: false,
cropBoxResizable: false,
toggleDragModeOnDblclick: false,

 });
//alert("cropper");
}
      //.css("background-image", "url("+ e.target.result + ")");
//    mohem      var jpegFile64 = xx.replace(/^data:image\/(png|jpeg);base64,/, "");
//var jpegFile64 = xx.replace(/^url\(\"data:image\/(png|jpeg);base64,/, "");
      //var jpegFile64 = jpegFile64.replace(/\")/, "");

    //  mohemm 2  var ww= base64ToBlob(jpegFile64, 'image/jpeg');

function base64ToBlob(base64, mime){
    mime = mime || '';
    var sliceSize = 1024;
    var byteChars = window.atob(base64);
    var byteArrays = [];
    for (var offset = 0, len = byteChars.length; offset < len; offset += sliceSize) {
        var slice = byteChars.slice(offset, offset + sliceSize);
        var byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }
    return new Blob(byteArrays, {type: mime});
}
function setBlob(object,mime){
  let fileInputElement = document.getElementById($(object).attr("id"));
//alert("window.atob : "+window.atob($(object).next().next().next().text()));
   let data = base64ToBlob($(object).next().next().next().text(), mime);
   var filename=fileInputElement.files[0].name;
   let file = new File([data], filename,{type:mime, lastModified:new Date().getTime()});
   let container = new DataTransfer();
   container.items.add(file);
   fileInputElement.files = container.files;
}
function setBlobfull(object,mime,base64){
  let fileInputElement = document.getElementById($(object).attr("id"));
//alert("window.atob : "+window.atob($(object).next().next().next().text()));
   let data = base64ToBlob($(object).next().next().next().text(), mime);
   var filename=fileInputElement.files[0].name;
   let file = new File([data], filename,{type:mime, lastModified:new Date().getTime()});
   let container = new DataTransfer();
   container.items.add(file);
   fileInputElement.files = container.files;
}
function setBlobfullONE(id,mime,base64){
  let fileInputElement = document.getElementById(id);
//alert("window.atob : "+window.atob($(object).next().next().next().text()));
   let data = base64ToBlob(base64, mime);
   var filename=fileInputElement.files[0].name;
   let file = new File([data], filename,{type:mime, lastModified:new Date().getTime()});
   let container = new DataTransfer();
   container.items.add(file);
   fileInputElement.files = container.files;
   return true;
}