﻿//// JScript File
////var body;
//var button;
//var range;
var query;
var exact;
var markedRanges;
var firstRange;
//var result;

/******************************************
* Find In Page Script -- Submitted/revised by Alan Koontz (alankoontz@REMOVETHISyahoo.com)
* Visit Dynamic Drive (http://www.dynamicdrive.com/) for full source code
* This notice must stay intact for use
******************************************/

//  revised by Alan Koontz -- May 2003

var TRange = null;
var dupeRange = null;
var TestRange = null;
var win = null;
var div = null;
var startBookmark= null;
var queryChanged = false;
var noResultsAtAll = true;
var isInIframe = false;

//  SELECTED BROWSER SNIFFER COMPONENTS DOCUMENTED AT
//  http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html

var nom = navigator.appName.toLowerCase();
var agt = navigator.userAgent.toLowerCase();
var is_major   = parseInt(navigator.appVersion);
var is_minor   = parseFloat(navigator.appVersion);
var is_ie      = (agt.indexOf("msie") != -1);
var is_ie4up   = (is_ie && (is_major >= 4));
var is_not_moz = (agt.indexOf('netscape')!=-1)
var is_nav     = (nom.indexOf('netscape')!=-1);
var is_nav4    = (is_nav && (is_major == 4));
var is_mac     = (agt.indexOf("mac")!=-1);
var is_gecko   = (agt.indexOf('gecko') != -1);
var is_opera   = (agt.indexOf("opera") != -1);


//  GECKO REVISION

var is_rev=0

//Find next text (do not mark permenantly)
function FindText()
{
	Initialize();
	if (queryChanged )
	{
	    queryChanged = false;
	    firstRange = null;
	    noResultsAtAll = true;
	    ClearAllMarks();
	}

	if(!DoFind(false) )
	{
	}
	else if (is_ie4up && firstRange == null)
	{
	    firstRange = TRange;
	}
} 

function Initialize()
{
    if (!query) //search text box
    {
        query = document.getElementById("txtSearchText");
    }
	
    if (!exact) // exact search checkbox
    {
        exact = document.getElementById("exact");
    }
	
    if (!markedRanges) //markedRanges array. keeps the marked ranges, if mark == true
    {
        markedRanges = [];
    }
    
    if (!win)
    {
        win = self;
    }

    if (div == null)
    {
        var tabId = GetQueryStringItem("tabid");
        var divId = null;
        if (tabId != null)
        {
            var divId = tabId.replace("Tab","Div");
        }
        else
        {
          divId = "documentDiv";
        }    
        div = document.getElementById(divId);
        
    }

}
//Find nextText (mark acording to boolean parameter)
// gets the query parameters then calls SearchRange
function DoFind(mark)
{
    try
	{
		return SearchRange(query.value.trim(), exact.checked, mark);
	}
	catch (e)
    {
        //alert(e);
        return false;
    }
}


// Hide from old browsers

if (is_gecko) 
{
    temp = agt.split("rv:")
    is_rev = parseFloat(temp[1])
}


//  USE THE FOLLOWING VARIABLE TO CONFIGURE FRAMES TO SEARCH
//  (SELF OR CHILD FRAME)

//  If you want to search another frame, change from "self" to
//  the name of the target frame:
//  e.g., var frametosearch = 'main'

//var frametosearch = 'main';


function SearchRange(queryText, exactVal, mark) 
{
    //  TEST FOR IE5 FOR MAC (NO DOCUMENTATION)

    if (is_ie4up && is_mac) 
        return false;

    //  TEST FOR NAV 6 (NO DOCUMENTATION)

    if (is_gecko && (is_rev <1)) 
        return false;

    //  TEST FOR Opera (NO DOCUMENTATION)

    if (is_opera) 
        return false;

    //  INITIALIZATIONS FOR FIND-IN-PAGE SEARCHES

    if(queryText != null && queryText!='') 
    //whichform.findthis.value!=null && whichform.findthis.value!='') 
    {

           str = queryText;//whichform.findthis.value;
           //win = whichframe;

           

           var frameval=true;//false;
//           if(win!=self)
//           {

//                frameval=true;  // this will enable Nav7 to search child frame
//                //win = parent.frames[whichframe];
//                win = parent.frames[frametosearch];

//           }
    }

    else 
        return false;  //  i.e., no search string was entered

    var wasStringFound = false;

    //  NAVIGATOR 4 SPECIFIC CODE

    if(is_nav4 && (is_minor < 5)) 
    {
       
      wasStringFound=win.find(str); // case insensitive, forward search by default

    //  There are 3 arguments available:
    //  searchString: type string and it's the item to be searched
    //  caseSensitive: boolean -- is search case sensitive?
    //  backwards: boolean --should we also search backwards?
    //  wasStringFound=win.find(str, false, false) is the explicit
    //  version of the above
    //  The Mac version of Nav4 has wrapAround, but
    //  cannot be specified in JS

     
    }

    //  NAVIGATOR 7 and Mozilla rev 1+ SPECIFIC CODE (WILL NOT WORK WITH NAVIGATOR 6)

    if (is_gecko && (is_rev >= 1)) 
    {
       
//        if(frameval!=false) 
//            win.focus(); // force search in specified child frame
//        if (startBookmark == null)
//        {
//            
//        }

          var startRange = null;
          
          if (div != null)
          {
            startRange = document.createRange();
            startRange.selectNode(div);
            //startRange.setEnd(div.firstChild, 0);
          }

        wasStringFound = win.find(str, false, false, true, exactVal, false, false);
        
        //Added by Tsahi:
        //marks the selection by wrapping it with a colorful span
        var sel = window.getSelection();
        
        //if it's out of range, the search is over
        if(sel != "" && startRange!=null  && !startRange.isPointInRange(sel.anchorNode,sel.anchorOffset))
        {
            wasStringFound = false;
        }
        
        if (mark)
        {
            //var sel = window.getSelection();
            for (i=0;i<sel.rangeCount;i++)
            {
                var currRange = sel.getRangeAt(i);
                var newNode = document.createElement("span");
                newNode.setAttribute("style","background-color:yellow;");
                currRange.surroundContents(newNode);
                markedRanges[markedRanges.length] = currRange;
            }
        }
        else
        {
            if (wasStringFound == false && startRange != null && sel!= null)
            {
                ReturnToTop();
                wasStringFound=win.find(str, false, false, false, exactVal, false, false);
                
                HandleNotFound(false)
            }
        }

    //  The following statement enables reversion of focus 
    //  back to the search box after each search event 
    //  allowing the user to press the ENTER key instead
    //  of clicking the search button to continue search.
    //  Note: tends to be buggy in Mozilla as of 1.3.1
    //  (see www.mozilla.org) so is excluded from users 
    //  of that browser.

//        if (is_not_moz)  
//            whichform.findthis.focus();

    //  There are 7 arguments available:
    //  searchString: type string and it's the item to be searched
    //  caseSensitive: boolean -- is search case sensitive?
    //  backwards: boolean --should we also search backwards?
    //  wrapAround: boolean -- should we wrap the search?
    //  wholeWord: boolean: should we search only for whole words
    //  searchInFrames: boolean -- should we search in frames?
    //  showDialog: boolean -- should we show the Find Dialog?


    }

     if (is_ie4up) 
     {
     
        // EXPLORER-SPECIFIC CODE revised 5/21/03
        try
        {
       
            
            if (TRange!=null && dupeRange.inRange(TRange)) 
            {            
                TestRange=win.document.body.createTextRange();

                if (dupeRange.inRange(TestRange)) 
                {
                    
                    TRange.collapse(false);
                    wasStringFound=TRange.findText(str, 1, (exactVal ? 2 : 0));
                    
                    //the following line added by Mike and Susan Keenan, 7 June 2003
                    win.document.body.scrollTop = win.document.body.scrollTop + TRange.offsetTop;         
                    if (wasStringFound) 
                    {
                        //added by Tsahi:
                        //either marks or selects range
                        if (mark)
                        {
                            MarkRange();
                        }
                        else
                        {
                            TRange.select();
                        }
                    
                    }                                   
                   else
                   {
                        HandleNotFound(mark);
                   }                           
                } 
             
                else 
                {
                    TRange.collapse(false);

                    wasStringFound=TRange.findText(str, 1, (exactVal ? 2 : 0));
                    if (wasStringFound) 
                    {

                        //the following line added by Mike and Susan Keenan, 7 June 2003
                        win.document.body.scrollTop = TRange.offsetTop;
                        //added by Tsahi:
                        //either marks or selects range  
                        if (mark)
                        {                        
                            MarkRange();
                        }
                        else
                        {

                           TRange.select();
                        }         
                    } 
                    else
                    {
        
                        HandleNotFound(mark);
                    }                           
                }
            }
            else if (TRange!=null)
            {
                HandleNotFound(mark);
            }
            
            if (TRange==null || (!mark && wasStringFound==0) )
            {  

                TRange=win.document.body.createTextRange();
                
                if(!isInIframe)
                    // Only move to div if we are not in the iframe
                    TRange.moveToElementText (div); 
                
                dupeRange = TRange.duplicate();
                wasStringFound=TRange.findText(str, 1,(exactVal ? 2 : 0));
                
                if (wasStringFound) 
                {
                    //the following line added by Mike and Susan Keenan, 7 June 2003
                    win.document.body.scrollTop = TRange.offsetTop;
                    
                    //added by Tsahi:
                    //either marks or selects range
                    if (mark)
                        MarkRange();
                    else
                        TRange.select();
                }
                else
                {
                    HandleNotFound(mark);
                }
            }
        }
        catch(e)
        {
            wasStringFound = false;
            
            //HandleNotFound(mark);
            
            // this case is special becuase sometimes once there is an exception (such as 800a025e)
            // selction is rendered impossible and you need to "restart" TRange by creating it again.
            if (firstRange != null) 
            {
                TRange = win.document.body.createTextRange();
                TRange.findText(str, 1,(exactVal ? 2 : 0));
                TRange.select();
            }
        }    
     
//      if (!wasStringFound) 
//        alert ("String '"+str+"' not found!") // string not found
    }
    if (wasStringFound)
        noResultsAtAll = false;
        
    return wasStringFound;
}
// -->

//Marks all search results
function MarkAll()
{
    Initialize()

    //first, clear all previous marks
    ClearAllMarks();

    if (is_gecko && (is_rev >= 1)) 
    {
        ReturnToTop();
    }
    

    //mark all results
    while (DoFind(true)){}
    
    //if results were found, go back to top of page (so the next search starts from the top)
    if (markedRanges.length >0)
    {
       if (is_gecko && (is_rev >= 1)) 
       {
            ReturnToTop();
            
       }
       else
       {
          //moves to start of div (collapses to reach real start of div)
          if(!isInIframe)
            TRange.moveToElementText (div); 
          
          TRange.collapse(true);
       }
    }
    else
    {
               if (noResultsAtAll)
                    alert("לא נמצא ערך מתאים");
                else
                    alert("לא נמצאו מופעים נוספים");
    }
}

//clears all marks made by this search 
//(but not marks made earlier, such as ones set in the Document.aspx load event)
function ClearAllMarks()
{
    //basically go over the markedRanges and remove marks
     if (markedRanges)
     {
       
        if (is_gecko && (is_rev >= 1)) 
        {
           for( i in markedRanges)
           {     
                //remove the span by replacing the colored span with its text
                var currRange = markedRanges[i];
                var currRangeContent = currRange .toString();
                var newNode = document.createTextNode(currRangeContent);
                currRange.deleteContents();
                currRange.insertNode(newNode);
            }
        }
        else
        {
           for( i in markedRanges)
           {     
              //change range's background color to transparent
                //TRange.moveToBookmark(markedRanges[i]);
                TRange =markedRanges[i];

                TRange.execCommand("BackColor", true, "transparent");

            }
        }
     }
     
     //reset range and markedRanges
     markedRanges =[];
     TRange = null;	
}


//IE only: mark range by changing range's background color to yellow
function MarkRange()
{
        TRange.expand();
        TRange.execCommand("BackColor", true, "yellow");
        markedRanges[markedRanges.length] = TRange.duplicate();//.getBookmark();
}

//toggle innersearch marking and button image
function ToggleMarking(sender)
{
   if (queryChanged ||
	    ((markedRanges == undefined || markedRanges.length == 0) 
        && document.getElementById("txtSearchText").value.trim() != ""))
    {
        queryChanged = false;
        //nothing is marked. Mark all.
        MarkAll();
        
        if( markedRanges.length > 0) // change button only if something was marked
        {
            sender.src = "Images/mark_btn_Txt_on.gif";
            sender.alt = "הסר סימון";
        }
    }
    else
    {
        //marks exist. clear all marks.
        ClearAllMarks();
        sender.src = "Images/mark_btn_Txt_off.gif";
        sender.alt = "סמן";        
    }
}

//change div to search in 
function ChangeSearchDiv(divId)
{
    div = document.getElementById(divId);
    
    if (dupeRange != null)
        TRange.moveToElementText(div); 
}

// Change the inner-search's search area
// param "win": the window to search in
// optional param "divId": the div in the window to search in
// param "isInIframe": True if the param "win" is an Iframe, else false
function ChangeSearchArea(win, divId, isInIframe)
{
    window.win = win;
    window.isInIframe = isInIframe;
        
    if (dupeRange != null)
    {
        TRange = win.document.body.createTextRange();
        dupeRange = TRange.duplicate();             
    }
    
    if(divId)
        ChangeSearchDiv(divId);
    else
        // There is no div to search in
        div = null;
}

//crude... iterate until you reach the top of the div
function ReturnToTop()
{   
    var startRange = null;

    if (div != null)
    {
        startRange = document.createRange();   
        startRange.selectNode(div);
    }
    else
    {
        startRange = win.document.createRange();   
    }

        
    var sel = win.getSelection();
    var outOfRange = false;
        
    if(sel != "" && startRange!=null  && !startRange.isPointInRange(sel.anchorNode,sel.anchorOffset))
    {
        outOfRange = true;
    }
    
    var reachedTop = false;  
    
    while (!reachedTop)
    {
        sel = win.getSelection();
            
        if(outOfRange == false  && (sel != "" && startRange!=null  && !startRange.isPointInRange(sel.anchorNode,sel.anchorOffset)))
        {
            reachedTop = true;
        }
        else
        {
           //search backwards
           reachedTop = !win.find(div.textContent.substring(0,5), false, true, true, true, false, false);
           outOfRange = false;
        }
    }
}

//note that textbox content has changed
function QueryHasChanged()
{
    queryChanged=true;
}


//puts out message and returns to first instance if no more items were found
function HandleNotFound(mark)
{
    if (!mark)
    {
        if (noResultsAtAll)
            alert("לא נמצא ערך מתאים");
        else
            alert("לא נמצאו מופעים נוספים");
    }
    
    if (firstRange != null)
    {
        TRange = firstRange;
        TRange.select();
    }
}
