
//<script>
// overWrite SafeView functions
if (typeof(NetisQuery) == "function")
{
	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 "default" : alert("go default"); break;
			case "search" :  q.submitTo("SearchForm.aspx");break;
			case "results":  oTopbar.showResults(bReload, this); break;
			case "document": q.showDoc(q.docNo); break;
			case "generalSearch": oTopbar.sendQuery(); break;
			case "toc": top.doOnTreeClick(top.oFocused); break;
			default: this.showPage__base(pageID, bReload); break;
		}
	}
}

function getTopbar()
{
	var doc = getContainerDocument();
	var w = doc.parentWindow;
	return w.Compat.getFrame("topbar");
}
var mozTitleLength = 8;
var ieTitleLength = 10;
var titleLength = Compat.isMoz ? mozTitleLength : ieTitleLength;

function OnGotoInfoPage()
{
	q.submitTo("CollectionInfo.aspx?dbID=" + q.dbID);
}

function OnGotoSearchScreen()
{
    Compat.getFrame("topbar").advancedSearch('yes');
}

function OnGotoResultList()
{
    if(q.resultsCount == 1)
        return;
    var resIndex = parent.document.getElementById(parent.focusedIndex).getAttribute("resIndex");
    if(!resIndex || !parent.document.getElementById(resIndex))
        q.showResultsDRM();
    else
        parent.showIt(resIndex);
}

function testRet(ret)
{
	if (ret)
		OnGotoInfoPage();
	else
		OnGotoResultList();
}

function isEncyclopediaAncestor(root)
{
    var oNodes = root.selectNodes("collection")
	for (var i = 0; i < oNodes.length; i++)
	{
		var o = oNodes.item(i);
		var iId = o.getAttribute("id");
		if(iId == "407449") //talmudic
		    return true;
	}
	return false;
}

function getAncestorsNode(nodeId)
{
	    XmlDoc.createIsland(q.appRoot + "NetisUtils/srvrutil_getAncestors.aspx?dbID=" + nodeId,
	    function(data) {
		    var root = data.documentElement;
		    if (root == null)
			    return;
		    if (root.tagName != "error")
		    {
			    _onEndPreview(isEncyclopediaAncestor(root));
			    return;
			}
		   _onEndPreview(false);
	    });	
}

function isEncyclopedia()
{
	try {
	XmlDoc.createIsland(q.appRoot + "NetisUtils/srvrutil_getNearestParentCollection.aspx?tid=" + titleID,
	function(data) {
		var root = data.documentElement;
		if (root == null)
			return;
		if (root.tagName != "error")
        {
            var nodeId = root.selectSingleNode("//result").getAttribute("value");
            getAncestorsNode(nodeId);
            return;
        }
        _onEndPreview(false);		
	});
	} catch(e) {_onEndPreview(false);}
}

function _onEndPreview(bEncyclopedia)
{
    var titles = Compat.getFrame("titles");
    var endPreviewTab = titles.endPreviewTab;
    var ind = this.frameElement.getAttribute("tabId");

    //If end preview tab exist just show it
    if(endPreviewTab != null)
    {
        var tab = titles.document.getElementById(titles.endPreviewTab);
        if(tab != null)
        {
            //trick to avoid closing the wrong tab (ind holdes the tab index of end preview)
            titles.focusedIndex = ind;
            titles.closeIframe();
            titles.showIt(endPreviewTab);
        	var oIframe = titles.document.getElementById("iFrame" + endPreviewTab);
            //display encyclopedia message
            try {
                oIframe.contentWindow.initEndP(bEncyclopedia);
            }catch(e){alert("err her : " + e.description);}
            return;
        }
    }      

    titles.endPreviewTab = ind;
    var tab = titles.document.getElementById(ind);
    var title = "Preview time has expired";
    tab.setAttribute("title", title);
    if(title.length > ieTitleLength) 
        title = title.substr(0, titleLength) + "...";
    
    tab.childNodes[0].data = title;
    q.submitTo(q.appRoot + "/endPreview.html?encyclopedia=" + ((bEncyclopedia) ? "yes" : "no")) ;
}

function OnEndPreview()
{
    isEncyclopedia();
}

function OnEndTime()
{
	OnEndPreview();
}

function OnHasNoRight(rightNo)
{
	var upgraderights = document.getElementById("upgraderights");
	upgraderights.setAttribute("src", "../upgradeRights.aspx?rightNo=" + rightNo);
	upgraderights.style.display = "inline";
	
}

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 goDoc(docNo)
{
    var oIFrame = Compat.getFrame("titles").createContainer(true);
    if(oIFrame == null) return;
    
    function doIt()
	{
	    if(oIFrame.contentWindow.document == null || oIFrame.contentWindow.document.readyState != "complete")
            setTimeout(doIt, 200);
        else
        {
            try{
            if (!onShowDoc(docNo)) return;
            // Save result selection before leaving this page
            q.selectedResults = getResultSelection().join(",");
            }catch(e){}
            q.submitFrame = oIFrame.contentWindow.document;
            q.showDoc(docNo);
        }
	}
	doIt();    
}

function OnLinkClicked(query, action)
{
	try
	{
		var qLink = q.makeCopy(globalSettings | resultSettings);
		
		if(query == null)
		{
			var HtmlCtl = SafeView.getObject();
			query = new String(HtmlCtl.GetQuery());
		}
		//Multiple id's
		//query = query.replace(/,/g, " or ");
		var fields = query.split(";");
		var fieldName;
		var fieldValue;
		for (i = 0; i < fields.length; i++)
		{
			var fieldStr = new String(fields[i]);
			var fieldVals = fieldStr.split(":");
			fieldName = fieldVals[0];
			if( fieldName == "ID" && fieldVals[1].indexOf(",") != -1 )
			{
				var arrID = fieldVals[1].split(","); 
				qLink.terms += "<or>";
				for (var k = 0; k < arrID.length; k++)
				{
					var bHasParNum = (arrID[k].substr(0,2) == "03");
			        var bHasSentenceNum = (arrID[k].substr(0,2) == "05");
			        if(bHasParNum) 
			            var parNum = new Number(arrID[k].substr(17,3));
			        else if(bHasSentenceNum)
			            var sentenceNum = new Number(fieldVals[1].substr(20,4));
			        if(bHasParNum || bHasSentenceNum)
			        {
			            qLink.terms += "<and>";
			            if(bHasParNum)
			                qLink.addParsedTerm(qLink.makeTerm("parNum", parNum, "num"));
			            else
			                qLink.addParsedTerm(qLink.makeTerm("sentenceNum", sentenceNum, "num"));
			            
			        }
			        fieldValue = arrID[k].substr(2,15);
					qLink.addParsedTerm(qLink.makeTerm(fieldName, fieldValue));
					if(bHasParNum || bHasSentenceNum)
			            qLink.terms += "<\/and>";
				}
				qLink.terms += "<\/or>";
			}
			else
			{	 
			    var bHasParNum = (fieldVals[1].substr(0,2) == "03");
			    var bHasSentenceNum = (fieldVals[1].substr(0,2) == "05");
			    if(action == "showPage")
			        fieldValue = fieldVals[1];
			    else
			        fieldValue = fieldVals[1].substr(2,15);
				qLink.addParsedTerm(qLink.makeTerm(fieldName, fieldValue));
                if(bHasParNum)
                {
                    var parNum = new Number(fieldVals[1].substr(17,3));
                    qLink.addParsedTerm(qLink.makeTerm("parNum ", parNum, "num"));
                }
                else if(bHasSentenceNum)
                {
                    var sentenceNum = new Number(fieldVals[1].substr(20,4));
                    //if(sentenceNum > 0)
                    qLink.addParsedTerm(qLink.makeTerm("sentenceNum", sentenceNum, "num"));
                }
			}
			//qLink.addParsedTerm(qLink.makeTerm(fieldVals[0], fieldVals[1]));
		}
		qLink.showResultsDRM(action);
	}
	catch(e)
	{
		alert(MSG_INVALID_LINK);
	}
}

NetisQuery.prototype.showResultsDRM = function(action, savedQueryName)
{
	if (this.terms.length == 0)
		throw "Please enter search term(s)";

	var oRequest = XmlHttp.createNew();
	if (oRequest == null)
	{
		// Either ActiveX is disabled altogether, or we don't have XMLHTTP.
		if (Compat.isActiveXEnabled())
			throw "XMLHTTP not available.\nPlease install IE 5 or greater.";
		return;
	}
	
	var titles = Compat.getFrame("titles");
    this.key = titles.getKeyID();
	var sURL = makeAbsolute(this.appRoot, "NetisUtils/srvrutil_xmlquery.aspx?key=" + this.key + "&qid=" + this.qid + "&isNew=true");
	var self = this;
	XmlHttp.setOnloadHandler(oRequest, function(oRequest) {
		try {
			self.handleResponse(oRequest, action, savedQueryName);
		} catch (e) {
			alert(e);
		}
	});
	if (typeof(setLoading) == "function")
		setLoading(true);
	oRequest.open("POST", sURL, true);
	oRequest.send(this.getQueryXML());
}

NetisQuery.prototype.handleResponse = function(oRequest, action, savedQueryName)
{
	if (typeof(setLoading) == "function")
		setLoading(false);
	var doc = oRequest.responseXML;
	var root = doc.documentElement;
	
	// Check possible error conditions

//	if (doc.parseError.errorCode != 0)
//		throw "Invalid server response:\n\n" + doc.parseError.reason;		
	if (root == null)
		throw "Empty server response.";
		
	switch (root.tagName)
	{
		case "reslist" : return root;
		case "login" :
			alert(MSG_LOGIN_FIRST);
			var loginURL = root.getAttribute("loginURL");
			var returnPage = root.getAttribute("returnPage");
			if (loginURL != null && loginURL.length != 0)
				this.loginURL = loginURL;
			if (returnPage == null || returnPage.length == 0)
				returnPage = this.searchURL;			// by default, return to search form after login
			if (this.loginURL.length != 0)
				this.showLogin(returnPage);
			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 = new Number(root.getAttribute("total"));
	if (total == 0)	{
		alert(MSG_NO_RESULTS);
		return;
	}
	
	var cost = new Number(root.getAttribute("cost"));
	var balance = new Number(root.getAttribute("balance"));
    var titles = Compat.getFrame("titles");
	this.qid = root.getAttribute("qid");
	if (this.verifyCost(total, cost, balance))
	{
	    //Show document in same iframe
	    if(action != null && (action == "prevDoc" || action == "nextDoc") )
	    {
            if(total == "1")
            {
                this.showDoc(1);
                return;
            }
            this.showResults();
	        return;
	    }
	    if(action == "showPage" || action == "biography")
	    {
	        var oIFrame = document.getElementById("pageContainer");
	        if(oIFrame == null)
	            oIFrame = pageContainer.frameElement;
	        this.docURL    = "NetisUtils/sfvw_document_page.aspx"; 
            oIFrame.width = "100%";
	        oIFrame.height = "88%";
	        //No SafeView
	        if(Compat.isMoz && document.getElementById("HtmlCtl") == null)
	            oIFrame.style.height = "100%";
	        oIFrame.style.zIndex = 100;
	    }
	    else{
	        //Show document in a new iframe
	        this.docURL    = "NetisUtils/sfvw_document.aspx"; 
	        var oIFrame = titles.createContainer();
	    }
	    if(oIFrame == null) return;
	    var oRes = this;
	    function doIt()
	    {
	        if(oIFrame.contentWindow.document == null  || oIFrame.contentWindow.document.readyState != "complete")
	            setTimeout(doIt, 200);
	        else
	        {
                oRes.submitFrame = oIFrame.contentWindow.document;
	            if (total == "1"  && action != null)
	            {
	                oRes.showDoc(1);
	                return;
	            }
	            setTabCaption(action, savedQueryName);
	            oRes.queryType = action;
	            oRes.showResults();
	        }
	    }
	    doIt();
	}
}

function trim(s) { return s.replace(/^\s+/, "").replace(/\s$/, ""); }

function setTabCaption(action, savedQueryName)
{
    try{
        var title = "";
        var titles = getContainerDocument().parentWindow.Compat.getFrame("titles");
        var oFocusedElem = titles.document.getElementById(titles.tabInd);
        
        if(action == "savedquery")
        {
			title = savedQueryName;
        }
        else
        {
			var searchFrame = titles.document.getElementById("iFrame1").contentWindow;
			var bodyField = searchFrame.document.getElementById("Body").value;
			//if(bodyField == "") //tabular search
			if(searchFrame.document.getElementById("tabularHeader").style.display == "")
			{
				var arrAll = new Array(); 
				for (var i = 1; i < 4; i++)
				{
					for (var j = 1; j < 5; j++)
					{
						sValue = trim(searchFrame.document.getElementById("word" + i + "-" + j).value);
						if(sValue != "")
							arrAll.push(sValue);
						else
							break;
					}
				}
					
				bodyField = arrAll.join(" ");
			}
			    
			var searchTerm = "";
			var collections_name = top.oFocused.collections_name;
			if(collections_name != "")
				searchTerm = "(" + collections_name + ")";
			//Don't add body field
			if(action == "link")
				title = "קשרים";
			else
			{    
				if(searchFrame.document.getElementById("currentCollection").checked)
					searchTerm = bodyField + " " + searchTerm;
				else
					searchTerm = bodyField;
	                
				title = searchTerm;
			}
		}
		if(action == "searchInRL")
		{
		    try{
		        var curTabId = this.frames.frameElement.getAttribute("tabId");
		        var curTitle = titles.document.getElementById(curTabId).getAttribute("title");
		        title = getDocFrame().document.getElementById("searchText").value + " " + curTitle;
		   }catch(e){
		        try {
                    title = getDocFrame().document.getElementById("searchText").value + " " + title;
                } catch(e) {}
		   }
		}
		
		oFocusedElem.setAttribute("title", title);
        if(title.length > ieTitleLength) 
            title = title.substr(0, titleLength) + "...";
        //Update only the text node
        oFocusedElem.childNodes[0].data = title;
    }catch(e){alert(e.description);}
}


// Update resultSelection and row appearance according to checkBox state.
function updateSelection(checkBox)
{
	var oRow = getParentRow(checkBox);
	var docID = getDocID(oRow);
	resultSelection.select(docID, checkBox.checked);
	selectRow(oRow, checkBox.checked);
	var divMrktDLG = parent.document.getElementById("divMrktDLG");
	var mrktDLG = parent.document.getElementById("mrktDLG");
	if(divMrktDLG.style.display == "inline")
	    mrktDLG.src = mrktDLG.src;
}

function AlertPrint()
{
	try{
	    if(this.frameElement.id == "iFrame" + parent.document.getElementById(parent.focusedIndex).id)
	        alert(MSG_PROTECT_PRINT);
	}catch(e){}
}

function fixIt(elem, refElem)
{
    var frameHND = document.getElementById("doc");
    if(frameHND != null)
    {
        frameHND.style.width = "100%";
        if (elem == null)
        {
	        //Mozilla
	        if (frameHND.contentDocument)
		        elem = frameHND.contentDocument.getElementById("rlDiv")
	        else // IE
		        elem = document.frames[0].document.getElementById("rlDiv");
        }
        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 newWidth = papa.clientWidth - elem.offsetLeft - deltaW();
		//if(newWidth > 0)
		//   elem.style.width = newWidth + "px";
		var newHeight = papa.clientHeight - elem.offsetTop - deltaH();
		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.
	function deltaH() { return elem.offsetHeight - elem.clientHeight; }
	function deltaW() { return elem.offsetWidth - elem.clientWidth; }
    if(refElem)
    {
        //override deltaH()
        function deltaH() { 
            var tabs = Compat.getFrame("titles").document.getElementById(refElem);
            return tabs.offsetHeight - 19; //19 is tab height 
        }
    }
	
	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 enableImage(doc, sImgId, bEnable)
{
	var oImg = doc.getElementById(sImgId);
	if (oImg == null)
		return;
	oImg.disabled = !bEnable;
	oImg.src = oImg.src.replace(/(-dis)?.gif/i,((bEnable) ? "" : "-dis") + ".gif");
	oImg.style.cursor = (bEnable) ? "pointer" : "default";
	if(!oImg.onclickORIG)
	{
		oImg.onclickORIG = oImg.onclick;
		oImg.onclick = function() { if (!this.disabled) this.onclickORIG(); }
	}
}

function OnHighlightDone(n)
{
	var oDoc = getToolbar();
	if (n == 0)
	{
		enableImage(oDoc, "imgPrevHighlight", false);
		enableImage(oDoc, "imgNextHighlight", false);
		enableImage(oDoc, "imgToggleHighlight", false);
	}
	if (q.resultsCount == 1)
	{
		enableImage(oDoc, "imgPrevDoc", false);
		enableImage(oDoc, "imgNextDoc", false);
		enableImage(oDoc, "imgResultList", false);
	}
	if(typeof(disableNoRight) == "function")
	    disableNoRight();
}

//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 addToMyLibrary()
{		
	var titles = getContainerDocument().parentWindow.Compat.getFrame("titles");
	var curTabId = this.frames.frameElement.getAttribute("tabId");
	var docTitle = titles.document.getElementById(curTabId).getAttribute("title");

    var docID;
	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")
				docID = node.childNodes[param].value;
		getTopbar().addToMyLibrary(null, docID, docTitle, false);
	}catch(e)
	{/*Low protection docID == null */
		var ar = docURL.split("/");
		docID = ar[ar.length-2];
		//var docTitle = getDocFrame().document.getElementById("header").innerHTML;
		getTopbar().addToMyLibrary(docURL, docID, docTitle, false);
	}
}

