var signFileUrl = '';

// smaple URL : http://stove99.tistory.com/207
/*var canvas = $("#signature-pad canvas")[0];
var sign = new SignaturePad(canvas, {
	minWidth: 1,
	maxWidth: 1,
	penColor: "rgb(0, 0, 0)"
});*/

function resizeCanvas(target){
	var canvas = target;

	//var ratio =  Math.max(window.devicePixelRatio || 1, 1);
	canvas.width = 130//window.innerWidth-25;
	canvas.height = 60;
	canvas.getContext("2d").scale(1, 1);
	//$("#drawCanvas").css("background","#8b9dc3");
	
	canvas.addEventListener("touchstart", function (e) {
		fn_setInputFocusOut();
	});
	
}
/* 
$(window).on("resize", function(){
	resizeCanvas();
});
*/
$("[data-action]").on("click", function(){
	if ( $(this).data("action")=="clear" ){
		sign.clear();
		//$("#drawCanvas").css("background","#8b9dc3");
	}
	else if ( $(this).data("action")=="save" ){
		if (sign.isEmpty()) {
			alert("서명해주세요");
		}
	}
});

function fn_loadSign(url, target){
	// 서명 가져오기
	var canvas1 = target;//$("#signature-pad canvas")[0];
	var context1 = canvas1.getContext("2d"); 
	var catImage = new Image();
	 
	catImage.src = url;
	
	catImage.addEventListener('load', eventCatImageLoaded, false);
	function eventCatImageLoaded(){
		context1.drawImage(catImage, 1, 1);
	}
}

function dataURItoBlob(dataURI){
    var byteString = atob(dataURI.split(',')[1]);
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++)
    {
        ia[i] = byteString.charCodeAt(i);
    }

    var bb = new Blob([ab], { "type": mimeString });
    return bb;
}

window.onpageshow = function(event) {
	if (event.persisted) {
		document.location.reload();
	}
};

function fn_signclear(){
	signFileUrl = '';
}

function fn_saveCanvas(type, target){
	// 서명
	var canvas = target; //$("#signature-pad canvas")[0];
	var context = canvas.getContext('2d');
	var dataUrl = canvas.toDataURL();
	var blob = dataURItoBlob(dataUrl);
	
	if(blob == null|| blob == ''|| blob == undefined||(sign.isEmpty()&&signFileUrl=='')){
		alert('서명 정보가 없습니다.');
		return;
	}
	
	var formData = new FormData();
	formData.append("type", type);
	formData.append("fileType", "I");
	formData.append("file", blob);
	
	$.ajax({
		url: "/webfile/uploadFile.do",
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		success : function(data){
			if(data.msgCode=='0'){
				signFileUrl = data.fileUrl;
				
				$("#modal_sign").modal("hide");
			}else{
				alert(data.msgDesc);
			}
		},
		beforeSend:function(){
			// 로딩열기
			fn_startLoadingView();
		},
		complete:function(){
			// 로딩닫기
			fn_stopLoadingView();	
		},
		error : function(xhr, status, error) {
			alert('에러가 발생하였습니다. 잠시후 다시 시도하십시오.');
		}
	});
}


/****************************************************************************
* 서명 팝업 열기
****************************************************************************/
function fn_modalOpenSign(){
	$("#modal_sign").modal("show");
}

/****************************************************************************
* 서명 여부 확인
****************************************************************************/
function fn_isCanvasBlank(canvas) {
  const context = canvas.getContext('2d');

  const pixelBuffer = new Uint32Array(
    context.getImageData(0, 0, canvas.width, canvas.height).data.buffer
  );

  return !pixelBuffer.some(color => color !== 0);
}