
var upload_form_attachment = null;

//attachment
function onChangedSalesQuotationAttachmentUpload(obj, idx) {
    upload_form_attachment = obj;
}
function uploadSalesQuotationAttachment(idx) {
    if($('#txtSalesQuotationAttachment'+idx).val() == "") {
            Swal.fire('System Warning','You must select the file to upload.',"warning") ;
            return ;
    } else {
        var fn = $('#txtSalesQuotationAttachment'+idx).val() ;
        if (validateUploadFileExtAttachment(fn)) {
            var url  = "index.pzx?c=" + sales_quotation_url + "&t=" + C_ADD_UPLOAD_ATTACH_SALES_QUOT_DOC  + "&d=" + new Date().getTime() + "&salesquotation_id=" + $("#txtSalesQuotationID").val()+"&attach_type=1"+"&attach_idx="+idx+"&attach_field=txtSalesQuotationAttachment"  ;
            uploaded = false ;
            ajaxUpload(upload_form_attachment,url,onUploadSalesQuotationAttachmentEnd);
        }
    }
}
function uploadSalesQuotationAttachmentIssue(idx) {
    if($('#txtSalesQuotationAttachmentIssue'+idx).val() == "") {
            Swal.fire('System Warning','You must select the file to upload.',"warning") ;
            return ;
    } else {
        var fn = $('#txtSalesQuotationAttachmentIssue'+idx).val() ;
        if (validateUploadFileExtAttachment(fn)) {
            var url  = "index.pzx?c=" + sales_quotation_url + "&t=" + C_ADD_UPLOAD_ATTACH_SALES_QUOT_DOC  + "&d=" + new Date().getTime() + "&salesquotation_id=" + $("#txtSalesQuotationID").val()+"&attach_type=1"+"&attach_idx="+idx+"&attach_field=txtSalesQuotationAttachmentIssue" ;
            uploaded = false ;
            ajaxUpload(upload_form_attachment,url,onUploadSalesQuotationAttachmentEnd);
        }
    }
}
function onUploadSalesQuotationAttachmentEnd(resp) {
    console.log(resp);
    var msgArr      = resp.split("*");
    var status      = msgArr[0];
    var centreItems = msgArr[1];
    var error       = msgArr[2];

	var s = centreItems.split("|") ;
	if (status==C_OK) {
        $('#txtSalesQuotationAttachmentFilename'+s[2]).val(s[0]);
        $('#txtSalesQuotationAttachmentFilenameIssue'+s[2]).val(s[0]);
        var btnView = "<a title='View Attachment' style='color:green; margin-top: 5px;' href='javascript:' onclick='downloadSalesQuotationFile("+s[3]+", \""+s[1]+"\")'>"+s[0]+"</a>";
        $('#col_attachment'+s[2]).html('');
        $('#col_attachment'+s[2]).append(btnView);
        $('#col_attachment_issue'+s[2]).html('');
        $('#col_attachment_issue'+s[2]).append(btnView);

        var btnAction = "<button type='button' class='btn btn btn-icon btn-danger btn-sm btn-icon-md' onclick='removeSalesQuotationAttachment("+s[2]+");'><i class='fa fa-trash'></i></button>";
        $('#col_action'+s[2]).html('');
        $('#col_action'+s[2]).append(btnAction);
        $('#col_action_issue'+s[2]).html('');
        $('#col_action_issue'+s[2]).append(btnAction);
        
        return s[0];
	} else {
        Swal.fire("System Error", "Failed to upload attachment. " + error, "error");
        return "";
	}
}
function validateUploadFileExtAttachment(file) {
	var extArray = new Array(".png", ".jpg", ".jpeg", ".pdf", ".doc", ".docx", ".xls", ".xlsx"); 
	var validext = false;
	if (!file) 
		return;
   
	while (file.indexOf("\\") != -1)
		file = file.slice(file.indexOf("\\") + 1);
            
	var ext = file.slice(file.indexOf(".")).toLowerCase();
	for (var n = 0; n < extArray.length; n++) 
	{
		if (extArray[n] == ext) { validext = true; break; }
	}
	if (validext) {
		return true ;
	} else {
		Swal.fire("System Warning","You can only upload files in .png, .jpg, .jpeg, .doc, .docx, .xls, .xlsx format","warning") ;
		return false ;
	}
}
function removeSalesQuotationAttachment(docId) {
    Swal.fire({
        title: "Delete Attachment",
        text: "Are you sure you want to delete the attachment?",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "Yes",
        cancelButtonText: "No",
        confirmButtonColor: '#2754e6',
    }).then(function(result) {
        if (result.value) {
            var data  = { 
                "type"                  : C_DELETE_ATTACHMENT,
                 "salesquotation_id"    : $('#txtSalesQuotationID').val(), 
                 "doc_id"               : docId,
                 "attach_type"          : 1,
            };
            var url   = "index.pzx?c=" + sales_quotation_url + "&t=" + C_DELETE_ATTACHMENT  + "&d=" + new Date().getTime() ;
            callServer(url,"json",data,onResponseSalesQuotationAttachment,null) ;
        }
    });
}
function onResponseSalesQuotationAttachment(obj,resp) {
    if (resp.status != C_OK ) {
        Swal.fire('Error', resp.mesg, "error");
        return false;
    }

    if(resp.type == C_DELETE_ATTACHMENT) {
        // console.log(resp.data);
        var txtAttach = '<input type="file" class="form-control" id="txtSalesQuotationAttachment'+resp.data.doc_id+'" name="txtSalesQuotationAttachment'+resp.data.doc_id+'" onchange="onChangedSalesQuotationAttachmentUpload(this.form, '+resp.data.doc_id+');" />'+
        '<input type="hidden" class="form-control" id="txtSalesQuotationAttachmentFilename'+resp.data.doc_id+'"/>';
        $('#col_attachment'+resp.data.doc_id).html('');
        $('#col_attachment'+resp.data.doc_id).append(txtAttach);

        var txtAttach = '<input type="file" class="form-control" id="txtSalesQuotationAttachmentIssue'+resp.data.doc_id+'" name="txtSalesQuotationAttachmentIssue'+resp.data.doc_id+'" onchange="onChangedSalesQuotationAttachmentUpload(this.form, '+resp.data.doc_id+');" />'+
        '<input type="hidden" class="form-control" id="txtSalesQuotationAttachmentFilenameIssue'+resp.data.doc_id+'"/>';
        $('#col_attachment_issue'+resp.data.doc_id).html('');
        $('#col_attachment_issue'+resp.data.doc_id).append(txtAttach);

        var btnAction = "<button type='button' class='btn btn btn-icon btn-success btn-sm btn-icon-md' onclick='uploadSalesQuotationAttachment("+resp.data.doc_id+");'><i class='fa fa-upload'></i></button>";
        $('#col_action'+resp.data.doc_id).html('');
        $('#col_action'+resp.data.doc_id).append(btnAction);

        
        var btnAction = "<button type='button' class='btn btn btn-icon btn-success btn-sm btn-icon-md' onclick='uploadSalesQuotationAttachmentIssue("+resp.data.doc_id+");'><i class='fa fa-upload'></i></button>";
        $('#col_action_issue'+resp.data.doc_id).html('');
        $('#col_action_issue'+resp.data.doc_id).append(btnAction);
    } 
}