
var g_NewTextPrompt = "<Type new item text here>"

function LoadAllTextItems()
{
   LoadTextItems(g_AnnouncementsType)
   LoadTextItems(g_CalendarType)
   LoadTextItems(g_PrayerRequestsType)
}

function LoadTextItems(Type)
{
   if (Type == g_AnnouncementsType)
      new CTextItems("iAnnouncements", g_AnnouncementsType)
   else if (Type == g_CalendarType)
      new CTextItems("iCalendar", g_CalendarType)
   else if (Type == g_PrayerRequestsType)
      new CTextItems("iPrayerRequests", g_PrayerRequestsType)
}

function GetFieldID(FieldName, TextItemIDNumber, Type)
{
   return "i" + FieldName
      + "_" + String(Type)
      + "_" + String(TextItemIDNumber)
}

function GetEditFieldID(FieldName, TextItemIDNumber, Type)
{
   return "iEdit" + FieldName
      + "_" + String(Type)
      + "_" + String(TextItemIDNumber)
}

function GetItemTemplate(Type)
{
   var html = ""
   switch (Type)
   {
      case g_AnnouncementsType:
      case g_PrayerRequestsType:
         html += "<div id='{TitleID}' class='Title'>{Title}</div>\n"
         break;
      case g_CalendarType:
         html += "<div id='{DateID}' class='Date'>{Date}</div>\n"
         break;
      default:
         alert("Invalid item template type number");
         break;
   }
   html += "<div id='{BodyID}' class='Body'>{Body}</div>\n"
      + "<div id='{LastUpdatedID}' class='LastUpdated'>Updated: {LastUpdated}</div>\n"
   return html;
}

function SetItemToEditMode(ItemData)
{
   var Buttons = ById(
      GetFieldID("Buttons", ItemData.ID, ItemData.Type))
   Buttons.innerHTML = GetEditButtons(ItemData.ID, ItemData.Type)

   if (ItemData.Type == g_AnnouncementsType
         || ItemData.Type == g_PrayerRequestsType)
   {
      var Title = ById(
         GetFieldID("Title", ItemData.ID, ItemData.Type))
      Title.innerHTML = '<input '
         + 'type="text" '
         + 'style="'
            + 'width:98%;'
            + '" '
         + 'id="' + GetEditFieldID("Title", ItemData.ID, ItemData.Type) + '" '
         + 'value="' + htmlspecialchars(ItemData.Title) + '" '
         + 'tabindex="' + String(GetNextTabIndex()) + '" '
         + '/>'
   }
   else if (ItemData.Type == g_CalendarType)
   {
      var DateField = ById(
         GetFieldID("Date", ItemData.ID, ItemData.Type))
      DateField.innerHTML = GetCalendarField(
            GetEditFieldID("Date", ItemData.ID, ItemData.Type),
               ItemData.Date)
   }

   var Body = ById(GetFieldID("Body", ItemData.ID, ItemData.Type))
   Body.innerHTML = '<textarea '
      + 'type="text" '
      + 'rows="' + String(CalculateTextAreaRows(ItemData.Body, 70)) + '" '
      + 'style="'
         + 'width:98%;'
         + '" '
      + 'id="' + GetEditFieldID("Body", ItemData.ID, ItemData.Type) + '" '
      + 'tabindex="' + String(GetNextTabIndex()) + '" '
      + '>'
      + ItemData.Body
      + '</textarea>'

   if (ItemData.Type == g_AnnouncementsType
         || ItemData.Type == g_PrayerRequestsType)
   {
      var Additional = ById(
         GetFieldID("Additional", ItemData.ID, ItemData.Type))

      if (Trim(ItemData.ShowUntil) == "")
      {
         var ShowUntil = new Date()
         ShowUntil.setDate(ShowUntil.getDate() + 60)
         ItemData.ShowUntil = To8601String(ShowUntil)
      }

      Additional.innerHTML = '<table><tr><td><em>Show until</em>&nbsp;</td><td>'
         + GetCalendarField(
            GetEditFieldID("ShowUntil", ItemData.ID, ItemData.Type),
               ItemData.ShowUntil)
         + '</td></tr></table>'
   }

   var LastUpdated = ById(
      GetFieldID("LastUpdated", ItemData.ID, ItemData.Type))
   LastUpdated.style.display = "none"
}

function SetShortDateString(ContainerID, InputID)
{
   var Container = ById(ContainerID)
   var Input = ById(InputID)
   Container.innerHTML = FormatShortDate(Input.value)
}

function GetCalendarField(FieldID, DateString)
{
   var FieldName = FieldID.replace(/^i/, "")
   var ContainerID = FieldID + '_ShortDateString'
   return '<table '
      + 'style="border:solid 1px #ddd;" '
      + '>'
      + '<tr>'
      + '<td '
         + 'nowrap '
         + 'id="' + ContainerID + '" '
         + 'style="'
            + 'width:9em;'
            + 'font-weight:bold;'
            + '" '
         + '>'
      + FormatShortDate(DateString)
      + '</td>'
      + '<td nowrap>'
      + '<input '
         + 'type="text" '
         + 'name="' + FieldName + '" '
         + 'id="' + FieldID + '" '
         + 'value="' + DateString + '" '
         + 'style="'
            + 'width:5.5em;'
            + 'font-size:8pt;'
            + '" '
         + 'readonly '
         + 'onfocus="this.blur()" '
         + '/>'
      + '</td>'
      + '<td nowrap>'
      + '<img '
         + 'src="/images/Calendar.png" '
         + 'width="16" '
         + 'height="16" '
         + 'onmouseover="SetHandCursor(this)" '
         + 'onmouseout="SetNormalCursor(this)" '
         + 'onclick="'
            + 'scwNextAction=SetShortDateString.runsAfterSCW(this, \''
               + ContainerID + '\', \'' + FieldID + '\');'
                  + 'scwShow(scwID(\''+ FieldID + '\'), this)" '
         + 'style="'
            + 'position:relative;'
            + 'top:2px;'
            + '" '
         + '/>'
      + '</td>'
      + '</tr>'
      + '</table>'
}

function GetEditButtons(ID, Type)
{
   if (g_IsEditing)
   {
      if (ID == 0)
         return GetSaveButton(ID, Type)
      else
         return GetRestartButton(Type)
            + '<div style="margin-bottom:8px;"></div>'
            + GetSaveButton(ID, Type)
            + '<div style="margin-bottom:8px;"></div>'
            + GetDeleteButton(ID, Type)
   }
   else
   {
      if (ID == 0)
         return GetSaveButton(ID, Type)
      else
         return GetEditButton(ID, Type)
            + '<div style="margin-bottom:8px;"></div>'
            + GetDeleteButton(ID, Type)
   }
}

function GetEditButton(ID, Type)
{
   return '<img '
      + 'width="16" '
      + 'height="16" '
      + 'src="/images/EditInformationHS.png" '
      + 'alt="Edit Item" '
      + 'onclick="EditItem(' + String(ID) + ', ' + String(Type) + ')" '
      + 'onmouseover="SetHandCursor(this)" '
      + 'onmouseout="SetNormalCursor(this)" '
      + '/>'
}

function GetDeleteButton(ID, Type)
{
   return '<img '
      + 'width="16" '
      + 'height="16" '
      + 'src="/images/DeleteHS.png" '
      + 'alt="Delete Item" '
      + 'onclick="DeleteItem(' + String(ID) + ', ' + String(Type) + ')" '
      + 'onmouseover="SetHandCursor(this)" '
      + 'onmouseout="SetNormalCursor(this)" '
      + '/>'
}

function GetSaveButton(ID, Type)
{
   return '<img '
      + 'width="16" '
      + 'height="16" '
      + 'src="/images/saveHS.png" '
      + 'onclick="SaveItem(' + String(ID) + ', ' + String(Type) + ')" '
      + 'onmouseover="SetHandCursor(this)" '
      + 'onmouseout="SetNormalCursor(this)" '
      + '/>'
}

function GetRestartButton(Type)
{
   return '<img '
      + 'width="16" '
      + 'height="16" '
      + 'src="/images/RestartHS.png" '
      + 'alt="Cancel" '
      + 'onclick="CancelEditing(' + String(Type) + ')" '
      + 'onmouseover="SetHandCursor(this)" '
      + 'onmouseout="SetNormalCursor(this)" '
      + '/>'
}

function CancelEditing(Type)
{
   g_IsEditing = false
   LoadTextItems(Type)
}

function DeleteItem(ID, Type)
{
   if (!confirm("Delete this item?"))
      return

   var http = GetXmlHttpObject()
   if (!http)
      return

   http.onreadystatechange = function()
   {
      if (http.readyState == 4 && http.status == 200)
      {
         LoadTextItems(Type)
      }
   }

   var params = "Action=Delete&ID=" + String(ID);
   var url = "/UpdateTextItems.php"
   SendPostRequest(http, url, params);
}

function EditItem(ID, Type)
{
   if (g_IsEditing)
   {
      alert("You are currently editing another item.\n"
         + "Please save or cancel editing the other item before editing this one.")
      return
   }

   g_IsEditing = true

   var http = GetXmlHttpObject()
   if (!http)
      return

   http.onreadystatechange = function()
   {
      if (http.readyState == 4 && http.status == 200)
      {
         eval(http.responseText);

         if (Data.length != 1)
         {
            alert("Item not found!\n"
               + "ID: " + String(ID) + "\n"
               + "Type: " + String(Type))
            return
         }

         var ItemData = Data[0]

         SetItemToEditMode(ItemData)
      }
   }
   var url = "/GetTextItems.php?ArrayName=Data&Type="
      + String(Type) + "&ID=" + String(ID);
   SendGetRequest(http, url);
}

function SaveItem(ID, Type)
{
   var http = GetXmlHttpObject()
   if (!http)
      return

   var params
   if (ID == 0)
      params = "Action=Insert"
   else
      params = "Action=Update"
         + "&ID=" + String(ID)

   var FieldNames = new Array()
   switch (Type)
   {
      case g_AnnouncementsType:
      case g_PrayerRequestsType:
         FieldNames.push("Title")
         FieldNames.push("Body")
         FieldNames.push("ShowUntil")
         break;
      case g_CalendarType:
         FieldNames.push("Date")
         FieldNames.push("Body")
         break;
   }
   for (var i in FieldNames)
   {
      var FieldName = FieldNames[i]
      var FieldValue = ById(GetEditFieldID(FieldName, ID, Type)).value
      if (FieldValue == g_NewTextPrompt)
      {
         alert("Please type the item text")
         return
      }
      params += "&" + FieldName + "=" + encodeURIComponent(FieldValue)
   }

   params += "&Type=" + String(Type)
   var url = "/UpdateTextItems.php"

   http.onreadystatechange = function()
   {
      if (http.readyState == 4 && http.status == 200)
      {
         LoadTextItems(Type)
      }
   }
   SendPostRequest(http, url, params)

   g_IsEditing = false;
}

function CTextItem(ItemData, Type)
{
   this.ItemData = ItemData
   this.Type = Type
   this.GetHtml = GetHtml
   this.GetEditWrapper = GetEditWrapper

   function GetHtml()
   {
      var html = GetItemTemplate(this.Type)
      for (var name in this.ItemData)
      {
         var value = this.ItemData[name]
         /*if (name == "Title"
               || name == "Body")
            value = htmlspecialchars(value)*/
         if (name == "Date")
            value = FormatShortDate(value)
         if (name == "Body")
            value = FormatText(value)
         html = html.replace("{" + name + "ID}",
            GetFieldID(name, this.ItemData.ID, this.Type))
         html = html.replace("{" + name + "}", String(value))
      }
      if (g_IsLoggedIn)
         html = this.GetEditWrapper(html)
      return html;
   }

   function GetEditWrapper(html)
   {
      var wrapper = '<table style="'
            + 'width:98%;'
            + 'border-top:dotted 2px #ccc;'
            + 'margin-bottom:1em;'
            + '">'
         + '<tr>'
         + '<td style="'
            + 'vertical-align:top;'
            + 'width:99%;'
            + 'padding:0;'
            + '">'
         + html
         + '</td>'
         + '<td '
            + 'rowspan="2"'
            + 'id="' + GetFieldID("Buttons", this.ItemData.ID, this.Type) + '" '
            + 'style="'
               + 'vertical-align:top;'
               + 'width:1%;'
               + 'padding:10px 0 0 0;'
            + '">'
         + GetEditButtons(this.ItemData.ID, this.Type)
         + '</td>'
         + '</tr>'

      if (this.Type == g_AnnouncementsType
            || this.Type == g_PrayerRequestsType)
      {
         wrapper += '<tr>'
            + '<td '
               + 'id="' + GetFieldID("Additional", this.ItemData.ID, this.Type) + '" '
               + '>'
            + '</td>'
            + '</tr>'
      }

      wrapper += '</table>'

      return wrapper
   }
}

function CTextItems(ContainerID, Type)
{
   var http = GetXmlHttpObject()
   if (!http)
   {
      return
   }

   var SortFunc = GetSortFunction(Type)
   http.onreadystatechange = function()
   {
      if (http.readyState == 4 && http.status == 200)
      {
         ProcessResponse(http.responseText, ContainerID, SortFunc, Type)
      }
   }
   var url = "/GetTextItems.php?ArrayName=Data&Type=" + Type;
   SendGetRequest(http, url);

   function ProcessResponse(JSON, ContainerID, SortFunc, Type)
   {
      eval(JSON);

      if (SortFunc != null)
         Data = Data.sort(SortFunc)

      var Container = ById(ContainerID);

      var html = ""

      var NewItemData
      if (g_IsLoggedIn)
      {
         NewItemData = GetNewTextItemJSON(Type)
         var TextItem = new CTextItem(NewItemData, Type)
         html += TextItem.GetHtml()
      }

      for (var i = 0; i < Data.length; ++i)
      {
         var TextItem = new CTextItem(Data[i], Type)
         html += TextItem.GetHtml()
      }

      if (!g_IsLoggedIn && Data.length == 0)
         Container.innerHTML = "There are currently no items to display."
      else
         Container.innerHTML = html;

      if (g_IsLoggedIn)
         SetItemToEditMode(NewItemData)
   }

   function SortByDate(a, b)
   {
      // Date ascending
      if (a.Date < b.Date)
         return -1
      else if (a.Date > b.Date)
         return 1
      else
         return 0
   }

   function SortByLastUpdated(a, b)
   {
      // LastUpdated descending i.e. most recent first
      var DateA = ToDate(a.LastUpdated)
      var DateB = ToDate(b.LastUpdated)
      if (DateA > DateB)
         return -1
      else if (DateA < DateB)
         return 1
      else
         return 0
   }

   function SortByTitle(a, b)
   {
      // Title ascending
      if (a.Title < b.Title)
         return -1
      else if (a.Title > b.Title)
         return 1
      else
         return 0
   }

   function GetSortFunction(Type)
   {
      switch (Type)
      {
         case g_AnnouncementsType:
            return SortByLastUpdated;
         case g_PrayerRequestsType:
            return SortByTitle;
         case g_CalendarType:
            return SortByDate;
         default:
            return null;
      }
   }
}

function GetNewTextItemJSON(Type)
{
   return {
      "ID":0,
      "Date":To8601String(new Date()),
      "Title":g_NewTextPrompt,
      "Body":g_NewTextPrompt,
      "Type":Type,
      "ShowUntil":"",
      "Created":"",
      "LastUpdated":""
   }
}

