/*
#
#  GreatWebScripts    http://www.GreatWebScripts.com
#
#  Copyright (c)2006-2008, GreatWebScripts. All rights reserved.
#
#  No portion of this content may be copied, distributed or reproduced for any
#  reason without the express written consent of the owner. Federal copyright
#  law prohibits unauthorized reproduction by any means and imposes severe fines
#  for violation.
#

#
#  $RCSfile: photocap_server.js,v $ $Revision: 1.10 $   $Date: 2008-11-26 13:43:48-05 $
#
*/

//
// Constants: not changed in code
//

// Number of mSec in blink
HILITE_TIMERVALUE = 500;

// Number of times to blink
HILITE_COUNT      = 5;

// Color to use when hilighting entry
HILITE_COLOR = '#ffff99';

// === Constants End  === //



//
// Global Variables: global variables updated
//

// Caption Data (Retrieval)

// Length of timer (poll interval)
var retrievecaptiondata_TimerValue = 15000;  // Default Value - might change

// Timer to reissue retrieve
var retrievecaptiondata_TimerID = 0;


// Caption Data (Hilight)

// Actual Timer
var captionModifiedHilite_TimerID = 0;


// Length of timer (hilight new caption)
var captionModifiedHilite_Inx;                // Times blinked so var

// Array stores ID of modified (hilighted) captions
var captionModifiedHilite_Data = [];

// Latest Date and count of caption data from server
var caption_lastdate = -1;
var caption_lastcount = -1;


// Ballot Data

// Ballot Data (Hilight)

// Length of timer (hilight new ballot)
var ballotModifiedHilite_Inx;                // Times blinked so var

// Actual Timer
var ballotModifiedHilite_TimerID = 0;

// Array stores ID of current ballots
var ballotModifiedDisplayed_Data = [];

// Array stores ID of hilighted ballots
var ballotModifiedHilight_Data = [];

// Latest Date of ballot data from server
var ballot_lastdate = -1;


// Function Globals
var ajaxgws_retrievecaptiondata_photofile;



// === Global Variables End  === //



// Function Group: ajaxgws_retrievecaptiondata
//   Read the caption data (for the peek display)
//


// Called first time
function ajaxgws_retrievecaptiondata_timed (photofile, interval)
{
  // Save off input parameters
  ajaxgws_retrievecaptiondata_photofile = photofile;
  retrievecaptiondata_TimerValue = interval;

  // And do it
  ajaxgws_retrievecaptiondata_timer_cb ();

  // Set the timer if not running already
  // (Note: interval timer expires repeatedly)
  if (retrievecaptiondata_TimerID == 0)
    retrievecaptiondata_TimerID =
        setInterval ('ajaxgws_retrievecaptiondata_timer_cb()', retrievecaptiondata_TimerValue);
} // end ajaxgws_retrievecaptiondata_timed


// Timer Callback
function ajaxgws_retrievecaptiondata_timer_cb ()
{
  x_ajaxgws_retrievecaptiondata (ajaxgws_retrievecaptiondata_photofile, ajaxgws_retrievecaptiondata_cb );
} // end ajaxgws_retrievecaptiondata_timer_cb


// Main Function
function ajaxgws_retrievecaptiondata_cb (response)
{
  var innerHTML = '';         // HTML string built up
  var hilitevalue = false;    // flag indicates a value was changed


  // Parse the Response in XML
  var doc = ajaxgwsc_InitializeXML (response);

  // Save pointer to XML element
  var result = doc.documentElement;

  // Ensure we have something
  if (result != null)
  {
    // Retrieve the date and admin status
    var captiondate = result.getAttribute('lastdate');
    var admin = result.getAttribute('admin');
    var count = result.getAttribute('count');

    // Validate the pieces are found
    if (! document.getElementById('caption_peek_frame')) return;

    // Process only if newer data available
    if ( (captiondate > caption_lastdate) || (count != caption_lastcount) )
    {
      var captions = result.getElementsByTagName('caption');

      // Clear the array of hilighted items
      ajaxgws_CaptionHiliteclear ();

      // Number of captions
      var capcount = 0;
      if (null !== captions) capcount = captions.length;

      innerHTML +=
          "<table id='caption_peek_table' cellspacing='8'>";

      // Loop over all captions
      for (inx=0; inx < capcount; inx++)
      {
        // Extract the record
        captionrecord = captions [inx];
        memberid = captionrecord.getAttribute ('memberid');
        status = captionrecord.getAttribute ('status');

        // Find the data associated with the node
        captionrecorddata = captionrecord.childNodes;

        // Default Initializations
        mine='?';submittor='?';datetime='?';captiontext='?';uxdatetime=0;

        // And loop over all the nodes
        for (iinx=0; iinx < captionrecorddata.length; iinx++)
        {
          // Extract name and value
          name = captionrecorddata [iinx].nodeName;
          value = ajaxgwsc_getInnerText (captionrecorddata [iinx]);

          // Extract the data for the node
          switch (name)
          {
            case 'Mine': mine = value; break;
            case 'Submittor': submittor = value; break;
            case 'Datetime': datetime = value; break;
            case 'Captiontext': captiontext = value; break;
            case 'uxDatetime': uxdatetime = value; break;
          } // end switch (name)

        } // end for (iinx=0; iinx < captionrecorddata.length; iinx++)


        // If any value modified save in the array and set the timer flag
        if ((caption_lastdate > 0) && (uxdatetime > caption_lastdate))
        {
          hilitevalue = true;
          captionModifiedHilite_Data [captionModifiedHilite_Data.length] =inx;
        } // end if (ismodified != '?')


        // Check for my own captions
        if (mine == 'Yes')
        {
           thisclass = 'caption_peek_panel_me';
           heading = "* Your Caption * ";
        }
        else
        {
          thisclass = 'caption_peek_panel';
          heading = "";
        } // end if (mine = 'Yes')

        innerHTML +=
           "<tr class='" + thisclass + "'>" +
           "<td  ID='caprow_" + inx + "' class='caption_peek_panel_row'>" ;


        // Only admin can see member
        if (admin == 'Yes')
        {
           innerHTML +=
              "<span class='caption_peek_panel_submittor'>" +
              "Submitted by: " + submittor +
              "</span>" +
              "&nbsp;&nbsp;&nbsp;";
        } // end if ($admin)

        // Date/time
        innerHTML +=
          "<span class='caption_peek_panel_date'>" +
          datetime +
          "</span>";

        // Display notice if own caption
        if (heading != '')
        {
          innerHTML +=
            "&nbsp;&nbsp;&nbsp;" +
            "<span class='caption_peek_panel_own'>" +
             heading +
            "</span>";
        } // end  if (heading != '')

        innerHTML +=
           "<br>" +
           "<span class='caption_peek_panel_caption'>" +
           captiontext +
           "</span>" +
           "</td>";

        // End of Row
        innerHTML +=
           "</tr>";
      } // end for (inx=0; inx< captions.length; inx++)

      // End the Table
      innerHTML +=
         "<tr><td> <br> </td></tr>" +
         "</table>";

      // Any captions found?
      if (capcount == 0)
      {
         innerHTML = "<div class='successmsg'>";
         innerHTML += "<br>No captions have been entered yet";
         innerHTML += "</div>";
      } // end if (capcount == 0)

      // Do it!
      document.getElementById('caption_peek_frame').innerHTML = innerHTML;
      document.getElementById('caption_peek_frame_title_count').innerHTML = capcount;
    } // end if ( (captiondate > caption_lastdate) || (count != caption_lastcount) )

    // Save off the latest date
    caption_lastdate = captiondate;
    caption_lastcount = count;


    // If a value was modified set the hilight (blink) timer
    if (hilitevalue == true)
    {
      // Set the counter to the Hilight count -- twice because each
      // blink takes two cycles (off -> on)
      captionModifiedHilite_Inx = 2 * HILITE_COUNT;
      ajaxgws_hilitecaptiondata_timer_cb ();
    } // if (hilitevalue == true)

  } // end if (result != null)

} // end ajaxgws_retrievecaptiondata_cb


//
// Called to clear all hilights in input array
//
function ajaxgws_CaptionHiliteclear ()
{
   // Loop over every caption to remove hilight
   for (inx=0; inx < captionModifiedHilite_Data.length; inx++)
   {
     // inxvalue is the ID of the index that changed
     inxvalue = captionModifiedHilite_Data [inx];

     // Set the color of the associated element
     document.getElementById('caprow_' +inxvalue).style.backgroundColor = 'transparent';

   } // end for (inx=0; inx < captionModifiedHilite_Data.length; inx++)

   // And clear the array
   captionModifiedHilite_Data = [];

   // If the timer is running clear it
   if (captionModifiedHilite_TimerID != 0) clearTimeout (captionModifiedHilite_TimerID);
   captionModifiedHilite_TimerID = 0;

} // end ajaxgws_CaptionHiliteclear


//
// Callback to hilight caption data
//
function ajaxgws_hilitecaptiondata_timer_cb ()
{

   // Decrement the blink count
   captionModifiedHilite_Inx -= 1;

   // Use even/odd to determine if we are hilighting or un-hilighting
   if (captionModifiedHilite_Inx < 0)           hilight = false;  // De Hilite
   else if (captionModifiedHilite_Inx % 2 == 0) hilight = true;   // Hilite
   else                                         hilight = false;  // De Hilight

   // Determine the color based on hilight flag
   if (hilight) bgColor = HILITE_COLOR;
   else         bgColor = 'transparent';

   // Loop over every caption to hilight
   for (inx=0; inx < captionModifiedHilite_Data.length; inx++)
   {
     // inxvalue is the ID of the index that changed
     inxvalue = captionModifiedHilite_Data [inx];

     // Set the color of the associated element
     document.getElementById('caprow_' +inxvalue).style.backgroundColor = bgColor;

   } // end for (inx=0; inx < captionModifiedHilite_Data.length; inx++)

   // Reset the timer- ensure we do not end with hilighted items
   captionModifiedHilite_TimerID = 0; // Timer has expired
   if ((captionModifiedHilite_Inx > 0) || (hilight == true) )
   {
       captionModifiedHilite_TimerID = setTimeout ('ajaxgws_hilitecaptiondata_timer_cb()', HILITE_TIMERVALUE);
   } // end if ((captionModifiedHilite_Inx > 0) || (hilight == true) )

} // end ajaxgws_hilitecaptiondata_timer_cb


// Function Group: ajaxgws_retrieveuservotingdata
//   Retrieve the Voting Data
//



//
// Callback to process ballot data
//
function ajaxgws_retrieveuservotingdata_cb (response)
{
  var current_vote = 0;  // Temp Use

  var ballots_innerHTML = '';
  var candidates_innerHTML = '';

  // Parse the Response in XML
  var doc = ajaxgwsc_InitializeXML (response);

  // Save pointer to XML element
  var result = doc.documentElement;

  // Ensure we have something
  if (result != null)
  {

    // Validate the pieces are found
    if (! document.getElementById('vote_captiontable_voted_frame')) return;
    if (! document.getElementById('vote_captiontable_unvoted_frame')) return;


    // Clear the array of hilighted items
    ajaxgws_BallotHiliteclear ();


    // Need to check for notice

    // Extract photofile
    var photofile = result.getAttribute ('photofile');
    var votedate = result.getAttribute('lastdate');

    //
    // Ballot Processing
    //

    // Extract ballots
    var ballots = result.getElementsByTagName('ballot');

    // Number of ballots
    var ballotscount = 0;
    if (null !== ballots) ballotscount = ballots.length;

    if (ballotscount > 0)
    {
      ballots_innerHTML +=
            "<table class='vote_captiontable_captions_table' ID='vote_captiontable_voted_table'>";

      for (inx=0; inx < ballotscount; inx++)
      {
         // Votes are zero based
         current_vote = inx + 1;

         // Find the data associated with the node
         ballotrecord = ballots [inx];

         // Find the data associated with the node
         ballotrecorddata = ballotrecord.childNodes;

         // Default Initializations
         member_id='?';caption_inx='?';caption='?';uxdatetime=0;

         // And loop over all the nodes
         for (iinx=0; iinx < ballotrecorddata.length; iinx++)
         {
           // Extract name and value
           name = ballotrecorddata [iinx].nodeName;
           value = ajaxgwsc_getInnerText (ballotrecorddata [iinx]);

           // Extract the data for the node
           switch (name)
           {
             case 'member_id': member_id = value; break;
             case 'caption_inx': caption_inx = value; break;
             case 'caption': caption = value; break;
             case 'uxDatetime': uxdatetime = value; break;
           } // end switch (name)

         } // end for (iinx=0; iinx < ballotrecorddata.length; iinx++)

         // Determine whether the ballot was modified
         captionID =  member_id + "_" + caption_inx;

         if (ballotModifiedDisplayed_Data [inx] != undefined)
           if (ballotModifiedDisplayed_Data [inx] != captionID)
               ballotModifiedHilight_Data [ballotModifiedHilight_Data.length] = inx;
         ballotModifiedDisplayed_Data [inx] = captionID;

         // Begin Display
         ballots_innerHTML += "<tr ID='vote_captiontable_panel'>";

         ballots_innerHTML +=
             "<td ID='ballot_id_row_" +inx+ "' class='vote-table-td-index'>" +
             current_vote + ':' +
             "</td>";

         // Check if there was data
         if (member_id != '?')
         {
             //  Vote indicator
             ballots_innerHTML +=
                    "<td ID='ballot_selector_row_" +inx+ "' class='vote-table-td-pulldown'>" +
                    "<select name=\"vote_"+member_id+"_"+caption_inx+"\"  " +
                    "   onchange=\"javascript:x_ajaxgws_saveuservotingdata ('"+photofile+"',"+member_id+","+caption_inx+",this.options[this.selectedIndex].value,ajaxgws_retrieveuservotingdata_cb);\"> " +
                    "<option value='0'>["+current_vote+"]" +  // Current Value (default) option
                    "<option value='delete'>Remove" ;         // Delete option

              // Display the voting selection, but don't let user choose same vote value
              for (vote_inx=1; vote_inx <= ballotscount; vote_inx++)
                if (vote_inx != current_vote)
                   ballots_innerHTML += "<option value='"+vote_inx+"'>"+vote_inx;
              ballots_innerHTML += "</select> ";
              ballots_innerHTML += "</td>";

              // Caption
              ballots_innerHTML +=
                      "<td ID='ballot_caption_row_" +inx+ "' class='vote-table-td-caption'>" +
                      caption +
                      "</td>";

         } // end if (member_id != '?')
         else
         {
            ballots_innerHTML +=
                "<td ID='ballot_selector_row_" +inx+ "' class='vote-table-td-pulldown_null'>-</td>" +
                "<td ID='ballot_caption_row_" +inx+  "' class='vote-table-td-caption'>" +
                "<span class='vote-table-td-caption-none'>You Have Not Selected a #" +current_vote+ " Entry</span>" +
                "</td>";

         } // end else to: if (member_id != '?')

         ballots_innerHTML += "</tr>";
      } // end for (inx=0; inx < ballotscount; inx++)

      ballots_innerHTML += "</table>";

    } // end if (ballotscount > 0)


    //
    // Candidate Processing
    //

    // Extract candidates
    var candidates = result.getElementsByTagName('candidate');

    // Number of candidates
    var candidatecount = 0;
    if (null !== candidates) candidatecount = candidates.length;


    if (candidatecount > 0)
    {
      candidates_innerHTML +=
            "<table class='vote_captiontable_captions_table' id='vote_captiontable_unvoted_table'>";

      // Loop over all captions
      for (inx=0; inx < candidatecount; inx++)
      {
        // Votes are zero based
        current_vote = inx + 1;

        // Extract the record
        candidaterecord = candidates [inx];

        // Find the data associated with the node
        candidaterecorddata = candidaterecord.childNodes;

        // And loop over all the nodes
        member_id='?';caption_inx='?';caption='?';
        for (iinx=0; iinx < candidaterecorddata.length; iinx++)
        {
          // Extract name and value
          name = candidaterecorddata [iinx].nodeName;
          value = ajaxgwsc_getInnerText (candidaterecorddata [iinx]);

          // Extract the data for the node
          switch (name)
          {
            case 'member_id': member_id = value; break;
            case 'caption_inx': caption_inx = value; break;
            case 'caption': caption = value; break;
          } // end switch (name)

        } // end for (iinx=0; iinx < candidaterecord.length; iinx++)

        candidates_innerHTML +=
             "<tr>" +
             "<td class='vote-table-td-pulldown' >";

        //  Vote indicator
        candidates_innerHTML +=
             "<select name='vote_"+member_id+"_"+caption_inx+"'  " +
             "   onchange=\"javascript:x_ajaxgws_saveuservotingdata ('"+photofile+"',"+member_id+","+caption_inx+",this.options[this.selectedIndex].value,ajaxgws_retrieveuservotingdata_cb);\"> " +
             "<option value='0'>*VOTE*"; // Blank (default) option


        for (vote_inx=1; vote_inx <= ballotscount; vote_inx++)
             candidates_innerHTML += "<option value='"+vote_inx+"'>"+vote_inx;
        candidates_innerHTML += "</select> ";
        candidates_innerHTML += "</td>";

        // Caption
        candidates_innerHTML +=
            "<td class='vote-table-td-caption' >" +
            caption +
            "</td>";
        candidates_innerHTML += "</tr>";

      } // end for (inx=0; inx < candidatecount; inx++)

      candidates_innerHTML += "</table>";
    } // end if (candidatecount > 0)

    else
    {
       candidates_innerHTML += "<div class='failuremsg'>";
       candidates_innerHTML += "<br>There are no captions for you to vote";
       candidates_innerHTML += "</div>";
    } // end else to: if (candidatecount > 0)

    // Save off the latest date
    ballot_lastdate = votedate;

    // Do it!
    document.getElementById('vote_captiontable_voted_frame').innerHTML = ballots_innerHTML;
    document.getElementById('vote_captiontable_unvoted_frame').innerHTML = candidates_innerHTML;

    // If something to hilight then do it
    if (ballotModifiedHilight_Data.length > 0)
    {
       ballotModifiedHilite_Inx = 2 * HILITE_COUNT;
       ajaxgws_hilitballotdata_timer_cb ();
    } // end if (ballotModifiedHilight_Data.length > 0)
  } // end if (result != null)

} // end ajaxgws_retrieveuservotingdata_cb

//
// Hilights the modified ballot data
//
function ajaxgws_hilitballotdata_timer_cb ()
{

   // Decrement the blink count
   ballotModifiedHilite_Inx -= 1;

   // Use even/odd to determine if we are hilighting or un-hilighting
   if (ballotModifiedHilite_Inx < 0)           hilight = false;  // De Hilite
   else if (ballotModifiedHilite_Inx % 2 == 0) hilight = true;   // Hilite
   else                                        hilight = false;  // De Hilight

   // Determine teh color based on hilight flag
   if (hilight) bgColor = HILITE_COLOR;
   else         bgColor = 'transparent';

   // Loop over every caption to hilight
   for (inx=0; inx < ballotModifiedHilight_Data.length; inx++)
   {
     // inxvalue is the ID of the index that changed
     inxvalue = ballotModifiedHilight_Data [inx];

     // Set the color of the associated elements
     document.getElementById('ballot_id_row_' +inxvalue).style.backgroundColor = bgColor;
     document.getElementById('ballot_selector_row_' +inxvalue).style.backgroundColor = bgColor;
     document.getElementById('ballot_caption_row_' +inxvalue).style.backgroundColor = bgColor;

   } // end for (inx=0; inx < captionModifiedHilite_Data.length; inx++)

   // Reset the timer- ensure we do not end with hilighted items
   ballotModifiedHilite_TimerID = 0;  // Timer expired
   if ((ballotModifiedHilite_Inx > 0) || (hilight == true) )
   {
       ballotModifiedHilite_TimerID = setTimeout ('ajaxgws_hilitballotdata_timer_cb()', HILITE_TIMERVALUE);
   } // end if ((captionModifiedHilite_Inx > 0) || (hilight == true) )

} // end ajaxgws_hilitballotdata_timer_cb


//
// Called to clear all ballots hilighted in input array
//
function ajaxgws_BallotHiliteclear ()
{
   // Loop over every caption to remove hilight
   for (inx=0; inx < ballotModifiedHilight_Data.length; inx++)
   {
     // inxvalue is the ID of the index that changed
     inxvalue = ballotModifiedHilight_Data [inx];

     // Clear the color of the items
     document.getElementById('ballot_id_row_' +inxvalue).style.backgroundColor = 'transparent';
     document.getElementById('ballot_selector_row_' +inxvalue).style.backgroundColor = 'transparent';
     document.getElementById('ballot_caption_row_' +inxvalue).style.backgroundColor = 'transparent';
   } // end for (inx=0; inx < ballotModifiedHilight_Data.length; inx++)

   // And clear the array
   ballotModifiedHilight_Data = [];

   // If the timer is running clear it
   if (ballotModifiedHilite_TimerID != 0) clearTimeout (ballotModifiedHilite_TimerID);
   ballotModifiedHilite_TimerID = 0;

} // end ajaxgws_BallotHiliteclear



function ajaxgws_save1caption_cb (response)
{

  // Parse the Response in XML
  var doc = ajaxgwsc_InitializeXML (response);

  // Save pointer to XML element
  var result = doc.documentElement;

  // Ensure we have something
  if (result != null)
  {
    // Retrieve status
    var status = result.getAttribute('status');
    var inx = result.getAttribute('id');

    // Find the corresponding error status icon
    icon = document.getElementById('caption_erricon_'+inx);
    caption = document.getElementById('caption_'+inx);

    // Check if error returned or not
    if (status.length > 0)
    {
      icon.style.visibility="visible";
      icon.title = status;
      caption.className = 'caption-error';
    }
    else
    {
      icon.style.visibility="hidden";
      icon.title = 'No Error';
      caption.className = 'caption-original';
    } // end if (status.length > 0)

  } // end if (result != null)

  // Rebuild the peek display
  ajaxgws_retrievecaptiondata_timer_cb ();

} // end ajaxgws_save1caption_cb


function ajaxgws_save1caption (caption, inx, me, photofile)
{
 // Save it
 x_ajaxgws_saveusercaptiondata (encodeURI (caption.value), inx, me, photofile, ajaxgws_save1caption_cb);

 // Restore the graphic values
 caption.defaultValue = caption.value;
 caption.className = 'caption-original';

} // end ajaxgws_save1caption

//
// Called to save ALL caption data
//
function ajaxgws_saveallcaptions (count, me, photofile)
{
  for (inx=0; inx <count; inx++)
  {
    caption = document.getElementById('caption_'+inx);

    // If data changed save it
    if (caption.value != caption.defaultValue)
      ajaxgws_save1caption (caption, inx, me, photofile);

  } // end for (inx=0; inx++; inx <count)

} // end ajaxgws_saveallcaptions


// Preview Caption CB
function ajaxgws_previewcaption_cb (response)
{
  // Parse the Response in XML
  var doc = ajaxgwsc_InitializeXML (response);

  // Save pointer to XML element
  var result = doc.documentElement;
  var caption = result.getElementsByTagName('captiondata');

  // Extract data attributes
  var inx = result.getAttribute ('id');
  var status = result.getAttribute ('status');

  var captioninx = parseInt (inx) + 1;

  var previewwin = popupwindow.open("previewbox", "inline", "Loading...", "Caption Preview", "left=150px,top=10px,resize=1,scrolling=0", "recal")
  previewwin.onclose = function() {popupwindow.hide(this); return false;};

  // Generate the caption text
  caption_text = ajaxgwsc_getInnerText (result);

  // Add error text if appropriate
  if (status != '')
    caption_text = "<span id='previewstatus'>" + status + "<br></span>" + caption_text;

  // And display it
  document.getElementById("titleframe").innerHTML = "Caption #" + captioninx;
  document.getElementById("previewframe").innerHTML = caption_text;

  // Find the corresponding error status icon
  icon = document.getElementById('caption_erricon_'+inx);
  caption = document.getElementById('caption_'+inx);


  // Check if error returned or not
  if (status.length > 0)
  {
    icon.style.visibility="visible";
    icon.title = status;
    caption.className = 'caption-error';
  }
  else
  {
    icon.style.visibility="hidden";
    icon.title = '';
    caption.className = 'caption-original';
  } // end if (status.length > 0)


} // end ajaxgws_previewcaption_cb


//
// Called to revert ALL caption data
//
function ajaxgws_revertallcaptions (count)
{

  // Loop over all captions
  for (inx=0; inx <count; inx++)
  {
    caption = document.getElementById('caption_'+inx);

    // Revert all captions
    caption.value = caption.defaultValue;
    caption.className = 'caption-original';

  } // end for (inx=0; inx++; inx <count)

} // end ajaxgws_revertallcaptions


