// @(#)global.js	4.106 09/11/24 Xinet, Inc. Copyright (c) 2000, 2005 by Xinet, Inc.  All Rights Reserved.
// WN_Include_Safe

function userinfo(u,b,a,i,s,l,f,d,c,h,p,o,x,cp_old,v,cp,mailto,acl,maxup,group1,n,keys,shocom)
{
	this.user = u
	this.basket = b
	this.archives = a
	this.iconview = i
	this.shortview = s
	this.longview = l
	this.showfpoinfo = f
	this.showdates = d
	this.changecomment = c
	this.highres = h
	this.upload = p
	this.imgorder = o
	this.fileadm = x
	this.defaultview = v
	this.changepassword=cp;
	this.mailto=mailto;
	this.acl=acl;
	this.maxupload=maxup;
	this.primarygroup = group1;
	this.allownonimages = n;
	this.changekeywords = keys;
	this.showcomments = shocom;
}

function userobjinfo (u,id,name,sal,first,last,title,dept,co,addr,city,st,zip,ctry,phone,cell,fax,email,notes)
{
	u.id		=id;
	u.user		=name;
	u.salutation	=sal;
	u.first		=first;
	u.last		=last;
	u.title		=title;
	u.dept		=dept;
	u.company	=co;
	u.address	=addr;
	u.city		=city;
	u.state		=st;
	u.zip		=zip;
	u.country	=ctry;
	u.phone		=phone;
	u.mobile	=cell;
	u.fax		=fax;
	u.email		=email;
	u.notes		=notes;
}

function userobj (name,issubadmin,id,sal,first,last,title,dept,co,addr,city,st,zip,ctry,phone,cell,fax,email,notes)
{
	this.name = name;
	this.issubadmin = issubadmin;
	if (id) {
		userobjinfo (this,id,name,sal,first,last,title,dept,co,addr,city,st,zip,ctry,phone,cell,fax,email,notes);
	}
}

function cwd(p,h,n,b)
{
	this.path = p
	this.htmlpath = h
	this.name = n
	this.inbasket = b
}

function buildobject(n,p,c,t,r,l,d,i,cdt,mdt,adt,m)
{
	this.name = n
	this.path = p
	this.archive = false
	this.comment = c
	this.type = t
	this.creator = r
	this.length = l
	this.isadir = d
	this.inbasket = i
	this.isimage = m
	this.cdate = new Date(cdt * 1000)
	this.mdate = new Date(mdt * 1000)
	this.adate = new Date(adt * 1000)
}

function dirob(name,path,depth) {
	this.name = name
	this.path = path
	this.depth = depth
}

function buildvol(p,n,v)
{
	this.path = p;
	this.name = n;
	this.isventurevol = v;
}

function addarchive(n,nm,d,off)
{
	this.name = n
	this.number = nm
	this.date = new Date(d * 1000)
	this.offset = off
}

function addimginfo(w,h,r,t,c,l,dbid)
{
	this.width = w
	this.height = h
	this.resolution = r
	this.imagetype = t
	this.colorspace = c
	this.length = l
	this.dbfileid = dbid
}

function keyworditem(id, order, editable, name, desc, type ,size, cols, rows, precision, flags, display, hidden, limited, fixed, valueflag, indexflag, permflag) {
	this.id = id;
	this.order = order;
	this.editable = editable;
	this.name = name;
	this.desc = desc;
	this.type = type;
	this.size = size;
	this.cols = cols;
	this.rows = rows;
	this.precision = precision;
	this.flags = flags;
	this.display = display;
	this.hidden = hidden;
	this.limited = limited;
	this.fixed = fixed;
	this.valueflags = valueflag;
	this.indexflag = indexflag;
	this.permflags = permflag;
	this.value = "";
	this.htmlvalue = "";
	this.values = new Array();
	this.htmlvalues = new Array();
	this.dbvalues = new Array();
	this.curvalues = new Array();
	this.valuescount = 0;
}

function dateitem (year, month, day, hour, minute, second, dayname)
{
	this.year = year;
	this.month = month;
	this.day = day;
	this.hour = hour;
	this.minute = minute;
	this.second = second;
	this.dayname = dayname;
}

function browsebutton(dir) {
	document.writeln("<INPUT TYPE=button VALUE=\"" + lang.browse + "\" onClick=\"window.location='/webnative/listdir?" + dir + "'\">");
}

function searchbutton(dir) {
	document.writeln("<INPUT TYPE=button VALUE=\"" + lang.search + "\" onClick=\"window.location='/webnative/searchengine?" + dir + "'\">");
}

function toplevelbutton(goTop) {
	document.writeln("<INPUT TYPE=button VALUE=\"" + lang.toplevel + "\" onClick=\""+(goTop?"top":"window")+".location='/webnative/listdir?-t'\">");
}

function helpbutton(file) {
	var helpdir = "/webnative/streamfile?-help+";
	document.write("<INPUT TYPE=button VALUE=\"" +lang.help+ "\" onClick=\"window.open('"+helpdir+file+"', 'helpWindow')\">");
}

function basketbutton() {
	if (uinfo.basket) {
		document.writeln("<INPUT TYPE=button VALUE=\"" + lang.sbasket + "\" onClick=\"FocusBasket()\">");
	}
}
function uploadbutton(dir) {
	if (uinfo.upload) {
		document.writeln("<INPUT TYPE=button VALUE=\"" + lang.upload + "\" onClick=\"window.location='/webnative/upload?" + dir + "'\">")
	}
}

function hexStr(s)
{
	var a = "\t\n\f\r !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
	var h = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F")
	var x = ""

	for (var i = 0; i < s.length; i++) {
		var c = a.indexOf(s.charAt(i)) + 1
		x += h[c >> 4]
		x += h[c & 15]
	}
	return x
}


function setCookie(name, value, forceExpire) {
  var today = new Date();
  var dateString = "";

  var day = today.getDay();
  var date = today.getDate();
  var month = today.getMonth();
  var year = today.getYear()+5;
  var hours = today.getHours();
  var minutes = today.getMinutes();
  var seconds = today.getSeconds();
  var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

  year += (year < 2000) ? ((year > 100) ? 1900 : 2000) : 0

  dateString = days[day]+", "+date+"-"+months[month]+"-"+year+" "+hours+":"+minutes+":"+seconds+" GMT";

  if( !forceExpire ) {
    document.cookie = (name+"="+value+";expires="+dateString+";");
  } else {
    document.cookie = (name+"="+value+";");
  }
}


function getCookie(Name)
{
	if (document.cookie.length <= 0) {
		return(false)
	}
	offset = document.cookie.indexOf(Name + "=")
	if (offset < 0) {
		return(false)
	}
	offset += Name.length + 1
	end = document.cookie.indexOf(";", offset)
	if (end < 0) {
		end = document.cookie.length
	}
	return unescape(document.cookie.substring(offset, end))
}

var basketWindow = null

function OpenBasketWindow(sURL)
{
	if( basketWindow && !basketWindow.closed ) {
		handleOpenBasketWindow(basketWindow, sURL);
        } else {
		openBlankWindow("basketWindow", "toolbar=no,resizable=yes,scrollbars=yes,width=600,height=600", handleOpenBasketWindow, sURL);
	}
}

function handleOpenBasketWindow(newWin, sURL) {
	basketWindow = newWin;
	bDoc = basketWindow.document;
	bDoc.open();
	bDoc.writeln("<BODY><FORM METHOD=POST ACTION='/webnative/basketcontrol'><INPUT TYPE=hidden NAME=controlpath VALUE='"+sURL+"'></FORM></BODY>");
	bDoc.close();
	bDoc.forms[0].submit();
}


function FocusBasket()
{
	basketWindow = window.open("/webnative/basketcontrol", "basketWindow", "toolbar=no,resizable=yes,scrollbars=yes,width=600,height=600")
	basketWindow.focus()
	return true
}

function printsmallview(f,uinfo,descend, framedoc, target, extra, imgname, fref, controlFrame)
{
	if(!framedoc) {
		framedoc = document;
 	}

        if(!target) {
		target = "_self";
        }

	if(!extra) {
		extra = "";
	}

	if(!imgname) {
		imgname = "";
	}

	if( !controlFrame ) {
		controlFrame = "window";
	}

	var w = 32
	var h = 32
	var m = false;
	if (f.smallweb) {
		w = f.smallweb.width
		h = f.smallweb.height
	} else if( f.isadir ) {
		w = wn_iconwidth;
		h = wn_iconheight;
        }

	if (f.creator == "p2ac") {
		framedoc.write("<A HREF='javascript:top.OpenAccWindow(\"" + f.path + "\")")
		m = lang.awin
	} else if ((f.numlinks > 0 || f.numpreviews >= 1 || f.type == "XDOC" || f.type == "XPRJ") && (f.fileid || !f.archive)) {
		framedoc.write("<A ID='previewLink"+f.path+"' HREF='/webnative/mview?" + f.path)
		if( f.type == "XDOC" || f.type == "XPRJ" ) {
			m = lang.vquark
		} else {
			m = lang.vfile
		}
	} else if (f.creator == "InDn" && (f.type == "InDd" || f.type == "snDd" || f.type == "IDd3" || f.type == "IDd4" || f.type == "IDd5" || f.type == "IDd6") && (f.fileid || !f.archive)) {
		framedoc.write("<A HREF='/webnative/mview?" + f.path)
		m = lang.vindesign;
	} else if (f.archive && descend && !f.largeweb) {
		framedoc.write("<A HREF='/webnative/imageinfo?" + f.path)
		m = lang.iwin + f.name
	} else if (f.largeweb) {
		framedoc.write("<A HREF='/webnative/getimage?-web+");
		if( f.largeweb.dbfileid ) {
			framedoc.write("-id"+"+"+f.largeweb.dbfileid+"+");
		}
		framedoc.write(f.path)
		m = lang.bpre
	} else if ( isHtml(f) && allowDownload(f, uinfo) ) {
		framedoc.write("<A HREF='/webnative/streamfile?-html+" + f.path)
		m = lang.vhtml
	} else if (uinfo.highres) {
		// Stream the well-supporerted mime types 
		m = lang.vhtml;	
		sURL = streamURL(f.path,f.type);
 		if( sURL ) {
			framedoc.write("<A HREF='"+sURL);
		} else {
			m = false;
		}
	}
	if (m == false && descend){
		framedoc.write("<A HREF='/webnative/imageinfo?" + f.path)
		if (fref)
			m = lang.dview 
		else
			m = lang.iwin + f.name
	}

	if (m != false && fref) {
		if( fref.v2 ) {
			framedoc.write("' onMouseOver='" + controlFrame + ".showMessage( "+ fref.docPath +", \""+fref.spanID+"\", \"" + m + "\")' onMouseOut='" + controlFrame + ".showMessage( "+ fref.docPath +", \""+fref.spanID+"\", \"\")' "+extra+" TARGET='"+target+"'>")
		} else {
			framedoc.write("' onMouseOver='" + fref + ".value=\"" + m + " \"; return true' onMouseOut='" +fref + ".value=\"\"; return true;' "+extra+" TARGET='"+target+"'>")
		}
	} else if (m != false)
		framedoc.write("' onMouseOver='window.status=\"" + m + " \"; return true' "+extra+" TARGET='"+target+"'>")
	framedoc.write("<IMG "+imgname+" ID='previewImg"+f.path+"' BORDER=0 ");
	if (!f.archive || !f.archive.pict) {
		framedoc.write(" HEIGHT=" + h + " WIDTH=" + w)
	}
	framedoc.write(" SRC='/webnative") 
	if ((f.archive && f.archive.pict) && !(f.fileid && f.smallweb)){
		framedoc.write("/archivepict?-o+" + f.archive.offset + "+-l+" + f.archive.pict + "+" + f.archive.name + "+" + f.archive.number + "+" + f.path)
	} else if (f.smallweb) {
		framedoc.write("/getimage?-small+");
		if( f.smallweb.dbfileid ) {
			framedoc.write("-id"+"+"+f.smallweb.dbfileid+"+");
		}
		framedoc.write(f.path);
	} else if (f.isadir) {
		framedoc.write("doc/images/"+wn_icondirpath+"wn_folder.gif");
	} else {
		framedoc.write("/webicon?")
		if (f.archive) {
			framedoc.write("-off+")
		}
		if (f.custicon) {
			framedoc.write(f.path)
		} else {
			framedoc.write("-T+" + hexStr(f.type) + "+-C+" + hexStr(f.creator))
		}
	}
	if(m != false)
		framedoc.write("' ALT='" + m + "'></A>");
	else
		framedoc.write("' ALT='" + f.name + "'>");
        
}

function prettybigsize(bytes)
{
	if (bytes == 0) {
		return("0 bytes")
	}
	if (bytes < 1048576) {
		return( Math.round(bytes/1024) + " " + lang.kbyte);
	} else if (bytes < 1073741824) {
		return(Math.round(bytes / 1048576) + " " + lang.mbyte);
	} else {
		return(Math.round(bytes / 1073741824) + " " + lang.gbyte);
	}
}



function streamFile(path,type) {
	var sURL = streamURL(path,type);
	if( sURL ) {
		window.open(sURL,"streamWin");
	}
}

function streamURL(path,type) {
	var base = "/webnative/streamfile?-cd+"
	var extension = path.substr( path.lastIndexOf(".") )
	var typeMap = new Array()
	var extMap = new Array()
	
	if( extension.length != 4 && extension.length != 5 ) {
		extension = ""
	} else {
		extension = extension.toLowerCase()
	}

	extMap[".pdf"] = "-pdf"
	extMap[".gif"] = "image/gif"
	extMap[".mov"] = "video/quicktime"
	extMap[".wav"] = "audio/x-wav"
	extMap[".aiff"] = "audio/x-aiff"
	extMap[".aif"] = "audio/x-aiff"
	extMap[".mid"] = "audio/x-midi"
	extMap[".midi"] = "audio/x-midi"
	extMap[".mpg"] = "video/mpeg"
	extMap[".mpeg"] = "video/mpeg"
	extMap[".mp3"] = "audio/mp3"
	extMap[".mp4"] = "video/mp4"
	extMap[".asf"] = "video/x-ms-asf"
	extMap[".wmv"] = "video/x-ms-wmv"
	extMap[".ra"] = "application/vnd.rn-realmedia"
	extMap[".rm"] = "application/vnd.rn-realmedia"

	if( extMap[extension] ) {
		return base + extMap[extension] + "+" + path
	}

	typeMap["PDF "] = "-pdf"
	typeMap["GIF "] = "image/gif"
	typeMap["MooV"] = "video/quicktime"
	typeMap["WAVE"] = "audio/x-wav"
	typeMap["AIFC"] = "audio/x-aiff"
	typeMap["Midi"] = "audio/x-midi"
	typeMap["MPEG"] = "audio/mpeg"
	typeMap["Mp3 "] = "audio/mp3"
	typeMap["MPG3"] = "audio/mp3"
	typeMap["VfW "] = "video/x-msvideo"
	typeMap["PNRA"] = "application/vnd.rn-realmedia"
	typeMap["PNRM"] = "application/vnd.rn-realmedia"

	if( typeMap[type] ) {
		return base + typeMap[type] + "+" + path
	} else {
		return false
	}

}

function printFileName(f,framedoc,sourceFrameName,streamEnabled, targ) {
	var doStream = (f.type == "PDF " && streamEnabled && !f.archive );
	if (f.type == "PDF ")
		var str = lang.ppdf;
	else
		var str = lang.vhtml;
	// we link PDFs to enable streaming.
	if( !sourceFrameName ) {
		sourceFrameName = "window";
	}
	if( doStream ) {
		framedoc.write("<A HREF='' onClick='"+sourceFrameName+".streamFile(\""+f.path+"\",\""+f.type+"\"); return false;'") 
		if (targ)
			framedoc.write("' onMouseOver='" + targ + ".value="+sourceFrameName+".removeHTMLEnts(\"" + str + " \"); return true' onMouseOut='" + targ + ".value=\"\"; return true;'>");
		else 
			framedoc.write("onMouseOver='window.status="+sourceFrameName+".removeHTMLEnts(\""+str+"\");return true;' onMouseOut='window.status=\"\"; return true;'>");
	}
	framedoc.write(filterLongName(f.name));
	if( doStream ) {
		framedoc.writeln("</A>");
	}	
}

function isDef(variable) {
  if( !variable && variable != 0 && variable != "" ) {
    return false;
  }
  return true;
}

function n2sz(number, digitCount) 
{
  if (!number) {
	var zeros = "0000000000000000000";
	return zeros.substr(0, digitCount);
  }

  var results = "";
  number  = new Number(number);
  results = new String(number+Math.pow(10,digitCount));
  results = results.substr(results.length - digitCount);
  return results;
}

function makeDateString(dateObj) {
  return (isDef(dateObj.year)?n2sz(dateObj.year,4):"0000") +"-"+
         (isDef(dateObj.month)?n2sz(dateObj.month,2):"00")+"-"+
         (isDef(dateObj.day)?n2sz(dateObj.day,2):"00")+" "+
	 (isDef(dateObj.hour)?n2sz(dateObj.hour,2):"00")+":"+
	 (isDef(dateObj.minute)?n2sz(dateObj.minute,2):"00")+":"+
	 (isDef(dateObj.second)?n2sz(dateObj.second,2):"00");
}


function DateObj(dateString) {
  this.year   = new Number(dateString.substring(0,4));
  this.month  = new Number(dateString.substring(5,7));
  this.day    = new Number(dateString.substring(8,10));
  this.hour   = new Number(dateString.substring(11,13));
  this.minute = new Number(dateString.substring(14,16));
  this.second = new Number(dateString.substr(17));
}

// Time is zero'ed for today button
function jsDate2DateString(today) 
{
    var dateString = "";

    var date    = n2sz(today.getDate(), 2);
    var month   = n2sz(today.getMonth()+1, 2);
    var year    = today.getYear();
    var hours   = "12"; //n2sz(today.getHours(), 2);
    var minutes = "00"; //n2sz(today.getMinutes(), 2);
    var seconds = "00"; //n2sz(today.getSeconds(), 2);

    if (year < 2000) {
	if (year > 100) {
	    year += 1900;
	} else {
	    year += 2000;
	}
    }

    dateString = year+"-"+month+"-"+date+" "+hours+":"+minutes+":"+seconds;
    return dateString;
}


function addDefaultIfEmpty(keyObj, digits) {
	return "<OPTION VALUE='"+n2sz(0,digits)+"' "+((!isDef(keyObj.value))?"SELECTED":"")+">\n";
}

function buildDateComponentSelect(varName, beginEndIndex, endIndex, keyObj, keyObjIndex, optionValues, optionDescs, selectedIndex, digits) {
  var results = "";
  if( beginEndIndex ) {
    results += varName+".value.substring(0,"+beginEndIndex+")";
  } 
  if( endIndex < 20 ) {
    if( beginEndIndex ) {
      results += "+";
    }
    results += "this.options[this.selectedIndex].value+"+varName+".value.substr("+endIndex+")"
  }
  results += "' NAME='date"+keyObj.id+"_"+keyObjIndex+"' ID='"+varName+"_date"+keyObj.id+"_"+keyObjIndex+"'>\n";
  results += addDefaultIfEmpty(keyObj, digits);
  for( var j = 0; j < optionValues.length; ++j ) {
    results += "<OPTION VALUE='"+optionValues[j]+"'"+((selectedIndex==j)?" SELECTED":"")+">"+optionDescs[j]+"\n";
  }
  return results;
}


//Set These Variables in the local style to change the year range of the popup
var dateControlYears = 25;
var dateControlYearsAhead = 10;

function buildDateControl(keyObj, varName, forceGUI, noEdit) {
  var today = new Date();
  var monthsShort =  [ lang.jan,lang.feb,lang.mar,
                       lang.apr,lang.mayshort,lang.jun,
		       lang.jul,lang.aug,lang.sep,
		       lang.oct,lang.nov,lang.dec ];
  var monthsLong =   [ lang.january,lang.february,lang.march,
                       lang.april,lang.may,lang.june,
		       lang.july,lang.august,lang.september,
		       lang.october,lang.november,lang.december ];
  var weekdayShort = [ lang.sun,lang.mon,lang.tue,lang.wed,lang.thu,lang.fri,lang.sat ];
  var weekdayLong =  [ lang.sunday,lang.monday,lang.tuesday,lang.wednesday,lang.thursday,lang.friday,lang.saturday ];
  var monthsInt2 = new Array(); for(i = 1; i < 13; ++i) monthsInt2[i-1] = n2sz(i,2);
  var monthsIntVar = new Array(); for(i = 1; i < 13; ++i) monthsIntVar[i-1] = new String(i);
  var yearInt2 = new Array(); for(i = 0; i < dateControlYears; ++i) yearInt2[i] = n2sz(today.getFullYear()-(i-dateControlYearsAhead),2);
  var yearInt4 = new Array(); for(i = 0; i < dateControlYears; ++i) yearInt4[i] = n2sz(today.getFullYear()-(i-dateControlYearsAhead),4);
  var dayInt2 = new Array(); for(i = 1; i < 32; ++i) dayInt2[i-1] = n2sz(i,2);
  var dayIntVar = new Array(); for(i = 1; i < 32; ++i) dayIntVar[i-1] = new String(i);
  var hoursInt2 = new Array(); for(i = 0; i < 24; ++i) hoursInt2[i] = n2sz(i,2);
  var minsecInt2 = new Array(); for(i = 0; i < 60; ++i) minsecInt2[i] = n2sz(i,2);
  
  var datePieces = keyObj.display.split("%");
  var results = "";
  var wasBlank = false;

  var monthSelectID = 0;
  var dateSelectID = 0;
  var yearSelectID = 0;
  var hourSelectID = 0;
  var minSelectID = 0;
  var secSelectID = 0;
  var ampmSelectID = 0;
  var hasAMPM = 0
  
  if( !isDef(keyObj.date) )  {
      wasBlank = true;
      keyObj.date = (keyObj.value) ? new DateObj(keyObj.value) : new Object();
  }

  if (!keyObj.editable && !forceGUI) {
    noEdit = true;
  } 

  if( !keyObj.editable && !noEdit ) {
    if( !isDef(keyObj.dates) ) {
      keyObj.dates = new Array(0);
    }

    results += "<SELECT NAME='"+varName+"'>";
    if (wasBlank)
	results += "<OPTION VALUE=''></OPTION>";
    for( var i = 0; i < keyObj.dates.length; ++i ) {
      results += "<OPTION VALUE='"+makeDateString(keyObj.dates[i])+"'";
      if( keyObj.dbvalue == keyObj.dbvalues[i] ) {
        results += " SELECTED";
      }
      results += ">"+keyObj.values[i];
    }
    results += "</SELECT>\n";

  } else if( !noEdit || !wasBlank ) {

    if( !noEdit ) {
      results = "<INPUT TYPE=hidden NAME='"+varName+"' VALUE='"+makeDateString(keyObj.date)+"'>\n";
    }

    for( var i = 0; i < datePieces.length; ++i ) {
      if( datePieces[i] != "" ) {
        var selected = 0;
	var formatChar = datePieces[i].charAt(0) 

	if( !noEdit && formatChar != "W") {
          results += "<SELECT ";
          results += "onChange='";
          results += "if( (this.selectedIndex == 0) && "+wasBlank+") {";
          results += "  "+varName+".value = \"\";";
          results += "} else if ( ("+varName+".value ==\"\") && (this.selectedIndex > 0) ) {";
          results += "  "+varName+".value = \"0000-00-00 00:00:00\";";
          results += "}";
          results += varName+".value=";
	}
	switch( formatChar ) {
        case 'M': /* full month name */
    	  selected = keyObj.date.month-1;
          results += (noEdit) ? monthsLong[selected] : 
			buildDateComponentSelect(varName, 5, 7, keyObj, i, monthsInt2, monthsLong, selected, 2);
	  monthSelectID = varName+"_date"+keyObj.id+"_"+i;
          break;
        case 'Y': /* 4-digit year */
          selected = Math.abs(today.getFullYear()-keyObj.date.year+dateControlYearsAhead)
          results += (noEdit) ? yearInt4[selected] :
			buildDateComponentSelect(varName, 0, 4, keyObj, i, yearInt4, yearInt4, selected, 4);
	  yearSelectID = varName+"_date"+keyObj.id+"_"+i;
          break;
        case 'y': /* 2-digit year */
	  selected = Math.abs(today.getFullYear()-keyObj.date.year+dateControlYearsAhead);
          results += (noEdit) ? yearInt2[selected] :
			buildDateComponentSelect(varName, 0, 4, keyObj, i, yearInt4, yearInt2, selected, 4);
	  yearSelectID = varName+"_date"+keyObj.id+"_"+i;
          break;
        case 'd': /* 2-digit day */
	  selected = keyObj.date.day-1;
          results += (noEdit) ? dayInt2[selected] : 
			buildDateComponentSelect(varName, 8, 10, keyObj, i, dayInt2, dayInt2, selected, 2);
	  dateSelectID = varName+"_date"+keyObj.id+"_"+i;
          break;
        case 'e': /* variable-digit day */
	  selected = keyObj.date.day-1;
          results += (noEdit) ? dayIntVar[selected] :
			buildDateComponentSelect(varName, 8, 10, keyObj, i, dayInt2, dayIntVar, selected, 2);
	  dateSelectID = varName+"_date"+keyObj.id+"_"+i;
          break;
        case 'm': /* 2-digit month */
	  selected = keyObj.date.month-1;
          results += (noEdit) ? monthsInt2[selected] :
			buildDateComponentSelect(varName, 5, 7, keyObj, i, monthsInt2, monthsInt2, selected, 2);
	  monthSelectID = varName+"_date"+keyObj.id+"_"+i;
          break;
        case 'c': /* variable-digit month */
	  selected = keyObj.date.month-1;
          results += (noEdit) ? monthsIntVar[selected] :
			buildDateComponentSelect(varName, 5, 7, keyObj, i, monthsInt2, monthsIntVar, selected, 2);
	  monthSelectID = varName+"_date"+keyObj.id+"_"+i;
          break;
        case 'b': /* abbr. month name */
	  selected = keyObj.date.month-1;
          results += (noEdit) ? monthsShort[selected] :
			buildDateComponentSelect(varName, 5, 7, keyObj, i, monthsInt2, monthsShort, selected, 2);
	  monthSelectID = varName+"_date"+keyObj.id+"_"+i;
          break;
        case 'r': /* hh:mm:ss [AP]M */
          hasAMPM++;
	  if( noEdit ) {
	    results += (keyObj.date.hour == 0) ? 12 : ( (keyObj.date.hour > 12) ? keyObj.date.hour-12 : keyObj.date.hour ) + ":";
            results += keyObj.date.minute + ":" + keyObj.date.second + " ";
            results += (keyObj.date.hour >= 12) ? "PM" : "AM";
	  } else {
            results += "("+varName+".value.substring(0,11)+(((date"+keyObj.id+"_"+i+"_4.selectedIndex!=1)?(12+new Number(this.options[this.selectedIndex].value)):this.options[this.selectedIndex].value))+"+varName+".value.substr(13))'"
    	    results += " NAME='date"+keyObj.id+"_"+i+"_1' ID='" + varName + "_date"+keyObj.id+"_"+i+"_1'>";
  	    results += addDefaultIfEmpty(keyObj, 2);
            results += "<OPTION VALUE='0'"+((keyObj.date.hour == 12 || keyObj.date.hour == 0)?" SELECTED":"")+">12";
            for( var j = 1; j < 12; ++j ) {
	      results += "<OPTION VALUE='"+n2sz(j,2)+"'";
              if( keyObj.date.hour < 13 ) {
                results += ((keyObj.date.hour == j)?" SELECTED":"")
              } else {
                results += (( (keyObj.date.hour-12) ==j)?" SELECTED":"")
              }
              results += ">"+n2sz(j,2);
            }        
	    results += "</SELECT>:";
	    hourSelectID = varName+"_date"+keyObj.id+"_"+i+"_1";

            results += "<SELECT onChange='"+varName+".value=";
            results += buildDateComponentSelect(varName, 14, 16, keyObj, i+"_2", minsecInt2, minsecInt2, keyObj.date.minute, 2);
	    results += "</SELECT>:";
	    minSelectID = varName+"_date"+keyObj.id+"_"+i+"_2";
            results += "<SELECT onChange='"+varName+".value=";
            results += buildDateComponentSelect(varName, 17, 19, keyObj, i+"_3", minsecInt2, minsecInt2, keyObj.date.second, 2);
	    results += "</SELECT>&nbsp;";
	    secSelectID = varName+"_date"+keyObj.id+"_"+i+"_3";
            results += "<SELECT onChange='"+varName+".value=";
            results += "("+varName+".value.substring(0,11)+(((this.selectedIndex==1)?(date"+keyObj.id+"_"+i+"_1.options[date"+keyObj.id+"_"+i+"_1.selectedIndex].value):(12+(new Number(date"+keyObj.id+"_"+i+"_1.options[date"+keyObj.id+"_"+i+"_1.selectedIndex].value)))))+"+varName+".value.substr(13))'"
  	    results += " NAME='date"+keyObj.id+"_"+i+"_4' ID='" + varName + "_date"+keyObj.id+"_"+i+"_4'>";

	    ampmSelectID = varName+"_date"+keyObj.id+"_"+i+"_4";
	    results += addDefaultIfEmpty(keyObj, 2);
  	    results += "<OPTION VALUE='AM'"+((keyObj.date.hour<12)?" SELECTED":"")+">AM";
	    results += "<OPTION VALUE='PM'"+((keyObj.date.hour>=12)?" SELECTED":"")+">PM";
	  }
          break;
        case 'T': /* hh:mm:ss */
          if( noEdit ) {
	    results +=  keyObj.date.hour + ":" + keyObj.date.minute + ":" + keyObj.date.second;
	  } else {
            results += buildDateComponentSelect(varName, 11, 13, keyObj, i+"_1", hoursInt2, hoursInt2, keyObj.date.hour, 2);
	    results += "</SELECT>:";
	    hourSelectID = varName+"_date"+keyObj.id+"_"+i+"_1";
            results += "<SELECT onChange='"+varName+".value=";
            results += buildDateComponentSelect(varName, 14, 16, keyObj, i+"_2", minsecInt2, minsecInt2, keyObj.date.minute, 2);
	    results += "</SELECT>:";
	    minSelectID = varName+"_date"+keyObj.id+"_"+i+"_2";
            results += "<SELECT onChange='"+varName+".value=";
            results += buildDateComponentSelect(varName, 17, 19, keyObj, i+"_3", minsecInt2, minsecInt2, keyObj.date.second, 2);
	    secSelectID = varName+"_date"+keyObj.id+"_"+i+"_3";
          }
          break;
        case 'W': 
	  if (isDef(keyObj.date.dayname)) {
	      // Handle numeric days 
	      if (keyObj.date.dayname >= '0' && keyObj.date.dayname < '7') {
		  results += weekdayLong[keyObj.date.dayname];
	      } else {
		  results += keyObj.date.dayname;
	      }
          } else {
	    datePieces[i] = ""
	  }
           
        default:
          break;
        }
        if( !noEdit && formatChar != "W" ) {
          results += "</SELECT>\n";
        }
        if( datePieces[i].length > 1 ) {
          results += datePieces[i].substr(1);
        }
      }
    }
    if (!noEdit) {
	    // Draw the today button to set today's date
	    // Commented values set the time as well, see jsDate2DateString as well
	    results += "<INPUT TYPE=button VALUE='"+lang.today+"' ONCLICK='";
	    results += varName+".value=\""+jsDate2DateString(today)+"\";";
	    if(yearSelectID) 
		results += "document.getElementById(\""+yearSelectID+"\").value=\""+n2sz(today.getFullYear(),4)+"\";";
	    if(monthSelectID)
		results += "document.getElementById(\""+monthSelectID+"\").value=\""+n2sz(today.getMonth()+1,2)+"\";";
	    if(dateSelectID)
		results += "document.getElementById(\""+dateSelectID+"\").value=\""+n2sz(today.getDate(),2)+"\";";
	    if(hourSelectID) {
		 results += "document.getElementById(\""+hourSelectID+"\").options[1].selected = true;"; 

		 if(ampmSelectID) {
		     results += "document.getElementById(\""+ampmSelectID+"\").value=\"PM\";";
		 }
		 if(minSelectID) {
		     results += "document.getElementById(\""+minSelectID+"\").options[1].selected = true;"; 
		 }
		 if(secSelectID) {
		     results += "document.getElementById(\""+secSelectID+"\").options[1].selected = true;"; 
		 }
	    }
	    results += "'>\n";
    }
  }
  return results;  
}

function setkeywordperms(thingy, search, limited, locked, hidden, showdata, upload, uploadrequired)
{
	thingy.savexmp = (thingy.editable & 2) || (thingy.fixed && thingy.editable);
	thingy.search = search;
	thingy.limited = limited;
	thingy.locked = locked;
	thingy.editable = locked?0:1;
	thingy.hidden = hidden;
	thingy.showdata = showdata;
	thingy.upload = upload;
	thingy.uploadrequired = uploadrequired;
	thingy.fixed = locked; // deprecated
}


function fixDocCharset(thedoc) {
  if( isWindows && (isIE4OrBetter && !isIE6OrBetter) && thedoc.charset ){
      thedoc.charset = LanguageCharset;
  }   
}

function strfriendly(str) {
	var nicestr = "";
	var c;
	for (var i = 0; i < str.length; i++) {
		c = str.charAt(i);
		if (c == '\'' || c == '"' || c == '`')
			nicestr += '\\';
		nicestr += c;
	}
	return (nicestr);
}

var isNav          = (navigator.appName.indexOf("Netscape") > -1);
var isIE           = (navigator.appName.indexOf("Explorer") > -1);
var isSafari       = (navigator.appVersion.indexOf("Safari") > -1);
var isFirefox      = (navigator.userAgent.indexOf("Firefox") > -1);
if (navigator.userAgent.indexOf("Mozilla") > -1) isFirefox=1;

var begin           = isIE ? (navigator.appVersion.indexOf("MSIE")+5) : 0;
var end             = navigator.appVersion.indexOf('.',begin);
var appVersionMajor = new Number(navigator.appVersion.substring(begin,(end>-1) ? end : navigator.appVersion.length-1));

var isNav4OrBetter = isNav && (appVersionMajor >= 4);
var isNav5OrBetter = isNav && (appVersionMajor >= 5);
var isNav6OrBetter = isNav && (appVersionMajor >= 6);
var isIE4OrBetter  = isIE && (appVersionMajor >= 4);
var isIE5OrBetter  = isIE && (appVersionMajor >= 5);
var isIE6OrBetter  = isIE && (appVersionMajor >= 6);

var isWindows = (navigator.platform.indexOf("Win") >= 0); 
var isUnix    = (navigator.platform.indexOf("nix") >= 0); 
var isMac     = (navigator.platform.indexOf("Mac") >= 0); 
var isMacOSX  = (navigator.userAgent.indexOf("OS X") >= 0) || (navigator.userAgent.indexOf("MSIE 5.23") >= 0); 

function getKeywordName(keyObj) {
  var keyname = eval("lang.keyword"+keyObj.id);
  if(keyname) {
    return keyname; 
  }
  return keyObj.name;
}

function
numbersonly(evt)
{
	evt = (evt) ? evt : event;
	var charcode = (evt.charCode) ? evt.charCode : 
		((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	if (charcode > 31 && (charcode < 45 || charcode > 57)) {
		alert(removeHTMLEnts(lang.numbersonly));
		return false;
	}
	return true;
}

function
integeronly(evt)
{
	evt = (evt) ? evt : event;
	var charcode = (evt.charCode) ? evt.charCode : 
		((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	if (charcode > 31 && (charcode < 48 || charcode > 57) && charcode != 45) {
		alert(removeHTMLEnts(lang.integersonly));
		return false;
	}
	return true;
}

/* A filename cannot conatin any of the following characters 
 * 	\ / : * ? " < > | ' `
 */
function
filenamecharsonly(evt)
{
	evt = (evt) ? evt : event;
	var charcode = (evt.charCode) ? evt.charCode : 
		((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	if (charcode > 31 && 
	    (charcode==92 || charcode==47 || charcode==42 || charcode==96 ||
	     charcode==63 || charcode==34 || charcode==60 || charcode==62 ||
	     charcode==33 || charcode==58 || charcode==39 || charcode >126)) {
		alert(removeHTMLEnts(lang.filenamecharsonly));
		return false;
	}
	return true;
}

/* A filename cannot conatin any of the following characters 
 * ' "
 */
function
dbnamecharsonly(evt)
{
	evt = (evt) ? evt : event;
	var charcode = (evt.charCode) ? evt.charCode : 
		((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	if (charcode > 31 && 
	    (charcode==34 || charcode==39 || charcode==96 || charcode >126)) {
		alert(removeHTMLEnts(lang.dbnamecharsonly));
		return false;
	}
	return true;
}

// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
function autoComplete (field, select, property, forcematch) {
	var found = false;
	for (var i = 0; i < select.options.length; i++) {
		if (select.options[i][property].toUpperCase().indexOf(field.value.toUpperCase()) == 0) {
			found=true; break;
		}
	}
	if (found) { select.selectedIndex = i; }
	else { select.selectedIndex = -1; }
	if (field.createTextRange) {
		if (forcematch && !found) {
			field.value=field.value.substring(0,field.value.length-1); 
			return;
		}
		var cursorKeys ="8;46;37;38;39;40;33;34;35;36;45;";
		if (cursorKeys.indexOf(event.keyCode+";") == -1) {
			var r1 = field.createTextRange();
			var oldValue = r1.text;
			var newValue = found ? select.options[i][property] : oldValue;
			if (newValue != field.value) {
				field.value = newValue;
				var rNew = field.createTextRange();
				rNew.moveStart('character', oldValue.length) ;
				rNew.select();
			}
		}
	}
}

// The custname will replace the default "keywordX" 
function drawdatafield_old(doc, keyword, noedit, newvalue, newhtmlvalue, custname) {
	var valueBackup = (isDef(newvalue) && (newvalue != null)) ? keyword.value : null;
	var htmlvalueBackup = (isDef(newhtmlvalue) && (newhtmlvalue != null)) ? keyword.htmlvalue : null;

	fieldname = (custname ? custname : "keyword"+keyword.id); 
	if( valueBackup != null ) {
		keyword.value = newvalue;
		keyword.htmlvalue = newhtmlvalue;
	}

	if (keyword.editable && !noedit) {

		switch (keyword.type) {
		case 12: //TYPEDATETIME:
			doc.writeln(buildDateControl(keyword, fieldname, false, noedit));
			break;
		case 253:// STRING
		case 1: //TYPETINY:
		case 2: //TYPESHORT:
		case 3: //TYPELONG:
		case 4: //TYPEFLOAT:
		case 5: //TYPEDOUBLE:
		case 8: //TYPEBIGINT
		case 104: //TYPEDECIMAL:
		case 105: //TYPEINTMAP:
//  			if (keyword.fixed) {
//  				var str = "";
//  				if( keyword.htmlvalue && keyword.htmlvalue.replace ) {
//  					// parse for new lines
//    					var regex = new RegExp ('\\r', 'g');
//    				        str = keyword.htmlvalue.replace(regex, '<br>');
//  				} else {
//  					str = keyword.htmlvalue;
//  				}
//  				doc.writeln(str);
//  			} else 
			if (keyword.limited == 1) {
				if (keyword.valuescount) {
					dovaluepopup(doc, keyword.id, keyword.values, keyword.valuescount, keyword.value, false, keyword.value, keyword.values, fieldname);
				} else {
					doc.writeln(keyword.value);
				}
			} else {
				if (keyword.rows > 1) {
					doc.write("<TEXTAREA NAME='"+fieldname+"'");
					doc.write(" ROWS="+keyword.rows);
					doc.write(" COLS="+keyword.cols);
					doc.write(" SIZE="+keyword.size);
					doc.write(" MAXLEN="+keyword.size);
					doc.write(">"+keyword.value+"</TEXTAREA>");
				} else {
					doc.writeln("<INPUT TYPE='text' ID='"+fieldname+"' NAME='"+fieldname+"' SIZE="+keyword.cols+" MAXLEN="+keyword.size+" VALUE=\""+deQuotify(keyword.value)+"\"");
					if (keyword.type != 253) {
					    if (keyword.type == 4 || keyword.type == 5 || keyword.type == 104) {
						doc.write(" onkeypress=\"return numbersonly(event)\"");
					    } else {
						doc.write(" onkeypress=\"return integeronly(event)\"");
					    }
					}
					if (keyword.limited == 2) {
					    doc.write(" onkeyup=\"autoComplete(this, this.form."+fieldname+"popup,'text', false)\"");
					}
					doc.writeln(">");
				}
				if (keyword.limited == 2) {
					if (keyword.valuescount) {
						var onchange = "this.form."+fieldname+".value=this.options[this.selectedIndex].value";
						var skipval = false;
						if (!keyword.valueflags & 1) {
							skipval = true;
						}
						dovaluepopup(doc, keyword.id, keyword.values, keyword.valuescount, keyword.value, false, keyword.value, keyword.values, fieldname+"popup", onchange, skipval);

					}
				}

			}
			break;

		case 100: // Boolean:
			boolitems = keyword.display.split('/');
			if (boolitems.length != 2) {
				boolitems = new Array(2);
				boolitems[0] = lang.truestr;
				boolitems[1] = lang.falsestr;
			}
//  			if (keyword.fixed) {
//  				if (keyword.value == 1)
//  					doc.writeln(boolitems[0]);
//  				else if (keyword.value == 0)
//  					doc.writeln(boolitems[1]);
//  			} else {
				if (keyword.display == 'checkbox') {
					doc.writeln("<INPUT TYPE='hidden' NAME='"+fieldname+"' VALUE=\""+((keyword.value == 1) ? 1 : 0)+"\">");
					doc.write("<INPUT TYPE='checkbox' NAME='checkbox"+keyword.id+"'");
					if (keyword.value == 1) {
						doc.write(" CHECKED");
					}
					doc.writeln(" OnClick='if("+fieldname+".value==1) "+fieldname+".value = 0; else "+fieldname+".value = 1;'>");
				} else {
					doc.writeln("<SELECT NAME='"+fieldname+"'>");
					doc.write("<OPTION VALUE=1");
					if (keyword.value == 1)
						doc.write(" SELECTED");
					doc.writeln(">"+boolitems[0]+"</OPTION>");
					doc.write("<OPTION VALUE=0");
					if (keyword.value == 0)
						doc.write(" SELECTED");
					doc.writeln(">"+boolitems[1]+"</OPTION>");
					doc.writeln("</SELECT>");
				}
//			}
		break;
		}
	} else {
		if (keyword.type == 100) {
			var trueValue = null;
			var falseValue = null;
			if( keyword.display == 'checkbox' ) {
				trueValue = "X";
				falseValue = "-";
			} else {
				var booleanValues = keyword.display.split("/");
				if( booleanValues.length != 2 ) {
					trueValue = lang.truestr;
					falseValue = lang.falsestr;
				} else {
					trueValue = booleanValues[0];
					falseValue = booleanValues[1];
				}					
			}
			if( keyword.value == 1 || keyword.value == "on" || keyword.value == true ) {
				doc.writeln(trueValue);
			} else {
				doc.writeln(falseValue);
			}
		} else {
			var str= isDef(keyword.htmlvalue) ? keyword.htmlvalue : keyword.value;
  			if (keyword.type == 253) {
  				var regex = new RegExp ('\\r', 'g');
  			        str = str.replace(regex, '<br>');
  			}
			doc.writeln(str);
		}
	}

	if( valueBackup != null ) {
		keyword.value = valueBackup;
		keyword.htmlvalue = htmlvalueBackup;
	}
}

/* This is a little different in that it will add the vname 
 * if it doesn't exist */
function dovaluepopup_old(doc, keyword_id, varray, num, vname, dosubmit, vhtmlname, vhtmlarray, fieldname, onchange, skipval)
{
	var i = 0;
	var x = 0;
	var found = false;

	if (vname) {
		for (i = 0; i < num; i++) {
			if (vname == varray[i]) {
				found = true;
			}
		}
	}	
	doc.write("<SELECT id='"+fieldname+"' name='"+fieldname+"'");
	if (dosubmit)
		doc.write(" onChange='submit()'");
	else if (onchange != '') {
		doc.write(" onChange='"+onchange+"'");
	}
	doc.writeln(">");
	
	if (!found && !skipval) {
		doc.writeln("<OPTION value=\""+deQuotify(vname)+"\" SELECTED>"+vhtmlname+"</OPTION>");
	} else {
		doc.writeln("<OPTION value=''>&nbsp;</OPTION>");
	}
	for (i = 0; i < num; i++) {
		doc.write("<OPTION value=\""+deQuotify(varray[i])+"\"");
		if (vname == varray[i]) {
			doc.write(" SELECTED");
			x = i;
		}
		doc.writeln(">"+vhtmlarray[i]+"</OPTION>");
	}
	doc.writeln("</SELECT>");
	return x;
}

function drawdatafield (doc, keyword, noedit, newvalue, newhtmlvalue, custname) 
{
    doc.writeln(getdatafieldstr (keyword, noedit, newvalue, newhtmlvalue, custname));
}

// The custname will replace the default "keywordX" 
// This returns the datafield item in a string
function getdatafieldstr (keyword, noedit, newvalue, newhtmlvalue, custname) 
{
	var html = "";
	var valueBackup = (isDef(newvalue) && (newvalue != null)) ? keyword.value : null;
	var htmlvalueBackup = (isDef(newhtmlvalue) && (newhtmlvalue != null)) ? keyword.htmlvalue : null;

	fieldname = (custname ? custname : "keyword"+keyword.id); 
	if( valueBackup != null ) {
		keyword.value = newvalue;
		keyword.htmlvalue = newhtmlvalue;
	}

	if (keyword.editable && !noedit) {

		switch (keyword.type) {
		case 12: //TYPEDATETIME:
			html += buildDateControl(keyword, fieldname, false, noedit);
			break;
		case 253:// STRING
		case 1: //TYPETINY:
		case 2: //TYPESHORT:
		case 3: //TYPELONG:
		case 4: //TYPEFLOAT:
		case 5: //TYPEDOUBLE:
		case 8: //TYPEBIGINT
		case 104: //TYPEDECIMAL:
		case 105: //TYPEINTMAP:
//  			if (keyword.fixed) {
//  				var str = "";
//  				if( keyword.htmlvalue && keyword.htmlvalue.replace ) {
//  					// parse for new lines
//    					var regex = new RegExp ('\\r', 'g');
//    				        str = keyword.htmlvalue.replace(regex, '<br>');
//  				} else {
//  					str = keyword.htmlvalue;
//  				}
//  				html += str;
//  			} else 
			if (keyword.limited == 1) {
				if (keyword.valuescount) {
					html += getvaluepopupstr (keyword.id, keyword.values, keyword.valuescount, keyword.value, false, keyword.value, keyword.values, fieldname);
				} else {
					html += keyword.value;
				}
			} else {
				if (keyword.rows > 1) {
					html += "<TEXTAREA NAME='"+fieldname+"'";
					html += " ROWS="+keyword.rows;
					html += " COLS="+keyword.cols;
					html += " SIZE="+keyword.size;
					html += " MAXLEN="+keyword.size;
					html += ">"+keyword.value+"</TEXTAREA>";
				} else {
					html += "<INPUT TYPE='text' ID='"+fieldname+"' NAME='"+fieldname+"' SIZE="+keyword.cols+" MAXLEN="+keyword.size+" VALUE=\""+deQuotify(keyword.value)+"\"";
					if (keyword.type != 253) {
					    if (keyword.type == 4 || keyword.type == 5 || keyword.type == 104) {
						html += " onkeypress=\"return numbersonly(event)\"";
					    } else {
						html += " onkeypress=\"return integeronly(event)\"";
					    }
					}
					if (keyword.limited == 2) {
					    html += " onkeyup=\"autoComplete(this, this.form."+fieldname+"popup,'text', false)\"";
					}
					html += ">";
				}
				if (keyword.limited == 2) {
					if (keyword.valuescount) {
						var onchange = "this.form."+fieldname+".value=this.options[this.selectedIndex].value";
						var skipval = false;
						if (!keyword.valueflags & 1) {
							skipval = true;
						}
						dovaluepopup(document, keyword.id, keyword.values, keyword.valuescount, keyword.value, false, keyword.value, keyword.values, fieldname+"popup", onchange, skipval);

					}
				}

			}
			break;

		case 100: // Boolean:
			boolitems = keyword.display.split('/');
			if (boolitems.length != 2) {
				boolitems = new Array(2);
				boolitems[0] = lang.truestr;
				boolitems[1] = lang.falsestr;
			}
//  			if (keyword.fixed) {
//  				if (keyword.value == 1)
//  					html += boolitems[0]);
//  				else if (keyword.value == 0)
//  					html += boolitems[1]);
//  			} else {
				if (keyword.display == 'checkbox') {
					html += "<INPUT TYPE='hidden' NAME='"+fieldname+"' VALUE=\""+((keyword.value == 1) ? 1 : 0)+"\">";
					html += "<INPUT TYPE='checkbox' NAME='checkbox"+keyword.id+"'";
					if (keyword.value == 1) {
						html += " CHECKED";
					}
					html += " OnClick='if("+fieldname+".value==1) "+fieldname+".value = 0; else "+fieldname+".value = 1;'>";
				} else {
					html += "<SELECT NAME='"+fieldname+"'>";
					html += "<OPTION VALUE=1";
					if (keyword.value == 1)
						html += " SELECTED";
					html += ">"+boolitems[0]+"</OPTION>";
					html += "<OPTION VALUE=0";
					if (keyword.value == 0)
						html += " SELECTED";
					html += ">"+boolitems[1]+"</OPTION>";
					html += "</SELECT>";
				}
//			}
		break;
		}
	} else {
		if (keyword.type == 100) {
			var trueValue = null;
			var falseValue = null;
			if( keyword.display == 'checkbox' ) {
				trueValue = "X";
				falseValue = "-";
			} else {
				var booleanValues = keyword.display.split("/");
				if( booleanValues.length != 2 ) {
					trueValue = lang.truestr;
					falseValue = lang.falsestr;
				} else {
					trueValue = booleanValues[0];
					falseValue = booleanValues[1];
				}					
			}
			if( keyword.value == 1 || keyword.value == "on" || keyword.value == true ) {
				html += trueValue;
			} else {
				html += falseValue;
			}
		} else {
			var str= isDef(keyword.htmlvalue) ? keyword.htmlvalue : keyword.value;
  			if (keyword.type == 253) {
  				var regex = new RegExp ('\\r', 'g');
  			        str = str.replace(regex, '<br>');
  			}
			html += str;
		}
	}

	if( valueBackup != null ) {
		keyword.value = valueBackup;
		keyword.htmlvalue = htmlvalueBackup;
	}

	return html;
}


function dovaluepopup(doc, keyword_id, varray, num, vname, dosubmit, vhtmlname, vhtmlarray, fieldname, onchange, skipval)
{
	doc.writeln(getvaluepopupstr(keyword_id, varray, num, vname, dosubmit, vhtmlname, vhtmlarray, fieldname, onchange, skipval));
}


/* This is a little different in that it will add the vname 
 * if it doesn't exist */
function getvaluepopupstr (keyword_id, varray, num, vname, dosubmit, vhtmlname, vhtmlarray, fieldname, onchange, skipval)
{
	var html = "";
	var i = 0;
	var x = 0;
	var found = false;

	if (vname) {
		for (i = 0; i < num; i++) {
			if (vname == varray[i]) {
				found = true;
			}
		}
	}	
	html += "<SELECT id='"+fieldname+"' name='"+fieldname+"'";
	if (dosubmit)
		html += " onChange='submit()'";
	else if (onchange != '') {
		html += " onChange='"+onchange+"'";
	}
	html += ">";
	
	if (!found && !skipval) {
		html += "<OPTION value=\""+deQuotify(vname)+"\" SELECTED>"+vhtmlname+"</OPTION>";
	} else {
		html += "<OPTION value=''>&nbsp;</OPTION>";
	}
	for (i = 0; i < num; i++) {
		html += "<OPTION value=\""+deQuotify(varray[i])+"\"";
		if (vname == varray[i]) {
			html += " SELECTED";
			x = i;
		}
		html += ">"+vhtmlarray[i]+"</OPTION>";
	}
	html += "</SELECT>";

	return html;
	
}



function makeDirPathList(wantEscaped) {
  var result = "";

  if( (window.dirs && window.dirs.length > 0) || (window.volumes && window.volumes.length > 0) ) {
    var end = window.dirs ? dircount : numvols;
    var list = window.dirs ? dirs : volumes;

    for( var i = 0; i < end; ++i ) {
      result += ("-dir" + (i+1) + "+" + (wantEscaped ? escape(list[i].path) : list[i].path));
      if( i < end-1 ) {
        result += "+";
      }
    }
  } else if( window.dir ) {
    result = wantEscaped ? escape(dir.path) : dir.path;
  } 
  return result;
}

function plusToSpace(s) {
  var result = "";

  for(var i = 0; i < s.length; ++i) {
    result += ( (s.charAt(i) == '+') ? ' ' : s.charAt(i) );
  }
  return result;
}

function escapePlus(s) {
  var result = "";

  result = escape(s)
  result = result.replace( /\+/g, "%2B")

  return result;
}

function deQuotify(s) {
  var result = "";
  s = s+"";
  for( var i = 0; i < s.length; ++i ) {
    result += ( (s.charAt(i) == '\"') ? "&quot;" : s.charAt(i) );
  }
  return result;
}

function OpenAccWindow(p)
{
	var newurl = "/webnative/plugins/acc_plug?" + p

	accWindow = window.open(newurl, "accWindow", 'toolbar=no,resizable=yes,scrollbars=yes')
	accWindow.focus()
}

var onChildOpened = null;
var onChildOpenedArgs = null;

function openBlankWindow(name, windowArgs, handlerFunction, funcArgs) {
	if( !name ) {
		name = "childWindow";
	}
	if( !windowArgs ) {
		windowArgs = "";
	}

	onChildOpened = handlerFunction;
	onChildOpenedArgs = funcArgs;
	window.open("/webnativedoc/doc/blank.html", name, windowArgs);
}

function writeBlankIFrame(width, height, handlerFunction, funcArgs) {
	onChildOpened = handlerFunction;
	onChildOpenedArgs = funcArgs;
	document.writeln("<IFRAME SRC='/webnativedoc/doc/blank.html' HEIGHT='"+height+"' WIDTH='"+width+"'></IFRAME>");
}

var loading = false;
function basketIsLoading() {
  var result = loading;
  if(result) {
    result = !confirm(removeHTMLEnts(lang.basketwait));
  }
  return result;
}


function filterLongName(filename, preserveBrackets) {
  var result = removeHTMLEnts(filename);

  if( result.length > 33 ) {
    result = result.substr(0,16) + '\u2026' + result.substr(result.length-16);
  }
  if( !preserveBrackets ) {
    result = result.replace("<", "&lt;");
    result = result.replace(">", "&gt;");
  }

  return result;
}

function ArchiveFormats() {
  this.FORMAT_COOKIE = "FORMAT_COOKIE";
  this.ZIP = 'zip';
  this.MACZIP = 'maczip';
  this.SIT = 'sit';
  this.UNCOMPRESSED_ZIP = 'uzip';
  this.UNCOMPRESSED_MACZIP = 'umaczip';
  this.formats = [ this.SIT, this.MACZIP, this.ZIP, this.UNCOMPRESSED_ZIP, this.UNCOMPRESSED_MACZIP ];
}

ArchiveFormats.prototype.getFormatDescriptions = function() {
  return [ lang.dlbstuffit, lang.dlbzipmac, lang.dlbzippc, lang.dlbuzippc, lang.dlbuzipmac ];
}

ArchiveFormats.prototype.getDescriptionFor = function(format) {
  var desc = this.getFormatDescriptions()
  for( var i = 0; i < this.formats.length; ++i ) {
    if( this.formats[i] == format ) {
      return desc[i];
    }
  }
  return ""
}

function getArchiveFormat() {
  var result = archiveFormats.ZIP;
  var cookie = getArchiveFormatCookie()

  if( cookie ) {
    result = cookie;
  } else {
    if( isMacOSX ) {
      result = archiveFormats.MACZIP;
    } else if( isMac ) {
      result = archiveFormats.SIT;
    }
  }

  return result;
}

function getArchiveFormatCookie() {
  var cookie = getCookie(archiveFormats.FORMAT_COOKIE);

  return cookie ? cookie : "";
}


var archiveFormats = new ArchiveFormats();

function getFormatDescription (format)
{
    var formatDescriptions = archiveFormats.getFormatDescriptions()
    for (var i = 0; i < archiveFormats.formats.length; i++) {
	if (format == archiveFormats.formats[i]) {
	    return formatDescriptions[i];
	}
    }
}

function drawArchFormatList(framedoc, inputName, omitHandler, value, dodefault) {
  var selected = value ? value : getArchiveFormat();
  var formatDescriptions = archiveFormats.getFormatDescriptions()

  framedoc.writeln("<SELECT NAME='"+inputName+"' ")
  if( !omitHandler ) {
    framedoc.writeln("onChange='setCookie(\""+archiveFormats.FORMAT_COOKIE+"\", this.options[this.selectedIndex].value, false)'")
  }
  framedoc.writeln(">");

  if (dodefault) {
      framedoc.write("<OPTION value=''");
      if (value == '') {
	  framedoc.write(" SELECTED");
	  selected = '';
      }
      framedoc.write(">"+lang.userperms.defaultstr+" ("+getFormatDescription(dodefault)+")</OPTION>");
  }

  for( var i = 0; i < archiveFormats.formats.length; ++i ) {
    framedoc.writeln("<OPTION VALUE='"+archiveFormats.formats[i]+"'"+ ( (selected == archiveFormats.formats[i]) ? " SELECTED": "" ) +">"+formatDescriptions[i]);
  }
  framedoc.writeln("</SELECT>");
}

function writeThirdPartyButtons(framedoc, file, args) {
  if( isDef(window.uinfo) && isDef(window.wnButtonManager) && isDef(window.wnStyleContext) ) {
    wnButtonManager.writeButtons(framedoc, file, uinfo, args, wnStyleContext);
  }
}

function allowDownload(file, permissions) {
	return !file.isadir && !file.archive && (permissions.highres || (permissions.allownonimages && !file.isimage));
}

function isHtml(f) {
	if (f.type == "R*ch")
		return true
	var n = f.name.toLowerCase()
	if (n.length > 4 && n.lastIndexOf(".htm") > (n.length - 6))
		return true
	return false
}

function extractUsername(name) {
	if( name.indexOf("\\") > -1 ) {
		name = name.substr( name.indexOf("\\") + 1 )
	}
	return name
}


function unixtime (jsdate) 
{
	return parseInt (jsdate.getTime() / 1000);
}

function unixtime2date (unixtime)
{
	var udate = new Date (unixtime*1000);
	return udate; 
}

