var openeditwindows = new Array


// set up the post flags we know about
function gotoadmin()
{
    window.location="admin.php";
}


// jump to an anchor (which must be in the form <a name="foo" id="foo"> </a>)
// the second argument is where the anchor should be in the window - 0 = top,
// 1 = bottom.
function gotoanchor(label,wpos)
{
    var pos = getAnchorPosition(label)
    self.scrollTo(pos.x,pos.y-window.innerHeight*wpos)
}

var opencommentid = 0

function closecomments()
{
    var node = document.getElementById('commentopendiv')
    if(node)
    {
        node.parentNode.innerHTML = ''
    }
    if(opencommentid)
    {
        // put back the comment count block
        node = document.getElementById('commentcount'+opencommentid)
        node.style.display = 'block'
        opencommentid = 0
    }
}

function displaycomments(msg)
{
    closecomments()
    
    // if the node we're asking for is already open, JUST close it. Otherwise
    // reopen.
    
    if(!document.getElementById('commentopendiv'+msg))
    {
        var node = document.getElementById('commentspace'+msg)
        createrequest('comment.php?msg='+msg,'GET','',
                      function(req)
                      {
                          node.innerHTML = req.responseText
                          
                          opencommentid = msg
                          node = document.getElementById('commentcount'+opencommentid)
                          node.style.display = 'none'
                          
                          gotoanchor('cs'+msg,0.5)
                          
                      }
                      )
    }
//    window.open('comment.php?msg='+msg,'','resizable=no,toolbar=no,status=no,scrollbars=yes,width=380,height=400')
}

function commentsubmit()
{
    // this does both change and add - the form sends a thing to tell us which.
    // extract info from form
    
    var form = document.getElementById('commentform')
    var inputs = form.getElementsByTagName('input')
    
    var msg
    var act
    var rand
    var url
    var author
    var email
    var pw
    var ctext
    var commentnumber
    
    for(i=0;i<inputs.length;i++)
    {
        var b = inputs[i]
        var t = b.getAttribute('type')
        var n = b.getAttribute('name')
        var v = encodeURIComponent(b.value)
        
        // get the data
        
        if(t == 'hidden')
        {
            if(n == 'msg')
            {
                msg = v
            }
            else if(n == 'do')
            {
                act= v
            }
            else if(n == 'random')
            {
                rand = v
            }
            else if(n == 'com')
            {
                commentnumber = v
            }
        }
            
        if(t == 'text')
        {
            if(n == 'author')
            {
                author = v
            }
            else if(n == 'email')
            {
                email = v
            }
            else if(n == 'url')
            {
                url = v
            }
            else if(n == 'password')
            {
                pw = v
            }
        }
    }
    
    inputs = form.getElementsByTagName('textarea')
    if(inputs && inputs.length)
    {
        ctext = escape(inputs[0].value)
    }
    
    // we've got the form data, we now need to assemble a rather ugly AJAX request to update
    // the comment. If the server just responds with 'error' then we alert and leave thing as they are.
    // Otherwise we refetch the comments.
    
    var args
    if(act == 'add')
    {
        args = 'do=addcomment'
    }
    else if(act == 'change')
    {
        args = 'do=changecomment&com='+commentnumber
    }
    
    args += '&msg='+msg+'&author='+author+'&email='+email+'&url='+url+'&text='+ctext+'&random='+rand+'&password='+pw
    
    // send the request
    
    createrequest('comment.php','POST',args,
                  function(req)
                  {
                      if(handlesimplereplynonotify(req))
                      {
                          // close and reopen comment node
                          displaycomments(msg)
                      }
                  });
}

function commenteditopen(postid,commentid)
{
    // open edit form inside comment.
    
    // fetch the editor form via ajax
    
    var node = document.getElementById('editcommentspace'+commentid)
    createrequest('comment.php?do=getcommenteditform&com='+encodeURIComponent(commentid),'GET','',
                  function(req)
                  {
                      node.innerHTML = req.responseText
                      resizeelements()
                      gotoanchor("commentsubmit",1)
                  });
}

function commentaddopen(postid)
{
    // open add form
    
    // fetch the editor form via ajax
    
    var node = document.getElementById('commentopendiv'+postid)
    createrequest('comment.php?do=getcommentaddform&msg='+encodeURIComponent(postid),'GET','',
                  function(req)
                  {
                      node.innerHTML = req.responseText
                      resizeelements()
                      gotoanchor("commentsubmit",1)
                  });
}

function commentdelete(postid,commentid)
{
    // ajax comment delete
    
    postid=parseInt(postid)
    commentid=parseInt(commentid)
    
    createrequest('comment.php','POST','do=deletecomment&com='+commentid,
                  function(req)
                  {
                      if(handlesimplereplynonotify(req))
                      {
                          displaycomments(postid)
                      }
                  });
}

function postflagobject(bit,flagname,label)
{
    this.bit = bit
    this.flagname = flagname
    this.label = label
}

var postflagset = new Array

function regpostflag(bit,flagname,label)
{
    var o = new postflagobject(bit,flagname,label)
    postflagset.push(o)
}

regpostflag(1,'preview','preview')
regpostflag(2,'private','private')


function login()
{
    var name = document.getElementById("loginname").value;
    var pass = document.getElementById("loginpass").value;
    
    pass = sha1Hash(pass);
    
    createrequest('admin.php','POST','do=login&name='+name+'&pass='+pass,
                  function(req)
                  {
                      if(handlesimplereplynonotify(req))
                      {
                          window.location.reload(true);
                      }
                  }
                  );
}

function logout()
{
    createrequest('admin.php','POST','do=logout',
                  function(req)
                  {
                      handlesimplereplynonotify(req);
                      window.location.reload(true);
                  }
                  );
}

// decodestring reverses htmlspecialchars()

function decodestring(str)
{
    var s = new String(str)
    s = s.replace(/&lt;/g,'<')
    s = s.replace(/&gt;/g,'>')
    s = s.replace(/&quot;/g,'"')
    s = s.replace(/&#039;/g,"'")
    s = s.replace(/&amp;/g,'&')
    return s;
}

// create a button inside the flags section of the edit form,
// append to the given div.

function createflagbutton(parentdiv,flagname,flaglabel)
{
    var e = document.createTextNode(flaglabel+': ')
    parentdiv.appendChild(e)
    
    e = document.createElement('input')
    e.setAttribute('type','checkbox')
    e.setAttribute('name','fb_'+flagname)
    e.setAttribute('id','fb_'+flagname)
    e.checked = false
    
    parentdiv.appendChild(e)
}

function resizetextswithin(ed,edwidth)
{
    // change the width of all text inputs
    
    var inputs = ed.getElementsByTagName('input')
    for(i=0;i<inputs.length;i++)
    {
        var b = inputs[i]
        var t = b.getAttribute('type')
        if(t == 'text')
        {
            b.style.width = edwidth
        }
    }
    
    // change the width of the textarea
    
    inputs = ed.getElementsByTagName('textarea')
    inputs[0].style.width = edwidth
}

// recurse prevention
var inresize = 0

// resize window elements
function resizeelements()
{
    inresize++
    // work out the width of the centre box. 
        
    var cwidth = document.getElementById('centre').offsetWidth - 160
    edwidth = cwidth + "px"
    
    // resize the edit components
    
    for(var loop=0;loop<openeditwindows.length;loop++)
    {
        resizetextswithin(openeditwindows[loop],edwidth)
    }
    
    // resize any open comment box
    
    var node = document.getElementById('commentform')
    if(node)
    {
        var node2 = document.getElementById('commentopendiv'+opencommentid)
        node2.style.width = (cwidth-60)+'px'
        resizetextswithin(node,(cwidth-80)+'px')

    }
    
    
    
    // enough room for the right window? If not,
    // get rid of it
    
    if(cwidth<200)
    {
        if(inresize<2)
        {
            document.getElementById('right').style.display='none'
            resizeelements()
        }
    }
    else
    {
        document.getElementById('right').style.display='block'
    }
    
    inresize--
        
}


// append an edit form to the end of the given span. Set the
// the hidden 'ident' form input to be 'ident'.

var editidentopen=0
var editedimageid=0

function makeedit(insertspan,ident)
{
    var allowopen=1
    if(editidentopen)
    {
        if(editidentopen==ident)allowopen=0
        closealledits()
    }
    
    if(allowopen)
    {
        // create a clone of the edit template at this spot
        var ed = document.getElementById('edittemplate')
        var span = document.getElementById(insertspan)
        var i
        
        ed = ed.cloneNode(true)
        ed.style.display = 'block'
        ed.setAttribute('name','editform') // so we can delete it later!
        
        openeditwindows.push(ed)
        
        // hide the ownerbuttons
        
        i = document.getElementById('ownerbuttons'+ident)
        if(i)
        {
            i.style.display='none'
        }
        
        
        // create flag buttons
        
        var q = ed.getElementsByTagName('div')
        for(i=0;i<q.length;i++)
        {
            var flagdiv=q[i]
            if(flagdiv.getAttribute('name') == 'editpostflags')
            {
                for(j=0;j<postflagset.length;j++)
                {
                    createflagbutton(flagdiv,
                                     postflagset[j].flagname,
                                     postflagset[j].label
                                     );
                }
            }
        }
        
        
        // get all inputs in the form; we'll be modifying some of them
        var inputs = ed.getElementsByTagName('input')
    
        // now trundle down and edit the action URL for the
        // post button, and collect references to some
        // of the nodes for plugging data into later.
        
        var subjnode
        var textnode
        var oldflagsnode
        var tagsnode
        var oldimgnode
        var imgsizenode
        var imgposnode
        var imgclicknode
        
        for(i=0;i<inputs.length;i++)
        {
            var b = inputs[i]
            var t = b.getAttribute('type')
            var n = b.getAttribute('name')
        
            // change the value of the ident hidden input
        
            if(t == 'hidden')
            {
                if(n == 'ident')
                {
                    b.setAttribute('value',ident)
                }
                if(n == 'oldimageid')
                {
                    oldimgnode = b
                }
                if(n == 'oldflags')
                {
                    oldflagsnode = b
                }
            }
            
            // store references to the text fields
            
            if(t == 'text')
            {
                if(n == 'subject')
                {
                    subjnode = b
                }
                else if(n == 'tags')
                {
                    tagsnode = b
                }
            }
            
            // and checkboxes
            
            if(t == 'checkbox')
            {
                if(n == 'imgclick')
                {
                    imgclicknode = b;
                }
            }
        }
        
        // now do the same for selects
        
        inputs = ed.getElementsByTagName('select')
        
        for(i=0;i<inputs.length;i++)
        {
            var b = inputs[i]
            var n = b.getAttribute('name')
            
            if(n == 'imgsize')
            {
                imgsizenode = b
            }
            else if(n == 'imgpos')
            {
                imgposnode = b
            }
        }
        
        
        
        // also look for a tr called in here called 'imageformspan' and
        // change its ID so we can look for it later. We need this to
        // find items within this form.
        
        var x = ed.getElementsByTagName('tr')
        for(i=0;i<x.length;i++)
        {
            var t = x[i]
            if(t.getAttribute('name')=='imageformbit')
            {
                t.setAttribute('id',"imgfrm")
            }
        }
        
        
        // now look at the form element itself - we'll change the URL
        // so the form will take us straight back here
        inputs = ed.getElementsByTagName('form')
        var form = inputs[0]
        
       
        
        
        inputs = ed.getElementsByTagName('textarea')
        textnode = inputs[0]
        
        // if this is an old thingy (i.e. the ident isn't 'new') then ask the server for the details
        // and plug them in
        
        if(ident!='new')
        {
            var newact = window.location+'#'+ident
            form.action = newact
            textnode.value = "loading"
            subjnode.value = "loading"
            tagsnode.value = "loading"
            
            createrequest("ajax.php","POST",
                          "do=fetchmarkup&id="+ident,
                          function(req)
                          {
                              var x = req.responseXML.getElementsByTagName('reply');
                              x=x[0];
                              if(parseInt(getNodeValue(x,'error')))
                              {
                                  alert(getNodeValue(x,'status'));
				  closealledits();
                              }
                              else
                              {
                                  var e
                                  var flags
                                  textnode.value = decodestring(getNodeValue(x,'markup'))
                                  subjnode.value = decodestring(getNodeValue(x,'subject'))
                                  tagsnode.value = getNodeValue(x,'tags')
                                  oldimgnode.value = getNodeValue(x,'image')
                                  imgsizenode.value = getNodeValue(x,'imgsize')
                                  imgposnode.value = getNodeValue(x,'imgpos')
                                  flags = parseInt(getNodeValue(x,'imgflags'))
                                  imgclicknode.checked = (flags & 8) ? true : false
                                  
                                  flags = parseInt(getNodeValue(x,'flags'))
                                  oldflagsnode.value = flags
                                  for(i=0;i<postflagset.length;i++)
                                  {
                                      e = document.getElementById('fb_'+postflagset[i].flagname)
                                      e.checked = (flags & postflagset[i].bit) ? true : false
                                  }
                              }
                          }
                          )
        }
        else
        {
            form.setAttribute('action',window.location)
        }
            
        editidentopen=ident
        span.appendChild(ed)
        
        resizeelements()
    }
}

function closealledits(evt)
{
    // reveal the owner buttons for the open edit
    var i = document.getElementById('ownerbuttons'+editidentopen)
    if(i)
    {
        i.style.display='block'
    }
    
    // get rid of all edits
    for(var loop=0;loop<openeditwindows.length;loop++)
    {
        var v = openeditwindows[loop]
        v.parentNode.removeChild(v)
        editidentopen=0
    }
    openeditwindows = new Array
}

function showimgselection(tp)
{
    var imgblock = document.getElementById('imgfrm')
    
    if(imgblock)
    {
        var x = imgblock.getElementsByTagName('div')
        for(var i=0;i<x.length;i++)
        {
            var d = x[i]
            var n = d.getAttribute('name').split('_',2)
            if(n[0] == 'imgsel')
            {
                if(n[1] == tp)
                {
                    d.style.display='inline'
                }
                else
                {
                    d.style.display='none'
                }
            }
        }
    }
        
}
    

function makenewedit()
{
    makeedit('neweditplace','new')
}

