/****************************
Roboshrub Inc.
Load Menu
http://roboshrub.blogspot.com
*****************************/

var loaded=-1;

// Sets up the load window.
function showLoad() {
  g('loadInfo').innerHTML="";
  togglePrompt('loadPrompt');
  showWindow('loadWindow');
  disableLoad(false);
  loadList();
}

// Populates a list of saved files for the "Load" window
function loadList() {
  loaded=-1;
  try {
    if (data.get("Velt_2").length<1) {throw "";} // Don't bother if there are no files
    
    var temp=data.get("Velt_2").split("|F|");
    g('loadContainer').innerHTML="";
    
    // Radio buttons for each file
    for (i=temp.length-1; i>=0; i--) {
      var currentName=temp[i].split("|P|")[0];
      g('loadContainer').innerHTML+="<input type='radio' id='load"+i+"' name='loader' onclick='loaded="+i+"'><label for='load"+i+"'>"+currentName+"</label><br>";
    }
      
    // Checks if there were no saves.
    if (g('loadContainer').innerHTML=="") {throw "";}
  }
  catch(e) {
    g('loadContainer').innerHTML="<div class='nofile'>There are no saved files.<\/div>";
  }
}

// Disables/enables all elements in the Load window
function disableLoad(a) {
  var loadItems=g('loadWindow').getElementsByTagName("input");
  for (i=0; i<loadItems.length; i++) {
    loadItems[i].disabled=a;
  }
}

// Returns to the main screen from the Load window.
function justEndLoad() {
  g('loadInfo').innerHTML="";
  disableLoad(false);
  closeAllWindows();
}

// Cancels password and renaming.
function cancelLoad() {
  g('loadInfo').innerHTML="";
  disableLoad(false);
}

// Filesystem specific date
// Day of the month | Day of the Week | Month | Year | Hour | Minute
function giveTime() {
  var clock, year, day, weekday, themonth, hour, min2, actualDate;
  clock=new Date();
  year=clock.getYear();
  themonth=clock.getMonth();
  weekday=clock.getDay();
  day=clock.getDate();
  hours=clock.getHours();
  min2=clock.getMinutes();
  if (year<1900) {
    year+=1900;
  }
  actualDate=day+"|N|"+weekday+"|N|"+themonth+"|N|"+year+"|N|"+hours+"|N|";
  actualDate+=(min2<10)?"0"+min2:min2; // Adds zero prefix to the minute value if it is under 10.
  return actualDate;
}

// Parses filesystem date pattern into human readable text.
function readDate(savedDate) {
  var q=savedDate.split("|N|");
  /** Compensate for 12 hour clock **/
  if (!clock24) {
    if (q[4]==12) {q[5]+=" PM";}				// 12:00 PM
    else if (q[4]==0) {q[5]+=" AM"; q[4]=12;}	// 12:00 AM
    else if (q[4]>12) {q[5]+=" PM"; q[4]-=12;}	// >12:00 PM
    else if (q[4]<12) {q[5]+=" AM";}			// <12:00 PM
  }
  
  return (week[q[1]]+", "+q[0]+" "+month[q[2]]+", "+q[3]+",<br>"+q[4]+":"+q[5]);
}

// File info
function getInfo() {
  if (loaded<0) {
    g('loadInfo').innerHTML="You haven't selected a file.";
    return;
  }
  var temp=data.get("Velt_2").split("|F|");
  var q=temp[loaded].split("|P|");
  var message="<q>"+q[0]+"</q> was last saved<br>"+readDate(q[2])+".<br><br>It is "+((q[1]=="|N|")?'<strong>NOT</strong> ':'')+"password protected.";
  if (q[1]=="|N|") {
    message+="<br><br>It is a "+g('newFileType').options[q[11]].text+" and it contains "+(q[3].split("|S|").length)+" slides.";
  }
  g('loadInfo').innerHTML=message;
}

function setArraysFromSave(c_name, a, cp) {
  var temp = data.get(c_name).split("|F|")[(cp) ? 0 : a].split("|P|");
  activeFileType = temp[11]; // File type
  activeFile = a;
  curSlide = 0;
  slideContent = temp[3].split("|S|");
  slideNotes = temp[4].split("|S|");
  resetDefaultSlideValues();
  
  /*** Gets formatting ***/
  var loadBacks = [];
  var loadLinks = [];
  var loadLists = [];
  var loadSpace = [];
  var loadLayout = [];
  var loadTrans = [];
  var loadTiming = [];
  
  if (temp.length == 12) {
    temp.push([]);
    temp.push("|N|");
    temp.push("|N|");
    var tmp = temp[3].split("|S|").length;
    for (i=0; i<tmp; i++) {
      temp[12].push([]);
      temp[12][i] = [].concat(defaultSlideTransitions);
      temp[12][i] = temp[12][i].join("|N|");
    }
    temp[12] = temp[12].join("|S|");
  }
    
  for (i=0; i<slideContent.length; i++) {
    loadBacks[i] = temp[5].split("|S|")[i].split("|N|");

    if (activeFileType == 0 || activeFileType == 1) {
      loadLinks[i] = temp[6].split("|S|")[i].split("|N|");
      loadLists[i] = temp[7].split("|S|")[i].split("|N|");
      loadSpace[i] = temp[8].split("|S|")[i].split("|N|");
    }
    if (activeFileType == 2 || activeFileType == 3) {
      loadBacks[i] = loadBacks[i][0];
    }

    loadLayout[i] = temp[9].split("|S|")[i].split("|N|");
    loadTrans[i] = temp[12].split("|S|")[i].split("|N|");
    
    // Slide Timing
    if (temp[13] == "|N|") {
      loadTiming[i] = [].concat(defaultSlideTiming);
      continue;
    }
    
    loadTiming[i] = temp[13].split("|S|")[i].split("|N|");
    loadTiming[i][0] = loadTiming[i][0] == "1";
    loadTiming[i][1] = parseInt(loadTiming[i][1]);
    loadTiming[i][2] = parseInt(loadTiming[i][2]);
  }

  if (activeFileType == 0 || activeFileType == 1) {
    slideBacks = [].concat(loadBacks);
    slideLinks = [].concat(loadLinks);
    slideLists = [].concat(loadLists);
    slideSpace = [].concat(loadSpace);
    g('contentFrame').contentWindow.document.getElementsByTagName('html')[0].style.padding = '';
  }
  slideLayout = [].concat(loadLayout);
  slideTrans = [].concat(loadTrans);
  slideTiming = [].concat(loadTiming);
  
  // S5 Edit File Info
  if (activeFileType == 2 || activeFileType == 3) {
    var tempMeta = temp[8].split("|N|");
    g('efiN').value = tempMeta[0];
    g('efiC').value = tempMeta[1];
    g('efiE').value = tempMeta[2];
    g('efiD').value = tempMeta[3];
    g('efiS').value = tempMeta[5];
    g('efiL').value = tempMeta[6];
    g('efiV').value = tempMeta[7];
    g('efiW').value = tempMeta[9];
    g('editFileSelectTL').selectedIndex = parseInt(tempMeta[10]);
    g('editFileSelectTR').selectedIndex = parseInt(tempMeta[11]);
    g('editFileSelectBL').selectedIndex = parseInt(tempMeta[12]);
    g('editFileSelectBR').selectedIndex = parseInt(tempMeta[13]);
    updateOverlay();
    applyPreview();
    g('contentFrame').contentWindow.document.getElementsByTagName('html')[0].style.padding = '20px 0';
  }

  // Sets the number of slides
  g('slideList').innerHTML = '';
  for (i=0; i<slideContent.length; i++) {
    g('slideList').innerHTML += "<div onclick='changeSlide(" + g('slideList').getElementsByTagName('div').length + ");'></div>"
  }
  
  var tmp = g('contentFrame').contentWindow.document.createElement('style');
  tmp.appendChild(g('contentFrame').contentWindow.document.createTextNode(layoutCSS));
  g('contentFrame').contentWindow.document.getElementsByTagName('head')[0].appendChild(tmp);

  // Custom Fields
  g('customFieldChildren').innerHTML = '';
  if (temp[10] != "|N|") {
    customFields = temp[10].split("|S|");
    for (i=0; i<customFields.length; i++) {
      customFields[i] = customFields[i].split("|N|");
      g('customFieldChildren').innerHTML += "<option>" + customFields[i][0] + "</option>"; // Sets up every custom field
    }
  }
  // File had no custom fields
  else {
    customFields = [];
  }
  
  // Velt file
  if (activeFileType == 0 || activeFileType == 1) {
    g('footStrip').getElementsByTagName('button')[3].style.display = 'inline'; // Enable HTML toggling
    for (i=0; i<showVelt.length; i++) {
      showVelt[i].style.display = (showVelt[i].nodeName == "DIV") ? "block" : "inline";
    }
    for (i=0; i<showS5.length; i++) {
     showS5[i].style.display = "none";
    }
    defaultSlideLayout = ["2", ""];
  }
  
  // S5 file
  if (activeFileType == 2 || activeFileType == 3) {
    for (i=0; i<showVelt.length; i++) {
      showVelt[i].style.display = "none";
    }
    for (i=0; i<showS5.length; i++) {
      showS5[i].style.display = (showS5[i].nodeName == "DIV") ? "block" : "inline";
    }
    defaultSlideLayout = [0, ''];
	
    slideBacks = loadBacks;
    g('S5headText').value = slideBacks[0];
    newSlideLayout[0] = 0;
  }
  
  // Velt logbook
  if (activeFileType == 1) {
    slideBacks.push([].concat(newSlideBacks));
    slideLinks.push([].concat(newSlideLinks));
    slideLists.push([].concat(newSlideLists));
    slideSpace.push([].concat(newSlideSpace));
    slideTrans.push([].concat(newSlideTransitions));
    slideTiming.push([].concat(newSlideTiming));
    slideLayout.push([20, ""]);
    
    curSlide = g('slideList').getElementsByTagName('div').length;
    g('slideList').innerHTML += "<div onclick='changeSlide(" + g('slideList').getElementsByTagName('div').length + ");'></div>";
    slideNotes.push("");
    slideContent.push(getDateTime(parseInt(data.get("Velt_2_skinGlobal").split("|N|")[3])) + "<br /><br />LOG");
    newSlideLayout[0] = 20;
  }
  // S5 Logbook
  if (activeFileType == 3) {
    curSlide = g('slideList').getElementsByTagName('div').length;
    g('slideList').innerHTML += "<div onclick='changeSlide(" + g('slideList').getElementsByTagName('div').length + ");'></div>";
    slideNotes.push("");
    slideContent.push("");
    slideBacks.push(getDateTime(parseInt(data.get("Velt_2_skinGlobal").split("|N|")[3])));
    slideLayout.push([0, ""]);
    slideTrans.push([].concat(newSlideTransitions));
    slideTiming.push([].concat(newSlideTiming));
    newSlideLayout=[0, ""];
  }
  
  // Current Notes
  g('notesText').value = slideNotes[curSlide];
  
  // Current Content
  g('contentFrame').contentWindow.document.body.innerHTML = slideContent[curSlide];
  g('textWindow').value = slideContent[curSlide];
  
  g('S5headText').value = slideBacks[curSlide];
  g('noteNum').innerHTML = curSlide+1;
  
  slideListColors();
  if (activeFile > -1) {
    setFormatting();
  }
  forceRepaint();
}

// Takes a save from the cookie and writes it to the current window.
function loadSave() {
  if (loaded<0) {
    g('loadInfo').innerHTML="You haven't selected a file.";
    return;
  }
  var temp=data.get("Velt_2").split("|F|");
  var q=temp[loaded].split("|P|");
  
  // If password exists, prompts user for it.
  if (q[1]!="|N|") {
    disableLoad(true);
    g('loadInfo').innerHTML="Please enter the file's <strong>password</strong> to continue.";
    g('loadInfo').innerHTML+="<form class='invisiForm' action='' onsubmit='continueLoadingFromPass();return false;'><fieldset><input id='verbox' type='password'>";
    g('loadInfo').innerHTML+="<input type='button' onclick='continueLoadingFromPass();' value='OK'></fieldset></form>";
  }
  else {
    setArraysFromSave("Velt_2", loaded);
    loaded=-1;
    justEndLoad();
  }
}

// Continues loading a file that has a password.
function continueLoadingFromPass() {
  var temp=data.get("Velt_2").split("|F|");
  var q=temp[loaded].split("|P|");
  
  // Checks old password to make sure it's the right one.
  if (q[1]!=g('verbox').value) {
    cancelLoad();
    g('loadInfo').innerHTML="That password is incorrect.";
    return;
  }
  setArraysFromSave("Velt_2", loaded);
  loaded=-1;
  justEndLoad();
}

// Changes the password of a save.
function changePass() {
  if (loaded<0) {
    g('loadInfo').innerHTML="You haven't selected a file.";
    return;
  }
  var temp=data.get("Velt_2").split("|F|");
  var q=temp[loaded].split("|P|");
  
  disableLoad(true);
  g('loadInfo').innerHTML="Do you want to change the password of <q>"+q[0]+"</q>?<div>";
  g('loadInfo').innerHTML+="<input type='button' style='margin:5px;' onclick='finishPass();' value='Yes'>";
  g('loadInfo').innerHTML+="<input type='button' style='margin:5px;' onclick='cancelLoad();' value='No'></div>";
}

// Asks for previous password.
function finishPass() {
  var temp=data.get("Velt_2").split("|F|");
  var q=temp[loaded].split("|P|");
  
  // If save had previous password, asks for it.
  if (q[1]!="|N|") {
    g('loadInfo').innerHTML="Please enter the <strong>current</strong> password.";
    g('loadInfo').innerHTML+="<form class='invisiForm' action='' onsubmit='verifyOldPassword();return false;'><fieldset>";
    g('loadInfo').innerHTML+="<input id='verbox' type='password'><input type='button' style='margin-left:5px;' onclick='verifyOldPassword();' value='OK'></fieldset></form>";
  }
  else {
    g('loadInfo').innerHTML="Please enter the <strong>NEW</strong> password.";
    g('loadInfo').innerHTML+="<form class='invisiForm' action='' onsubmit='setNewPassword();return false;'><fieldset>";
    g('loadInfo').innerHTML+="<input id='newbox' type='password'><input type='button' style='margin-left:5px;' onclick='setNewPassword();' value='OK'></fieldset></form>";
  }
}

// Verifies the old password before changing to a new one.
function verifyOldPassword() {
  var temp=data.get("Velt_2").split("|F|");
  var q=temp[loaded].split("|P|");
  
  // Checks old password to make sure it's the right one.
  if (q[1]!=g('verbox').value) {
    cancelLoad();
    g('loadInfo').innerHTML="That password is incorrect.";
    return;
  }

  g('loadInfo').innerHTML="Please enter the <strong>NEW</strong> password.";
  g('loadInfo').innerHTML+="<form class='invisiForm' action='' onsubmit='setNewPassword();return false;'><fieldset>";
  g('loadInfo').innerHTML+="<input id='newbox' type='password'><input type='button' style='margin-left:5px;' onclick='setNewPassword();' value='OK'></fieldset></form>";
}

// Sets the new password.
function setNewPassword() {
  var temp=data.get("Velt_2").split("|F|");
  var q=temp[loaded].split("|P|");
  
  // Updates the password
  q[1]=(g('newbox').value=='') ? "|N|" : g('newbox').value;
  q[2]=giveTime();
  
  // Gets everything back together
  temp[loaded]=q.join("|P|");
  data.set("Velt_2", temp.join("|F|"));
  
  disableLoad(false);
  loadList();
  g('loadInfo').innerHTML="<q>"+q[0]+"</q> has had its password changed.";
}

// Renames selected save.
function rename() {
  if (loaded<0) {
    g('loadInfo').innerHTML="You haven't selected a file.";
    return;
  }
  var temp=data.get("Velt_2").split("|F|");
  var q=temp[loaded].split("|P|");
  
  disableLoad(true);
  g('loadInfo').innerHTML="Do you want to rename <q>"+q[0]+"</q>?<div>";
  g('loadInfo').innerHTML+="<input type='button' class='miniButton' style='margin:5px;' onclick='checkNameForPass();' value='Yes'>";
  g('loadInfo').innerHTML+="<input type='button' class='miniButton' style='margin:5px;' onclick='cancelLoad();' value='No'></div>";
}

// Asks the user for the file's password before allowing rename.
function checkNameForPass() {
  var temp=data.get("Velt_2").split("|F|");
  var q=temp[loaded].split("|P|");
  
  // If password exists, prompts user for it.
  if (q[1]!="|N|") {
    g('loadInfo').innerHTML="Please enter the file's <strong>password</strong> to continue.<form class='invisiForm' action='' onsubmit='continueNamingFromPass();return false;'><fieldset>";
    g('loadInfo').innerHTML+="<input id='verbox' type='password'><input type='button' style='margin-left:5px;' onclick='continueNamingFromPass();' value='OK'></fieldset></form>";
  }
  else {
    g('loadInfo').innerHTML="Please enter the file's <strong>NEW</strong> name.<form class='invisiForm' action='' onsubmit='setNewName();return false;'><fieldset>";
    g('loadInfo').innerHTML+="<input id='newbox' type='text'><input type='button' style='margin-left:5px;' onclick='setNewName();' value='OK'></fieldset></form>";
  }
}

// Verify file's password before allowing rename.
function continueNamingFromPass() {
  var temp=data.get("Velt_2").split("|F|");
  var q=temp[loaded].split("|P|");
  
  // Checks old password to make sure it's the right one.
  if (q[1]!=g('verbox').value) {
    cancelLoad();
    g('loadInfo').innerHTML="That password is incorrect.";
    return;
  }
  
  // Allow user to rename file
  g('loadInfo').innerHTML="Please enter the file's <strong>NEW</strong> name.<form class='invisiForm' action='' onsubmit='setNewName();return false;'><fieldset>";
  g('loadInfo').innerHTML+="<input id='newbox' type='text'><input type='button' style='margin-left:5px;' onclick='setNewName();' value='OK'></fieldset></form>";
}

// Sets the new name of the file.
function setNewName() {
  var temp=data.get("Velt_2").split("|F|");
  var q=temp[loaded].split("|P|");
  
  // Updates the password
  q[0]=g('newbox').value;
  q[2]=giveTime();
  
  // Gets everything back together
  temp[loaded]=q.join("|P|");
  data.set("Velt_2", temp.join("|F|"));

  g('loadInfo').innerHTML="The file has been renamed.";
  loadList();
  disableLoad(false);
}

/** Logbook function **/
function toggleLogbook() {
  if (loaded<0) {
    g('loadInfo').innerHTML="You haven't selected a file.";
    return;
  }
  var temp=data.get("Velt_2").split("|F|");
  var q=temp[loaded].split("|P|");
  
  // File has no password
  if (q[1]=="|N|") {
	
	// Velt
    if (q[11]=="0") {q[11]="1";}
	else if (q[11]=="1") {q[11]="0";}
	
	// S5
	if (q[11]=="2") {q[11]="3";}
	else if (q[11]=="3") {q[11]="2";}
	
    g('loadInfo').innerHTML=(q[11]=="1" || q[11]=="3")?"<q>"+q[0]+"</q> is now a logbook.":"<q>"+q[0]+"</q> is no longer a logbook.";
	
    // Gets everything back together
    temp[loaded]=q.join("|P|");
    data.set("Velt_2", temp.join("|F|"));
  }
  // User must jump through hoops
  else {
    disableLoad(true);
    g('loadInfo').innerHTML="Please enter the file's <strong>password</strong> to continue.<form class='invisiForm' action='' onsubmit='continueTogglingLogbook();return false;'><fieldset>";
    g('loadInfo').innerHTML+="<input id='verbox' type='password'><input type='button' style='margin-left:5px;' onclick='continueTogglingLogbook();' value='OK'></fieldset></form>";
  }
}

function continueTogglingLogbook() {
  var temp=data.get("Velt_2").split("|F|");
  var q=temp[loaded].split("|P|");
  
  // Password matches
  if (g('verbox').value==q[1]) {
    // Velt
    if (q[11]=="0") {q[11]="1";}
	else if (q[11]=="1") {q[11]="0";}
	
	// S5
	if (q[11]=="2") {q[11]="3";}
	else if (q[11]=="3") {q[11]="2";}
	
    g('loadInfo').innerHTML=(q[11]=="1" || q[11]=="3")?"<q>"+q[0]+"</q> is now a logbook.":"<q>"+q[0]+"</q> is no longer a logbook.";
    
    // Gets everything back together
    temp[loaded]=q.join("|P|");
    data.set("Velt_2", temp.join("|F|"));
  }
  else {
    g('loadInfo').innerHTML="That password is incorrect.";
  }
  disableLoad(false);
}
