-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1784 lines (1549 loc) · 70.8 KB
/
script.js
File metadata and controls
1784 lines (1549 loc) · 70.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let historyStack = [];
const MAX_HISTORY = 5;
let currentQuestions = [];
let currentQuestionIndex = -1;
let userResponses = {};
let selectedCategories = new Set();
let currentTest = {
questions: [],
currentQuestionIndex: 0,
score: 0,
timeLeft: 0,
timer: null
};
// Add this object to store the topics for each category
const categoryTopics = {
quantitative: [
"Percentage",
"Ratio and Proportion",
"Age Problems",
"Partnership",
"Allegations and Mix",
"Average",
"Time and Work",
"Pipes and Cistern",
"Profit and Loss",
"Probability",
"Simple and Compound Interest",
"Chain Rule",
"Train Problems",
"Boats and Streams",
"Permutation and Combination",
"Number System",
"HCF and LCM",
"Data Interpretation"
],
verbal: [
"Reading Comprehension",
"Spotting Errors",
"Sentence Formation",
"Sentence Correction",
"Synonym & Antonym",
"Idioms and Phrases"
],
logical: [
"Seating Arrangement",
"Clock Problems",
"Calendar",
"Blood Relations",
"Directions",
"Number Series",
"Word Pattern",
"Coding Decoding",
"Mathematical Operations",
"Venn Diagram",
"Visual Reasoning",
"Paper Cutting and Folding",
"Cubes and Dices",
"Data Sufficiency",
"Statement and Assumption",
"Statement and Conclusion"
]
};
// Shared Functions
function openDialog() {
document.getElementById("api-key-dialog").style.display = "block";
const apiKey = document.getElementById("api-key-input").value;
const message = document.getElementById("api-key-message");
message.style.display = apiKey ? "none" : "block";
}
function closeDialog() {
document.getElementById("api-key-dialog").style.display = "none";
}
function saveApiKey() {
const apiKey = document.getElementById("api-key-input").value.trim();
const message = document.getElementById("api-key-message");
const apiKeyButton = document.querySelector(".api-key-button");
const resumeButton = document.querySelector(".resume-button");
if (apiKey) {
localStorage.setItem("geminiApiKey", apiKey);
message.style.display = "none";
document.getElementById("application-tabs").style.display = "block";
apiKeyButton.style.display = "none";
resumeButton.style.display = "block";
closeDialog();
showTab("letter");
} else {
message.style.display = "block";
alert("Please enter a valid API Key.");
}
}
function showTab(tab) {
const jobContent = document.getElementById("job-application-content");
const resumeContent = document.getElementById("resume-content");
const emailContent = document.getElementById("email-content");
const aptitudeContent = document.getElementById("aptitude-content");
const tabContent = document.getElementById("tab-content");
const tabs = document.querySelectorAll(".tab-button");
// Remove active class from all tabs
tabs.forEach((t) => t.classList.remove("active"));
// Add active class to clicked tab
const activeTab = document.querySelector(`.tab-button[onclick*="${tab}"]`);
if (activeTab) {
activeTab.classList.add("active");
}
// Hide all content sections
jobContent.style.display = "none";
resumeContent.style.display = "none";
if (emailContent) emailContent.style.display = "none";
if (aptitudeContent) aptitudeContent.style.display = "none";
// Show selected tab content
if (tab === "letter") {
tabContent.style.display = "block";
jobContent.style.display = "block";
} else if (tab === "resume") {
tabContent.style.display = "block";
resumeContent.style.display = "block";
// Auto-fill resume text if available
const storedResume = localStorage.getItem('userResume');
const resumeTextArea = document.getElementById('resume-text');
if (storedResume && resumeTextArea) {
resumeTextArea.value = storedResume;
}
} else if (tab === "email") {
tabContent.style.display = "block";
emailContent.style.display = "block";
} else if (tab === "aptitude") {
tabContent.style.display = "block";
aptitudeContent.style.display = "block";
}
}
function enableEditing(elementId = 'letter-output') {
const outputDiv = document.getElementById(elementId);
if (outputDiv) {
outputDiv.contentEditable = true;
outputDiv.style.border = '2px solid var(--primary-color)';
outputDiv.focus();
outputDiv.style.backgroundColor = '#fafafa';
outputDiv.style.padding = '2rem';
// Add instruction
const instruction = document.createElement('div');
instruction.className = 'edit-instruction';
instruction.textContent = 'You can now edit the text. Click outside to finish editing.';
outputDiv.parentNode.insertBefore(instruction, outputDiv);
// Handle clicking outside
function handleClickOutside(event) {
if (!outputDiv.contains(event.target)) {
outputDiv.contentEditable = false;
outputDiv.style.border = '2px solid var(--border-color)';
outputDiv.style.backgroundColor = 'var(--card-bg)';
outputDiv.style.padding = '1.5rem';
// Remove the instruction
const instruction = document.querySelector('.edit-instruction');
if (instruction) {
instruction.remove();
}
// Remove the event listener
document.removeEventListener('click', handleClickOutside);
}
}
// Add the event listener with a slight delay to prevent immediate triggering
setTimeout(() => {
document.addEventListener('click', handleClickOutside);
}, 100);
}
}
// History Management
function showHistory() {
const historyDialog = document.createElement('div');
historyDialog.innerHTML = `
<div class="dialog history-dialog" style="display: block;">
<div class="dialog-content history-content">
<span class="close" onclick="this.closest('.dialog').remove()">×</span>
<h2>Recent Generations</h2>
<div class="history-list">
${historyStack.map((item, i) => {
// Extract first line as title
const firstLine = item.content.split('\n')[0];
// Get letter type from content
const letterType = item.content.includes('Letter of Recommendation') ? 'LOR' :
item.content.includes('Statement of Purpose') ? 'SOP' :
item.content.includes('Cover Letter') ? 'Cover Letter' :
item.content.includes('General Letter to') ? 'General Letter' :
'Job Application';
// Format the timestamp
const timestamp = new Date(item.timestamp).toLocaleString();
return `
<div class="history-item">
<div class="history-item-header">
<span class="history-type">${letterType}</span>
<span class="history-timestamp">${timestamp}</span>
</div>
<div class="history-preview">${firstLine}</div>
<button onclick="loadHistory(${i})" class="history-load-btn">Load</button>
</div>
`;
}).join('')}
</div>
</div>
</div>
`;
document.body.appendChild(historyDialog);
}
function loadHistory(index) {
const activeTab = document.querySelector('[id$="-content"]:not([style*="none"])')?.id;
if (!activeTab) return;
const outputDiv = activeTab.includes("job") ?
document.getElementById("application-output") :
document.getElementById("lor-output");
if (outputDiv && historyStack[index]) {
outputDiv.innerHTML = historyStack[index].content;
document.querySelector(".dialog")?.remove();
}
}
// Job Application Functions
async function generateLetter() {
const spinner = document.querySelector(".loading-spinner");
const letterTypeSelect = document.getElementById("template-style");
const outputDiv = document.getElementById("letter-output");
// Validate required elements exist
if (!letterTypeSelect || !outputDiv || !spinner) {
console.error("Required elements not found");
return;
}
const letterType = letterTypeSelect.value;
const apiKey = localStorage.getItem("geminiApiKey");
if (!apiKey) {
outputDiv.innerHTML = "Please add your API key first.";
return;
}
document.getElementById("download-buttons").style.display = "none";
spinner.style.display = "block";
// Handle LOR fields if needed
if (letterType === "lor") {
const studentNameInput = document.getElementById("student-name");
const recommenderNameInput = document.getElementById("recommender-name");
const relationshipInput = document.getElementById("relationship");
const coursesInput = document.getElementById("courses");
const achievementsInput = document.getElementById("achievements");
const purposeInput = document.getElementById("purpose");
const lorTypeInput = document.getElementById("lor-type");
// Validate LOR-specific inputs exist
if (!studentNameInput || !recommenderNameInput || !relationshipInput ||
!coursesInput || !achievementsInput || !purposeInput || !lorTypeInput) {
outputDiv.innerHTML = "Error: LOR form elements not found. Please refresh the page.";
spinner.style.display = "none";
return;
}
const studentName = studentNameInput.value.trim();
const recommenderName = recommenderNameInput.value.trim();
const relationship = relationshipInput.value.trim();
const courses = coursesInput.value.trim();
const achievements = achievementsInput.value.trim();
const purpose = purposeInput.value.trim();
const lorType = lorTypeInput.value;
if (!studentName || !recommenderName || !relationship) {
outputDiv.innerHTML = "Please fill in all required fields.";
spinner.style.display = "none";
return;
}
const useResumeCheckbox = document.getElementById('use-resume');
const useResume = useResumeCheckbox ? useResumeCheckbox.checked : false;
const storedResume = useResume ? localStorage.getItem('userResume') : '';
const requestData = {
senderInfo: recommenderName,
recipientInfo: studentName,
context: `${relationship} - ${courses}`,
keyPoints: useResume ? `${achievements}\n\nResume:\n${storedResume}` : achievements,
purpose: purpose,
type: lorType,
};
try {
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contents: [{
parts: [{
text: `Generate a Letter of Recommendation with the following details:
From: ${requestData.senderInfo} (Recommender)
For: ${requestData.recipientInfo} (Candidate)
Context: ${requestData.context}
Key Achievements/Skills: ${requestData.keyPoints}
Purpose: ${requestData.purpose}
Type: ${requestData.type}
Format requirements:
- Professional letterhead with recommender's title and institution
- Opening that establishes relationship with candidate and duration/context
- Explanation of recommender's qualifications to evaluate the candidate
- 2-3 specific examples that demonstrate candidate's exceptional qualities
- Include detailed anecdotes with measurable outcomes/impact
- Compare candidate to peers using specific percentiles or rankings when possible
- Address relevant skills for the position/program the candidate is pursuing
- Include both strengths and areas of growth (framed positively)
- Strong concluding endorsement with level of enthusiasm clearly stated
- Professional closing with contact information offer
- 500-750 words in length
- Formal academic/professional tone throughout`
}]
}]
})
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (!data.candidates || data.candidates.length === 0) {
throw new Error('No response generated from API');
}
const outputText = data.candidates[0]?.content?.parts?.[0]?.text || "Failed to generate";
const letterHeading = `Letter of Recommendation for ${requestData.recipientInfo} - ${requestData.type}`;
outputDiv.innerHTML = `<h3 class="letter-heading">${letterHeading}</h3>\n\n${outputText}`;
historyStack.push({
content: `${letterHeading}\n\n${outputText}`,
timestamp: new Date().toISOString(),
type: letterType
});
if (historyStack.length > MAX_HISTORY) historyStack.shift();
document.getElementById("download-buttons").style.display = "flex";
} catch (error) {
console.error("Error generating LOR:", error);
outputDiv.innerHTML = `Error: ${error.message}. Please check your internet connection and API key.`;
} finally {
spinner.style.display = "none";
}
return;
}
// Handle all other letter types consistently
const contextInput = document.getElementById("context-input");
const keyPointsInput = document.getElementById("key-points-input");
const senderInfoInput = document.getElementById("sender-info");
const recipientInfoInput = document.getElementById("recipient-info");
// Validate all required inputs exist
if (!contextInput || !keyPointsInput || !senderInfoInput || !recipientInfoInput) {
outputDiv.innerHTML = "Error: Required form elements not found. Please refresh the page.";
spinner.style.display = "none";
return;
}
const context = contextInput.value.trim();
const keyPoints = keyPointsInput.value.trim();
const senderInfo = senderInfoInput.value.trim();
const recipientInfo = recipientInfoInput.value.trim();
if (!context || !keyPoints || !senderInfo || !recipientInfo) {
outputDiv.innerHTML = "Please fill in all required fields.";
spinner.style.display = "none";
return;
}
const useResumeCheckbox = document.getElementById('use-resume');
const useResume = useResumeCheckbox ? useResumeCheckbox.checked : false;
const storedResume = useResume ? localStorage.getItem('userResume') : '';
let requestData = {
senderInfo,
recipientInfo,
context,
keyPoints: useResume ? `${keyPoints}\n\nResume:\n${storedResume}` : keyPoints,
type: letterType === 'other' ? 'General Letter' : letterType.toUpperCase()
};
const promptTemplates = {
lor: `Generate a Letter of Recommendation with the following details:
From: ${requestData.senderInfo} (Recommender)
For: ${requestData.recipientInfo} (Candidate)
Context: ${requestData.context}
Key Achievements/Skills: ${requestData.keyPoints}
Format requirements:
- Professional letterhead with recommender's title and institution
- Opening that establishes relationship with candidate and duration/context
- Explanation of recommender's qualifications to evaluate the candidate
- 2-3 specific examples that demonstrate candidate's exceptional qualities
- Include detailed anecdotes with measurable outcomes/impact
- Compare candidate to peers using specific percentiles or rankings when possible
- Address relevant skills for the position/program the candidate is pursuing
- Include both strengths and areas of growth (framed positively)
- Strong concluding endorsement with level of enthusiasm clearly stated
- Professional closing with contact information offer
- 500-750 words in length
- Formal academic/professional tone throughout
Dont include any other text or comments`,
job: `Generate a Job/Internship Application Letter with the following details:
From: ${requestData.senderInfo}
To: ${requestData.recipientInfo}
Context: ${requestData.context}
Qualifications & Skills: ${requestData.keyPoints}
Format requirements:
- Professional tone
- Clear statement of position and organization interest
- Highlight most relevant achievements from the provided qualifications
- Connect skills directly to position requirements mentioned in context
- Provide specific examples of how your experience relates to the role
- Express enthusiasm with specific reasons for interest
- Strong closing with clear next steps
- 400-600 words in length
- Properly formatted with date, address blocks, and signature
Dont include any other text or comments`,
cover: `Generate a Cover Letter with the following details:
From: ${requestData.senderInfo}
To: ${requestData.recipientInfo}
Context: ${requestData.context}
Qualifications & Skills: ${requestData.keyPoints}
Format requirements:
- Attention-grabbing opening referencing the company or position
- Concise highlighting of most relevant qualifications from Qualifications & Skills
- Include specific achievements that directly match job requirements
- Demonstrate understanding of the position needs mentioned in context
- Professional but conversational tone
- Compelling closing with clear interest in interview
- 250-400 words in length
- Properly formatted with date, address blocks, and signature
Dont include any other text or comments`,
sop: `Generate a Statement of Purpose with the following details:
Applicant: ${requestData.senderInfo}
Program/Institution: ${requestData.recipientInfo}
Background: ${requestData.context}
Goals & Achievements: ${requestData.keyPoints}
Format requirements:
- Engaging opening that conveys passion for the field
- Personal and professional narrative showing intellectual development
- Connect past experiences to specific aspects of the target program
- Include specific academic achievements with measurable outcomes
- Explain why this specific program/institution is the ideal fit
- Clearly articulate short-term and long-term academic/career goals
- Demonstrate knowledge of faculty research or program strengths
- Address any unusual aspects of academic record if mentioned in background
- Maintain professional yet authentic voice throughout
- Compelling conclusion that reinforces fit and readiness
- 800-1000 words in length
Dont include any other text or comments`,
other: `Generate a formal letter based on the following details:
From: ${requestData.senderInfo}
To: ${requestData.recipientInfo}
Context: ${requestData.context}
Key Details: ${requestData.keyPoints}
Format requirements:
- Proper formal letter structure with date and address blocks
- Clear purpose stated in opening paragraph
- Organized supporting details in body paragraphs
- Professional tone appropriate for the context
- Specific details from provided information
- Proper closing with contact information
- 200-400 words in length
- Suitable for official correspondence
Examples of acceptable letters:
- Leave applications
- Medical leave requests
- Permission requests
- Formal complaints
- Resource requests
- Academic appeals
Dont include any other text or comments`
};
const requestBody = {
contents: [
{
parts: [
{
text: promptTemplates[letterType] || promptTemplates["job"],
},
],
},
],
};
let letterHeading = '';
if (letterType === 'lor') {
letterHeading = `Letter of Recommendation for ${requestData.recipientInfo} - ${requestData.type}`;
} else if (letterType === 'job') {
letterHeading = `Job Application to ${requestData.recipientInfo}`;
} else if (letterType === 'cover') {
letterHeading = `Cover Letter for ${requestData.recipientInfo}`;
} else if (letterType === 'sop') {
letterHeading = `Statement of Purpose for ${requestData.recipientInfo}`;
} else if (letterType === 'other') {
letterHeading = `General Letter to ${requestData.recipientInfo}`;
}
try {
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
}
);
const data = await response.json();
// Enhanced error handling
if (!data.candidates || data.candidates.length === 0) {
console.error("API response missing candidates:", data);
outputDiv.innerHTML = `Error: No response generated. ${data.error ? data.error.message : 'Please check your API key and try again.'}`;
spinner.style.display = "none";
return;
}
const outputText = data.candidates[0]?.content?.parts?.[0]?.text || "Failed to generate";
// Add heading to the output
outputDiv.innerHTML = `<h3 class="letter-heading">${letterHeading}</h3>\n\n${outputText}`;
historyStack.push({
content: `${letterHeading}\n\n${outputText}`,
timestamp: new Date().toISOString(),
type: letterType
});
if (historyStack.length > MAX_HISTORY) historyStack.shift();
document.getElementById("download-buttons").style.display = "flex";
} catch (error) {
console.error("Error generating letter:", error);
outputDiv.innerHTML = `Error: ${error.message}. Please check your internet connection and API key.`;
} finally {
spinner.style.display = "none";
}
}
// LOR Functions
async function generateLOR() {
const spinner = document.querySelector(".loading-spinner");
const studentName = document.getElementById("student-name").value.trim();
const recommenderName = document
.getElementById("recommender-name")
.value.trim();
const relationship = document.getElementById("relationship").value.trim();
const courses = document.getElementById("courses").value.trim();
const achievements = document.getElementById("achievements").value.trim();
const purpose = document.getElementById("purpose").value.trim();
const apiKey = localStorage.getItem("geminiApiKey");
const outputDiv = document.getElementById("lor-output");
const lorType = document.getElementById("lor-type").value;
document.getElementById("lor-download-buttons").style.display = "none";
spinner.style.display = "block";
if (!studentName || !recommenderName || !relationship) {
outputDiv.innerHTML = "Please fill required fields";
spinner.style.display = "none";
return;
}
const requestBody = {
contents: [
{
parts: [
{
text: `Write ${lorType} LOR for ${studentName} from ${recommenderName} (${relationship}) for ${purpose}.
Courses: ${courses}
Achievements: ${achievements}
Include: Letterhead, relationship context, achievements, personal qualities, strong recommendation`,
},
],
},
],
};
try {
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
}
);
const data = await response.json();
const outputText =
data?.candidates?.[0]?.content?.parts?.[0]?.text || "Failed to generate";
outputDiv.innerHTML = outputText;
historyStack.push({
content: outputText,
timestamp: new Date().toISOString(),
type: 'lor'
});
if (historyStack.length > MAX_HISTORY) historyStack.shift();
document.getElementById("lor-download-buttons").style.display = "flex";
} catch (error) {
outputDiv.innerHTML = `Error: ${error.message}`;
} finally {
spinner.style.display = "none";
}
}
// Download Functions
function downloadPDF() {
const outputText = document.getElementById("letter-output").innerText;
const doc = new jspdf.jsPDF();
// Set document properties
doc.setFont('helvetica');
doc.setFontSize(12);
// Set margins (in mm)
const margin = 20;
const pageWidth = doc.internal.pageSize.width;
const pageHeight = doc.internal.pageSize.height;
const contentWidth = pageWidth - (2 * margin);
// Split text into lines that fit within margins
const lines = doc.splitTextToSize(outputText, contentWidth);
// Calculate lines per page (accounting for margins)
const lineHeight = doc.getTextDimensions('test').h * 1.2;
const linesPerPage = Math.floor((pageHeight - (2 * margin)) / lineHeight);
// Add pages and text
let currentPage = 1;
for (let i = 0; i < lines.length; i += linesPerPage) {
if (i > 0) {
doc.addPage();
currentPage++;
}
// Add page number at bottom
doc.setFontSize(10);
doc.text(`Page ${currentPage}`, pageWidth/2, pageHeight - 10, { align: 'center' });
doc.setFontSize(12);
// Add content for this page
const pageLines = lines.slice(i, i + linesPerPage);
doc.text(pageLines, margin, margin + (lineHeight/2));
}
doc.save("generated-letter.pdf");
}
function downloadDOCX() {
const outputText = document.getElementById("letter-output").innerText;
const doc = new docx.Document({
sections: [
{
children: [new docx.Paragraph(outputText)],
},
],
});
docx.Packer.toBlob(doc).then((blob) => saveAs(blob, "generated-letter.docx"));
}
function downloadLorPDF() {
const outputText = document.getElementById("lor-output").innerText;
const doc = new jspdf.jsPDF();
// Set document properties
doc.setFont('helvetica');
doc.setFontSize(12);
// Set margins (in mm)
const margin = 20;
const pageWidth = doc.internal.pageSize.width;
const pageHeight = doc.internal.pageSize.height;
const contentWidth = pageWidth - (2 * margin);
// Split text into lines that fit within margins
const lines = doc.splitTextToSize(outputText, contentWidth);
// Calculate lines per page (accounting for margins)
const lineHeight = doc.getTextDimensions('test').h * 1.2;
const linesPerPage = Math.floor((pageHeight - (2 * margin)) / lineHeight);
// Add pages and text
let currentPage = 1;
for (let i = 0; i < lines.length; i += linesPerPage) {
if (i > 0) {
doc.addPage();
currentPage++;
}
// Add page number at bottom
doc.setFontSize(10);
doc.text(`Page ${currentPage}`, pageWidth/2, pageHeight - 10, { align: 'center' });
doc.setFontSize(12);
// Add content for this page
const pageLines = lines.slice(i, i + linesPerPage);
doc.text(pageLines, margin, margin + (lineHeight/2));
}
doc.save("recommendation-letter.pdf");
}
function downloadLorDOCX() {
const outputText = document.getElementById("lor-output").innerText;
const doc = new docx.Document({
sections: [
{
children: [new docx.Paragraph(outputText)],
},
],
});
docx.Packer.toBlob(doc).then((blob) =>
saveAs(blob, "recommendation-letter.docx")
);
}
// Add this function to handle input field changes
function updateInputFields() {
const letterType = document.getElementById('template-style').value;
const inputsContainer = document.querySelector('.letter-inputs');
const outputDiv = document.getElementById('letter-output');
const downloadButtons = document.getElementById('download-buttons');
const storedResume = localStorage.getItem('userResume');
// Clear the output and hide download buttons
if (outputDiv) {
outputDiv.innerHTML = '';
}
if (downloadButtons) {
downloadButtons.style.display = 'none';
}
// Add resume checkbox HTML
const resumeCheckboxHTML = storedResume ? `
<div class="resume-checkbox-container">
<label class="resume-checkbox-label">
<input type="checkbox" id="use-resume" class="resume-checkbox">
Use the Added Resume
</label>
</div>
` : '';
// Define input fields for each letter type
const inputFields = {
lor: `
${resumeCheckboxHTML}
<div class="input-row">
<input type="text" id="student-name" placeholder="Student's Full Name">
<input type="text" id="recommender-name" placeholder="Recommender's Name">
</div>
<div class="input-row">
<input type="text" id="relationship" placeholder="Relationship (e.g., Professor)">
<select id="lor-type">
<option value="academic">Academic</option>
<option value="professional">Professional</option>
<option value="scholarship">Scholarship</option>
</select>
</div>
<textarea id="courses" placeholder="Relevant courses/projects" rows="2"></textarea>
<textarea id="achievements" placeholder="Key achievements and skills" rows="3"></textarea>
<textarea id="purpose" placeholder="Purpose of recommendation" rows="2"></textarea>
`,
job: `
${resumeCheckboxHTML}
<textarea id="context-input" placeholder="Enter job description and role details..." rows="3"></textarea>
<textarea id="key-points-input" placeholder="Enter your relevant experience and qualifications..." rows="3"></textarea>
<div class="input-row">
<input type="text" id="sender-info" placeholder="Your name and contact information">
<input type="text" id="recipient-info" placeholder="Company name and hiring manager details">
</div>
`,
cover: `
${resumeCheckboxHTML}
<textarea id="context-input" placeholder="Enter position details and company information..." rows="3"></textarea>
<textarea id="key-points-input" placeholder="Enter your relevant skills and experiences..." rows="3"></textarea>
<div class="input-row">
<input type="text" id="sender-info" placeholder="Your name and contact information">
<input type="text" id="recipient-info" placeholder="Hiring manager's name and title">
</div>
`,
sop: `
${resumeCheckboxHTML}
<textarea id="context-input" placeholder="Enter your academic background and research interests..." rows="3"></textarea>
<textarea id="key-points-input" placeholder="Enter your achievements, goals, and motivation..." rows="3"></textarea>
<div class="input-row">
<input type="text" id="sender-info" placeholder="Your name and current institution">
<input type="text" id="recipient-info" placeholder="Target program/university name">
</div>
`,
other: `
${resumeCheckboxHTML}
<textarea id="context-input" placeholder="Letter purpose (e.g., Leave application, Medical request)" rows="2"></textarea>
<textarea id="key-points-input" placeholder="Key details (dates, reasons, supporting information)" rows="3"></textarea>
<div class="input-row">
<input type="text" id="sender-info" placeholder="Your name and position">
<input type="text" id="recipient-info" placeholder="Recipient's name and title">
</div>
`,
};
// Update the input fields
inputsContainer.innerHTML = inputFields[letterType];
}
// Initialization
window.onload = function() {
// Initialize theme
initTheme();
// Auto-fill resume text area if available
const storedResume = localStorage.getItem('userResume');
if (storedResume && document.getElementById('resume-text')) {
document.getElementById('resume-text').value = storedResume;
}
// Initialize resume button state
updateResumeButton();
// Update input fields to show checkbox if resume exists
updateInputFields();
};
window.onclick = function (event) {
if (event.target === document.getElementById("api-key-dialog")) {
closeDialog();
}
};
// Change function name from startResumeAnalysis to analyzeResume
async function analyzeResume() {
const resumeText = document.getElementById("resume-text").value.trim();
if (!resumeText) {
alert("Please paste your resume first");
return;
}
const apiKey = localStorage.getItem("geminiApiKey");
const spinner = document.querySelector("#resume-content .loading-spinner");
const outputDiv = document.getElementById("resume-output");
// Clear previous output and show loader
outputDiv.innerHTML = '';
spinner.style.display = "block";
// Maximum number of retries
const maxRetries = 3;
let attempt = 0;
while (attempt < maxRetries) {
try {
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contents: [{
parts: [{
text: `Analyze this resume and generate interview preparation items:
${resumeText}
Requirements:
1. For each item provide:
- Question type (Technical/Behavioral/Scenario)
- Specific question
- Concise answer (2-3 sentences)
- 3-4 key bullet points
2. Format response as valid JSON:
{
"items": [
{
"type": "question type",
"question": "text",
"answer": "2-3 sentence answer",
"keyPoints": ["point1", "point2"]
}
]
}
3. Focus on technical implementations and measurable outcomes
4. Include specific tools/technologies mentioned in resume`
}]
}]
})
}
);
if (!response.ok) {
// If it's a 503 error, retry after a delay
if (response.status === 503) {
attempt++;
if (attempt < maxRetries) {
await new Promise(resolve => setTimeout(resolve, 1000 * attempt)); // Exponential backoff
continue;
}
}
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (!data || !data.candidates || !data.candidates[0] || !data.candidates[0].content) {
throw new Error('Invalid response structure from API');
}
const textResponse = data.candidates[0].content.parts[0].text;
if (!textResponse) {
throw new Error('Empty response from API');
}
const cleanJSON = textResponse.replace(/```json/g, '').replace(/```/g, '');
try {
const interviewData = JSON.parse(cleanJSON);
if (!interviewData || !interviewData.items || !Array.isArray(interviewData.items)) {
throw new Error('Invalid JSON structure');
}
displayInterviewItems(interviewData.items);
document.getElementById("interview-container").classList.remove("hidden");
break; // Success! Exit the retry loop
} catch (jsonError) {
throw new Error(`Failed to parse response: ${jsonError.message}`);
}
} catch (error) {
attempt++;
if (attempt === maxRetries || error.message !== 'HTTP error! status: 503') {
console.error("Error generating Q&A:", error);
outputDiv.innerHTML = `
<div class="error-message">
${attempt === maxRetries ?
'Service is temporarily unavailable. Please try again in a few moments.' :
'Error analyzing resume. Please try again.'}
<br>
<small style="display: block; margin-top: 0.5rem; color: #666;">
Error details: ${error.message}
</small>
</div>`;
break;
}
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
}
// Hide loader when done
spinner.style.display = "none";
}
// Updated display function
function displayInterviewItems(items) {
const container = document.getElementById("interview-questions");
container.innerHTML = items.map((item, index) => `
<div class="interview-question">
<div class="question-header">
<span class="question-type">${item.type}</span>
<span class="question-number">Question ${index + 1}</span>
</div>
<div class="question-text">${item.question}</div>
<div class="answer-section">