var canvasFontHeightCalculator = ( text, size, family ) => {
	$( 'body' ).append( '<canvas id="canvasFontHeightCalculator" style="display: none;"></canvas>' );

	let canvas = document.getElementById('canvasFontHeightCalculator');
	
	canvas.width = parseFloat( size.replace(/pt/g, '') ) * text.length;
	canvas.height = parseFloat( size.replace(/pt/g, '') ) * 2;

	let context = canvas.getContext( "2d" );
	context.font = size + ' ' + family;
	context.textAlign = 'center';
	context.textBaseline = 'middle';
	context.fillText( text, canvas.width / 2, canvas.height / 2);

	let sourceWidth = canvas.width;
	let sourceHeight = canvas.height;

	var data = context.getImageData(0, 0, sourceWidth, sourceHeight).data;
	var firstY = -1;
	var lastY = -1;

	for(var y = 0; y < sourceHeight; y++) {
		for(var x = 0; x < sourceWidth; x++) {
			var alpha = data[((sourceWidth * y) + x) * 4 + 3];

			if(alpha > 0) {
				firstY = y;
				break;
			}
		}
		if(firstY >= 0) {
			break;
		}

	}

	for(var y = sourceHeight; y > 0; y--) {
		for(var x = 0; x < sourceWidth; x++) {
			var alpha = data[((sourceWidth * y) + x) * 4 + 3];
			if(alpha > 0) {
				lastY = y;
				break;
			}
		}
		if(lastY >= 0) {
			break;
		}

	}

	$( '#canvasFontHeightCalculator' ).remove();

	let height = ( lastY - firstY );

	return height;
};

var isCustomActivity = false;

function closeProductCustomBlock() {
	isCustomActivity = false;
	$("#seconday-product-activity").hide();
	$("#main-product-activity").fadeIn(200);
}

function startCustomBlock2() {
	let valid = true;

	if( $( '.product-options .form-group.required' ).length > 0 ) {
		$( '.product-options .form-group.required' ).each( ( i, e ) => {
			let $e = $( e ).find( 'input, select' );

			if( $e.attr( 'type' ) == 'text' ) {
				if( $e.val() == "" ) valid = false;
			} else if( $e.attr( 'type' ) == 'radio' ) {
				if( $( 'input[name="' + $e.attr( 'name' ) + '"]' ).val() == '' ) valid = false;
			} else {
				if( $e.val() == "" ) valid = false;
			}
		} );
	}

	if( !valid ) {
		$( '#button-cart' ).trigger( 'click' ); 
		return false;
	}

	isCustomActivity = true;
	$("#main-product-activity").hide();
	$("#seconday-product-activity").fadeIn(200);

	$("body, html").animate({
		scrollTop: 0
	}, 400);

	refreshBoxStatus();

	setTimeout( () => {
		refreshBoxStatus();

		setTimeout( () => {
			$( '.custom-block-text' ).each( ( i, e ) => {
				$( e ).find( 'input[type="text"]' ).trigger( 'keyup' );
			} );
		}, 10 );
	}, 200 );
}

function startCustomBlock() {
	let valid = true;

	if( $( '.product-options .form-group.required' ).length > 0 ) {
		$( '.product-options .form-group.required' ).each( ( i, e ) => {
			let $e = $( e ).find( 'input, select' );

			if( $e.attr( 'type' ) == 'text' ) {
				if( $e.val() == "" ) valid = false;
			} else if( $e.attr( 'type' ) == 'radio' ) {
				if( $( 'input[name="' + $e.attr( 'name' ) + '"]' ).val() == '' ) valid = false;
			} else {
				if( $e.val() == "" ) valid = false;
			}
		} );
	}

	if( !valid ) {
		$( '#button-cart' ).trigger( 'click' ); 
		return false;
	}

	isCustomActivity = true;
	$("#main-product-activity").hide();
	$("#seconday-product-activity").fadeIn(200);

	let w = $( '.mask' ).data( 'w' ),
		h = $( '.mask' ).data( 'h' );

	w = parseInt( w );
	h = parseInt( h );

	nw = parseInt( $( '#custom-back-container' ).parent().width() );
	nh = parseInt( ( nw * h ) / w );

	let canvas = document.getElementById("c");

	canvas.width = nw;
	canvas.height = nh;

	previewImageCustomResize( () => {
		let valid = true;

		if( $( '.product-options .form-group.required' ).length > 0 ) {
			$( '.product-options .form-group.required' ).each( ( i, e ) => {
				let $e = $( e ).find( 'input, select' );

				if( $e.attr( 'type' ) == 'text' ) {
					if( $e.val() == "" ) valid = false;
				} else if( $e.attr( 'type' ) == 'radio' ) {
					if( $( 'input[name="' + $e.attr( 'name' ) + '"]' ).val() == '' ) valid = false;
				} else {
					if( $e.val() == "" ) valid = false;
				}
			} );
		}

		if( !valid ) {
			$( '#button-cart' ).trigger( 'click' ); 
			return false;
		}

		$("body, html").animate({
			scrollTop: 0
		}, 400);

		refreshBoxStatus();

		setTimeout( () => {
			refreshBoxStatus();

			setTimeout( () => {
				$( '.custom-block-text' ).each( ( i, e ) => {
					$( e ).find( 'input[type="text"]' ).trigger( 'keyup' );
				} );
			}, 10 );
		}, 200 );
	} );

	
}

var customBgRatio = 0;

function defaultPosition($cfb) {
	var $_box = $cfb;

	if($_box.data('type') == 1) {
		var $_textContainer =$_box.next('.tracker-image-container');
		var $_text = $_textContainer.find('.tracker-image');
		var $_tracker = $_textContainer.next('.tracker');
		var $_rotatable = $_tracker.find('.tracker-rotatable');

		var _fontSize = $_text.data('fs') * customBgRatio;

		$_text.css('font-size', _fontSize + 'pt');
		// $_text.css('line-height', _fontSize + 'pt');
		$_text.css('line-height','normal');
		$_text.css('transform', "translate( -50%, -50% )");
		$_text.css( 'transform-origin', 'bottom left' );

		$_textContainer.find( 'canvas' ).remove();
		$_textContainer.append( '<canvas id="' + $_box.attr( 'id' ) + '-canvas" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%) scale(' + customBgRatio + ');"></canvas>' );
		let canvas = document.getElementById( $_box.attr( 'id' ) + '-canvas' );
		canvas.width = $_textContainer.outerWidth() / customBgRatio;
		canvas.height = $_textContainer.outerHeight() / customBgRatio;
		let context = canvas.getContext( "2d" );
		context.font = $_text.data('fs') + 'pt ' + $_text.css( 'font-family' );
		context.textAlign = 'center';
		context.textBaseline = 'middle';
		context.fillStyle = $_text.css('color');
		context.fillText( $_text.text(), canvas.width / 2, ( ( canvas.height / 2 ) + parseInt( $_box.data( 'position-y' ) ) ));

		$_textContainer.css('width', ($_box.data('w') * customBgRatio));
		$_textContainer.css('height', ($_box.data('h') * customBgRatio));
		$_textContainer.css('transform', "rotate("+ $_box.data('r') + "deg)");
		$_textContainer.css('left', ($_box.data('l') * customBgRatio));
		$_textContainer.css('top', ($_box.data('t') * customBgRatio));

		$_tracker.css('width', ($_box.data('w') * customBgRatio));
		$_tracker.css('height', ($_box.data('h') * customBgRatio));
		$_tracker.css('left', ($_box.data('l') * customBgRatio));
		$_tracker.css('top', ($_box.data('t') * customBgRatio));
		$_tracker.css('transform', "rotate("+ $_box.data('r') + "deg)");

		$_box.css('width', ($_box.data('w') * customBgRatio));
		$_box.css('height', ($_box.data('h') * customBgRatio));
		$_box.css('transform', "rotate("+ $_box.data('r') + "deg)");
		$_box.css('left', ($_box.data('l') * customBgRatio));
		$_box.css('top', ($_box.data('t') * customBgRatio));
		// $_text.css('margin-top', ($_box.outerHeight() / 2)).css('line-height', '0');
	} else {
		var $_imageContainer =$_box.next('.tracker-image-container');
		var $_image = $_imageContainer.find('.tracker-image');
		var $_tracker = $_imageContainer.next('.tracker');
		var $_rotatable = $_tracker.find('.tracker-rotatable');

		$_box.css('width', ($_box.data('w') * customBgRatio));
		$_box.css('height', ($_box.data('h') * customBgRatio));
		$_box.css('transform', "rotate("+ $_box.data('r') + "deg)");
		$_box.css('left', ($_box.data('l') * customBgRatio));
		$_box.css('top', ($_box.data('t') * customBgRatio));
		$_box.css( 'border-radius', ( $_box.data( 'circle' ) == '1' ? '100%' : '0' ) );

		$_imageContainer.css('width', ($_box.data('w') * customBgRatio));
		$_imageContainer.css('height', ($_box.data('h') * customBgRatio));
		$_imageContainer.css('transform', "rotate("+ $_box.data('r') + "deg)");
		$_imageContainer.css('left', ($_box.data('l') * customBgRatio));
		$_imageContainer.css('top', ($_box.data('t') * customBgRatio));
		$_imageContainer.css( 'border-radius', ( $_box.data( 'circle' ) == '1' ? '100%' : '0' ) );

		$_image.css('width', ($_box.data('w') * customBgRatio));
		$_image.css('height', ($_box.data('h') * customBgRatio));
		// $_image.css('transform', "rotate("+ $_box.data('r') + "deg)");
		$_image.css('left', 0);
		$_image.css('top', 0);


		$_tracker.css('width', ($_box.data('w') * customBgRatio));
		$_tracker.css('height', ($_box.data('h') * customBgRatio));
		$_tracker.css('left', ($_box.data('l') * customBgRatio));
		$_tracker.css('top', ($_box.data('t') * customBgRatio));
		$_tracker.css('transform', "rotate("+ $_box.data('r') + "deg)");
		$_tracker.css( 'border-radius', ( $_box.data( 'circle' ) == '1' ? '100%' : '0' ) );
	}
}

function resetBoxesPosition() {
	var a = $("#custom-back-container");

	a.find('.custom-fixed-box').each(function(){
		defaultPosition($(this));

		// $(this).find('.tracker-image').attr('src', $(this).find('.tracker-image').data('original-image')).addClass('original');
	});

	// a.find('.tracker-image').each(function(){
	// 	$(this).attr('src', $(this).data('original-image')).addClass('original');
	// });
}

function refreshBoxStatus() {
	var a = $("#custom-back-container");

	// var _i = new Image();

	// _i.src = a.find('.mask').attr('src');
	// var b = _i.naturalWidth;
	// var b =  a.find('.mask')[0].naturalWidth;
	var b =  a.find('.mask').data( 'w' );

	var x = a.find('.mask').width();
	var y = b;

	var _r = x / y;

	customBgRatio = _r;

	a.find('.custom-fixed-box').each(function(){
		var $_box = $(this);
		var $_imageContainer = $(this).next('.tracker-image-container');
		var $_image = $_imageContainer.find('.tracker-image');
		var $_tracker = $_imageContainer.next('.tracker');
		var $_rotatable = $_tracker.find('.tracker-rotatable');

		defaultPosition($(this));

		$_rotatable.css('transform', "rotate("+ 0 + "deg)");
	});

	$( '.custom-block-text' ).each( ( i, e ) => {
		$( e ).find( 'input[type="text"]' ).trigger( 'keyup' );
	} );
}


function devcreatecanvas() {
	$("#custom-back-container").css('border', 'none');

	$("#test").html('');
	html2canvas(
		$("#custom-back-container"),
		{
			width: 5000,
			height: 5000,
			onrendered: function(canvas) {
				theCanvas = canvas;
				document.body.appendChild(canvas);
				// Canvas2Image.saveAsPNG(canvas);
				$("#test").append(canvas);
				// document.body.removeChild(canvas);
				$("#custom-back-container").css('border', '');
			}
		}
	);
}
var _zoomIncrement = 0.02;

var _zoomInterval = false;
var _zoomEl = false;

function forceUnlink(file){
	$.ajax({
		url: 'index.php?route=product/product/force_unlink',
		type: 'POST',
		data: {
			file: file,
		},
		success: function() { }
	});
}

$(document).ready(function(){
	$( '.select-family-form' ).on( 'change', ( e ) => {
		let $e = $( e.currentTarget );

		$( e.currentTarget ).css( 'font-family', $( e.currentTarget ).find( 'option:selected' ).css( 'font-family' ) );

		$( '#cfb-' + $e.data( 'id' ) ).prev( 'style' ).html('<style>@font-face {font-family: \'custom_font_' +  $e.data( 'id' ) + '\';src: url(\'' + $e.val() + '\');</style>');

		let fontFace = new FontFace(
			'custom_font_' +  $e.data( 'id' ),
			'url("' + $e.val() + '")'
		);
		document.fonts.add( fontFace );
		fontFace.load().then( () => {
			$( '.custom-block-text input[type="text"]' ).trigger( 'keyup' );
		} );

		$( '#custom-block-' + $e.data( 'id' ) ).find( '.cbm-text-font' ).val( $e.val() );

		
	} );

	$( '.selected-color-form-new' ).on( 'click', ( e ) => {
		$( e.currentTarget ).parent().toggleClass( 'active' );
	} );
	$( '.select-color-form-new' ).find( 'button' ).on( 'click', ( e ) => {
		let value = $( e.currentTarget ).val();

		$( e.currentTarget ).parent().prev().css( 'background', value );
		$( e.currentTarget ).parent().parent().removeClass( 'active' );

		$( '#custom-block-' + $( e.currentTarget ).parent().parent().data( 'id' ) ).find( '.cbm-text-color' ).val( value );
		$( '#cfb-text-' + $( e.currentTarget ).parent().parent().data( 'id' ) ).css( 'color', value );

		$( '[name="custom[' + $( e.currentTarget ).parent().parent().data( 'id' ) + '][text]"]' ).trigger( 'change' );
	} );



	$( '.selected-background-form-new' ).on( 'click', ( e ) => {
		$( e.currentTarget ).parent().toggleClass( 'active' );
	} );
	$( '.select-background-form-new' ).find( 'button' ).on( 'click', ( e ) => {
		let value = $( e.currentTarget ).val();

		$( e.currentTarget ).parent().prev().css( 'background', value );
		$( e.currentTarget ).parent().parent().removeClass( 'active' );

		$( '#custom-block-' + $( e.currentTarget ).parent().parent().data( 'id' ) ).find( '.cbm-text-background' ).val( value );
		$( '#cfb-' + $( e.currentTarget ).parent().parent().data( 'id' ) ).next().css( 'background', value );
	} );

	$( '.select-family-form' ).on( 'click', ( e ) => {
		$( e.currentTarget ).toggleClass( 'open' );

		if( $( e.currentTarget ).hasClass( 'open' ) ) {
			$( e.currentTarget ).find( '.select-family-form-dropdown button' ).each( ( i, f ) => {
				$( f ).html( '<span style="position: relative; display: inline-block; font-size: 1px; line-height: 1px;">' + text_custom_modal_font + '</span>' );

				let font_size = 1;

				while( $( f ).find( 'span' ).outerWidth() < $( f ).width() && $( f ).find( 'span' ).outerHeight() < $( f ).height() ) {
					font_size++;

					$( f ).find( 'span' ).css( {
						'font-size': font_size + 'px',
						'line-height': font_size + 'px',
					} );
				}
			} );
		}
	} );

	$( '.select-family-form button' ).on( 'click', ( e ) => {
		let $e = $( e.currentTarget );

		$e.parent().parent().css( 'font-family', $e.css( 'font-family' ) );
		$e.parent().parent().parent().parent().find( ' .cbm-text-font' ).val( $e.val() );
		$( '#cfb-text-' + $e.data( 'id' ) ).css(  'font-family', $e.css( 'font-family' )  );

		$( '[name="custom[' + $e.data( 'id' ) + '][text]"]' ).trigger( 'change' );
	} );

	$( document ).on( 'click', ( e ) => {
		let x = $( e.target ),
			found = false;

		$( '.select-color-form-new, .select-color-form-new *, .select-background-form-new, .select-background-form-new *, .select-family-form, .select-family-form *' ).each( ( i, f ) => {
			if( e.target == f ) {
				found = true;
			}
		} );

		if( found == false ) {
			$( '.select-color-form-new' ).removeClass( 'active' );
			$( '.select-background-form-new' ).removeClass( 'active' );
			$( '.select-family-form' ).removeClass( 'open' );
		}
	} );

	$( '#custom-text-modal-autocomplete' ).on( 'click', ( e ) => {
		if( $( e.currentTarget ).is( ':checked' ) ) {
			$( '.custom-block-text' ).each( ( i, e ) => {
				let $e = $( e ).find( 'input[type="text"]' );

				window.__ctmaFix = true;
				$e.val( $e.attr( 'placeholder' ) ).trigger( 'keyup' );
				setTimeout( () => {
					window.__ctmaFix = false;
				}, 100 );
			} );
		}
	} );

	$( '#ante-custom-modal-open' ).on( 'click', () => {
		let modal = new bootstrap.Modal(document.getElementById('custom-text-modal'), {
			keyboard: false
		});

		modal.show();
	} );

	$("#prep-customisation").prop('disabled', false);

	$(".custom-block-text").each(function() {
		$(this).find('input').on('change keyup', function() {
			if( !window.__ctmaFix && $( this ).attr( 'type' ) == 'text' && $( '#custom-text-modal-autocomplete' ).is( ':checked' ) ) {
				$( '#custom-text-modal-autocomplete' ).prop( 'checked', false );
			}

			var _text = $(this).val();
			_text = _text.substr( 0, parseInt( $( this ).attr( 'maxlength' ) ) );
			$( this ).val( _text );

			let _max = $( this ).attr( 'maxlength' ) - $( this ).val().length;

			$( this ).parent().find( 'span.input-group-max-length' ).html( _max );

			var _id = $(this).data('id'),
				validNo = 0,
				cbFontAllowBig = $(this).parent().parent().find('.cbm-text-font-allow-big').val(),
				cbFontAllowSmall = $(this).parent().parent().find('.cbm-text-font-allow-small').val(),
				cbFontAllowNumber = $(this).parent().parent().find('.cbm-text-font-allow-number').val(),
				cbFontAllowSign = $(this).parent().parent().find('.cbm-text-font-allow-sign').val();

			if(_text.length <= 0) {
				validNo++;
			}
			
			if( cbFontAllowBig == 0 && /[A-Z]/.test( _text ) ) {
				if( cbFontAllowSmall == 1 ) {
					_text = _text.toLowerCase();
				} else {
					_text = _text.replace( /[a-z]/gi, '' );
				}
			}

			if( cbFontAllowSmall == 0 && /[a-z]/.test( _text ) ) {
				if( cbFontAllowBig == 1 ) {
					_text = _text.toUpperCase();
				} else {
					_text = _text.replace( /[a-z]/gi, '' );
				}
			}

			if( cbFontAllowNumber == 0 && /[0-9]/.test( _text ) ) {
				_text = _text.replace(/[0-9]/g, '');
			}

			if( cbFontAllowSign == 0 && /[!-#%-*,-\/:;?@[-\]_{}\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4E\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65\u{10100}-\u{10102}\u{1039F}\u{103D0}\u{1056F}\u{10857}\u{1091F}\u{1093F}\u{10A50}-\u{10A58}\u{10A7F}\u{10AF0}-\u{10AF6}\u{10B39}-\u{10B3F}\u{10B99}-\u{10B9C}\u{10F55}-\u{10F59}\u{11047}-\u{1104D}\u{110BB}\u{110BC}\u{110BE}-\u{110C1}\u{11140}-\u{11143}\u{11174}\u{11175}\u{111C5}-\u{111C8}\u{111CD}\u{111DB}\u{111DD}-\u{111DF}\u{11238}-\u{1123D}\u{112A9}\u{1144B}-\u{1144F}\u{1145B}\u{1145D}\u{114C6}\u{115C1}-\u{115D7}\u{11641}-\u{11643}\u{11660}-\u{1166C}\u{1173C}-\u{1173E}\u{1183B}\u{11A3F}-\u{11A46}\u{11A9A}-\u{11A9C}\u{11A9E}-\u{11AA2}\u{11C41}-\u{11C45}\u{11C70}\u{11C71}\u{11EF7}\u{11EF8}\u{12470}-\u{12474}\u{16A6E}\u{16A6F}\u{16AF5}\u{16B37}-\u{16B3B}\u{16B44}\u{16E97}-\u{16E9A}\u{1BC9F}\u{1DA87}-\u{1DA8B}\u{1E95E}\u{1E95F}]/u.test( _text ) ) {
				_text = _text.replace(/[^a-zA-Z0-9]+/g, "");
			}

			if( $("#cfb-" + _id).data( 'required' ) == 0 ) {
				validNo = 0;
				if( _text.length == 0 ) {
					_text = $(this).attr('placeholder');
					// _text = '';
				}
			}

			if( validNo > 0 ) {
				_text = $(this).attr('placeholder');
				$("#cfb-" + _id).removeClass('checked');

				$( this ).parent().removeClass( 'valid' );
			} else {
				$("#cfb-" + _id).addClass('checked');

				$( this ).parent().addClass( 'valid' );
			}

			$("#cfb-" + _id).next('.tracker-text').find('.tracker-image').text(_text);

			let _tw = $("#cfb-" + _id).next('.tracker-text').find('.tracker-image').width(),
				_cw = $("#cfb-" + _id).next('.tracker-text').width(),
				_origfnt = parseFloat( $("#cfb-" + _id).next('.tracker-text').find('.tracker-image').attr( 'data-fs' ) ),
				_fnt = parseFloat( $( '#custom-block-' + _id ).find( '.cbm-text-size' ).val() );

			while( _tw > _cw ) {
				_fnt -= 1;
				$("#cfb-" + _id).next('.tracker-text').find('.tracker-image').css( 'font-size', ( _fnt * customBgRatio ) + 'pt' );		

				_tw = $("#cfb-" + _id).next('.tracker-text').find('.tracker-image').width();
			}

			while( _tw <= _cw && _fnt < _origfnt ) {
				_fnt += 1;
				$("#cfb-" + _id).next('.tracker-text').find('.tracker-image').css( 'font-size', ( _fnt * customBgRatio ) + 'pt' );

				_tw = $("#cfb-" + _id).next('.tracker-text').find('.tracker-image').width();

				if( _tw > _cw ) {
					_fnt -= 1;
					$("#cfb-" + _id).next('.tracker-text').find('.tracker-image').css( 'font-size', ( _fnt * customBgRatio ) + 'pt' );

					break;
				}
			}

			$("#cfb-" + _id).next('.tracker-text').find( 'canvas' ).remove();
			$("#cfb-" + _id).next('.tracker-text').append( '<canvas id="cfb-' + _id + '-canvas" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%) scale(' + customBgRatio + ');"></canvas>' );

			let _align = $( '#cfb-' + _id ).data( 'align' );

			let canvas = document.getElementById( 'cfb-' + _id + '-canvas' );
			canvas.width = $("#cfb-" + _id).next('.tracker-text').outerWidth()  / customBgRatio;
			canvas.height = $("#cfb-" + _id).next('.tracker-text').outerHeight()  / customBgRatio;

			let context = canvas.getContext( "2d" );
			context.font = _fnt + 'pt ' + $("#cfb-" + _id  + '-canvas').prev().css( 'font-family' );

			context.textAlign = 'center';
			let _alignPosition = canvas.width / 2;

			if( _align == 'left' && parseFloat( $( '#cfb-' + _id ).data( 'arc' ) ) == 0 ) {
				context.textAlign = 'left';
				_alignPosition = 0;
			} else if( _align == 'right' && parseFloat( $( '#cfb-' + _id ).data( 'arc' ) ) == 0 ) {
				context.textAlign = 'right';
				_alignPosition = canvas.width;
			}

			context.textBaseline = 'middle';
			context.fillStyle = $("#cfb-" + _id  + '-canvas').prev().css('color');

			if( parseFloat( $( '#cfb-' + _id ).data( 'arc' ) ) > 0 ) {
				drawTextAlongArc(context, $("#cfb-" + _id  + '-canvas').prev().text(), canvas.width / 2, (canvas.height / 2) + ( canvas.height / 4 ), canvas.width / 2 - ( canvas.width * 0.08 ), Math.PI * parseFloat( $( '#cfb-' + _id ).data( 'arc' ) ) );
			} else {
				context.fillText( 
					$("#cfb-" + _id  + '-canvas').prev().text(), 
					_alignPosition, 
					( ( canvas.height / 2 ) + parseInt( $("#cfb-" + _id).data( 'position-y' ) ) ), 
					$( '#cfb-text-' + _id ).outerWidth() / customBgRatio );
			}

			$( '#custom-block-' + _id ).find( '.cbm-text-size' ).val( _fnt );
		});
	});

	$(".custom-block-upload-image").each(function() {
        var $i = $(this).find('.cbm-image');

        var _rW = $i.find('img').width();
        var _rH = $i.find('img').height();

        var _nW = $i.find('img').data('width');
        var _nH = $i.find('img').data('height');

		var _ratioW = _nW / _rW;
        var _ratioH = _nH / _rH;

        $i.find('.dragable-block').css({
            width: _rW,
            height: _rH,
        }).draggable({
            containment: "parent",
            scroll: false,
			// start: function(e, u) {
			// 	// clearTimeout(zoomMoveDelayTimeout);
			// },
			// drag: function(e, u) {
			// 	// clearTimeout(zoomMoveDelayTimeout);
			// 	liveUpdateDragable
			// },
			drag: liveUpdateDragable,
			// stop: liveUpdateDragable
        });

		$i.find('.btn-original').on('click', function(){
			var _id = $(this).data('id');
 			var $y = $("#custom-block-" + _id + " .cbm-image");

			$y.find('img').attr('src', $(this).data('original'));
			$y.find('.cbm-image-input').val('');
			$y.find('input[type="file"]').val('');

			$y.removeClass('editable');

			$("#custom-block-" + _id).removeClass('done');
			$("#cfb-" + _id).removeClass('checked');

			var $_img = $("#cfb-image-" + _id);
			var $_imgContainer = $_img.parent();
			var $_tracker = $("#cfb-track-" + _id);

			$_img.css({
				width: '100%',
				height: 'auto',
			}).off('load').on('load',function(){
				var maxWidth = $('#custom-back-container').outerWidth();
				var maxHeight = $('#custom-back-container').outerHeight();

				var newWidth = $(this).width();

				if(newWidth > maxWidth) {
					$(this).css('width', maxWidth);
				}

				var newHeight = $(this).height();

				if(newHeight > maxHeight) {
					$(this).css('width', 'auto');
					$(this).css('height', maxHeight);
					$(this).css('width', $(this).outerWidth());
				}

				$_tracker.css('width', $(this).outerWidth());
				$_tracker.css('height', $(this).outerHeight());
				$(this).css({
					width: $_tracker.outerWidth(),
					height: $_tracker.outerHeight(),
				});

				$("#cbc-loader").fadeOut(200);
			});

			$_img.attr('src', $(this).data('original'));
        });

        $i.find('.btn-upload').on('click', function(){
            $(this).prev().trigger('click');
        });

        $i.find('input[type="file"]').off('change').on('change', function(){
			$("#cbc-loader").fadeIn(200);
            var _fD = new FormData();
            if($(this).prop('files').length > 0) {
                var _file = $(this).prop('files')[0];
                _fD.append('image', _file);
				_fD.append('id', $(this).data('id'));
				_fD.append('width', $(this).parent().find('img.img-responsive').data('width'));
				_fD.append('height', $(this).parent().find('img.img-responsive').data('height'));

				$("#custom-error").fadeOut(200);

				$("._ldR").remove();
				$('<div class="_ldR" style="position:absolute;background:rgba(255, 90, 0, 0.3);top:0;left:0;right:0;bottom:0;text-align:center;z-index:5;"><span style="position:absolute;top:50%;transform:translateY(-50%);left:0;right:0;text-align:center"><img src="catalog/view/theme/default/image/2.gif" style="width: 64px !important; height: auto !important;" /></span></div>').appendTo($(this).parent().find('.cbm-image-preview'));

				$("#custom-block-" + $(this).data('id')).find('.dragable-block').css({
					top: 0,
					left: 0,
				});

				$(this).parent().find('.btn-original, .btn-upload').prop('disabled', true);

                $.ajax({
                    url: 'index.php?route=product/product/custom_block_image_upload',
                    type: 'POST',
                    data: _fD,
					dataType: 'JSON',
                    processData: false,
                    contentType: false,
                    success: function(json) {
						var $b = $("#custom-block-" + json['product_custom_block_id'] + " .cbm-image");

						$b.find('.btn-original, .btn-upload').prop('disabled', false);

						if(json['success']) {

							// liveUpdateBlockImage($b);

							$b.addClass('editable');
							$b.find('.cbm-image-input').val(json['image_path']);
							// console.log($b.find('img.img-responsive'));
							$b.find('img.img-responsive').off('load').on( 'load', function(){
								var _rW = $(this)[0].getBoundingClientRect().width;
						        var _rH = $(this)[0].getBoundingClientRect().height;

								var _oW = $(this).prop('naturalWidth');
								var _oH = $(this).prop('naturalHeight');

						        var _nW = $(this).data('width');
						        var _nH = $(this).data('height');

								// var _tX = _rW * _nW / _oW;
								// var _tH = _rH * _nH / _oH;
								var _tX = _nW;
								var _tH = _nH;

								if(_tX > _rW) {
									ratio = _rW / _tX;
									_tX = _rW;
									_tH = _tH * ratio;
								}

								if(_tH > _rH) {
									ratio = _rH / _tH;
									_tX = _tX * ratio;
									_tH = _rH;
								}

								$(this).parent().find('.dragable-block').css({
						            width: _tX,
						            height: _tH,
						        });

								liveUpdateBlockImage($(this).parent().parent(), true);
								$(this).off('load');

								refreshBoxStatus();

								$("._ldR").remove();
								
								// $(this).parent().find('.dragable-block').trigger('dragstop');
							});

							$b.find('img').attr('src', json['image']);

							$b.find('.btn-rotate-left').on('click', function(){
								var $j = $(this).parent();
								var _i = $j.find('img');
								var _d = $j.find('.dragable-block');

								var _ = {
									deg: 90,
									image: $j.find('.cbm-image-input').val(),
									id: $j.find('input[type="file"]').data('id'),
								}
								$("._ldR").remove();
								$('<div class="_ldR" style="position:absolute;background:rgba(255, 90, 0, 0.3);top:0;left:0;right:0;bottom:0;text-align:center;z-index:5;"><span style="position:absolute;top:50%;transform:translateY(-50%);left:0;right:0;text-align:center"><img src="catalog/view/theme/default/image/2.gif" style="width: 64px !important; height: auto !important;" /></span></div>').appendTo($('#cfb-image-' + $j.find('input[type="file"]').data('id')).parent());

								$('<div class="_ldR" style="position:absolute;background:rgba(255, 90, 0, 0.3);top:0;left:0;right:0;bottom:0;text-align:center;z-index:5;"><span style="position:absolute;top:50%;transform:translateY(-50%);left:0;right:0;text-align:center"><img src="catalog/view/theme/default/image/2.gif" style="width: 64px !important; height: auto !important;" /></span></div>').appendTo($(this).parent().find('.cbm-image-preview'));
								ajaxAbort();
								$.ajax({
									url: 'index.php?route=product/product/custom_block_image_rotate',
									type: 'POST',
									data: _,
									dataType: 'JSON',
									success: function(json) {
										if(json['unlink']) forceUnlink(json['unlink']);

										var $_img = $("#cfb-image-" + json['product_custom_block_id']);
										var $_imgContainer = $_img.parent();
										var $_tracker = $("#cfb-track-" + json['product_custom_block_id']);

										$('[name="custom[' + json['product_custom_block_id'] + '][image]"]').val(json['image_path']);

										$("#custom-block-" + json['product_custom_block_id'] + " img.img-responsive").off('load').on('load', function(){
											let _dragle = $(this).next();

											if($(this).outerWidth() < _dragle.outerWidth()) {
												let _rat = $(this).outerWidth() / _dragle.outerWidth();

												_dragle.width($(this).outerWidth());
												_dragle.height(_dragle.outerHeight() * _rat);
											}

											if($(this).outerHeight() < _dragle.outerHeight()) {
												let _rat = $(this).outerHeight() / _dragle.outerHeight();

												_dragle.height($(this).outerHeight());
												_dragle.width(_dragle.outerWidth() * _rat);
											}

											_dragle.css('top', 0).css('left', 0);

											var $j = $(this).parent().parent();

											liveUpdateBlockImage($j);

											// clearTimeout(zoomMoveDelayTimeout);
											// zoomMoveDelayTimeout = setTimeout(function() {
											// 	liveUpdateBlockImage($j);
											// }, 600);

											$(this).off('load');
										});

										$("#custom-block-" + json['product_custom_block_id'] + " img.img-responsive").attr('src', json['image']);

										$_img.css({
											width: '100%',
											height: 'auto',
										}).off('load').on('load',function(){
											var maxWidth = $('#custom-back-container').outerWidth();
											var maxHeight = $('#custom-back-container').outerHeight();

											var newWidth = $(this).outerWidth();

											if(newWidth > maxWidth) {
												$(this).css('width', maxWidth);
											}

											var newHeight = $(this).outerHeight();

											if(newHeight > maxHeight) {
												$(this).css('width', 'auto');
												$(this).css('height', maxHeight);
												$(this).css('width', $(this).width());
											}

											// $_tracker.css('width', $(this).outerWidth());
											// $_tracker.css('height', $(this).outerHeight());
											// $(this).css({
											// 	width: $_tracker.outerWidth(),
											// 	height: $_tracker.outerHeight(),
											// });

											liveUpdateBlockImage($j);

											$(this).off('load');

											$("._ldR").remove();
										});

										$_img.attr('src', json['image']);
									}
								});
							});

							$b.find('.btn-rotate-right').on('click', function(){
								var $j = $(this).parent();
								var _i = $j.find('img');
								var _d = $j.find('.dragable-block');

								var _ = {
									deg: -90,
									image: $j.find('.cbm-image-input').val(),
									id: $j.find('input[type="file"]').data('id'),
								}
								$("._ldR").remove();
								$('<div class="_ldR" style="position:absolute;background:rgba(255, 90, 0, 0.3);top:0;left:0;right:0;bottom:0;text-align:center;z-index:5;"><span style="position:absolute;top:50%;transform:translateY(-50%);left:0;right:0;text-align:center"><img src="catalog/view/theme/default/image/2.gif" style="width: 64px !important; height: auto !important;" /></span></div>').appendTo($('#cfb-image-' + $j.find('input[type="file"]').data('id')).parent());

								$('<div class="_ldR" style="position:absolute;background:rgba(255, 90, 0, 0.3);top:0;left:0;right:0;bottom:0;text-align:center;z-index:5;"><span style="position:absolute;top:50%;transform:translateY(-50%);left:0;right:0;text-align:center"><img src="catalog/view/theme/default/image/2.gif" style="width: 64px !important; height: auto !important;" /></span></div>').appendTo($(this).parent().find('.cbm-image-preview'));
								ajaxAbort();
								$.ajax({
									url: 'index.php?route=product/product/custom_block_image_rotate',
									type: 'POST',
									data: _,
									dataType: 'JSON',
									success: function(json) {
										if(json['unlink']) forceUnlink(json['unlink']);

										var $_img = $("#cfb-image-" + json['product_custom_block_id']);
										var $_imgContainer = $_img.parent();
										var $_tracker = $("#cfb-track-" + json['product_custom_block_id']);

										$('[name="custom[' + json['product_custom_block_id'] + '][image]"]').val(json['image_path']);

										$("#custom-block-" + json['product_custom_block_id'] + " img.img-responsive").off('load').on('load',function(){
											let _dragle = $(this).next();

											if($(this).outerWidth() < _dragle.outerWidth()) {
												let _rat = $(this).outerWidth() / _dragle.outerWidth();

												_dragle.width($(this).outerWidth());
												_dragle.height(_dragle.outerHeight() * _rat);
											}

											if($(this).outerHeight() < _dragle.outerHeight()) {
												let _rat = $(this).outerHeight() / _dragle.outerHeight();

												_dragle.height($(this).outerHeight());
												_dragle.width(_dragle.outerWidth() * _rat);
											}

											_dragle.css('top', 0).css('left', 0);

											var $j = $(this).parent().parent();

											liveUpdateBlockImage($j);

											// clearTimeout(zoomMoveDelayTimeout);
											// zoomMoveDelayTimeout = setTimeout(function() {
											// 	liveUpdateBlockImage($j);
											// }, 600);

											$(this).off('load');
										});

										$("#custom-block-" + json['product_custom_block_id'] + " img.img-responsive").attr('src', json['image']);

										$_img.css({
											width: '100%',
											height: 'auto',
										}).off('load').on('load',function(){
											var maxWidth = $('#custom-back-container').outerWidth();
											var maxHeight = $('#custom-back-container').outerHeight();

											var newWidth = $(this).outerWidth();

											if(newWidth > maxWidth) {
												$(this).css('width', maxWidth);
											}

											var newHeight = $(this).outerHeight();

											if(newHeight > maxHeight) {
												$(this).css('width', 'auto');
												$(this).css('height', maxHeight);
												$(this).css('width', $(this).width());
											}

											// $_tracker.css('width', $(this).outerWidth());
											// $_tracker.css('height', $(this).outerHeight());
											// $(this).css({
											// 	width: $_tracker.outerWidth(),
											// 	height: $_tracker.outerHeight(),
											// });

											liveUpdateBlockImage($j);

											$(this).off('load');

											$("._ldR").remove();
										});

										$_img.attr('src', json['image']);
									}
								});
							});

							$b.find('.btn-zoom-in').off('mousedown mouseup mouseleave touchstart').on('mousedown touchstart', function() {
								_zoomEl = $(this);
								_zoomInterval = setInterval(function(){
									if( typeof _zoomEl === 'undefined' ) {
										clearInterval(_zoomInterval);
									}

									var $j = _zoomEl.parent();

									var _rW = $j.find('img')[0].getBoundingClientRect().width;
							        var _rH = $j.find('img')[0].getBoundingClientRect().height;

									var _oW = $j.find('img').prop('naturalWidth');
									var _oH = $j.find('img').prop('naturalHeight');

							        var _nW = $j.find('img').data('width');
							        var _nH = $j.find('img').data('height');

									var _tX = _rW * _nW / _oW;
									var _tH = _rH * _nH / _oH;

									var _kW = $j.find('.dragable-block')[0].getBoundingClientRect().width;
									var _kH = $j.find('.dragable-block')[0].getBoundingClientRect().height;

									var _percent = 0.005;

									var __newW = _kW * 1.01;
									var __newH = _kH * 1.01 ;

									if(__newW <= _rW && __newH <= _rH) {
										$j.find('.dragable-block').css({
											width: __newW,
											height: __newH,
											top: 0,
											left: 0,
										});
									}
								}, 10);

								$(this).on('mouseup mouseleave touchend touchcancel', function(){
									var $j = _zoomEl.parent();

									// clearTimeout(zoomMoveDelayTimeout);
									// zoomMoveDelayTimeout = setTimeout(function() {
									// 	liveUpdateBlockImage($j);
									// }, 600);

									liveUpdateBlockImage($j);

									clearInterval(_zoomInterval);
									$(this).off('mouseup mouseleave touchend touchcancel');
									_zoomEl = false;
								});
							});

							$b.find('.btn-zoom-out').off('mousedown mouseup mouseleave touchstart').on('mousedown touchstart', function() {
								_zoomEl = $(this);
								_zoomInterval = setInterval(function(){
									if( typeof _zoomEl === 'undefined' ) {
										clearInterval(_zoomInterval);
									}

									var $j = _zoomEl.parent();

									var _rW = $j.find('img')[0].getBoundingClientRect().width;
							        var _rH = $j.find('img')[0].getBoundingClientRect().height;

									var _oW = $j.find('img').prop('naturalWidth');
									var _oH = $j.find('img').prop('naturalHeight');

							        var _nW = $j.find('img').data('width');
							        var _nH = $j.find('img').data('height');

									var _tX = _rW * _nW / _oW;
									var _tH = _rH * _nH / _oH;

									var _kW = $j.find('.dragable-block')[0].getBoundingClientRect().width;
									var _kH = $j.find('.dragable-block')[0].getBoundingClientRect().height;

									var _percent = 0.005;

									var __newW = _kW * 0.99;
									var __newH = _kH * 0.99 ;

									// if(__newW >= _tX && __newH >= _tH) {
										$j.find('.dragable-block').css({
											width: __newW,
											height: __newH,
											top: 0,
											left: 0,
										});
									// }
								}, 10);

								$(this).on('mouseup mouseleave touchend touchcancel', function(){
									var $j = _zoomEl.parent();

									// clearTimeout(zoomMoveDelayTimeout);
									// zoomMoveDelayTimeout = setTimeout(function() {
									// 	liveUpdateBlockImage($j);
									// }, 600);

									liveUpdateBlockImage($j);

									clearInterval(_zoomInterval);
									$(this).off('mouseup mouseleave touchend touchcancel');
									_zoomEl = false;
								});
							});

							$b.find('.btn-save').off('click').on('click', function() {
								var $j = $(this).parent();
								var _i = $j.find('img');
								var _d = $j.find('.dragable-block');
								
								var _ = {
									x: _d.width() / _i.width(),
									y: _d.height() / _i.height(),
									top: _d.position().top / _i.height(),
									left: _d.position().left / _i.width(),
									image: $j.find('.cbm-image-input').val(),
									id: $j.find('input[type="file"]').data('id')
								}
								$("._ldR").remove();
								// _d.on('dragstop', function(event, ui) { return false; });
								$('<div class="_ldR" style="position:absolute;background:rgba(255, 90, 0, 0.3);top:0;left:0;right:0;bottom:0;text-align:center;z-index:5;"><span style="position:absolute;top:50%;transform:translateY(-50%);left:0;right:0;text-align:center"><img src="catalog/view/theme/default/image/2.gif" style="width: 64px !important; height: auto !important;" /></span></div>').appendTo($('#cfb-image-' + $j.find('input[type="file"]').data('id')).parent());

								$('<div class="_ldR" style="position:absolute;background:rgba(255, 90, 0, 0.3);top:0;left:0;right:0;bottom:0;text-align:center;z-index:5;"><span style="position:absolute;top:50%;transform:translateY(-50%);left:0;right:0;text-align:center"><img src="catalog/view/theme/default/image/2.gif" style="width: 64px !important; height: auto !important;" /></span></div>').appendTo($(this).parent().find('.cbm-image-preview'));
								ajaxAbort();
								$.ajax({
									url: 'index.php?route=product/product/custom_block_image_crop',
									type: 'POST',
									data: _,
									dataType: 'JSON',
									success: function(json) {
										if(json['unlink']) forceUnlink(json['unlink']);

										var $y = $("#custom-block-" + json['product_custom_block_id'] + " .cbm-image");

										$y.find('img').attr('src', json['image']);
										$y.find('.cbm-image-input').val(json['image_path']);
										$y.find('input[type="file"]').val('');

										$y.removeClass('editable');

										$("#custom-block-" + json['product_custom_block_id']).addClass('done');
										$("#cfb-" + json['product_custom_block_id']).addClass('checked');

										var $_img = $("#cfb-image-" + json['product_custom_block_id']);
										var $_imgContainer = $_img.parent();
										var $_tracker = $("#cfb-track-" + json['product_custom_block_id']);

										$_img.attr('style', "");

										$_img.css({
											width: '100%',
											height: 'auto',
										}).off('load').on('load',function(){
											let _rot = $_tracker.css( 'transform' );

											$_tracker.css( 'transform', 'rotate(0deg)' );
											$(this).parent().css( 'transform', 'rotate(0deg)' );

											var maxWidth = $('#custom-back-container')[0].getBoundingClientRect().width;
											var maxHeight = $('#custom-back-container')[0].getBoundingClientRect().height;

											var newWidth = $(this)[0].getBoundingClientRect().width;

											if(newWidth > maxWidth) {
												$(this).css('width', maxWidth);
											}

											var newHeight = $(this)[0].getBoundingClientRect().height;

											if(newHeight > maxHeight) {
												$(this).css('width', 'auto');
												$(this).css('height', maxHeight);
												$(this).css('width', $(this)[0].getBoundingClientRect().width);
											}

											$_tracker.css('width', $(this)[0].getBoundingClientRect().width);
											$_tracker.css('height', $(this)[0].getBoundingClientRect().height);
											$(this).css({
												width: $_tracker[0].getBoundingClientRect().width,
												height: $_tracker[0].getBoundingClientRect().height,
											});

											$("._ldR").remove();
											$("#cbc-loader").fadeOut(200);

											$_tracker.css( 'transform', _rot );
											$(this).parent().css( 'transform', _rot );

											$(this).off('load');

											refreshBoxStatus();
										});

										$_img.attr('src', json['image']);

										if( $( window ).width() < 576 ) {
											$( 'html' ).stop().animate( {
												scrollTop: $( '#custom-back-container' ).offset().top - 100,
											}, 400, 'linear' );
										}
									}
								});
							});


						}

						if(json['error']) {
							alert(json['error']);

							$("#cbc-loader").fadeOut(200);
							$("._ldR").remove();
						}
                    }
                });
            }
        });
    });

	setTimeout( () => {
		$("#prep-customisation").prop('disabled', false);
	}, 500 );
});

function previewCustomBlocks() {
	$("#custom-final-loader").fadeIn(200);

	var data = {
		product: $("input[name='product_id']").val(),
		quantity: $( '#input-quantity' ).val(),
		base: $("#custom-back-container .mask").attr('src'),
		images: [],
		text: [],
		backgrounds: [],
		postData: $('#product input[type=\'text\'], #product input[type=\'hidden\'], #product input[type=\'radio\']:checked, #product input[type=\'checkbox\']:checked, #product select, #product textarea, .product-options input[type=\'text\'], .product-options input[type=\'hidden\'], .product-options input[type=\'radio\']:checked, .product-options input[type=\'checkbox\']:checked, .product-options select, .product-options textarea').serializeObject(),
	};

	$(".custom-block-upload-image").each(function(){
		let _id = parseInt($(this).attr('id').replace(/custom-block-/g, ''));

		let path = $(this).find('.cbm-image-input').val();
		let preview = $('#cfb-image-' + _id).attr('src');

		if(path) {
			let x = $('#cfb-image-' + _id).parent().position().left / parseFloat($("#custom-back-container").width());
			let y = $('#cfb-image-' + _id).parent().position().top / parseFloat($("#custom-back-container").height());

			let width = parseFloat($('#cfb-image-' + _id).outerWidth()) / parseFloat($("#custom-back-container").width());
			let height = parseFloat($('#cfb-image-' + _id).outerWidth()) / parseFloat($("#custom-back-container").height());

			let owidth = parseFloat($('#cfb-image-' + _id)[0].getBoundingClientRect().width) / parseFloat($("#custom-back-container").width());
			let oheight = parseFloat($('#cfb-image-' + _id)[0].getBoundingClientRect().height) / parseFloat($("#custom-back-container").height());

			let rotation = $('#cfb-' + _id).data( 'r' );
			let circle = $('#cfb-' + _id).data( 'circle' );

			data.images.push({
				product_custom_block_id: _id,
				path: path,
				preview: preview,
				x: x,
				y: y,
				width: width,
				height: height,
				circle: circle,
				rotation: rotation,
				owidth: owidth,
				oheight: oheight,

				sort_order: $(this).find('.cbm-image-sort-order').val(),
			});
		}
	});

	$(".custom-block-text").each(function(){
		let _id = parseInt($(this).attr('id').replace(/custom-block-/g, ''));

		let _text = $(this).find('input[type="text"]').val();

		if(_text.length >= 0) {
			$('#cfb-text-' + _id).parent().prev().css( 'transform', 'rotate(0deg)' );

			let x = ($('#cfb-text-' + _id).parent().prev().position().left + ( $('#cfb-text-' + _id).parent().prev().outerWidth() / 2 ) ) / parseFloat($("#custom-back-container").width());
			let y = ($('#cfb-text-' + _id).parent().prev().position().top + ( $('#cfb-text-' + _id).parent().prev().outerHeight() / 2 ) ) / parseFloat($("#custom-back-container").height());

			$('#cfb-text-' + _id).parent().prev().css( 'transform', 'rotate(' + $('#cfb-text-' + _id).parent().prev().data( 'r' ) + 'deg)' );

			let dataUrl_x = $('#cfb-text-' + _id).parent().position().left / parseFloat($("#custom-back-container").width());
			let dataUrl_y = $('#cfb-text-' + _id).parent().position().top / parseFloat($("#custom-back-container").height());

			let font = $(this).find('.cbm-text-font').val();
			let size = $(this).find('.cbm-text-size').val();
			let color = $(this).find('.cbm-text-color').val();
			let r = $('#cfb-text-' + _id).parent().prev().data( 'r' );

			let box_x = $('#cfb-track-' + _id).outerWidth()  / parseFloat($("#custom-back-container").width());
			let box_y = $('#cfb-track-' + _id).outerHeight()  / parseFloat($("#custom-back-container").height());

			data.text.push({
				product_custom_block_id: _id,
				text: _text,
				x: x,
				y: y,
				font: font,
				size: size,
				color: color,
				r: r,

				box_x: box_x,
				box_y: box_y,

				dataUrl: $('#cfb-' + _id + '-canvas')[0].toDataURL(),
				dataUrl_x: dataUrl_x,
				dataUrl_y: dataUrl_y,

				sort_order: $(this).find('.cbm-sort-order').val(),
			});
		}
	});

	$(".custom-block-background").each(function(){
		let _id = parseInt($(this).attr('id').replace(/custom-block-/g, ''));

		let x = $('#cfb-image-' + _id).parent().position().left / parseFloat($("#custom-back-container").width());
		let y = $('#cfb-image-' + _id).parent().position().top / parseFloat($("#custom-back-container").height());

		let width = parseFloat($('#cfb-image-' + _id).outerWidth()) / parseFloat($("#custom-back-container").width());
		let height = parseFloat($('#cfb-image-' + _id).outerHeight()) / parseFloat($("#custom-back-container").height());

		let rotation = $('#cfb-' + _id).data( 'r' );
		let background_color = $(this).find('.cbm-text-background').val();

		data.backgrounds.push({
			product_custom_block_id: _id,
			background_color: background_color,
			x: x,
			y: y,
			width: width,
			height: height,
			r: rotation,

			sort_order: $(this).find('.cbm-sort-order').val(),
		});
	});

	// $( '.custom-fixed-box.active' ).next().next( '.tracker' ).trigger( 'click' );

	$.ajax({
		url: 'index.php?route=product/product/custom_image_render',
		type: 'POST',
		dataType: 'JSON',
		data: data,
		success: function(json) {
			if( typeof json['render_error'] === 'undefined' || json['render_error'] === true ) {
				$("#product input[name='custom_render']").val(json['path']);

				if( json.dev ) {
					$( '#dev-image' ).remove();
					$( '#custom-back-container' ).after( json.dev );
					$("#custom-final-loader").fadeOut(200);
					
					return false;
				}

				// -- TESTE
				// if( typeof dev !== 'undefined' && dev == 'test' ) {
				// 	$( '#test-render' ).remove();
				// 	$( '#custom-back-container' ).after( '<img src="' + json[ 'result2' ] + '" class="img-responsive" id="test-render" />' );
				// 	$("#custom-final-loader").fadeOut(200);
				// 	return false;
				// }
				// --

				// $("#button-cart").trigger('click'); // -- ALA BUN

				// #### copie din button-cart
				$("#custom-final-loader").fadeOut(200);
    
				$('.alert:not(#custom-error), .alert-dismissible, .text-danger').remove();
				$('.form-group').removeClass('has-error');

				if (json['error']) {
					if (json['error']['option']) {
						for (i in json['error']['option']) {
							var element = $('#input-option' + i.replace('_', '-'));

							if (element.parent().hasClass('input-group')) {
								element.parent().after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
							} else {
								element.after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
							}
						}
					}

					if (json['error']['custom_block'])
					{
						$("#custom-error").html( text_custom_error_incomplete ).fadeIn(200);
					}

					if (json['error']['recurring']) {
						$('select[name=\'recurring_id\']').after('<div class="text-danger">' + json['error']['recurring'] + '</div>');
					}

					// Highlight any found errors
					$('.text-danger').parent().addClass('has-error');
				}

				if (json['success']) {
					json.is_cart = true;
					addToCartNotification(json);

					// if( json['datalayer'] && typeof dataLayer !== 'undefined' ) dataLayer.push( json['datalayer'] );
					if( json['metapixel'] ) fbq( 'track', json['metapixel'].event, json['metapixel'].data );
					if( json['tiktok'] ) ttq.track( 'AddToCart', json['tiktok'] );

					$('#cart').load('index.php?route=common/cart/info&_t=' + ( Date.now() + '-' + Math.floor(Math.random() * 999) + 100 ) + ' #cart > *' );
				}
				// ####
			} else {
				$("#custom-final-loader").fadeOut(200);
				alert( text_custom_error_process );
			}



			// $("#custom-error").before('https://www.giftday.ro/image/' + json['path'] + '<br />');
			// $("#button-cart").trigger('click');
		}
	});
}

function liveUpdateBlockImage(element, reset_draggle) {
	var $j = element;
	var _i = $j.find('img');
	var _d = $j.find('.dragable-block');
	var _id = $j.find('input[type="file"]').data('id');
	var _t = $("#cfb-image-" + _id).parent();

	var _drag_pos = _d.position();
	var _dragLeft = _drag_pos.left;
	var _dragTop = _drag_pos.top;

	var _dragWidthPer = _d.width() / _i.width();
	var _dragHeightPer = _d.height() / _i.height();

	var nW = (1 * _t.width()) / _dragWidthPer;
	var nH = (1 * _t.height()) / _dragHeightPer;

	_dragLeft = (nW * _dragLeft) / _i.width();
	_dragTop = (nH * _dragTop) / _i.height();

	// console.log({
	// 	AoldW: _i.width(),
	// 	AoldH: _i.height(),
	// 	BoldW: $("#cfb-image-" + _id).width(),
	// 	BoldH: $("#cfb-image-" + _id).height(),
	// 	ColdW: _d.width(),
	// 	ColdH: _d.height(),
	// 	DoldW: _t.width(),
	// 	DoldH: _t.height(),
	// 	width: nW,
	// 	height: nH,
	// 	left: -_dragLeft,
	// 	top: -_dragTop,
	// });

	$("#cfb-image-" + _id).attr('src', _i.attr('src')).css({
		width: nW,
		height: nH,
		left: -_dragLeft,
		top: -_dragTop,
	});
}

function OLDliveUpdateBlockImage(element, reset_draggle) {
	var $j = element;
	var _i = $j.find('img');
	var _d = $j.find('.dragable-block');
	var _rd = (typeof reset_draggle !== 'undefined' ? reset_draggle : false);

	var _ = {
		x: _d.width() / _i.width(),
		y: _d.height() / _i.height(),
		top: _d.position().top / _i.height(),
		left: _d.position().left / _i.width(),
		image: $j.find('.cbm-image-input').val(),
		id: $j.find('input[type="file"]').data('id'),
		unlink: 'false',
		reset_draggle: _rd
	}

	if(_rd == "true") {
		$("#custom-block-" + _.id).find('.dragable-block').css({
			top: 0,
			left: 0,
		});
	}

	$("._ldR").remove();
	$('<div class="_ldR" style="position:absolute;background:rgba(255, 90, 0, 0.3);top:0;left:0;right:0;bottom:0;text-align:center;z-index:5;"><span style="position:absolute;top:50%;transform:translateY(-50%);left:0;right:0;text-align:center"><img src="catalog/view/theme/default/image/2.gif" style="width: 64px !important; height: auto !important;" /></span></div>').appendTo($('#cfb-image-' + $j.find('input[type="file"]').data('id')).parent());
	ajaxAbort();
	$.ajax({
		url: 'index.php?route=product/product/custom_block_image_crop',
		type: 'POST',
		data: _,
		dataType: 'JSON',
		success: function(json) {
			if(json['unlink']) forceUnlink(json['unlink']);

			var $_img = $("#cfb-image-" + json['product_custom_block_id']);
			var $_imgContainer = $_img.parent();
			var $_tracker = $("#cfb-track-" + json['product_custom_block_id']);

			$_img.css({
				width: '100%',
				height: 'auto',
			}).off('load').on('load',function(){
				var maxWidth = $('#custom-back-container')[0].getBoundingClientRect().width;
				var maxHeight = $('#custom-back-container')[0].getBoundingClientRect().height;

				var newWidth = $(this)[0].getBoundingClientRect().width;

				if(newWidth > maxWidth) {
					$(this).css('width', maxWidth);
				}

				var newHeight = $(this)[0].getBoundingClientRect().height;

				if(newHeight > maxHeight) {
					$(this).css('width', 'auto');
					$(this).css('height', maxHeight);
					// $(this).css('width', $(this).width());
				}
				$_tracker.css('width', $(this)[0].getBoundingClientRect().width);
				$_tracker.css('height', $(this)[0].getBoundingClientRect().height);
				$(this).css({
					width: $_tracker[0].getBoundingClientRect().width,
					height: $_tracker[0].getBoundingClientRect().height,
				});

				if(json['reset_draggle'] == "true") {
					$("#custom-block-" + json['product_custom_block_id']).find('.dragable-block').css({
						top: 0,
						left: 0,
					});
				}

				$("._ldR").remove();
			});

			$_img.attr('src', json['image']);
		}
	});
}

function liveUpdateDragable(event, ui) {
	var $j = $(this).parent().parent().parent();
	liveUpdateBlockImage($j);
	// clearTimeout(zoomMoveDelayTimeout);
	// zoomMoveDelayTimeout = setTimeout(function() {
	// 	liveUpdateBlockImage($j);
	// }, 600);
}

function switchCfbActive(i, e) {
	if( $( e ).data( 'type' ) == '1' || $( e ).data( 'type' ) == '2' ) {
		$('.custom-fixed-box').removeClass('active').removeClass('hidden');

		$(e).removeClass('hidden').addClass('active');
		
		$('.custom-block-upload-image').hide();
		$('.custom-block.custom-block-upload-image').hide();

		let modal = new bootstrap.Modal(document.getElementById('custom-text-modal'), {
			keyboard: false
		});

		modal.show();
	} else {
		$('.custom-block.custom-block-upload-image').hide();

		$('.custom-fixed-box').removeClass('active').addClass('hidden');
		$(e).removeClass('hidden').addClass('active');
		$('.custom-block-upload-image').hide();
		$('#custom-block-' + i).show();
	
		$("#cfb-track-" + i).on('click', function() {
			$('.custom-fixed-box').removeClass('active').removeClass('hidden');
			$('.custom-block-upload-image').hide();
			$('.custom-block.custom-block-upload-image').hide();
		});

		if( $( window ).width() < 576 ) {
			$( 'html' ).stop().animate( {
				scrollTop: $( '.custom-block-upload-image' ).parent().offset().top,
			}, 400, 'linear' );
		}
	}
}

var xhrQueue = [];
$(document).ajaxSend(function(event,jqxhr,settings){
    xhrQueue.push(jqxhr);
});
$(document).ajaxComplete(function(event,jqxhr,settings){
    var i;
    if((i=$.inArray(jqxhr,xhrQueue)) > -1){
        xhrQueue.splice(i,1);
    }
});
ajaxAbort = function (){
    var i=0;
    while(xhrQueue.length){
        xhrQueue[i++].abort();
    }
};

var zoomMoveDelayTimeout = false;

function drawTextAlongArc(context, str, centerX, centerY, radius, angle){
	context.save();
	context.translate(centerX, centerY);
	context.rotate(-1 * angle / 2);
	context.rotate(-1 * (angle / str.length) / 2);
	for (var n = 0; n < str.length; n++) {
		context.rotate(angle / str.length);
		context.save();
		context.translate(0, -1 * radius);
		var char = str[n];
		context.fillText(char, 0, 0);
		context.restore();
	}
	context.restore();
}

// $( window ).on( 'resize', () => {
// 	if( isCustomActivity ) {
// 		startCustomBlock();
// 	}
// } );
var previewImageCustomResizeCallback = () => {};
var previewImageCustomResize = ( callback ) => {
	previewImageCustomResizeCallback = callback;

	let product_id = parseInt( $( '[name="product_id"]' ).val() );

	$.ajax( {
		url: 'index.php?route=product/product/get_custom_background&product_id=' + product_id,
		type: 'GET',
		dataType: 'text',
		success: ( data ) => {
			let w = $( '.mask' ).data( 'w' ),
				h = $( '.mask' ).data( 'h' );

			w = parseInt( w );
			h = parseInt( h );

			nw = parseInt( $( '#custom-back-container' ).parent().width() );
			nh = parseInt( ( nw * h ) / w );

			if( nw > w ) {
				nw = w;
				nh = h;
			}

			nw *= 2;
			nh *= 2;

			let canvas = document.getElementById("c");

			canvas.width = nw;
			canvas.height = nh;

			var ctx = canvas.getContext("2d");

			var image = new Image();

			image.onload = function() {
				ctx.drawImage(image, 0, 0, w, h, 0, 0, nw, nh);

				previewImageCustomResizeCallback();
			};
			image.src = data;

			
		}
	} );
};

$( window ).resize( () => {
	refreshBoxStatus();
} );