var xmlHttp;          // Used for hand history fetching
var xmlHttpGroups;    // Used for group and access control
var xmlHttpQ;         // Used for toggling function

var o_histories;
var o_groups;

var i_current;
var i_page;

///////////////////////
// GENERAL FUNCTIONS //
///////////////////////
function GetXmlHttpObject()
{
  var xmlHttp=null;
  
  try {
    // Firefox, Opera 8.0+, Safari
    xmlHttp = new XMLHttpRequest();
  } catch(exception) {
    // Internet Explorer
    try
    {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (exception)
    {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
    
  return xmlHttp;
}

// Returns a HTML object (needed for browser compatibility)
function getObjectByName(o_name, o_type)
{
  var elem = document.getElementsByTagName(o_type);

  for(i=0;i<elem.length;i++){
    if(elem[i].getAttribute("name") == o_name) {
      return elem[i];
    }
  }
}

// Add an element dynamically inside a wanted tag in the HTML
// t_target   target object
// t_type     target type
// o_type     type of the generated object
// o_id       id of the generated object
// o_name     target name
// html_code  html code inside
function addElement(t_target, t_type, o_type, o_id, o_name, html_code) {
  var ni = getObjectByName(t_target, t_type);
  var newdiv = document.createElement(o_type);
  var divIdName = o_name;
  newdiv.setAttribute('name', divIdName);
  newdiv.setAttribute('id', o_id);
  newdiv.innerHTML = html_code;
  ni.appendChild(newdiv);
}

// Remove an object
// dFather     father object
// fatherType  type of the object (ie. div)
// dChild      child object
// childType   type of the child object
function removeElement(dFather, fatherType, dChild, childType) {
  var d = getObjectByName(dFather, fatherType);
  var dc = getObjectByName(dChild, childType);
  d.removeChild(dc);
}

/////////////////////////////
// HTML CREATION FUNCTIONS //
/////////////////////////////
function createHistoryEntry(p_action, p_title, p_date, p_index)
{
  var html = '<table border="0" width="433" height="*" cellpadding="5" cellspacing="0">\n' +
             '<td width="85" valign="top"><div id="handscontentfont">' + p_date +	'</div></td>' +
						 '<td width="*" valign="top"><div id="handscontentfont">';
	
//	if( p_active != "true" ) {
	  html = html + '<a href="javascript:showHistory(' + p_index +');">' + p_title + '</a>';
/*	} else {
	  html = html + p_title; 
	}*/
  
						 
	html = html + '</div></td>' +
						 '<td width="60" valign="top"><center><a href="javascript:removeRequest(' + p_index + ');">' +
						 '<image src="/images/cross.gif" title="Delete"></a></center></td>\n</table>\n';
						 
	return html;
}

// Creates a HTML entry.
// Parameters:
// p_type   int:     0=user, 1=group
// p_id     int:     rights_id
// p_title  string:  user- or groupname to be displayed
function createRightEntry(p_type, p_id, p_title)
{
  var html = '<table border="0" width="295" height="*" cellpadding="2" cellspacing="0" name="right_entry_'+p_id+'">' +
						 '<tr><td width="30"><center>';
						 
	if( p_type == 0 ) {
	  html += '<img src="/images/man.gif" title="User">';
	} else {
	  html += '<img src="/images/men.gif" title="Group">';
	}
	
	html += '</center></td><td width="150"><div id="handscontentfont">' + p_title + '</div></td>' +
	        '<td width="15"><a href="javascript:;;"><img src="/images/cross.gif" onclick="javascript:removeRights(' + p_id + ');" title="Delete"></a></td><td width="*"></td></tr></table>\n';

  return html;
}

///////////////////////////////////
// Management specific functions //
///////////////////////////////////

function clearSlots(p_offset)
{
  i_page_size = getObjectByName("page_size", "input").value;

  for( var i = p_offset; i < i_page_size; i++ ) {
    var o_obj = getObjectByName("history_link_"+i, "span");
    if( o_obj != null ) {
      o_obj.innerHTML = ""; 
    }
  }
}

// Handles the returned history XML object and displays it
function getHistoriesHandler()
{
  if( xmlHttp.readyState != 4 || xmlHttp.status != 200 ) {
    return;
  }  
  
  var xmldoc = xmlHttp.responseXML.documentElement;
  
  // Get the histories
  o_histories = xmldoc.getElementsByTagName('history');
  
  for(var i=0;i<o_histories.length;i++){
    var h_id = o_histories[i].getAttribute("id");
    var h_active = o_histories[i].getAttribute("active");
  
    // Get the metadata for the history
    var o_metadata = o_histories[i].getElementsByTagName('metadata');

    // Some variables for displaying the fetch info
    var m_title = "";
    var m_date = "";
    
    if( h_active == "true" ) {
      showHistory(i);
    }
    
    // If hand history is active, display the information appropriately
    if( o_metadata.length != 0 ) {
      var o_items = o_metadata[0].getElementsByTagName('item');
      
      // Loop through items
      for(var j=0; j<o_items.length;j++) {
        var data_name = o_items[j].getAttribute("name");
        
        if( data_name == "title" ) {
          m_title = unescape(o_items[j].firstChild.nodeValue); 
        } else if( data_name == "date" ) {
          m_date = o_items[j].firstChild.nodeValue; 
        }
      }
    }
    var html = createHistoryEntry('', m_title, m_date, i);
    var o_slot = getObjectByName("history_link_"+i, "span");
    
    // If slot has been created, there's no need to recreate it.
    if( o_slot == null ) {
      addElement('history_list', 'span', 'span', '', 'history_link_' + i, html);
    } else {
      o_slot.innerHTML = html; 
    }
  }
  
  clearSlots(o_histories.length);
  
  // Update the paging links
  refreshPaging();
}

// Get the current history (PHP will use sessions to track the current history)
function getHistories(p_offset)
{
  xmlHttp = GetXmlHttpObject();
 
  if (xmlHttp == null)
  {
    alert ("Your browser does not support AJAX!");
    return;
  }
 
  i_page_size = getObjectByName("page_size", "input").value;
 
  var g_url = "http://" + window.location.host + "/reviewer/manage_f.php";
  g_url = g_url + "?action=get&offset="+p_offset+"&pagesize="+i_page_size;

  // Send the request
  xmlHttp.open("GET", g_url, true);
  xmlHttp.onreadystatechange = getHistoriesHandler;  // Assign handler
  xmlHttp.send(null); 
}

// View history info of the indexed HH
function showHistory(p_id)
{
  var o_metadata = o_histories[p_id].getElementsByTagName('metadata');
  var o_rights = o_histories[p_id].getElementsByTagName('rights');
    
  i_current = p_id;  // Set the active hh
    
  // If hand history is active, display the information appropriately
  if( o_metadata.length != 0 ) {
    var o_items = o_metadata[0].getElementsByTagName('item');
      
    // Loop through items
    for(var j=0; j<o_items.length;j++) {
      var data_name = o_items[j].getAttribute("name");
        
      var h_item = getObjectByName("h_"+data_name, "span");
      if( h_item != null ) {
        if( data_name == "title") {
          var h_link_view = getObjectByName("h_link_view", "span");
          h_link_view.innerHTML = '(<a href="view.php?id='+o_histories[p_id].getAttribute("id")+'">view</a>)';
        }
        if( data_name == "private" ) {
          var priv = o_items[j].firstChild.nodeValue;
          var priv_str = '';
          switch( priv ) {
            case '0':
              priv_str = 'public';
              break;
            case '1':
              priv_str = 'restricted';
              break;
            case '2':
              priv_str = 'private';
              break; 
            default:
              priv_str = 'error';
              break;
          }
          h_item.innerHTML = '<a href="javascript:togglePrivate(' + priv + ');">' + priv_str + '</a> (click to toggle)'; 
        } else {
          if( o_items[j].firstChild != null ) {
            h_item.innerHTML = o_items[j].firstChild.nodeValue;
            
            if( data_name == "description" || data_name == "title" ) {
              h_item.innerHTML = unescape(h_item.innerHTML); 
            }
          }
        }
      }
    }
  }
  
  // Display the set rights to this history
  if( o_rights.length != 0 ) {
    var o_rl = o_rights[0].getElementsByTagName('right');

    var o_right_span = getObjectByName('rights', 'span');

    var s_rights = "";
    
    for( var k = 0; k < o_rl.length; k++ ) {
      var r_id = o_rl[k].getAttribute("r_id");
      var m_name = o_rl[k].firstChild.nodeValue;
      var g_id = o_rl[k].getAttribute("g_id");
      var u_id = o_rl[k].getAttribute("u_id");
      
      
      var html = "";
      
      if( g_id != null ) {
        html = createRightEntry(1, r_id, m_name);
      } else if( u_id != null ) {
        html = createRightEntry(0, r_id, m_name);        
      }    
      s_rights += html;
    }
    
    o_right_span.innerHTML = s_rights;
  }
  
  // Show the groups in a list
  var o_group_list = getObjectByName("groupselect", "select");
  o_group_list.options.length = 0; // Clear the options
  o_group_list.options[0] = new Option('Select group','0');;

  var used = false;
  for( var m = 0; m < o_groups.length; m++ ) {
    if( o_groups[m] == null ) { continue; }
    // TODO: Optimize
    for( var n = 0; n < o_rl.length; n++ ) {
      if( o_rl[n].getAttribute("g_id") != null && o_rl[n].getAttribute("g_id") == m ) {
        used = true;
        n = o_rl.length;
        break;
      } 
    } 
    
    if( !used ) {
      o_group_list.options[o_group_list.options.length] = new Option(o_groups[m], m); 
    } else {
      used = false;
    }
  }
}

function togglePrivateHandler()
{
  if( xmlHttpQ.readyState != 4 || xmlHttpQ.status != 200 ) {
    return;
  }
  
  var xmldoc = xmlHttpQ.responseXML.documentElement;
  
  // Get the histories
  o_toggled = xmldoc.getElementsByTagName('item');
  
  var o_cur_i = o_histories[i_current].getElementsByTagName("item");
  for( var i = 0; i < o_cur_i.length; i++ ) {
    if( o_cur_i[i].getAttribute("name") == "private" ) {
      var new_val = o_toggled[0].firstChild.nodeValue;
      o_cur_i[i].firstChild.nodeValue = new_val;
      var h_item = getObjectByName("h_private", "span");
      var priv_str = '';

      switch( new_val ) {
        case '0':
          priv_str = 'public';
          break;
        case '1':
          priv_str = 'restricted';
          break;
        case '2':
          priv_str = 'private';
          break; 
        default:
          priv_str = 'error';
          break;
      }

      
      h_item.innerHTML = '<a href="javascript:togglePrivate(' + new_val + ');">' + priv_str + '</a> (click to toggle)';
      return;
    } 
  }
}

function togglePrivate(p_priv)
{
  xmlHttpQ = GetXmlHttpObject();

  var g_url = "http://" + window.location.host + "/reviewer/manage_f.php";
  g_url = g_url + "?action=toggle_private&hh_id="+o_histories[i_current].getAttribute("id")+"&current="+p_priv;

  // Send the request
  xmlHttpQ.open("GET", g_url, true);
  xmlHttpQ.onreadystatechange = togglePrivateHandler;  // Assign handler
  xmlHttpQ.send(null); 
    
}

// Create a paging link
function createPagingLink(p_page, p_content)
{
  var html = '<a href="javascript:showPage(' + p_page + ');">' + p_content + '</a>&nbsp;&nbsp;';
  return html;
}

function showPage(p_page)
{
  var i_page_size = getObjectByName("page_size", "input").value;

  i_page = p_page;

  getHistories( p_page * i_page_size );
}

// Refresh the paging links
function refreshPaging()
{
  var o_paging = getObjectByName("paging_links", "div");
  var i_total_count = getObjectByName("history_count", "input").value;
  var i_page_size = getObjectByName("page_size", "input").value;
  var pages = (i_total_count / i_page_size + 0.999999 | 0);
  var s_paging = "";
  
  s_paging += createPagingLink('0', '<image src="/images/arrowleftdouble.gif">')
  var prev_page = i_page - 1 > 0 ? i_page - 1 : 0;
  var next_page = i_page + 1 < pages ? i_page + 1 : i_page;
  
  s_paging += createPagingLink(prev_page, '<image src="/images/arrowleft.gif">') 
    
  // The numbers of pages in between
  for( var i = 0; i < pages; i++ ) {
    if( i_page != i ) {
      s_paging += createPagingLink(i, i+1); 
    } else {
      s_paging += (i+1) + "&nbsp;&nbsp;";
    }
  }
  
  s_paging += createPagingLink(next_page, '<image src="/images/arrowright.gif">');
  
  s_paging += createPagingLink(pages-1, '<image src="/images/arrowrightdouble.gif">');
  
  // Set it on the document
  o_paging.innerHTML = s_paging;
}

function cancelDelete(p_id)
{
  var e_query = getObjectByName("history_query","span");
  e_query.innerHTML = "";
}

// Request removal of a history
function removeRequest(p_id)
{
  var e_query = getObjectByName("history_query","span");
  var o_items = o_histories[p_id].getElementsByTagName("item");
  var h_name = "";
  var h_id = -1;
  
  for( var i = 0; i < o_items.length; i++ ) {
    if( o_items[i].getAttribute("name") == "title" ) {
      h_name = o_items[i].firstChild.nodeValue;
      h_id = o_histories[p_id].getAttribute("id");
      break; 
    } 
  }
  
  e_query.innerHTML = '<form method=POST action="manage_f.php?action=remove_history'+"&"+'hh_id=' + h_id + '">Do you wish to delete group ' + unescape(h_name) + '<br><input type=submit value=Yes name="del"> <input type=button value=No onClick="javascript:cancelDelete();"></form>'; 
}

// GROUP AND RIGHT CONTROL

function addRightsHandler()
{
  if( xmlHttpGroups.readyState == 4 ) {
    if( xmlHttpGroups.status == 200 ) {
      var xmldoc = xmlHttpGroups.responseXML.documentElement;

      // Get group object
      var o_rights_xml = xmldoc.getElementsByTagName('right');
      var o_right_span = getObjectByName('rights', 'span');

      var o_cur_rights = o_histories[i_current].getElementsByTagName('rights');

      // This gets list of groups and prints out the links
      for(var i = 0; i < o_rights_xml.length; i++){
        var g_id = o_rights_xml[i].getAttribute("g_id");
        var u_id = o_rights_xml[i].getAttribute("u_id");

        var r_id = o_rights_xml[i].getAttribute("r_id");
        var r_title = o_rights_xml[i].firstChild.nodeValue;    
      
        var new_right = document.createElement('right');
        var html = "";
        
        if( g_id != null ) {
          new_right.setAttribute('g_id', g_id);
          html = createRightEntry(1, r_id, r_title);
          
          var o_gr_c = getObjectByName("groupselect", "select");
          
          for( var l = 0; l < o_gr_c.options.length; l++ ) {
            if( o_gr_c[l].selected ) {
              o_gr_c.removeChild(o_gr_c[l]);
            }
          }
        } else if( u_id != null ) {
          new_right.setAttribute('u_id', u_id); 
          html = createRightEntry(0, r_id, r_title);
          
          // Clear the textbox
          var o_uname = getObjectByName("searchuser", "input");
          o_uname.value = "";
        }
        new_right.setAttribute('r_id', r_id);
        
        new_right.innerHTML = r_title;
        o_cur_rights[0].appendChild(new_right);

        o_right_span.innerHTML += html;
      }
    }
  }  
}

function addRights()
{
  // Get the group and user input values
  var i_rg = getObjectByName("groupselect", "select").value; // Group ID to add
  var s_ru = getObjectByName("searchuser", "input").value;   // Username to add
    
  xmlHttpGroups = GetXmlHttpObject();
  
  var g_url = "http://" + window.location.host + "/reviewer/manage_f.php";
  g_url += "?action=add_rights&hh_id="+o_histories[i_current].getAttribute("id")+"&";
  if( i_rg != 0 ) {
    g_url += "g_id=" + i_rg +"&";
  }
  if( s_ru != "" ) {
    g_url += "username=" + s_ru;
  }

  // Send the request
  xmlHttpGroups.open("GET", g_url, true);
  xmlHttpGroups.onreadystatechange = addRightsHandler;  // Assign handler
  xmlHttpGroups.send(null);
}

function removeRightsHandler()
{
  if( xmlHttpGroups.readyState == 4 ) {
    if( xmlHttpGroups.status == 200 ) {
      var xmldoc = xmlHttpGroups.responseXML.documentElement;

      // Get group object
      var o_rights_xml = xmldoc.getElementsByTagName('right');
      var o_cur_father = o_histories[i_current].getElementsByTagName('rights');
      var o_cur_rights = o_cur_father[0].getElementsByTagName('right');
      var o_group_list = getObjectByName("groupselect", "select");

      for( var i = 0; i < o_rights_xml.length; i++ ) {
        for( var j = 0; j < o_cur_rights.length; j++ ) {
          var r_id = o_cur_rights[j].getAttribute("r_id");
          var d_id = o_rights_xml[i].firstChild.nodeValue;
          if( r_id == d_id ) {
            // Add to the box
            o_group_list.options[o_group_list.options.length] = new Option(o_cur_rights.item(j).firstChild.nodeValue, o_cur_rights.item(j).getAttribute("g_id")); 

            // Remove from the XML
            o_cur_father[0].removeChild(o_cur_rights.item(j));
             
            // Remove from the HTML
            removeElement("rights", "span", "right_entry_"+r_id, "table");
          } 
        }
      }
    }
  }
}

// Remove rights of the given rights_id
function removeRights(r_id)
{
  xmlHttpGroups = GetXmlHttpObject();
  
  var g_url = "http://" + window.location.host + "/reviewer/manage_f.php";
  g_url += "?action=remove_rights&r_id="+r_id;

  // Send the request
  xmlHttpGroups.open("GET", g_url, true);
  xmlHttpGroups.onreadystatechange = removeRightsHandler;  // Assign handler
  xmlHttpGroups.send(null);  
}

// Saves the user groups in a variable
function getGroupsHandler()
{
  if( xmlHttpGroups.readyState == 4 ) {
    if( xmlHttpGroups.status == 200 ) {
      var xmldoc = xmlHttpGroups.responseXML.documentElement;

      // Get groups
      var o_groups_xml = xmldoc.getElementsByTagName('group');

      // This gets list of groups and prints out the links
      for(var i = 0; i < o_groups_xml.length; i++){
        var g_id = o_groups_xml[i].getAttribute("id");
        var g_title = o_groups_xml[i].getAttribute("name");

        o_groups[g_id] = g_title;
      }
    }
  }

  // Now get the histories
  // TODO: Move this elsewhere?!
  getHistories(0);
}

// This function is only called on full page reload - otherwise everything is modified dynamically
function getGroups()
{
  xmlHttpGroups = GetXmlHttpObject();
 
  if (xmlHttpGroups == null)
  {
    alert ("Your browser does not support AJAX!");
    return;
  }
  
  o_groups = new Array();
 
  var g_url = "http://" + window.location.host + "/reviewer/groups_f.php";
  g_url += "?action=groups";

  // Send the request
  xmlHttpGroups.open("GET", g_url, true);
  xmlHttpGroups.onreadystatechange = getGroupsHandler;  // Assign handler
  xmlHttpGroups.send(null);
}


// Clean up
function clean_up(control_name)
{
  var control = getObjectByName(control_name, 'span');
  control.innerHTML = ""; 
}


window.onload=function() {
  i_page = 0;
  i_current = 0;
  getGroups();
}