var countdown; 
var reloadTargetHREF;
var theGallery;
var theCapperList;
var theCurrentTime;
var theLatestCappersMessage;
var theLastCaptionTime;
var chatDiv, t, voteCaptionID;
var galleryDelay_ms = 15000;
var m_galleryTimer = 0;
var m_grabTimer = 0;
var m_formLockoutTimer = 0;
var m_maxLockout_ms = 5000;
var voteLink;
var on = 1;
var off = 0;
var no = 2;
var starSRC = [];
starSRC[on] = "image0/star.png";
starSRC[off] = "image0/star_dark.png";
starSRC[no] = "image0/star_off.png";
var captionInEditMode;
var m_editModeIsOn = false;
var captionForm;
var captionID_EM;
var m_captionForm;
var userCaption = [];
var IS_FAVORITE_IMG_URL = "image0/favorite.png";
var IS_FAVORITE_TITLE = "You picked this caption as one of your favorites.";
var IS_CAPTION_SAVE_IMG_URL = "image0/pencil_add.png";
var IS_CANCEL_IMG_URL = "image0/cancel.png";
var IS_LOGIN_FULLPATH = "/users/login.php";
var IS_ADD_CAPTIONPATH = "savecaption.php";

var thePreviews;
var nowPlaying;   
var chatWin;
var chatButton;
var refreshChat = true;
var m_chatOnly = false;


var editFullpath;

try {document.getElementsByClassName('x');}
catch (e)
  {
  document.getElementsByClassName = 
	  function(cl) {
     var mc, Reg, el, i, classes, rm;
     rm = [];
     mc = new Reg('\\b'+cl+'\\b');
     el = this.getElementsByTagName('*');
     for (i = 0; i < el.length; i++) {
     classes = el[i].className;
     if (mc.test(classes)) {rm.push(el[i]);}
     }
    return rm;}; 
	}


  
function updateLink (linkID, searchText, replaceText)
  {
  var link;
  link = document.getElementById(linkID);
  link.href  = link.href.replace(searchText, replaceText);
  }

function captionChanged(captionField) {}

function displayVotes (votes)
  {
  if (votes.length > 0)
    {
    var favorites, favoriteInfo, num, voteDisplay, html, voteButton, numberOfVotes;
    for (num in votes)
       {
       if (votes[num].ID)
         {
         voteDisplay = document.getElementById("voteDisplay_" + votes[num].ID);
         if (voteDisplay)
           {
           numberOfVotes = parseInt(votes[num].N, 10);
           html = '<div class="voteCount" title="' + numberOfVotes + ' vote';
           if (numberOfVotes > 1) {html += 's';}
           html += '">' + numberOfVotes + '</div>';
           voteDisplay.innerHTML = html;
           if (votes[num].UP > 0) 
             {
             voteButton = document.getElementById("voteButton_" + votes[num].ID);
             voteButton.title = IS_FAVORITE_TITLE;
             voteButton.setAttribute("className", "favorite");
             voteButton.setAttribute("class", "favorite");
             }
           } 
         } 
       }  
    }
  }

function updateEdits (edits)
  {
  if (edits.length > 0)
    {
    var caption, cappomaticLogo, num;
    for (num in edits)
       {
       if (edits[num].ID)
         {
         caption = document.getElementById("caption_" + edits[num].ID);
			   if (caption) 
			    {
				  caption.innerHTML = edits[num].Cap;
          cappomaticLogo =  document.getElementById("matic_"+ edits[num].ID);
          if (cappomaticLogo && parseInt(edits[num].Auto, 10) === 0) {cappomaticLogo.style.display = "none";}
          }
        }
       } 
    }
  }

function cancelEdit()
  {
  if (captionInEditMode)
    {
    captionInEditMode.style.display = "inline";
    captionForm.style.display = "none";
    m_editModeIsOn = false;
    }
  return true;
  }  


function switchToForm(link, captionID)
  {
  var caption, formHTML, worked;
  worked = false;
  cancelEdit();
  captionInEditMode = link;
  captionInEditMode.style.display = "none";
  captionID_EM = captionID;
	caption = document.getElementById("caption_" + captionID).innerHTML;
  
  if (caption && YAHOO)
    {
    formHTML = "<form onSubmit='javascript:return ! editCaption(this);'><textarea rows='4' cols='35' id='caption'>" + 
      caption + "</textarea><input type='hidden' id='captionid' value='" + captionID +
      "' /><br /><input type='image' alt='Save changes' title='Save changes' src='" + IS_CAPTION_SAVE_IMG_URL + "' />  " +
      "<a href='' onClick='javascript: return ! cancelEdit();'><img alt='Cancel edit' title='Cancel edit' src='" + IS_CANCEL_IMG_URL + "' /></a></form>";
    captionForm = document.getElementById("captionForm_" + captionID);  
    captionForm.innerHTML = formHTML;
    captionForm.style.display = "inline";
    m_editModeIsOn = true;
    worked = true;
    }
  return worked;
  }

function toggleVisibility(elName, link)
  {
  var block;
  block = document.getElementById(elName);
  if (block)
    {
    if (block.style.display == "none")
      {
      block.style.display = "block";
      link.innerHTML = "-";
      }
    else
     {
     block.style.display = "none";
     link.innerHTML = "+";
     }
    return true; 
    } 
  else {return false;} 
  }

function switchGrab( src, width, height, imagenumber, dontScroll)
  {
  var links, ct, ci, i;
  
  hf_oldImagenumber = document.getElementById("imagenumber");
  ct = document.getElementById("caption");
  userCaption[hf_oldImagenumber.value] = ct.value ? ct.value : "";
  ct.value = (userCaption[imagenumber] ? userCaption[imagenumber] : ""); 
  hf_oldImagenumber.value = imagenumber;
  document.getElementById("theGrab").src = src;
	document.getElementById("theGrab").height = height;
	document.getElementById("theGrab").width = width;
	document.getElementById("imagesrc").value = src + "|"+ height + "|" + width;
	
  links = document.getElementsByName("imagepreview");
  for(i=0;i<links.length;i++) {links[i].className = "grabpreviewOff";}
	ci = document.getElementById("imagepreview_" + imagenumber);
	if (ci) {ci.className = "grabpreviewOn";}
	if (!dontScroll)  {document.location.href = "#gr";}
	return true;
  }


function reactivateCaptionForm()
  {
  if (m_formLockoutTimer > 0) {clearTimeout(m_formLockoutTimer); m_formLockoutTimer = 0;}
  var btnSubmit = document.getElementById("submcap");
  btnSubmit.className = "submit";
  btnSubmit.disabled = false;
  }

var AjaxVoter = {
  handleSuccess:function(o){
  try
    {
    var info = YAHOO.lang.JSON.parse(o.responseText);

    switch(parseInt(o.getResponseHeader['X-IS-VOTERESULT'], 10)) 
      {
      case 1:
        window.alert("Your vote has been recorded!");
        displayVotes (info.Favorites);
        break;
      case  2:
        // needs to login
        window.alert (info.ErrorMessage);
        window.location = 'vote.php?captionid=' + voteCaptionID;
        break;
      default:
        window.alert (info.ErrorMessage);
        break;
      }
    }
    catch (e) {window.alert('There was a problem updating the page. ' + e);}
  },

  handleFailure:function(o){},  processResult:function(o){},

  startRequest:function() {
     YAHOO.util.Connect.asyncRequest('GET', 'vote.php?low=1&captionid=' + voteCaptionID, vote_callback, "");
  }

};

var vote_callback =
{
  success:AjaxVoter.handleSuccess,
  failure:AjaxVoter.handleFailure,
  scope: AjaxVoter
};

var AjaxObject = {
  waitingSince : new Date(1980,1,1),
  maxWait_ms: 5000,
  handleSuccess:function(o){
  var results, result_nextCaptionID, newStamp;
  try 
	  {
		results = YAHOO.lang.JSON.parse(o.responseText);
    if (theGallery && ! m_editModeIsOn)
      {
      result_nextCaptionID = parseInt(results.NextCaptionID, 10);
      theGallery.innerHTML =  results.Captions + theGallery.innerHTML;  
      theCurrentTime.innerHTML = results.Time;
      if (result_nextCaptionID != nextCaptionID )
        {theLastCaptionTime.innerHTML = results.LastCaptionTime;}
      displayVotes(results.Favorites);
      newStamp = parseInt(results.LastCaptionTimestamp, 10);
      if (newStamp > lastCaptionTimestamp) {lastCaptionTimestamp = newStamp;}
      updateEdits(results.Edits);
      nextCaptionID = result_nextCaptionID; 

      if (results.CurrentCappers.substr(0,1) == "<")
        {
        theCapperList.innerHTML = results.CurrentCappers;
        theLatestCappersMessage.style.visibility =  'visible';
        }
      else
        {theCapperList.innerHTML = '<em>no-body</em>';}  
      }

    chatDiv = document.getElementById("theChat");  

    if (results.ChatComments)
		  {
		  nextChatID = Math.max(nextChatID, parseInt(results.NextCommentID, 10));
		  
		  if (chatDiv) 
			  {
				chatDiv.innerHTML = chatDiv.innerHTML  + results.ChatComments;
        chatDiv.scrollTop = chatDiv.scrollHeight;
				}
		  }

    }
  catch (e) {window.alert ('Problem updating the gallery ' + e);}
  finally {m_galleryTimer = window.setTimeout(function() {AjaxObject.startRequest();}, galleryDelay_ms);}
  },

  handleFailure:function(o){ m_galleryTimer = setTimeout(function() {AjaxObject.startRequest();}, galleryDelay_ms);
  },

  processResult:function(o){},

  startRequest:function(chatOnly) {

     var ms_untilReady, now, getURL;
		 now = new Date();
		 ms_untilReady = this.waitingSince.getTime() + this.maxWait_ms - now.getTime();
     if ( ms_untilReady < 0 )
       { 
       if (chatOnly) {m_chatOnly = chatOnly;}
       this.waitingSince = now;
       if (m_chatOnly) 
		     {getURL = 'latestchat.php?c=' + nextChatID; }
		   else
		     {getURL = 'latestcaptions.php?a=' + nextCaptionID + '&t=' + lastCaptionTimestamp; 
       if (refreshChat && window.nextChatID) {if (nextChatID>0) {getURL = getURL + '&c=' + nextChatID;}}}
       YAHOO.util.Connect.asyncRequest('GET', getURL, callback, "");
       }
     else { setTimeout(function() {AjaxObject.startRequest();}, ms_untilReady);}   
  }

};

var callback =
{
  success:AjaxObject.handleSuccess,
  failure:AjaxObject.handleFailure,
  scope: AjaxObject
};

// Start the transaction.
function startGalleryUpdate()
  {
    theGallery = document.getElementById("theGallery");
    if (theGallery)
      {
      theCurrentTime = document.getElementById("currentTime");
      theLastCaptionTime = document.getElementById("lastCaptionTime");
      theLatestCappersMessage = document.getElementById("latestCappersMessage");
      theCapperList = document.getElementById("capperList");    
      }
  if (theGallery){ m_galleryTimer = setTimeout(function() {AjaxObject.startRequest();}, galleryDelay_ms );}
  else if (chatDiv) { m_galleryTimer = setTimeout(function() {AjaxObject.startRequest(true);}, galleryDelay_ms );}
  }

function voteForCaption(captionid, theLink)
 {
 var voteSucceeded = false;
 voteCaptionID = captionid;
 voteLink = theLink;
 try
  {
  AjaxVoter.startRequest();
  voteSucceeded = true;
  }
 finally 
  { 
  return voteSucceeded;
  }
 }

function pauseUpdate(theButton)
  {
  if (m_galleryTimer > 0) {clearTimeout(m_galleryTimer);}
  if (m_grabTimer > 0) {clearTimeout(m_grabTimer);}
  // theButton = start
  // spinner stop  
  return true;
  }

function restartUpdate(theButton)
  {
  reloadImage(true);
  restartGalleryUpdate();
  // theButton = pause
  // spinner start  
  return true;
  }

function restartGalleryUpdate()
  {
  if (m_galleryTimer > 0)
    {
    clearTimeout(m_galleryTimer);
    AjaxObject.startRequest();
    }
  else {AjaxObject.startRequest();}
  }

function setStars(count, state, baseID)
  {
  var i;
  for (i = 1; i <= count; i++)
    {
    document.getElementById(baseID + i).src = starSRC[state];
    }
    
  for (i = count + 1; i <= 5; i++)
    {
    document.getElementById(baseID + i).src = starSRC[off];
    }
  }
  
function resetStars(rating, nStars, baseID)
  {
  var i;
  for (i = 1; i <= nStars; i++)
    {
    if (i <= rating)
      {document.getElementById(baseID + i).src = starSRC[on];}
    else
      {document.getElementById(baseID + i).src = starSRC[no];}
    }
  }

function toggleChat(button, fromPopup)
  {
  if (fromPopup)
    {
    window.opener.chatDiv.style.display = "block";
    window.opener.chatButton.className = "popOut";
    window.opener.chatButton.title = IS_POPOUT_HELPTEXT;
    window.opener.chatDiv.innerHTML = chatDiv.innerHTML;
	  window.close();

    refreshChat = true;
    }
  else if ((chatWin == null || chatWin.closed) && button.title == IS_POPOUT_HELPTEXT)
    {
    chatWin = window.open('chat.php','chatWin','width=626,height=536,scrollbars=yes'); 
    if (chatWin) {chatWin.focus();}
	  chatDiv.style.display = "none";
	  chatButton = button;
	  chatButton.className = "popIn";
	  chatButton.title = IS_POPIN_HELPTEXT;
	  }
	else
	  {
	  chatDiv.style.display = "block";
	  chatButton = button;
	  chatButton.className = "popOut";
	  chatButton.title = IS_POPOUT_HELPTEXT;
	  refreshChat = true;
	  if (chatWin && ! chatWin.closed)
	    {
      chatDiv.innerHTML = chatWin.chatDiv.innerHTML;
	    chatWin.close();
	    }
	  }
  
  return true;
  }

function restoreChat()
  {
	window.opener.chatDiv.style.display= "block";
	window.close();
	}

function fbs_click(url) 
  {
	t = document.title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(url)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436'); 
	return false;
	}

var AjaxEditor = {
  handleSuccess:function(o){
  var cappomaticLogo, results;
  results = YAHOO.lang.JSON.parse(o.responseText);
  switch(parseInt(results.EditResult,10)) 
    {
    case 1:
      document.getElementById("caption_" + captionID_EM).innerHTML = results.Caption;
      cancelEdit();
      cappomaticLogo =  document.getElementById("matic_"+ captionID_EM);
      if (cappomaticLogo) {cappomaticLogo.style.display = "none";}
       
      break;
    case  2:
      // needs to login
      if (confirm("You must be logged in to edit your captions.\n\nClick OK to log in."))
        {
        window.location = IS_LOGIN_FULLPATH + '?dest='  + escape(editFullpath);
        }
      break;
    default:
      window.alert (results.ErrorMessage);
      break;
    }
  },

  handleFailure:function(o){},  processResult:function(o){},

  startRequest:function(theForm) {
     var captionID, escapedCaption;
     escapedCaption = escape(theForm.caption.value);
     captionID = theForm.captionid.value;
     editFullpath = '/is/editcaption.php?caption=' + escapedCaption + '&captionid=' + captionID;

     YAHOO.util.Connect.asyncRequest('GET', editFullpath + '&low=1', edit_callback, "");
  }
};

var edit_callback =
{
  success:AjaxEditor.handleSuccess,
  failure:AjaxEditor.handleFailure,
  scope: AjaxEditor
};

function editCaption(form)
  {try {AjaxEditor.startRequest(form); return true;}
	 catch (e) {return false;}}  

var AjaxCaption = {
  handleSuccess:function(o){
  var loginParts, i, j, errormessage, pwd, captionText, results;
  reactivateCaptionForm();
  var results;
  results = YAHOO.lang.JSON.parse(o.responseText);  
  
  if (parseInt(results.NewLogon,10) == 1)
    {
    document.getElementById("userGreeting").innerHTML = results.Greeting;

    pwd = document.getElementById("password");      
    if (pwd) 
		  {
			pwd.value = ""; 
			pwd.style.display = "none"; 
			pwd.parentNode.removeChild(pwd);
			}
		loginParts = document.getElementsByClassName("xa_login");  
		check_password = function(el) {return "";};
		j = loginParts.length;
		for (i = 0; i < j; i++)
		  {
		  if (loginParts[0] && loginParts[0].parentNode)
		    {
		    loginParts[0].parentNode.removeChild(loginParts[0]);
		    loginParts = document.getElementsByClassName("xa_login");  
		    }
		  }
    }
  
  if (parseInt(results.SaveResult,10) == 1) 
    {
    captionText = document.getElementById("caption");      
    captionText.value = "";
    restartGalleryUpdate();
    errormessage = document.getElementById("cfError");
    if (errormessage && errormessage.length > 0) {errormessage.innerHTML = "";}
    }
   else { window.alert (results.ErrorMessage);}
  },

  handleFailure:function(o)
	 {reactivateCaptionForm(); 
	  m_captionForm.submit();},

  processResult:function(o){}, // This member is called by handleSuccess}

  startRequest:function(theForm) {
     if (m_formLockoutTimer === 0)
		   {
       m_captionForm = theForm;
       var btnSubmit = document.getElementById("submcap");
       btnSubmit.className = "active";
       btnSubmit.disabled = true;
		   m_formLockoutTimer = setTimeout(function() {reactivateCaptionForm();}, m_maxLockout_ms );
       YAHOO.util.Connect.setForm(theForm); 
       YAHOO.util.Connect.asyncRequest('POST', IS_ADD_CAPTIONPATH, caption_callback, "");
       }
    }
};

var caption_callback =
{
  success:AjaxCaption.handleSuccess,
  failure:AjaxCaption.handleFailure,
  scope: AjaxCaption
};

function setOpacity( value, element ) {
 element.style.opacity = value / 10;
 element.style.filter = 'alpha(opacity=' + parseInt(value * 10, 10) + ')';
}

var AjaxGrab = {
  waitingSince : new Date(1980,1,1),
  maxWait_ms: 5000,
  
  handleSuccess:function(o){
  var results, result_grabNumber;
  results = YAHOO.lang.JSON.parse(o.responseText);

  countdown.innerHTML = results.Secs2NextGrab;
  if (nowPlaying) {nowPlaying.innerHTML = results.NP;}
  if (thePreviews) 
	  {
	  if (! userCaption[parseInt(results.ImgNum,10)])
	    {
		  thePreviews.innerHTML = thePreviews.innerHTML + results.Grab;
		  thePreviews.scrollTop = thePreviews.scrollHeight;
		  userCaption[parseInt(results.ImgNum,10)] = '';
		  chatDiv = document.getElementById("theChat");  
		  if (chatDiv) {chatDiv.scrollTop = chatDiv.scrollHeight;}
		  }
		}
  countdown = document.getElementById('countdown');
  m_grabTimer = setTimeout(function() {countdownToNextImage();}, 1000);    
  },

  handleFailure:function(o){ }, processResult:function(o){ },

  startRequest:function() {
     var ms_untilReady, now;
		 now = new Date();
		 ms_untilReady = this.waitingSince.getTime() + this.maxWait_ms - now.getTime();
     if ( ms_untilReady < 0 )
       { 
       this.waitingSince = now;
       YAHOO.util.Connect.asyncRequest('GET', 'latestgrab.php', grab_callback, "");
       }
     else { m_grabTimer = setTimeout(function() {AjaxGrab.startRequest();}, ms_untilReady);}   
  }

};

var grab_callback =
{
  success:AjaxGrab.handleSuccess,
  failure:AjaxGrab.handleFailure,
  scope: AjaxGrab
};

function reloadImage(force)
  {
  if ((countdown) && (force || parseInt(countdown.innerHTML, 10) === 0))
    {
    AjaxGrab.startRequest();
    }
  }

function countdownToNextImage()
  {
  countdown.innerHTML = (parseInt(countdown.innerHTML, 10) - 1);
  if (countdown.innerHTML > 0)
    {m_grabTimer = setTimeout(function() {countdownToNextImage();}, 1000);}
  else // Brief delay to guarantee new image
    {setTimeout(function() {reloadImage();}, 1000);}
  }

function startCountdown(targetHREF)
  {
  reloadTargetHREF = targetHREF;

  countdown = document.getElementById('countdown');
  thePreviews = document.getElementById('previewImages');
  nowPlaying =  document.getElementById('nowPlaying');  
	nowPlaying =  document.getElementById('nowPlaying2');  

  if (document.getElementById('chatButton'))
	  {document.getElementById('chatButton').style.display = "block";}
  if (countdown){grabTimer = setTimeout(function() {countdownToNextImage();}, 1000);}
  var theHiddenSRC, theGrab, selectedImage;
  theGrab = document.getElementById('theGrab');
  theHiddenSRC = document.getElementById('imagesrc');
  if (theGrab && theHiddenSRC) 
	  {
	  selectedImage =  theHiddenSRC.value.split("|");
	  theGrab.src = selectedImage[0];
	  theGrab.height = selectedImage[1];
	  theGrab.width = selectedImage[2];
		}
	chatDiv = document.getElementById("theChat");	
	startGalleryUpdate();  

	if (chatDiv && window.opener) 
	 {if (window.opener.chatDiv) {chatDiv.innerHTML = window.opener.chatDiv.innerHTML;}}

  }

// Returns true as long as the post starts ok. The AjaxCaption actually does the gallery update
function saveAndReload(theForm)
  {
  var saved = false;
  try  {AjaxCaption.startRequest(theForm); saved = true;}
  catch (e) { saved = false;}
  return saved;
  }  