﻿/*=================================
  Authentication Methods
=================================*/
function login_Callback(resp){
  // Check if anything was returned
  if (resp.responseText == ''){
    alert('Login failed.\nPlease try again.');
    
    var frm = document.getElementById('login');
    frm.password.focus();
    frm.password.select();
  }else{
    // Set the logged-in flag
    loggedIn = true;
    
    // Show the main controls
    document.getElementById('add').style.display = 'block';
    document.getElementById('groups').style.display = 'block';
    document.getElementById('saved').style.display = 'block';
    
    // Form
    document.getElementById('userDetails').style.display = 'block';
    document.getElementById('login').style.display = 'none';
    
    // Username
    document.getElementById('username').innerHTML =
      document.getElementById('login').username.value;
      
    // Set the current group to the 1st
    currentGroup = eval('(' + resp.responseText + ')').Groups[0].fldGroupID;

    getData_Callback(resp);
  }
}

function login_OnSubmit(frm){
  // Get the Data
  var data = 'username=' + escape(frm.username.value) +
    '&password=' + escape(frm.password.value);
    
  // Set the Callback
  ajax.setReadyStateChanged(login_Callback);
  ajax.send('POST', '/login.aspx', true, data);
  
  return false;
}

function logout(resp){
  // Unset the logged-in flag
  loggedIn = false;

  // Reset all uneeded data
  if (files) files.length = 0;
  groups.length = 0;
  saved.length = 0;
  
  // Hide the main controls
  document.getElementById('add').style.display = 'none';
  document.getElementById('groups').style.display = 'none';
  document.getElementById('saved').style.display = 'none';

  // Hide any data
  document.getElementById('linksContainer').style.display = 'none';
  document.getElementById('saveGroup').style.display = 'none';
  document.getElementById('filesContainer').style.display = 'none';
  document.getElementById('notesContainer').style.display = 'none';
  
  // Show the Logo
  document.getElementById('info').style.display = 'block';
  
  // Form
  document.getElementById('userDetails').style.display = 'none';
  var frm = document.getElementById('login');
  frm.style.display = 'block';
  frm.username.value = 'Username';
  frm.username.focus();
  frm.password.value = '';
  
  // Reset the Public groups
  document.getElementById('publicGroups').selectedIndex = 0;
  if (resp) getData_Callback(resp);
}

function logout_Callback(resp){
  logout(resp);
}

function logout_OnClick(e){
  // Set the Callback
  ajax.setReadyStateChanged(logout_Callback);
  ajax.send('GET', '/login.aspx?logout=', true, null);
}

function register_Callback(resp){
  var data;
  try{
    data = eval('(' + resp.responseText + ')');
  }catch (m){
    alert('An unknown error occured');
    return;
  }
  
  // Display the message and redirect if ok
  if (data.msg) alert(data.msg);
  if (data.ok) document.location.href = '/index.aspx';
}

function register_OnSubmit(frm){
  // Validate the form
  if (frm.username.value.length == 0){ // Username
    alert('Username must be longer than 6 characters');
    frm.username.focus();
    return false;
  }else if (frm.pwd1.value.length < 6){ // Password
    alert('Password must be longer than 6 characters');
    frm.pwd1.focus();
    return false;
  }else if (frm.pwd1.value != frm.pwd2.value){ // Confirm Password
    alert('Passwords do not match');
    frm.pwd2.focus();
    return false;
  }else if (frm.email.value.length == 0){ // Email
    alert('Email address is required');
    frm.email.focus();
    return false;
  }
  
  // Set the post data
  var data = 'username=' + escape(frm.username.value) +
    '&pwd1=' + escape(frm.pwd1.value) +
    '&pwd2=' + escape(frm.pwd2.value) +
    '&email=' + escape(frm.email.value);

  // Set the Callback
  ajax.setReadyStateChanged(register_Callback);
  ajax.send('POST', '/register.aspx', true, data);
  
  return false;
}


/*=================================
  Get Data Methods
=================================*/
function getData(files, groups, links, pub, saved, notes){
  // Set the Callback
  ajax.setReadyStateChanged(getData_Callback);
  
  // Set the current group
  currentGroup = links;

  // Create the url
  var data = new Array();
  if (files) data.push('getFiles=');
  if (groups) data.push('getGroups=');
  if (links) data.push('getLinks=' + links);
  if (pub) data.push('getPublicGroups=');
  if (saved) data.push('getSavedGroups=');
  if (notes) data.push('getNotes=');
  var url = '/tools/getData.aspx?';
  for (var i = 0; i < data.length; i++){
    if (i > 0) url += '&';
    url += data[i];
  }
  
  // Send the Request
  ajax.send('GET', url, true, null);
}

function getData_Callback(resp){
  var data;
  try{
    data = eval('(' + resp.responseText + ')');
  }catch (e){
    return;
  }
  
  // Logged out?
  if (data.LoggedOut){
    alert('Your session has expired.\nYou will need to log back in.');
    logout();
    return;
  }
  
  // Set all the data first
  if (data.Columns) columns = data.Columns;
  if (data.Files) files = data.Files;
  if (data.Groups) groups = data.Groups;
  if (data.Notes) notes = data.Notes;
  if (data.Public) pub = data.Public;
  if (data.Saved) saved = data.Saved;
  if (data.Links) links = data.Links;

  // Columns
  if (data.Columns) setColumns();
  // Files
  if (data.Files) setFiles();
  // Groups
  if (data.Groups) setGroups();
  // Links
  if (data.Links) setLinks();
  // Notes
  if (data.Notes) setNotes();
  // Public
  if (data.Public) setPublic();
  // Saved
  if (data.Saved) setSaved();
}

function getGroup(groupID){
  // If no Group ID is give, get the current selected
  if (! groupID) groupID = document.getElementById('publicGroups').value;
  if (! groupID){
    alert('A Group needs to be selected first');
    return;
  }

  // Get all the links for the group
  getData(false, false, groupID, false, false, false);
  
  // Refresh the Groups
  setGroups();
  setSaved();
  
  // Update the Advert frame
  document.getElementById('advert').src = '/articles/' + groupID + '/';
}

function isOwnGroup(groupID){
  // Search own groups for the groupID
  for (var i = 0; i < groups.length; i++){
    if (groups[i].fldGroupID == groupID){
      return true;
    }
  }
  
  return false;
}


/*=================================
  Data Rendering
=================================*/
function allowLinkEditing(allow){
  var div;

  div = document.getElementById('optEditLink');
  div.title = allow ? 'Edit a Link' : '';
  div.onclick = allow ? optEditLink_OnClick : null;
  div.style.color = allow ? '#000000' : '#7F7F7F';
  div.style.cursor = allow ? 'pointer' : 'default';

  div = document.getElementById('optDeleteLink');
  div.title = allow ? 'Delete a Link' : '';
  div.onclick = allow ? optDeleteLink_OnClick : null;
  div.style.color = allow ? '#000000' : '#7F7F7F';
  div.style.cursor = allow ? 'pointer' : 'default';
}

function setColumns(){
  // Set the Column Names and the Edit form's Column values
  var table = document.getElementById('links');
  for (var i = 1; i <= 6; i++){
    table.tHead.rows[0].cells[i - 1].innerHTML = eval('columns[0].fldColumn' + i);
  }
}

function setFiles(){
  var table = document.getElementById('files');
  
  // Hide the Links container
  document.getElementById('info').style.display = 'none';
  document.getElementById('linksContainer').style.display = 'none';
  document.getElementById('notesContainer').style.display = 'none';
  
  // Show the Files container
  document.getElementById('filesContainer').style.display = 'block';
  
  // Redraw the Groups
  setGroups();
  setSaved();
  
  // Get the Table body and clear it
  var tb = table.tBodies[0];
  while (tb.rows.length > 0){
    tb.deleteRow(0);
  }
  
  // Add each of the rows
  for (var i = 0; i < files.length; i++){
    var row = document.createElement('tr');
    var cell, a;
    var file = files[i];
    
    // Filename
    cell = document.createElement('td');
    a = document.createElement('a');
    a.href = '/files/' + escape(file.Name);
    a.appendChild(document.createTextNode(file.Name));
    a.title = 'Download';
    cell.appendChild(a);
    row.appendChild(cell);
     
    // Type
    cell = document.createElement('td');
    cell.appendChild(document.createTextNode(file.Type));
    row.appendChild(cell);
   
    // Size
    cell = document.createElement('td');
    if (file.Size < 4096){
      cell.innerHTML = formatNumber(file.Size) + ' B';
    }else{
      cell.innerHTML = formatNumber(parseInt(file.Size / 1024)) + ' KB';
    }
    cell.style.textAlign = 'right';
    row.appendChild(cell);
     
    // Modified
    cell = document.createElement('td');
    cell.appendChild(document.createTextNode(file.Modified));
    row.appendChild(cell);
   
    // Delete
    cell = document.createElement('td');
    var img = document.createElement('img');
    img.src = '/images/tools/delete.png';
    img.alt = 'Delete';
    img.title = 'Delete this File';
    img.width = img.height = '12';
    img.style.cursor = 'pointer';
    img.onclick = deleteFile_OnClick;
    img.fileIndex = i;
    cell.appendChild(img);
    row.appendChild(cell);

    tb.appendChild(row);
  }
  
  // Cannot edit/delete links
  currentGroup = null;
  allowLinkEditing(false);
  
  // Navigate to the top of the page
  window.scroll(0,0);
}

function setGroups(){
  setGroupTable(groups, document.getElementById('groupsTable'));
}

function setGroupTable(groups, table){
  // Clear the rows
  var tb = table.tBodies[0];
  while (tb.rows.length > 0){
    tb.deleteRow(0);
  }
  
  var selGroup;

  // Add each of the Groups
  for (var i = 0; i < groups.length; i++){
    var row = document.createElement('tr');
    var cell, img;
    var group = groups[i];
    
    // Set the row's class
    row.className = (group.fldGroupID == currentGroup) ? 'selected' : '';

    // Get the Edit Links Group select
    if (i == 0 && group.fldAttributes != null){
      selGroup = document.getElementById('editLink').group;
      selGroup.options.length = 1;
    }
    
    // Name
    cell = document.createElement('td');
    cell.appendChild(document.createTextNode(group.fldName));
    cell.title = group.fldDescription;
    cell.style.cursor = 'pointer';
    cell.onclick = viewGroup_OnClick;
    row.appendChild(cell);
    
    // Move Up
    cell = document.createElement('td');
    if (i > 0){
      img = document.createElement('img');
      img.src = '/images/tools/up.png';
      img.alt = 'Up';
      img.title = 'Move Up';
      img.width = img.height = '12';
      img.style.cursor = 'pointer';
      img.onclick = moveGroup_OnClick;
      cell.appendChild(img);
    }
    row.appendChild(cell);
    
    // Move Down
    cell = document.createElement('td');
    if (i < groups.length - 1){
      img = document.createElement('img');
      img.src = '/images/tools/down.png';
      img.alt = 'Down';
      img.title = 'Move Down';
      img.width = img.height = '12';
      img.style.cursor = 'pointer';
      img.onclick = moveGroup_OnClick;
      cell.appendChild(img);
    }
    row.appendChild(cell);
     
    // Allow edit if Attributes are given
    if (group.fldAttributes != null){
      cell = document.createElement('td');
      img = document.createElement('img');
      img.src = '/images/tools/edit.png';
      img.alt = 'Edit';
      img.title = 'Edit this Group';
      img.width = img.height = '12';
      img.style.cursor = 'pointer';
      img.onclick = editGroup_OnClick;
      cell.appendChild(img);
      row.appendChild(cell);
    }
     
    // Delete
    cell = document.createElement('td');
    if (group.fldGroupID == currentGroup && (group.fldAttributes == null || groups.length > 1)){
      img = document.createElement('img');
      img.src = '/images/tools/delete.png';
      img.alt = 'Delete';
      img.title = 'Delete this Group';
      img.width = img.height = '12';
      img.style.cursor = 'pointer';
      img.onclick = deleteGroup_OnClick;
      cell.appendChild(img);
    }
    row.appendChild(cell);
    
    // Set the Group ID & add the row
    row.groupIndex = i;
    row.groups = groups;
    tb.appendChild(row);
    
    // Also add the group to the Edit Link form
    if (selGroup){
      selGroup.options[i + 1] = new Option(group.fldName, group.fldGroupID);
    }
  }
}

function setLinks(){
  var table = document.getElementById('links');
  
  // Hide the files container
  document.getElementById('info').style.display = 'none';
  document.getElementById('filesContainer').style.display = 'none';
  document.getElementById('notesContainer').style.display = 'none';
  
  // Show the Links container
  document.getElementById('linksContainer').style.display = 'block';
  
  // Create an array of indexes for the columns
  var cols = new Array();
  for (var i = 0; i < 6; i++){
    cols[i] = new Array();
  }
  for (var i = 0; i < links.length; i++){
    cols[links[i].fldColumn - 1].push(i);
  }
  
  // Get the total rows
  var rows = 0;
  for (var i = 0; i < 6; i++){
    if (cols[i].length >= rows) rows = cols[i].length;
  }
  
  // Get the Table body and clear it
  var tb = table.tBodies[0];
  while (tb.rows.length > 0){
    tb.deleteRow(0);
  }
  
  // Add each of the rows
  for (var j = 0; j < rows; j++){
    var row = document.createElement('tr');
    
    // Add each cell
    for (var i = 0; i < 6; i++){
      var link = links[cols[i][j]];
      var cell = document.createElement('td');
      if (link){
        // Create an anchor
        var a = document.createElement('a');
        a.href = link.fldURL;
        a.appendChild(document.createTextNode(link.fldTitle));
        a.title = link.fldDescription;
        if (link.fldAttributes & 2) a.target = '_blank';
        a.linkIndex = cols[i][j];
        cell.appendChild(a);
      }
      row.appendChild(cell);
    }
    tb.appendChild(row);
  }
  
  // Link Editing
  allowLinkEditing(isOwnGroup(currentGroup));
  
  // Check if this Group ID is in the Public groups
  document.getElementById('saveGroup').style.display = 'none';
  if (loggedIn){
    var sel = document.getElementById('publicGroups');
    for (var i = 0; i < sel.options.length; i++){
      if (sel.options[i].value == currentGroup){
        document.getElementById('saveGroup').style.display = 'block';
        break;
      }
    }
  }
  
  // Navigate to the top of the page
  window.scroll(0,0);
}

function setNotes(){
  var table = document.getElementById('notes');
  
  // Hide the Links container
  document.getElementById('info').style.display = 'none';
  document.getElementById('filesContainer').style.display = 'none';
  document.getElementById('linksContainer').style.display = 'none';
  
  // Show the Files container
  document.getElementById('notesContainer').style.display = 'block';
  
  // Redraw the Groups
  setGroups();
  setSaved();
  
  // Get the Table body and clear it
  var tb = table.tBodies[0];
  while (tb.rows.length > 0){
    tb.deleteRow(0);
  }
  
  // Add each of the rows
  for (var i = 0; i < notes.length; i++){
    var row = document.createElement('tr');
    var cell, img;
    var note = notes[i];
    
    // Note
    cell = document.createElement('td');
    cell.innerHTML = note.fldText.toString().replace(/\r\n/g, '<br />');
    row.appendChild(cell);
     
    // Created
    cell = document.createElement('td');
    cell.appendChild(document.createTextNode(note.fldCreated));
    row.appendChild(cell);
       
    // Modified
    cell = document.createElement('td');
    cell.appendChild(document.createTextNode(note.fldModified));
    row.appendChild(cell);
    
    // Edit
    cell = document.createElement('td');
    var img = document.createElement('img');
    img.src = '/images/tools/edit.png';
    img.alt = 'Edit';
    img.title = 'Edit this Note';
    img.width = img.height = '12';
    img.style.cursor = 'pointer';
    img.onclick = editNote_OnClick;
    img.noteIndex = i;
    cell.appendChild(img);
    row.appendChild(cell);
     
    // Delete
    cell = document.createElement('td');
    var img = document.createElement('img');
    img.src = '/images/tools/delete.png';
    img.alt = 'Delete';
    img.title = 'Delete this Note';
    img.width = img.height = '12';
    img.style.cursor = 'pointer';
    img.onclick = deleteNote_OnClick;
    img.noteIndex = i;
    cell.appendChild(img);
    row.appendChild(cell);

    tb.appendChild(row);
  }
  
  // Cannot edit/delete links
  currentGroup = null;
  allowLinkEditing(false);
  
  // Navigate to the top of the page
  window.scroll(0,0);
}

function setPublic(){
  // Get the Combobox
  var sel = document.getElementById('publicGroups');
        
  // Clear the options
  sel.options.length = 1;
  for (var i = 0; i < pub.length; i++){
    sel.options[i + 1] = new Option(pub[i].fldName, pub[i].fldGroupID);
  }
}

function setSaved(){
  setGroupTable(saved, document.getElementById('savedTable'));
}

function show_OnClick(sender, targetID){
  var target = document.getElementById(targetID);

  // Show or Hide
  if (sender.src.indexOf('plus') > -1){
    sender.src = '/images/tools/minus.png';
    sender.alt = sender.title = 'Hide';
    
    if (target) target.style.display = 'block';
  }else if (sender.src.indexOf('minus') > -1){
    sender.src = '/images/tools/plus.png';
    sender.alt = sender.title = 'Show';

    if (target) target.style.display = 'none';
  }
}


/*=================================
  Form Popups
=================================*/
function formContainer_Hide(obj){
  // Hide the object
  obj.style.display = 'none';
}

function formContainer_Show(obj){
  // Make the container hidden, and then allow it to be rendered
  // This means the size can be calculated
  obj.style.position = 'absolute';
  obj.style.left = '0px';
  obj.style.top = '0px';
  obj.hidden = true;
  obj.style.display = 'block';

  // Get the size of the Window
  var width, height;
  if (window.innerWidth && window.innerHeight){
    width = window.innerWidth;
    height = window.innerHeight;
  }else if (document.documentElement && document.documentElement.clientWidth && document.documentElement.clientHeight){
    width = document.documentElement.clientWidth;
    height = document.documentElement.clientHeight;
  }else if (document.body.clientWidth && document.body.clientHeight){
    width = document.body.clientWidth;
    height = document.body.clientHeight;
  }

  p = {x: width / 2, y: height / 2};
  p.x -= (obj.offsetWidth / 2);
  p.y -= (obj.offsetHeight / 2);

  // Add the Scroll position
  p.x += document.documentElement.scrollLeft;
  p.y += document.documentElement.scrollTop;
  
  // Set the location of the popup, and show it
  obj.style.left = p.x + 'px';
  obj.style.top = p.y + 'px';
  obj.hidden = false;
}
