//<script>
var GLOBES_DBID = 147;
var BOOKS_DBID = 371;
var BUFFER_DBID = 313;
var TAKTZIR_DBID = 348;
var MACHSHAVOT_DBID = 1718;
var ALL_DBID = ".";
var MSG_POPUP_BLOCK = "Please enable popups on this website";
var HIGHLIGHT_REGION = 100;
// overWrite SafeView functions
if (typeof(NetisQuery) == "function")
{
	NetisQuery.prototype.showResults__base = NetisQuery.prototype.showResults;
	NetisQuery.prototype.showResults = function()
	{
		var oContainer = Compat.getWindow(getContainerDocument());
		var oTopbar = getTopbar();
		oTopbar.top.saveQueryParameters(this);
		if((this.resultsCount == 1) && (oTopbar.sOneResult != "yes"))
		{
			if(!oTopbar.isLoggedIn())
			{
				this.docNo= 1;
				oTopbar.showLogin("document",true, this);
				return;
			}			
			var docFrame = getAvailableDocFrame(oContainer.top.getMainFrameTab("document"));
			if (docFrame == null)//user abort
				return;
			this.submitFrame = docFrame;
			oTopbar.setDocumentTab(true);
			this.showDoc(1);
		}
		else
		{
			var oResults = oContainer.top.getMainFrameTab("results")
			if(oResults.q)
				if((this.key == oResults.q.key) && (this.key != ""))
				{	
					oTopbar.setResultListTab();
					return;
				}
			
			try { oResults.clearWindow(); } catch (e) { }  // clear existing result list
			this.submitFrame = oResults.document;
			this.showResults__base();
			oTopbar.sOneResult = "";
			oTopbar.setResultListTab();
		}
	}

	NetisQuery.prototype.showCollectionProducts = function()
	{
		var oTopbar = getTopbar();
		oTopbar.showCollectionProducts(this);
	}
	
	NetisQuery.prototype.showResultsDRM__base = NetisQuery.prototype.showResultsDRM;
	NetisQuery.prototype.showResultsDRM = function()
	{
		this.key = getQueryKey();
		this.showResultsDRM__base();
	}

	NetisQuery.prototype.showPage__base = NetisQuery.prototype.showPage;
	NetisQuery.prototype.showPage = function(pageID, bReload)
	{
		var ar = pageID.split(",");
		if (ar.length > 1)
		{
			var pageID = ar.shift();
			this.setReturnPage(ar.join(","), bReload);
			this.submitTo(pageID);
			return;
		}
		var oTopbar = getTopbar();
		switch (pageID)
		{
			case "search" : 
				if(oTopbar.sQuery != "")
					oTopbar.performQuery();
				else if (oTopbar.sToShop == "yes")
					oTopbar.viewShopPage();
				else if (oTopbar.sToDemo == "yes")
					oTopbar.showDemoHelp();
				else if (oTopbar.sToOpinion == "yes")
					oTopbar.sendOpinion();
				else
				{
					oTopbar.setAdvancedSearchTab(); 
					if (oTopbar.sToChozim == "yes")
						oTopbar.openForms("chozim");
					else if (oTopbar.sToTfasim == "yes")
						oTopbar.openForms("tfasim");
					else if (oTopbar.sToYishma == "yes")
						oTopbar.openForms("yishma");
					else if (oTopbar.sToPatent == "yes")
						oTopbar.openForms("patent");
					else if (oTopbar.sToHegbelim == "yes")
						oTopbar.openForms("hegbelim");
				}
				break;
			case "results":
					oTopbar.setResultListTab();
				 //oTopbar.showResults(bReload, this); 
				 break;
			case "document": oTopbar.showDoc(this); break;
			case "generalSearch": oTopbar.sendQuery(); break;
			case "toc": top.doOnTreeClick(top.oFocused); break;
			case "openMail": 
				oTopbar.openMail();
				oTopbar.setAdvancedSearchTab(); 
				break;
			default: 
				if(pageID.match(/openForms~(.+?)$/i))
				{
					oTopbar.setAdvancedSearchTab(true);
					oTopbar.openForms(RegExp.$1);	
				}
				else
					this.showPage__base(pageID, bReload); 
				break;
		}
	}

	NetisQuery.prototype.showDocumentProducts = function(titleID)
	{
		showDocumentInfo(titleID, this);
	}
	
	NetisQuery.prototype.goBack = function()
	{
		var oTopbar = getTopbar();
		oTopbar.showPreviousTab();
	}

	NetisQuery.prototype.showLogin__base = NetisQuery.prototype.showLogin;
	NetisQuery.prototype.showLogin = function(returnPage, bReload)
	{
		var oTopbar = getTopbar();
		if (oTopbar == null)
			document.location.replace(this.appRoot + "?ret=" + encodeURIComponent(returnPage));
		else
			oTopbar.showLogin(returnPage, bReload, this);
	}
	
	NetisQuery.prototype.onNoResults = function()
	{
		var oTopbar = getTopbar();
		oTopbar.showNoResultsPage(this.terms);
	}
}

function getQueryKey()
{
	var key = getCookie("keyQuery");
	key = (key && key < 500) ? ++key : 0;
	setCookie("keyQuery",key);
	return key;
}

function createQuery()
{
	var qRet = new NetisQuery();
	var oTopbar = getTopbar();
	oTopbar.top.getQueryParameters(qRet);
	return qRet;
}

function getTopbar()
{
	var doc = getContainerDocument();
	var w = Compat.getWindow(doc);
	return w.Compat.getFrame("topbar");
}

function showPopup(url, features, onReturn)
{
	try {
		var href = document.location.href;
		url = makeAbsolute(href.substr(0, href.lastIndexOf("/")), url);
		Compat.showModalDialog(url, null, features, onReturn);
	} catch (e) {
		alert(MSG_POPUP_BLOCK);
	}
}

function OnGotoSearchScreen()
{
	var oTopbar = getTopbar();
	oTopbar.setAdvancedSearchTab();
}

function OnGotoResultList()
{
	if(q.resultsCount == 1)
		return;
//	var oTopbar = getTopbar();
//	oTopbar.setResultListTab();
	var qTemp = q.makeCopy(globalSettings | resultSettings | searchSettings);
	qTemp.showResults();
}

function showDocumentInfo(titleID, q)
{
	try {
		var topbar = Compat.getFrame("topbar")
		topbar.setTabClass("dormant", "dormant", "dormant");
		topbar.currentTab = "";	
		var qTemp = createQuery();
		qTemp.copyFrom(q, searchSettings);
		qTemp.submitFrame = top.getMainFrameTab("info").document; 
		top.setFrame("info");
	} catch (e) { }
	var url = "TitleInfo.aspx";
	if (titleID != null )
		url += "?tid=" + titleID;
	qTemp.submitTo(url);
}

function showCollectionInfo()
{
	try {
		var topbar = Compat.getFrame("topbar")
		topbar.setTabClass("dormant", "dormant", "dormant");
		topbar.currentTab = "";	
		var q = topbar.createQuery("info");
		top.setFrame("info");
	} catch (e) { }
//	q.submitTo("CollectionInfo.aspx?dbID=" + q.dbID);
	q.submitTo("TitleInfo.aspx");
}

// If 'q.submitFrame' is not available reset it
function checkSubmitFrame(oFrame)
{
	try {var t = q.submitFrame.location}
	catch(e)
	{
		var oContainer = getContainerDocument().parentWindow;
		q.submitFrame = oContainer.top.getMainFrameTab(oFrame).document;
	}
}

function showEndPreview(titleID)
{
	if (getViewType() == "ResultList")
	{
		checkSubmitFrame("results");
		q.submitTo("endpreviewResultList.aspx");
	}
	else
	{
		checkSubmitFrame("document");
		q.submitTo("endPreview.aspx?titleID=" + titleID + "&resultsCount=" + q.resultsCount);
	}
}

function GetRightName(rightNo)
{
	switch (rightNo) {
	case 0: return MSG_RIGHT_VIEW;
	case 1: return MSG_RIGHT_COPY;
	case 2: return MSG_RIGHT_PRINT;
	case 3: return MSG_RIGHT_SAVE;
	case 4: return MSG_RIGHT_PREVIEW;
	}
	return "";
}

function OnHasNoRight(rightNo)
{
	var rightStr = new String(GetRightName(rightNo));
	if (rightStr.length == 0)
		alert(MSG_HAS_NO_RIGHT_NUM + rightNo);
	else
	{
		var sMsg = MSG_HAS_NO_RIGHT_TO_1 + rightStr + MSG_HAS_NO_RIGHT_TO_2;
		sMsg += "\n" + MSG_HAS_NO_RIGHT_TO_3;
		var bResponse = confirm(sMsg);
		if (bResponse)
			if (typeof(titleID) != "undefined")
				showDocumentInfo(titleID, q);
			else
				showDocumentInfo(null, q);
	}
}

function getSafeViewMoz(oWindow)
{
	var doc = oWindow.document;
	var o = doc.getElementsByTagName("object");
	for (var i = 0; i < o.length; i++)
		if (o[i].type == "application/x-safeview")
			return o[i];
}

function getSafeViewObject()
{
	// IE test
	try { window.external.Test(); return window.external; } catch (e) { }
	// Mozilla test
	// Because of the way result list is organized (resultlistInner in an <IFRAME> inside resultlistClient),
	// we may need to go up the window hierarchy until we reach the safeview-protected document.
	for (var w = window; true; w = w.parent)
	{
		var o = getSafeViewMoz(w);
		if (o != null)
			return o;
		if (w == w.parent)	// top of hierarchy reached, safeview not found.
			break;
	}
	return null;
}

function getContainerDocument()
{
	var oSafeView = getSafeViewObject();
	if (oSafeView == null || oSafeView.Parent == null)
		return document;
	var doc = oSafeView.Parent.document;
	return (doc == null) ? oSafeView.Parent.Document : doc;
}

//function getSafeViewObject()
//{
//	// IE test
//	try { window.external.Test(); return window.external; } catch (e) { }
//	// Mozilla test
//	//  Because of the way result list is organized (resultlistInner in an <IFRAME> inside resultlistClient),
//	//  we may need to go up the window hierarchy until we reach the safeview-protected document.
//	for (var w = window; true; w = w.parent)
//	{
//		var doc = w.document;
//		var o = doc.getElementsByTagName("object");
//		for (var i = 0; i < o.length; i++)
//			if (o[i].type == "application/x-safeview")
//				return o[i];
//		if (w == w.parent)	// top of hierarchy reached, safeview not found.
//			break;
//	}
//	return null;
//}

//function getContainerDocument()
//{
//	var oSafeView = getSafeViewObject();
//	if (oSafeView == null || oSafeView.Parent == null)
//		return document;
//	var doc = oSafeView.Parent.document;
//	return (doc == null) ? oSafeView.Parent.Document : doc;
//}

function getAvailableDocFrame(o)
{
	try {
		var oFrames = o.document.getElementsByTagName("iframe");
		var maxTab = o.maxTab;
		var iOrder = -1;
		for(var i = 0 ; i < maxTab; i++)
		{
			if (!oFrames[i].getAttribute("use"))
			{
				oFrames[i].setAttribute("use", "yes");
				if (oFrames[i].contentWindow.document.charset != "windows-1255")
					oFrames[i].contentWindow.document.charset = "windows-1255"
				return oFrames[i].contentWindow.document;
			}
			else if (oFrames[i].getAttribute("order") == 0)
				iOrder = i;
		}
		if (i == maxTab && iOrder != -1)
		{
			if (confirm(TAB_EXCEED_MSG1 + o.window.TabTitleArr[iOrder].replace(/\.\.\./, "") + TAB_EXCEED_MSG2))
			{
				o.closeTab(iOrder);
				oFrames[iOrder].setAttribute("use", "yes");
				return oFrames[iOrder].contentWindow.document;
			}
			else return null;
		}
	} catch(e) { alert("Error in getAvailableDocFrame() : " + e.toString());}
}

function goDoc(docNo)
{
	try {
		var oTopbar = getTopbar();	
		if(!oTopbar.isLoggedIn())
		{
			q.docNo= docNo;
			oTopbar.showLogin("document",true, q);
			return;
		}
		
		var oContainer = getContainerDocument();
		// Save result selection before leaving this page
		var docFrame = getAvailableDocFrame(oContainer.parentWindow.top.getMainFrameTab("document"));
		if (docFrame == null)//user abort
			return;
		q.submitFrame = docFrame;
		try{q.selectedResults = getResultSelection().join(",");}catch(e){}
		oTopbar.setDocumentTab(true);
		if (Compat.isMoz)
			setTimeout(function() { q.showDoc(docNo); }, 100);
		else
			q.showDoc(docNo);
	} catch(e) { alert("Error in go doc : " + e.toString());}
}

function _openDoc(docId, target)
{
	var qTemp = createQuery();
	qTemp.key = "searchDoc";
	qTemp.addParsedTerm(qTemp.makeTerm("DocId", docId));
	
	var oRequest = XmlHttp.createNew();
	var sURL = makeAbsolute(qTemp.appRoot, "NetisUtils/srvrutil_xmlquery.aspx?key=" + qTemp.key);
	oRequest.open("POST", sURL, false);
	oRequest.send(qTemp.getQueryXML());

	var doc = oRequest.responseXML;
	var root = doc.documentElement;
	switch (root.tagName)
	{
		case "login" :
			alert(MSG_LOGIN_FIRST);
//			Compat.getFrame("topbar").showLogin("toc.aspx");
			return;
			break;
		case "error": throw "Server error:\n\n" + root.text;		// the server threw an exception
		case "info": throw root.text;								// server wants to tell us something
		case "query": break;										// proceed with parsing
		default: throw "Unexpected server response";
	}
	
	var total = parseInt(root.getAttribute("total"));
	qTemp.qid = root.getAttribute("qid");
	switch (total)
	{
		case 0:
			alert("The requested document not found [" + docId + "]");
			break;
		case 1:
			// in case of 1 result - keep the original result list in topbar frame
			var oTopbar = getTopbar();
			oTopbar.top.saveQueryParameters(q);
			qTemp.showDoc(1);
			break;
		default:
			if (confirm(total + " matching documents found. Display search results?"))
				qTemp.showResults();
			break;
	}
}

function toggleImage(doc, sImgId, bDisabled)
{
	try{
		var oImg = doc.getElementById(sImgId);
		oImg.disabled = bDisabled;
		if(oImg.tagName.toLowerCase() == "img")
			oImg.src = oImg.src.replace(/(-dis)?.gif/i,((bDisabled) ? "-dis" : "") + ".gif");
		else
			oImg.className = oImg.className.replace(/Dis$/,"") + ((bDisabled) ? "Dis" : "");
		oImg.style.cursor = ((bDisabled) ? "default" : "pointer");
		if(!oImg.onclickORIG)
		{
			oImg.onclickORIG = oImg.onclick;
			oImg.onclick = function() { if (!this.disabled) this.onclickORIG(); }
		}
	}catch(e) {}
}

function getDocType()
{
	var docType = null;
	//High protection
	try{ 
		docType = getToolbar().curDocType;
		if(!docType)
			docType = getToolbar().parentWindow.curDocType;
	}
	// Low protection
	catch(e)
	{
		docType = getToolbar().parentWindow.curDocType;
	}
	return (docType == null) ? "" : docType;
}

function getCurDocPath()
{
	var curDocPath = null;
	//High protection
	try{ 
		curDocPath = getToolbar().curDocPath; 
		if(!curDocPath)
			curDocPath = getToolbar().parentWindow.curDocPath;
	}
	// Low protection
	catch(e)
	{
		curDocPath = getToolbar().parentWindow.curDocPath;
	}
	return (curDocPath == null) ? "" : curDocPath;
}

function getCurPDFPath()
{
	var curPDFPath = null;
	//High protection
	try{ 
		curPDFPath = getToolbar().curPDFPath; 
		if(!curPDFPath)
			curPDFPath = getToolbar().parentWindow.curPDFPath;
	}
	// Low protection
	catch(e)
	{
		curPDFPath = getToolbar().parentWindow.curPDFPath;
	}
	return (curPDFPath == null) ? "" : curPDFPath;
}

function OnHighlightDone(n)
{
	var oDoc = getToolbar();
	if (n == 0)
	{
		toggleImage(oDoc, "imgPrevHighlight", true);
		toggleImage(oDoc, "imgNextHighlight", true);
		toggleImage(oDoc, "imgToggleHighlight", true);
	}
	if (q.resultsCount == 1)
	{
		toggleImage(oDoc, "imgPrevDoc", true);
		toggleImage(oDoc, "imgNextDoc", true);
		toggleImage(oDoc, "imgResultList", true);
	}
	showHideLock();
	showHidePDF();
	var docType = getDocType();
	switch (docType.toLowerCase())
	{
		case "scan" : 
		case "" : 
			try {oDoc.parentWindow.hideResizeButtons() ; } catch(e){}
			toggleImage(oDoc, "imgFind", true);
		case "sigi":
		case "globes":
		case "savir":
			toggleImage(oDoc, "imgIzkurim", true);
			break;
		case "hakika":
			var openDocMap = getCookie("openDocMap");
			if(openDocMap != "no")
				oDoc.parentWindow.toggleMap();
			break;
		default : 
	}
	// If we are comming to a document not by running a query(Remarks...)
	if (noQuery)
	{
		toggleImage(oDoc, "imgPrevDoc", true);
		toggleImage(oDoc, "imgNextDoc", true);
		toggleImage(oDoc, "imgResultList", true);
		toggleImage(oDoc, "imgPrevHighlight", true);
		toggleImage(oDoc, "imgNextHighlight", true);
		toggleImage(oDoc, "imgToggleHighlight", true);
		toggleImage(oDoc, "imgIzkurim", true);
	}
	if (hasComment)
	{
		var imgHndl = oDoc.getElementById("imgComments");
		if (imgHndl)
			imgHndl.className = "tlbChangeComment";
	}
}

function initTemplatesCombo()
{
	function onTemplatesLoaded(xmlTemplates)
	{
		if (xmlTemplates.documentElement == null)
			return;
		var oTemplates = xmlTemplates.selectNodes("/templates/template");
		var numTemplates = oTemplates.length;
		if (numTemplates < 2)
		{
			templatesCombo.setAttribute("view", "0");
			return;
		}
		for (var i = 0; i < numTemplates; i++) {
			var o = oTemplates.item(i);
			var sName = o.getAttribute("name");
			var sTitle = o.getAttribute("title");
			if (sTitle == null || sTitle == "")
				sTitle = sName;
			var oOption = new Option(sTitle + " display", sName);
			templatesCombo.options.add(oOption);
			if (sName == q.template)
				oOption.selected = true;
		}
		// Templates combo is hidden by default.
		// Only show it if more than one template is available.
		templatesCombo.style.display = "inline";
	}

	var templatesCombo = document.getElementById("templates");
	if (templatesCombo != null)
		XmlDoc.createIsland("srvrutil_templatesList.aspx?dbID=" + q.dbID, onTemplatesLoaded);
}

// return field type
function getFieldType(fieldName)
{
	var numFields = ["pageFrom", "pageTo", "Year", "DateSort", "BookletRL", "Booklet", "Page", "MMPPage", "CollectionID", "AncestorID", "taktzirID"];
	var dateFields = ["Update", "DateIndex"];
	for (var i in numFields)
		if (numFields[i] == fieldName)
			return "num";
	for (var i in dateFields)
		if (dateFields[i] == fieldName)
			return "date";
	return "word";
}

// return field type
function getFieldTypeShort(fieldName)
{
	var sFlag =  getFieldType(fieldName);
	switch (sFlag)
	{
		case "word" : return "w";
		case "num" : return "n";
		case "date" : return "d";
	}
	return "w";
}

function createTerm(fieldName, fieldValue)
{
	if (fieldValue.match(/^\"(.*)\"$/))
		return q.makeTerm(fieldName, RegExp.$1, "expr");
	var fieldType = getFieldType(fieldName);
	if (fieldName == "CaseType")
		return q.makeTerm(fieldName, fieldValue, fieldType);
	if ((fieldName == "ID") && (fieldValue.indexOf(" ")!=-1))
	{
		var arrID = fieldValue.split(" "); 
		var s = "<or>";
		for (var k=0; k < arrID.length; k++)
			s += q.makeTerm(fieldName, arrID[k], fieldType);
		s += "<\/or>";
		return s;
	}
	return q.makeTerm(fieldName, fieldValue, fieldType);
}

//on link click in Safeview
function OnLinkClicked(query) 
{ 
	try 
	{
		var qLink = q.makeCopy(globalSettings | resultSettings);
		//Globes
		if (qLink.dbID == GLOBES_DBID || qLink.dbID == BUFFER_DBID ||  qLink.dbID == TAKTZIR_DBID) 
			qLink.dbID = ".";

		try{
			if ((query == null) || (query == undefined) || (query == ""))
			{
				var HtmlCtl = SafeView.getObject();
				HtmlCtl.Test();
				query = new String(HtmlCtl.GetQuery());
			}
		}catch(e){alert("Error OnLinkClicked - " + e.description);}

		var fields = trim(query).split(";");
		var fieldName;	
		for (i = 0; i < fields.length; i++)
		{
			var ar = fields[i].split(":");
			fieldName = ar[0];
			var fieldValue = unescape(decodeURI(ar[1]));
			if (fieldName == "TakMachshavot")
			    qLink.dbID = MACHSHAVOT_DBID;			
			if(fieldName == "Type")
			    fieldValue = fieldValue.replace("תקציר(פסיקה", "תקצירפסיקה");
			if (fieldValue.match(/^\"(.*)\"$/))
				qLink.addParsedTerm(qLink.makeTerm(fieldName, RegExp.$1, "expr"));
			else{
				if(fieldName == "CaseType")
				    qLink.addTerm(fieldName, fieldValue, "tp");
    			else if (fieldName == "DateIndex")
    			    qLink.addTerm(fieldName, fieldValue, "d");
				else
				{
					if(fieldName == "ID" || fieldName== "TakMachshavot")
					{
						var arrID = fieldValue.split(" "); 
						qLink.terms += "<or>";
						for (var k=0; k < arrID.length; k++)
						{
							qLink.addParsedTerm(qLink.makeTerm(fieldName, arrID[k], getFieldType(fieldName)));
							if(arrID[k].indexOf("\/")!=-1)
							    qLink.addParsedTerm(qLink.makeTerm(fieldName, arrID[k].replace(/\//, "-"), getFieldType(fieldName)));
							if(arrID[k].indexOf("-")!=-1)
							    qLink.addParsedTerm(qLink.makeTerm(fieldName, arrID[k].replace(/-/, "\/"), getFieldType(fieldName)));
						}
						qLink.terms += "<\/or>";
					}
					else
					{
						qLink.addParsedTerm(qLink.makeTerm(fieldName, fieldValue, getFieldType(fieldName)));
						if((fieldName == "ID") && ((/^[א-ת]+[0-9_a-z]*@[0-9_a-z]+$/).test(fieldValue))) //link hakika
							qLink.addTerm("CaseType", "חקיקה@מעודכנת", "tp");										
					}
				}
			}
//			var s = createTerm(fieldName, fieldValue);
//			qLink.addParsedTerm(s);
	    } 
		qLink.sortBy("Type", 1);
		qLink.sortField2 = "";
		qLink.sortOrder2 = 0;
		
		if (fieldName == "savir_toc_link")
			qLink.template = "SavirTOC";
		else if (fieldName == "Subject" || fieldName == "Author") // maamarim
		{
			qLink.sortBy("Type", -1);
			qLink.sortField2 = "Header";
			qLink.sortOrder2= 1;
			qLink.template = "Maamarim";
			qLink.template = "Maamarim";	
		}
		else if (qLink.terms.indexOf("תקציר") > 0)
		{
			qLink.template = "Taktzirim"; // dummy
			qLink.dbID = TAKTZIR_DBID;
		}
		else if (fieldName == "Author")
            qLink.template = "Maamarim";
		else
		    qLink.template = "Shiluv";

		if (qLink.dbID != MACHSHAVOT_DBID)
		    if (qLink.terms != "") {
		        qLink.terms = "<not><and>" + qLink.terms + "</and><t f=\"Type\" v=\"כותרפסיקה\"/></not>";
		    }

	    /*if (qLink.dbID == MACHSHAVOT_DBID)
	        qLink.showDoc(1);
	    else*/
	        qLink.showResultsDRM();
	}
	catch(e)
	{
		alert(e.toString());
		alert(MSG_INVALID_LINK + MSG_POPUP_BLOCK);
		MSG_POPUP_BLOCK = "";
	}
}

function showIzkurimDialog()
{
	var izkurimDialogPath = "Izkurim.html";
	if(q != null)
		izkurimDialogPath = "../" + izkurimDialogPath;
	var sCurDocType = getDocType();
	if(sCurDocType == "Hakika" || sCurDocType == "Psika" || sCurDocType == "Scan" || sCurDocType == "taktzir")
	{
		var sHeight = (sCurDocType == "Hakika" ? "350" : "500");
		var features = Compat.fixDialogSize({ width: 450, height: sHeight - 20, heightIE7: sHeight - 20, heightIE: sHeight, help: "no", scroll: "no", status:"no" });
		var args = { openerwin: window};
		Compat.showModalDialog(izkurimDialogPath, args, features);
	}
	else
		alert(".לא ניתן למצוא איזכורים של מסמך זה");	
	
}
function showCommentsDialog(imgHndl)
{
	if (getTopbar().bIsGuest)
	{
		alert("פעולה זו זמינה למנויים בלבד");
		return;
	}

	try
	{
		var sHeight = 390;
		var features = Compat.fixDialogSize({ width: 450, height: sHeight, heightIE7: sHeight - 20, heightIE: sHeight + 10, help: "no", scroll: "no", status:"no" });
		var args = { openerwin: window, imgHndl: imgHndl};
		Compat.showModalDialog("../Comments.html", args, features);
	}
	catch(e)
	{
		if (e.number == -2147024891) // Popup blocker "Access is denied"
			alert(MSG_POPUP_BLOCK);
	}
}

function showCommentsDialogRL(docNo, header, imgHndl)
{
	if (getTopbar().bIsGuest)
	{
		alert("פעולה זו זמינה למנויים בלבד");
		return;
	}
	try
	{
		var sHeight = 390;
		var features = Compat.fixDialogSize({ width: 450, height: sHeight, heightIE7: sHeight - 20, heightIE: sHeight + 10, help: "no", scroll: "no", status:"no" });
		var iTilde = header.indexOf("~~");
		if(iTilde !=-1)
			header = header.substring(0, iTilde);
		if (header == "")//Globes...
		{
			header = getTopbar().top.sMareMakom;
			var iIndex = header.indexOf(" | ");
			header = (iIndex != -1)? header.substr(iIndex + 2) : header;
		}
		var args = { openerwin: window, userID :userID, docID: docNo, header: header, imgHndl: imgHndl};
		Compat.showModalDialog("../Comments.html", args, features);
	}
	catch(e)
	{
		if (e.number == -2147024891) // Popup blocker "Access is denied"
			alert(MSG_POPUP_BLOCK);
	}
}
///////////////////Document////////////////////////////////////
function goIzkurim(par,searchIn)
{

	try 
	{
		var qLink = (q == null ? top.savedQuery.makeCopy(globalSettings | resultSettings) : q.makeCopy(globalSettings | resultSettings) );
		
		qLink.template = "Shiluv";
		qLink.dbID = ".";
		
		var sCurDocType	= getDocType(); 
		if(sCurDocType == "Psika" || sCurDocType == "Scan" || sCurDocType == "taktzir")
		{
			var fields = tbrDocId.split(" ");
			if (fields.length == 1)
				qLink.addParsedTerm(qLink.makeTerm("Ref", fields[0], "word"));
			else 
			{
				for (var i in fields)
					fields[i] = "<t v=\"" + fields[i] + "\"/>";
				qLink.addParsedTerm("<or f=\"Ref\">" + fields.join("") + "</or>");
		    }
			if (searchIn != "Globes")
			{
				qLink.addParsedTerm(q.makeTerm("Type", "פסיקה", "word"));
				qLink.template = "PsikaBody";
				if(getCookie("psikaTemplate") == 'Psika')
					qLink.template = "Psika";
			}
		}	
		else 
		{
			if (par != "")
				qLink.addTerm("Ref","|s0(" + tbrDocId + " " + par + ")"); 
			else	
				qLink.addTerm("Ref",tbrDocId);
		}

			
		qLink.sortBy("DateSort", -1);

		//qLink.submitFrame =  parent.titles.document;
		qLink.showResultsDRM();
	}
	catch (error) {
		alert(error.toString());
	}
}
///////////////////End Document////////////////////////////////////

///////////////////Result List ////////////////////////////////////

//Changes on the fly in Result list
function fixRL(oXml)
{
try{
	var oItems = oXml.selectNodes("//item");
	var arrCommentsRL = null;
	var arrHasCommentsRL = null;
	var sAttrValue;
	for (var i = 0; i < oItems.length; i++)
	{
		//set the Comments column
		if(arrCommentsRL == null)
		{
			var resDocElement = getDocComment();
			if(typeof(resDocElement) == "object")
            {
			    arrCommentsRL = resDocElement.selectSingleNode("docID").text.split("~");
			    arrHasCommentsRL = resDocElement.selectSingleNode("hasComment").text.split("~");
            }
		}
        if(arrCommentsRL != null)
        {
		    oItems.item(i).setAttribute("CommentsRL", arrCommentsRL[i]);
		    oItems.item(i).setAttribute("HasCommentsRL", arrHasCommentsRL[i]);
        }
		
		//psika begin : arrange the psika begin text and style
		if((q.template == "PsikaBody") && (bIsGuest == false))
		{
			sAttrValue = bodyValue(oItems.item(i).getAttribute("psikaBegin"));
			oItems.item(i).setAttribute("psikaBegin", sAttrValue);
		}
	}
	return oXml;
}catch(e){return oXml;}
}

//Change Style and text of the begin text in Psika result list
function bodyValue(sVal)
{
	if(sVal.indexOf("<\/b>") == -1)
	{
		sVal = sVal.replace(/^[\s\t ]+/g,"");
		var oReg = new RegExp(/^((צ\s*ו)|(פ\s*ס\s*ק\s*[–-]?\s*ה?\s*ד\s*י\s*ן)|(ה\s*ח\s*ל\s*ט\s*ה\s*)|(ה\s*כ\s*ר\s*ע\s*ת\s*-?\s*ה?\s*ד\s*י\s*ן)|(ג\s*ז\s*ר\s*-?\s*ה?\s*ד\s*י\s*ן))/);
		if (oReg.test(sVal))
			sVal = sVal.replace(oReg,RegExp.$1 + "<\/b> ,");
		
		if (sVal.length > 100)
			return sVal + "....";
		
		if (sVal.length<50)
			return "";
	}		
	return sVal;		 
}

function getDocComment()
{
	var customer = getCookie("CustomerQueryName");
	if (customer == null)
	    customer = "כל המשתמשים";
	var xmlhttp = XmlHttp.createNew();
	var URL = q.appRoot + "getDocComments.aspx?userID=" + userID + "&customer=" + Compat.xmlEncode(customer);
	URL += "&qid=" + q.qid + "&key=" + q.key + "&sortField=" + q.sortField + "&sortOrder=" + q.sortOrder; //clientParams
	URL += "&page=" + q.page + "&RPP=" + q.resultsPerPage;		
	xmlhttp.open("GET", URL, false);
	xmlhttp.send("");
	var doc = xmlhttp.responseXML;
	var root = doc.documentElement;
	if (root == null || root.tagName == "error") 
		return "";
	else
		return root;
}

//initialization of the result list elements
function initRL()
{
	try {
	// if results from buffer - do not allow "search in results" or "save query"
	if (q.dbID == BUFFER_DBID)
		setDisplay(["marketingBar"], false);
	switch(q.template.toLowerCase())
	{
		case "psikabody":
		case "psika":
			setDisplay(["RL_Tags"], true);
			// Show first HighLight ???
			var isHighlightField = ((q.terms.indexOf("f=\"Body\"") > 0) || (q.terms.indexOf("f=\"CaseRef\"") > 0) || (q.terms.indexOf("f=\"Ref\"") > 0));
			if (getCookie("showHL") != "0" && isHighlightField)
				document.getElementById("psikaHL").checked = true;
			
			if (!isHighlightField)
				setDisplay(["HL_CB"], false);
				
			// Show Begin of document ???
			if (getCookie("psikaTemplate") == 'Psika')
			{
				document.getElementById("psikaBody").checked = false;
				
				if(q.template == 'PsikaBody')
					q.template = "Psika";
			}				
			else
			{
				document.getElementById("psikaBody").checked = true;
				
				if(q.template == 'Psika')
					q.template = "PsikaBody";
			}				
			break;
		case "kitveitaanot":
		case "shiluv":
			if (q.terms.indexOf("f=\"Body\"") > 0)
			{
				setDisplay(["RL_Tags"], true);
				setDisplay(["Begin_CB"], false);
			
				// Show first HighLight ???
				if (getCookie("showHL") != "0" && q.terms.indexOf("f=\"Body\"") > 0)
					document.getElementById("psikaHL").checked = true;
			}
			break;
		case "globes":
			if (q.terms.indexOf("f=\"ArticleContent\"") > 0)
			{
				setDisplay(["RL_Tags"], true);
				setDisplay(["Begin_CB"], false);
			
				// Show first HighLight ???
				if (getCookie("showHL") != "0" && q.terms.indexOf("f=\"ArticleContent\"") > 0)
					document.getElementById("psikaHL").checked = true;
			}
			break;
	}		
	}catch(e){alert("Error to initRL : " + e.description);}	
}

//Set highlight on mouse over record in result list
function onMouse(oRow,sType)
{
	var oHighlightRow;
	if (oRow.className.indexOf("highlight") == -1)
	{
		oHighlightRow = oRow.nextSibling;
		if(oHighlightRow)
			if (oHighlightRow.className.indexOf("highlight") == -1)
				oHighlightRow = null;
	}
	else
	{
		oHighlightRow = oRow;
		oRow = oHighlightRow.previousSibling;
	}
	
	if (oRow.className != "checkedRow")
	{
		oRow.className = "rlRowMouse" + sType;
		if(oHighlightRow)
			oHighlightRow.className = "highlight" + sType;
	}
	else if(oHighlightRow)
			oHighlightRow.className = "highlight";
}

//go to Taktzir file form result list (click on the image in the column Taktzirim)
function goToTaktzirFromRL(sQuery)
{
	OnLinkClicked(sQuery.replace(/netis:\/\/\//i,"").replace("תקציר(פסיקה","תקצירפסיקה"));
}

//go to Izkurim form result list (click on the image in the column Izkurim)
function goIzkurimFromRL(evt)
{
	try {
		var qLink = (q == null ? top.savedQuery.makeCopy(globalSettings | resultSettings) : q.makeCopy(globalSettings | resultSettings) );
		qLink.dbID = ".";
		var evt = Compat.getEvent(evt);
		var fields = evt.target.getAttribute("name").toLowerCase().split(" ");
		var iTotal = new Number(evt.target.innerText);
		for (var i in fields)
			fields[i] = "<t v=\"" + fields[i] + "\"/>";
		qLink.addParsedTerm("<or f=\"Ref\">" + fields.join("") + "</or>");
		if(qLink.terms != "")
		{
			qLink.addTerm("Type", "פסיקה");
			qLink.sortBy("DateSort", -1);
			qLink.showResultsDRM();
		}
	}
	catch (error) {
		alert(error.toString());
	}
	evt.stopPropagation();
} 

//Display the begin text (change template "Psika" to "psikaBody"
function changePsikaTemplate()
{
	var sTemplateName = 'Psika';
	if (document.getElementById("psikaBody").checked)
		sTemplateName = 'PsikaBody';
	setCookie("psikaTemplate", sTemplateName);
	setTemplate(sTemplateName);
}

///////////////////End Result List ///////////////////////////

/////////////////// Utils ////////////////////////////////////

function attributeValue(obj, attrName)
{
	var s = obj.getAttribute(attrName);
	return (s == null) ? "" : s;
}

//set cookie
function setCookie(sName, sValue)
{ 
	path = "/";
	document.cookie = sName + "=" + escape(sValue) + "; expires=Fri, 31 Dec 3000 23:59:59 GMT;path=" + path;
}
 
//get cookie
function getCookie(sName)
{
  //cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    //a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0])
      return (aCrumb[1] == null) ? null : unescape(aCrumb[1]);
  }
 
  //a cookie with the requested name does not exist
  return null;
}

function trim(str)
{
	return str.replace(/^\s+/,"").replace(/\s+$/,"");
}
/////////////////// End Utils ////////////////////////////////

// Fix RL table on resize
function fixHeight(elem)
{
	var frameHND = document.getElementById("doc");
	frameHND.style.width = "100%";
	if (elem == null)
	{
		//Mozilla
		if (frameHND.contentDocument)
			elem = frameHND.contentDocument.getElementById("rlTableDiv")
		else // IE
			elem = document.frames[0].document.getElementById("rlTableDiv");
	}
	if (elem == null)
		return;
	
	// We want to resize elem so that it fits completely in parent's client area.
	// The deltas are needed to accomodate browser-specific quirks.
	function _fixSize()
	{
		var newHeight = papa.clientHeight - elem.offsetTop;
		if(newHeight > 0)
			elem.style.height = newHeight  + "px";
	}

	// Default deltas for IE in quirks mode:
	// account for the difference between elem's outer and inner dimensions.

	var papa = elem.offsetParent;

	if (document.defaultView)
	{
		// In Mozilla, we have to account for parent's borders instead.
		// We also cheat a bit by subtracting 1 pixel if elem is not positioned at (0, 0),
		// as in the case of safeview-protected document with toolbar at the top.
		var parentStyle = document.defaultView.getComputedStyle(papa, "");
		deltaH = function() 
		{
			return parseInt(parentStyle.borderTopWidth) + parseInt(parentStyle.borderBottomWidth) +
			((elem.offsetTop) ? 1 : 0);
		}
		deltaW = function() 
		{
			return parseInt(parentStyle.borderLeftWidth) + parseInt(parentStyle.borderRightWidth) +
			((elem.offsetLeft) ? 1 : 0);
		}
	}
	var origWidth = papa.clientWidth, origHeight = papa.clientHeight;
	_fixSize();
	// If parent's client area has changed because scrollbars are gone, we have to recalculate.
	if (papa.clientWidth != origWidth || papa.clientHeight != origHeight)
		_fixSize();
}

function showHidePDF()
{
	var oDoc;
	try //No SafeView
	{
		oDoc = getToolbar();
	}catch(e)// In SafeView
	{
		oDoc = getContainerDocument();
	}
	var curPDFPath = getCurPDFPath();
	if (curPDFPath != "")
	{
		var oImg = oDoc.getElementById("imgpdfdoc");
		if (oImg != null)   //If there is no toolbar
			oImg.style.visibility = "visible";
	}
}

function _showHideLock()
{
	var oDoc;
	try //No SafeView
	{
		oDoc = getToolbar();
	}catch(e)// In SafeView
	{
		oDoc = getContainerDocument();
	}
	if(oDoc.readyState != "complete")
		setTimeout(_showHideLock, 1000);

    var oImg = oDoc.getElementById("imglockdoc");
    try {
        if (rights[Rights.SAVE] == 0)
            oImg = null;
    } catch (e) { }
		
	if (oImg != null)   //If there is no toolbar
		oImg.style.visibility = "visible";

    oImg = oDoc.getElementById("imgSendToFriend");
    try {
        if (rights[Rights.SAVE] == 0)
            oImg = null;
    } catch (e) { }	
	if (oImg != null)   //If there is no toolbar
	    oImg.style.visibility = "visible";

    //if the right is view only : don't diplay print and save (taktzirim machshavot)
	try {
	    if (rights[Rights.PRINT] == 0) {
	        oImg = oDoc.getElementById("imgPrint");
	        if (oImg != null)   //If there is no toolbar
	            oImg.style.visibility = "hidden";
        }
        if (rights[Rights.SAVE] == 0) {
            oImg = oDoc.getElementById("imgSave");
            if (oImg != null)   //If there is no toolbar
                oImg.style.visibility = "hidden";
        }
        if (rights[Rights.COPY] == 0) {
            oImg = oDoc.getElementById("imgCopy");
            if (oImg != null)   //If there is no toolbar
                oImg.style.visibility = "hidden";
        }
    } catch (e) { }
}

function showHideLock()
{
	var viewingRights;
	try //No SafeView
	{
		viewingRights = rights[Rights.VIEW];
	}catch(e)// In SafeView
	{
		viewingRights = SafeView.getNode().CheckLocalRight(Rights.VIEW);
	}
	if (viewingRights != 0 )
		_showHideLock();
}

function isInApplication()
{
	// If in application there is a topbar
	return (getTopbar() != null);
}

function cleanTextLinkInNewWin(oLink)
{
	try {
		//לתקציר פסק הדין
		var sInnerHtml = oLink.innerHTML;
		sInnerHtml = sInnerHtml.replace(/<[^>]+>/ig, "");
		if((/((לתקציר פסק הדין)|(לפסק הדין המלא)|(לתקציר - מאגר סביר))/).test(sInnerHtml))
			 oLink.innerHTML = "";
		return oLink.innerHTML;
	}catch(e){alert(e.description);return null;}
}

function cleanDocumentFromLinks(doc)
{	try{
		var linkCollection = doc.getElementsByTagName("a");
		for (var i = 0; i < linkCollection.length; i++)
		{
			try // Some document(links) fail here
			{
				linkCollection[i].innerHTML = cleanTextLinkInNewWin(linkCollection[i]);
			}catch(e){}
			linkCollection[i].href = "javascript:;";
			linkCollection[i].removeAttribute("target");
			linkCollection[i].onclick = "javascript:;";
			linkCollection[i].style.textDecoration = "none";
			linkCollection[i].style.color = "black";
			linkCollection[i].style.cursor = "default";
		}
	}catch(e){alert(e.description);}	
}

function isImgFile()
{
	var oTopbar = getTopbar();
	var sCurDocType = getDocType();
	return (sCurDocType == "Scan" || sCurDocType == "Yalkut")
}

function saveAsImg()
{
	var newWindow = window.open(tbrDocPath.replace("https","http"),"SaveImage","directories=yes,status=yes,menubar=yes,toolbar=yes, resizable=yes, top=100000,left=100000, width=0, height=0"); 
	newWindow.document.execCommand("SaveAs");
	newWindow.close();
}

var SVMinVersion = 313;
function getSafeviewVersion()
{
	if (Compat.isIE)
	{
		try
		{
			var oSafeview = new ActiveXObject("SafeView.Navigator");
			return getVersionNumber(oSafeview.Test());
		}
		catch(e)
		{
			var oSafeview = new ActiveXObject("SafeView.DRM");
			return getVersionNumber(oSafeview.Test());
		}
	}
	else return SVMinVersion;
}

function getVersionNumber(str)
{
	return str.substr(str.lastIndexOf(".") + 1, str.length);
}

function sendToFriend()
{	

	var docFrameID = frameElement.id.replace("fdoc","");
 	var docTitle = parent.document.getElementById("font_" + docFrameID).title;
 	var sCurDocPath = (q.dbID == BUFFER_DBID) ? getCurDocPath() : "";

	try
	{	// Safe-View docURL == null
		var o = SafeView.getObject();
		var node = SafeView.getNode();
		for ( var param in node.childNodes)
			if (node.childNodes[param].name == "DocID")
				var docID = node.childNodes[param].value;
		getTopbar().sendToFriend(null, docID, docTitle, sCurDocPath);
	}catch(e)
	{/*Low protection docID == null */
		getTopbar().sendToFriend(docURL, null, docTitle,sCurDocPath);
	}
}

function openNewWin(sUrl ,bSelf)
{   
    if (bSelf)
	    Compat.openWindow({ url: sUrl, name:"_blank", focus: true },{ width:460, height:250, menubar:"no"});
	else
	    Compat.openWindow({ url: sUrl, name:"_blank", focus: true },{ width:850, height:470,left:200,top:200, menubar:"no"});
}

function unparseTerms(sTerms)
{
    try{
		var arrTerms;
		var arrTermsMissim = new Array();
		var xmlDoc = XmlDoc.loadXml("<terms>" + sTerms + "</terms>");

		if (xmlDoc.parseError.errorCode != 0)
			return;
	
		var oTerms = xmlDoc.firstChild.childNodes;
		var arrFields;
		var arrFieldsMissim;
		var arrPsika = new Array("Type", "Sides", "CaseNumber", "DateIndex", "JudgeName", "Body");
		var arrPsikaMissim = new Array("type", "P_Sides", "P_case_number", "DateIndex", "P_judge_name", "FullText");
		var arrHakika = new Array("Type", "LawName", "Body", "LawChapter");
		var arrHakikaMissim = new Array("type", "L_Name", "FullText", "L_ParTitle");

        var	oRegExpType = /<t f=['"]type['"][^>]+v=['"]((פסיקה)|(חקיקה))['"]/ig;
        var arrType = oRegExpType.exec(sTerms);
        if (arrType == null) 
            return "";
        var sType = arrType[1];
        var sValue = "";
        switch(sType)
        {
            case "פסיקה":
                arrFields = arrPsika;
                arrFieldsMissim = arrPsikaMissim;
                sType = "Psika";
                break;
            case "חקיקה":
                arrFields = arrHakika;
                arrFieldsMissim = arrHakikaMissim;
                sType = "Hakika";
                break;
        }
		var	oRegExp = /<(.+?) f=['"](.+?)['"]/ig;
 		for (var i = 0;i<oTerms.length;i++)
		{
			var sXMLTerm = oTerms[i].xml;
			if (sXMLTerm.match(oRegExp) == null) 
				continue;
			
			var sFieldName = RegExp.$2;
			if((sFieldName == "CaseType") || (sFieldName == "PagesRL"))
			    continue;
			var sFieldValue = unparse(sXMLTerm);
			var sFieldMissim = "";
			for (var j=0;j < arrFields.length;j++)
				if (arrFields[j] == sFieldName)
				{
				    sFieldMissim = arrFieldsMissim[j];
				    if(sFieldMissim == "type")
				        sFieldValue = sType;
				    break;
				}
			if(sFieldMissim == "")
			    return "";
			arrTermsMissim.push(sFieldMissim + ":" + sFieldValue);
		}
		return arrTermsMissim.join(";");
		
	}catch(e){alert("search form " + e.description); return "";}	
}

