/*

  Random Javascript Functions for alstream.php

*/

function submitMyUpload()
{
  showFields('myalertbox');
  animateBox();
  return true;
}

function animateBox()
{
  var ab=document.getElementById('myalertbox');

  if (ab) {
    if (ab.style.borderStyle == 'solid') ab.style.borderStyle='dashed';
    else if (ab.style.borderStyle == 'dashed') ab.style.borderStyle='dotted';
    else ab.style.borderStyle='solid';
    setTimeout('animateBox()',300);
  }
}

function dorightalign()
{
  var ab=document.getElementById('contblock');
  var bb=document.getElementById('contspcr');
  var pb=document.getElementById(kPixDiv);
  var lp=document.getElementById(kLastPix);
  if (ab && lp) {
    var xpos=lp.offsetLeft+lp.clientWidth+ab.clientWidth;
    if ( xpos > pb.clientWidth ) xpos=ab.clientWidth;
    var xwid=pb.clientWidth;
    var xdif=xwid-xpos;
    if (xdif >= ab.clientWidth && bb!=null) {
      var newid=Math.floor(xdif/ab.clientWidth)*ab.clientWidth;
      if ( newid > 0 ) {
        bb.style.display='block';
        bb.style.width=newid+'px';
      } else {
        bb.style.display='none';
      }
    }
  }
}

function findxPos(obj) {
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    do {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    } while (obj = obj.offsetParent);
  }
  return curleft;
}

function toggleFields(fieldname)
{
   var myelem=document.getElementById(fieldname);
   if (myelem != null ) {
     if ( myelem.style.display=='block' ) myelem.style.display = 'none';
     else myelem.style.display = 'block';
   }
}

function showMenu(fieldname)
{
  var myelem=document.getElementById(fieldname);
  if (myelem != null && myelem.style.display != 'block') {
    hamFields();
    myelem.style.display = 'block';
  }
  return false;
}

function qualifyMouseout(event)
{
    if (event.target.className=='menuitdiv' &&
	//	event.relatedTarget.parent.id != event.target.id )
	event.relatedTarget.nodeName == 'DIV' )
	return true;
    else
        return false;
}

function hamFields()
{
   var mcntr=0;
   var x=document.getElementById('menuHead'+mcntr);
   var fcvalue=document.getElementById('uplfiles');
   if (fcvalue && fcvalue.value) var fpvalue=fcvalue.parentNode.parentNode;
   while(x) {
     if (x != fpvalue) x.style.display='none';
     mcntr++;
     x=document.getElementById('menuHead'+mcntr);
   }
}

function toggleCapEntry(pixno)
{
   var tepn='te'+pixno;
   var cepn='ce'+pixno;
   var dipn='di'+pixno;

   // Move the box over to the left IF it's on the righthand side of
   // the page.  Note that a non-displayed element doesn't have an xpos,
   // so we base this off the xpos of the parent picture.
   var xpos=0;
   if (document.getElementById(dipn)) xpos=findxPos(document.getElementById(dipn));
   if (document.body.clientWidth-xpos < 300) document.getElementById(cepn).style.marginLeft=-200;
   else document.getElementById(cepn).style.marginLeft=0;

   if ( document.getElementById(cepn).style.display=='block' ) {
    document.getElementById(cepn).style.display = 'none';
    document.getElementById(dipn).style.zIndex=10;
   } else {
    document.getElementById(cepn).style.display = 'block';
    document.getElementById(tepn).focus();
    document.getElementById(dipn).style.zIndex=99;
   }
}

function toggleTagEntry(pixno)
{
   var tepn='tb'+pixno;
   var cepn='tx'+pixno;
   var dipn='di'+pixno;
   // Move the box over to the left IF it's on the righthand side of
   // the page.  Note that a non-displayed element doesn't have an xpos,
   // so we base this off the xpos of the parent picture.
   var xpos=0;
   if (document.getElementById(dipn)) xpos=findxPos(document.getElementById(dipn));
   if (document.body.clientWidth-xpos < 300) document.getElementById(cepn).style.marginLeft=-200;
   else document.getElementById(cepn).style.marginLeft=0;

   if ( document.getElementById(cepn).style.display=='block' ) {
    document.getElementById(cepn).style.display = 'none';
    document.getElementById(dipn).style.zIndex=10;
   } else {
    document.getElementById(cepn).style.display = 'block';
    document.getElementById(tepn).value="";
    document.getElementById(tepn).focus();
    document.getElementById(dipn).style.zIndex=99;
   }
}

function toggleSTagEntry(pixno)
{
   var tepn='tc'+pixno;
   var cepn='ts'+pixno;
   var dipn='di'+pixno;
   // Move the box over to the left IF it's on the righthand side of
   // the page.  Note that a non-displayed element doesn't have an xpos,
   // so we base this off the xpos of the parent picture.
   var xpos=0;
   if (document.getElementById(dipn)) xpos=findxPos(document.getElementById(dipn));
   if (document.body.clientWidth-xpos < 300) document.getElementById(cepn).style.marginLeft=-200;
   else document.getElementById(cepn).style.marginLeft=0;

   if ( document.getElementById(cepn).style.display=='block' ) {
    document.getElementById(cepn).style.display = 'none';
    document.getElementById(dipn).style.zIndex=10;
   } else {
    document.getElementById(cepn).style.display = 'block';
    document.getElementById(tepn).value="";
    document.getElementById(tepn).focus();
    document.getElementById(dipn).style.zIndex=99;
   }
}

function toggleDateEntry(pixno)
{
   var dtpn='dt'+pixno;
   var depn='dey'+pixno;
   var dipn='di'+pixno;

   if ( document.getElementById(dtpn).style.display=='block' ) {
    document.getElementById(dtpn).style.display = 'none';
    document.getElementById(dipn).style.zIndex=10;
   } else {
    document.getElementById(dtpn).style.display = 'block';
    document.getElementById(depn).focus();
    document.getElementById(dipn).style.zIndex=99;
   }
}

function toggleArtEntry(pixno)
{
   var artpn='art'+pixno;  /* The outer DIV */
   var arxpn='arx'+pixno;  /* The TEXTAREA container DIV */
   var arapn='ara'+pixno;  /* The TEXTAREA */
   var arypn='ary'+pixno;  /* The Article TEXT */

   if ( document.getElementById(arxpn).style.display=='block' ) {
    document.getElementById(arxpn).style.display = 'none';
    if ( document.getElementById(arypn).innerHTML.length > 6 ) {
          document.getElementById(arypn).style.display= 'block';
          document.getElementById(artpn).style.border= '1px solid #000000';
          document.getElementById(arypn).style.color= '#000000';
    }
    else document.getElementById(artpn).style.display = 'none';
   } else {
    document.getElementById(artpn).style.display = 'block';
    document.getElementById(artpn).style.border= 'none';
    document.getElementById(arypn).style.color= '#ffffff';
    document.getElementById(arxpn).style.display = 'block';
    document.getElementById(arapn).focus();
   }
}

function showFields(fieldname)
{
   if (document.getElementById(fieldname))
     document.getElementById(fieldname).style.display = 'block';
}

function hideFields(fieldname)
{
   if (document.getElementById(fieldname))
     document.getElementById(fieldname).style.display = 'none';
}

function hideAllFields(fieldname)
{
    for (var i=0;document.getElementById(fieldname+i)!=null;i++)
      if (document.getElementById(fieldname+i))
       document.getElementById(fieldname+i).style.display = 'none';
}

function showAllFields(fieldname)
{
    for (var i=0;document.getElementById(fieldname+i);i++)
      if (document.getElementById(fieldname+i))
       document.getElementById(fieldname+i).style.display = 'block';
}


function raiseTNPix(pixno)
{
  showFields('ta'+pixno);
  showFields('dprev'+pixno);
  showFields('dnext'+pixno);
  showFields('dlikes'+pixno);
  showFields('pa'+pixno);
  showFields('rotrt'+pixno);
  showFields('rotlt'+pixno);
  raiseTags(pixno);
  raiseCaption(pixno);
  hamFields();
}

function lowerTNPix(pixno)
{
  hideFields('ta'+pixno);
  hideFields('dprev'+pixno);
  hideFields('dnext'+pixno);
  if (!parseInt(document.getElementById('lkc'+pixno).innerHTML)) hideFields('dlikes'+pixno);
  hideFields('pa'+pixno);
  hideFields('rotrt'+pixno);
  hideFields('rotlt'+pixno);
  hideFields('td'+pixno);
  hideFields('tx'+pixno);
  hideFields('ts'+pixno);
  lowerCaption(pixno);
}

function raiseTags(pixno)
{
  var fieldname="td"+pixno;
  var tffn="tf"+pixno;
  var tgfn="tg"+pixno;
  if (document.getElementById(tffn).innerHTML || document.getElementById(tgfn).innerHTML ) document.getElementById(fieldname).style.display = 'block';
}

function raiseCaption(pixno)
{
  var captext="cap"+pixno;
  var capbox="cd"+pixno;
  var outerbox="di"+pixno;
  if (document.getElementById(captext).innerHTML) {
    document.getElementById(capbox).style.display = 'block';
    document.getElementById(outerbox).style.zIndex=99;
  }
}

function lowerCaption(pixno)
{
  var captext="cap"+pixno;
  var capbox="cd"+pixno;
  var outerbox="di"+pixno;
  if (document.getElementById(captext).innerHTML) {
    document.getElementById(capbox).style.display = 'none';
    document.getElementById(outerbox).style.zIndex=10;
  }
}

function makeHttpObject() {
  try {return new XMLHttpRequest();}
  catch (error) {}
  try {return new ActiveXObject("Msxml2.XMLHTTP");}
  catch (error) {}
  try {return new ActiveXObject("Microsoft.XMLHTTP");}
  catch (error) {}

  throw new Error("Could not create HTTP request object.");
}

function killPix(fieldname,dbuid) {
  var x=window.confirm("Are you sure you want to permanently delete this?")
  if (x) reallyKillPix(fieldname,dbuid);
}

function killDiv(pixno,dbuid) {
  var x=window.confirm("Are you sure you want to permanently delete this?")
  if (x) reallyKillDiv(pixno,dbuid);
}

function reallyKillPix(fieldname,dbuid) {
  ajpost("cmd=kill&k="+dbuid);
  document.getElementById(fieldname).style.display = 'none';
}

function reallyKillDiv(pixno,dbuid) {
  ajpost("cmd=kill&k="+dbuid);
  document.getElementById("di"+pixno).style.display = 'none';
  document.getElementById("pi"+pixno).style.display = 'none';
}

function killTags(pixno,dbuid) {
  var tffn="tf"+pixno;
  var tgfn="tg"+pixno;
  ajpost("cmd=untag&k="+dbuid);
  document.getElementById(tffn).innerHTML = '';
  document.getElementById(tgfn).innerHTML = '';
}

function submitUpload(dbuid) {
    ajpost("cmd=doupload&k="+dbuid);
}

function submitCaption(pixno,dbuid) {
  var tefn="te"+pixno;
  var cefn="ce"+pixno;
  var capfn="cap"+pixno;

  pecaption=document.getElementById(tefn).value;
  caption=escape(pecaption);

  params="cmd=caption&k="+dbuid+"&c="+caption;
  ajpost(params);

  document.getElementById(capfn).innerHTML=pecaption;
  hideFields(cefn);
}

function submitLike(pixno,dbuid) {
  var capfn=document.getElementById("lkc"+pixno);
  var delcfn=document.getElementById("delc"+pixno);
  var dlikesfn=document.getElementById("dlikes"+pixno);
  var params="cmd=like&k="+dbuid;
  ajpost(params);
  if (capfn) {
    var numlikes=parseInt(capfn.innerHTML)+1;
    capfn.innerHTML=numlikes;
  }
  if (delcfn) delcfn.style.display='block';
  if (dlikesfn) dlikesfn.innerHTML='<small>&uarr;['+numlikes+']</small>';
}

function submitDeLike(pixno,dbuid) {
  var capfn="lkc"+pixno;
  var delcfn="delc"+pixno;
  var params="cmd=delike&k="+dbuid;
  ajpost(params);
  document.getElementById(capfn).innerHTML='0';
  document.getElementById(delcfn).style.display='none';
}


function submitRotRt(pixno,dbuid) {
  var capfn="lkc"+pixno;
  var delcfn="delc"+pixno;
  var params="cmd=rotrt&k="+dbuid;
  ajpost(params);
//  document.getElementById(capfn).innerHTML='0';
//  document.getElementById(delcfn).style.display='none';
}

function submitRotLt(pixno,dbuid) {
  var capfn="lkc"+pixno;
  var delcfn="delc"+pixno;
  var params="cmd=rotlt&k="+dbuid;
  ajpost(params);
//  document.getElementById(capfn).innerHTML='0';
//  document.getElementById(delcfn).style.display='none';
}

function submitArticle(pixno, dbuid) {
  var artpn='art'+pixno;
  var arxpn='arx'+pixno;
  var arapn='ara'+pixno;
  var arypn='ary'+pixno;

  var ataipn='whizzy'+arapn;

  if (document.getElementById(ataipn) != null) pecaption=cleanUp();
  else  pecaption=document.getElementById(arapn).value.replace(/\n/g,"<br>\n");

  caption=escape(pecaption);

  params="cmd=article&k="+dbuid+"&c="+caption;
  ajpost(params);

  document.getElementById(arypn).innerHTML=pecaption;

  showFields('art'+pixno);

  toggleArtEntry(pixno);
}

function submitDate(pixno,dbuid) {
  var dtfn="dt"+pixno;
  var deyfn="dey"+pixno;;
  var demfn="dem"+pixno;
  var dedfn="ded"+pixno;
  var dehfn="deh"+pixno;
  var deifn="dei"+pixno;
  var desfn="des"+pixno;
  var capfn="cap"+pixno;

  var yval=document.getElementById(deyfn).value;
  var mval=document.getElementById(demfn).value;
  var dval=document.getElementById(dedfn).value;
  var hval=document.getElementById(dehfn).value;
  var ival=document.getElementById(deifn).value;
  var sval=document.getElementById(desfn).value;

  var pecaption = yval+"-";
  pecaption += mval+"-";
  pecaption += dval+" ";
  pecaption += hval+":";
  pecaption += ival+":";
  pecaption += sval;

  caption=escape(pecaption);

  params="cmd=reseq&k="+dbuid+"&c="+caption;
  ajpost(params);

  hideFields(dtfn);
}

function submitTag(pixno,dbuid) {
  var tefn="tb"+pixno;
  var cefn="tx"+pixno;
  var tffn="tf"+pixno;
  pecaption=document.getElementById(tefn).value;
  caption=escape(pecaption);

  lecaption="<a href=\""+kSiteURL+"?t="+caption+"\">"+pecaption+"</a>";

  params="cmd=tag&k="+dbuid+"&c="+caption;
  ajpost(params);

  var suggestionStr=','+mySuggestions.states.toString()+',';
  if (suggestionStr.indexOf(','+pecaption+',')<0) {
    mySuggestions.states.push(pecaption);
    mySuggestions.states.sort();
  }

  if (document.getElementById(tffn).innerHTML) document.getElementById(tffn).innerHTML+=","+lecaption; else document.getElementById(tffn).innerHTML=lecaption;
  document.getElementById(tefn).value="";
// hideFields(cefn);
}

function submitSTag(pixno,dbuid) {
  var tefn="tc"+pixno;
  var cefn="ts"+pixno;
  var tffn="tg"+pixno;
  pecaption=document.getElementById(tefn).value;
  caption=escape(pecaption);

  lecaption="<a class=scname href=\""+kSiteURL+"?p="+caption+"\"><i>"+pecaption+"</i></a><br>";

  params="cmd=stag&k="+dbuid+"&c="+caption;
  ajpost(params);

  var suggestionStr=','+myScSuggestions.states.toString()+',';
  if (suggestionStr.indexOf(','+pecaption+',')<0) {
    myScSuggestions.states.push(pecaption);
    myScSuggestions.states.sort();
  }
  document.getElementById(tffn).innerHTML=lecaption;
  document.getElementById(tefn).value="";
  hideFields(cefn);
}

function ajpost(params) {
  var request = makeHttpObject();
  request.open("POST", kBaseDir+"aljax.php", true);
  request.onreadystatechange = function() {
    if(request.readyState == 4 && request.status != 200) alert(request.responseText);
    else if (request.responseText.indexOf("ERROR:")!=-1) alert(request.responseText);
    else if (request.responseText.indexOf("NOTE:")==0) alert(request.responseText);
    else if (request.responseText.indexOf("RELOAD:")==0) window.location.reload(true);
    else if (request.responseText.indexOf("UPLOAD:")==0) window.location.replace(kSiteURL+'?t=uploads');
    else if (request.responseText) window.status=request.responseText;
  }
  request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  request.setRequestHeader("Content-length", params.length);
  request.setRequestHeader("Connection", "close");
  request.send(params);
}

function tbFill( tbName, fillText )
{
  document.getElementById(tbName).value=fillText;
  document.getElementById(tbName).focus();
}

function reloadAlStream()
{
  window.location=kFullURL;
}


/**
 *
 *  Drag and Drop
 *
**/

  var internalDNDType = 'imguid/plain';
  function dragStartHandler(event, myuid, mypixno) {
      event.dataTransfer.setData('Text', myuid+","+mypixno);
      event.dataTransfer.effectAllowed = 'move'; // only allow moves
  }

  function dropHandler(event, myuid, mypixno) {
    var evdata = event.dataTransfer.getData('Text');
    var evuid = evdata.split(',')[0];
    var evpixno = evdata.split(',')[1];
    ajpost("cmd=moveent&k="+myuid+"&t="+evuid);

    /* Insert Y ( the dragged ) after X ( the dropped upon ) */
    var xnode=document.getElementById('di'+mypixno);
    var ynode=document.getElementById('di'+evpixno);
    var pxnode=xnode.parentNode;
    var pynode=ynode.parentNode;

    pynode.removeChild(ynode);
    pxnode.replaceChild(ynode,xnode);
    pxnode.insertBefore(xnode,ynode);

  }

 function dropHandlerDiv(event, myuid, mypixno) {
    var evdata = event.dataTransfer.getData('Text');
    var evuid = evdata.split(',')[0];
    var evpixno = evdata.split(',')[1];
    ajpost("cmd=moveent&k="+myuid+"&t="+evuid);

    alert("Moved: "+evuid+" to "+myuid);
  }

/**
 * An autosuggest textbox control.
 * @class
 * @scope public
 */
function AutoSuggestControl(myTextBox /*:HTMLInputElement NAME*/, 
                            oProvider /*:SuggestionProvider*/,
			    myListDiv /*:HTML DIV for List NAME*/,
			    fctOnSubmit, fctOnCancel ) {
       
    /**
     * Suggestion provider for the autosuggest feature.
     * @scope private.
     */
    var oTextbox=document.getElementById(myTextBox);
    var oListDiv=document.getElementById(myListDiv);

    this.fctonsubmit=fctOnSubmit;
    this.fctoncancel=fctOnCancel;

/*    this.fctonsubmit="Submit Pressed.";
    this.fctoncancel="Cancel Pressed."; */

    this.tbname=myTextBox;

    this.provider /*:SuggestionProvider*/ = oProvider;

    this.listdiv = oListDiv;
    
    /**
     * The textbox to capture.
     * @scope private
     */
    this.textbox /*:HTMLInputElement*/ = oTextbox;
    
    //initialize the control
    this.init();
    
}

/**
 * Autosuggests one or more suggestions for what the user has typed.
 * If no suggestions are passed in, then no autosuggest occurs.
 * @scope private
 * @param aSuggestions An array of suggestion strings.
 */
AutoSuggestControl.prototype.autosuggest = function (aSuggestions /*:Array*/) {
    
    //make sure there's at least one suggestion
    this.listdiv.innerHTML="";
    if (aSuggestions.length > 0) {
        /* this.typeAhead(aSuggestions[0]); */
        for (var i=0; i < aSuggestions.length; i++) { 
         this.listdiv.innerHTML+="<a href=\"javanote.html\" onClick=\"tbFill(\'"+this.tbname+"\',\'"+aSuggestions[i]+"\'); return false;\">"+aSuggestions[i]+"</a><br>";
        }
    }
};

AutoSuggestControl.prototype.autocomplete = function (aSuggestion /*:String*/) {
    
    if (aSuggestion) tbFill(this.tbname, aSuggestion);
};


/**
 * Handles keyup events.
 * @scope private
 * @param oEvent The event object for the keyup event.
 */
AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) {

    var iKeyCode = oEvent.keyCode;

    //make sure not to interfere with non-character keys
    if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode <= 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {

      if (iKeyCode == 27 ) eval(this.fctoncancel);
      if (iKeyCode == 13 ) eval(this.fctonsubmit);
      if (iKeyCode == 39 ) this.provider.requestComplete(this);


        //ignore
    } else {
        //request suggestions from the suggestion provider
        this.provider.requestSuggestions(this);
    }
};

/**
 * Initializes the textbox with event handlers for
 * auto suggest functionality.
 * @scope private
 */
AutoSuggestControl.prototype.init = function () {

    //save a reference to this object
    var oThis = this;
    
    //assign the onkeyup event handler
    this.textbox.onkeyup = function (oEvent) {
    
        //check for the proper location of the event object
        if (!oEvent) {
            oEvent = window.event;
        }    
        
        //call the handleKeyUp() method with the event object
        oThis.handleKeyUp(oEvent);
    };
    
};

/**
 * Selects a range of text in the textbox.
 * @scope public
 * @param iStart The start index (base 0) of the selection.
 * @param iLength The number of characters to select.
 */
AutoSuggestControl.prototype.selectRange = function (iStart /*:int*/, iLength /*:int*/) {

    //use text ranges for Internet Explorer
    if (this.textbox.createTextRange) {
        var oRange = this.textbox.createTextRange(); 
        oRange.moveStart("character", iStart); 
        oRange.moveEnd("character", iLength - this.textbox.value.length);      
        oRange.select();
        
    //use setSelectionRange() for Mozilla
    } else if (this.textbox.setSelectionRange) {
        this.textbox.setSelectionRange(iStart, iLength);
    }     

    //set focus back to the textbox
    this.textbox.focus();      
}; 

/**
 * Inserts a suggestion into the textbox, highlighting the 
 * suggested part of the text.
 * @scope private
 * @param sSuggestion The suggestion for the textbox.
 */
AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) {

    //check for support of typeahead functionality
    if (this.textbox.createTextRange || this.textbox.setSelectionRange){
        var iLen = this.textbox.value.length; 
        this.textbox.value = sSuggestion; 
        this.selectRange(iLen, sSuggestion.length);
    }
};


/**
 * Provides suggestions for state names (USA).
 * @class
 * @scope public
 */


function StateSuggestions() {
    this.states = [ "zantedeschia" ];
}


/**
 * Request suggestions for the given autosuggest control. 
 * @scope protected
 * @param oAutoSuggestControl The autosuggest control to provide suggestions for.
 */
StateSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl) {
    var aSuggestions = [];
    var sTextboxValue = oAutoSuggestControl.textbox.value;

    if (sTextboxValue.length > 0){
      for (var i=0; i < this.states.length; i++) { 
        if (this.states[i].toLowerCase().indexOf(sTextboxValue.toLowerCase()) == 0) {
           aSuggestions.push(this.states[i]);
        } 
      }
    }

    //provide suggestions to the control
    oAutoSuggestControl.autosuggest(aSuggestions);
};

StateSuggestions.prototype.requestComplete = function (oAutoSuggestControl) {
    var aSuggestion = "";
    var sTextboxValue = oAutoSuggestControl.textbox.value;

    if (sTextboxValue.length > 0){
      for (var i=0; i < this.states.length; i++) { 
        if (this.states[i].toLowerCase().indexOf(sTextboxValue.toLowerCase()) == 0) {
	   if (this.states[i].toLowerCase()==sTextboxValue.toLowerCase()) {
             if(this.states[i+1]) i++;
           }
           aSuggestion=this.states[i];
	   break;
        } 
      }
    }

    //provide suggestions to the control
    oAutoSuggestControl.autocomplete(aSuggestion);
};



