var frms = 0;
var rform = 'advanced-vvls';
var vfile='';
var imgBaseUrl='/dtic/images/';
var srcp='v:sources';
var active='';

var state = '';
var sources = new Object();
sources["dod-web-sites"]="category";
sources["service-orgs"]="dod-web-sites";
sources["army"]="service-orgs";
sources["navy"]="service-orgs";
sources["airforce"]="service-orgs";
sources["marines"]="service-orgs";
sources["coastguard"]="service-orgs";
sources["jcs"]="service-orgs";
sources["agencies"]="dod-web-sites";
sources["dod-st"]="category";
sources["dodlabs"]="dod-st";
sources["otherdod"]="dod-st";
sources["dtic"]="dod-st";
sources["dtic-st"]="category";
sources["tech-reports"]="dtic-st";
sources["ultech-reports"]="dtic-st";
sources["rs"]="dtic-st";
sources["ird"]="dtic-st";
sources["tems"]="dtic-st";
sources["dstp"]="dtic-st";
sources["ihst"]="dtic-st";
sources["search-tools"]="category";
sources["corporate-source"]="search-tools";
sources["thesaurus"]="search-tools";
sources["jacp"]="category";
sources["aulimp"]="jacp";
sources["aulimp2"]="jacp";
sources["ndia"]="jacp";
sources["scampi"]="jacp";
sources["scampi2"]="jacp";
sources["research"]="category";
sources["brd"]="research";
sources["gtkb"]="research";
sources["rrto"]="research";
sources["recm"]="research";
sources["egov"]="research";
sources["budget-info"]="category";
sources["rdds"]="budget-info";
sources["cbd"]="budget-info";
sources["egov"]="budget-info";
sources["standards"]="category";
sources["ulmctl"]="standards";
sources["mctl"]="standards";
sources["dod-issuances"]="standards";
sources["des"]="standards";
sources["discg"]="standards";

function myescape(str) {
  if (window.encodeURIComponent) return encodeURIComponent(str);
  else return escape(str);
}

function myunescape(str) {
  if (window.decodeURIComponent) {
    try {
      return decodeURIComponent(str);
    }
    catch(e) {
      return str;
    }
  } else {
    return unescape(str);
  }
}

function Parse_string() {
  var str = "";
  var i = 0;
  if (this.multiple) {
    for(var i; i < this.params.length; i += 2) {
      if (i) str += this.d1;
      str += myescape(this.params[i]) + this.d2 + myescape(this.params[i+1]);
    }
  } else {
    for (name in this.params) {
      if (i++) str += this.d1;
      str += myescape(name) + this.d2 +
             myescape(this.params[name]);
    }
  }
  return str;
}

function Parse_get(name) {
  return this.params[name];
}

function Parse_set(name, value) {
  if (! value) delete this.params[name];
  else this.params[name] = value;
}

function Parse(str, d1, d2, multiple) {
  this.string = Parse_string;
  this.get = Parse_get;
  this.set = Parse_set;
  this.d1 = d1;
  this.d2 = d2;
  this.multiple = multiple;
  if (multiple) {
    this.params = new Array();
  } else {
    this.params = new Object();
  }
  if (! str) return;
  var pairs = str.split(d1);
  for(var i = 0; i < pairs.length; i++) {
    var pos = pairs[i].indexOf(d2);
    var name; var value; var uname; var uvalue;
    if (pairs[i].length == 0) {
      continue;
    } else if (pos == -1) {
      name = pairs[i];
      value = "";
    } else {
       name = pairs[i].substring(0,pos);
       value = pairs[i].substring(pos+1);
    }
    uname = myunescape(name);
    uvalue = myunescape(value);
    if (multiple) {
      this.params[2*i] = uname;
      this.params[2*i+1] = uvalue;
    } else {
      this.params[uname] = uvalue;
    }
  }
}

function parseqs(link, unique) {
  return new Parse(link.search.substring(1), "&", "=", ! unique);
}
var cgi = parseqs(location, 1);
var cookies;
function parsecookies() {
  cookies = new Parse(document.cookie, "; ", "=");
}
parsecookies();

function getElt(id) {
  return document.getElementById ? document.getElementById(id) :
           (document.all ? document.all[id] : 0);
}

function toggle(id, show) {
  var elt = getElt(id);
  if (! elt) return;
  if (show > 0 || (! show && elt.style.display == 'none')) {
    elt.style.display = '';
    toggled = displayed = id;
  } else {
    elt.style.display = 'none';
    toggled = displayed = 0;
  }
}

function togimg(id, show){
  var sw = getElt(id);
  if (!sw) return;
  if (show < 0 || (! show && sw.className == 'sopen')) {
    sw.className = 'sclosed';
  } else {
    sw.className = 'sopen';
  }
}


var sel_cmax = 5000;
var sel_crname = "vivisimo-sel-";
var sel_cname = sel_crname + vfile;
var sel_docs = cookies.get(sel_cname);
var sel_adocs = new Object();
var sel_count = 0;
var sel_num_here = 0;

function sel_add(form) {
  var msg = 'You need to select some results before exporting them!';
  parsecookies();
  var ids = cookies.get(sel_cname);
  if (! ids) {
    alert(msg);
    return false;
  }
  var idsa = ids.split("|");
  var idss = "";
  for (i = 0; i < idsa.length; i++) {
    if (idsa[i].search(/^[\d\.]+$/) >= 0) {
      idss += "Ndoc" + idsa[i] + " ";
    } else {
      idss += idsa[i] + " ";
    }
  }
  if (idss.search(/^ *$/) >= 0) {
    alert(msg);
    return false;
  }
  form.ids.value = idss;
  return true;
}

function sel_check(id, sel, nocount) {
  if (! sel_adocs[id]) {
    sel_adocs[id] = 1;
    sel_num_here++;
  }
  var inp = getElt('inp-'+id);
  if (inp &&
      (sel ||
       (sel_docs && sel_docs.lastIndexOf('|' + id + '|') >= 0)))
  {
    if (sel < 0) {
      inp.checked = 0;
      if (! nocount) sel_count += -1;
    } else {
      inp.checked = 1;
      if (! nocount) sel_count++;
    }
  }
  if (! nocount) sel_all_check();
}

function sel_all_check() {
  var inpt = getElt('sel-all-top');
  var inpb = getElt('sel-all-bottom');
  if (inpt) inpt.checked = (sel_count == sel_num_here);
  if (inpb) inpb.checked = (sel_count == sel_num_here);
}

function sel_all(sel) {
  for (n in sel_adocs) {
    if (sel_doc(n, sel) >= 0) {
      sel_check(n, sel ? 1 : -1, 1);
    } else {
      break;
    }
  }
}

function sel_cmax_check() {
  if (document.cookie.length < sel_cmax) return 0;
  parsecookies();
  for (c in cookies.params) {
    if (c != sel_cname && c.lastIndexOf(sel_crname) == 0) {
      document.cookie = c + "=;" + " expires=Thu, 01-Jan-1970 00:00:01 GMT";
      return sel_cmax_check();
    }
  }
  return -1;
}

function sel_num(sids) {
  var ids = sids ? sids : cookies.get(sel_cname);
  if (! ids) return 0;
  var idsa = ids.split('|');
  return idsa.length - 2;
}

function sel_doc(id, add) {
  parsecookies();
  var ids = cookies.get(sel_cname);

  if (add && sel_cmax_check() < 0) {
    alert("Too many results selected!");
    return -1;
  }
  if (! add && ids) {
    ids = ids.replace('\|' + id + '\|', '|');
    sel_count += -1;
  } else if (! ids || ids.lastIndexOf('|'+id+'|') < 0) {
    if (! ids) ids = "|";
    ids = ids + id + '|';
    sel_count++;
  }
  sel_all_check();
  document.cookie = sel_cname + "=" + ids;
  var num = getElt("sel-num-top");
  if (num) num.innerHTML = sel_num(ids);
  num = getElt("sel-num-bottom");
  if (num) num.innerHTML = sel_num(ids);
  return 0;
}

function set_params(sel) {
  var p = new Parse(sel.options[sel.selectedIndex].value, "&", "=");
  var form = sel.form;
  for (name in p.params) {
    if (name == ' target') form.target = p.params[name];
    if (form[name]) form[name].value = p.params[name];
  }
}


var tip = null;
var tip_shadow = null;
var tip_shown = 0;
var doc_elt = null;
if (document.documentElement) doc_elt = document.documentElement;
else if (document.body) doc_elt = document.body;

if (doc_elt) {
    doc_elt.onclick = function () { return showTip(); }
}

function showTip(e, id) {
  var mx, my;

  if (!e) e = window.event;

  if (tip_shown == 1 && !id) {
      tip_shown = 0;
      return;
  }

  if (tip) tip.style.visibility = 'hidden';
  if (tip_shadow) tip_shadow.style.visibility = 'hidden';

  if (! id) {
        return;
  }

  tip_shown = 1;

  if (e.clientX) {
      mx = e.clientX;
      my = e.clientY;
  } else if (e.pageX) {
      mx = e.pageX;
      my = e.pageY;
  } else {
      return;
  }

  if (mx + 210 > doc_elt.offsetWidth) mx = doc_elt.offsetWidth - 210;
  if (my + 50 >  doc_elt.offsetHeight) my = my - 150;

  if (document.documentElement &&
      document.documentElement.scrollTop)
  {
      menx = document.documentElement.scrollLeft + mx;
      meny = document.documentElement.scrollTop + my;
  } else if (document.body) {
      menx = document.body.scrollLeft + mx;
      meny = document.body.scrollTop + my;
  } else {
      menx = window.pageXOffset + mx;
      meny = window.pageYOffset + my;
  }

  var node = document.getElementById(id);
  var shadow = document.getElementById(id + "-shadow");

  if (! node) {
        alert("No node with id " + id);
  } else {
        node.style.left = menx + 'px';
        node.style.top = meny + 'px';
        node.style.visibility = 'visible';
        tip = node;

        if (shadow) {
          shadow.style.left = (menx + 5) + 'px';
          shadow.style.top = (meny + 6) + 'px';
          shadow.style.visibility = 'visible';
          tip_shadow = shadow;
        }
  }

  return false;
};


function changeSource(input, rec) {
  var parent_name = sources[input.value];
  var parent_checked = true;
  var parent_elt = null;
  var i = 0;
  var ignp = "v:ignore";
  input.name = srcp;
  while(i < input.form.elements.length) {
    var elt = input.form.elements[i];
    i++;
    if (elt.name != ignp && elt.name != srcp) continue;
    var elt_parent_name = sources[elt.value];
    if (elt_parent_name == parent_name) {
      parent_checked = parent_checked && elt.checked;
    } else if (elt_parent_name == input.value) {
      if (elt.checked != input.checked) {
        if (rec) {
          //alert(elt.value);
          elt.checked = input.checked;
          changeSource(elt, -1);
        }
        if (elt.checked && input.checked) elt.name = ignp;
        else elt.name = srcp;
      } else {
        elt.name = ignp;
      }
    } else if (elt.value == parent_name) {
      parent_elt = elt;
    }

  }
  if (rec >= 0 && parent_elt && parent_elt.checked != parent_checked) {
    //alert(parent_checked);
    parent_elt.checked = parent_checked;
    changeSource(parent_elt, 0);
  }
}


function td(id){
  togimg('switch-'+id);
  toggle('toggle-'+id);
  return false;
}



function pviewall(show) {
  toggle('pv-all', - show);
  toggle('pvc-all', show);
  var as = document.body.getElementsByTagName("a");
  for (i = 0; i < as.length; i++) {
    if (as[i].id &&
        ((show > 0 && as[i].id.search(/^po-/) >= 0) ||
         (show < 0 && as[i].id.search(/^pc-/) >= 0))) {
      as[i].onclick();
    }
  }
}

function pview(id, show, post) {
  var lk = getElt('po-' + id);
  var fr = getElt('pf-' + id);
  if (! lk || ! fr) return false;
  toggle('pf-' + id, show);
  toggle('po-' + id, - show);
  toggle('pc-' + id, show);
  if (! show) return;
  if (fr.src) ;
  else if (post) postlink(lk, 'pf-'+id);
  else fr.src = lk.href;
  return false;
}

function setts(link) {
  var qs = link.search;
  var tf = parent.frames['tree'];
  if (! tf) return;
  var state = tf.state;
  qs = qs.replace(/v%3astate=[^&]*/i, "");
  if (state) qs += "&v%3astate="+state;
  link.search = qs;
}

function posturl(url,target) {
  var form = document.createElement("form");
  var u = url.split('?', 2);
  form.action = u[0];
  form.method = "post";
  if (target) form.target = target;
  form.style.display = "none";
  var qs = new Parse(u[1],"&","=",1);
  for (var i = 0; i < qs.params.length; i+=2) {
    var input = document.createElement("input");
    form.appendChild(input);
    input.name = qs.params[i];
    input.value = qs.params[i+1];
  }
  document.body.appendChild(form);
  form.submit();
  return false;
}

function postlink(link, target) {
  return posturl(link.href, target ? target : link.target);
}

function doctog(id, show) {
  if ((document.all && document.selection.createRange().text) ||
      (document.getSelection && document.getSelection())) return;
  var sh = show == 2 ? -1 : (show == 1 ? 1 : 0);
  togimg('doctog-' + id, -sh);
  toggle('doctog1-' + id, sh);
  toggle('doctog2-' + id, -sh);
}

function doctoghover(div, ish) {
  if (! document.all) return;
  div.className = ish ? 'doctoghover' : 'doctog1';
}

function doctogall(show) {
  doctog('all',show);
  var divs = document.body.getElementsByTagName("div");
  for (i = 0; i < divs.length; i++) {
    if (divs[i].id && divs[i].id.search(/^doctog1-/) >= 0) {
      var id = divs[i].id.replace(/^doctog1-/,'');
      doctog(id, show);
    }
  }
}

/* DEPRECATED */
function query(sources) {
  var doc = frms ? parent.parent.frames['form'].document : document;
  var f = doc[rform];
  var ipt = f[srcp];
  if (ipt) ipt.value = sources;
  f.submit();
  return false;
}



var logins_cookie = "vivisimo-logins";
   var logins;
   function parselogins() {
     parsecookies();
     logins = new Parse(cookies.get(logins_cookie),",",":");
   }

   function islogin(name) {
     parselogins();
     var now = new Date();
     var logindate = logins.get(name);
     if (logindate && (logindate < 0 || logindate > now.getTime())) return true;
     return false;
   }

   function loginset(name, expire) {
     parselogins();
     var now = new Date();
     logins.set(name, expire >= 0 ? now.getTime() + expire * 1000 : -1);
     document.cookie = logins_cookie + "=" + myescape(logins.string());
     return false;
   }

   var logframename = "vivisimoLoginFrame";
   var logwin;
   var logsrc;
   var logdocurl;
   var logdoctarget;
   var logurls = new Object();
   var logframe;
   
   function login(name, link) {
     if (logwin) return false;
     var urlo = logurls[name];
     if (! urlo) return true;
     if (islogin(name)) return true;
     var url = urlo[0];
     var expire = urlo[1];
     var method = urlo[2];
     var loginwait = urlo[3];
     if (method == "POST" || method == "post") {
       logwin = window.open("about:blank", logframename);
       posturl(url, logframename);
     } else {
       logwin = window.open(url, logframename);
     }
     window.setTimeout("loadUrl()", loginwait);
     logsrc = name;
     logdocurl = link.href;
     logdoctarget = link.target;
     loginset(name, expire);
     return false;
   }

   function loadUrl() {
     if (! logdocurl) return;
     if (logwin) logwin.close();
     logwin = 0;
     if (logdoctarget == '_blank') {
       open(logdocurl);
     } else if (logdoctarget == '_top') {
       top.location = logdocurl;
     } else if (logdoctarget == '_self' || ! logdoctarget) {
       location = logdocurl;
     } else if (logdoctarget) {
       frames[logdoctarget].location = logdocurl;
     }
   }

var sc=cgi.get('tscroll');
var jsactive=cgi.get('active');

window.onload = function () {
  // scroll
  if (sc > 0 && scroll) scroll(0, parseInt(sc));
  // reset images
  if (jsactive) {
    sw(active, 0);
    sw(jsactive, 1);
    active = jsactive;
  }
  status='';
}

function sw(id, open) {
  var n = getElt(id);
  if (! n) return;
  var c = n.className;
  if (open){
     if(c.indexOf('-active')<0 && c.indexOf('root') < 0) n.className = c+'-active';
  } else {
     n.className = c.replace('-active','');
  }
}


function oc(link, type, exp, id, path) {
  var newUrl = link.href
  if (type == 2) {
    // delay because of IE bug
    window.setTimeout('sw("'+active+'", 0)',50);
    window.setTimeout('sw("'+id+'", 1)',100);
    active = id;
  } else if(type == 5) {
    newUrl2 = newUrl.replace("=list","=tree");
    open(newUrl2.replace("=root|","="+path+"|")+"&active="+imgId,"tree");
  } else if(type < 2 || type==4) {
    // save scroll param
    var sc = 0;
    if (document.layers) sc = window.pageYOffset; //Netscape4
    else if (document.documentElement) sc = document.documentElement.scrollTop;
    else if (document.body) sc = document.body.scrollTop; //IE or Netscape6
    if(sc) newUrl += "&tscroll="+sc;
   // save active id
    if(type == 0) {
      link.href = newUrl+"&active="+active;
    } else if(type == 1) {
      open(link.href.replace("=tree","=list"),"list");
      link.href = newUrl+"&active="+id;
    } else if(type == 4) {
      link.href = newUrl;
    }
  }
}

function validate(correctForm) {
  if (typeof correctForm == "undefined") {
    correctForm = true;
  } // if (typeof correctForm == "undefined")
  if (document.contactForm.first_name.value.length <= 0) {
    if (correctForm) {
      alert("Please tell us your first name.");
      document.contactForm.first_name.focus();
    } // if (correctForm)
    return false;
  } else if (document.contactForm.last_name.value.length <= 0) {
    if (correctForm) {
      alert("Please tell us your last name.");
      document.contactForm.last_name.focus();
    } // if (correctForm)
    return false;
  } else if (document.contactForm.email.value.length <= 0) {
    if (correctForm) {
      alert("Please tell us your email address.");
      document.contactForm.email.focus();
    } // if (correctForm)
    return false;
  } else if (!isValidEmail(document.contactForm.email.value)) {
    if (correctForm) {
      alert("Please provide a valid email address.");
      document.contactForm.email.value = '';
      document.contactForm.email.focus();
    } // if (correctForm)
    return false;
  } else if (document.contactForm.company.value.length <= 0) {
    if (correctForm) {
      alert("Please tell us what organization you are from.");
      document.contactForm.company.focus();
    } // if (correctForm)
    return false;
  } else if (document.contactForm.title.value.length <= 0) {
    if (correctForm) {
      alert("Please tell us your position at "+document.contactForm.company.value);
      document.contactForm.title.focus();
    } // if (correctForm)
    return false;
  } else if (document.contactForm.country.value.length <= 0) {
    if (correctForm) {
      alert("Please tell us what country you are from.");
      document.contactForm.country.focus();
    } // if (correctForm)
    return false;
  } else if (document.contactForm.description.value.indexOf("<a ") > 0) {
    if (correctForm) {
      alert("Please do not use HTML links in your message.  If you need to provide us with a URL, simply typing it will suffice.");
      document.contactForm.description.focus();
    } // if (correctForm)
    return false;
  } else {
    return true;
  } // if
} // function validate()

function validateDownload(correctForm) {
  if (typeof correctForm == "undefined") {
    correctForm = true;
  } // if (typeof correctForm == "undefined")
  if (validate(correctForm)) {
    document.contactForm.email.value = document.contactForm.email.value.toLowerCase();
    if (document.contactForm.email.value.indexOf('@mail.ru') > 0 ||
        document.contactForm.email.value.indexOf('@mail.com') > 0 || 
        document.contactForm.email.value.indexOf('@hotmail.com') > 0 ||
        document.contactForm.email.value.indexOf('@hotbox.com') > 0 ||
        document.contactForm.email.value.indexOf('@hotbox.ru') > 0 ||
        document.contactForm.email.value.indexOf('@gmail.com') > 0 || 
        document.contactForm.email.value.indexOf('@rediffmail.com') > 0 || 
        document.contactForm.email.value.indexOf('@aol.com') > 0 || 
        document.contactForm.email.value.indexOf('@verizon.net') > 0 || 
        document.contactForm.email.value.indexOf('@lycos.com') > 0 || 
        document.contactForm.email.value.indexOf('@comcast.net') > 0 || 
        document.contactForm.email.value.indexOf('@adelphia.net') > 0 || 
        document.contactForm.email.value.indexOf('@cox.net') > 0 || 
        document.contactForm.email.value.indexOf('@royalmail.com') > 0 ||
        document.contactForm.email.value.indexOf('@charter.net') > 0 ||
        document.contactForm.email.value.indexOf('@e-mailanywhere.com') > 0 || 
        document.contactForm.email.value.indexOf('@yahoo.com') > 0) {
      if (correctForm) {
        alert("Please use a valid email address from a company domain.");
        document.contactForm.email.focus();
      } // if (correctForm)
      return false;
    } else {
      if (validateDownloadPhone(correctForm)) {
        var contacts;
        if (correctForm) {
          contacts = "No contact preferences provided.";
          if (document.contactForm.contactEmail.checked) {
            contacts = document.contactForm.contactEmail.value;
          } // if (document.contactForm.contactEmail.checked)
          if (document.contactForm.contactPhone.checked) {
            contacts = document.contactForm.contactPhone.value;
          } // if (document.contactForm.contactPhone.checked)
          if (document.contactForm.contactEmail.checked && document.contactForm.contactPhone.checked) {
            contacts = document.contactForm.contactEmail.value + "\n" + document.contactForm.contactPhone.value;
          } // if (document.contactForm.contactEmail.checked && document.contactForm.contactPhone.checked))
          document.contactForm.description.value = contacts + "\n\n" + document.contactForm.description.value;
        } // if (correctForm)
        return true;
      } else {
        return false;
      } // if (validateDownloadPhone(correctForm))
    }
  } else {
    return false;
  } // if
} // function validateDownload()

function validateDownloadPhone(correctForm) {
  if (typeof correctForm == "undefined") {
    correctForm = true;
  } // if (typeof correctForm == "undefined")
  if (document.contactForm.contactPhone.checked) {
    if (document.contactForm.phone.value.length = 0) {
      if (correctForm) {
        alert("We cannot contact you be telephone as you requested if you do not provide us with a telephone number at which to reach you.");
        document.contactForm.phone.focus();
      } // if (correctForm)
      return false;
    } else {
      return true;
    } // if (document.contactForm.phone.value.length &amp;lt;= 0)
  } else {
    return true;
  } // if (document.contactForm.contactPhone.checked)
}

function checkDownloadButton() {
  var path = "/vivisimo/images/design/";
  var base = path + "downloadwhitepaper";
  var on   = base + ".gif";
  var off  = base + "-gray.gif";
  var img  = document.getElementById("downloadWhitepaper");
  if (validateDownload(false)) {
    img.src = on;
  } else {
    img.src = off;
  } // if (validateDownload(false))
} // function checkDownloadButton()

function isValidEmail(str) {
   return (str.indexOf("@") > 0);
}

function clearSearchQuery() {
  if (document.siteSearch.query.value=="search our site") {
    document.siteSearch.query.value = "";
  } // if (document.siteSearch.query.value=="search our site")
} // function clearSearchQuery()


function loadFrontpage() {
  document.searchForm.query.focus();
  if (!readCookie('flashplayed')) {
    createCookie('flashplayed', 'true', 30);
    drawFrontpageFlash();
  } // if (!readCookie('flashplayed'))
} // function loadFrontpage

function drawFrontpageFlash() {
  var flashpath = 'http://vivisimo.com/images/frontpage/flash0001/flash.swf';
  var element = document.getElementById('flash');
  element.innerHTML = '<object width="530" height="238"><param name="movie" value="'+flashpath+'" /><embed type="application/x-shockwave-flash" width="530" height="238" src="'+flashpath+'" /></object>';
} // function drawFrontpageFlash()


// Cookie handling functions from quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
