var cropper;
var current_crop_object;
var current_view_image;
var build_server = '';
$(document).ready(function (){
	if($('#build_server').length){
		build_server = $('#build_server').val();
	}
	$('#myfile').on('change', function (e) {
		e.preventDefault();
		var files = e.originalEvent.target.files;
		upload(files[0]);
        reset($(this));
    });
	$('.choose_file_button').click(function () {
		current_crop_object = $(this).parent().find('input[name="file_image_input"]');
        $('#popupUpload').modal('show');
    });
	$('input[type="hidden"][name="image[]"]').each(function( index ) {
		if($(this).val() != ""){
			try{
				var image = JSON.parse($(this).val());
				var avatar = $(this).parent().find('.choose_file_avatar') 
				avatar.css({
					'background' : 'url(' + build_server + image.icon_file + ') no-repeat center center/100% 100%',
					'-webkit-transform' : 'rotate(' + image.rotate + 'deg)',
					'-moz-transform' : 'rotate(' + image.rotate + 'deg)',
					'-ms-transform' : 'rotate(' + image.rotate + 'deg)',
					'-o-transform' : 'rotate(' + image.rotate + 'deg)',
					'transform' : 'rotate(' + image.rotate + 'deg)'
				});
			}catch(e){
			}
		}
	});
	
	$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
		var tab_id = e.target.getAttribute("href");
		switch(tab_id){
			case '#currentUploadTab' :
				loadRecentImage();
				break;
		}
	});
	$('input[type="text"].form-select-search').keyup(function(){
		var expr = utf8Convert($(this).val());

		console.log('input[type="radio"][name="' + $(this).data('for') + '"]');
		$('input[type="radio"][name="' + $(this).data('for') + '[radio]"]').each(function(){
			var string = utf8Convert($(this).parent().text());
			console.log(string);
			if(string.indexOf(expr) !== -1){
				$(this).parents().eq(3).removeClass('hidden');
			}else{
				$(this).parents().eq(3).addClass('hidden');
			}
		});
		if( $('input.form-select[type="radio"]:not(.loaded)').length
			&& !loading_icon
		){
			$('input.form-select[type="radio"]:not(.loaded)').removeClass('check_image');
			loadIcon();
		}
	});

	if($('.text-input-label').length > 0
		&& $('.text-suggestion').length > 0
	){
		var suggestion_link = $('<a>').attr({
			href : 'javascript:void(0)'
		}).html($('.text-suggestion-title').eq(0).html());

		// $('.text-input-label').append('(').append(suggestion_link).append(')');
		// $('#token').closest('li').before($('<li>').html(suggestion_link));
		$('.text-input-label').last().closest('li').after($('<li>').html(suggestion_link));

		var modal = $('<div>').attr({
			class : 'modal fade',
			role : 'dialog'
		});

		var modal_dialog = $('<div>').attr({
			class : 'modal-dialog',
			style : 'margin-top: 140px;'
		});

		var modal_content = $('<div>').attr({
			class : 'modal-content modal-style'
		});

		var modal_header = $('<div>').attr({
			class : 'modal-header'
		}).html('<button type="button" class="close maright" data-dismiss="modal"><img src="/images/icons/close.png" title="#" alt="image"></button><h4 class="spnb">Chọn gợi ý</h4>');

		var suggestion_content = $('#suggestion-list').clone();

		var modal_body = $('<div>').attr({
			class : 'modal-body'
		}).html(suggestion_content);

		var modal_footer = $('<div>').attr({
			class : 'modal-footer'
		}).html('<button type="button" class="btn btn-primary" data-dismiss="modal" title="Close">Close</button>');

		modal.append(modal_dialog);
		modal_dialog.append(modal_content);
		modal_content.append(modal_header);
		modal_content.append(modal_body);
		// modal_content.append(modal_footer);

		suggestion_content.find('a.text-suggestion-copy-btn').click(function(e){
			e.stopPropagation();
			alertify.set('notifier','position', 'bottom-center');
			if(copyTextToClipboard($(this).siblings('.text-suggestion-content').text().trim())){
				alertify.success('Đã sao chép gợi ý');
			}else{
				alertify.success('Lỗi khi sao chép. Vui lòng sap chép theo cách thủ công.');
			};
			if ($('.text-input-label').length == 1) {
				$('.text-input-label').siblings('.item-input').find('.form-control').val($(this).siblings('.text-suggestion-content').text().trim());
				$('.text-input-label').siblings('.item-input').find('.form-control').focus();
			}
			modal.modal('hide');
		});

		suggestion_content.find('.text-suggestion').click(function(e){
			e.stopPropagation();
			alertify.set('notifier','position', 'bottom-center');
			if(copyTextToClipboard($(this).find('.text-suggestion-content').text().trim())){
				alertify.success('Đã sao chép gợi ý');
			}else{
				alertify.success('Lỗi khi sao chép. Vui lòng sap chép theo cách thủ công.');
			};
			if ($('.text-input-label').length == 1) {
				$('.text-input-label').siblings('.item-input').find('.form-control').val($(this).find('.text-suggestion-content').text().trim());
				$('.text-input-label').siblings('.item-input').find('.form-control').focus();
			}
			modal.modal('hide');
		});
		
		suggestion_content.find('.border-suggestion').removeClass('border-suggestion');
		suggestion_link.click(function(){
			// var top = $('#suggestion-list').offset().top;
			// $('html, body').animate({
			// 	scrollTop: top
			// }, 500);
			modal.modal();
		})
	}

	$('a.text-suggestion-copy-btn').click(function(e){
		e.stopPropagation();
		alertify.set('notifier','position', 'bottom-center');
		if(copyTextToClipboard($(this).siblings('.text-suggestion-content').text().trim())){
			alertify.success('Đã copy gợi ý');
		}else{
			alertify.success('Lỗi khi copy. Bạn vui lòng thực hiện copy gợi ý thủ công.');
		};
		if ($('.text-input-label').length == 1) {
			$('.text-input-label').siblings('.item-input').find('.form-control').val($(this).siblings('.text-suggestion-content').text().trim());
			var top = $('.text-input-label').siblings('.item-input').find('.form-control').offset().top;
			$('html, body').animate({
				scrollTop: top - 100
			}, 500);
			setTimeout(function(){
				$('.text-input-label').siblings('.item-input').find('.form-control').focus();
			},500);
		}
	})
	$('.text-suggestion').click(function(e){
		e.stopPropagation();
		alertify.set('notifier','position', 'bottom-center');
		if(copyTextToClipboard($(this).find('.text-suggestion-content').text().trim())){
			alertify.success('Đã sao chép gợi ý');
		}else{
			alertify.success('Lỗi khi sao chép. Vui lòng sap chép theo cách thủ công.');
		};
		if ($('.text-input-label').length == 1) {
			$('.text-input-label').siblings('.item-input').find('.form-control').val($(this).find('.text-suggestion-content').text().trim());
			var top = $('.text-input-label').siblings('.item-input').find('.form-control').offset().top;
			$('html, body').animate({
				scrollTop: top - 100
			}, 500);
			setTimeout(function(){
				$('.text-input-label').siblings('.item-input').find('.form-control').focus();
			},500);
		}
		// modal.modal('hide');
	});
});
function upload(file){
	var form_data = new FormData();	
	form_data.append('file', file);
	var jqXHR = $.ajax({
		xhr : function() {
			var xhrobj = $.ajaxSettings.xhr();
			if (xhrobj.upload) {
				xhrobj.upload.addEventListener('progress', function(event) {
					var percent = 0;
					var position = event.loaded || event.position;
					var total = event.total;
					if (event.lengthComputable) {
						percent = Math.ceil(position / total * 100);
					}
					// Set progress
					// _this.setProgress(percent);
				}, false);
			}
			return xhrobj;
		},
		url : build_server + '/upload',
		xhrFields: {
			withCredentials: true
		},
		type : "POST",
		contentType : false,
		processData : false,
		cache : false,
		data : form_data,
		tryCount : 0,
		retryLimit : 2,
		beforeSend : function() {
			$('#loading-upload-image').removeClass('hidden');
			$('#uploadTab .btn-file').addClass('hidden');
		},
		complete : function() {
			$('#loading-upload-image').addClass('hidden');
			$('#uploadTab .btn-file').removeClass('hidden');
		},
		success : function(result) {
			try {
				if(result.success == true){					
					
					current_crop_object.parent().find('.choose_file_avatar').css({'background' : 'url(' + build_server + result.icon_file + ') no-repeat center center/100% 100%'});
					current_crop_object.data('current_image',result.uploaded_file);
					current_crop_object.data('current_image_thumb',result.thumb_file);
					current_crop_object.data('current_icon_file',result.icon_file);
					
					initCrop(build_server + result.thumb_file);
					
					$.ajax({
						url : '/effect/save-recent-image',
						method : 'POST',
						data : {
							'server': build_server,
							'icon'	: result.icon_file,
							'thumb'	: result.thumb_file,
							'image'	: result.uploaded_file,
						}
					})
					// var image_crop = new Image();
					// $('#cropModal').modal('show');
					// $('#loading-crop-image').removeClass('hidden');
					// $('#crop-image-wrapper').addClass('hidden');
					// $('#popupUpload').modal('hide');
					// image_crop.onload = function(){
						// $('#loading-crop-image').addClass('hidden');
						// $('#crop-image-wrapper').removeClass('hidden');
						
						// $('#cropbox').attr('src',result.thumb_file);

						// var image = document.getElementById('cropbox');
						// $("#cropbox").width(image_crop.width);
						// $("#cropbox").height(image_crop.height);						
						
						// if(image_crop.height > 2 * $(window).height() / 3){	
							// $("#cropbox").width(image_crop.width * 2 * $(window).height() / 3 / image_crop.height);
							// $("#cropbox").height(2 * $(window).height() / 3);
						// }
						 
						// if($("#cropbox").width() > $("#cropbox").parent().width()){
							// $("#cropbox").width('100%').height('auto');
						// }
		
						// if(current_crop_object.data('width') != 0 && current_crop_object.data('height') != 0){
							// var aspectRatio = current_crop_object.data('width') / current_crop_object.data('height');							
							// if(cropper == undefined){
								// cropper = new Cropper(image, {
									// aspectRatio: aspectRatio,
									// viewMode : 1,
									// autoCropArea : 1,
									// dragMode : 'move',
									// ready: function () {
										// saveCropImage();
									// }
								// });
							// }else{
								// cropper.replace(result.thumb_file);
								// cropper.setAspectRatio(aspectRatio);
								// saveCropImage();
							// }
						// }else{
							// if(cropper == undefined){
								// cropper = new Cropper(image, {
									// viewMode : 1,
									// autoCropArea : 1,
									// dragMode : 'move',
									// ready: function () {
										// saveCropImage();
									// }
								// });
							// }else{
								// cropper.replace(result.thumb_file);
								// cropper.setAspectRatio(NaN);
								// saveCropImage();
							// }
						// }
					// };
					
					// setTimeout(function(){
						// image_crop.src = result.thumb_file;
					// }, 500);
				}else{
					alert(result.info);
				}				
			}catch(err) {
				// console.log(err);
				alert('Error while uploading image. Please try with other image');
			}
		},
		error :  function(){
			this.tryCount++;
			if(this.tryCount<=this.retryLimit){
				$.ajax(this);
				return;
			} else {
				// clearCameraCache();
				myApp.alert('error','error');
			}
		}
	});
}
function initCrop(image_url){
	var image_crop = new Image();
	$('#cropModal').modal('show');
	$('#loading-crop-image').removeClass('hidden');
	$('#crop-image-wrapper').addClass('hidden');
	$('#popupUpload').modal('hide');
	
	image_crop.onload = function(){
		
		$('#loading-crop-image').addClass('hidden');
		$('#crop-image-wrapper').removeClass('hidden');
		
		$('#cropbox').attr('src',image_url);
		var image = document.getElementById('cropbox');	
		
		$("#cropbox").width(image_crop.width);
		$("#cropbox").height(image_crop.height);						
		
		if(image_crop.height > 2 * $(window).height() / 3){	
			$("#cropbox").width(image_crop.width * 2 * $(window).height() / 3 / image_crop.height);
			$("#cropbox").height(2 * $(window).height() / 3);
		}
		// console.log($("#image_crop").width());
		 
		if($("#cropbox").width() > $("#cropbox").parent().width()){
			$("#cropbox").width('100%').height('auto');
		}
		if($('#crop-image-wrapper').width() > $('#crop-image-wrapper').height()){
			var tmp_height = $("#crop-image-wrapper").width();
			if(tmp_height > 2 * $(window).height() / 3){
				var tmp_height = 2 * $(window).height() / 3;
			}
			if(tmp_height > 400){
				var tmp_height = 400;
			}
			$('#crop-image-wrapper').height(tmp_height);
		}

		var data_width = current_crop_object.attr('data-width');
		var data_height = current_crop_object.attr('data-height');
		
		var width_matches = data_width.match(/\[(.*)\](.*)\[\/(.*)\]/);
		var height_matches = data_height.match(/\[(.*)\](.*)\[\/(.*)\]/);

		if(width_matches){
			current_crop_object.data('width',$('input.form-select[type="radio"][data-optionlabel="' + width_matches[1] + '"]:checked').data(width_matches[2].toLowerCase()));
		}
		if(height_matches){
			current_crop_object.data('height',$('input.form-select[type="radio"][data-optionlabel="' + height_matches[1] + '"]:checked').data(height_matches[2].toLowerCase()));
		}
		if(current_crop_object.data('width') != 0 && current_crop_object.data('height') != 0){
			var aspectRatio = current_crop_object.data('width') / current_crop_object.data('height');							
			if(cropper == undefined){
				cropper = new Cropper(image, {
					aspectRatio: aspectRatio,
					viewMode : 2,
					autoCropArea : 1,
					dragMode : 'move',
					ready: function () {
						saveCropImage();
					}
				});
			}else{
				cropper.replace(image_url);
				cropper.setAspectRatio(aspectRatio);
				saveCropImage();
			}
		}else{
			if(cropper == undefined){
				cropper = new Cropper(image, {
					viewMode : 2,
					autoCropArea : 1,
					dragMode : 'move',
					ready: function () {
						saveCropImage();
					}
				});
			}else{
				cropper.replace(result.thumb_file);
				cropper.setAspectRatio(NaN);
				saveCropImage();
			}
		}
	}
	setTimeout(function(){
		image_crop.src = image_url;
	}, 500);
}
function saveCropImage(){
	if(current_crop_object != undefined && cropper != undefined){		
		crop_data = cropper.getData();
		image_data = cropper.getImageData();
		image_data = {
			'image' : current_crop_object.data('current_image'),
			'image_thumb' : current_crop_object.data('current_image_thumb'),
			'icon_file' : current_crop_object.data('current_icon_file'),
			'x' : crop_data.x,
			'y' : crop_data.y,
			'width' : crop_data.width,
			'height' : crop_data.height,
			'rotate' : crop_data.rotate,
			'scaleX' : crop_data.scaleX,
			'scaleY' : crop_data.scaleY,
			'thumb_width' : image_data.naturalWidth,
		};
		current_crop_object.parent().find('.choose_file_avatar').css(
			{
				'-webkit-transform' : 'rotate(' + crop_data.rotate + 'deg)',
				'-moz-transform' : 'rotate(' + crop_data.rotate + 'deg)',
				'-ms-transform' : 'rotate(' + crop_data.rotate + 'deg)',
				'-o-transform' : 'rotate(' + crop_data.rotate + 'deg)',
				'transform' : 'rotate(' + crop_data.rotate + 'deg)'
			}
		);
		$('#' + current_crop_object.attr('rel')).val(JSON.stringify(image_data));
	}
}
function saveCropFullImage(){
	if(current_crop_object != undefined && cropper != undefined){		
		crop_data = cropper.getData();
		image_data = cropper.getImageData();

		var aspectRatio = current_crop_object.data('width') / current_crop_object.data('height');

		var width,height;
		var x = y = 0;
		switch(image_data.rotate){
			case 90:
			case -90:
			case 270:
			case -270:
				width = image_data.naturalHeight
				height = image_data.naturalWidth
				break;
			default:
				width = image_data.naturalWidth
				height = image_data.naturalHeight
				break;
		}
		if(width / height > aspectRatio){
			y = (height - width / aspectRatio) / 2;
			height = width / aspectRatio;
		}else{
			x = (width - height * aspectRatio) / 2;
			width = height * aspectRatio;
		}
		image_data = {
			'image' : current_crop_object.data('current_image'),
			'image_thumb' : current_crop_object.data('current_image_thumb'),
			'icon_file' : current_crop_object.data('current_icon_file'),
			'x' : x,
			'y' : y,
			'width' : width,
			'height' : height,
			'rotate' : crop_data.rotate,
			'scaleX' : crop_data.scaleX,
			'scaleY' : crop_data.scaleY,
			'thumb_width' : image_data.naturalWidth,
		};
		current_crop_object.parent().find('.choose_file_avatar').css(
			{
				'-webkit-transform' : 'rotate(' + crop_data.rotate + 'deg)',
				'-moz-transform' : 'rotate(' + crop_data.rotate + 'deg)',
				'-ms-transform' : 'rotate(' + crop_data.rotate + 'deg)',
				'-o-transform' : 'rotate(' + crop_data.rotate + 'deg)',
				'transform' : 'rotate(' + crop_data.rotate + 'deg)'
			}
		);
		$('#' + current_crop_object.attr('rel')).val(JSON.stringify(image_data));
	}
}
//new
function changeImage(image,thumb,icon,server){
	if (current_crop_object != undefined) {
		current_crop_object.data('current_image',image);
		current_crop_object.data('current_image_thumb',thumb);
		current_crop_object.data('current_icon_file',icon);
		if(server != undefined){
			current_crop_object.parent().find('.choose_file_avatar').css({'background' : 'url(' + server + icon + ') no-repeat center center/100% 100%'});
			initCrop(server + thumb);
		}else{
			current_crop_object.parent().find('.choose_file_avatar').css({'background' : 'url(' + icon + ') no-repeat center center/100% 100%'});
			initCrop(thumb);
		}
	}
	if(server != undefined){
		var form_data = new FormData();	
		form_data.append('server',server);
		form_data.append('image',image);
		form_data.append('thumb',thumb);
		form_data.append('icon',icon);
		$.ajax({
			url : build_server + '/upload/download-image',
			xhrFields: {
				withCredentials: true
			},
			type : "POST",
			contentType : false,
			processData : false,
			cache : false,
			data : form_data
		})
	}
}
function loadRecentImage(){
	$.ajax({
		type: "GET",
		url: "/effect/recent-image",
		beforeSend: function(){
			$('#currentUploadTab').html('<div class = "text-center"><img src = "/images/icons/loader.gif"/></div>');
		},
		success : function(data){
			$("#currentUploadTab").html(data);
		},
		error : function (data){
			$("#currentUploadTab").html("<div class = 'text-center' style = 'margin-top: 140px;'>You havent got any image uploaded</div>");
		}
	});
}
function loadFacebookImage(){
	$.ajax({
		type: "GET",
		url: "/picture/facebook-album",
		beforeSend: function(){
			$("#facebook_picture_warper").html("<div class = 'text-center' style = 'margin-top: 140px;'><span class = 'loading_data'>Waiting while image loading</span></div>");
		},
		success : function(data){
			$("#facebook_picture_warper").html(data);
		},
		error : function (data){
			$("#facebook_picture_warper").html("<div class = 'text-center' style = 'margin-top: 140px;'>Error when loading image from facebook</div>");
		}
	});
}
function getFacebookImage(image){
	$.ajax({
		type: "GET",
		url: "/picture/get-facebook-image",
		data: {
			image: image
		},
		beforeSend: function(){
			$("#facebook_picture_warper").html("<div class = 'text-center' style = 'margin-top: 140px;'><span class = 'loading_data'>Waiting while image loading</span></div>");
		},
		success : function(data){
			
			var result = jQuery.parseJSON(data);
			if(result.success == true){
				$.fancybox.close();
				changeImage(result.image);
				initCrop(result.image,[0,0,10000,10000]);
			}else{
				$("#facebook_picture_warper").html("<div class = 'text-center' style = 'margin-top: 140px;'>Error when loading image from facebook</div>");
			}
		},
		error : function (data){
			$("#facebook_picture_warper").html("<div class = 'text-center' style = 'margin-top: 140px;'>Error when loading image from facebook</div>");
		}
	});
//	
}
function removeRecentImageList(image){
	$.ajax({
		type: "POST",
		url: "/effect/remove-recent-image",
		retryLimit : 2,
		data: {
		},
		beforeSend: function(){
		},
		success : function(data){
			loadRecentImage();
		},
		error : function (data){
			this.retryLimit--;
			if (this.retryLimit) {
				$.ajax(this);
				return;
			}
			$('#currentUploadTab').html('<div class = "text-center">Some Error Occurred while trying delete history.</div>');
            return;
		}
	});
//	
}
function rotateCropper(degree){
	if(cropper != undefined){
		cropper.clear();
		cropper.rotate(degree);
		cropper.zoom(-0.1);
		cropper.zoom(-0.1);
		cropper.zoom(-0.1);
		cropper.zoom(-0.1);
		cropper.zoom(-0.1);
		cropper.zoom(-0.1);
		cropper.zoom(-0.1);
		cropper.zoom(-0.1);
		cropper.zoom(-0.1);
		cropper.zoom(-0.1);
		cropper.zoom(-0.1);
		cropper.crop();
	}
}
window.reset = function (e) {
    e.wrap('<form>').closest('form').get(0).reset();
    e.unwrap();
};
function utf8Convert(str){
	str = str.toLowerCase();
	str = str.replace(/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/g, 'a');
	str = str.replace(/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/g, 'e');
	str = str.replace(/(ì|í|ị|ỉ|ĩ)/g, 'i');
	str = str.replace(/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/g, 'o');
	str = str.replace(/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/g, 'u');
	str = str.replace(/(ỳ|ý|ỵ|ỷ|ỹ)/g, 'y');
	str = str.replace(/(đ)/g, 'd');
		
	str = str.replace(/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/g, 'a');
	str = str.replace(/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/g, 'e');
	str = str.replace(/(Ì|Í|Ị|Ỉ|Ĩ)/g, 'i');
	str = str.replace(/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/g, 'o');
	str = str.replace(/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/g, 'u');
	str = str.replace(/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/g, 'y');
	str = str.replace(/(Đ)/g, 'd');
		
	// str = str.replace(/[^A-Za-z0-9]/g, '-');
	// str = str.replace(/-+/g, '-');
	return str;
}
function copyTextToClipboard(text) {
	var textArea = document.createElement("textarea");
	
	//
	// *** This styling is an extra step which is likely not required. ***
	//
	// Why is it here? To ensure:
	// 1. the element is able to have focus and selection.
	// 2. if element was to flash render it has minimal visual impact.
	// 3. less flakyness with selection and copying which **might** occur if
	//    the textarea element is not visible.
	//
	// The likelihood is the element won't even render, not even a flash,
	// so some of these are just precautions. However in IE the element
	// is visible whilst the popup box asking the user for permission for
	// the web page to copy to the clipboard.
	//
	// Place in top-left corner of screen regardless of scroll position.
	textArea.style.position = 'fixed';
	textArea.style.top = 0;
	textArea.style.left = 0;
	
	// Ensure it has a small width and height. Setting to 1px / 1em
	// doesn't work as this gives a negative w/h on some browsers.
	
	textArea.style.width = '2em';
	textArea.style.height = '2em';
	
	// We don't need padding, reducing the size if it does flash render.
	
	textArea.style.padding = 0;
	
	// Clean up any borders.
	
	textArea.style.border = 'none';
	textArea.style.outline = 'none';
	textArea.style.boxShadow = 'none';
	
	// Avoid flash of white box if rendered for any reason.
	
	textArea.style.background = 'transparent';
	textArea.value = text;
	document.body.appendChild(textArea);
	
	textArea.select();
	
	try {
		var successful = document.execCommand('copy');
		var msg = successful ? 'successful' : 'unsuccessful';
	} catch (err) {
		console.log('Oops, unable to copy');
		return false;
	}
	document.body.removeChild(textArea);
	return true;
}