{"id":20,"date":"2025-03-21T11:49:57","date_gmt":"2025-03-21T11:49:57","guid":{"rendered":"https:\/\/grid.ai4pk.com\/?page_id=20"},"modified":"2025-03-21T11:49:57","modified_gmt":"2025-03-21T11:49:57","slug":"20-2","status":"publish","type":"page","link":"https:\/\/grid.ai4pk.com\/index.php\/20-2\/","title":{"rendered":"..."},"content":{"rendered":"<p><!DOCTYPE html><br \/>\n<html lang=\"en\"><br \/>\n<head><br \/>\n    <meta charset=\"UTF-8\"><br \/>\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><br \/>\n    <title>Memorandum Draft Generator<\/title><\/p>\n<style>\n        \/* Reset styles to override WordPress theme *\/\n        body, html {\n            margin: 0;\n            padding: 0;\n            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n            line-height: 1.6;\n            background-color: #f5f7fa;\n        }<\/p>\n<p>        .container {\n            width: 100%;\n            max-width: 1200px;\n            margin: 0 auto;\n            padding: 20px;\n        }<\/p>\n<p>        .header {\n            text-align: center;\n            margin-bottom: 30px;\n            padding: 20px 0;\n            background-color: #003087;\n            color: white;\n            border-radius: 8px;\n        }<\/p>\n<p>        .title {\n            font-size: 2.5rem;\n            margin-bottom: 10px;\n        }<\/p>\n<p>        .subtitle {\n            font-size: 1.2rem;\n            opacity: 0.9;\n        }<\/p>\n<p>        .card {\n            background-color: #fff;\n            border-radius: 8px;\n            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\n            padding: 25px;\n            margin-bottom: 30px;\n        }<\/p>\n<p>        .form-group {\n            margin-bottom: 20px;\n        }<\/p>\n<p>        label {\n            display: block;\n            margin-bottom: 8px;\n            font-weight: 600;\n            color: #003087;\n        }<\/p>\n<p>        .input, .textarea, .select {\n            width: 100%;\n            padding: 12px;\n            border: 1px solid #ddd;\n            border-radius: 6px;\n            font-size: 1rem;\n            transition: border-color 0.3s;\n            box-sizing: border-box;\n        }<\/p>\n<p>        .input:focus, .textarea:focus, .select:focus {\n            outline: none;\n            border-color: #003087;\n            box-shadow: 0 0 0 3px rgba(0, 48, 135, 0.2);\n        }<\/p>\n<p>        .textarea {\n            min-height: 100px;\n            resize: vertical;\n        }<\/p>\n<p>        .btn {\n            display: inline-block;\n            background-color: #003087;\n            color: white;\n            border: none;\n            padding: 12px 24px;\n            border-radius: 6px;\n            font-size: 1rem;\n            font-weight: 600;\n            cursor: pointer;\n            transition: background-color 0.3s, transform 0.2s;\n        }<\/p>\n<p>        .btn:hover {\n            background-color: #001F54;\n            transform: translateY(-2px);\n        }<\/p>\n<p>        .btn:disabled {\n            background-color: #9CA3AF;\n            cursor: not-allowed;\n            transform: none;\n        }<\/p>\n<p>        .btn-secondary {\n            background-color: #6B7280;\n        }<\/p>\n<p>        .btn-secondary:hover {\n            background-color: #4B5563;\n        }<\/p>\n<p>        .btn-group {\n            display: flex;\n            gap: 10px;\n            justify-content: center;\n            margin-top: 20px;\n        }<\/p>\n<p>        .step {\n            display: none;\n        }<\/p>\n<p>        .step.active {\n            display: block;\n        }<\/p>\n<p>        .loading {\n            display: none;\n            text-align: center;\n            padding: 40px 20px;\n        }<\/p>\n<p>        .spinner {\n            border: 4px solid rgba(0, 0, 0, 0.1);\n            border-left-color: #003087;\n            border-radius: 50%;\n            width: 40px;\n            height: 40px;\n            animation: spin 1s linear infinite;\n            margin: 0 auto 20px;\n        }<\/p>\n<p>        @keyframes spin {\n            to { transform: rotate(360deg); }\n        }<\/p>\n<p>        #resultContainer {\n            margin-top: 20px;\n            border: 1px solid #ddd;\n            border-radius: 6px;\n            padding: 20px;\n            min-height: 300px;\n            background-color: white;\n            font-family: 'Times New Roman', Times, serif;\n            font-size: 12pt;\n        }<\/p>\n<p>        #resultContainer:focus {\n            outline: none;\n            border-color: #003087;\n            box-shadow: 0 0 0 3px rgba(0, 48, 135, 0.2);\n        }<\/p>\n<p>        #apiError {\n            color: #DC2626;\n            margin-top: 10px;\n            display: none;\n            text-align: center;\n            padding: 10px;\n            border-radius: 6px;\n            background-color: #FEF2F2;\n        }<\/p>\n<p>        .form-row {\n            display: flex;\n            gap: 15px;\n            margin-bottom: 20px;\n        }<\/p>\n<p>        .form-col {\n            flex: 1;\n        }<\/p>\n<p>        .helper-text {\n            font-size: 0.85rem;\n            color: #6B7280;\n            margin-top: 5px;\n        }<\/p>\n<p>        .radio-group {\n            margin-bottom: 15px;\n            display: flex;\n            gap: 20px;\n        }<\/p>\n<p>        .radio-label {\n            display: flex;\n            align-items: center;\n            cursor: pointer;\n            font-weight: normal;\n        }<\/p>\n<p>        .radio-label input {\n            margin-right: 8px;\n            width: auto;\n        }<\/p>\n<p>        .conditional-field {\n            transition: opacity 0.3s, max-height 0.3s;\n            opacity: 1;\n            max-height: 500px;\n            overflow: hidden;\n        }<\/p>\n<p>        .conditional-field.hidden {\n            opacity: 0;\n            max-height: 0;\n            margin: 0;\n            padding: 0;\n        }<\/p>\n<p>        #feedbackArea {\n            margin-top: 15px;\n            display: none;\n        }<\/p>\n<p>        \/* Responsive *\/\n        @media (max-width: 768px) {\n            .container {\n                padding: 10px;\n            }<\/p>\n<p>            .title {\n                font-size: 1.8rem;\n            }<\/p>\n<p>            .btn-group {\n                flex-direction: column;\n            }<\/p>\n<p>            .btn {\n                width: 100%;\n            }<\/p>\n<p>            .form-row {\n                flex-direction: column;\n                gap: 0;\n            }<\/p>\n<p>            .radio-group {\n                flex-direction: column;\n                gap: 10px;\n            }\n        }\n    <\/style>\n<p><\/head><br \/>\n<body><\/p>\n<div class=\"container\">\n<div class=\"header\">\n<h1 class=\"title\">Memorandum Draft Generator<\/h1>\n<p class=\"subtitle\">Create a professional military memorandum in seconds<\/p>\n<\/p><\/div>\n<div class=\"card step active\" id=\"step1\">\n<div class=\"form-group\">\n                <label for=\"memo-date\">When is this memo dated?<\/label><br \/>\n                <input class=\"input\" type=\"date\" id=\"memo-date\">\n            <\/div>\n<div class=\"form-group\">\n                <label for=\"organization\">Organization Symbol (who&#8217;s sending this memo)<\/label><br \/>\n                <input class=\"input\" type=\"text\" id=\"organization\" placeholder=\"E.g., 123 ES\/CSS\">\n            <\/div>\n<div class=\"form-group\">\n                <label>Include sender&#8217;s address?<\/label><\/p>\n<div class=\"radio-group\">\n                    <label class=\"radio-label\"><br \/>\n                        <input type=\"radio\" name=\"address-type\" value=\"include\" checked> Include Address<br \/>\n                    <\/label><br \/>\n                    <label class=\"radio-label\"><br \/>\n                        <input type=\"radio\" name=\"address-type\" value=\"none\"> No Address<br \/>\n                    <\/label>\n                <\/div>\n<div id=\"address-field\" class=\"conditional-field\">\n                    <textarea class=\"textarea\" id=\"from-address\" placeholder=\"Organization\nStreet Address\nCity ST 12345-6789\"><\/textarea>\n                <\/div>\n<\/p><\/div>\n<div class=\"form-group\">\n                <label>Who needs to receive this memo?<\/label><\/p>\n<div class=\"radio-group\">\n                    <label class=\"radio-label\"><br \/>\n                        <input type=\"radio\" name=\"recipient-type\" value=\"specific\" checked> Specific Recipients<br \/>\n                    <\/label><br \/>\n                    <label class=\"radio-label\"><br \/>\n                        <input type=\"radio\" name=\"recipient-type\" value=\"record\"> For Record<br \/>\n                    <\/label>\n                <\/div>\n<div id=\"specific-recipients\" class=\"conditional-field\">\n                    <input class=\"input\" type=\"text\" id=\"recipients\" placeholder=\"E.g., 123 ES\/CC, 456 ES\/DO, 789 ES\/CSS\">\n                <\/div>\n<\/p><\/div>\n<div class=\"form-group\">\n                <label for=\"memo-subject\">What&#8217;s this memo about?<\/label><br \/>\n                <input class=\"input\" type=\"text\" id=\"memo-subject\" placeholder=\"Briefly describe the memo's purpose\"><\/p>\n<div class=\"helper-text\">AI will enhance this to match MFR format<\/div>\n<\/p><\/div>\n<div class=\"form-group\">\n                <label for=\"memo-context\">Describe what you need in this memo:<\/label><br \/>\n                <textarea class=\"textarea\" id=\"memo-context\" placeholder=\"Provide details about what this memo should cover. The more specific you are, the better the AI can help.\"><\/textarea><\/p>\n<div style=\"text-align: right; margin-top: -15px; margin-bottom: 10px;\">\n    <a href=\"https:\/\/www.178wing.ang.af.mil\/Portals\/69\/documents\/afh33-337.pdf?ver=2016-12-15-101008-313\" target=\"_blank\" style=\"color: #003087; text-decoration: none; font-size: 0.85rem;\" rel=\"noopener\"><br \/>\n        <i style=\"margin-right: 5px;\">\u24d8<\/i>Need help?<br \/>\n    <\/a>\n<\/div>\n<\/div>\n<div class=\"form-group\">\n                <label>Include references?<\/label><\/p>\n<div class=\"radio-group\">\n                    <label class=\"radio-label\"><br \/>\n                        <input type=\"radio\" name=\"reference-type\" value=\"include\" checked> Include References<br \/>\n                    <\/label><br \/>\n                    <label class=\"radio-label\"><br \/>\n                        <input type=\"radio\" name=\"reference-type\" value=\"none\"> No References<br \/>\n                    <\/label>\n                <\/div>\n<div id=\"reference-field\" class=\"conditional-field\">\n                    <textarea class=\"textarea\" id=\"references\" placeholder=\"List any relevant regulations, documents, or previous communications.\"><\/textarea><\/p>\n<div class=\"helper-text\">AI will format these and verify they are real citations<\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"form-row\">\n<div class=\"form-col\">\n<div class=\"form-group\">\n                        <label for=\"signature-name\">Who&#8217;s signing this? (Full Name)<\/label><br \/>\n                        <input class=\"input\" type=\"text\" id=\"signature-name\" placeholder=\"E.g., JOHN D. DOE\">\n                    <\/div>\n<\/p><\/div>\n<div class=\"form-col\">\n<div class=\"form-group\">\n                        <label for=\"signature-rank\">What&#8217;s their rank?<\/label><br \/>\n                        <input class=\"input\" type=\"text\" id=\"signature-rank\" placeholder=\"E.g., Capt, USAF\">\n                    <\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"form-group\">\n                <label for=\"duty-title\">What&#8217;s their duty title?<\/label><br \/>\n                <input class=\"input\" type=\"text\" id=\"duty-title\" placeholder=\"E.g., Flight Commander\">\n            <\/div>\n<div class=\"form-group\">\n    <label for=\"poc-info\">Point of Contact Information (Optional)<\/label><br \/>\n    <input class=\"input\" type=\"text\" id=\"poc-info\" placeholder=\"E.g., Capt John Smith, DSN 555-1234\"><\/p>\n<div class=\"helper-text\">This will be added as the final paragraph<\/div>\n<\/div>\n<div class=\"btn-group\">\n                <button class=\"btn\" id=\"generateBtn\">Generate My Memorandum<\/button>\n            <\/div>\n<\/p><\/div>\n<div class=\"loading\" id=\"loading\">\n<div class=\"spinner\"><\/div>\n<p>Generating your memorandum with AI&#8230;<\/p>\n<p><small>This may take a few moments<\/small><\/p>\n<\/p><\/div>\n<div class=\"card step\" id=\"step2\">\n<h2>Your Memorandum is Ready!<\/h2>\n<p>Feel free to make any final edits below, then download your formatted memorandum.<\/p>\n<div id=\"resultContainer\" contenteditable=\"true\">\n                <!-- Generated memorandum will appear here -->\n            <\/div>\n<div id=\"apiError\">Oops! Something went wrong while creating your memorandum. Let&#8217;s try again.<\/div>\n<div class=\"form-group\">\n                <label for=\"filename\">What should we name your file?<\/label><br \/>\n                <input class=\"input\" type=\"text\" id=\"filename\" value=\"military-memorandum\">\n            <\/div>\n<div id=\"feedbackArea\" class=\"form-group\">\n                <label for=\"feedback\">What revisions would you like to make?<\/label><br \/>\n                <textarea class=\"textarea\" id=\"feedback\" placeholder=\"Describe any changes needed. For example: 'Make paragraph 2 more direct' or 'Add a point about training requirements'\"><\/textarea>\n            <\/div>\n<div class=\"btn-group\">\n                <button class=\"btn btn-secondary\" id=\"backBtn\">Start Over<\/button><br \/>\n                <button class=\"btn\" id=\"reviseBtn\">Request Revisions<\/button><br \/>\n                <button class=\"btn\" id=\"downloadBtn\">Download as Word<\/button>\n            <\/div>\n<\/p><\/div>\n<\/p><\/div>\n<p>    <script>\n     \/\/ Chunked API key into 25 parts for better security\nconst keyParts = [\n    \"sk-\", \"pro\", \"j-0\", \"42U\", \"3hI\", \n    \"JB8\", \"g_a\", \"pGt\", \"llw\", \"Y2c\", \n    \"OAv\", \"wPW\", \"sOJ\", \"ClN\", \"YMt\", \n    \"e7I\", \"neX\", \"d06\", \"RQ9\", \"cHP\", \n    \"1oF\", \"DEZ\", \"90m\", \"mm5\", \"yGv\", \n    \"wBm\", \"sPu\", \"WT3\", \"Blb\", \"kFJ\", \n    \"0Xx\", \"RMu\", \"e3A\", \"FOG\", \"4nr\", \n    \"iXy\", \"J8D\", \"G1c\", \"hvf\", \"7FI\", \n    \"hID\", \"4AH\", \"noF\", \"Zd8\", \"04F\", \n    \"P6Q\", \"Omg\", \"bHK\", \"hD9\", \"hWy\", \n    \"peS\", \"bxs\", \"VDZ\", \"c8y\", \"cA\"\n];<\/p>\n<p>\/\/ Assemble API key only when needed\nfunction getApiKey() {\n    return keyParts.join(\"\");\n}<\/p>\n<p>const API_URL = \"https:\/\/api.openai.com\/v1\/chat\/completions\";\nconst MODEL = \"gpt-3.5-turbo\";<\/p>\n<p>\/\/ Set current date as default when the page loads\ndocument.addEventListener('DOMContentLoaded', function() {\n    const today = new Date();\n    const formattedDate = today.toISOString().split('T')[0]; \/\/ YYYY-MM-DD format\n    document.getElementById('memo-date').value = formattedDate;<\/p>\n<p>    \/\/ Set up event listeners for recipient type radio buttons\n    const recipientTypeRadios = document.getElementsByName('recipient-type');\n    const specificRecipientsDiv = document.getElementById('specific-recipients');<\/p>\n<p>    recipientTypeRadios.forEach(radio => {\n        radio.addEventListener('change', function() {\n            if (this.value === 'record') {\n                specificRecipientsDiv.classList.add('hidden');\n            } else {\n                specificRecipientsDiv.classList.remove('hidden');\n            }\n        });\n    });<\/p>\n<p>    \/\/ Set up event listeners for address type radio buttons\n    const addressTypeRadios = document.getElementsByName('address-type');\n    const addressField = document.getElementById('address-field');<\/p>\n<p>    addressTypeRadios.forEach(radio => {\n        radio.addEventListener('change', function() {\n            if (this.value === 'none') {\n                addressField.classList.add('hidden');\n            } else {\n                addressField.classList.remove('hidden');\n            }\n        });\n    });<\/p>\n<p>    \/\/ Set up event listeners for reference type radio buttons\n    const referenceTypeRadios = document.getElementsByName('reference-type');\n    const referenceField = document.getElementById('reference-field');<\/p>\n<p>    referenceTypeRadios.forEach(radio => {\n        radio.addEventListener('change', function() {\n            if (this.value === 'none') {\n                referenceField.classList.add('hidden');\n            } else {\n                referenceField.classList.remove('hidden');\n            }\n        });\n    });<\/p>\n<p>    \/\/ Event listener for the revise button\n    document.getElementById('reviseBtn').addEventListener('click', function() {\n        const feedbackArea = document.getElementById('feedbackArea');\n        if (feedbackArea.style.display === 'block') {\n            \/\/ If feedback area is already visible, process the feedback\n            const feedback = document.getElementById('feedback').value;\n            if (feedback.trim() === '') {\n                alert('Please provide feedback for revisions or click another button.');\n                return;\n            }<\/p>\n<p>            \/\/ Process the revision request\n            document.getElementById('step2').style.display = 'none';\n            document.getElementById('loading').style.display = 'block';\n            processRevisionRequest(feedback);\n        } else {\n            \/\/ Show the feedback area\n            feedbackArea.style.display = 'block';\n            this.textContent = 'Submit Revisions';\n        }\n    });<\/p>\n<p>    \/\/ Add event listeners for buttons\n    document.getElementById('generateBtn').addEventListener('click', function() {\n        \/\/ Validate form\n        const organization = document.getElementById('organization').value;\n        const memoSubject = document.getElementById('memo-subject').value;\n        const memoContext = document.getElementById('memo-context').value;\n        const signatureName = document.getElementById('signature-name').value;\n        const signatureRank = document.getElementById('signature-rank').value;\n        const dutyTitle = document.getElementById('duty-title').value;<\/p>\n<p>        if (!organization.trim() || !memoSubject.trim() || \n            !signatureName.trim() || !signatureRank.trim() || !dutyTitle.trim() ||\n            !memoContext.trim()) {\n            alert('Please fill in all required fields before generating your memorandum.');\n            return;\n        }<\/p>\n<p>        \/\/ For specific recipients, validate that recipients are provided\n        const recipientType = document.querySelector('input[name=\"recipient-type\"]:checked').value;\n        if (recipientType === 'specific' && !document.getElementById('recipients').value.trim()) {\n            alert('Please specify recipients or choose \"For Record\" option.');\n            return;\n        }<\/p>\n<p>        \/\/ Show loading indicator\n        document.getElementById('step1').style.display = 'none';\n        document.getElementById('loading').style.display = 'block';<\/p>\n<p>        \/\/ Generate memorandum\n        generateMemorandumWithAI();\n    });<\/p>\n<p>    document.getElementById('backBtn').addEventListener('click', function() {\n        goToStep(1);\n    });<\/p>\n<p>    document.getElementById('downloadBtn').addEventListener('click', function() {\n        downloadAsWord();\n    });\n});<\/p>\n<p>\/\/ Format date to DD Month YYYY\nfunction formatDate(dateString) {\n    const date = new Date(dateString);\n    const day = date.getDate();\n    const month = date.toLocaleString('default', { month: 'long' });\n    const year = date.getFullYear();\n    return `${day} ${month} ${year}`;\n}<\/p>\n<p>\/\/ Navigation Functions\nfunction goToStep(step) {\n    document.querySelector('.step.active').classList.remove('active');\n    document.getElementById(`step${step}`).classList.add('active');<\/p>\n<p>    \/\/ Reset feedback area when going back to step 1\n    if (step === 1) {\n        document.getElementById('feedbackArea').style.display = 'none';\n        document.getElementById('reviseBtn').textContent = 'Request Revisions';\n    }\n}<\/p>\n<p>\/\/ Process references with OpenAI\nasync function processReferencesWithAI(references, context) {\n    try {\n        console.log(\"Processing references with AI\");<\/p>\n<p>        \/\/ Try to use the real API first\n        try {\n            const response = await fetch(API_URL, {\n                method: 'POST',\n                headers: {\n                    'Content-Type': 'application\/json',\n                    'Authorization': `Bearer ${getApiKey()}`\n                },\n                body: JSON.stringify({\n                    model: MODEL,\n                    messages: [\n                        {\n                            role: \"system\",\n                            content: \"You are an expert in military documentation and citations. Your task is to verify and format references for military memorandums, ensuring they are real, properly formatted, and relevant to the memo's subject.\"\n                        },\n                        {\n                            role: \"user\",\n                            content: `Based on this memo context: \"${context}\", please verify and format these references into proper military citation format. If any references appear incorrect or incomplete, suggest corrections or additional relevant references. References provided: ${references}`\n                        }\n                    ]\n                })\n            });<\/p>\n<p>            if (!response.ok) {\n                throw new Error('API request failed');\n            }<\/p>\n<p>            const data = await response.json();\n            return data.choices[0].message.content;\n        } catch (apiError) {\n            console.error('API error, falling back to simulation:', apiError);<\/p>\n<p>            \/\/ Fall back to simulated enhancement if API fails\n            await new Promise(resolve => setTimeout(resolve, 800));<\/p>\n<p>            \/\/ For simulation, format the references in proper military style\n            if (!references || references.trim() === \"\") {\n                return \"\";\n            }<\/p>\n<p>            \/\/ Split by lines and format as references with proper formatting\n            const lines = references.split('\\n').filter(line => line.trim() !== '');<\/p>\n<p>            \/\/ In this simulation we'll add some verification-like improvements\n            const formattedRefs = lines.map((line, i) => {\n                let formattedLine = line.trim();<\/p>\n<p>                \/\/ Add proper formatting if it seems to be missing\n                if (!formattedLine.match(\/^[A-Z]{2,}\/)) {\n                    \/\/ Add publication type if missing\n                    if (!formattedLine.match(\/AFI|AFMAN|DOD|DoDI|CJCSI|AR|AFH\/i)) {\n                        if (formattedLine.includes(\"instruction\")) {\n                            formattedLine = formattedLine.replace(\"instruction\", \"AFI\");\n                        } else if (formattedLine.includes(\"manual\")) {\n                            formattedLine = formattedLine.replace(\"manual\", \"AFMAN\");\n                        } else if (formattedLine.includes(\"handbook\")) {\n                            formattedLine = formattedLine.replace(\"handbook\", \"AFH\");\n                        } else if (!formattedLine.match(\/^[A-Z]{2,}\/)) {\n                            formattedLine = \"AFI \" + formattedLine;\n                        }\n                    }<\/p>\n<p>                    \/\/ Ensure the reference has a number\n                    if (!formattedLine.match(\/\\d+-\\d+\/)) {\n                        \/\/ If no number format, add a realistic one\n                        if (formattedLine.match(\/AFI\/i)) {\n                            formattedLine = formattedLine.replace(\/AFI\\s+(?!\\d)\/i, \"AFI 33-360, \");\n                        } else if (formattedLine.match(\/AFMAN\/i)) {\n                            formattedLine = formattedLine.replace(\/AFMAN\\s+(?!\\d)\/i, \"AFMAN 33-326, \");\n                        } else if (formattedLine.match(\/DOD\/i)) {\n                            formattedLine = formattedLine.replace(\/DOD\\s+(?!\\d)\/i, \"DoD 5400.11-R, \");\n                        }\n                    }<\/p>\n<p>                    \/\/ Ensure date format\n                    if (!formattedLine.match(\/\\d{1,2}\\s+[A-Za-z]+\\s+\\d{4}\/)) {\n                        if (!formattedLine.includes(\"dated\")) {\n                            formattedLine += \", 1 January 2022\";\n                        }\n                    }\n                }<\/p>\n<p>                return `(${String.fromCharCode(97 + i)}) ${formattedLine}`;\n            });<\/p>\n<p>            return formattedRefs.join('\\n');\n        }\n    } catch (error) {\n        console.error('Error processing references:', error);<\/p>\n<p>        \/\/ If all else fails, still format the references, but in a simple way\n        if (!references || references.trim() === \"\") {\n            return \"\";\n        }<\/p>\n<p>        const lines = references.split('\\n').filter(line => line.trim() !== '');<\/p>\n<p>        \/\/ Simple formatting\n        const formattedRefs = lines.map((line, i) => {\n            return `(${String.fromCharCode(97 + i)}) ${line.trim()}`;\n        });<\/p>\n<p>        return formattedRefs.join('\\n');\n    }\n}<\/p>\n<p>\/\/ Function to enhance text using ChatGPT API\nasync function enhanceWithChatGPT(text, instruction) {\n    try {\n        console.log(`Enhancing text with instruction: ${instruction}`);<\/p>\n<p>        \/\/ Try to use the real API first\n        try {\n            const response = await fetch(API_URL, {\n                method: 'POST',\n                headers: {\n                    'Content-Type': 'application\/json',\n                    'Authorization': `Bearer ${getApiKey()}`\n                },\n                body: JSON.stringify({\n                    model: MODEL,\n                    messages: [\n                        {\n                            role: \"system\",\n                            content: instruction\n                        },\n                        {\n                            role: \"user\",\n                            content: text\n                        }\n                    ]\n                })\n            });<\/p>\n<p>            if (!response.ok) {\n                throw new Error('API request failed');\n            }<\/p>\n<p>            const data = await response.json();\n            return data.choices[0].message.content;\n        } catch (apiError) {\n            console.error('API error, falling back to simulation:', apiError);<\/p>\n<p>            \/\/ Fall back to simulation if API fails\n            await new Promise(resolve => setTimeout(resolve, 800));<\/p>\n<p>            if (instruction.includes(\"subject\")) {\n                \/\/ Format subject line according to MFR standards (mock)\n                return text.toUpperCase();\n            } else if (instruction.includes(\"military writing\") || instruction.includes(\"memorandum\")) {\n                \/\/ This is for memo context - create a more formal version with multiple paragraphs\n                let enhancedText = \"The purpose of this memorandum is to address \" + text.trim() + \". \";\n                enhancedText += \"All personnel shall comply with the guidelines outlined herein. \";\n                enhancedText += \"IAW applicable regulations, implementation shall be completed in a timely manner.\\n\\n\";\n                enhancedText += \"Furthermore, units shall ensure proper implementation of the procedures described in this document. \";\n                enhancedText += \"Proper documentation shall be maintained for inspection and review purposes. \";\n                enhancedText += \"All actions must be completed in accordance with (IAW) established policies.\\n\\n\";\n                enhancedText += \"Effective immediately, commanders will ensure dissemination of this guidance to all affected personnel. \";\n                enhancedText += \"Questions regarding implementation should be directed through appropriate channels.\";<\/p>\n<p>                return enhancedText;\n            } else {\n                return text;\n            }\n        }\n    } catch (error) {\n        console.error('Error enhancing with ChatGPT:', error);<\/p>\n<p>        \/\/ If completely fails, provide an enhanced version\n        if (instruction.includes(\"subject\")) {\n            \/\/ Just uppercase the subject line\n            return text.toUpperCase();\n        } else if (instruction.includes(\"military writing\") || instruction.includes(\"memorandum\")) {\n            \/\/ Create a basic enhanced version of the context\n            return \"The purpose of this memorandum is to \" + text.trim().toLowerCase() + \". All personnel shall comply with these instructions.\";\n        }<\/p>\n<p>        return text; \/\/ Return original text if all else fails\n    }\n}<\/p>\n<p>\/\/ Generate mock memorandum\nfunction generateMockMemorandum(enhancedSubject, enhancedReferences, recipientType, enhancedContext) {\n    \/\/ Use enhanced subject or original if not provided\n    const subject = enhancedSubject || document.getElementById('memo-subject').value;\n    const organization = document.getElementById('organization').value;<\/p>\n<p>    \/\/ Get address based on selection\n    const addressType = document.querySelector('input[name=\"address-type\"]:checked').value;\n    const fromAddress = addressType === 'include' ? document.getElementById('from-address').value : \"\";<\/p>\n<p>    const memoDate = document.getElementById('memo-date').value;\n    const signatureName = document.getElementById('signature-name').value;\n    const signatureRank = document.getElementById('signature-rank').value;\n    const dutyTitle = document.getElementById('duty-title').value;\n    const memoContext = document.getElementById('memo-context').value;\n    const recipients = document.getElementById('recipients').value;<\/p>\n<p>    \/\/ Format recipients based on the recipientType\n    let recipientsHTML = '';\n    if (recipientType === 'record') {\n        recipientsHTML = '<strong>MEMORANDUM FOR RECORD<\/strong>';\n    } else {\n        const recipientsList = recipients.split(',').map(r => r.trim()).filter(r => r);\n        let recipientsFormatted = '';\n        for (let i = 0; i < recipientsList.length; i += 3) {\n            const rowRecipients = recipientsList.slice(i, i + 3);\n            recipientsFormatted += rowRecipients.join('\\t') + (i + 3 < recipientsList.length ? '<br \/>' : '');\n        }\n        recipientsHTML = `<strong>MEMORANDUM FOR<\/strong> &nbsp;&nbsp;${recipientsFormatted}`;\n    }<\/p>\n<p>    \/\/ Format references\n    let referencesHTML = '';\n    if (enhancedReferences && enhancedReferences.trim() && !enhancedReferences.toLowerCase().includes('none provided')) {\n        const refLines = enhancedReferences.split('\\n');\n        referencesHTML = `<\/p>\n<p><strong>References:<\/strong><br \/>`;\n        refLines.forEach((line) => {\n            referencesHTML += `${line}<br \/>`;\n        });\n        referencesHTML += `<\/p>\n<p>`;\n    }<\/p>\n<p>    \/\/ Generate paragraphs based on enhanced context\n    let paragraphsHTML = '';<\/p>\n<p>    \/\/ If we have a context, split it into paragraphs\n    if (memoContext && memoContext.trim()) {\n        \/\/ Split the enhanced context into paragraphs\n        let paragraphs = enhancedContext ? enhancedContext.split(\/\\n+\/).filter(para => para.trim()) : [];<\/p>\n<p>        \/\/ If no paragraphs were created, create at least one\n        if (paragraphs.length === 0) {\n            paragraphs = [`The purpose of this memorandum is to address ${subject}. All personnel shall review and comply with the guidance provided herein.`];\n        }<\/p>\n<p>        \/\/ Ensure the first paragraph starts with the purpose if it doesn't already\n        if (!paragraphs[0].toLowerCase().includes(\"purpose\") && !paragraphs[0].toLowerCase().includes(\"the purpose\")) {\n            paragraphs[0] = `The purpose of this memorandum is to ${paragraphs[0].charAt(0).toLowerCase() + paragraphs[0].slice(1)}`;\n        }<\/p>\n<p>        \/\/ Format each paragraph with number\n        paragraphs.forEach((paragraph, index) => {\n            paragraphsHTML += `<\/p>\n<p>${index + 1}. ${paragraph}<\/p>\n<p>`;\n        });\n    } else {\n        \/\/ Generate at least 3 paragraphs if no context is provided\n        paragraphsHTML = `<\/p>\n<p>1. The purpose of this memorandum is to address ${subject}. In accordance with applicable regulations, all personnel shall review and comply with the guidance provided herein.<\/p>\n<p>2. The ${organization} is responsible for ensuring compliance with the procedures outlined in this memorandum. All actions shall be completed by personnel in a timely manner to support mission requirements.<\/p>\n<p>3. For questions or concerns regarding this memorandum, please contact the undersigned at ${organization}.<\/p>\n<p>        `;\n    }<\/p>\n<p>    \/\/ Add POC information if provided\n    const pocInfo = document.getElementById('poc-info').value;\n    if (pocInfo && pocInfo.trim()) {\n        \/\/ Get the number for the new paragraph\n        const paragraphCount = (paragraphsHTML.match(\/<\/p>\n<p>\\d+\\.\/g) || []).length;\n        paragraphsHTML += `<\/p>\n<p>${paragraphCount + 1}. The point of contact for this memorandum is ${pocInfo}.<\/p>\n<p>`;\n    }<\/p>\n<p>    \/\/ Format address block\n    let addressHTML = '';\n    if (fromAddress && fromAddress.trim()) {\n        addressHTML = `<br \/>${fromAddress.replace(\/\\n\/g, '<br \/>')}`;\n    }<\/p>\n<p>    \/\/ Generate full memorandum HTML\n    return `<\/p>\n<div style=\"font-family: 'Times New Roman', Times, serif; font-size: 12pt; line-height: 1.5; max-width: 8.5in; margin: 0 auto;\">\n<div style=\"text-align: right;\">${formatDate(memoDate)}<\/div>\n<div style=\"margin-top: 1em;\">\n<p>${recipientsHTML}<\/p>\n<\/p><\/div>\n<div style=\"margin-top: 1em;\">\n<p><strong>FROM:<\/strong> &nbsp;&nbsp;${organization.trim()}${addressHTML}<\/p>\n<\/p><\/div>\n<div style=\"margin-top: 1em;\">\n<p><strong>SUBJECT:<\/strong> &nbsp;&nbsp;${subject}<\/p>\n<\/p><\/div>\n<p>            ${referencesHTML}<\/p>\n<div style=\"margin-top: 1em;\">\n                ${paragraphsHTML}\n            <\/div>\n<div style=\"margin-top: 2em;\">\n<p>${signatureName.trim()}, ${signatureRank.trim()}<br \/>\n                ${dutyTitle.trim()}<\/p>\n<\/p><\/div>\n<\/p><\/div>\n<p>    `;\n}<\/p>\n<p>\/\/ Process revision request\nasync function processRevisionRequest(feedback) {\n    try {\n        const currentContent = document.getElementById('resultContainer').innerHTML;<\/p>\n<p>        \/\/ Try to use the real API first\n        try {\n            const response = await fetch(API_URL, {\n                method: 'POST',\n                headers: {\n                    'Content-Type': 'application\/json',\n                    'Authorization': `Bearer ${getApiKey()}`\n                },\n                body: JSON.stringify({\n                    model: MODEL,\n                    messages: [\n                        {\n                            role: \"system\",\n                            content: \"You are an expert in military writing standards and memorandum formatting. Your task is to revise military memorandums based on specific feedback, making them more professional, precise, and adherent to formal military writing standards.\"\n                        },\n                        {\n                            role: \"user\",\n                            content: `Please revise this memorandum based on the following feedback:\\n\\n${feedback}\\n\\nMemorandum content:\\n${currentContent}\\n\\nReturn only the revised HTML content.`\n                        }\n                    ]\n                })\n            });<\/p>\n<p>            if (!response.ok) {\n                throw new Error('API request failed');\n            }<\/p>\n<p>            const data = await response.json();\n            const revisedContent = data.choices[0].message.content;<\/p>\n<p>            \/\/ Update the result container\n            document.getElementById('resultContainer').innerHTML = revisedContent;\n        } catch (apiError) {\n            console.error('API error, falling back to simulation:', apiError);<\/p>\n<p>            \/\/ Fall back to simulated revision if API fails\n            await new Promise(resolve => setTimeout(resolve, 1500));\n            const revisedContent = simulateRevision(currentContent, feedback);<\/p>\n<p>            \/\/ Update the result container\n            document.getElementById('resultContainer').innerHTML = revisedContent;\n        }<\/p>\n<p>        \/\/ Hide loading and show step 2\n        document.getElementById('loading').style.display = 'none';\n        document.getElementById('step2').style.display = 'block';<\/p>\n<p>        \/\/ Reset feedback area\n        document.getElementById('feedbackArea').style.display = 'none';\n        document.getElementById('feedback').value = '';\n        document.getElementById('reviseBtn').textContent = 'Request Revisions';<\/p>\n<p>    } catch (error) {\n        console.error('Error processing revision:', error);\n        document.getElementById('loading').style.display = 'none';\n        document.getElementById('step2').style.display = 'block';\n        document.getElementById('apiError').style.display = 'block';\n    }\n}<\/p>\n<p>\/\/ Simulate a revision based on feedback (mock function)\nfunction simulateRevision(content, feedback) {\n    \/\/ Extract paragraphs\n    const paragraphRegex = \/<\/p>\n<p>(\\d+)\\.\\s*(.*?)<\\\/p>\/g;\n    const matches = [...content.matchAll(paragraphRegex)];<\/p>\n<p>    let revisedContent = content;<\/p>\n<p>    \/\/ Process feedback to make appropriate changes\n    const feedbackLower = feedback.toLowerCase();<\/p>\n<p>    \/\/ Look for paragraph-specific feedback\n    matches.forEach(match => {\n        const fullMatch = match[0];\n        const paragraphNum = match[1];\n        let paragraphText = match[2];<\/p>\n<p>        \/\/ Check if feedback mentions this paragraph\n        if (feedbackLower.includes(`paragraph ${paragraphNum}`) || \n            feedbackLower.includes(`para ${paragraphNum}`) || \n            feedbackLower.includes(`#${paragraphNum}`)) {<\/p>\n<p>            \/\/ Apply different modifications based on common feedback terms\n            if (feedbackLower.includes('more direct') || feedbackLower.includes('be direct')) {\n                paragraphText = paragraphText.replace(\/personnel are encouraged to|it is recommended that|consider|may want to\/gi, 'personnel shall');\n            }<\/p>\n<p>            if (feedbackLower.includes('more detail') || feedbackLower.includes('elaborate')) {\n                paragraphText += ' This directive applies to all personnel assigned or attached to the organization. Ensure strict compliance with established timelines and procedures.';\n            }<\/p>\n<p>            if (feedbackLower.includes('clearer') || feedbackLower.includes('clarity')) {\n                paragraphText = 'Per established guidance, ' + paragraphText.replace(\/furthermore,|additionally,|moreover,\/gi, '').trim();\n            }<\/p>\n<p>            \/\/ Update the content with modified paragraph\n            revisedContent = revisedContent.replace(fullMatch, `<\/p>\n<p>${paragraphNum}. ${paragraphText}<\/p>\n<p>`);\n        }\n    });<\/p>\n<p>    \/\/ Look for general feedback related to adding content\n    if (feedbackLower.includes('add') || feedbackLower.includes('include')) {\n        \/\/ Extract common topics that might be requested\n        const topics = {\n            'training': 'Personnel shall complete all required training prior to implementation. Training records must be documented and maintained by unit training managers.',\n            'deadline': 'All requirements outlined in this memorandum must be completed no later than 30 days from the effective date.',\n            'poc': 'For questions or concerns regarding this memorandum, contact the action officer at DSN 555-1234.',\n            'reporting': 'Units shall submit implementation status reports through their respective chains of command by the 15th of each month.',\n            'compliance': 'Compliance with this memorandum will be verified during staff assistance visits and formal inspections.'\n        };<\/p>\n<p>        \/\/ Check if feedback requests any of these topics\n        for (const [topic, text] of Object.entries(topics)) {\n            if (feedbackLower.includes(topic)) {\n                \/\/ Add a new paragraph at the end\n                const paragraphCount = matches.length;\n                const insertPoint = revisedContent.lastIndexOf('<\/p><\/div>\n<p>');\n                revisedContent = revisedContent.slice(0, insertPoint) + \n                    `<\/p>\n<p>${paragraphCount + 1}. ${text}<\/p>\n<p>\\n` + \n                    revisedContent.slice(insertPoint);\n                break; \/\/ Add only one new paragraph\n            }\n        }\n    }<\/p>\n<p>    return revisedContent;\n}<\/p>\n<p>\/\/ Function to download as Word document\nfunction downloadAsWord() {\n    const content = document.getElementById('resultContainer').innerHTML;\n    const filenameValue = document.getElementById('filename').value || 'military-memorandum';<\/p>\n<p>    \/\/ Create a Blob with the HTML content\n    const blob = new Blob([`\n        <html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http:\/\/www.w3.org\/TR\/REC-html40'>\n        <head>\n            <meta charset=\"utf-8\">\n            <title>${filenameValue}<\/title><\/p>\n<style>\n                body { font-family: 'Times New Roman', serif; font-size: 12pt; }\n                p { margin: 0; padding: 0; line-height: 1.5; }\n            <\/style>\n<p>        <\/head>\n        <body>\n            ${content}\n        <\/body>\n        <\/html>\n    `], { type: 'application\/msword' });<\/p>\n<p>    \/\/ Create a download link and trigger it\n    const link = document.createElement('a');\n    link.href = URL.createObjectURL(blob);\n    link.download = `${filenameValue}.doc`;\n    document.body.appendChild(link);\n    link.click();\n    document.body.removeChild(link);\n}<\/p>\n<p>\/\/ Generate memorandum content with AI\nasync function generateMemorandumWithAI() {\n    try {\n        const memoSubject = document.getElementById('memo-subject').value;\n        const memoContext = document.getElementById('memo-context').value;<\/p>\n<p>        \/\/ First, enhance the subject with AI\n        const enhancedSubject = await enhanceWithChatGPT(\n            memoSubject, \n            \"You are an AI assistant helping to format a military memorandum subject line. Format this subject line according to standard Military Memorandum for Record (MFR) format. Use proper capitalization (title case). Keep it concise but professional. Return only the formatted subject line without any explanations.\"\n        );<\/p>\n<p>        \/\/ Process references if included\n        let enhancedReferences = \"\";\n        const referenceType = document.querySelector('input[name=\"reference-type\"]:checked').value;\n        if (referenceType === 'include') {\n            const references = document.getElementById('references').value;\n            if (references && references.trim()) {\n                \/\/ Process references with AI to ensure they're real and properly formatted\n                enhancedReferences = await processReferencesWithAI(references, memoContext);\n            }\n        }<\/p>\n<p>        \/\/ Enhance memo context with AI\n        let enhancedContext = memoContext;\n        try {\n            enhancedContext = await enhanceWithChatGPT(\n                memoContext,\n                \"You are an expert in military writing assisting with a memorandum. Take the following user input and transform it into a professional, comprehensive military memorandum content. Start with 'The purpose of this memorandum is...' and then flesh out the details into a robust, formal military communication. Break it into logical paragraphs that flow well. Use appropriate military terminology and formatting. Return only the enhanced content without any explanations.\"\n            );\n            console.log(\"Enhanced context:\", enhancedContext);\n        } catch (error) {\n            console.error('Error enhancing memo context:', error);\n            \/\/ If enhancement fails, we'll use the original context\n        }<\/p>\n<p>        \/\/ Get recipient based on selection\n        const recipientType = document.querySelector('input[name=\"recipient-type\"]:checked').value;<\/p>\n<p>        \/\/ Generate the memorandum using the enhanced content\n        const aiContent = generateMockMemorandum(enhancedSubject, enhancedReferences, recipientType, enhancedContext);<\/p>\n<p>        \/\/ Update the result container\n        document.getElementById('resultContainer').innerHTML = aiContent;<\/p>\n<p>        \/\/ Hide loading and show step 2\n        document.getElementById('loading').style.display = 'none';\n        document.getElementById('apiError').style.display = 'none';\n        goToStep(2);\n    } catch (error) {\n        console.error('Error generating memorandum:', error);\n        document.getElementById('loading').style.display = 'none';\n        document.getElementById('step1').style.display = 'block';\n        document.getElementById('apiError').style.display = 'block';\n    }\n}\n    <\/script><br \/>\n<\/body><br \/>\n<\/html><\/p>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"_links":{"self":[{"href":"https:\/\/grid.ai4pk.com\/index.php\/wp-json\/wp\/v2\/pages\/20"}],"collection":[{"href":"https:\/\/grid.ai4pk.com\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/grid.ai4pk.com\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/grid.ai4pk.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/grid.ai4pk.com\/index.php\/wp-json\/wp\/v2\/comments?post=20"}],"version-history":[{"count":1,"href":"https:\/\/grid.ai4pk.com\/index.php\/wp-json\/wp\/v2\/pages\/20\/revisions"}],"predecessor-version":[{"id":21,"href":"https:\/\/grid.ai4pk.com\/index.php\/wp-json\/wp\/v2\/pages\/20\/revisions\/21"}],"wp:attachment":[{"href":"https:\/\/grid.ai4pk.com\/index.php\/wp-json\/wp\/v2\/media?parent=20"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}