<script>
"use strict";
var ADMIN_URL = "<?=get_admin_path()?>";
$('document').ready(function(){
	toggleUrlUploadField(false);
});

function toggleUrlUploadField(resetField=true){
	var uploadType = $('#upload_type').val();
	if(resetField){
		//$('#document_file').val('');
	}
	if(uploadType=="URL"){
		$('.input-group-btn').hide();
		$('#document_file').prop('readonly',false);
	}else{
		//$('#document_file').val($('#prev_document_file').val());
		$('.input-group-btn').show();
		$('#document_file').prop('readonly',true);		
	}	
	showHideDocumentViewBtn();	
}

function loadDocumentFile() {
	$('#form-upload').remove();	
	$('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input type="file" name="file" accept=".jpg,.png,.gif,.pdf" /><?=csrf_field()?></form>');
	$('#form-upload input[name=\'file\']').trigger('click');
	
	if (typeof timer != 'undefined') {
    	clearInterval(timer);
	}
	
	var timer = setInterval(function() {
		if ($('#form-upload input[name=\'file\']').val() != '') {
			clearInterval(timer);		
			
			$.ajax({
				url: '<?=get_admin_path("dealer/document_upload")?>',				
				type: 'post',		
				dataType: 'json',
				data: new FormData($('#form-upload')[0]),
				cache: false,
				contentType: false,
				processData: false,		
				beforeSend: function() {
					$('#btn_upload_document_file').html('<i class="fa fa-spinner fa-spin fa-1x fa-fw" style="color:white;"></i>');
				},
				complete: function() {
					$('#btn_upload_document_file').html('<i class="fa fa-upload" style="color:white;"></i>');
				},	
				success: function(json) {
					$('input[id=\'document_file\']').attr('value', json['filename']);
					$('#document_file_error').html(json['file_error']);
					showHideDocumentViewBtn();
				},							
			});
		}
	}, 500);
}

function viewDocumentFile(){
	var uploadType = $('#upload_type').val();
	var docFile = $('#document_file').val();
	if(uploadType=="URL"){
		window.open(docFile);
	}else{
		window.open('<?=base_url("public/download")?>/'+docFile);
	}	
}

function showHideDocumentViewBtn(){
	var docFile = $('#document_file').val();
	if(docFile.trim()!=''){
		$('#view_document_file_btn').show();
	}else{
		$('#view_document_file_btn').hide();
	}
}
</script>