var grid_data;
var grid_header;

function clientNFO()
{
  document.getElementById("example").innerHTML=
  "<p>Browser CodeName: " + navigator.appCodeName + "</p>"
  + "<p>Browser Name: " + navigator.appName + "</p>"
  + "<p>Browser Version: " + navigator.appVersion + "</p>"
  + "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>"
  + "<p>Platform: " + navigator.platform + "</p>"
  + "<p>User-agent header: " + navigator.userAgent + "</p>";
}

function InitVerbosity()
{
  var cell;
  
  /* Process Page Specific code */
  if (typeof page != "undefined") 
  {
    if (page == "login")
      document.getElementById('email').focus();
    else if (page == "register")
      document.getElementById('email1').focus();
    else if (page == "forgot")
      document.getElementById('email').focus();
    else if (page == "contactus")
      document.getElementById('department').focus();
    else if (page == "step1")
      document.getElementById('email_old').focus();
    else if (page == "step2")
    {
      _SELECT('period', _GET('period'));
      document.getElementById('publicname').value = _GET('publicname');
      document.getElementById('pp').checked = true;
      if (_GET('method')=="cc")
        document.getElementById('cc').checked = true;

      document.getElementById('publicname').focus();
    }
    else if (page == "step3")
    {
      _SELECT('country', _GET('country'));
      document.getElementById('addr1').value = _GET('addr1');
      document.getElementById('addr2').value = _GET('addr2');
      document.getElementById('city').value = _GET('city');
      document.getElementById('state').value = _GET('state');
      document.getElementById('zipcode').value = _GET('zipcode');
      document.getElementById('cardname').value = _GET('cardname');
      document.getElementById('cardnumber').value = _GET('cardnumber');
      document.getElementById('cardcode').value = _GET('cardcode');
      _SELECT('cardexpmonth', _GET('cardexpmonth'));
      _SELECT('cardexpyear', _GET('cardexpyear'));
      document.getElementById('addr1').focus();
    }
    else if (page == "step4")
    {
      cell = document.getElementById('cancelpurchase');
      cell.innerHTML="Leave Store";
    }
  }

  grid_mode = _GET('cmd');
  if (grid_mode)
  {
    grid_mode="cmd=" + grid_mode;
    AsyncLoadGrid(null, "");
  }

  if (grid_mode == "cmd=SERVER-STATUS")
  {
    ResetTimer();
  }
}

function submitform(name)
{
  var f = document.forms[name];
  if (f)
  {
    f.submit();
  }
}

function SelectRadio(btnid)
{
  document.getElementById(btnid).checked = true;
}

function grid_RPP_Changed()
{
  AsyncLoadGrid(null, "");
}

// # for number, prev,next,1,999999
function grid_GotoPage(pagenumber)
{
  param = "&p=" + pagenumber;
  AsyncLoadGrid(null, param);
}

function grid_PageManual(obj)
{
  if (document.getElementById('grid_page'))
  {
    grid_GotoPage(document.getElementById('grid_page').value - 1);
  }
}

function grid_SearchButton()
{
  if (document.getElementById('grid_search'))
  {
    param = "&data_search=" + document.getElementById('grid_search').value;
    AsyncLoadGrid(null, param);
  }
}

function GridRowClicked(rowid)
{
  Redirect("/src/run.php?row=" + rowid + "&" + grid_mode);
}

function GridHeaderClicked(colid)
{
  param = "&colid=" + colid;
  AsyncLoadGrid(null, param);
}

function SubmitUsingGridSelection(formid, action)
{
  if(!document.getElementById) return; //Prevent older browsers from getting any further.
  if(!document.createElement) return; //Prevent non W3C Dom method.

  var xml = "<xml>";
  if (typeof grid_data != "undefined") 
  {
    for (i=0; i<grid_data.length; i++)
    {
      if (grid_data[i].checked)
        xml += "<sel>" + grid_data[i].id + "</sel>";
    }
  }
  xml += "</xml>";
  var field_area = document.getElementById(formid);
  var input = document.createElement("input");
  input.id = "cmd";
  input.name = "cmd";
  input.type = "hidden";
  input.value = action;
  field_area.appendChild(input);

  input = document.createElement("input");
  input.id = "xml";
  input.name = "xml";
  input.type = "hidden";
  input.value = xml;
  field_area.appendChild(input);
  
  submitform(formid);
}

function ToggleSelectCheck(rowid)
{
  var cellid = "sel-" + rowid;
  grid_data[rowid].checked = !grid_data[rowid].checked;
  var cell = document.getElementById(cellid);
  if (cell)
  {
    cell.checked = grid_data[rowid].checked;
  }
}

function GridSelectPage()
{
  checked = 0;
  for (i=0; i<grid_data.length; i++)
  {
    if (i==0)
      checked = !grid_data[i].checked;

    grid_data[i].checked = checked;
    selid = "sel-" + i;
    cell = document.getElementById(selid);
    if (cell)
      cell.checked = checked;
  } 
}

function ProcessTimeEventFn(xmldata)
{
  if (xmldata == null)
  {
    param = grid_mode + "&ajax=1&sid=" + Math.random();
    //param = "cmd=AUTO-STATUS-SIMPLE&ajax=1&sid=" + Math.random();
    ajaxRequest_Auto(param, ProcessTimeEventFn);
  }
  else
  { 
    AsyncLoadGrid(xmldata, "");
    return;


    var x = xmldata.getElementsByTagName("simple-status");
    if (x)
    {
      online = x[0].getAttribute('online');
      if (online == "OFFLINE")
        color = "#FF0000";
      else
        color = "#00FF00";

      txt = "<table width='100%'>" +
      "<tr><th align='center' scope='row'>Status</th><td align='center' bgcolor='" + color +"'>" + online + "</td></tr>" +
      "</table>";

      cell = document.getElementById("simple-status");
      if (cell)
      {
        cell.innerHTML=txt;
      }
    }
  }
}

function AsyncLoadGrid(xmldata, postparams)
{
  if (xmldata == null)
  {
    if (document.getElementById('grid_rpp'))
      postparams += "&rpp=" + document.getElementById('grid_rpp').value;
    
    param = grid_mode + postparams + "&ajax=1&sid=" + Math.random();
    ajaxRequest_Single(param, AsyncLoadGrid);
  }
  else
  {
    if (xmldata.firstChild==null || xmldata.firstChild.firstChild==null)
      return;

    var gridinst = xmldata.getElementsByTagName("grid");
    if (gridinst.length)
    {
      for (var i=0; i<gridinst.length; i++)
      {
        UpdateDatagridFromXML( gridinst[i] );
      }
    }
  }
}

function UpdateDatagridFromXML(xmldata)
{
  var grid_page = 0;
  var grid_pages = 1;
  var grid_rows = 0;
  var grid_sortcol = -1;
  var grid_sortdir = "";
  var grid_search = "";
  var grid_multi = 0;
  var grid_name = xmldata.getAttribute('name');

  grid_data = new Array();
  grid_header = new Array();

  var x = xmldata.getElementsByTagName("global");
  if (x.length)
  {
    grid_multi = x[0].getAttribute('multi');
    grid_rows = x[0].getAttribute('rows');
    grid_pages = x[0].getAttribute('pages');
    grid_page = x[0].getAttribute('page');
    grid_sortcol = x[0].getAttribute('sortcol');
    grid_sortdir = x[0].getAttribute('sortdir');
    grid_search = x[0].getAttribute('search');
    grid_page++;
  }

  x = xmldata.getElementsByTagName("hdr");
  for (var i=0; i<x.length; i++)
  {
    var obj = new Object;
    var attr = x[i].getAttribute('width');

    obj.width = "";
    if (attr)
      obj.width = "width='" + attr + "'";

    obj.name = x[i].firstChild.nodeValue;
    obj.width = ""; // width='8'
    obj.colname = x[i].getAttribute('colname');
    grid_header.push(obj);
  }

  x = xmldata.getElementsByTagName("row");
  for (i=0; i<x.length; i++)
  {
    obj = new Object;
    obj.row = new Array();
    obj.id = x[i].getAttribute('id');
    obj.checked = x[i].getAttribute('checked') ? 1 : 0;

    for (var t=0; t<grid_header.length; t++)
    {
      var data = "";
      var datatag = x[i].getElementsByTagName("data");
      var dt = datatag[t];
      if (dt && dt.firstChild && dt.firstChild.nodeValue)
        data = dt.firstChild.nodeValue;

      obj.row.push(data);
    }

    grid_data.push(obj);
  }

  txt = "<table width='100%' class='linktable'><tr>";

  if (grid_multi)
    txt += "<th class='linkheader' onClick='GridSelectPage()'>Select</th>";

  for (i=0; i<grid_header.length; i++)
  {
    arrowdir="";
    if (grid_sortcol == i)
    {
      if (grid_sortdir == 'asc')
        arrowdir="&nbsp;<img src='../images/sort-down.gif' width='9' height='9'>";
      else
        arrowdir="&nbsp;<img src='../images/sort-up.gif' width='9' height='9'>";
    }
    txt += "<th " + grid_header[i].width + " class='linkheader' onClick='GridHeaderClicked(" + i + ")'> " + grid_header[i].name + " " + arrowdir + " </th>";
  }
  txt += "</tr>";
  for (i=0; i<grid_data.length; i++)
  {
    if (i & 1)
      altclass = "linkrow1";
    else
      altclass = "linkrow0";

    idstr = grid_data[i].id; // This is the value that identifies this row
    newrow = "<tr class='" + altclass + "' id=\"row" + i + "\" onMouseOver='checktoggle_over(this, 0)' " +
             "onMouseOut=\"checktoggle_over(this, '" + altclass + "')\" >";

    txt += newrow;
    if (grid_multi)
    {
      checked = grid_data[i].checked ? " checked='checked' " : "";
      txt += "<td align='center' onClick=\"ToggleSelectCheck(" + i + ")\" >" +
      "<input type='checkbox' name='sel-" + i + "' id='sel-" + i + "' value='on'" + checked + "/> </td>";
    }

    for (t=0; t<grid_header.length; t++)
    {
      txt += "<td onClick=\"GridRowClicked('" + idstr + "')\" >" + grid_data[i].row[t] + "</td>";
    }
    txt += "</tr>";
  }

  txt += "<tr align='right'><td colspan='" + grid_header.length + "'>" +
  "<table border='0' cellspacing='3' cellpadding='3' class='normal-text'>"+
  "<tr><td>Page " + grid_page + " of " + grid_pages + "</td><td class='buttonlinks'>" +
  "<a href='JavaScript:void(0);' onclick='grid_GotoPage(0)'><img src='../images/page-first.png' width='16' height='16'></a>"+
  "<a href='JavaScript:void(0);' onclick='grid_GotoPage(\"prev\")'><img src='../images/page-prev.png' width='16' height='16'></a>"+
  "<a href='JavaScript:void(0);' onclick='grid_GotoPage(\"next\")'><img src='../images/page-next.png' width='16' height='16'></a>"+
  "<a href='JavaScript:void(0);' onclick='grid_GotoPage(999999)'><img src='../images/page-last.png' width='16' height='16'></a></td>"+
  "<td>Go to page "+
  "<input name='grid_page' type='text' class='inputbox' id='grid_page' size='3' maxlength='6' value='' onchange='grid_PageManual(this)'/>"+
  "</td></tr></table>"+
  "</td></tr></table>";

  cell = document.getElementById(grid_name);
  cell.innerHTML=txt;

  txt = "";
  if (grid_search != "")
    txt += "<br>Search results for: " + grid_search + "<br />";

  if (grid_rows==0)
    txt += "No entries found.";
  else if (grid_rows==1)
    txt += "1 entry found.";
  else
    txt += grid_rows + " entries found.";

  cell = document.getElementById("rows_found");
  cell.innerHTML=txt;
}

function checktoggle_over(obj,classname) 
{
  if(document.getElementById) {
    var cell = document.getElementById(obj.id);  
    if (classname == 0)
      cell.className = 'dyn_hilte_row';
    else
      cell.className = classname;
  }
}

function ajaxObject()
{
  var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]; //activeX versions to check for in IE
  
  if (window.ActiveXObject)
  { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)  
    for (var i=0; i<activexmodes.length; i++)
    {
      try 
      {
        return new ActiveXObject(activexmodes[i]);
      }
      catch(e) { //suppress error
      }
    }
  }
  else if (window.XMLHttpRequest) // if Mozilla, Safari etc
    return new XMLHttpRequest();
  else
    return false;
}

function ResetTimer()
{
  t=setTimeout("ProcessTimeEventFn()", 5000);
}

function ajaxBusy(isbusy, error)
{
  var imgobj = document.getElementById('ajaxbusy');
  if (imgobj)
  {
    if (isbusy)
      imgobj.className = "";
    else
      imgobj.className = "invisible";
  }
}

function ajaxRequest_Single(parameters, callback)
{
  var ajax = new ajaxObject();
  if (ajax)
  {
    if (callback != null)
    {      
      if (ajax.overrideMimeType)
        ajax.overrideMimeType('text/xml'); 
    
      ajax.onreadystatechange=function()
      {
        if (ajax.readyState==4)
        {
          if (ajax.status==200 || window.location.href.indexOf("http")==-1) // or if offline
          {
            var   xmldata = ajax.responseXML; //retrieve result as an XML object
            var   err = xmldata.getElementsByTagName("error");
            if (err.length)
            {
              ajaxBusy(false,true);
            //document.getElementById("busy").innerHTML="Error";
            }
            else
            {
              ajaxBusy(false,false);
              callback(xmldata, null);
            }
          }
          else
          {
            ajaxBusy(false,true);
          //document.getElementById("busy").innerHTML="Error";
          }
        }
      }
    }

    ajaxBusy(true,false);
    ajax.open("POST", "/src/run.php", true);
    ajax.setRequestHeader('User-Agent','XMLHTTP/1.0');
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajax.send(encodeURI(parameters));
  }
}

function ajaxRequest_Auto(parameters, callback)
{
  var ajax = new ajaxObject();
  if (ajax)
  {
    if (callback != null)
    {
      ajaxBusy(true,false);
      //document.getElementById("busy").innerHTML="Busy";
      
      if (ajax.overrideMimeType)
        ajax.overrideMimeType('text/xml'); 

      ajax.onreadystatechange=function()
      {
        if (ajax.readyState==4)
        {
          ajaxBusy(false,false);
          //document.getElementById("busy").innerHTML="Ok";

          if (ajax.status==200 || window.location.href.indexOf("http")==-1) // or if offline
          {
            var   xmldata = ajax.responseXML; //retrieve result as an XML object
            var   err = xmldata.getElementsByTagName("error");
            if (err.length)
            {
            //document.getElementById("first").innerHTML=err[0].childNodes[0].nodeValue;
            //document.getElementById("second").innerHTML="";
            }
            else
            {
              //setCookie('sqlip',document.getElementById("sqlip").value);
              callback(xmldata, null);
            }
          }
          else
          {
          //document.getElementById("first").innerHTML="Web server offline";
          //document.getElementById("second").innerHTML="";
          }
      
          ResetTimer();
        }
      }
    }

    ajax.open("POST", "/src/run.php", true);
    ajax.setRequestHeader('User-Agent','XMLHTTP/1.0');
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajax.send(encodeURI(parameters));
  }
}

function Redirect(url)
{
  window.location.assign(url);
}

function _GET( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  var rv = "";  
  if( results != null )
    rv = unescape(results[1]);

  return rv;
}

function _SELECT(obj, name)
{
  var droplist = document.getElementById(obj);
  for (var i=0; i<droplist.length; i++)
  {
    if (droplist.options[i].value == name)
    {
      droplist.options[i].selected = true;
      return;
    }
  }
}
