// initialize variables relevant to the current document.
//
// INPUTS (as "META" variables): 
//  * jmQovc = file name (relative path without extension, i.e. 'tnk1/ktuv/mjly/mj-01-01')
//  * author
//  * receiver
//
// OUTPUTS:
//  * path_from_site_to_document (path of document relative to site root)
//  * relative_depth (number of directories in path. a document in the root has depth 0.)
//  * absolute_document_url
//  * absolute_site_url
//  * path_from_document_to_site (of site)
//  * path_from_document_to_cgi
//  * path_from_site_to_cgi
//  * filepath_from_cgi_to_site
//  * linkpath_from_cgi_to_site
//
//  * site_name
//


//////////////   CONSTANTS   //////////////
var SUBSEQUENT_CLICKS_TO_EDIT = 5;
var LOCALIZATION_ATTRIBUTES = "dir=rtl lang=he";
var RTE_WIDTH_UNITS = "%";
var RTE_HEIGHT_UNITS = "px";
var RTE_WIDTH = 100;
var RTE_HEIGHT = 480;

var title_without_quotes = document.title.replace(/["]/,"").replace(/[']/,"");

var theBnim, theBnimArray, theWrittenBnim;  // should be defined in a <script> block afterwards


document.write("<DIV id=test></DIV>");
contentEditable = (document.getElementById("test")["contentEditable"] != null);

function getFirstElementNamed(theName) {
	theArray = document.getElementsByName(theName);
	return theArray[0].content;
}

var path_from_root_to_document, theAuthor, theReceiver, theTvnit;
if (document.getElementsByName) {
	path_from_root_to_document = getFirstElementNamed('jmQovc');
	theAuthor = getFirstElementNamed('author');
	theReceiver = getFirstElementNamed('receiver');
	theTvnit = getFirstElementNamed('tvnit');
}
else if (document.all) {
	path_from_root_to_document = document.all.jmQovc.content;
	theAuthor = document.all.author.content;
	theReceiver = document.all.receiver.content;
	theTvnit = document.all.tvnit.content;
}
else {
	path_from_root_to_document = window.location.href.replace(/^.*:\/\/\/?[^\/]*\/(.*)[.][^.]*$/, "$1");
	theAuthor = "";
	theReceiver = "";
	theTvnit = "";
}

var server = "http://tora.us.fm/";
var path_components = /^([^\/]*)\/(.*)$/.exec(path_from_root_to_document);
var site = path_components[1];
var path_from_site_to_document = path_components[2];
var path_components = /([^\/]+)$/.exec(path_from_root_to_document);
var path_from_document_to_document = path_components[1];


var absolute_site_url = server + site;

var siomt = (path_from_site_to_document.match(/[.]/)? "": ".html");
var absolute_document_url = absolute_site_url + "/" + path_from_site_to_document + siomt;

var relative_depth=0;
for (i=0; i<path_from_site_to_document.length; ++i) {
	if (path_from_site_to_document.charAt(i)=='/') relative_depth++;
}

var path_from_document_to_site = '';
for (i=0; i<relative_depth; ++i) {
	path_from_document_to_site += '../';
}

var path_from_site_to_cgi = "../cgi-bin";
var filepath_from_cgi_to_site = (/localhost|127.0.0.1/.test(document.URL))? "../"+site : "../httpdocs/"+site;
var linkpath_from_cgi_to_site = "../"+site;
var path_from_document_to_cgi = path_from_document_to_site + path_from_site_to_cgi;



/* site-specific variables */

var site_name='';
var usernameHint = '';
var passwordHint = '(אם אין לך סיסמה, יש להשאיר ריק. השינויים שלך ייכנסו לגירסה לא רשמית)';
var emailHint = '(לא חובה למלא)';
if (site=='tnk1') {
	site_name='אתר הניווט בתנך';
	passwordHint = '(אם אין לך סיסמה, יש לכתוב את 3 האותיות הראשונות בספר צפניה. במצב עריכה, השינויים שלך ייכנסו לגירסה לא רשמית)';
}
else if (site=='nxt') {
	site_name='אתר נוער חובב תנך';
}
else if (site=='tokxot')
	site_name='האתר למחאות מקוריות';
else if (site=='tryg')
	site_name='האתר למקוריות במצוות';
else if (site=='erelsgl')
	site_name='האתר של אראל סגל';
else if (site=='dugma') {
	usernameHint = '(בעריכת האתר לדוגמה, יש להשתמש בשם "הנהלה")';
	passwordHint = '(בעריכת האתר לדוגמה, יש להשתמש בסיסמה "הנהלה")';
	site_name='אתר לדוגמה';
}
else {
	site_name='האתר';
}



var theTosft, theBnim, theTokn, theTguvot, theTitle, documentHasEditableParts;
function getDocumentParts() { // called in "tguva" and "klinihul"
	theTosft = document.getElementById('tosft');
	theBnim = document.getElementById('ulbnim');
	theTokn = document.getElementById('tokn');
	theTguvot = document.getElementById('ultguvot');
	theTitle = document.getElementById('h1');

	documentHasEditableParts = (theTokn && theTguvot) || (theTosft && theBnim);
}
var theAddForm, theEditForm, theButtons, theButtonsTop;  // updated in "tguva" and "klinihul" 
function getFormParts() { // called in "tguva" and "klinihul"
	theAddForm = document.getElementById('addform');
	theEditForm = document.getElementById('editform');
	theButtons = document.getElementById('buttons');
	theButtonsTop = theButtons.offsetTop;
}

// END OF VARIABLE INITIALIZATION




/* cookies functions, from: http://www.webreference.com/js/column8/functions.html */

/* arguments:
   name - name of the cookie
   value - value of the cookie
   [expirationDays] - expiration date of the cookie, in days from today
     (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 setCookie(name, value, expirationDays, path, domain, secure) {
  var expires = null;
  if (expirationDays) {
     // create an instance of the Date object
     expires = new Date();
     // fix the bug in Navigator 2.0, Macintosh
     fixDate(expires);
     expires.setTime(expires.getTime() + expirationDays * 24 * 60 * 60 * 1000);
  }
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}


/*
  name - name of the desired cookie
  return string containing value of specified cookie or ""
  if cookie does not exist
*/

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return "";       // instead of null
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}


/*
   name - name of the cookie
   [path] - path of the cookie (must be same as path used to create cookie)
   [domain] - domain of the cookie (must be same as domain used to
     create cookie)
   path and domain default if assigned null or omitted if no explicit
     argument proceeds
*/

function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"

function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}

// END OF COOKIE FUNCTIONS












// Cross-Browser Rich Text Editor
// http://www.kevinroth.com/rte/demo.htm
// Written by Kevin Roth (kevin@NOSPAMkevinroth.com - remove NOSPAM)
// Visit the support forums at http://www.kevinroth.com/forums/index.php?c=2

//init variables
var isRichText = false;
var rng;
var currentRTE;

var isIE;
var isGecko;
var isSafari;
var isKonqueror;

var imagesPath;
var includesPath;
var cssFile;


function initRTE(imgPath, incPath, css) {
	//set browser vars
	var ua = navigator.userAgent.toLowerCase();
	isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1)); 
	isGecko = (ua.indexOf("gecko") != -1);
	isSafari = (ua.indexOf("safari") != -1);
	isKonqueror = (ua.indexOf("konqueror") != -1);
	
	//check to see if designMode mode is available
	if (document.getElementById && document.designMode && !isSafari && !isKonqueror) {
		isRichText = true;
	}
	
	if (isIE) {
		document.onmouseover = raiseButton;
		document.onmouseout  = normalButton;
		document.onmousedown = lowerButton;
		document.onmouseup   = raiseButton;
	}
	
	//set paths vars
	imagesPath = imgPath;
	includesPath = incPath;
	cssFile = css;
	
	if (isRichText) document.writeln('<style type="text/css">@import "' + includesPath + 'rte.css";</style>');
	
	//for testing standard textarea, uncomment the following line
	//isRichText = false;
}

function writeRichText(rte, html, width, height, buttons, readOnly) {
	if (isRichText)
		writeRTE(rte, html, width, height, buttons, readOnly);
	else
		document.write(DefaultHTML(rte, html, width, height, buttons, readOnly));
}

function RichTextHTML(rte, html, width, height, buttons, readOnly) {
	if (isRichText)
		return RTEHTML(rte, html, width, height, buttons, readOnly);
	else
		return DefaultHTML(rte, html, width, height, buttons, readOnly);
}

function DefaultHTML(rte, html, width, height, buttons, readOnly) {
	return '<textarea name="' + rte + '" id="' + rte + '" style="width: ' + width + RTE_WIDTH_UNITS + '; height: ' + height + RTE_HEIGHT_UNITS + ';"' + (readOnly? ' readonly': '') + '>' + html + '</textarea>';
}

function raiseButton(e) {
	//IE-Only Function
	var el = window.event.srcElement;
	
	className = el.className;
	if (className == 'rteImage' || className == 'rteImageLowered') {
		el.className = 'rteImageRaised';
	}
}

function normalButton(e) {
	//IE-Only Function
	var el = window.event.srcElement;
	
	className = el.className;
	if (className == 'rteImageRaised' || className == 'rteImageLowered') {
		el.className = 'rteImage';
	}
}

function lowerButton(e) {
	//IE-Only Function
	var el = window.event.srcElement;
	
	className = el.className;
	if (className == 'rteImage' || className == 'rteImageRaised') {
		el.className = 'rteImageLowered';
	}
}

function RTEHTML(rte, html, width, height, buttons, readOnly) {
	if (readOnly) buttons = false;

	//adjust minimum table widths
	if (RTE_WIDTH_UNITS == 'px') {
		if (isIE) {
			if (buttons && (width < 600)) width = 600;
			var tablewidth = width;
		} else {
			if (buttons && (width < 500)) width = 500;
			var tablewidth = width + 4;
		}
	}


	RTEText = '<br>העורך נבנה ע"י <a dir=ltr lang=en target=_blank href=http://www.kevinroth.com>Kevin Roth</a>' + '<div class="rteDiv">';
	if (buttons) { RTEText += 
		'<table class="rteBack" cellpadding=2 cellspacing=0 id="Buttons1_' + rte + '" width="' + tablewidth + '">' +
		'	<tr>' +
		'		<td>' +
		'			<select id="formatblock_' + rte + '" onchange="Select(\'' + rte + '\', this.id);">' +
		'				<option value="">[Style]</option>' +
		'				<option value="<p>">Paragraph</option>' +
		'				<option value="<h1>">Heading 1 <h1></option>' +
		'				<option value="<h2>">Heading 2 <h2></option>' +
		'				<option value="<h3>">Heading 3 <h3></option>' +
		'				<option value="<h4>">Heading 4 <h4></option>' +
		'				<option value="<h5>">Heading 5 <h5></option>' +
		'				<option value="<h6>">Heading 6 <h6></option>' +
		'				<option value="<address>">Address <ADDR></option>' +
		'				<option value="<pre>">Formatted <pre></option>' +
		'			</select>' +
		'		</td>' +
		'		<td>' +
		'			<select id="fontname_' + rte + '" onchange="Select(\'' + rte + '\', this.id)">' +
		'				<option value="Font" selected>[Font]</option>' +
		'				<option value="Arial, Helvetica, sans-serif">Arial</option>' +
		'				<option value="Courier New, Courier, mono">Courier New</option>' +
		'				<option value="Times New Roman, Times, serif">Times New Roman</option>' +
		'				<option value="Verdana, Arial, Helvetica, sans-serif">Verdana</option>' +
		'			</select>' +
		'		</td>' +
		'		<td>' +
		'			<select unselectable="on" id="fontsize_' + rte + '" onchange="Select(\'' + rte + '\', this.id);">' +
		'				<option value="Size">[Size]</option>' +
		'				<option value="1">1</option>' +
		'				<option value="2">2</option>' +
		'				<option value="3">3</option>' +
		'				<option value="4">4</option>' +
		'				<option value="5">5</option>' +
		'				<option value="6">6</option>' +
		'				<option value="7">7</option>' +
		'			</select>' +
		'		</td>' +
		'		<td width="100%">' +
		'		</td>' +
		'	</tr>' +
		'</table>' +
		'<table class="rteBack" cellpadding="0" cellspacing="0" id="Buttons2_' + rte + '" width="' + tablewidth + '">' +
		'	<tr>' +
		'		<td><img id="bold" class="rteImage" src="' + imagesPath + 'bold.gif" width="25" height="24" alt="Bold" title="Bold" onClick="FormatText(\'' + rte + '\', \'bold\', \'\')"></td>' +
		'		<td><img class="rteImage" src="' + imagesPath + 'italic.gif" width="25" height="24" alt="Italic" title="Italic" onClick="FormatText(\'' + rte + '\', \'italic\', \'\')"></td>' +
		'		<td><img class="rteImage" src="' + imagesPath + 'underline.gif" width="25" height="24" alt="Underline" title="Underline" onClick="FormatText(\'' + rte + '\', \'underline\', \'\')"></td>' +
		'		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>' +
		'		<td><img class="rteImage" src="' + imagesPath + 'left_just.gif" width="25" height="24" alt="Align Left" title="Align Left" onClick="FormatText(\'' + rte + '\', \'justifyleft\', \'\')"></td>' +
		'		<td><img class="rteImage" src="' + imagesPath + 'centre.gif" width="25" height="24" alt="Center" title="Center" onClick="FormatText(\'' + rte + '\', \'justifycenter\', \'\')"></td>' +
		'		<td><img class="rteImage" src="' + imagesPath + 'right_just.gif" width="25" height="24" alt="Align Right" title="Align Right" onClick="FormatText(\'' + rte + '\', \'justifyright\', \'\')"></td>' +
		'		<td><img class="rteImage" src="' + imagesPath + 'justifyfull.gif" width="25" height="24" alt="Justify Full" title="Justify Full" onclick="FormatText(\'' + rte + '\', \'justifyfull\', \'\')"></td>' +
		'		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>' +
		'		<td><img class="rteImage" src="' + imagesPath + 'hr.gif" width="25" height="24" alt="Horizontal Rule" title="Horizontal Rule" onClick="FormatText(\'' + rte + '\', \'inserthorizontalrule\', \'\')"></td>' +
		'		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>' +
		'		<td><img class="rteImage" src="' + imagesPath + 'numbered_list.gif" width="25" height="24" alt="Ordered List" title="Ordered List" onClick="FormatText(\'' + rte + '\', \'insertorderedlist\', \'\')"></td>' +
		'		<td><img class="rteImage" src="' + imagesPath + 'list.gif" width="25" height="24" alt="Unordered List" title="Unordered List" onClick="FormatText(\'' + rte + '\', \'insertunorderedlist\', \'\')"></td>' +
		'		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>' +
		'		<td><img class="rteImage" src="' + imagesPath + 'outdent.gif" width="25" height="24" alt="Outdent" title="Outdent" onClick="FormatText(\'' + rte + '\', \'outdent\', \'\')"></td>' +
		'		<td><img class="rteImage" src="' + imagesPath + 'indent.gif" width="25" height="24" alt="Indent" title="Indent" onClick="FormatText(\'' + rte + '\', \'indent\', \'\')"></td>' +
		'		<td><div id="forecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'textcolor.gif" width="25" height="24" alt="Text Color" title="Text Color" onClick="FormatText(\'' + rte + '\', \'forecolor\', \'\')"></div></td>' +
		'		<td><div id="hilitecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'bgcolor.gif" width="25" height="24" alt="Background Color" title="Background Color" onClick="FormatText(\'' + rte + '\', \'hilitecolor\', \'\')"></div></td>' +
		'		<td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>' +
		'		<td><img class="rteImage" src="' + imagesPath + 'hyperlink.gif" width="25" height="24" alt="Insert Link" title="Insert Link" onClick="FormatText(\'' + rte + '\', \'createlink\')"></td>' +
		'		<td><img class="rteImage" src="' + imagesPath + 'image.gif" width="25" height="24" alt="Add Image" title="Add Image" onClick="AddImage(\'' + rte + '\')"></td>';
		if (isIE) {
			RTEText += '		<td><img class="rteImage" src="' + imagesPath + 'spellcheck.gif" width="25" height="24" alt="Spell Check" title="Spell Check" onClick="checkspell()"></td>';
		}
		RTEText += 
			'		<td width="100%"></td>' + 
			'	</tr>' + 
			'</table>';
	} // end of "if buttons"

	RTEText += '<iframe id="' + rte + '" name="' + rte + '" width="' + width + RTE_WIDTH_UNITS + '" height="' + height + RTE_HEIGHT_UNITS + '" src="about:blank"></iframe>';
	if (!readOnly) RTEText += '<br /><input type="checkbox" id="chkSrc' + rte + '" onclick="toggleHTMLSrc(\'' + rte + '\');" />&nbsp;HTML source';
	RTEText += 
		'<iframe width="154" height="104" id="cp' + rte + '" src="' + includesPath + 'palette.htm" marginwidth="0" marginheight="0" scrolling="no" style="visibility:hidden; display: none; position: absolute;"></iframe>' +
		'<input type="hidden" id="hdn' + rte + '" name="' + rte + '" value="">' +
		'</div>';
		
	return RTEText;
}

function SetRTE(rte,html,readOnly) {
	document.getElementById('hdn' + rte).value = html;
	enableDesignMode(rte, html, readOnly);
}

function writeRTE(rte, html, width, height, buttons, readOnly) {
	document.writeln(RTEHTML(rte, html, width, height, buttons, readOnly));
	SetRTE(rte,html,readOnly);
}

function enableDesignMode(rte, html, readOnly) {
	var frameHtml = '<html ' + LOCALIZATION_ATTRIBUTES + ' id="' + rte + '">\n';  // CHANGED BY EREL
	frameHtml += "<head>\n";
	if (cssFile.length > 0) {
		frameHtml += "<link media=\"all\" type=\"text/css\" href=\"" + cssFile + "\" rel=\"stylesheet\">\n";
	} else {
		frameHtml += 
			"<style>\n" + 
			"body {\n" + 
			"	background: #FFFFFF;\n" + 
			"	margin: 0px;\n" + 
			"	padding: 0px;\n" + 
			"}\n" + 
			"</style>\n";
	}
	frameHtml += 
		"</head>\n" + 
		"<body class=RTE>\n" +  // CHANGED BY EREL
		html + "\n" + 
		"</body>\n" + 
		"</html>";

	if (document.all) {
		var oRTE = frames[rte].document;
		oRTE.open();
		oRTE.write(frameHtml);
		oRTE.close();
		if (!readOnly) oRTE.designMode = "On";
	} else {
		try {
			if (!readOnly) document.getElementById(rte).contentDocument.designMode = "on";
			try {
				var oRTE = document.getElementById(rte).contentWindow.document;
				oRTE.open();
				oRTE.write(frameHtml);
				oRTE.close();
				if (isGecko && !readOnly) {
					//attach a keyboard handler for gecko browsers to make keyboard shortcuts work
					oRTE.addEventListener("keypress", kb_handler, true);
				}
			} catch (e) {
				alert("Error preloading content.");
			}
		} catch (e) {
			//gecko may take some time to enable design mode.
			//Keep looping until able to set.
			if (isGecko) {
				command = "enableDesignMode(" + 
					"'" + rte + "', " + 
					"standardizeHTMLTokn(theTokn.innerHTML), " +  // CHANGED BY EREL
					readOnly + 
					");" ;
				setTimeout(command, 10);
			} else {
				return false;
			}
		}
	}
}

function updateRTE(rte) {
	if (!isRichText) return;

	//set message value
	var oHdnMessage = document.getElementById('hdn' + rte);
	var oRTE = document.getElementById(rte);
	var readOnly = false;
	
	//check for readOnly mode
	if (document.all) {
		if (frames[rte].document.designMode != "On") readOnly = true;
	} else {
		if (document.getElementById(rte).contentDocument.designMode != "on") readOnly = true;
	}
	
	if (isRichText && !readOnly) {
		//if viewing source, switch back to design view
		if (document.getElementById("chkSrc" + rte).checked) {
			document.getElementById("chkSrc" + rte).checked = false;
			toggleHTMLSrc(rte);
		}
		
		if (oHdnMessage.value == null) oHdnMessage.value = "";
		if (document.all) {
			oHdnMessage.value = frames[rte].document.body.innerHTML;
		} else {
			oHdnMessage.value = oRTE.contentWindow.document.body.innerHTML;
		}
		
		//if there is no content (other than formatting) set value to nothing
		if (stripHTML(oHdnMessage.value.replace("&nbsp;", " ")) == "" 
			&& oHdnMessage.value.toLowerCase().search("<hr") == -1
			&& oHdnMessage.value.toLowerCase().search("<img") == -1) oHdnMessage.value = "";
		//fix for gecko
		if (escape(oHdnMessage.value) == "%3Cbr%3E%0D%0A%0D%0A%0D%0A") oHdnMessage.value = "";
	}
}

function toggleHTMLSrc(rte) {
	//contributed by Bob Hutzel (thanks Bob!)
	var oRTE;
	if (document.all) {
		oRTE = frames[rte].document;
	} else {
		oRTE = document.getElementById(rte).contentWindow.document;
	}
	
	if (document.getElementById("chkSrc" + rte).checked) {
		document.getElementById("Buttons1_" + rte).style.visibility = "hidden";
		document.getElementById("Buttons2_" + rte).style.visibility = "hidden";
		if (document.all) {
			oRTE.body.innerText = oRTE.body.innerHTML;
		} else {
			var htmlSrc = oRTE.createTextNode(oRTE.body.innerHTML);
			oRTE.body.innerHTML = "";
			oRTE.body.appendChild(htmlSrc);
		}
	} else {
		document.getElementById("Buttons1_" + rte).style.visibility = "visible";
		document.getElementById("Buttons2_" + rte).style.visibility = "visible";
		if (document.all) {
			//fix for IE
			var output = escape(oRTE.body.innerText);
			output = output.replace("%3CP%3E%0D%0A%3CHR%3E", "%3CHR%3E");
			output = output.replace("%3CHR%3E%0D%0A%3C/P%3E", "%3CHR%3E");
			
			oRTE.body.innerHTML = unescape(output);
		} else {
			var htmlSrc = oRTE.body.ownerDocument.createRange();
			htmlSrc.selectNodeContents(oRTE.body);
			oRTE.body.innerHTML = htmlSrc.toString();
		}
	}
}

//Function to format text in the text box
function FormatText(rte, command, option) {
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
		
		//get current selected range
		var selection = oRTE.document.selection; 
		if (selection != null) {
			rng = selection.createRange();
		}
	} else {
		oRTE = document.getElementById(rte).contentWindow;
		
		//get currently selected range
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}
	
	try {
		if ((command == "forecolor") || (command == "hilitecolor")) {
			//save current values
			parent.command = command;
			currentRTE = rte;
			
			//position and show color palette
			buttonElement = document.getElementById(command + '_' + rte);
			var iLeftPos = getOffsetLeft(buttonElement);
			var iTopPos = getOffsetTop(buttonElement) + (buttonElement.offsetHeight + 4);
			document.getElementById('cp' + rte).style.left = (iLeftPos) + "px";
			document.getElementById('cp' + rte).style.top = (iTopPos) + "px";
			if (document.getElementById('cp' + rte).style.visibility == "hidden") {
				document.getElementById('cp' + rte).style.visibility = "visible";
				document.getElementById('cp' + rte).style.display = "inline";
			} else {
				document.getElementById('cp' + rte).style.visibility = "hidden";
				document.getElementById('cp' + rte).style.display = "none";
			}
		} else if (command == "createlink") {
			var szURL = prompt("Enter a URL:", "");
			try {
				//ignore error for blank urls
				oRTE.document.execCommand("Unlink", false, null);
				oRTE.document.execCommand("CreateLink", false, szURL);
			} catch (e) {
				//do nothing
			}
		} else {
			oRTE.focus();
		  	oRTE.document.execCommand(command, false, option);
			oRTE.focus();
		}
	} catch (e) {
		alert(e);
	}
}

//Function to set color
function setColor(color) {
	var rte = currentRTE;
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
	} else {
		oRTE = document.getElementById(rte).contentWindow;
	}
	
	var parentCommand = parent.command;
	if (document.all) {
		//retrieve selected range
		var sel = oRTE.document.selection; 
		if (parentCommand == "hilitecolor") parentCommand = "backcolor";
		if (sel != null) {
			var newRng = sel.createRange();
			newRng = rng;
			newRng.select();
		}
	}
	oRTE.focus();
	oRTE.document.execCommand(parentCommand, false, color);
	oRTE.focus();
	document.getElementById('cp' + rte).style.visibility = "hidden";
	document.getElementById('cp' + rte).style.display = "none";
}

//Function to add image
function AddImage(rte) {
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
		
		//get current selected range
		var selection = oRTE.document.selection; 
		if (selection != null) {
			rng = selection.createRange();
		}
	} else {
		oRTE = document.getElementById(rte).contentWindow;
		
		//get currently selected range
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}
	
	imagePath = prompt('Enter Image URL:', 'http://');				
	if ((imagePath != null) && (imagePath != "")) {
		oRTE.focus();
		oRTE.document.execCommand('InsertImage', false, imagePath);
		oRTE.focus();
	}
}

//function to perform spell check
function checkspell() {
	try {
		var tmpis = new ActiveXObject("ieSpell.ieSpellExtension");
		tmpis.CheckAllLinkedDocuments(document);
	}
	catch(exception) {
		if(exception.number==-2146827859) {
			if (confirm("ieSpell not detected.  Click Ok to go to download page."))
				window.open("http://www.iespell.com/download.php","DownLoad");
		} else {
			alert("Error Loading ieSpell: Exception " + exception.number);
		}
	}
}

// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
// KJR 11/12/2004 Changed to position palette based on parent div, so palette will always appear in proper location regardless of nested divs
function getOffsetTop(elm) {
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;
	var parents_up = 2; //the positioning div is 2 elements up the tree
	
	while(parents_up > 0) {
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}
	
	return mOffsetTop;
}

// Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div.
// KJR 11/12/2004 Changed to position palette based on parent div, so palette will always appear in proper location regardless of nested divs
function getOffsetLeft(elm) {
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;
	var parents_up = 2;
	
	while(parents_up > 0) {
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
		parents_up--;
	}
	
	return mOffsetLeft;
}

function Select(rte, selectname) {
	var oRTE;
	if (document.all) {
		oRTE = frames[rte];
		
		//get current selected range
		var selection = oRTE.document.selection; 
		if (selection != null) {
			rng = selection.createRange();
		}
	} else {
		oRTE = document.getElementById(rte).contentWindow;

		//get currently selected range
		var selection = oRTE.getSelection();
		rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}

	var idx = document.getElementById(selectname).selectedIndex;
	// First one is always a label
	if (idx != 0) {
		var selected = document.getElementById(selectname).options[idx].value;
		var cmd = selectname.replace('_' + rte, '');
		oRTE.focus();
		oRTE.document.execCommand(cmd, false, selected);
		oRTE.focus();
		document.getElementById(selectname).selectedIndex = 0;
	}
}

function kb_handler(evt) {
	var rte = evt.target.id;
	
	//contributed by Anti Veeranna (thanks Anti!)
	if (evt.ctrlKey) {
		var key = String.fromCharCode(evt.charCode).toLowerCase();
		var cmd = '';
		switch (key) {
			case 'b': cmd = "bold"; break;
			case 'i': cmd = "italic"; break;
			case 'u': cmd = "underline"; break;
		};

		if (cmd) {
			FormatText(rte, cmd, true);
			//evt.target.ownerDocument.execCommand(cmd, false, true);
			// stop the event bubble
			evt.preventDefault();
			evt.stopPropagation();
		}
 	}
}

function docChanged (evt) {
	alert('changed');
}

function stripHTML(oldString) {
	var newString = oldString.replace(/(<([^>]+)>)/ig,"");
	
	//replace carriage returns and line feeds
   newString = newString.replace(/\r\n/g," ");
   newString = newString.replace(/\n/g," ");
   newString = newString.replace(/\r/g," ");
	
	//trim string
	newString = trim(newString);
	
	return newString;
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") return inputString;
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
	
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length - 1, retValue.length);
	
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length - 1);
      ch = retValue.substring(retValue.length - 1, retValue.length);
   }
	
	// Note that there are two spaces in the string - look for multiple spaces within the string
   while (retValue.indexOf("  ") != -1) {
		// Again, there are two spaces in each of the strings
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ") + 1, retValue.length);
   }
   return retValue; // Return the trimmed string back to the user
}

//Usage: initRTE(imagesPath, includesPath, cssFile)
initRTE(
	path_from_document_to_site+"../_script/", 
	path_from_document_to_site+"../_script/", 
	path_from_document_to_site+"_themes/klli.css");



















////////////////////// catch subsequent clicks //////////////////

// The following code could be used to perform an action after
// several subsequent mouse-clicks.

var lastClickTime = new Date();
var clickCount = 0;

// countSubsequentClicks sets clickCount to the current number of subsequent clicks,
//   and returns the new value.
function countSubsequentClicks() {
    var now = new Date();
    var difference = now.getTime() - lastClickTime.getTime();
    if (difference <= 300)
       ++clickCount;
    else
       clickCount=1;
    lastClickTime = now;
    return clickCount;
}

// make the page editable/uneditable (used as a "click" and "mousedown" event handler)
function toggleEdit(eventObject) {
    count = countSubsequentClicks();
    if (count==SUBSEQUENT_CLICKS_TO_EDIT) {
       clickType=(navigator.appName=="Netscape")? eventObject.which: event.button;
       if (theEditForm.style.display=='none')
          showEdit('editinplace'); 
       else
          hideEdit();
    }
}

// end of "catch subsequentclicks" functions







/* scroll functions */

function scrollButtonsWithWindow(){
	if (document.body.scrollTop) {
		theButtons.style.top=document.body.scrollTop+theButtonsTop;
	}
	else if (window.pageYOffset) {
		theButtons.style.top=window.pageYOffset+theButtonsTop;
		setTimeout('scrollButtonsWithWindow()',30)
	}
}
//window.onscroll=scrollButtonsWithWindow;

function scrollToBottom(eventObject) {
    if (countSubsequentClicks()==SUBSEQUENT_CLICKS_TO_EDIT) {
	document.body.scrollTop = theButtonsTop;
    }
}

// END OF SCROLL FUNCTIONS


function ktov_bnim(header, pattern, footer) {
   if (!theWrittenBnim) 
      theWrittenBnim = new Array(theBnimArray.length);
   regexp = new RegExp(pattern,"i");
   regexp1 = new RegExp(">"+pattern, "i");
   regexp2 = new RegExp("^"+pattern, "i");
   theText = "";
   numWritten = 0;
   for (i=0; i<theBnimArray.length; ++i) {
      bn = theBnimArray[i];
      if (regexp1.test(bn) || regexp2.test(bn)) {
         if (numWritten==0) theText += header;
         if (!/img/i.test(bn)) {
            theText += "<LI>";
            bn = bn.replace(/ציור/, "<img style='margin-bottom:-0.5ex' title='ציור' src="+path_from_document_to_site+"_themes/cyur.gif>ציור");
         }
         bn = bn.
            replace(/שיר:/, "<img style='margin-bottom:-0.5ex' title='שיר' src="+path_from_document_to_site+"_themes/tw.gif>").
            replace(/מבנה:/, "").
            replace(/הבדלים:/, "").
            replace(/מאמר דמיוני:/, "<img style='margin-bottom:-0.5ex' title='דימיוני' src="+path_from_document_to_site+"_themes/ein_knisa.gif>מאמר דימיוני:").
            replace(/מאמר:/, "").
            replace(/כלל:/, "").
            replace(/מאמר לא גמור:/, "<img style='margin-bottom:-0.5ex' title='לא גמור' src="+path_from_document_to_site+"_themes/jtil.gif> ").
            replace(/שאלה:/, "<img style='margin-bottom:-0.5ex' title='שאלה' src="+path_from_document_to_site+"_themes/jtil.gif> ").
            replace(/מצוות:/, "<img style='margin-bottom:-0.5ex' title='מצוה' src="+path_from_document_to_site+"_themes/mcwa.gif> ").
            replace(regexp,"");
            
         theText += bn;
         ++numWritten;
         theWrittenBnim[i] = 1;
      }
   }
   if (numWritten>0) theText += footer;
   document.write(theText);
}

function ktov_bnim_axrim() {
   header=""; footer="";
   theText = "";
   numWritten = 0;
   for (i=0; i<theBnimArray.length; ++i) {
      if (!theWrittenBnim[i]) {
         bn = theBnimArray[i];
         if (numWritten==0) theText += header;
         theText += ("<LI>"+bn);
         ++numWritten;
      }
   }
   if (numWritten>0) theText += footer;
   document.write(theText);
} 

// the header of every document
function kotrt() {
        theText="";
	if (!document.getElementById("h1")) {
	 	theText += ("<H1 id=h1>" + document.title + "</H1>");
	}

	if (theAuthor.length>0) {
		if (theAuthor=="אראל" || theAuthor=="אראל סגל")
			theAuthor += " (ללא הסמכה לפסיקת הלכה)";
		else if ("רענן" == theAuthor)
			theAuthor = "<A href=mailto:raananyosef@yahoo.com>"+theAuthor+"</A>";
		theText += ("<i><center>מאת: " + theAuthor + "</center></i><BR>");
		if (document.body.className == "dmwt") {
			theText += ("<i><center>מימון: " + "אראל" + "</center></i><BR>");
		}
	}

	if (theReceiver.length>0)
		theText += ("<i><center>אל: " + theReceiver + "</center></i><BR>");

	if (/http:/.test(document.URL)  && !(/cgi-bin/.test(document.URL))) 
		theText += ("<i><center><A style='text-decoration:none; font-size:10pt; font-weight:bold; border:solid 1pt' href=" + path_from_document_to_cgi + "/print.pl?ktovt=" + path_from_site_to_document + "&mslul=" + filepath_from_cgi_to_site + ">גרסה ידידותית למדפסת</A></center></i><br>");

	document.write(theText);
}



// write links to older/newer versions of this document
function girsaot() {
	var theText = ("<DIV style='padding:0;margin:0;font-size:12pt;background:white;color:black;text-align:center'>");
	if (/http:/.test(document.URL)  && !(/cgi-bin/.test(document.URL))) {
		if (/-open/.test(document.URL)) {
			theText += ('זוהי <b>הגירסה הפתוחה</b> של הדף, שכוללת גם שינויים שנעשו על-ידי הגולשים  עד ' + document.lastModified + '. ');
			otherHref = path_from_document_to_document+siomt;
			theText += ('כדי לעבור לגירסה הרשמית של הדף, <a href='+ otherHref + '>יש ללחוץ כאן</a>.');
		}
		else if (/\d\d\d\d\d\d\d\d\d\d\d\d/.test(document.URL)) {
			theText += ('זוהי מהדורה לא רשמית של הדף, שנוצרה ' + document.lastModified + '. ');
			otherHref = path_from_document_to_document+siomt;
			theText += ('כדי לעבור לגירסה הרשמית של הדף, <a href='+ otherHref + '>יש ללחוץ כאן</a>.');
		}
		else {
			if (/http:/.test(document.URL)) {
				theText += ('<iframe width=100% height=42 src=' + path_from_document_to_cgi + '/rewrite.pl?versionlist=short&followup=' + path_from_root_to_document +'></iframe>');
			}
			else {
				theText += ('זוהי <b>הגירסה הרשמית</b> של הדף, שעודכנה לאחרונה ב-' + document.lastModified + '. ');
				otherHref = path_from_document_to_document+'-open'+siomt;
				theText += ('כדי לבדוק אם לדף יש גירסה פתוחה, שכוללת גם שינויים שנעשו על-ידי הגולשים, <a href=' + otherHref + '>יש ללחוץ כאן</a>.');
			}
		}
	} // end of "if http..."
	theText += ("</DIV>");
        document.write(theText);
}



// the footer of every document
function txtit() {
	document.write("</div><div style=clear:both>");   // close the outside div and open a new div, to prevent "blinking"
	document.write("<HR>");
	girsaot();

	theText = ("<DIV class=txtit>");

	if (/אראל/.test(theAuthor))
		theText += ("<br>ניתן להשתמש בחומר שבדף זה על-פי תנאי הרשיון שב<a href="+path_from_document_to_site+"../rjyon.html>קישור</a>");
	theText += (" <br> דף זה נמצא ברשת בכתובת: <A dir=ltr href=" + absolute_document_url  + ">" + absolute_document_url   + "</A>");
	theText += ("  <BR>" + site_name + ": <A dir=ltr href=" + absolute_site_url + ">" + absolute_site_url + "</A>");
	theText += ("</DIV>");

	document.write(theText);
}


function getElement(obj) {
	if (typeof(obj)=='string')
		return document.getElementById(obj);
	else
		return obj;
}


// show and hide
function show(obj) {
	getElement(obj).style.display=''
}
function hide(obj) {
	getElement(obj).style.display='none'
}
function showorhide(obj) {
	element = getElement(obj);
	if (element.style.display == 'none')
		element.style.display = '';
	else
		element.style.display = 'none';
}
function showclass(c)
{
	for (i in document.all) {
		obj = document.all[i];
		if (obj.className == c)
			show(obj);
	}
}
function hideclass(c)
{
	for (i in document.all) {
		obj = document.all[i];
		if (obj.className == c)
			hide(obj);
	}
}
function activate(obj) {
	if (obj.hiddenText)
		obj.innerHTML=obj.hiddenText;
}
function deactivate(obj) {
	if (obj.innerHTML.length > 0) {
		obj.hiddenText = obj.innerHTML;
		obj.innerHTML="";
	}
}


function mark(obj) {
	getElement(obj).style.color='green'
}
function unmark(obj) {
	getElement(obj).style.color=''
}
function markOnly(theButton) {
	unmark('button1');
	unmark('button2');
	unmark('button3');
	unmark('button4');
	unmark('button5');
	mark(theButton);
}


function standardizeHTMLTokn(theHTML) {
	theText = theHTML.
	/* add newline before a start-tag (except an underline and a subscript) */
		replace(/(<[^uU\/!])/ig,"\r\n$1").
		replace(/\r\n(<sub>)/ig,"$1").
	/* add space after an end-tag (except an underline) */
		replace(/(<\/[^uU>][^>]*>)/ig,"$1 ").
		replace(/(<\/sub>) /ig,"$1").
	/* remove unneeded tags */
		replace(/<\/LI>/ig,"").
		replace(/<\/P>/ig,"").
		replace(/<\/TD>/ig,"").
		replace(/<\/TR>/ig,"").
		replace(/<TBODY>/ig,"").
		replace(/<\/TBODY>/ig,"").
		replace(/<o:p>\s*<\/o:p>/ig,"").
	/* remove unneeded properties (added by "Word") */
		replace(/ class=MsoNormal[a-z]*/ig,"").
		replace(/mso-[^ ">]*:\s*[^ ">]*/ig,"").
		replace(/margin[^ ">]*:\s*[^ ">]*/ig,"").
		replace(/style=[\"\'][\"\']/ig,"").
		replace(/TEXT-INDENT: -[0-9a-z.]*/ig,"").
	/* remove "vid:" (added by "Visual Studio") */
		replace(/href=\"vid:/ig,"href=\"").
		replace(/margin[^ ">]*:\s*[^ ">]*/ig,"").
		replace(/style=[\"\'][\"\']/ig,"").
	/* remove unneeded spans */
		replace(/<SPAN[^>]*>\s*<\/SPAN>/ig,"").
		replace(/<SPAN>([^<]*)<\/SPAN>/ig,"$1").
		replace(/<SPAN[^>]*>\s*<\/SPAN>/ig,"").
		replace(/<SPAN>([^<]*)<\/SPAN>/ig,"$1").
	/* create citations: replace "<<...>>" with "<CITE>...</CITE>" */
		replace(/&lt;&lt;/ig, "<CITE>").
		replace(/&gt;&gt;/ig, "<\/CITE>").
	/* create small text: replace "[[...]]" with "<SMALL>...</SMALL>" */
		replace(/\[\[/ig, "<SMALL>").
		replace(/\]\]/ig, "<\/SMALL>").
	/* create lists: replace " (( * ... * ... ))" with "<LI> ... <LI> ..." */
		replace(/<P[^>]*>[^<a-zA-Zא-ת]*\*/ig,"<LI>").
		replace(/<P[^>]*>\s*(<B[^>]*>\s*)*(<SPAN[^>]*>\s*)*(<FONT[^>]*>\s*)*·\s*(<\/FONT>\s*)*(<\/SPAN>\s*)*/ig,"<LI>").
		replace(/(<DIV[^>]*>)[^<a-zA-Zא-ת]*\*/ig,"<LI>$1").
		replace(/(<DIV[^>]*>)\s*(<B[^>]*>\s*)*(<SPAN[^>]*>\s*)*(<FONT[^>]*>\s*)*·\s*(<\/FONT>\s*)*(<\/SPAN>\s*)*/ig,"<LI>$1").
		replace(/\(\(/ig, "<UL>").
		replace(/\)\)/ig, "<\/UL>").
	/* remove unneeded parts of a link */
		replace(/(\.htm)\?[^\"\'<>]*/ig,"$1").
	/* fix span direction (for bidi text) */
		//replace(/(<P[^>]*>\s*)(<B[^>]*>\s*)*(<SPAN[^>]*>\s*)*(<SPAN[^>]*)dir=...([^>]*>)/ig,"$1$2$3$4$5").
		replace(/(<P[^>]*>)([^א-ת]*)(<SPAN[^>]*)dir=...([^>]*>)/ig,"$1$2$3$4").
		replace(/(<LI[^>]*>)([^א-ת]*)(<SPAN[^>]*)dir=...([^>]*>)/ig,"$1$2$3$4").
	/* remove unneeded newlines */
		replace(/\r\n(\r\n)+/ig, "\r\n").
		replace(/^\r\n/ig, "").
		replace(/\r\n$/ig, "");
	return theText;
}

function standardizeHTMLTguvot(theHTML) {
	return theHTML.
		replace(/<\/LI>/ig,"").
		replace(/<\/P>/ig,"").
		replace(/[\r\n]/ig,"").
		replace(/(<[!][-][-]top:)/ig,"\r\n$1").
		replace(/(<li>)/ig,"\r\n$1").
		replace(/[(]<[!][-][-]responses:[^>]+>\d+[)]/ig,"").
		replace(/<span> ?<\/span>/ig,"").
		replace(/(<ul><[!][-][-]insert:)/ig,"\r\n$1").
		replace(/(<\/ul><[!][-][-]end:)/ig,"\r\n$1").
		replace(/\r\n(\r\n)+/ig, "\r\n").
		replace(/^\r\n/ig, "").
		replace(/\r\n$/ig, "");

	return theHTML;
}

function standardizeHTMLToknAndTguvot(toknHTML, tguvotHTML) {
		return "<DIV id=tokn>\r\n" + 
			standardizeHTMLTokn(toknHTML) + "\r\n" +
			"</DIV !--tokn-->\r\n" + 
			"<h2 id=tguvot>" + document.getElementById('tguvot').innerHTML + "</h2>\r\n\r\n" + 
			"<ul id=ultguvot !--begin-->\r\n" + 
			standardizeHTMLTguvot(tguvotHTML) + "\r\n" +
			"</ul !--end-->\r\n\r\n";
}

function standardizeHTML() {
	if (theTokn && theTguvot)
		return standardizeHTMLToknAndTguvot(theTokn.innerHTML, theTguvot.innerHTML);
	else if (theBnim && theTosft) {
		return 	"<!--tosft0--><DIV id=tosft>\r\n" +
			standardizeHTMLTokn(theTosft.innerHTML) + "\r\n" +
			"</DIV !--tosft--><!--tosft1-->\r\n"+
			"<ul id=ulbnim style='display:none'>\r\n" + 
			standardizeHTMLTokn(theBnim.innerHTML) + "\r\n" +
			"</ul !--end-->\r\n\r\n";
	}
	else {
		alert('התגלתה תקלה במבנה המסמך. נא להודיע למנהל האתר!');
	}
}



// INPUT:  text from a text-area
// OUTPUT: the text converted to HTML, to put in a new document
function text2HTML(theText) {
	return theText.
		replace(/(http:\/\/[^ \r\n\t()<>{}]+)/gi, "<a href=$1>$1</a>").
		replace(/\cM/g, "").
		replace(/\n\n/g, "<p>").
		replace(/\n/g, "<br>").
		replace(/&lt;/gi, "<").
		replace(/&gt;/gi, ">").
		replace(/&quot;/gi, "\"");
}


function makeEditable(theElement, isEditable) {
	if (theElement) {
		theElement.contentEditable=isEditable;
		theElement.className = isEditable? 'edited': '';
	}
}

function makeDocumentEditable(isEditable) {
	if (theBnim) {
		makeEditable (theTosft, isEditable);
		makeEditable (theBnim, isEditable);
		theBnim.style.display = (isEditable? '': 'none');
	}
	else {
		makeEditable (theTokn, isEditable);
		makeEditable (theTguvot, isEditable);
	}
	makeEditable (theTitle, isEditable);
}

function hideEdit() {
	hide(theEditForm);
	makeDocumentEditable(false);
}

function showAdd(theForm) {
	show(theAddForm);
	hideEdit(theEditForm);
	hide('addtext');
	hide('addlink');
	hide('addfile');
	show(theForm);
}
function showEdit(theForm) {
	theAddForm.qijur.value='http://';
	if (contentEditable) theAddForm.jm_qovc_al_hlqox.value=''; // TODO TEMPVER
	hide(theAddForm);
	show(theEditForm);
	makeDocumentEditable(theForm=='editinplace');
	hide('editinplace');
	hide('editwithbuttons');
	show(theForm);
}




function ValidateNotEmpty(field, fieldName) {
	if (field.value.length==0) {
		alert('שכחת למלא ' + fieldName + "!");
		return false;
	}
	else 
		return true;
}


function ValidateName(name) {return ValidateNotEmpty(name,'שם')}
function ValidateTitle(title) {return ValidateNotEmpty(title,'נושא')}



function removeHTMLColor (theHTML) {
   return theHTML.
      replace(/<FONT[^>]*>/ig, "").
      replace(/<\/FONT>/ig, "").
      replace(/font-family:[^;\"\' >]*/ig, "").
      replace(/font-size:[^;\"\' >]*/ig, "").
      replace(/color:[^;\"\' >]*/ig, "");
//   return theHTML.
//      replace(/<FONT[^>]*>((.|\r|\n)*)<\/FONT>/ig, "$1").
//      replace(/color:[^;\"\' >]*/ig, "");
}


function buttonHTML(id, action, title, description) {
	if (action=='') 
		return '<td id=' + id + '>';
	else {
		action = "markOnly('" + id + "');" + action;
		return '<td id=' + id + '><button onclick="' + action + '">' + title + '</button>&nbsp;' + description;
	}
}

function fiveButtonsHTML(peula1, jm1, teur1, peula2, jm2, teur2, peula3, jm3, teur3, peula4, jm4, teur4, peula5, jm5, teur5) {
return '<P id=buttons style="text-align:center">' + 
	'<table><tr>'+
        buttonHTML('button1',peula1,jm1,teur1)+
        buttonHTML('button2',peula2,jm2,teur2)+
        buttonHTML('button3',peula3,jm3,teur3)+
        buttonHTML('button4',peula4,jm4,teur4)+
        buttonHTML('button5',peula5,jm5,teur5)+
	'</table>'+
'</P>'; 
}





help = 	
	'&nbsp;<div></div><a href=javascript:showorhide("helpedittext")>איך&nbsp;לערוך&nbsp;טקסט?</a>' + 
	'<div id=helpedittext style="display:none">' +
    '<p><b>חדש: ניתן להיכנס למצב עריכה גם על-ידי '+SUBSEQUENT_CLICKS_TO_EDIT+' הקלקות ברצף במקום כלשהו במסמך.</b> ' + 
	'<p>לעריכת טקסט יש שתי אפשרויות: <ul>' +
	'<li>טקסט פשוט (ללא עיצוב, בצבע אחד, בשפה אחת) ניתן לערוך ישירות על הדף. ' +
	'ניתן להשתמש במקשי-עריכה: <STRONG>Ctrl+B להדגשה</STRONG>, <EM>Ctrl+I להטיה</EM>, <U>Ctrl+U לקו-תחתי</U>, <A href="javascript:alert(\'Ctrl+K = הוספת קישור\')">Ctrl+K</A>' +
	'<br>* כוכביות בתחילת שורה (כמו כאן) יהפכו לנקודות של רשימה.' +
	'<li>טקסט מעוצב (בצבעים, בשפות שונות) יש לערוך ב"וורד" או בתוכנה אחרת, ואז להעתיק ולהדביק כאן.</ul>' + 
	'</div>' + 
	'&nbsp;&nbsp;<a href=javascript:showorhide("helpeditimages")>איך&nbsp;להוסיף&nbsp;ציורים?</a>' + 
	'<div id=helpeditimages style="display:none">' +
	'<p>להוספת ציור או צילום יש שתי אפשרויות: <ul>' + 
	'<li>אם הציור נמצא באינטרנט - פשוט סמנו אותו בעזרת העכבר, העתיקו (Ctrl+C) והדביקו (Ctrl+V). זהירות - אל תפגעו בזכויות יוצרים!' + 
	'<li>אם הציור נמצא על המחשב שלכם - לחצו על "הוסף קובץ" והוסיפו את הציור שלכם לאתר, ואז תוכלו לסמן אותו להעתיק ולהדביק באותו אופן.</ul>' + 
	'<br>לאחר שמדביקים את הציור במסמך, ניתן להקליק עליו ואז לשנות את גודלו ע"י משיכת הריבועים הלבנים הקטנים שמקיפים אותו.<ul>' + 
	'</div>' +
	'&nbsp;<a href=javascript:showorhide("helpdelete")>איך&nbsp;למחוק&nbsp;דפים?</a>' + 
	'<div id=helpdelete style="display:none">' +
	'<p>למחיקת דף זה, יש לכתוב בו את המחרוזת "למחיקה".' +
	'<br>הדף יימחק מדף האב שלו, ומהדף "הוספות אחרונות לאתר".' +
	'<br>הדף יישאר על הדיסק במשך מספר ימים, כך שיהיה אפשר לבטל את המחיקה.' +
	'</div>' + 
        '';





// INPUT: 4 form fields.
// ACTION: set the corresponding cookies.
function setCookies (name, email, rememberme, password) {
   setCookie('name',name.value,365,"/",null,null);   // remember the name and email for a year
   setCookie('email',email.value,365,"/",null,null); // remember the name and email for a year
   if (rememberme.checked) {
      setCookie('password',password.value,null,"/",null,null); // remember the password only for this session
   }
   else {
      deleteCookie('password',"/");
   }
}


//formTextStyle = ' style="font-size:15pt" ';
formTextStyle = '';

idFields = 
	'<input type=hidden name=followup value='+path_from_root_to_document+'>'+
	'<TABLE>'+
	'<TR style="background:#efefef"'+formTextStyle+'><TD>שם:<TD><input type=text        name=name value="' + getCookie('name') + '" size=50><TD>' + usernameHint +
	'<TR style="background:#dfdfdf"'+formTextStyle+'><TD>סיסמה:<TD><input type=password name=password value="' + getCookie('password') + '"><TD>' + passwordHint + 
	'<TR style="background:#dfdfdf"'+formTextStyle+'><TD>דואל:<TD><input type=text name="email" value="' + getCookie('email') + '" size=50><TD>' + emailHint +
	'<TR style="background:#efefef"'+formTextStyle+'><TD style="text-align:left"><input name=rememberme type=checkbox' + (getCookie('name')? ' checked': '') + '><TD>שמור את הפרטים שלי על המחשב הזה (עד שאסגור את החלון)<TD>' + 
	'</TABLE>';

function formHeader(formId) {
	return '<FORM method=post style="display:none" id=' + formId + 
	' target=_blank ENCTYPE=multipart/form-data action="' + path_from_document_to_cgi + '/rewrite.pl"' + 
	' onsubmit="setCookies(name,email,rememberme,password); return ValidateName(name)&&ValidateTitle(title)">';
}


origsubjectInput = '<input type=hidden name="origsubject" value="' + title_without_quotes + '">';
orignameInput = '<input type=hidden name="origname" value="' + theAuthor + '">';
origemailInput = '<input type=hidden name="origemail" value="' + theReceiver + '">';

bodyclassInput = '<select size=1 name="bodyclass" onchange="if (selectedIndex>0) {this.form.title.value=options[selectedIndex].text+\': \'+title_without_quotes}">' +
  '<OPTION value="" SELECTED>* סוג התוספת *' +
  '<option value=tguva>תגובה' +
  '<option value=mamr>מאמר' +
  '<option value=la_gmwr>שאלה';
if (/tnk1.ljon.jorj/.test(path_from_root_to_document))
 bodyclassInput += 
  '<option value=hgdrh>הגדרה' + 
  '<option value=hbdl>הבדל';
if (/tnk1/.test(path_from_root_to_document))
 bodyclassInput += 
  '<option value=hpwk>מאמר דמיוני' + 
  '<option value=jyr>שיר';
if (/tryg.mcwa/.test(path_from_root_to_document))
 bodyclassInput += 
  '<option value=hgdrh>הגדרה' + 
  '<option value=fem>טעם';
bodyclassInput += '</select>';


titleInput = '<input type=hidden name=title value="'+title_without_quotes+'">' + 
             '<input type=hidden name=titlechanged value="">';

subjectInput = '<input type=text name=title size=50 value="' + (theTvnit.length>0? "תוספת ל": "תגובה ל") + ': ' + title_without_quotes + '">';

function setRewriteTitle(theForm) {
  if (theTitle) {
      theForm.title.value = theTitle.innerHTML;
      if (theTitle.innerHTML == document.title)
         theForm.titlechanged.value = "";
      else
         theForm.titlechanged.value = "1";
   }
}


function tguva () {
	document.write("</div><div>");   // close the outside div and open a new div, to prevent "blinking"
	getDocumentParts();

	if (theTvnit.length>0) {
		kftor1 = "הוסף מאמר חדש";
		teur1 = "אם כתבתם מאמר שקשור ל"+document.title+", אתם מוזמנים לשים אותו כאן; אם יש לכם שאלה על דף זה (לא שאלה הלכתית) אתם מוזמנים לשאול אותה כאן";
	}
	else {
		kftor1 = "הוסף תגובה";
		teur1 = "אם יש לכם תגובה על "+document.title+", אתם מוזמנים לשים אותה כאן; אם יש לכם שאלה על דף זה (לא שאלה הלכתית) אתם מוזמנים לשאול אותה כאן";
	}
	
	document.write(fiveButtonsHTML(
	   "showAdd('addtext');theAddForm.qijur.value='http://';theAddForm.jm_qovc_al_hlqox.value=''", 
	   kftor1, 
	   teur1,
	   "showAdd('addlink');theAddForm.jm_qovc_al_hlqox.value=''",
	   "הוסף קישור",
	   'אם מצאתם באינטרנט מאמר או אתר שקשור ל'+document.title+', אתם מוזמנים לשים כאן קישור. <small>אפשר להוסיף גם קישור למאמר שנמצא באתר זה.</small>',
	   "showAdd('addfile');theAddForm.qijur.value='http://'",
	   "הוסף קובץ",
	   'אם יש לכם קובץ שקשור ל'+document.title+' (ציור, מצגת, שיר...) אתם מוזמנים לשים אותו כאן',
	   (documentHasEditableParts&&contentEditable? "showEdit('editinplace')": ""),
	   "תקן דף זה",
	   "אם גיליתם טעות במסמך אתם מוזמנים לתקן...",
	   (theTokn&&theTguvot? "SetRTE('RTE',standardizeHTMLTokn(theTokn.innerHTML),false); showEdit('editwithbuttons')": ""),
	   "עצב דף זה",
	   ""
	)); 

	document.write(formHeader('addform')+idFields+
		origsubjectInput+
		orignameInput+
		origemailInput+
		'<p>'+
		bodyclassInput + 
		subjectInput + 

		'<div id="addtext" style="display:none">'+
			'<P><B>תנאי שימוש</B>: הטופס מיועד לתגובות ענייניות בלבד. ביטויי לעג וזלזול יימחקו ללא אזהרה. לחיצה על כפתור "שליחה" מהווה הסכמה לתנאי זה.' + 
			'<h3>תוכן (טקסט וקישורים):</h3>' + 
			'<p><textarea name=body COLS=50 ROWS=10></textarea>' +
		'</div>'+

		'<div id="addfile" style="display:none">'+
			'<h3>קובץ מהמחשב שלכם</h3>'+
			'<p><input type=file name=jm_qovc_al_hlqox size=40>'+
		'</div>'+

		'<div id="addlink" style="display:none">'+
			'<h3>קישור חיצוני לאתר ברחבי הרשת</h3>'+
			'<p><input type=text name=qijur dir=ltr value="http://" size=45>'+
		'</div>'+

		'<input name=add type=submit value="שליחה" onclick="if (ValidateName(theAddForm.name)&&ValidateTitle(theAddForm.title)) body.value=text2HTML(body.value)">'+
		'התגובה תופיע באתר תוך מספר דקות. אנא התאזרו בסבלנות! אם התגובה לא נשלחת - אנא כתבו דואל למנהל האתר'+

	'</FORM>');

	document.write(formHeader('editform')+idFields+
		titleInput+
		'<textarea style="display:none" name=content></textarea>'+
 		'<div id="editwithbuttons" style="display:none">' + 
			'<h3>עריכה</h3>'+
				'<p>ערכו את המסמך למטה, מלאו את פרטיכם ולחצו על "שמור שינויים".' + 
				//Usage: RichTextHTML(fieldname, html, width, height, buttons, readOnly)
				RichTextHTML('RTE', '', RTE_WIDTH, RTE_HEIGHT, true, false) + 
			'<br><input type=submit name=rewrite value="שמור שינויים" onclick="if (ValidateName(theEditForm.name)) {updateRTE(\'RTE\'); setRewriteTitle(theEditForm); theEditForm.content.value=standardizeHTMLToknAndTguvot(theEditForm.RTE.value,theTguvot.innerHTML);}">'+
		'</div>'+
 		'<div id="editinplace" style="display:none">'+
			'<h3>עריכה</h3>'+
				'<p>ערכו את המסמך למעלה, מלאו את פרטיכם ולחצו על "שמור שינויים". <small>אפשר גם להוסיף הערה שמסבירה מה תיקנתם.</small>' +
				help+
			'<br><input type=submit name=rewrite value="שמור שינויים" onclick="if (ValidateName(theEditForm.name)) {setRewriteTitle(theEditForm); theEditForm.content.value=standardizeHTML()}">'+
			(theTokn? '<button onclick="theTokn.innerHTML=removeHTMLColor(theTokn.innerHTML);">התאם עיצוב יעד</button>': '') +
		'</div>'+
		'<input type=submit name=versionlist value="הצג מהדורות קודמות">'+
	'</FORM>');

	getFormParts();

        document.onclick = toggleEdit;  
        document.onmousedown = toggleEdit;  
        // a double-click anywhere on the page will scroll the window to the buttons section
}  // end of function "tguva"



function klinihul() {
	document.write("</div><div>");   // close the outside div and open a new div, to prevent "blinking"
	getDocumentParts();

	document.write(fiveButtonsHTML(
	   "showAdd('addtext'); theAddForm.jm_qovc_al_hlqox.value=''", 
	   "הוסף דף חדש", 
	   "",
	   (documentHasEditableParts&&contentEditable? "showEdit('editinplace')": ""),
	   "תקן דף זה",
	   "",
	   (theTokn&&theTguvot? "SetRTE('RTE',standardizeHTMLTokn(theTokn.innerHTML),false); showEdit('editwithbuttons')": ""),
	   "עצב דף זה",
	   "",
	   "showAdd('addfile')",
	   "הוסף קובץ",
	   "",
	   "",
	   "",
	   ""
	));

	document.write(formHeader('addform')+idFields+
		'כתבו את הפרטים שיופיעו בכותרת של הדף החדש ולחצו על "שליחה". לאחר מכן תוכלו לערוך את התוכן של הדף החדש.' +
		origsubjectInput+
		orignameInput+
		origemailInput+

		'<p>'+

		'כותרת: ' + subjectInput + 
		'<br>'+

		'<div id="addtext" style="display:none">'+
		'</div>'+

		'<div id="addfile" style="display:none">'+
			'<h3>בחרו קובץ מהמחשב שלכם:</h3>'+
			'<p><input type=file name=jm_qovc_al_hlqox size=40>'+
		'</div>'+

		'<div id="addlink" style="display:none">'+
			'<h3>קישור חיצוני לאתר ברחבי הרשת</h3>'+
			'<p><input type=text name=qijur dir=ltr value="http://" size=45>'+
		'</div>'+

		'<input name=add type=submit value="שליחה">'+ 
                ' לאחר השליחה, תוכלו לערוך את הדף החדש, או לחזור לדף זה ולרענן אותו על-מנת לראות את הקישור לדף החדש.' +

	'</FORM>');

	document.write(formHeader('editform')+idFields+
		titleInput+
		'<textarea style="display:none" name=content></textarea>'+
 		'<div id="editwithbuttons" style="display:none">' + 
			'<h3>עריכה</h3>'+
				'<p>ערכו את המסמך למטה, מלאו את פרטיכם ולחצו על "שמור שינויים".' + 
				//Usage: RichTextHTML(fieldname, html, width, height, buttons, readOnly)
				RichTextHTML('RTE', '', RTE_WIDTH, RTE_HEIGHT, true, false) + 
			'<br><input type=submit name=rewrite value="שמור שינויים" onclick="if (ValidateName(theEditForm.name)) {updateRTE(\'RTE\'); setRewriteTitle(theEditForm); theEditForm.content.value=standardizeHTMLToknAndTguvot(theEditForm.RTE.value,theTguvot.innerHTML);}">'+
		'</div>'+
 		'<div id="editinplace" style="display:none">'+
			'<h3>עריכה</h3>'+
				'<p>ערכו את המסמך למעלה, מלאו את פרטיכם ולחצו על "שמור שינויים".' +
				help+
			'<br><input type=submit name=rewrite value="שמור שינויים" onclick="if (ValidateName(theEditForm.name)) {setRewriteTitle(theEditForm); theEditForm.content.value=standardizeHTML()}">'+
			'<button onclick="theTokn.innerHTML=removeHTMLColor(theTokn.innerHTML);">התאם עיצוב יעד</button>'+
		'</div>'+
		'<input type=submit name=versionlist value="הצג מהדורות קודמות">'+
	'</FORM>');

	getFormParts();

	document.onclick = toggleEdit;
	document.onmousedown = toggleEdit;
	// a multiple-click anywhere on the page will make the page editable/uneditable
}  // end of function "klinihul"




function ktov_forum() {
	document.write("<div style='text-align: center'>");
	if (/http:/.test(document.URL))
		document.write("<iframe name=dyunim id=dyunim width=70% align=center height=200 src=" + path_from_site_to_cgi + "/display.pl?board=nxt&showstart=0&expand=0&sort=1&maxtopics=60></iframe>");
	else
		document.write("<p style='text-align: center; margin-left: 2cm; margin-right: 2cm; padding-top: 0.5cm; padding-bottom: 0.5cm; background: #444444'><a href=../nxtboard/wwwboard.html>אתר הדיונים (קריאה בלבד)</a>");
	document.write("</div>");
}

function ktov_whatsnew() {
	theText = '';
	if (/http:/.test(document.URL)) {
		if (site=='tnk1') {
			theText = 
				"<DIV style='text-align:center; width:50%'>" + 
				"<iframe height=200 src=" + path_from_site_to_cgi + "/display.pl?file=" + site + "/board&showstart=0&expand=0&sort=1&maxtopics=20></iframe>" + 
				"<BR>"+
				"<iframe height=200 src=" + path_from_site_to_cgi + "/display.pl?file=" + site + "/whatsnew&showstart=0&expand=0&maxtopics=40>    </iframe>" + 
				"</DIV>";
		}
		else {
			theText = 
				"<DIV style='text-align:center'> <TABLE><TR>" + 
				"<TD><iframe width=400 height=200 src=" + path_from_site_to_cgi + "/display.pl?file=" + site + "/board&showstart=0&expand=0&sort=1&maxtopics=20></iframe>&nbsp;" + 
				"<TD><iframe width=400 height=200 src=" + path_from_site_to_cgi + "/display.pl?file=" + site + "/whatsnew&showstart=0&expand=0&maxtopics=40></iframe>" + 
				"</TABLE> </DIV>";
        }
    }
	else
		theText = "<p style='text-align: center; margin-left: 2cm; margin-right: 2cm; padding-top: 0.5cm; padding-bottom: 0.5cm'><a href=board.html>המאמרים האחרונים שנוספו לאתר</a>";
	document.write(theText);
}



// INPUT:
//  * path_from_root_to_file = path of a text file (in a tab-seperated-value format), relative to the site root.
// It will create three links to the file: as a table, as a list, as plain text.
//
// USAGE EXAMPLE:
// instead of:
// 	<A href=../tnk1/ezor/prtim.txt>
// say:
//  	<SCRIPT>ATSV('../tnk1/ezor/prtim.txt')</SCRIPT>
function ATSV(path_from_root_to_file) {
	if (/^[.][.][\/]/.test(path_from_root_to_file))
		path_from_main_root_to_file = path_from_root_to_file.substring(3);
	else
		path_from_main_root_to_file = site+"/"+path_from_root_to_file;
	href = path_from_document_to_site+"../_script/display.html?"+path_from_main_root_to_file;
	document.write("&nbsp;<A href="+href+"+Cards class=magr>כרטיסים</A>")
	document.write("&nbsp;<A href="+href+"+Table class=magr>טבלה</A>")
	document.write("&nbsp;<A href="+href+"+List class=magr>רשימה</A>")
//	document.write("&nbsp;<A href="+path_from_document_to_site+path_from_root_to_file+" class=magr>טקסט בלבד</A>")
}

