var contacts = [] ;
var upload_form = null;
var m_filename = "";
var m_filedoc = "";

$(document).ready(function() {
    $('#btnMeetingSave').on('click',addMeeting) ;
    $('#btnMeetingUpdate').on('click',updateMeeting) ;
    $('#btnNewMeeting').on('click',newMeeting) ;
    $('#btnMeetingLogout').on('click',onLogout) ;
    getAutoSearch("ACCOUNT_NAME_SEARCH");
    showReminder();
}) ;

function meetingView() {
    LoadingScreen("show");
    var data = { "type": C_VIEW,
				 "index": screen_index,
				};
    var url  = "index.pzx?c=" + meeting_url + "&d=" + new Date().getTime() ;
	callServer(url,"json",data,onResponseMeeting,null) ;
}

function changeMeetingStatus(){
    var status = $('#cobMeetingStatus').val();
    if((status == 0  || status == 1) &&  status != ""){ // 0 = Follow up, 1 = Confirmed
        $('#followUpSection').css('display', '');
    } else {
        $('#followUpSection').css('display', 'none');
    }
}

function newMeeting() {
    clearMeetingForm();
}

function addMeeting() {
    saveMeeting(C_ADD);
}

function updateMeeting() {
    saveMeeting(C_UPDATE);
}

function saveMeeting(type) {
    if (validateMeeting()) {
        var data = {
            "type"              : type,
            
            "prospect_id"       : $('#txtMeetingProspectID').val(),
            "contact_id"        : $('#txtMeetingContactID').val(),
            "person_id"         : $('#txtMeetingPersonID').val(),
            "conversation_id"   : $('#txtMeetingConversationID').val(),

            "name"              : $('#txtMeetingName').text(),
            "contact_name"      : $('#cboContactName').text(),
            "contact_phone"     : $('#txtMeetingPhone').val(),
            "contact_email"     : $('#txtMeetingEmail').val(),
            "location"          : $('#txtMeetingLocation').val(),
            "date"              : $('#txtMeetingDate').val(),
            "time"              : $('#txtMeetingTime').val(),
            "conversation"      : $('#txtMeetingConversation').val(),
            "status"            : $('#cobMeetingStatus').val(),

            "followup_location" : $('#txtMeetingFollowUpLocation').val(),
            "followup_date"     : $('#txtMeetingFollowUpDate').val(),
            "followup_time"     : $('#txtMeetingFollowUpTime').val(),
            "next_action"       : $('#txtMeetingNextAction').val(),
            "insert_to_calendar": $('#txtMeetingInsertToCalendar').is(':checked') ? 1 : 0,
            "reminder_days"     : $('#cboMeetingReminder').val(),
            "file_name"         : m_filename,
            "file_doc"          : m_filedoc
        };
        var url = "request.pzx?c=" + meeting_url + "&d=" + new Date().getTime();
        callServer(url, "json", data, onResponseMeeting, null);
    }
}

function getMeetinginfo(prospect_id, person_id, conversation_id, contact_id, newFromHistory=false) {
    // if called with newFromHistory=true, mark the transient flag so onResponseMeeting will treat it as a new record
    if (newFromHistory === true) {
        meetingNewFromHistory = true;
    }

    var data = {
        "type"               : C_GET,
        "prospect_id"        : prospect_id,
        "person_id"          : person_id,
        "conversation_id"    : conversation_id,
        "contact_id"         : contact_id,
    }
    var url = "request.pzx?c=" + meeting_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onResponseMeeting,null) ;
}

function validateMeeting() {
	if ($('#txtMeetingName').val()==""){
		$('#txtMeetingName').focus() ;
		swal.fire('System Warning', 'Account Name can not be blank.', 'warning') ;
		return false ;
	}

    if ($('#cboContactName').val()==""){
		$('#cboContactName').focus() ;
		swal.fire('System Warning', 'Contact Name can not be blank.', 'warning') ;
		return false ;
	}

    if ($('#txtMeetingPhone').val()==""){
		$('#txtMeetingPhone').focus() ;
		swal.fire('System Warning', 'Phone can not be blank.', 'warning') ;
		return false ;
	}

    if ($('#txtMeetingDate').val()==""){
		$('#txtMeetingDate').focus() ;
		swal.fire('System Warning', 'Date can not be blank.', 'warning') ;
		return false ;
	}

    if ($('#txtMeetingTime').val()==""){
		$('#txtMeetingTime').focus() ;
		swal.fire('System Warning', 'Time can not be blank.', 'warning') ;
		return false ;
	}

    if ($('#cobMeetingStatus').val()==""){
		$('#cobMeetingStatus').focus() ;
		swal.fire('System Warning', 'Status can not be blank.', 'warning') ;
		return false ;
	}else{
        if($('#cobMeetingStatus').val() == 0 || $('#cobMeetingStatus').val() == 1){ // 0 = Follow up, 1 = Confirmed
            if ($('#txtMeetingFollowUpLocation').val()==""){
                $('#txtMeetingFollowUpLocation').focus() ;
                swal.fire('System Warning', 'Location can not be blank.', 'warning') ;
                return false ;
            }

            if ($('#txtMeetingFollowUpDate').val()==""){
                $('#txtMeetingFollowUpDate').focus() ;
                swal.fire('System Warning', 'Date can not be blank.', 'warning') ;
                return false ;
            }

            if ($('#txtMeetingFollowUpTime').val()==""){
                $('#txtMeetingFollowUpTime').focus() ;
                swal.fire('System Warning', 'Time can not be blank.', 'warning') ;
                return false ;
            }
            
            // if($('#txtMeetingInsertToCalendar').is(':checked')){
                // if inserting to calendar, reminder cannot be blank
                // if ($('#cboMeetingReminder').val()==""){
                    // $('#cboMeetingReminder').focus() ;
                    // swal.fire('System Warning', 'Reminder can not be blank.', 'warning') ;
                    // return false ;
                // }
            // }
        }
    }
	return true ;
}

function onResponseMeeting(){
    if (resp.status == C_OK) {
		if (resp.type == C_ADD) {
			swal.fire("Successful", resp.mesg, "success");
            // $('#txtMeetingProspectID').val(resp.data);
            // uploadMeetingAttchment(resp.data);
            clearMeetingForm();
        }else if (resp.type == C_UPDATE) {
            swal.fire("Successful", resp.mesg, "success");
            clearMeetingForm();
		}else if(resp.type == C_GET){
            showContent(resp.data.htmlContent);

            $('#txtMeetingName').val(resp.data.account_name);

            $('#txtMeetingProspectID').val(resp.data.prospect_id);
            $('#txtMeetingContactID').val(resp.data.contact_id);
            $('#txtMeetingPersonID').val(resp.data.person_id);
            $('#txtMeetingConversationID').val(resp.data.conversation_id);
            $('#txtMeetingName').trigger('change');

            // contact <option> values are person_id, so select by person_id (not contact_id)
            $('#cboContactName').val(resp.data.person_id);
            // trigger change so phone/email and internal ids get populated from contacts array
            // $('#cboContactName').trigger('change');
            $('#txtMeetingPhone').val(resp.data.contact_phone);
            $('#txtMeetingEmail').val(resp.data.contact_email);
            $('#txtMeetingLocation').val(resp.data.location);
            $('#txtMeetingDate').val(resp.data.date);
            $('#txtMeetingTime').val(resp.data.time);
            $('#txtMeetingConversation').val(resp.data.conversation);
            $('#cobMeetingStatus').val(resp.data.status);
            $('#cobMeetingStatus').trigger('change');

            $('#txtMeetingFollowUpLocation').val(resp.data.followup_location);
            $('#txtMeetingFollowUpDate').val(resp.data.followup_date);
            $('#txtMeetingFollowUpTime').val(resp.data.followup_time);
            $('#txtMeetingNextAction').val(resp.data.next_action);

            $('#txtMeetingInsertToCalendar').prop('checked', resp.data.insert_to_calendar == 1);
            $('#cboMeetingReminder').val(resp.data.reminder_days);

            $('#btnMeetingSave').css("display", "none");
            $('#btnMeetingUpdate').css("display", "");

            // If this GET was triggered to start a NEW meeting from history, convert the loaded data
            // into a new meeting: clear conversation id and show Save button instead of Update.
            if (meetingNewFromHistory) {
                $('#txtMeetingConversationID').val('');
                $('#btnMeetingSave').css("display", "");
                $('#btnMeetingUpdate').css("display", "none");

                // Display the next action as the conversation. Do NOT keep follow-up fields set.
                var conv = resp.data.next_action || '';
                // Do NOT append follow-up fields into conversation; they will be cleared per request
                $('#txtMeetingConversation').val(conv);
                $('#txtMeetingLocation').val(resp.data.followup_location);

                // Clear follow-up status and follow-up fields, then trigger change to hide follow-up section
                $('#cobMeetingStatus').val('');
                $('#txtMeetingFollowUpLocation').val('');
                $('#txtMeetingFollowUpDate').val('');
                $('#txtMeetingFollowUpTime').val('');
                $('#txtMeetingNextAction').val('');
                $('#cobMeetingStatus').trigger('change');

                // Focus conversation textarea
                $('#txtMeetingConversation').focus();

                meetingNewFromHistory = false;
            } else {
                showReminder();
            }

            startMeeting(false, resp.data.date, resp.data.time);
        }else if (resp.type == "GET_ACCOUNT_INFO") {
            if (resp.data != "") {
                controlMeetingForm();
                // $('#divAccountContactDetail').html();
                // $('#btnAccountSave').css('display', 'none');
                // $('#btnAccountUpdate').css('display', '');
                $('#txtMeetingProspectID').val(resp.data.id);
                // $('#txtMeetingLocation').val(resp.data.location);
                contacts = resp.data.contacts ;
                $('#cboContactName').html(resp.data.contact_options);
                $('#cboContactName').val(resp.data.person_id);
            } else {
                contacts = [];
                clearMeetingForm();
                controlMeetingForm(true);
                $('#txtMeetingName').val('');
                swal.fire('System Warning', 'Account not found. Please create an account to proceed.', 'warning');
                return;
            }
        }
	}else{
		swal.fire('System Warning', resp.mesg, 'warning');
    }
}

function clearMeetingForm(){
    $('#txtMeetingID').val('');
    $('#txtMeetingName').val('');
    $('#cboContactName').html('');
    // display contact name placeholder
    $('#cboContactName').append('<option value="" disabled selected>Contact Name</option>');
    $('#txtMeetingPhone').val('');
    $('#txtMeetingEmail').val('');
    $('#txtMeetingLocation').val('');
    $('#txtMeetingDate').val('');
    $('#txtMeetingTime').val('');
    $('#txtMeetingConversation').val('');
    $('#cobMeetingStatus').val("");
    $('#txtMeetingFollowUpLocation').val('');
    $('#txtMeetingFollowUpDate').val('');
    $('#txtMeetingFollowUpTime').val('');
    $('#txtMeetingNextAction').val('');

    $('#txtMeetingProspectID').val('');
    $('#txtMeetingContactID').val('');
    $('#txtMeetingPersonID').val('');
    $('#txtMeetingConversationID').val('');

    $('#btnMeetingSave').css("display", "");
    $('#btnMeetingUpdate').css("display", "none");
    $('#btnStartMeeting').prop('disabled', false);
    $('#btnStartMeeting').html('Start Meeting');

    $('#followUpSection').css('display', 'none');
    contacts = [] ;

    $('#txtMeetingInsertToCalendar').val('');
    $('#txtMeetingReminderDays').val('');

    $('#txtMeetingInsertToCalendar').prop('checked', false);
    $('#cboMeetingReminder').val('');
    $('#divMeetingAttachments').html('');

}

function controlMeetingForm(disabled=false){
    $('#cboContactName').prop('disabled', disabled);
    $('#txtMeetingPhone').prop('disabled', disabled);
    $('#txtMeetingEmail').prop('disabled', disabled);
    $('#txtMeetingLocation').prop('disabled', disabled);
    // $('#txtMeetingDate').prop('disabled', disabled);
    // $('#txtMeetingTime').prop('disabled', disabled);
    $('#txtMeetingConversation').prop('disabled', disabled);
    $('#cobMeetingStatus').prop('disabled', disabled);
    $('#txtMeetingFollowUpLocation').prop('disabled', disabled);
    $('#txtMeetingFollowUpDate').prop('disabled', disabled);
    $('#txtMeetingFollowUpTime').prop('disabled', disabled);
    $('#txtMeetingNextAction').prop('disabled', disabled);

    $('#btnMeetingSave').prop("disabled", disabled);
    $('#btnMeetingUpdate').prop("disabled", disabled);
    // $('#btnStartMeeting').prop('disabled', disabled);
}

function getAutoSearch(type) {
    var data = { "type": type};
    var url = "request.pzx?c=" + meeting_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onAutoSearch, null);
}

function onAutoSearch(obj, resp) {
    if (resp.status == C_OK) {
        if (resp.data != null && resp.data.length != 0) {
            var filteredAutoSearch = resp.data;
            if (resp.type == "ACCOUNT_NAME_SEARCH") {
                $('#txtMeetingName').autocomplete({
                    source: filteredAutoSearch,
                    minLength: 1,
                    autoFocus: true
                });
            }
        }
    }
}

function changeAccountName() {
    $('#txtMeetingPhone').val('');
    $('#txtMeetingEmail').val('');
    // $('#txtMeetingPersonID').val('');
    // $('#txtMeetingContactID').val('');
    // $('#txtMeetingConversationID').val('');
    
    var data = {
        "type": "GET_ACCOUNT_INFO",
        "account_name" : $('#txtMeetingName').val(),
        "person_id" : $('#txtMeetingPersonID').val(),
    }
    var url = "request.pzx?c=" + meeting_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onResponseMeeting, null);
}

function changeContactName() {
    var person_id = $('#cboContactName').val();
    if(person_id != ""){
        for(var i=0; i<contacts.length; i++){
            if(contacts[i].person_id == person_id){
                $('#txtMeetingPhone').val(contacts[i].phone);
                $('#txtMeetingEmail').val(contacts[i].email);
                $('#txtMeetingPersonID').val(contacts[i].person_id);
                $('#txtMeetingContactID').val(contacts[i].contact_id);
                break;
            }
        }
    }
}

function startMeeting(isNow=true, date=null, time=null) {
    if(isNow){
        $today = new Date();
    } else {
        if (date == null) {
            date = $today.getFullYear() + '-' + String($today.getMonth() + 1).padStart(2, '0') + '-' + String($today.getDate()).padStart(2, '0');
        }
        if (time == null) {
            time = String($today.getHours()).padStart(2, '0') + ':' + String($today.getMinutes()).padStart(2, '0');
        }
        $today = new Date(date + 'T' + time);
    }

    var day = String($today.getDate()).padStart(2, '0');
    var month = String($today.getMonth() + 1).padStart(2, '0'); //January is 0!
    var year = $today.getFullYear();
    var todayDate = year + '-' + month + '-' + day;
    $('#txtMeetingDate').val(todayDate);

    var hours = String($today.getHours()).padStart(2, '0');
    var minutes = String($today.getMinutes()).padStart(2, '0');
    var currentTime = hours + ':' + minutes;
    // Convert to 12-hour format with AM/PM
    var ampm = 'AM';
    var hourInt = parseInt(hours);  // Convert hours to integer
    if (hourInt > 12) {
        hourInt -= 12;
        ampm = 'PM';
    } else if (hourInt === 0) {
        hourInt = 12;
    } else if (hourInt === 12) {
        ampm = 'PM';
    }
    var meetingTime = hourInt + ':' + minutes + ' ' + ampm;
    if (minutes < 10) {
        meetingTime = hourInt + ':' + minutes + ' ' + ampm;
    }
    $('#txtMeetingTime').val(currentTime);

    $('#btnStartMeeting').prop('disabled', true);
    $('#btnStartMeeting').html('Start Time: ' + meetingTime);
}

/**
 * Start a new meeting using data from a history item.
 * This will load the Meeting view and pre-fill follow-up and conversation fields.
 * @param {number} prospect_id
 * @param {number} person_id
 * @param {number} conversation_id
 * @param {number} contact_id
 * @param {string} next_action
 * @param {string} action_location
 * @param {string} action_date
 * @param {string} action_time
 */
function startMeetingFromHistory(prospect_id, person_id, conversation_id, contact_id) {
    // Load the Meeting view into the center panel then populate fields
    var url = "index.pzx?c=" + meeting_url + "&d=" + new Date().getTime();
    // Use jQuery load with a callback so we populate after the view HTML and scripts are inserted
    $("#sbg-center-panel").load(url, { type: 'v' }, function() {
        try {
            // set hidden ids
            $('#txtMeetingProspectID').val(prospect_id);
            $('#txtMeetingPersonID').val(person_id);
            $('#txtMeetingContactID').val(contact_id);
            // new conversation
            $('#txtMeetingConversationID').val('');

            // populate follow up and next action
            $('#txtMeetingFollowUpLocation').val(action_location || '');
            if (action_date) $('#txtMeetingFollowUpDate').val(action_date);
            if (action_time) $('#txtMeetingFollowUpTime').val(action_time);
            $('#txtMeetingNextAction').val(next_action || '');

            // Put next_action and follow up location into conversation textarea as initial conversation
            var conv = (next_action || '');
            if (action_location) conv += '\nLocation: ' + action_location;
            $('#txtMeetingConversation').val(conv);

            // ensure save button is visible (creating new meeting)
            $('#btnMeetingSave').css('display', '');
            $('#btnMeetingUpdate').css('display', 'none');

            // if contacts for the prospect are preloaded, try to select the contact person
            if ($('#cboContactName option').length > 0 && person_id) {
                $('#cboContactName').val(person_id);
                $('#cboContactName').trigger('change');
            }
        } catch (e) {
            console.error('startMeetingFromHistory error', e);
        }
    });
}

function showReminder(){
    if($('#cobMeetingStatus').val() == 0 || $('#cobMeetingStatus').val() == 1){ // 0 = Follow up, 1 = Confirmed
        $('#cboMeetingReminder').css('display', 'inline');
    } else {
        $('#cboMeetingReminder').css('display', 'none');
    }
}

function downloadICS() {
    if ($('#cboMeetingReminder').val()=="0"){
        $('#cboMeetingReminder').focus() ;
        swal.fire('System Warning', 'Please select a reminder duration.', 'warning') ;
        return;
    }
    
    // Collect meeting information from form
    var summary = $('#txtMeetingName').val() || 'Meeting';
    var description = $('#txtMeetingNextAction').val() || '';
    var location = $('#txtMeetingFollowUpLocation').val() || '';
    var meetingDate = $('#txtMeetingFollowUpDate').val() || '';
    var meetingTime = $('#txtMeetingFollowUpTime').val() || '';
    var contactName = $('#cboContactName').find("option:selected").text();
    var contactEmail = $('#txtMeetingEmail').val() || '';
    var contactPhone = $('#txtMeetingPhone').val() || '';
    
    // Validate required fields
    if (!meetingDate || !meetingTime) {
        swal.fire('System Warning', 'Please set a meeting date and time.', 'warning');
        return;
    }
    
    // Format date and time for iCalendar format (YYYYMMDDTHHMMSSZ)
    var dateParts = meetingDate.split('-');
    var timeParts = meetingTime.split(':');
    var hours = String(timeParts[0]).padStart(2, '0');
    var minutes = String(timeParts[1]).padStart(2, '0');
    // Use floating local time (no trailing Z) so calendar apps interpret as local time
    var startDateTime = dateParts[0] + dateParts[1] + dateParts[2] + 'T' + hours + minutes + '00';
    
    // Set end time 1 hour after start time
    var endHour = String(parseInt(hours) + 1).padStart(2, '0');
    var endDateTime = dateParts[0] + dateParts[1] + dateParts[2] + 'T' + endHour + minutes + '00';
    
    // Generate unique identifier
    var uid = 'meeting-' + new Date().getTime() + '@aopcloud.local';
    
    // Create description with contact info
    var fullDescription = description;
    if (contactName) fullDescription += '\nX-CONTACT: ' + contactName;
    if (contactPhone) fullDescription += '\nX-PHONE: ' + contactPhone;
    if (contactEmail) fullDescription += '\nX-EMAIL: ' + contactEmail;

    // Set reminder to alert user 15 minutes before meeting
    // (This can be customized as needed)
    var reminderMinutes = $('#cboMeetingReminder').val() || 15;
    
    // Calculate reminder date and time
    switch(reminderMinutes) {
        case '1': // 1 day
            reminderMinutes = 1440;
            break;
        case '3': // 3 days
            reminderMinutes = 4320;
            break;
        case '7': // 7 days
            reminderMinutes = 10080;
            break;
        default: // 1 day
            reminderMinutes = 1440;
            break;
    }
    // var reminderDateTime = new Date(new Date(startDateTime).getTime() - (reminderMinutes * 60 * 1000)).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
    
    // Build iCalendar content
    var ics = 'BEGIN:VCALENDAR\r\n';
    ics += 'VERSION:2.0\r\n';
    ics += 'PRODID:-//AOPClouds App//EN\r\n';
    ics += 'CALSCALE:GREGORIAN\r\n';
    ics += 'METHOD:PUBLISH\r\n';
    ics += 'BEGIN:VEVENT\r\n';
    ics += 'UID:' + uid + '\r\n';
    ics += 'DTSTAMP:' + new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '') + '\r\n';
    ics += 'DTSTART:' + startDateTime + '\r\n';
    ics += 'DTEND:' + endDateTime + '\r\n';    
    ics += 'SUMMARY:' + summary + '\r\n';
    ics += 'DESCRIPTION:' + fullDescription.replace(/\r\n/g, '\\n') + '\r\n';
    ics += 'LOCATION:' + location + '\r\n';
    if (contactEmail) {
        ics += 'ATTENDEE;CN=' + contactName + ';RSVP=TRUE:mailto:' + contactEmail + '\r\n';
    }
    ics += 'STATUS:CONFIRMED\r\n';
    ics += 'SEQUENCE:0\r\n';
    ics += 'BEGIN:VALARM\r\n';
    ics += 'TRIGGER:-PT' + reminderMinutes + 'M\r\n';
    ics += 'ACTION:DISPLAY\r\n';
    ics += 'DESCRIPTION:Meeting Reminder\r\n';
    ics += 'END:VALARM\r\n';
    ics += 'END:VEVENT\r\n';
    ics += 'END:VCALENDAR\r\n';
    
    // Download the file
    var blob = new Blob([ics], { type: 'text/calendar;charset=utf-8' });
    var link = document.createElement('a');
    var url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', 'meeting-' + meetingDate + '-' + meetingTime + '-' + contactName + '.ics');
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

function changeAttachment(obj) {
    upload_form = obj ;
}

function onUploadEnd(resp) {
	$('#setting_upload').hide() ;
	$('#btnCompanyLogoUpload').prop('disabled','');
	var s = resp.split("|") ;
	if (s[0]==C_OK) {
        m_filename = s[1] ;
        m_filedoc = s[2] ;

        // Append newly uploaded temp file to attachments list so user sees it immediately
        try{
            var displayName = m_filename;
                // Newly uploaded files are stored in temp until the meeting is saved, link to temp
                var filePath = '../doc/temp/' + m_filedoc;
            var li = '<li class="list-group-item d-flex justify-content-between align-items-center" style="padding: 0px !important;" data-filedoc="' + m_filedoc + '">'
                    + '<div><a href="' + filePath + '" target="_blank">' + displayName + '</a></div>'
                    + '<div>'
                    + '<button type="button" class="btn btn-sm btn-outline-danger ms-2" onclick="deleteMeetingAttachment(0, null, this);"><i class="bi bi-trash"></i></button>'
                    + '</div>'
                    + '</li>';
            // if no attachment, add the first one
            if ($('#divMeetingAttachments').children().length == 0) {
                $('#divMeetingAttachments').html();
            }
            $('#divMeetingAttachments').append(li);
        } catch (e) {
            console.error('Error appending uploaded attachment', e);
        }
	} else {
		swal.fire('System Warning',s[1],"warning") ;
	}
}

function uploadMeetingAttchment() {
    var id_prospect = $('#txtMeetingProspectID').val() ;
    var id_conv = $('#txtMeetingConversationID').val() ;
	var fn = $('#txtMeetingAttachment').val() ;
	if (validImageExt(fn)) {
		var url = "upload.pzx?t=f&n=txtMeetingAttachment&id=" + id_prospect + "&idconv=" + id_conv + "&d=" + new Date().getTime();
		$('#setting_upload').show() ;
		uploaded = false ;
		ajaxUpload(upload_form,url,onUploadEnd);
	}
}

function validImageExt(file) 
{
	var extArray = new Array(".doc", ".docx", ".xls", ".xlsx", ".pdf", ".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 .doc, .docx, .xls, .xlsx, .pdf, .png, .jpg, .jpeg format', 'warning') ;
		return false ;
	}
}

function deleteMeetingAttachment(prospect_id, filedoc, btn){
    swal.fire({
        title: 'Confirm delete',
        text: 'Are you sure you want to delete this attachment?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Delete',
        cancelButtonText: 'Cancel'
    }).then(function(result){
        if(result.isConfirmed){
            // if filedoc not provided, try to read from DOM (li data-filedoc)
            try{
                if (!filedoc || filedoc == null) {
                    var $li = $(btn).closest('li');
                    filedoc = $li.data('filedoc');
                }
            } catch(e){
                console.error('Failed to resolve filedoc from DOM', e);
            }

            var data = {
                type: 'DELETE_ATTACHMENT',
                prospect_id: prospect_id || 0,
                filedoc: filedoc
            };
            var url = "request.pzx?c=" + meeting_url + "&d=" + new Date().getTime();
            callServer(url, "json", data, onDeleteAttachment, null);
        }
    });
}

function onDeleteAttachment(){
    if (resp.status == C_OK) {
        var fd = resp.data.filedoc;
        // remove matching list item
        try{
            var selector = 'li[data-filedoc="' + fd + '"]';
            $(selector).remove();
        } catch(e){
            console.error('Error removing attachment element', e);
        }
        swal.fire('Success', resp.mesg, 'success');
    } else {
        swal.fire('System Warning', resp.mesg, 'warning');
    }
    m_filedoc = "";
    m_filename = "";
}