/*

LICENSE


This program is free software; you can redistribute it 
and/or modify it under the terms of the GNU General Public 
License (GPL) as published by the Free Software Foundation; 
either version 2 of the License, or (at your option) any 
later version.

This program is distributed in the hope that it will be 
useful, but WITHOUT ANY WARRANTY; without even the 
implied warranty of MERCHANTABILITY or FITNESS FOR A 
PARTICULAR PURPOSE.  See the GNU General Public License 
for more details.

To read the license please visit
http://www.gnu.org/copyleft/gpl.html

*/

/*extern out,XPathResult,idupdate,idupdate2,index,Sortable,Ajax,Element,$,Insertion,Nifty */

   var boxIndexes = {};

   function getActualIndex(index) {
      if(boxIndexes[index]) {
         return boxIndexes[index];
      } else {
         return index;
      }//end if-else boxIndexes[index]
   }//end function getActualIndex

   function showboxmenu(boxmenuid) {
      var boxmenu = document.getElementById("boxmenu" + boxmenuid);
      var boxmenuarrow = document.getElementById("boxmenuarrow" + boxmenuid);
      boxmenu.style.display = "block";
      boxmenuarrow.href = "javascript:hideboxmenu(" + boxmenuid + ");";
      boxmenuarrow.innerHTML = "<img src=\"images/arrowdown.png\" alt=\"menu\" />";
   }//end function showboxmenu
   
   function hideboxmenu(boxmenuid) {
      var boxmenu = document.getElementById("boxmenu" + boxmenuid);
      var boxmenuarrow = document.getElementById("boxmenuarrow" + boxmenuid);
      boxmenu.style.display = "none";
      boxmenuarrow.href = "javascript:showboxmenu(" + boxmenuid + ");";
      boxmenuarrow.innerHTML = "<img src=\"images/arrowright.png\" alt=\"menu\" />";
   }//end function hideboxmenu
   
   function hideout() {//hides the 'ajaxout' display message box
      out.innerHTML = "";out.style.display = "none";
   }//end function hideout
   
   function handleResponseError(response) {//check if AJAX call responded with an error (not errored) and display appropriate message
      if((response == "ONLY ADMIN CAN EDIT THIS PAGE!") || (response == "TRUNCATE ERROR") || (response == "WRITE ERROR")) {alert(response);}
   }//end function handleResponseError
   
   function xget( xpathSelector ) {
      var it = document.evaluate( xpathSelector, document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
       if( it.snapshotLength ) {
          return it.snapshotItem( 0 );
       }
       return '';
   }//end function xget

   function AJAXerror(err) {
      alert('Error ' + err.status + ' -- ' + err.statusText);
   }//end function AJAXerror

   function setsidebar(type,contents,max,title,index,readitems) {//open the sidebar with type type and contents contents and fetch
      if(!max) {max = 5;}
      if(!title) {title = '';}
      if(!index) {index = '';}
      $('sidebar').style.display = 'block';//open sidebar
      $('sidebarcontents').innerHTML = '<i>Loading...</i>';
      if(type == 'blank') {
         $('sidebarcontents').innerHTML = '';
         $('sidebar').style.display = 'none';
         return;
      }//end if type == blank
      if(type == 'url') {
         try {
            new Ajax.Updater("sidebarcontents",contents, {asynchronous:true, onFailure:AJAXerror});//send request and set handler functions
         } catch (e) {
            alert(e);
         }//end try-catch
         return;
      }//end if type == url
      $('sidebarcontrol').type.value = type;
      $('sidebarcontrol').contents.value = contents;
      $('sidebarcontrol').max.value = max;
      try {
         new Ajax.Updater("sidebarcontents","include/boxes/boxes.php?box[INDEX]=" + index + "&box[READITEMS]=" + readitems + "&box[TYPE]=" + type + "&box[CONTENTS]=" + encodeURIComponent(contents) + "&box[MAX]=" + max + "&box[TITLE]=" + encodeURIComponent(title) + "&box[SUMMARY]=all&box[NEWWINDOW]=1&includerel=yes&nomenu=yes", {asynchronous:true, onFailure:AJAXerror});//send request and set handler functions
      } catch (e) {
         alert(e);
      }//end try-catch
   }//end function setsidebar

   function disableSorting() {
      Sortable.destroy("oldindex");
   }//end disableSorting

   function enableSorting() {
      //code for drag-and-drop boxes
      Sortable.create("oldindex",
        {tag:'div',overlap:'horizontal',handle:'headertitle',constraint: false,
         onUpdate:function(){
            var getstring = "updateboxes.php?noredirect=yes&nobools=yes&" + Sortable.serialize("oldindex") + index;//set up GET string
            idupdate = ("&" + Sortable.serialize("oldindex")).split('&oldindex[]=');//store ids for updating box ids later
            disableSorting();//disable sorting until the request is done so we don't end up with weird data errors
            out.innerHTML = "Updating...";out.style.display = "block";//display updating message
            try {
               new Ajax.Request(getstring, {onSuccess:handleBoxmoveSuccess, onFailure:AJAXerror});//send request and set handler functions
            } catch (e) {
               alert(e);
            }//end try-catch
         }
       });
   }//end enableSorting
   
   function handleBoxmoveSuccess(result) {
      handleResponseError(result.responseText);//if response is an error, display error
      //the following code changes the ids on the boxes to make them match their ids in the file after update
      if(idupdate !== 0) {
         var bx = ["dummy"];
         var dl = ["dummy"];
         var dl2 = ["dummy"];
         var edt = ["dummy"];
         var i;
         idupdate2 = index.split('&index[]=');
         for(i=1;i<idupdate.length;i++) {
            bx.push(document.getElementById("box_" + idupdate[i]));
            dl.push(document.getElementById("deletelinks" + idupdate[i]));
            dl2.push(document.getElementById("deletelink" + idupdate[i]));
            edt.push(xget('//div[@id="box_'+idupdate[i]+'"]//div//input[@name="oldindex"]'));
         }//end for i
         for(i=1;i<idupdate2.length;i++) {
            if(bx[i] != "dummy") {
               bx[i].id = "box_" + idupdate2[i];
               boxIndexes[idupdate[i]] = idupdate2[i];
            }//end if bx[i] ! dummy
            if(dl[i] != "dummy") {
               dl[i].id = "deletelinks" + idupdate2[i];
               dl[i].innerHTML = "<a href=\"javascript:deletebox(&quot;" + idupdate2[i] + "&quot;);\">Yes</a> / <a href=\"javascript:Element.toggle(&quot;deletelinks" + idupdate2[i] + "&quot;);\">No</a>";
            }//end if dl[i] ! dummy
            if(dl2[i] != "dummy") {
               dl2[i].id = "deletelink" + idupdate2[i];
               dl2[i].innerHTML = "<a href=\"updateboxes.php?oldindex=" + idupdate2[i] + "&amp;delete=yes\" onclick=\"Element.toggle(&quot;deletelinks" + idupdate2[i] + "&quot;);return false;\">delete</a>";
            }//end if dl[i] ! dummy
            if(edt[i] != "dummy") {
               edt[i].value = idupdate2[i];
            }//end if edt[i] ! dummy
         }//end for i
      }//end if idupdate != 0
      hideout();//hide updating message and box
      enableSorting();//re-enable sorting
   }//end function handleBoxmoveSuccess
   
   function deletebox(boxid) {
      out.innerHTML = "Deleting...";out.style.display = "block";//display updating message
      try {
         new Ajax.Request("updateboxes.php?noredirect=yes&deleteconfirm=yes&oldindex=" + boxid, {onSuccess:function(result){handleResponseError(result.responseText);hideout();}, onFailure:AJAXerror});//send request and set handler functions
      } catch (e) {
         alert(e);
      }//end try-catch
      Element.remove("box_" + boxid);//remove box
      setsidebar('blank');
   }//end function deletebox
   
   function markreadunread(type,data,index) {
      var actualindex = getActualIndex(index);
      if(type == 'unread') {
         out.innerHTML = 'Marking Unread...';
         out.style.display = 'block';
         new Ajax.Request('markreadunread.php?mark=unread&index='+actualindex+'&data='+data,
            {
               onSuccess:function(result) {
                  handleResponseError(result.responseText);
                  hideout();
                  var blocks = data.split(',');
                  for(var i=0; i<blocks.length; i++) {
                     $('id'+blocks[i]).className = 'unread';
                     var tmp = xget('//div[@id="id'+blocks[i]+'"]//img');
                     tmp.src = 'images/flag_red.png';
                     tmp = xget('//div[@id="id'+blocks[i]+'"]//a');
                     tmp.href = 'javascript:markreadunread("read","'+blocks[i]+'","'+index+'");';
                     tmp = xget('//div[@id="id'+blocks[i]+'"]//span[@class="itemtitle"]//a');
                     tmp.onmousedown = 'markreadunread("read","'+blocks[i]+'","'+index+'");';
                     tmp = xget('//div[@id="id'+blocks[i]+'"]//a[@class="ui"][last()]');
                     tmp.onmousedown = 'markreadunread("read","'+blocks[i]+'","'+index+'");';
                  }//end for blocks
                }
             ,
                onFailure:AJAXerror
             });
      } else {
         out.innerHTML = 'Marking Read...';
         out.style.display = 'block';
         new Ajax.Request('markreadunread.php?mark=read&index='+actualindex+'&data='+data,
            {
               onSuccess:function(result) {
                  handleResponseError(result.responseText);
                  hideout();
                  var blocks = data.split(',');
                  for(var i=0; i<blocks.length; i++) {
                     $('id'+blocks[i]).className = 'read';
                     var tmp = xget('//div[@id="id'+blocks[i]+'"]//img');
                     tmp.src = 'images/flag_white.png';
                     tmp = xget('//div[@id="id'+blocks[i]+'"]//a');
                     tmp.href = 'javascript:markreadunread("unread","'+blocks[i]+'","'+index+'");';
                     tmp = xget('//div[@id="id'+blocks[i]+'"]//span[@class="itemtitle"]//a');
                     tmp.onmousedown = '';
                     tmp = xget('//div[@id="id'+blocks[i]+'"]//a[@class="ui"][last()]');
                     tmp.onmousedown = '';
                     if(blocks.length > 1) {
                        tmp = xget('//div[@id="box_'+actualindex+'"]//span[@class="allread"]//img');
                        if(tmp) {
                           Element.remove(tmp);
                        }
                     }//end if blocks.length > 1
                  }//end for blocks
                }
             ,
                onFailure:AJAXerror
             });
      }//end if-else unread
   }//end function markreadunread
   
   
   function showboxes(classes) {
      var boxes = document.getElementsByClassName('box');
      for(var i=0; i<boxes.length; i++) {
         if(!classes || Element.hasClassNames(boxes[i], classes)) {
            Element.show(boxes[i]);
         } else {
            Element.hide(boxes[i]);
         }
      }//end for
   }//end function showboxes
   
   function addBookmark(type,title,link,contents) {
      var tags = prompt('Enter tags:','');
      if(!tags) {tags = '';}
      out.innerHTML = 'Saving Mark...';
      out.style.display = 'block';
      new Ajax.Request('marks.php?add&ajax', {method:'post', postBody:'type=' + encodeURIComponent(type) + '&title=' + encodeURIComponent(title) + '&link=' + encodeURIComponent(link) + '&contents=' + encodeURIComponent(contents) + '&tags=' + encodeURIComponent(tags), onSuccess:function(result){hideout();}, onFailure:AJAXerror});//send request and set handler functions
   }//end function addBookmark
   
   function writeScript(src) {
      var thescript = document.createElement("script");
      thescript.type = "text/javascript";
      thescript.src = src;
      document.body.appendChild(thescript);
   }//end function writeScript
   
   function addBox() {
      setsidebar('url','addbox.php?form');
      writeScript('addbox.php?js');
   }//end function addBox
   
   function getBox(boxid,sibling,removesibling,callback) {
      new Ajax.Request('include/boxes/boxes.php?box[INDEX]='+boxid+'&get', {onSuccess:function(response){
         if(!removesibling)
            Element.remove('box_'+boxid);
         if(sibling) {
            new Insertion.Before(sibling,response.responseText);
         } else {
            new Insertion.Bottom($('oldindex'),response.responseText);
         }//end if-else sibling
         Nifty("div#box_"+boxid,"transparent");
         if(removesibling)
            Element.remove(sibling);
         if(callback) callback();
      }, onFailure:AJAXerror});//send request and set handler functions
   }//end function afterRefreshBox
   
   function addNewBox(data) {
      disableSorting();
      new Insertion.Bottom('oldindex','<div id="box_TEMP" class="box" style="float:left;width:400px;font-style:italic;"><h2>Adding...</h2></div>');
      Nifty("div#box_TEMP","transparent");
      Element.scrollTo('box_TEMP');
      new Ajax.Request('addbox.php', {method:'post', postBody:'noredirect=yes&'+data, onSuccess:function(result){getBox(result.responseText,$('box_TEMP'),true);enableSorting();}, onFailure:AJAXerror});//send request and set handler functions
      setsidebar('blank');
   }//end function addNewBox
   
   function boxMsg(boxid,msg) {
      var sibling = xget("//div[preceding-sibling::div[@id='box_"+boxid+"']]");
      if(!sibling) sibling = false;
      if(!msg) return sibling;
      var width = $('box_'+boxid).style.width;
      if(!width) width = '400px';
      Element.remove('box_'+boxid);
      if(sibling)
         new Insertion.Before(sibling,'<div id="box_'+boxid+'" class="box" style="float:left;width:'+width+';font-style:italic;"><h2>'+msg+'</h2></div>');
      else
         new Insertion.Bottom($('oldindex'),'<div id="box_'+boxid+'" class="box" style="float:left;width:'+width+';font-style:italic;"><h2>'+msg+'</h2></div>');
      Nifty("div#box_"+boxid,"transparent");
      return sibling;
   }//function boxMsg
   
   function refreshBox(boxid,url,isidx) {
      disableSorting();
      var sibling = boxMsg(boxid,'Refreshing...');
      if(!isidx) {
         new Ajax.Request('clearcachefor.php?noredirect&url='+url, {onSuccess:function(result){getBox(boxid,sibling);enableSorting();}, onFailure:AJAXerror});//send request and set handler functions
      } else {
         new Ajax.Request('clearcachefor.php?noredirect&index='+url, {onSuccess:function(result){getBox(boxid,sibling);enableSorting();}, onFailure:AJAXerror});//send request and set handler functions
      }
   }//end refreshBox
   
   function updateBox(boxid,data) {
      disableSorting();
      var sibling = boxMsg(boxid,'Saving...');
      new Ajax.Request('updateboxes.php?noredirect=yes', {method:'post', postBody:data, onSuccess:function(result){getBox(boxid,sibling);enableSorting();}, onFailure:AJAXerror});//send request and set handler functions
      setsidebar('blank');
   }//end function updateBox
