
var currentActiveButton = null;
var tempUploadQueue = [];
var projectId = "";
var params = {};
var G_previewTemplate = ""; //"<div class=\"dz-preview dz-file-preview\"><div class=\"col-md-9 cl-div-uploads-left\"><div class=\"dz-filename\"><span data-dz-name></span></div></div><div class=\"col-md-3 cl-div-uploads-right\"><div class=\"dz-progress\"><span class=\"dz-upload\" data-dz-uploadprogress></span></div><div class=\"dz-upload-status\"><div class=\"dz-success-mark\">\n<i class=\"fa fa-check\" aria-hidden=\"true\"></i></div>\n<div class=\"dz-error-mark\">\n<i class=\"fa fa-exclamation\" aria-hidden=\"true\"></i></div></div><div class=\"dz-remove\"><span class=\"fa-stack\"><i class=\"fa fa-trash fa-stack-1x\" aria-hidden=\"true\" data-dz-remove></i><i class=\"fa fa-circle-o-notch fa-stack-2x fa-spin cl-i-delete-spinner\" aria-hidden=\"true\"></i></span></div></div></div></div>";
var previewContainer = null;
var validated = false;
var docTypeString = "";
var docRename = "";
var loadingMsgContainer = null;
var loadingMsgSpan = null;
// Edited By Vijay - Create a map to identify header for each document category
// var doc_map = new Array();
var image_map = new Array(); // Created this map to map image file name with description and changed name - had to do this due to limitaions i queue
var image_desc_map = new Array();
var uploaded_file_id="";
var image_type = "image";  // keyword to check if the uploaded document is an image
var image_description = ""; // image description global
var image_uploaded_id="";
var documentUpload_ID="#documentUploadButton";
var imageUpload_ID="#imageUploadButton";
var upload_preview_container = "#id-div-uploaded-list";
// Source : https://stackoverflow.com/questions/7317273/warn-user-before-leaving-web-page-with-unsaved-changes
var uploading = false;
var setUploadStatus = function() { uploading = false; };
 
window.onload = function() {
    window.addEventListener("beforeunload", function (e) {
        if (!uploading) {
            return undefined;
        }
        var alert_message = "Files have not finished uploading. If you leave this page, data will be lost";
        (e || window.event).returnValue = alert_message; //Gecko + IE
        return alert_message; //Gecko + Webkit, Safari, Chrome etc.
    });
};
var uploadEventListener = 
function(){
    if(currentActiveButton == $(imageUpload_ID)[0].dropzone){
        var names = [];
        var fileList = tempUploadQueue = $(this).get(0).files;
        var filesPreviewContainer = $("#id-div-image-file-list");
        filesPreviewContainer.empty();
        $("#id-span-image-upload-count").html(fileList.length);
        for (var i = 0; i < fileList.length; ++i) {
            names.push(fileList[i].name);
            var file_id = fileList[i].name.replace(".","-");
            // Edited by Vijay - To create rename file and file description input for each image selected by the user for upload
            var file_desc_html='<div class="col-md-12 cl-div-file-rename-input"><div class="col-md-3 cl-ignore-bs-right-padding" style="text-align:center;"><label for="'+file_id+'-fname" class="form-control-label">File Name</label></div>';
                file_desc_html+='<div class="col-md-9"><input id="'+file_id+'-fname" value="'+fileList[i].name+'" class="form-control" type="text"/></div></div> ';
                file_desc_html+='<div class="col-md-12 cl-div-file-rename-input">';
                file_desc_html+='<div class="col-md-3 cl-ignore-bs-right-padding" style="text-align:center;"><label for="'+file_id+'-desc" class="form-control-label">Description</label></div>';
                file_desc_html+='<div class="col-md-9"><input id="'+file_id+'-desc" class="cl-img-desc-input form-control" type="text"/></div></div>';
                file_desc_html+='<hr>';
            filesPreviewContainer.append(file_desc_html);
            // Edited by Vijay till here
            // filesPreviewContainer.append("<div class=\"cl-div-file-preview\"><span class=\"cl-span-file-preview\">"+fileList[i].name+"</span></div>");
        }
        $("#id-btn-upload-image-confirm").show();
        $("#id-btn-upload-image-update").hide();
        $("#imageModalLabel").html("Upload Images"); // Setting image modal title 
        $("#imageCountHeader").show(); // Displaying file count
        $("#modalBodyDesc").show(); // Displaying modal body description
        $("#id-modal-image").modal('show');
        
    }
    else if(currentActiveButton == $(documentUpload_ID)[0].dropzone){
        $("#id-modal-document").find("input[type=checkbox]").prop("checked", false);
        $("#id-modal-document").find("input[type=checkbox]").prop("indeterminate", false);
       
        // // show Upload button and hide update button
        // $("#id-btn-upload-document-confirm").show();
        $("#id-btn-upload-document-update").hide();
       
        $("#id-modal-document").modal('show');
        $(".cl-modal-file-type-id").hide();
        $(".cl-file-rename-class").show();
        $("#file-rename-tag").html("1");
        $("#documentModalLabel").html("Upload Documents"); // Adding title from the modal when browsefiles button is clicked
        $("#id-btn-upload-document-confirm").show();
        tempUploadQueue = $(this).get(0).files[0];
        $("#id-inp-document-file-rename").val(tempUploadQueue.name.substr(0, tempUploadQueue.name.indexOf(".") > 0 ? tempUploadQueue.name.indexOf(".") : tempUploadQueue.name.length ));
        docRename = tempUploadQueue.name.substr(tempUploadQueue.name.indexOf(".") > 0 ? tempUploadQueue.name.indexOf(".") : tempUploadQueue.name.length);
    }

    return false;
}

var createElement = function(string) {
    var div;
    div = document.createElement("div");
    div.innerHTML = string;
    return div.childNodes[0];
  };

function removeFile(file){}

function format_doc_category_string(docCategory){
    if(docCategory == null || docCategory == ""){
        docCategory = 'Drawings';
    }
    console.log("docCategory"+docCategory);
    docCategory=docCategory.toLowerCase();
    console.log("docCategory"+docCategory.toLowerCase());
    docCategory=docCategory.replace(new RegExp(" ", 'g'), "-");
    return docCategory;
}

function create_doc_category_div(fileName,docType,uploadby="user"){
    var html='<div class="col-md-12 dz-preview dz-file-preview dz-processing dz-success cl-uploaded-doc-filename '+uploaded_file_id+'_div">';
    html+='<div class="col-md-4" style="text-align: left;">'
    html+=docType+'</div>';
    html+='<div class="col-md-4" style="text-align: center;">'
    html+=fileName+'</div>';
    html+='<div class="col-md-2" style="text-align: center;">'
    html+=uploadby+'</div>';
    html+='<div class="col-md-2" style="text-align: right;">';
    html+='<div class="col-md-8 cl-progress-bar dz-progress"><span class="dz-upload '+uploaded_file_id+'-dz-upload" data-dz-uploadprogress></span></div><div class="col-md-2"><span class="dz-edit-mark" onclick="update_document_section('+"'"+uploaded_file_id+"'"+');" ><i class="fa fa-pencil-square" aria-hidden="true"></i></span></div><div class="col-md-2"><span class="fa-stack" onclick="delete_document_section('+"'"+uploaded_file_id+"'"+');" style="cursor:pointer"><i class="fa fa-trash fa-stack-1x" aria-hidden="true" data-dz-remove=""></i></div></div>';
    html+='</div>';
    return html;
}

function create_image_uploaded_divlist(fileName,docType){
    var html='<div class="col-md-12 dz-preview dz-file-preview dz-processing dz-success cl-uploaded-doc-filename '+uploaded_file_id+'_div">';
    html+='<div class="col-md-4" style="text-align: left;">'
    html+=fileName+'</div>';
    html+='<div class="col-md-4" style="text-align: center;">'
    html+=docType+'</div>';
    html+='<div class="col-md-4" style="text-align: right;">';
    html+='<div class="col-md-8 cl-progress-bar dz-progress"><span class="dz-upload '+uploaded_file_id+'-dz-upload" data-dz-uploadprogress></span></div><div class="col-md-2"><span class="dz-edit-mark" onclick="update_image_section('+"'"+uploaded_file_id+"'"+');" style="cursor:pointer"><i class="fa fa-pencil-square" aria-hidden="true"></i></span></div><div class="col-md-2"><span class="fa-stack" onclick="delete_document_section('+"'"+uploaded_file_id+"'"+');" style="cursor:pointer"><i class="fa fa-trash fa-stack-1x" aria-hidden="true" data-dz-remove=""></i></div></div>';
    html+='</div>';
    return html;
}

function update_document_section(document_id){
    showEditDocumentTypesDialog(projectId, document_id);
}

function update_image_section(image_id){
    showEditImageDialog(projectId,image_id);
}

function delete_document_section(document_id){ // Function to show popup to delte file permanently
    $("#id-modal-delete-doc-confirm").attr("project_id",projectId);
    $("#id-modal-delete-doc-confirm").attr("document_id",document_id);
    $("#id-modal-delete-doc-confirm").modal("show");
}

function reset_docs_upload_function(){

    disable_docs_function();
    $(imageUpload_ID).children('img').attr('src', 'images/UploadIcon.77795d31.png');
    $(imageUpload_ID).removeAttr("disabled");
    $(imageUpload_ID).attr("title", "");;


}

function disable_docs_function(){
    $('#first-col input[type="checkbox"]').prop("checked",false);
    $('#second-col input[type="checkbox"]').prop("checked",false);
    $(documentUpload_ID).attr("disabled",true);
    $(documentUpload_ID).attr("title","Please identify file content(s) to upload a document");
    $(documentUpload_ID).children('img').attr('src', 'images/UploadIcon_grey.0dec1698.png');
}

function disable_imgs_function(){
    $('#third-col input[type="checkbox"]').prop("checked",false);
    $(imageUpload_ID).attr("disabled",true);
    $(imageUpload_ID).attr("title", "Please check Images checkbox to upload images ");
    $(imageUpload_ID).children('img').attr('src', 'images/UploadIcon_grey.0dec1698.png');
}

function reset_images_upload_function(){
    console.log("CameInside");
    disable_imgs_function();
    $(documentUpload_ID).removeAttr("disabled");
    $(documentUpload_ID).children('img').attr('src', 'images/UploadIcon.77795d31.png');
    $(documentUpload_ID).attr("title","");
}

$(document).ready( function() {

    // load the file preview template from the file
    $.get('FilePreviewTemplate.php', function (fileTemp) {
        G_previewTemplate = fileTemp;
    });

    $("img").unveil();
    $("img").trigger("unveil");
    Dropzone.autoDiscover = false;
    var documentUploadButton;
    var imageUploadButton;
    previewContainer = $(upload_preview_container);
    loadingMsgContainer = $(".cl-section-loading-msg");
    loadingMsgSpan = $(".cl-span-loading-msg");

    // if(typeof params.pid !== "undefined"){
    //     projectId = params.pid;
    //     $("#id-project-overview-bclink").attr("href", "projectOverview.php?edit=true&id=".projectId);
    //     $("#id-project-overview-bclink").attr("pid", projectId);
    // }

    window.location.search.replace(/[?&;#]+([^=&]+)=([^&]*)/gi,function(str,key,value){params[key] = value;});

    if(typeof params.pid !== "undefined"){
        projectId = params.pid;
        // alert(projectId);

        attachOverviewEventListener($('#id-global-container'), true, projectId);
        $("#id-project-overview-bclink").attr("href", "projectOverview.php?edit=true&id="+projectId);
        $("#id-project-overview-bclink").attr("pid", projectId);

        $.post("API.php", {project: "VALIDATE_CURRENT_USER", id: projectId}, function(data){
            if(data.response){
                validated = true;
                $("#id-project-title-text span").html(data.project_title+" Documents");

                $.post("API.php", {document: "LIST", project_id: projectId}, function(data){
                    console.log(data);
                    $.each(data.data, function(index, file){
                        var previewElement = createElement(G_previewTemplate);
                        $(previewElement).attr("id",file.document_id);
                        $(previewElement).find(".dz-filename").children().first().html(file.true_name);
                        $(previewElement).addClass("dz-processing");
                        $(previewElement).addClass("dz-success");
                        $(previewElement).addClass("dz-complete");
                        var document_types =  file.document_type;
                        document_types = document_types.replace("document:","");
                        document_types = document_types.split(";");
                        var fileName = file.true_name;
                        uploaded_file_id = file.document_id;
                        var uploaded_by = file.last_name;
                        console.log(file);
                        $.each(document_types,function(index,document_type){
                            // console.log(document_type);
                            if(document_type ==  image_type){
                                // do something
                                $("#div-uploaded-images").append(create_image_uploaded_divlist(fileName,file.description));
                                $("."+uploaded_file_id+"_div").addClass("dz-complete");
                            }
                            else{
                                var docType;
                                console.log("Document type : "+document_type);
                                docType = doc_map[document_type];
                                if(docType == null || docType == ""){
                                    docType = 'Drawings';
                                }
                                docType=format_doc_category_string(docType);
                                var div_html=create_doc_category_div(fileName,document_type,uploaded_by);
                                $("#div-uploaded-"+docType).append(div_html);
                                $("."+uploaded_file_id+"_div").addClass("dz-complete");
                            }
                        })
                        $(previewElement).find(".dz-remove").click(function(){
                            var fileRowElem = $(this).parent().parent();
                            var document_id = $(fileRowElem).attr("id");

                            // show popup box
                            // show_confirmation_popup()
                            $("#id-modal-delete-doc-confirm").data("file_dom_row",fileRowElem);
                            $("#id-modal-delete-doc-confirm").attr("project_id",projectId);
                            $("#id-modal-delete-doc-confirm").attr("document_id",document_id);
                            $("#id-modal-delete-doc-confirm").modal("show");
                            /*
                            $(fileRowElem).addClass("dzi-deleting");
                            // console.log("deleting file with id : " + document_id);
                            $.post("API.php",{document: "DELETE", project_id: projectId, document_id: document_id}, function(data){
                                if(data.response){
                                    $(fileRowElem).remove();
                                }
                            }, "json");
                            */
                        });

                        $(previewElement).find(".dz-edit").click(function(){
                            var fileRowElem = $(this).parent().parent();
                            var document_id = $(fileRowElem).attr("id");
                           
                            // console.log("Editing file with id : " + document_id);
                            // open the popup which allows the editing of the document types
                            showEditDocumentTypesDialog(projectId, document_id);
                             
                        });
                        
                        // $(previewContainer).append(previewElement);
                    });
                },"json");

                $(".cl-btn-project-doc-upload").click(function(){
                    currentActiveButton = this.dropzone;
                });
                $("#docs-upload-img").click(function(){
                    $(documentUpload_ID).click();
                })
                $("#imgs-upload-img").click(function(){
                    $(imageUpload_ID).click();
                })

                // Open modal box on clicking document browse files button
                // $("#doc-UploadButton").click(function(){
                //     $("#id-modal-document").find("input[type=checkbox]").prop("checked", false);
                //     $("#id-modal-document").find("input[type=checkbox]").prop("indeterminate", false);
                //     $("#id-btn-upload-document-confirm").hide();
                //     $("#id-btn-upload-document-update").hide();
                //     $(".cl-file-rename-class").hide();
                //     $(".cl-file-choose-class").show();
                //     $("#id-modal-document").modal('show');

                // });

                documentUploadButton =  new Dropzone(documentUpload_ID, {
                    url: "Upload.php",
                    autoProcessQueue: false,
                    addRemoveLinks: false,
                    createImageThumbnails: false,
                    acceptedFiles: 'application/pdf, .pdf, .doc, .docx, .xls, .xlsx', 
                    maxFilesize: '2000', 
                    uploadMultiple: false, 
                    parallelUploads: 1, 
                    previewsContainer: '#id-div-uploaded-list', 
                    previewTemplate: G_previewTemplate,
                    init: function(){
                        Array.from($(".dz-hidden-input")).forEach(function(element){
                            element.removeEventListener("change", uploadEventListener);
                        });
                        Array.from($(".dz-hidden-input")).forEach(function(element){
                            element.addEventListener("change", uploadEventListener, {capture: true, once: false});
                            element.customListener = uploadEventListener;
                        });

                        this.on("removedfile", function(file){
                            // console.log("deleting file : " + file.name);
                            $.post("API.php",{document: "DELETE", project_id: projectId, document_id: $(file.previewElement).attr("id")}, function(data){
                                // console.log(data.response);
                            }, "json");
                        });

                        this.on("addedfile", function(file){
                            // console.log("adding file : " + file.name);
                            // console.log("Document ID: "+file.document_id);
                            uploaded_file_id=$(file.previewElement).attr("id");
                            $(previewContainer).find(".dz-edit").click(function()
                            {
                                var fileRowElem = $(this).parent().parent();
                                var document_id = $(fileRowElem).attr("id");
                                
                                // console.log("Editing file with id : " + document_id);
                                // open the popup which allows the editing of the document types
                                showEditDocumentTypesDialog(projectId, document_id);
                                    
                            });
                        });

                        //uploadMultiple is false, so just sending suffices
                        this.on("sending", function(file, xhr, formData){
                            var randStrings = [];
                            randStrings[0] = $(file.previewElement).attr("id");
                            formData.append("randString", randStrings);
                            formData.append("projectId", projectId);                
                            formData.append("fileType", docTypeString);
                            formData.append("rename", docRename);
                            formData.append("file_desc","");
                            docTypeString = "";                
                        });
                    }
                });
                $(documentUploadButton).addClass("dropzone");


                imageUploadButton =  new Dropzone(imageUpload_ID, { 
                    url: "Upload.php", 
                    autoProcessQueue: true, 
                    addRemoveLinks: false, 
                    createImageThumbnails: false,
                    acceptedFiles: 'image/*', 
                    maxFilesize: '20', 
                    uploadMultiple: true, 
                    parallelUploads: 1, 
                    previewsContainer: '#id-div-uploaded-list', 
                    previewTemplate: G_previewTemplate,
                    init: function(){
                        Array.from($(".dz-hidden-input")).forEach(function(element){
                            element.removeEventListener("change", uploadEventListener);
                        });
                        Array.from($(".dz-hidden-input")).forEach(function(element){
                            element.addEventListener("change", uploadEventListener, {capture: true, once: false});
                            element.customListener = uploadEventListener;
                        }); 

                        this.on("removedfile", function(file){
                            // console.log("deleting file : " + file.name);
                            $.post("API.php",{document: "DELETE", project_id: projectId, document_id: $(file.previewElement).attr("id")}, function(data){
                                // console.log(data.response);
                            }, "json");
                        });

                        this.on("addedfile", function(file){
                            // console.log("adding file : " + file.name);
                            // console.log("image id : "+$(file.previewElement).attr("id"));
                            // console.log("Description : "+image_description);
                            // adding image div to image uploaded div
                            uploaded_file_id = $(file.previewElement).attr("id");
                            var file_name = file.name;
                            $("#div-uploaded-images").append(create_image_uploaded_divlist(image_map[file_name],image_desc_map[file_name]));
                            // image_description="";
                        });

                        //uploadMultiple is false, so just sending suffices
                        this.on("sending", function(file, xhr, formData){
                            var randStrings = [];
                            var file_name = file.name;

                            randStrings[0] = $(file.previewElement).attr("id");
                            formData.append("randString", randStrings);
                            formData.append("projectId", projectId);                
                            formData.append("fileType", "image"); 
                            formData.append("file_desc",image_desc_map[file_name]); // sending image description
                            formData.append("rename",image_map[file_name]);
                            image_description="";              
                        });
                    }
                });
                $(imageUploadButton).addClass("dropzone");
                
                
                $("#id-modal-image").on('hidden.bs.modal', function(e){
                    tempUploadQueue = [];
                    Array.from($(".dz-hidden-input")).forEach(function(element){
                        element.value = ''; //reset fileList
                    });
                });

                $("#id-modal-document").on('hidden.bs.modal', function(e){
                    Array.from($(".dz-hidden-input")).forEach(function(element){
                        element.value = ''; //reset fileList
                    });
                });

                $("#id-btn-upload-image-confirm").click(function(){
                    var file_new_name = "";
                    image_description="";
                    var file_id="";
                    uploading=true;
                    $(upload_preview_container).focus();
                    $.each(tempUploadQueue, function(index, file){
                        image_description="";
                        file_new_name = file.name;

                        file_id=file_new_name.replace(".","-");
                        file_new_name = $("#"+file_id+"-fname").val();
                        image_description = $("#"+file_id+"-desc").val();
                        image_map[file.name] = file_new_name;
                        image_desc_map[file.name] = image_description;
                        currentActiveButton.addFile(file);
                        currentActiveButton.processQueue();
                    });
                    
                    $("#id-div-image-file-list").html("");
                    $("#id-modal-image").modal('hide');
                    disable_imgs_function();
                });

                $("#id-btn-upload-document-confirm").click(function(){
                    docTypeString = "";
                    var docCategory="";
                    uploading=true;
                    $(upload_preview_container).focus();
                    docRename = $("#id-inp-document-file-rename").val() + docRename;
                    $.each($(".form-check-input"), function(index, elem){
                        if( $(elem).prop("checked") ){
                            docTypeString += ";"+$(elem).val();
                        }
                    });
                    docTypeString = docTypeString.replace(/([;]+)/, ";").replace(/^;/, "").replace(/;$/, "");
                    console.log("docTypeString : "+docTypeString);
                    docTypeString = "document:"+docTypeString;  
                    // Edited by Vijay
                    tempUploadQueue.rename = docRename;
                    currentActiveButton.addFile(tempUploadQueue);
                    currentActiveButton.processQueue();
                    // Edited by Vijay Till here            
                    
                    $.each($(".form-check-input"), function(index, elem){
                        if( $(elem).prop("checked") ){
                            // Edited by Vijay - To populate the document under corresponding section
                            docCategory = doc_map[$(elem).val()];
                            docCategory=format_doc_category_string(docCategory);
                            var div_html=create_doc_category_div(docRename,$(elem).val());
                            $("#div-uploaded-"+docCategory).append(div_html);
                            // Edited by Vijay Till here
                        }
                    });
                    $("#id-modal-document").modal('hide');
                    disable_docs_function();
                });

                $("#id-btn-upload-document-update").click(function(){
                    docTypeString = "";
                    var document_name  = $("#id-inp-document-file-rename").val();                 
                    var document_id = $("#id-modal-document").attr("document-id");
                    var project_id = $("#id-modal-document").attr("project-id");
                    $("."+document_id+"_div").remove();
                    $.each($("#id-modal-document").find("input[type=checkbox]"), function(index, elem){
                        if( $(elem).prop("checked") ){
                            docTypeString += ";"+$(elem).val();
                            docCategory = doc_map[$(elem).val()];
                            docCategory=format_doc_category_string(docCategory);
                            var div_html=create_doc_category_div(docRename,$(elem).val());
                            $("#div-uploaded-"+docCategory).append(div_html);
                        }
                    });
                                        
                    docTypeString = docTypeString.replace(/([;]+)/, ";").replace(/^;/, "").replace(/;$/, "");
                    docTypeString = "document:"+docTypeString; 
                    
                    var description = "";
                    updateDocumentDetails(project_id, document_id, docTypeString, document_name, description);
                    $("#id-modal-document").modal('hide');
                    
                });

                $("#id-btn-upload-image-update").click(function(){
                                     
                    var image_id = $("#id-modal-image").attr("document-id");
                    var project_id = $("#id-modal-image").attr("project-id");
                    
                    var image_name  = $("#"+image_id+"-fname").val();
                    var description  = $("#"+image_id+"-desc").val();
                    docTypeString="image";
                    updateDocumentDetails(project_id, image_id, docTypeString, image_name, description );
                    $("."+image_id+"_div").remove();
                    uploaded_file_id = image_id;
                    $("#div-uploaded-images").append(create_image_uploaded_divlist(image_name,description));
                    $("#id-modal-image").modal('hide');
                    
                });
                var first_col_checkboxes = $('#first-col input[type="checkbox"]');
                var second_col_checkboxes = $('#second-col input[type="checkbox"]');
                var third_col_checkboxes = $('#third-col input[type="checkbox"]');
                $('#first-col input[type="checkbox"]').change(function(){
                    console.log("CametoReset");
                    reset_images_upload_function();
                    var length = first_col_checkboxes.filter(":checked").length;
                    if(length==0)
                        disable_docs_function();
                });
                $('#second-col input[type="checkbox"]').change(function(){
                    console.log("CametoReset2");
                    reset_images_upload_function();
                    var length = second_col_checkboxes.filter(":checked").length;
                    if(length==0)
                        disable_docs_function();
                });
                $('#third-col input[type="checkbox"]').change(function(){
                    reset_docs_upload_function();
                    var length = third_col_checkboxes.filter(":checked").length;
                    if(length==0)
                        disable_imgs_function();

                });
            } else {
                alert("Project requested is not owned by the current user or sufficient permissions are not given for current user. No further action is possible on this page.");
                return;
            }
        },"json");
    }

    $("#id-modal-document").find("input[type=checkbox]").click(function(){
        var subTypeContainer = $(this).parent().parent().parent();
        var checkedString =$(subTypeContainer).attr("data-checked-str");
        if(!checkedString || typeof checkedString === "undefined"){
            checkedString = "";
        }

        if($(this).prop("checked") && (checkedString.indexOf($(this).val()) == -1)){
            checkedString += ","+$(this).val();
        } else if(!$(this).prop("checked") && (checkedString.indexOf($(this).val()) != -1)){
            checkedString = checkedString.replace($(this).val(), "");
        }

        checkedString = checkedString.replace(/([,]+)/, ",").replace(/^,/, "").replace(/,$/, "");
        if(subTypeContainer.children().length != 1){
            $(subTypeContainer).find("input[type=checkbox]").first().prop("indeterminate", (checkedString !== "" && checkedString.split(",").length > 0));
        }
        $(subTypeContainer).attr("data-checked-str", checkedString);
    });

    /*
    $("#id-btn-submit-project-submit").click(function(ev){
        $.post("API.php", {project: "SUBMIT_REVIEW", id: projectId, submit_type: "isUD_certification" }, function(data){
            if( data.success )
            {
                launch_project_submit_confirmation_dialog(projectId);
            }
            else
            {
                // call function from submitProjectClick.js
                show_error_popup_on_submit(data);
            }
        },"json");
    });
    */

});

/*
var launch_project_submit_confirmation_dialog = function (project_id)
{
    $("#id-modal-project-submit").attr("data-project-id", project_id );
    $("#id-modal-project-submit-screen-1").hide();
    $("#id-modal-project-submit-screen-2").hide();
    $("#id-modal-project-submit-screen-3").show();
    $("#id-modal-project-submit").modal('show');
};

$("#id-btn-project-submit-modal-close-btn").click(function(ev)
{
    var target = "projectDashboard-copy.php";
    window.location.href = target;        
});

// if user clicks outside the modal dialog then 'hidden.bs.modal' event is 
// triggered. Handle this case and redierect user to the Manage Project Page.
$("#id-modal-project-submit").on("hidden.bs.modal", function () {
    var target = "projectDashboard-copy.php";
    window.location.href = target;   
});
*/

$("#id-btn-submit-project-save-docs").click(function(ev){
    var target = "myProjects.php";
    window.location.href = target;
});

$("#id-btn-submit-project-close-page").click(function(ev){
    var target = "myProjects.php";
    window.location.href = target;
});
// when user click on the edit icon in front of uploaded document;
// show user with the already checked options from the database.
var showEditDocumentTypesDialog = function (project_id, document_id)
{
    // clear all the check boxes
    $(".cl-modal-file-type-id").show();
    $(".cl-file-rename-class").show();
    $("#file-rename-tag").html("1");
    $("#id-modal-document").find("input[type=checkbox]").prop("checked", false);
    $("#id-modal-document").find("input[type=checkbox]").prop("indeterminate", false);
    $("#documentModalLabel").html(""); // Removing title from the modal when update button is clicked
     $.post("API.php", {document: "GET_DETAILS", project_id: project_id, document_id:document_id}, function(document_info){
        // console.log("The document details are : ",document_info);
        // console.log(document_info);
        $("#id-inp-document-file-rename").val(document_info.true_name);
        // console.log("Document types are : ",document_info.document_type);
        var document_types =  document_info.document_type;
        document_types = document_types.replace("document:","");
        document_types = document_types.split(";");
        $.each(document_types,function(index,document_type){
            // console.log(document_type);
            $("#id-modal-document").find("input[type=checkbox]").filter(function()
            {
                return this.value === document_type;
            }).prop('checked', true);
        })
     },"json");

    // get the document information from the id
    $("#id-modal-document").attr("project-id",project_id);
    $("#id-modal-document").attr("document-id",document_id);
    
    // hide the upload button and show update button
    $("#id-btn-upload-document-confirm").hide();
    $("#id-btn-upload-document-update").show();
    $(".cl-file-rename-class").show();
    $(".cl-file-choose-class").hide();
    $("#id-modal-document").modal('show');
}
var showEditImageDialog = function (project_id, document_id)
{

     $.post("API.php", {document: "GET_DETAILS", project_id: project_id, document_id:document_id}, function(document_info){
        
        $("#id-inp-document-file-rename").val(document_info.true_name);
        $("#id-span-image-upload-count").html(1);
        $("#id-div-image-file-list").empty();
        var image_id = document_info.document_id;
        var description = document_info.description;
        var file_desc_html='<div class="col-md-12 cl-div-file-rename-input"><div class="col-md-2"><label for="'+image_id+'-fname" class="form-control-label">File Name</label></div>';
        file_desc_html+='<div class="col-md-10"><input id="'+image_id+'-fname" value="'+document_info.true_name+'" class="form-control" type="text"/></div></div> ';
        file_desc_html+='<div class="col-md-12 cl-div-file-rename-input">';
        file_desc_html+='<div class="col-md-2"><label for="'+image_id+'-desc" class="form-control-label">Description</label></div>';
        file_desc_html+='<div class="col-md-10"><input id="'+image_id+'-desc" value="'+description+'" class="cl-img-desc-input form-control" type="text"/></div></div>';
        $("#id-div-image-file-list").append(file_desc_html);
     },"json");

    // get the document information from the id
    $("#id-modal-image").attr("project-id",project_id);
    $("#id-modal-image").attr("document-id",document_id);
    
    // hide the upload button and show update button
    $("#id-btn-upload-image-confirm").hide();
    $("#id-btn-upload-image-update").show();

    $("#imageModalLabel").html("");  // setting image modal title to empty
    $("#imageCountHeader").hide();  // Hiding file count header
    $("#modalBodyDesc").hide(); // Hiding modal body description
    $("#id-modal-image").modal('show');
}

var updateDocumentDetails = function (project_id, document_id, types, name,description)
{
     $.post("API.php", {document: "UPDATE_DETAILS", project_id: project_id, document_id:document_id, types: types, name: name, description: description}, function(document_info){
        // console.log("Document Update status : "+document_info.success);
     },"json");
}

$("#id-btn-delete-doc-yes").click(function(ev){
    // var fileRowElem = $("#id-modal-delete-doc-confirm").data("file_dom_row");
    var project_id = $("#id-modal-delete-doc-confirm").attr("project_id");
    var document_id = $("#id-modal-delete-doc-confirm").attr("document_id");
    
    // $(fileRowElem).addClass("dzi-deleting");
    // console.log("deleting file with id : " + document_id);
    // alert('before');
    $.post("API.php",{document: "DELETE", project_id: project_id, document_id: document_id}, function(data){
        // alert('inside');
        // alert(JSON.stringify(data));
        if(data.response){
            // $(fileRowElem).remove();
            // alert('success');
            // console.log(data);
            $("."+document_id+"_div").remove();
            $("#id-modal-delete-doc-confirm").modal('hide');
        }
    }, "json");
});

function attachOverviewEventListener(projectElem, attach){
    var btn = $(projectElem).find(".cl-project-edit-btn");
    if(!attach){
        $(btn).css("cursor", "no-drop");
        $(btn).click(function(ev){
            return false;
        });
    } else {
        $(btn).css("cursor", "pointer");
        $(btn).click(function(ev){
            var target = "projectOverview.php?edit=true&id="+projectId ;
            window.location.href = target;
        });
    }
}
;