//browser detection

// convert all characters to lowercase to simplify testing
var agt=navigator.userAgent.toLowerCase();

// *** BROWSER VERSION ***
// Note: On IE5, these return 4, so use is_ie5up to detect IE5.
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);

// Note: Opera and WebTV spoof Navigator.  We do strict client detection.
// If you want to allow spoofing, take out the tests for opera and webtv.
var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
            && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
            && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
var is_nav2 = (is_nav && (is_major == 2));
var is_nav3 = (is_nav && (is_major == 3));
var is_nav4 = (is_nav && (is_major == 4));
var is_nav4up = (is_nav && (is_major >= 4));
var is_navonly      = (is_nav && ((agt.indexOf(";nav") != -1) ||
                      (agt.indexOf("; nav") != -1)) );
var is_nav6 = (is_nav && (is_major == 5));
var is_nav6up = (is_nav && (is_major >= 5));


var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_ie3    = (is_ie && (is_major < 4));
var is_ie4    = (is_ie && (is_major == 4) && (agt.indexOf("msie 4")!=-1) );
var is_ie4up  = (is_ie && (is_major >= 4));
var is_ie5    = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.0")!=-1) );
var is_ie5_5  = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.5") !=-1));
var is_ie5up  = (is_ie && !is_ie3 && !is_ie4);
var is_ie5_5up =(is_ie && !is_ie3 && !is_ie4 && !is_ie5);
var is_ie6    = (is_ie && (is_major == 4) && (agt.indexOf("msie 6.")!=-1) );
var is_ie6up  = (is_ie && !is_ie3 && !is_ie4 && !is_ie5 && !is_ie5_5);

var is_opera = (agt.indexOf("opera") != -1);
var is_opera2 = (agt.indexOf("opera 2") != -1 || agt.indexOf("opera/2") != -1);
var is_opera3 = (agt.indexOf("opera 3") != -1 || agt.indexOf("opera/3") != -1);
var is_opera4 = (agt.indexOf("opera 4") != -1 || agt.indexOf("opera/4") != -1);
var is_opera5 = (agt.indexOf("opera 5") != -1 || agt.indexOf("opera/5") != -1);
var is_opera5up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4);

var is_konqueror = (agt.indexOf("konqueror") > -1) ? 1 : 0;

var is_gecko = (agt.indexOf('gecko') != -1 &&!is_konqueror);
var stylesheets=new Array();


function checkboxFormSubmit()
{
  alert("here");
}

function checkboxFormInLine(url,varname,form)
{
  document.writeln("<hr>\n<p><b>Data to display</b>");
  //   document.writeln('<div id="kamiel" class="hideable" style="display: none;" >');
  document.writeln('<form method="GET" '+
		   'action="'+url+'">');
  document.writeln("<table class=\"layout\"><tr>");
  var keys="";
  var script='onchange="this.form.submit();"';
  for (var i in form) {
    if(form[i].nl) {
      document.writeln("</tr><tr>");
      continue;
    }
    document.writeln('<td><input type="checkbox" name="'+varname+
		     '['+ form[i].key+']" '+
		     (form[i].va?"checked ":"")+script+
		     '>'+form[i].ti+
		     '&nbsp;&nbsp;</td>');
    keys+=(","+form[i].key);
  }
  document.writeln('<input type="hidden" name="'+varname+
		   '_keys" value="'+keys.slice(1)+'">');
  document.writeln("</tr></table>");
  document.writeln("</form>");
  //  document.writeln("</div>");  
}

function popupForm__showform(anchorid)
{

  var ppw=new PopupWindow();
  window.childContent=this.forms[anchorid];
  var wWidth=window.innerWidth?window.innerWidth:
    document.body.clientWidth;
  var height=is_nav4?300:600; //600 because initial window needs to be 
  //bigger than content (it is resized later)
    var height=10;
  ppw.offsetY=-height;
  ppw.setSize(wWidth-100,height);
  //  alert(wWidth);
  //  ppw.populate(globalform);
  ppw.setUrl("popup.php?title="+this.titles[anchorid]);
  //  ppw.setWindowProperties("toolbar=no,location=no,status=no,menubar=no,scrollbars=auto,resizable,alwaysRaised,dependent,titlebar=no"); 
  ppw.showPopup(anchorid);

}




function submitAndClose(el)
{
  setCookie(stickycookiename,window.opener.name,0,0,0,0);
  el.form.submit(); 
  //  window.close();
  setTimeout("window.close();", 500);
  return true;
}

function submitAndDontClose(el)
{
  setCookie(stickycookiename,window.opener.name,0,0,0,0);
  //  alert("setting cookie:"+window.opener.name);
  el.form.submit(); 
  return true;
}

function popupForm__checkboxForm(title,url,varname,form,anchorid)
{
  str='<form target="'+window.name+'" method="GET" action="'+url+'">';
  str+="<table class=\"layout\"><tr>";
  this.counter++;
  var keys="";
  var i=0;
  var numcols=0;
  for (var i in form) {
    if(form[i].nl) {
      str+="</tr><tr>";
      if(i+1>numcols)
	numcols=i+1;
      i=0;
      continue;
    }
    str+='<td><input type="checkbox" name="'+varname+
      '['+ form[i].key+']" '+
      (form[i].va?"checked":"")+'>'+form[i].ti+
      '&nbsp;&nbsp;</td>';
    keys+=(","+form[i].key);
  }
  str+='<tr></tr><td>';
  str+='<input type="submit" value="OK" name="ok"  onclick="'
    +'submitAndClose(this);">';
  str+='</td><td>';
  str+='<input type="submit" value="Apply" name="apply"  onclick="'
    +'submitAndDontClose(this);">';
  str+='</td><td>';
  str+='<input type="submit" value="Close" name="close" onclick="'
    +'window.close();">';
  str+='<input type="hidden" name="'+varname+
    '_keys" value="'+keys.slice(1)+'">';
  str+="</td></tr></table>";
  str+="</form>";
  if(typeof(anchorid)=='undefined') {
    anchorid="formPopup"+Math.floor(Math.random()*1000000);
  }
  anchorid="anchor_"+window.name+"_"+anchorid;
  //alert("anchorid="+anchorid);
  this.forms[anchorid]=str;
  this.titles[anchorid]=title;
  return anchorid;
 }


function popupForm ()
{
  this.checkboxForm=popupForm__checkboxForm;
  this.showform=popupForm__showform;
  this.messageWindow=popupForm__messageWindow;
  this.closeMessage=popupForm__closeMessage;
  this.forms=new Array();
  this.titles=new Array();
}


ppf=new popupForm();

//cookies

// name - name of the cookie
// value - value of the cookie
// [expires] - expiration date of the cookie (defaults to end of current session)
// [path] - path for which the cookie is valid (defaults to path of calling document)
// [domain] - domain for which the cookie is valid (defaults to domain of calling document)
// [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
// * an argument defaults when it is assigned null as a placeholder
// * a null placeholder is not required for trailing omitted arguments




function progressBar(left,right,len) 
{
  //  alert("left="+left+" right="+right+"len="+len);
  var wWidth=window.innerWidth?window.innerWidth:
    document.body.clientWidth;
  if(!wWidth)
    maxwidth=100;
  else
    maxwidth=wWidth/2;
  if(is_ie4up&&!is_ie6up)
    return progressBarImages(left,right,len,maxwidth);
   var wl=Math.floor(left*maxwidth/len);
   var wr=Math.ceil(right*maxwidth/len);
   var style; 
   if(wl>0) {
     style="padding-right: "+wl+"px; ";
     document.write('<span class=\"progress\" style=\"'+style+'"></span>');
   }
   if(wr-wl>0) {
       style="padding-right: "+(wr-wl)+"px;  background: blue; ";
       document.write('<span class=\"progress\" style=\"'+style+'"></span>');
     }
   if(maxwidth-wr>0) {
     style="padding-right: "+(maxwidth-wr)+"px;";
     document.write('<span class=\"progress\" style=\"'+style+'"></span>');
   }
}

function setCookie(name, value, expires, path, domain, secure) {
  if(value=="") return;
  //  alert(name+"="+value);
  var curCookie = name + "=" + value +
      ((expires)?"; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}



function getCookie(Name) {
//Get cookie routine by Shelley Powers 
  var search = Name + "="
  var returnvalue = "";
  if (document.cookie.length > 0) {
    offset = document.cookie.indexOf(search)
    // if cookie exists
    if (offset != -1) { 
      offset += search.length
      // set index of beginning of value
      end = document.cookie.indexOf(";", offset);
      // set index of end of cookie value
      if (end == -1) end = document.cookie.length;
      returnvalue=unescape(document.cookie.substring(offset, end))
      }
    
   }
  return returnvalue;
}


//stylesheet loading



//sticky variable functions
//the code below makes sure every window gets a name, even if it
//doesn't normally
//the name of the currently active window is stored in a cookie
//so that server pages can set different defaults for each window


stickycookiename="currentwindow";

function wphonfocus(evt) 
{
  //java.lang.System.out.println("onfocus: setcookie "+window.name);
  setCookie(stickycookiename,window.name,0,0,0,0);
  return false;
}


window.onfocus=wphonfocus;

if(!window.name&&window.newwindowname)
  window.name=newwindowname;


setCookie(stickycookiename,window.name,0,0,0,0);
//java.lang.System.out.println("startup: setcookie "+window.name);



///////////////////////////


//script for cleaning up form elements that have not changed
//before sending a post or get to server
function RemoveDefaults(what) {
var result = true;
var output = '';
var localresult=true;
for (var i=0, j=what.elements.length; i<j; i++) {
     myType = what.elements[i].type;
        if (myType == 'checkbox' || myType == 'radio') {
            if (what.elements[i].checked &&what.elements[i].defaultChecked) {
                 what.elements[i].checked=false;
                result = false
            }
        }
        if (myType == 'password' || myType == 'text' || myType == 'textarea') {
            if (what.elements[i].value == what.elements[i].defaultValue) {
what.elements[i].value=0;
            // output += '"'+what.elements[i].name+'",';
            result=false
            }
        }
        if (myType == 'select-one' || myType == 'select-multiple') {
localresult=true;
            for (var k=0, l=what.elements[i].options.length; k<l; k++) {
                if (what.elements[i].options[k].selected && what.elements[i].options[k].defaultSelected) {
             //output += '"'+what.elements[i].name+'",';
                  result = false
                  localresult=false
                }
            }
        }
     if(!localresult) 
        what.elements[i].length=0;
    }
  if (output != '') {
    //what.elements['NotChanged'].value=output;
    //    alert(output);
   }
    return true;
}



///////////frame functions//////////////////

function framesok(name)
{

if(!parent||!parent.frames)
  return false;
 if(parent.frames.length<2)
  return false;
 if(!parent.frames['contents'])
  return false;
 curparent=parent.location+"";
 if(curparent.indexOf(name)<0) {
   //   alert("location="+parent.location+" name="+name);
   return false;
 }
 return true;
}



function listNavMenu(baseurl) 
{
  var sep=(baseurl.indexOf("?")<0)?"?":"&";
  var prevstr='';
  var step=1;
  var symbol=(is_nav4||is_konqueror)?'&lt;':
    '<span class="triangleNav">&#9664;</span>';
  if(IE)
    symbol='<span class="triangleNavIE">3</span>';
  var symbols=symbol;
  for(var i=0;i<=this.level;i++) 
    {
      var ref=(i==0)?this.currentRecord:this.currentNavFirstKey;
      if(ref-step<0) {
	prevstr=(symbols+' '+prevstr);
      } else {
	var key=(this.useValueInQuery?this.papers[ref-step]
		 :ref-step);
	prevstr='<a class="jump" href="'+baseurl+sep+this.queryPrefix
	  +key+'">'
	  +symbols+'<\/a>&nbsp;'+prevstr;
      }
      step*=this.maxEntries;
      symbols+=symbol; 
    }
  document.write(prevstr);
  menu=yams.menu[this.currentKey];
  //  alert(typeof(menu));
  //alert(this.currentKey+"="+yams.menu[this.currentKey].length);
  //do not us "item" because IE seems to use this for something!
  for (it in menu) {
    var key=menu[it].qu.slice(1);
    var paper=menu[it].ti;
    //    alert(typeof(key)+"="+typeof(this.currentPaper)+"="+this.useValueInQuery);
    if(this.useValueInQuery&&key==String(this.currentPaper)||
       !this.useValueInQuery&&key==this.currentRecord) {
      document.write(' <b>'+paper+'</b>');
      //alert(key+"="+this.currentPaper);
    } else {
      document.write(' <a  href="'+baseurl+sep+this.queryPrefix+key
		     +'">'+paper+'<\/a>');
    }
  }

  var nextstr='';
  var step=1;
  var symbol=(is_nav4||is_konqueror)?'&gt;'
    :'<span class="triangleNav">&#9654;</span>';
  if(IE)
    symbol='<span class="triangleNavIE">4</span>';
  symbols=symbol;
  for(var i=0;i<=this.level;i++) 
    {
      var ref=(i==0)?this.currentRecord:this.currentNavFirstKey;
      if(ref+step>=this.papers.length) {
	nextstr+=(' '+symbols);
      } else {
	var key=(this.useValueInQuery?this.papers[ref+step]
		 :ref+step);
	nextstr+=' <a class="jump" href="'+baseurl+sep+this.queryPrefix
		       +key+'">'
	  +symbols+'<\/a>';
      }
      step*=this.maxEntries;
      symbols+=symbol; 
    }
  document.write(nextstr);

}

function listNavBar(baseurl) 
{
  if(this.level>=1) {
  info="Click here to select a "+this.itemName+", or click on one of the "
    +"links to the right";
  var id=this.itemName+'ListA';
  document.writeln('<p><b><a id="'+id+'" name="'+id+'" title="'
		   +info+'" href="javascript:void(0)" onclick="'+
		   'if(yams) yams.displayMainMenu(event,\''+
		   this.baseKey+'\',\''
		   +baseurl+'\',\'?'+this.queryPrefix+
		   '\',\''+id+'\');">');
  document.writeln('Select</a> '+this.itemName
		   +':</b> <span class="paperNav">');
  } else {
    document.writeln('<p><b>Select '+this.itemName
		     +':</b> <span class="paperNav">');
  }
  this.NavMenu(baseurl);
  document.writeln("</span>");


}


function listCountBar(baseurl) 
{
  if(this.maxPapers)
    document.writeln(" "+this.papers.length+'/'+this.maxPapers+"&nbsp;");
  else
    document.writeln(" "+this.papers.length+' papers'+"&nbsp;");
  if(!is_nav4&&this.maxPapers) {
      progressBar(0,this.papers.length,this.maxPapers);
  }
}


uniqueListNameCounter=0;

function uniqueListName(prefix,suffix)
{
  return prefix+(uniqueListNameCounter++)+':'+suffix;
}

function listLeafMenu(papers) 
 {
   papersout=new Array();
   var k=0;
   for(var i=0;i<papers.length;i+=this.maxEntries) {
     var islast=(i+this.maxEntries>=papers.length);
     var last=islast?(papers.length-1):(i+this.maxEntries-1);
     var key=this.itemName+'List:'+i+':'+last;
     yams.menu[key]=new Array();
     for(var j=i;j<=last;j++) {
       var label=papers[j];
       var url='|'+(this.useValueInQuery?label:j);
       yams.menu[key][j-i]={ti:label, qu:url};
       if(j==this.currentRecord) {
	 this.currentKey=key;
	 this.currentPaper=papers[j];
	 this.currentNavFirstKey=i;
       }
     }
     //alert(key+"="+yams.menu[key].length);
     papersout[k++]={start:i, end:last};
 
   }
   return papersout;
 }


function listBranchMenu(menuDesc,papers) 
 {
   var menuDescout=new Array();
   var k=0;
   for(var i=0;i<menuDesc.length;i+=this.maxEntries) {
     var islast=(i+this.maxEntries>=menuDesc.length);
     var last=islast?(menuDesc.length-1):(i+this.maxEntries-1);
     var start=menuDesc[i]["start"];
     var end=menuDesc[last]["end"];
     var key=this.itemName+'List:'+start+':'+end;
     if(last>i) {
       yams.menu[key]=new Array();
       for(var j=i;j<=last;j++) {
	 var substart=menuDesc[j]["start"];
	 var subend=menuDesc[j]["end"];
	 var label=papers[substart]+' -  '+papers[subend];
	 var sm=this.itemName+'List:'+substart+':'+subend;
	 yams.menu[key][j-i]= { ti:label, sm:sm};
       }
     }
     //alert(key+"="+yams.menu[key].length);
     menuDescout[k++]={start:start,end:end};
   }
   return menuDescout;
 }



function listMenuGenerate()
{

  var menuDesc=this.listLeafMenu(this.papers);
  while (menuDesc.length>1)
    {
      this.level++;
      menuDesc=this.listBranchMenu(menuDesc,this.papers);
    }
  if(menuDesc.length>0)
    this.baseKey=this.itemName+'List:'+menuDesc[0]['start']+':'
      +menuDesc[0]['end'];
}


listMenu.prototype.listBranchMenu=listBranchMenu;
listMenu.prototype.listLeafMenu=listLeafMenu;
listMenu.prototype.NavMenu=listNavMenu;
listMenu.prototype.NavBar=listNavBar;
listMenu.prototype.CountBar=listCountBar;
listMenu.prototype.generate=listMenuGenerate;
listMenu.prototype.setDefaults=listMenuSetDefaults;

function listMenu()
{
}

function listMenuSetDefaults(papers,currentRecord,maxPapers)
{
  this.maxEntries=10;
  this.currentKey='';
  this.currentPaper=0;
  this.currentNavFirstKey=0;
  this.papers=papers;
  this.currentRecord=currentRecord;
  this.level=0;
  this.queryPrefix="qqq=";
  this.itemName='blabla';
  this.useValueInQuery=true;
  this.maxPapers=(typeof(maxPapers)=='undefined')?false:maxPapers;
}



function paperListMenu(papers,currentRecord,maxPapers)
{

  this.setDefaults(papers,currentRecord,maxPapers);
  this.queryPrefix="PaperID=";
  this.itemName='paper';
  this.useValueInQuery=true;
  //return ret;
}

paperListMenu.prototype=new listMenu();
paperListMenu.baseClass=listMenu.prototype.constructor;
paperListMenu.constructor=paperListMenu;

function userListMenu(users,currentRecord,maxUsers)
{

  this.setDefaults(users,currentRecord,maxUsers);
  this.queryPrefix="CurrentRecord=";
  this.itemName='user';
  this.useValueInQuery=false;
}

userListMenu.prototype=new listMenu();
userListMenu.baseClass=listMenu.prototype.constructor;
userListMenu.constructor=userListMenu;


//not used
function progressBarImages(left,right,len,maxwidth) 
{
  if(len==0)
    return;
   var wl=Math.floor(left*maxwidth/len);
   var wr=Math.ceil(right*maxwidth/len);
   // wl=20;
   //   wr=80;
   if(wl>0) 
     document.write('<img class="progress" src="images/pixel.gif" '
		      +'height="9" width="'+ wl +'">');
   if(wr-wl>0)
     document.write('<img class="progress" src="images/hbar.gif" '
		      +'height="9" width="'+ (wr-wl) +'">');
   if(maxwidth-wr>0)
     document.write('<img class="progress" src="images/pixel.gif" '
		      +'height="9" width="'+ (maxwidth-wr) +'">');
   //  alert(wl+"="+wr+"="+maxwidth);
   //document.write("\n");
}





function popupForm__closeMessage()
{
  str='<form  method="GET" action="">';
  str+="<table class=\"layout\"><tr><td>";
  str+='<input type="submit" value="Close" name="close" onclick="'
    +'window.close();"></td></td></table>';
  str+="</form>";
  return str;
}




function popupForm__messageWindow(title,message)
{
  var wWidth=window.innerWidth?window.innerWidth:
  document.body.clientWidth;
  var anchorid="formPopup"+Math.floor(Math.random()*1000000);
  this.forms[anchorid]="<div style=\"width: "+wWidth+"px;\">\n"+
    message+"\n</div>\n"+this.closeMessage();
  this.titles[anchorid]=title;
  return anchorid;
}




function printversion()
{
  var baseurl=window.location.href;
  var sep=(baseurl.indexOf("?")<0)?"?":"&";
  //  window.location.href=baseurl+sep+"format=print";
  window.open(baseurl+sep+"format=print","print");
}
