// - next store user id for each item, sort of overkill but
K.ICON_URL = "/img/icons/";
var ajax_item_r = make_new_ajax_request("/item_backend.php", item_callback);
var tmp_add_id = 0;

// screaming we need to put this in some kind of context object
var scroll_to_item_id = null;
var items_root_parents = null;

var items_root = null;
var all_items_by_id = new Array();

var root_item_under_users_tree = false;

// for items we're adding that haven't been saved
var all_tmp_items_by_id = new Array();

var g_il = null;

function dump_info()
{  
   var items_div= document.getElementById("items_div");
   dBug(
   "ST=" + items_div.scrollTop + ", " +
   "OH=" + items_div.offsetHeight + ", "
   );
}

function upload_item_callback(upload_num)
{  
   el = document.getElementById("upload_div" + upload_num);
   if (el)
   {  el.parentNode.removeChild(el);
   }
}

function cut_item(id)
{  user.cut_item_now = id;
//   draw_items();
}

function uncut_item(id)
{  user.cut_item_now = null;
//   draw_items();
}

function paste_item(to_parent)
{  var xml = _tag_(K.TAG_ITEM_ID, user.cut_item_now) +
      "<NewParentID>" + to_parent + "</NewParentID>";
//   send_ajax_request(ajax_item_r, "Move", xml);
}

function fetch_item_data(item_list)
{



}

function Item(id, version)
{
   this.id = id;
   this.version = version;
   this.loaded = false;
   this.picked = false;
   this.editing = false;
   this.read_privacy = K.ITEM_PRIVACY_READ_PRIVATE;
   this.write_privacy = K.ITEM_PRIVACY_WRITE_NONE;
   this.owner_user_id = null;
   this.attributes= K.ITEM_ATTRIB_NONE;
   this.children = new Array();
   this.tmp_add_id = null;
   this.my_el = null;
   this.unique_views = 0;
   this.rotate_tag = 0;
   this.insert_before = null;
}

// someday get fancy and make this work - and fixup the links that call it
//  to be more 'sophisticated' with function links not javascript: text
Item.prototype.remove = function() 
{  if (this.id)
   {  
//      send_ajax_request(ajax_item_r, "Delete", 
//         _tag_(K.TAG_ITEM_ID, this,id));
   }
}


function delete_item(item_id)
{  
   var xml = _tag_(K.TAG_ITEM_ID, item_id);
//   send_ajax_request(ajax_item_r, K.TAG_CMD_DELETE, xml);
   do_ajax("/item_backend.php", process_delete_item, 
      K.TAG_CMD_DELETE, xml);
} 

// basically add a 'proxy' item, but set it to 'editing' so
//  we can draw it properly
function add_item(parent_id, item_type, to_top)
{  
   // make a 'stub' object so that I have something to draw
   var m = new Item();
   m.editing = true;
   m.attributes = K.ITEM_ATTRIB_NONE;
   m.tmp_add_id = tmp_add_id++; // used for adding new items
   m.id = null; // flags to the edit controls that this is a new item
   m.type = item_type;
   m.parent_id = parent_id;
   m.text = "";
   m.insert_before = -1;
   if (to_top)
   {  m.insert_before = 0;
   }
   
   var my_parent = all_items_by_id[parent_id];
   if (to_top)
   {  my_parent.children.unshift(m);
   }
   else
   {  my_parent.children.push(m);
   }
   all_tmp_items_by_id[m.tmp_add_id] = m;
////   scroll_to_item_id

//   draw_items();

   if (m.my_el)
   {  
      var items_div= document.getElementById("items_div");
      var st = items_div.scrollTop;
      var oh = items_div.offsetHeight;
      var el_pos = findPos(m.my_el, items_div)[1];
      if (el_pos < st || el_pos > st + oh)     
      {  var new_pos = el_pos -  (oh/2);
//dBug(new_pos);
         //dBug("ST=" + st + ", OH=" + oh + ", EL@" + el_pos + ", NP=" + new_post);
         if (new_pos < 0)
         {  new_pos = 0;
         }
         items_div.scrollTop = new_pos;
      }
  //    else  dBug("no need");
   }
}

function set_privacy(item_data, mode, recur, is_read)
{  var item_list;
   if (!items instanceof Array) {
      item_list = [];
      item_list.push(item_data);
   } else {
      item_list = item_data;
   }
  
   var xml  = _tag_(K.TAG_ITEM_ID, item_id);
   xml += "<IsRead>" + xml_escape(is_read) + "</IsRead>";
   xml += "<Privacy>" + xml_escape(mode) + "</Privacy>";
   xml += "<Recursive>" + (recur ? "1" : "0") + "</Recursive>";
///   send_ajax_request(ajax_item_r, "EditPrivacy", xml);
}

function shift_item(item_id, is_up, is_top)
{  
   var xml  = _tag_(K.TAG_ITEM_ID, item_id);
   xml += "<Direction>" + 
      (is_up ? (is_top ? K.TAG_SHIFT_TOP : K.TAG_SHIFT_UP) : 
      (is_top ? K.TAG_SHIFT_BOTTOM : K.TAG_SHIFT_DOWN)) + 
      "</Direction>";
//   send_ajax_request(ajax_item_r, "Shift", xml);
}

function draw_root_item(item, el)
{  //add_menu_for_item(item, el);

   var new_el;
   var t = "(home) &nbsp;&nbsp;";
   new_el = document.createElement('SPAN');
   new_el.innerHTML = t;
   el.appendChild(new_el);
}


function rotate_image_item(item_id, is_cw)
{
   var xml = _tag_(K.TAG_ITEM_ID, item_id) +
      "<Degrees>" + (is_cw ? -90 : 90 ) + "</Degrees>";
   item = all_items_by_id[item_id];
   item.rotate_tag += (is_cw ? -1 : 1);
//   send_ajax_request(ajax_item_r, "EditImage", xml);
}

function submit_upload_image(tmp_add_id)
{
   var item = all_tmp_items_by_id[tmp_add_id];
   el = document.getElementById('upload_frm' + tmp_add_id);

   var xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
   xml += "<UploadImage>";
   xml += _tag_(K.TAG_TYPE_ID, ITEM_TYPE_IMAGE);
   xml += "<TempID>" + tmp_add_id + "</TempID>";
   xml += "<ParentID>" + item.parent_id  + "</ParentID>";
   xml += "<InsertBefore>" + item.insert_before + 
      "</InsertBefore></UploadImage>";

   el.target = "upload_iframe" + tmp_add_id; 
   el.action = "/upload_backend.php?xml=" + urlencode(xml);
   el.submit();
}

function save_edit(item_id)
{  
   var el = document.getElementById("edit_" + item_id);

   xml  = _tag_(K.TAG_ITEM_ID, item_id);
   xml += _tag_(K.TAG_PAYLOAD, el.value);
//   send_ajax_request(ajax_item_r, "Edit", xml);
}

/*
function add_menu_for_item(item, el)
{  return;
   if (user.is_guest) return;
   var el_span = document.createElement('SPAN');
   el.appendChild(el_span);

   var popup_control = document.createElement('img');
   var button_id = "item_control_" + item.id;;
   popup_control.setAttribute('id', button_id);
   popup_control.style.cursor = "pointer";
   popup_control.style.display = "none";
   popup_control.style.position = "absolute";
   popup_control.showing_menu = false;
   popup_control.src = '/img/gear.png';
   popup_control.className = "yuimenuitem";
   popup_control.parent_el = el_span;
   popup_control.item = item;
   popup_control.onclick = show_gear_menu;
   el_span.appendChild(popup_control);
   el.onmouseover= function() { 
      if (!popup_control.item.editing)
      {  popup_control.style.display ="inline";
//         el = document.getElementById("control_pad");
//         el.style.display = "inline";
      }
   }
   el.onmouseout = function() { 
      if (!popup_control.showing_menu)
      {  popup_control.style.display ="none";
         popup_control.showing_menu = false;
//         el = document.getElementById("control_pad");
//         el.style.display = "inline";
      }
   }
}*/

function pick_item(item_id)
{  
   if (user.item_picked_now && all_items_by_id[user.item_picked_now])
   {  all_items_by_id[user.item_picked_now].picked = false;
   }

   // unpick if already picked
   if (user.item_picked_now == item_id)
   {  user.item_picked_now = null;
   }
   else
   {  user.item_picked_now = item_id;
   }

 // don't set if 'null' sent in
   if (user.item_picked_now && all_items_by_id[user.item_picked_now])
   {  all_items_by_id[user.item_picked_now].picked = true;
   }
   draw_search_results();
//   draw_items();
}

function pick_item2(item)
{  
   if (user.item_picked_now && all_items_by_id[user.item_picked_now])
   {  all_items_by_id[user.item_picked_now].picked = false;
   }

   // unpick if already picked
   if (user.item_picked_now == item.id())
   {  user.item_picked_now = null;
   }
   else
   {  user.item_picked_now = item.id();
   }

 // don't set if 'null' sent in
   if (user.item_picked_now && all_items_by_id[user.item_picked_now])
   {  all_items_by_id[user.item_picked_now].picked = true;
   }
   draw_search_results();
//   draw_items();
}

function guest_toggle_item(item_id)
{  var item = all_items_by_id[item_id];
   item.attributes ^= K.ITEM_ATTRIB_HIDE;
//   draw_items();
}

/*
<DIV style="clear:left;float:left; margin-left:80; padding:0; border:solid thick green">
   
   <DIV style="float:left; margin-left:10; padding:0; border:solid thick red">
         <A HREF="javascript:alert('wha');" style="float:left">
            <img style="border:0" src="/img/icons/pick_item.png"/>
         </A>
        <DIV style="float: none;border:solid thick blue; margin-left:15">
          this is some text this is some text this is some text this is some text
        </DIV>
   </DIV>
   
</DIV>
*/





var g_ic = 0;
var g_last_trans_process = null;

function item_callback()
{  g_ic++;
   var r = process_ajax_response(ajax_item_r);
   if (!r)
   {  
      dBug("Item callback NOT READY #" + g_ic);
      return;
   }


   dBug("Item callback START #" + g_ic);

   if (r.command == 'Move')
   {  if (r.command_ok)
      {  // again, cheap trick 
         user.cut_item_now = null; 
      }
      else
      {  alert("error: " + r.command_error);
      } 
   }
   else if (r.command == 'EditImage')
   {  
      var item_id = get_xml_value(r.doc, K.TAG_ITEM_ID);
      var el = document.getElementById("img_" + item_id);

      var item = all_items_by_id[item_id];
      el.src= "im.php?id=" + item_id + "&sz=thumb&rot=" + item.rotate_tag;
   }
   else if (r.command == K.TAG_CMD_ITEM_LOAD) {
 //     var item_data = r.doc.getElementsByTagName(K.TAG_WRAP_ITEM_DATA)[0];

//      var root = r.doc.getElementsByTagName(K.TAG_WRAP_ITEM);
      process_inbound_item_data(r);
//      draw_search_results();  // replace with auto draw
   }
   else if (r.command == K.TAG_CMD_CHILD_LIST)
   {
// error checking?!?
//      var item_data = r.doc.getElementsByTagName(K.TAG_WRAP_ITEM_DATA)[0];
      process_inbound_item_data(r, r.command);

// detect parent, invoke 'check order'

   }
// I guess really, there should be one error per item returned!
//  ...for when I batch things later
   else if (r.command == K.TAG_CMD_EDIT_TEXT)
   {  if (r.command_error)
      {  alert("error: " + r.command_error);
      }
      else
      {  
         process_inbound_item_data(r);
      }
   }
/* TODO: handle read/write privacy */
   else if (r.command == K.TAG_CMD_EDIT_PRIV)
   {  if (r.command_error)
      {  alert("error: " + r.command_error);
      }
      else
      {  var item_id = get_xml_value(r.doc, K.TAG_ITEM_ID);
         var new_priv = get_xml_value(r.doc, K.TAG_PRIVACY);
         var is_read = get_xml_value(r.doc, K.TAG_IS_READ);

         if (all_items_by_id[item_id])
         {  
            if (is_read == 1)
            {  all_items_by_id[item_id].read_privacy = new_priv;
            }
            else
            {  all_items_by_id[item_id].write_privacy = new_priv;
            }
 
            if (get_xml_value(r.doc, TAG_RECURSIVE))
            {
               if (is_read == 1)
               {  traverse_items(item_id, function(item) { 
                     item.read_privacy = new_priv;});
               }
               else
               {  traverse_items(item_id, function(item) { 
                     item.write_privacy = new_priv;});
               }
            }
//            draw_items();
         }
      }
   } 
   else if (r.command == TAG_CMD_EDIT_ATTRIB)
   {  if (r.command_error)
      {  alert("error: " + r.command_error);
      }
      else
      {  var item_id = get_xml_value(r.doc, K.TAG_ITEM_ID);
         if (item_id && all_items_by_id[item_id])
         {  all_items_by_id[item_id].attributes = 
               get_xml_value_null(r.doc, K.TAG_ATTRIB_NOW);
//            draw_items();
         }
      }
   }
   else if (r.command == K.TAG_CMD_SHIFT)
   {  var item_id = get_xml_value(r.doc, K.TAG_ITEM_ID);
   
      if (r.command_ok)
      {
         var the_item =  g_all_items[item_id];
         if (the_item) {
            var the_parent = the_item.parent_id();
            if (g_all_items[the_parent]) {
               g_all_items[the_parent].set_children_loaded(false);
               next_load(); 
            } 
         }
          
         //process_affected_items(r);
      }
      else
      {  alert("Shift failed: " + r.command_error);
      }
   }  

   g_last_trans_process = r.trans_id;
   dBug("Item callback STOP #" + g_ic);
}

function process_affected_items(r)
{
   var sets = r.doc.getElementsByTagName("AffectedItemSets");
   if (sets)
   {  //dBug(sets);
   }
   else dBug("NOOOOOOOOO!");

//   var item_id = get_xml_value(r.doc, K.TAG_ITEM_ID);

}


