var cover_document = null;
var cover_filename = "";
var temp_filename = "";
var cover_lines_used = 0;

function showCoverPage(coverpage) {
    switch(coverpage) {
        case 1:
            $('#sales-quotation-cover-rows-1').show();
            $('#sales-quotation-cover-rows-2').hide();
            $('#sales-quotation-cover-rows-3').hide();
        break;
        case 2:
            $('#sales-quotation-cover-rows-1').hide();
            $('#sales-quotation-cover-rows-2').show();
            $('#sales-quotation-cover-rows-3').hide();
        break;
        case 3:
            $('#sales-quotation-cover-rows-1').hide();
            $('#sales-quotation-cover-rows-2').hide();
            $('#sales-quotation-cover-rows-3').show();
        break;
        default:
            $('#sales-quotation-cover-rows-1').show();
            $('#sales-quotation-cover-rows-2').hide();
            $('#sales-quotation-cover-rows-3').hide();
            break;
    }
}

function onInputCoverDescription(obj, idx) {    
    var max_lines = $('#maximum_lines'+idx).text();
    // var lines_used = $('#lines_used'+idx);

    var span = document.createElement("span");

    $(obj).keydown(function(e) {        
        newLines = $(this).val().split("\n").length;
        // lines_used.text(newLines);
        span.innerHTML = $(this).val();
        
        if(e.keyCode == 13 && newLines >= max_lines) {
            // lines_used.css('color', 'red');
            Swal.fire("System Warning", "The text has reached the maximum lines allowed.", "warning");
            return false;
        }
        // else {
        //     lines_used.css('color', '');
        // }
    });
}

function onChangedSalesQuotationCoverUpload(obj, idx) {
    upload_form_cover = obj;
}

function onChangedSelectionCoverPage(obj, idx) {    
    if($(obj).val() != undefined) {
        var cover_page = $(obj).val().split("|");
        $('#txtCoverPageId'+cover_page[0]).val(cover_page[0]);
        $('#txtCoverPageLine'+cover_page[0]).val(cover_page[1]);
        $('#maximum_lines'+cover_page[0]).text(cover_page[1]);
        $('#txtCoverDesc'+cover_page[0]).attr('rows', cover_page[1]);
        // $('#txtCoverDesc'+cover_page[0]).css('resize', 'none');
        $('#cmbCoverPage'+cover_page[0]).prop('selectedIndex', parseInt(cover_page[0])-1);
        showCoverPage(parseInt(cover_page[0]));
    }
}
function showCoverTemplate(obj){
    sales_cover_idx = obj.length == 0 ? 1:obj.length;
    var id_max_q = [1000];        
    var counter = 0;

    for(var i=0;i<obj.length;i++) {
        counter++;
        cover_id = obj[i].cover_id;
        cover_line_no = obj[i].cover_line_no;
        cover_page = obj[i].cover_page;
        cover_page_line = obj[i].cover_page_line;
        cover_document = obj[i].cover_document;
        cover_desc = obj[i].cover_desc;

        id_max_q.push(cover_id);

        $('#txtCoverId'+counter).val(cover_id);
        $('#txtCoverLineNo'+counter).val(cover_line_no);
        $('#txtCoverDocument'+counter).val();
        $('#txtCoverFilename'+counter).val(cover_document);
        $('#txtCoverPageId'+counter).val(cover_page);
        $('#txtCoverPageLine'+counter).val(cover_page_line);
        $('#txtCoverDesc'+counter).val(cover_desc);
        sales_cover_idx++;
    }

    onChangedSelectionCoverPage($('#cmbCoverPage1'), 0);
}
function showSalesQuotationCoverData(obj){
    sales_cover_idx = obj.length == 0 ? 1:obj.length;
    var id_max_q = [1000];        
    var counter = 0;
    for(var i=0;i<obj.length;i++) {
        counter++;
        cover_id = obj[i].cover_id;
        cover_line_no = obj[i].cover_line_no;
        cover_page = obj[i].cover_page;
        cover_page_line = obj[i].cover_page_line;
        cover_document = obj[i].cover_document;
        cover_desc = obj[i].cover_desc;

        id_max_q.push(cover_id);

        $('#txtCoverId'+counter).val(cover_id);
        $('#txtCoverLineNo'+counter).val(cover_line_no);
        $('#txtCoverDocument'+counter).val();
        $('#txtCoverFilename'+counter).val(cover_document);
        $('#txtCoverPageId'+counter).val(cover_page);
        $('#txtCoverPageLine'+counter).val(cover_page_line);
        $('#txtCoverDesc'+counter).val(cover_desc);

        onChangedSelectionCoverPage($('#cmbCoverPage'+counter), counter);
        
        // switch(cover_page) {
        //     case "1":
        //         $('#cmbCoverPage'+sales_cover_idx).prop('selectedIndex', 0);
        //         break;
        //     case "2":
        //         $('#cmbCoverPage'+sales_cover_idx).prop('selectedIndex', 1);
        //         break;
        //     case "3":
        //         $('#cmbCoverPage'+sales_cover_idx).prop('selectedIndex', 2);
        //         break;
        //     default:
        //         $('#cmbCoverPage'+sales_cover_idx).prop('selectedIndex', 0);
        //         break;
        // }

        sales_cover_idx++;
    }   
}

function getSalesQuotationCover(){
    var arrays = [];
    var data = {};
    $('#sales-quotation-cover-list tr').each(function() {
        var idx = $(this).attr('id');
        idx = idx.substring(idx.lastIndexOf('-')+1);
        // if($('#txtCoverDesc'+idx).val() != '') {
            data = { 
					"cover_id"          : $('#txtCoverId'+idx).val(),
					"cover_document"    : $('#txtCoverDocument'+idx).val(),
					"temp_filename"     : $('#txtCoverFilename'+idx).val(),
					"cover_page"        : $('#txtCoverPageId'+idx).val(),
					"cover_page_line"   : $('#txtCoverPageLine'+idx).val(),
					"cover_desc"        : $('#txtCoverDesc'+idx).val(),
                };
            
            arrays.push(data);
        // }
        // else {
        //     Swal.fire("Warning", "Description cannot be blank!", "warning");
        //     return;
        // }
    });
    // console.log(JSON.stringify(arrays));
    return JSON.stringify(arrays) ;
}

function onUploadSalesQuotationCoverPageEnd(resp) {
	var s = resp.split("|") ;
	if (s[0]==C_OK) {
		temp_filename = s[2];
        cover_document = s[3];
        // console.log(temp_filename);
        $('#txtCoverDocument'+s[4]).val(cover_document);
        $('#txtCoverFilename'+s[4]).val(temp_filename);
        return temp_filename;
	} else {
        Swal.fire("System Error", "Failed to upload file. " + s[1], "error");
        return "";
	}
}

function uploadSalesQuotationCoverPage(idx) {
    if($('#txtCoverUpload'+idx).val() == "") {
            Swal.fire('System Warning','You must select the file to upload.',"warning") ;
            return ;
    } else {
        var fn = $('#txtCoverUpload'+idx).val() ;
        if (validateUploadFileExt(fn)) {
            var url = "upload.pzx?t=f&n=txtCoverUpload"+idx+"&idx="+idx+"&d=" + new Date().getTime();
            uploaded = false ;
            ajaxUpload(upload_form_cover,url,onUploadSalesQuotationCoverPageEnd);
        }
    }
}

function validateUploadFileExt(file) {
	var extArray = new Array(".png", ".jpg", ".jpeg"); 
	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 format","warning") ;
		return false ;
	}
}

function clearCover() {
    // $('#sales-quotation-cover-list').html('');
    $('#sales-quotation-cover-list tr').each(function() {
        var idx = $(this).attr('id');
        idx = idx.substring(idx.lastIndexOf('-')+1);
        $('#txtCoverId'+idx).val('');
        $('#txtCoverLineNo'+idx).val('');
        $('#txtCoverDocument'+idx).val('');
        $('#txtCoverFilename'+idx).val('');
        $('#txtCoverPageId'+idx).val('');
        $('#txtCoverPageLine'+idx).val('');
        $('#txtCoverDesc'+idx).val('');
    });
}

function popupSaveTemplateCover() {
    var strBtn = "<button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\">Cancel</button>" +
                     "<button onclick=\"saveTemplateCover();\" class=\"btn btn-primary ml-2\" > Save </button>";
    $('#modalSaveCoverTemplateConfirmationButton').html(strBtn);
}

function saveTemplateCover() {
    var data = { 
            "name"                  : $('#CoverTemplateName').val(),
            "data"                  : getSalesQuotationCover(),
            "option_template"       : $('#txtChkCoverTempOption').val(),
            "template_id"           : $('#CoverTemplateList').val(),
            // "new_name"              : $('#coverTemplateNewName').val(),
            "type"                  : "C_SAVE_COVER_TEMPLATE"
            };

    var test = ($('#chkCoverTempOption').is(':checked') ? '1' : '0');

    var url = "index.pzx?c=" + sales_quotation_url + "&d=" + new Date().getTime() ;
  
    callServer(url,"json",data,onCoverTemplateResponse,null) ;
}

function changeCoverTempOption() {
    if($('#chkCoverTempOption').is(':checked')){
        $('#divCoverTemplateList').hide();
        $('#divCoverTemplateName').show();

        $('#txtChkCoverTempOption').val("1");
    }else{
        $('#divCoverTemplateList').show();
        $('#divCoverTemplateName').hide();

        $('#txtChkCoverTempOption').val("0");
    }

    populateCoverTemplateList();
}

function populateCoverTemplateList() {
    var data = { 
                "type"                 : "C_VIEW_LOAD_COVER_TEMPLATE_LIST"
            };
    var url = "index.pzx?c=" + sales_quotation_url + "&d=" + new Date().getTime() ;
  
    callServer(url,"json",data,onCoverTemplateResponse,null) ;
}

function popupLoadTemplateCover() {
    var data = { 
                "type"                 : "C_VIEW_LOAD_COVER_TEMPLATE"
                };
    var url = "index.pzx?c=" + sales_quotation_url + "&d=" + new Date().getTime() ;
  
    callServer(url,"json",data,onCoverTemplateResponse,null) ;
}

function DeleteTemplateCover() {
    $("#LoadCoverTemplateConfirmationView").modal("hide");
    var data = { 
            "template_id"          : $('#CoverTemplateLoad').val(),
            "type"                 : "C_DELETE_COVER_TEMPLATE"
            };
    var url = "index.pzx?c=" + sales_quotation_url + "&d=" + new Date().getTime() ;
  
    callServer(url,"json",data,onCoverTemplateResponse,null) ;
}

function LoadTemplateCover() {
    var data = { 
                "template_id"          : $('#CoverTemplateLoad').val(),
                "type"                 : "C_LOAD_COVER_TEMPLATE"
                };
    var url = "index.pzx?c=" + sales_quotation_url + "&d=" + new Date().getTime() ;
  
    callServer(url,"json",data,onCoverTemplateResponse,null) ;
}

function onCoverTemplateResponse(obj,resp){
    if (resp.status != C_OK ) {
        Swal.fire("Error", resp.mesg, "error");
        return false;
    }

    if(resp.type == "C_SAVE_COVER_TEMPLATE"){
        $('#CoverTemplateName').val("");
        $('#chkCoverTempOption').prop('checked', true);
        $('#CoverTemplateList').val(0);
        // $('#CoverTemplateNewName').val("");

        $('#SaveCoverTemplateConfirmationView').modal('hide'); 
        Swal.fire("Success", resp.mesg, "success");
      
    }else if(resp.type == "C_VIEW_LOAD_COVER_TEMPLATE"){
        var strBtn = "<button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\">Cancel</button>" +
                     "<button onclick=\"DeleteTemplateCover();\" type=\"button\" class=\"btn btn-danger ml-2\" >Delete</button>" +
                     "<button onclick=\"LoadTemplateCover();\" class=\"btn btn-primary ml-2\" > Load </button>";

        $('#modalLoadCoverTemplateConfirmationButton').html(strBtn);
        $("#CoverTemplateLoad").html(resp.data.load_option);
      
    } else if(resp.type == "C_VIEW_LOAD_COVER_TEMPLATE_LIST"){
        $("#CoverTemplateList").html(resp.data.load_option);
    }
    else if(resp.type == "C_LOAD_COVER_TEMPLATE"){
        $('#LoadCoverTemplateConfirmationView').modal('hide'); 

         var myObj = JSON.parse(resp.data.salesquotation_cover);
         showCoverTemplate(myObj);
    } else if(resp.type == "C_DELETE_COVER_TEMPLATE"){
         Swal.fire("Success", resp.mesg, "success");
    }
}