
function getArgs()
{
  var args = new Object();
  var query = location.search.substring(1);  // Get query string.
  var pairs = query.split("&");                     // Break at comma.
  
  for(var i = 0; i < pairs.length; i++)
  {
	  var pos = pairs[i].indexOf('=');       // Look for "name=value".
	  if (pos == -1) continue;               // If not found, skip.
	  var argname = pairs[i].substring(0,pos);  // Extract the name.
	  var value = pairs[i].substring(pos+1); // Extract the value.
	  args[argname] = unescape(value);          // Store as a property.
  }
  return args;                               // Return the object.
}

function htmlEncode(str)
{
  if (str == null)
    str = "";
  else if (str != "")
  {
    str = str.replace(/&/g, "&amp;");
    str = str.replace(/</g, "&lt;");
    str = str.replace(/>/g, "&gt;");
    str = str.replace(/"/g, "&quot;");
  }
  return str;
} 

function replaceText(sText, sOld, sNew)
{
  if (sText != null && sText != "" && sText.indexOf(sOld) >= 0)
    sText = sText.split(sOld).join(sNew);

  return sText;
}

function IncludeProjectList()
{
  // to stop the project list file from being cached, add a random number to the end of the file name
  var ver = Math.floor(Math.random() * 1000000 + 1);
  document.write("<script type=\"text/javascript\" charset=\"ISO-8859-1\" src=\"XI_ProjectList.js?ver=" + ver + "\"></script>");
}

var sectionStates = new Array();
  
function toggleSection(sImg, sSection)
{
  var oImg = getElById(sImg);
  var oSection = getElById(sSection);

  if (oSection.style.display == "none")
  {
    sectionStates[sSection] = 1;
    oSection.style.display = "";
    oImg.src = "Graphics/rollup_collapse.png";
    oImg.title = "Collapse";
    
    if (sSection == "featuresSection")
    {
      // poke the relative control
      overrideStylesDiv.style.display = "none";
      overrideStylesDiv.style.display = "";
    }
  }
  else
  {
    sectionStates[sSection] = 0;
    oSection.style.display = "none";
    oImg.src = "Graphics/rollup_expand.png";
    oImg.title = "Expand";
  }
}

function HideButtons(names)
{
  var oCell;

  for (var index = 0; index < names.length; index++)
  {
    if ((oCell = document.getElementById(names[index])) != null)
      oCell.style.display = "none";
  }
}

function HasSiteAdminAccess()
{
  var sProjects = GetCookieValue("projects", "");
  return (sProjects != null && sProjects != "" && sProjects.substr(0, 1) == "0")
}

function HasProjectAdminAccess(sProjectCode)
{
  var sProjects = GetCookieValue("projects", "");
  var bValidated = false;
  
  if (sProjects != null && sProjects != "")
  {
    var bits = sProjects.split(",");
    var mode = parseInt(bits[0], 10);

    if (mode == 0 || mode == 1)
      bValidated = true;
    else
    {
      // look for this project in the list of projects
      for (index = 1; !bValidated && index < bits.length; index++)
      {
        if (sProjectCode == bits[index].substr(1))
          bValidated = ((parseInt(bits[index].substr(0, 1), 10) & 2) == 2);
      }
    }
  }
  return bValidated;
}

function HasProjectViewAccess(sProjectCode)
{
  var sProjects = GetCookieValue("projects", "");
  var bValidated = false;
  
  if (sProjects != null && sProjects != "")
  {
    var bits = sProjects.split(",");
    var mode = parseInt(bits[0], 10);

    if (mode < 3)
      bValidated = true;
    else
    {
      // look for this project in the list of projects
      for (index = 1; !bValidated && index < bits.length; index++)
      {
        if (sProjectCode == bits[index].substr(1))
          bValidated = ((parseInt(bits[index].substr(0, 1), 10) & 1) == 1);
      }
    }
  }
  return bValidated;
}

function GetCookieValue(sCookieName, sDefaultValue)
{
  var sValue = sDefaultValue;
  
  if (document.cookie != "")
  {
    var bits = document.cookie.split(";");
    for (var i = 0; i < bits.length; i++)
    {
      var nPos = bits[i].indexOf("=");
      var sName = (nPos > 0) ? trimString(bits[i].substr(0, nPos)) : "";

      if (sName == sCookieName)
      {
        sValue = bits[i].substr(nPos + 1);
        break;
      }
    }
  }
  return sValue;
}

function trimString(str)
{
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--)
	{
		if (/\S/.test(str.charAt(i)))
		{
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}

function StopEvent(e)
{
  if ((typeof e.stopPropagation) != "undefined")
    e.stopPropagation();

  if ((typeof e. preventDefault) != "undefined")
    e.preventDefault();

  if ((typeof e.cancelBubble) != "undefined")
    e.cancelBubble = true;

  if ((typeof e.returnValue) != "undefined")
    e.returnValue = false;
}

function getLeftPos(element)
{
  var left = 0;

  if ((typeof element.style.pixelLeft) != "undefined")
    left = element.style.pixelLeft;
  else if ((typeof element.style.left) != "undefined" && element.style.left != '')
    left = parseInt(element.style.left);
  return left;
}

function getTopPos(element)
{
  var top = 0;

  if ((typeof element.style.pixelTop) != "undefined")
    top = element.style.pixelTop;
  else if ((typeof element.style.top) != "undefined" && element.style.top != '')
    top = parseInt(element.style.top);
  return top;
}

function getAbsolutePos(element, type)
{
  var pos = 0;

  while (element != null && element.tagName != 'BODY')
  {
    pos += (type == "offsetTop") ? element.offsetTop : element.offsetLeft;
    element = element.offsetParent;
  }
  return pos;
}

function getAbsolutePos2(element, type, divNames)
{
  var pos = 0;

  while (element != null && element.tagName != 'BODY' && (element.id == '' || (typeof divNames[element.id]) == "undefined"))
  {
    // alert(element.id + ", " + element.tagName + ", " + ((type == "offsetTop") ? element.offsetTop : element.offsetLeft));
    pos += (type == "offsetTop") ? element.offsetTop : element.offsetLeft;
    element = element.offsetParent;
  }
  return pos;
}

function getElById(idVal)
{
  var obj = null;
  
  if (document.getElementById)
    obj = document.getElementById(idVal);
  else if (document.all)
    obj = document.all[idVal];
    
  // if (obj == null)
  //   alert("Problem getting element by id: " + idVal);
    
  return obj;
}

function RemoveElement(idVal) 
{
  var el = document.getElementById(idVal);
  if (el != null && el.parentNode != null)
    el.parentNode.removeChild(el);
}

function MakeCSVSafe(sText)
{
  if (sText.indexOf("\"") >= 0)
    sText = "\"" + replaceText(sText, "\"", "\"\"") + "\"";
  else if (sText.indexOf(",") >= 0 || sText.indexOf(";") >= 0)
    sText = "\"" + sText + "\"";
  else if (sText.length > 0 && (sText.substr(0, 1) == " " || sText.substr(sText.length - 1, 1) == " "))
    sText = "\"" + sText + "\"";  

  return sText;
}

function CreateCombobox(newNode, sName, sClassName)
{
  var oCombo = (newNode.document) ? newNode.document.createElement("SELECT") : newNode.ownerDocument.createElement("SELECT");
  
  oCombo.id = sName;    
  oCombo.name = sName;    
  oCombo.className = sClassName;
  oCombo.size = 1; 
  
  newNode.appendChild(oCombo);
  return oCombo;
}

function AddOption(newNode, sValue, sText, bSelected)
{
  var oOption = (newNode.document) ? newNode.document.createElement("OPTION") : newNode.ownerDocument.createElement("OPTION");
  
  oOption.value = sValue;    
  oOption.innerHTML = htmlEncode(sText);
  oOption.selected = bSelected;    
  
  newNode.appendChild(oOption);
}

function replaceControl(control, newNode)
{
  var nextSibling = control.nextSibling;
  var parentNode = control.parentNode;
  var cArgs = arguments.length;
  var index;
  
  // hope this works
  for(index=2;index<cArgs;index+=2)
    newNode.setAttribute(arguments[index], arguments[index + 1]);

  // now do the replacement  
  parentNode.removeChild(control);
  
  if (nextSibling != null)
    parentNode.insertBefore(newNode, nextSibling);
  else
    parentNode.appendChild(newNode);
}

function insertNode(newNode, insertAtObj, sWhere)
{
  if (insertAtObj == null)
  {
	  insertAtObj = getElById("domRoot");
	  if ((typeof sWhere) == "undefined")
	    sWhere = "beforeEnd";
  }
  else if ((typeof sWhere) == "undefined")
    sWhere = "afterEnd";

  if (insertAtObj != null)
  {
	  if (sWhere == "beforeBegin")
		  insertAtObj.parentNode.insertBefore(newNode, insertAtObj);
	  else if (sWhere == "beforeEnd")
		  insertAtObj.appendChild(newNode);
	  else if (sWhere == "afterBegin")
		  insertAtObj.insertBefore(newNode, insertAtObj.firstChild);
	  else if (sWhere == "afterEnd")
	  {
		  if (insertAtObj.nextSibling != null)
        insertAtObj.parentNode.insertBefore(newNode, insertAtObj.nextSibling);
		  else
		    insertAtObj.parentNode.appendChild(newNode);
	  }
	}
  return (insertAtObj != null);
}

function EnableControls(bDisable)
{
  var index;
  
  for (index=1;index<arguments.length;index++)
    arguments[index].disabled = bDisable;
}

var g_ie6Request = null;

function MakeAjaxCall(url, bAsynchronous)
{
  var http_request;

  if (window.XMLHttpRequest)
    http_request = new XMLHttpRequest(); 
  else if (window.ActiveXObject)
  {
    http_request = new ActiveXObject("Microsoft.XMLHTTP");
    g_ie6Request = http_request;
  }
  else
    http_request = null;
    
  if (http_request != null)
  {
    if (url.indexOf("\n") >= 0)
      url = replaceText(url, "\n", "%0A");
    
    if (url.indexOf("#") >= 0)
      url = replaceText(url, "#", "%23");
      
    http_request.open( "GET", url, ((typeof bAsynchronous) == "undefined") ? true : bAsynchronous);
    http_request.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" ); // Read past any cached version
    http_request.onreadystatechange = function()
    {
      var request = (g_ie6Request != null) ? g_ie6Request : this;
      if (request.readyState == 4)
      {
        if (request.status != 200)
          alert("An error occured communicating with the server.");
        else if (request.responseText != "")
        {
          if (request.responseText.charAt(0) != '<')
            eval(request.responseText);
          else
            alert("The server has returned an unexpected response:\n" + request.responseText);
        }
        
        g_ie6Request = null;
      }
    };
    http_request.send(null);
  }
}

function PostDataToServer(url, sData)
{
  var http_request;

  if (window.XMLHttpRequest)
    http_request = new XMLHttpRequest(); 
  else if (window.ActiveXObject)
  {
    http_request = new ActiveXObject("Microsoft.XMLHTTP");
    g_ie6Request = http_request;
  }
  else
    http_request = null;
    
  if (http_request != null)
  {
    if (sData.length > 2000 && !IsFirefox())
    {
      http_request.open( "POST", url, true );
      http_request.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" ); // Read past any cached version
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", sData.length);
      http_request.setRequestHeader("Connection", "close");    
    }
    else
    {
      http_request.open("GET", url + "?" + sData, true);
      http_request.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" ); // Read past any cached version
      sData = null;
    }
    
    http_request.onreadystatechange = function ()
    {
      var request = (g_ie6Request != null) ? g_ie6Request : this;
      if ( request.readyState == 4 )
      {
        if (request.status != 200)
          alert("An error occured communicating with the server.");
        else if (request.responseText != "")
        {
          if (request.responseText.charAt(0) != '<')
            eval(request.responseText);
          else
            alert("The server has returned an unexpected response:\n" + request.responseText);
        }
        
        g_ie6Request = null;
      }
    };
    
    http_request.send(sData);
  }
}

var reSignedFloat = /^[-+]?[0-9]+(\.[0-9]+)?$/;
var reSignedInt = /^[-+]?[0-9]+$/;

function ValidFloat(sFloat)
{
  return (sFloat != "" && reSignedFloat.test(sFloat));
}

function readInt(obj, sProperty, sPropertyDescription, sValue, sDefault, bForceDefault)
{
  var bSuccess = true;

  if (bForceDefault || sValue == "")
    obj[sProperty] = sDefault;
  else
  {
    sValue = sValue.replace(/\,/g, ""); // remove any commas
    sValue = sValue.replace(/\s/g, ""); // remove any spaces
    
    if (reSignedInt.test(sValue))
      obj[sProperty] = sValue;
    else if (sPropertyDescription != null)
    {
      alert("Please enter a valid number for the " + sPropertyDescription);
      bSuccess = false;
    }
    else
      obj[sProperty] = sDefault;
  }
  
  return bSuccess;
}

function readFloat(obj, sProperty, sPropertyDescription, sValue, sDefault, bForceDefault)
{
  var bSuccess = true;

  if (bForceDefault || sValue == "")
    obj[sProperty] = sDefault;
  else
  {
    sValue = sValue.replace(/\,/g, ""); // remove any commas
    sValue = sValue.replace(/\s/g, ""); // remove any spaces
    
    if (reSignedFloat.test(sValue))
      obj[sProperty] = sValue;
    else if (sPropertyDescription != null)
    {
      alert("Please enter a valid number for the " + sPropertyDescription);
      bSuccess = false;
    }
    else
      obj[sProperty] = sDefault;
  }
  
  return bSuccess;
}

function numberToString(num, precision)
{
  var truncNum;
  if ((typeof num.toFixed) != "undefined")
    truncNum = num.toFixed(precision);
  else
  {
    precision += 2;
    truncNum = num.toString();
    if (truncNum.length > precision && truncNum.indexOf(".") < precision)
      truncNum = truncNum.substring(0, precision);
  }

  return truncNum;
}

// adds the item to the array only if the array doesn't already contain this item
function addItemToArray(vArray, item)
{
  var index = vArray.length - 1;

  while (index >= 0 && item != vArray[index])
    index--;

  if (index < 0)
    vArray[vArray.length] = item;
}

function isItemInArray(vArray, item)
{
  var index = vArray.length - 1;

  while (index >= 0 && item != vArray[index])
    index--;

  return (index >= 0);
}

function isStringInArray(vArray, item)
{
  var index = vArray.length - 1;

  item = item.toLowerCase()
  while (index >= 0 && item != vArray[index].toLowerCase())
    index--;

  return index;
}

function ToString(obj)
{
  var sText = "";
  for (var sProperty in obj)
  {
    if (sText == "")
      sText = sProperty + ": " + obj[sProperty];
    else
      sText = sText + ", " + sProperty + ": " + obj[sProperty];
  }
  return sText;
}

function validateStartupValues()
{
  if (!HasSiteAdminAccess())
    window.location = "XI_Unauthorised.htm";
}

function IsFirefox()
{
  return (document.getBoxObjectFor != null || window.mozInnerScreenX != null);
}
