// Copyright (c) European Patent Office, 1998-2002
// Author: mhp
NS = (navigator.appName=='Netscape')?1:0;
MaxTitleLength = 100;
MaxPNs = 20;
FirstPN = '';
PNCookie = '';
today      = new Date();
expirydate = new Date(today.getTime() + (30 * 86400000)); // 30 days from now

CheckedIn = 0;

urlTitle=""; // make it global and existing
cc="ep" // defaults
lg="en" // defaults
cookieMessage = "The cookie is full, possibly due to very long titles, we apologise";

function formatDocInfo(str) {
/*
  Kind
  Inventor
  Applicant
  Publication date
  IPC 
*/
  parts = str.split('|')
  if (parts.length <5) return
  inv = parts[1];
  app = parts[2];
  ipc = parts[4];
  if (inv) {
    invs = inv.split(';')
    if (invs.length>2) parts[1] = invs[0]+";"+invs[1]+"(+"+(invs.length-2)+")";
  }
  if (app) {
    apps = app.split(';')
    if (apps.length>2) parts[2] = apps[0]+";"+apps[1]+"(+"+(apps.length-2)+")";
  }
  if (ipc) {
    ipcs = ipc.split(';')
    if (ipcs.length>2) parts[4] = ipcs[0]+";"+ipcs[1]+"(+"+(ipcs.length-2)+")";
  }
  return parts.join('|'); // NOTE - will be escaped later
}

function toggleCheck(cb,title,kind,env) {

   var PN = cb.name;
   if (cb.checked) {
     if (!title && urlTitle) title = urlTitle;
     if (!kind) kind = '1';
     if (!env) env='l2';
   
      cb.checked = addPN(PN,formatDocInfo(kind),cleanTitle(title),env); /* uncheck if cookie not saved */
  }
  else { // remove without asking
     if (!removePN(PN)) {
        cb.checked=true; // Check if cookie not modified
     }
  }
}

function cleanTitle(theTitle) {
  if (theTitle == '') return '';
  if (NS) {
     SApos = '%92'; // Single apostrophe
     DApos = '%94'; // Double apostrophe
  }
  else {
     SApos = '&#146;';
     DApos = '&#148;';
  }
  if (theTitle.indexOf('%27')!=-1) theTitle = swap(theTitle,'%27',SApos);
  if (theTitle.indexOf('%22')!=-1) theTitle = swap(theTitle,'%22',DApos);
  theTitle = swap(theTitle,'+',' ');
  theTitle = unescape(theTitle); // put back
  return theTitle;
}

function getPos(PN) {
  if (PNCookie=='') getPNs(); // only get the pns once in this page
  var Found = false;
  for (var i=0,n=PNCookie.length;i<n;i++) {
     if (PNCookie[i].indexOf(PN) !=-1) { // Already there?
        Found = true;
        break;
     }
  }
  if (Found) return i;
  else return -1;
}
function addPN(PN,Kind,title,env) {
  if (PNCookie=='') getPNs(); // only get the pns once in this page
  var Found = false;
  if (CheckedIn >= MaxPNs ) {
      window.open("/search97cgi/s97_cgi.exe?Action=FormGen&Template="+cc+"/"+lg+"/info.hts&INFO=cookies.html","help");
     return false;
  }
  Found = getPos(PN) != -1;
  if (Found) return true; // Keep the checkbox checked...

  if (title.length > MaxTitleLength) { // chop the title but not in the middle of a tag or entity
     var ampPos = title.lastIndexOf('&');
     var offset = (MaxTitleLength-3)-ampPos;
     if (offset > 0 && offset <= 5) title = title.substring(0,ampPos);
     else title = title.substring(0,MaxTitleLength-3);
     title += '...';
  }
  PNCookie[PNCookie.length] = 'PN='+ PN + '&KC=' + Kind + '&TI=' + title + '&ENV=' + env; // add it to end
  writePNCookie();
  // double Check that the user accepted the cookie!
  var theCookie = ''+ document.cookie;
  var PNPos = theCookie.indexOf(PN);
  
  var FPNPos = theCookie.indexOf(FirstPN);

  if (PNPos < FPNPos || PNPos == -1) {
     window.open("/search97cgi/s97_cgi.exe?Action=FormGen&Template="+cc+"/"+lg+"/info.hts&INFO=cookies.html","help");
     return false;
  }
  else CheckedIn++;
  showInMenu(CheckedIn);
//  if (CheckedIn==1 && document.all) document.all('mypl').disabled=false;
  if (document.layers) location.reload(); // sorry netscape

  return true;
}

xxx=0;
function showInMenu(CheckedIn) {
  if (document.all && document.all('menuPnCount')) {
     document.all('menuPnCount').innerHTML=CheckedIn;
  }
  else if (document.getElementById && document.getElementById('menuPnCount')) {
     document.getElementById('menuPnCount').innerHTML=CheckedIn;
  }
  else if (document.layers) status=CheckedIn +' pns in My Patents List';// - this functionality needs attention for netscape4';
//  status='called ' + (xxx++) +' - '+new Date()
}




function removePN(PN) {
  if (PNCookie=='') getPNs(); // only get the pns once in this page
  var Found = false;
  for (var i=0,n=PNCookie.length;i<n;i++) {
     if (PNCookie[i].indexOf(PN) !=-1) { // Already there?
        Found = true;
        break;
     }
  }
  if (!Found) return false;

  PNCookie[i] = '';
  writePNCookie();

  var theCookie = ''+ document.cookie;
  var PNPos = theCookie.indexOf(PN);
  var FPNPos = theCookie.indexOf(FirstPN);
  if (PNPos != -1 && PNPos < FPNPos) { /* Is it gone from the PNList (it might still be in the FirstPN) */
     window.open("/search97cgi/s97_cgi.exe?Action=FormGen&Template="+cc+"/"+lg+"/info.hts&INFO=cookies.html","help");
     return false;
  }
  else CheckedIn--;

  showInMenu(CheckedIn);
//  if (CheckedIn<1 && document.all) document.all('mypl').disabled=false;
 
  return true;
}

function writePNCookie() {
  var theCookie = '';
  var allCookies = document.cookie;
  var mpnListCookie = escape(getCookie('mPnList')); // get the escaped length 
  var nonListCookieLength=allCookies.length-mpnListCookie.length;
  var maxListLength = 4000-nonListCookieLength;
  for (var i=0,n=PNCookie.length;i<n;i++) {
     if (PNCookie[i] != '') {
       if (escape(theCookie+PNCookie[i]).length < maxListLength)
       theCookie += ':' + PNCookie[i];
     }
     
  }
  if (theCookie == '') delCookie('mPnList','/','.espacenet.com'); // remove an empty cookie...
  else {
     theCookie = theCookie.substring(1); // loose leading ':'
      setCookie('mPnList',theCookie,expirydate,'/','.espacenet.com'); // Remember TWO dots!
  }
}

function getPNs() {
  var Crumbles = getCookie('mPnList');
  if (Crumbles != null) {
     Crumbles = Crumbles.split(':PN').join('@@@PN'); // turns out there can be unescaped : in the title
     PNCookie = Crumbles.split('@@@');
  }
  else PNCookie = new Array();
  CheckedIn = PNCookie.length;
}

function checkEm(theDoc,theForm) {
  getPNs();
  CB = theForm.elements;
  CheckedIn = 0;
  for (var i=0,n=CB.length;i<n;i++) {
     if (CB[i].name!="compactCheck") CB[i].checked = false; // untag per default
     for (var j=0,m=PNCookie.length;j<m;j++) {
       if (PNCookie[j].indexOf(CB[i].name) !=-1 ) {
          CB[i].checked = true;
       }
     }
  }
  CheckedIn = PNCookie.length;  
  showInMenu(CheckedIn);
}


pns = new Array();

function crtItem(pn,ti) {
   this.pn=pn;
   this.title=ti;
}
function pnArray() {
   var pnCookie = getCookie('mPnList');
   if (!pnCookie) return
   list = pnCookie.split(':');
   for (i=0;i<list.length;i++) {
      vars = list[i].split('&');
      pn="";
      ti="";
      for (j=0;j<vars.length;j++) {
         vals = vars[j].split('=');
         if (vals[0]=='PN') pn = vals[1];
         if (vals[0]=='TI') ti = vals[1];
      }
      if (pn) pns[pns.length]=new crtItem(pn,ti)
   }
}


function setChk(idx) {
   if (isNaN(idx) &&    document.form1.elements[idx])
     document.form1.elements[idx].checked = !document.form1.elements[idx].checked;
   else document.form1.chk[idx].checked=!document.form1.chk[idx].checked;
   window.focus();
}

function getSearch() {
   var CurrentSearch = getCookie('menuCurrentSearch');
   if (!CurrentSearch) {
      CurrentSearch = "javascript:;"
      window.open("/search97cgi/s97_cgi.exe?Action=FormGen&Template="+cc+"/"+lg+"/info.hts&INFO=cookies.html","help")
      //javascript:alert('Sorry - cookies are needed to retrieve the last search')";
   }
   return CurrentSearch;
}


/* Utility scripts */
function mySplit(S,Delim) {
  var spl   = new Array();
  if (S.indexOf(Delim) == -1) {
     spl[0] = S;
    return spl;
  }
  var t     = 0;
  var oldp  = 0;
  var p     = 0;
  var dL    = Delim.length;
  while(S.indexOf(Delim,oldp) >= 0) {
     p      = S.indexOf(Delim,oldp);
     spl[t] = S.substring(oldp,p);
     oldp   = p+dL;
     t++;
  }
  if (p < S.length) spl[t] = S.substring(p+dL);
  return spl;
}

function getCookie(Name) {
  var search = Name + "="
  if (document.cookie.length > 0) {
     offset = document.cookie.indexOf(search)
     if (offset != -1) {
        offset += search.length
        end = document.cookie.indexOf(";", offset)
        if (end == -1) end = document.cookie.length
        return unescape(document.cookie.substring(offset, end))
     }
  }
}

function setCookie (name,value,expires,path,theDomain,secure) {
  var theCookie = name + "=" + escape (value) +
  ((expires)    ? "; expires=" + expires.toGMTString() : "") +
  ((path)       ? "; path="    + path   : "") +
  ((theDomain)  ? "; domain="  + theDomain : "") +
  ((secure)     ? "; secure"            : "");
  document.cookie = theCookie;
}

function delCookie(name,path,domain) {
  if (getCookie(name)) document.cookie = name + "=" +
     ((path)   ? ";path="   + path   : "") +
     ((domain) ? ";domain=" + domain : "") +
     ";expires=Thu, 01-Jan-70 00:00:01 GMT";
}

function saveForm(theForm) {
  var saveString="";
  var DB = ""
  var st = "";
  var idx ="";
  DB= theForm.DB.options[theForm.DB.selectedIndex].value
  if (theForm.st) st = (theForm.st[0].checked)?theForm.st[0].value:theForm.st[1].value;
  if (theForm.IDX && theForm.IDX.checked) idx = theForm.IDX.value;
  // text and hidden
  for (i=0;i<theForm.elements.length;i++) {
    var tp = theForm.elements[i].type;
    if (tp=='hidden' || tp == 'text') {
      saveString += "&" + theForm.elements[i].name+'='+escape(theForm.elements[i].value);
    }
  }
  saveString = theForm.action+'?'+
      'DB='+DB+
      ((st)?'&'+st:'')+
      ((idx)?'&IDX='+idx:'')+
      saveString;
  setCookie("refine",saveString,expirydate, "/",".espacenet.com");
}


function swap(aString,fromString,toString) {
  var pos = aString.indexOf(fromString);
  var fl = fromString.length;
  while (pos != -1) {
     aString = aString.substring(0, pos) + toString + aString.substring(pos+fl);
     pos = aString.indexOf(fromString);
  }
  return aString;
}

function initLocalPage() {
   // will be overridden
}

function initpage() {
//  if (window.focus) self.focus();

  if (document.form1) checkEm(self.document,document.form1);
  pnArray();

  initLocalPage();
}
window.onload=initpage;
pnArray(); // run before the body
//document.write('<a href="#" onClick="alert(CheckedIn+\'\\n-------------\\n\'+(PNCookie)?PNCookie.join(\'\\n\'):\'Where is the beef?\') ); return false">[?]</a>')


