// JavaScript Document
var dom = (document.getElementById) ? true : false;
var ns5 = ((navigator.userAgent.indexOf("Gecko")>-1) && dom) ? true: false;
var ie5 = ((navigator.userAgent.indexOf("MSIE")>-1) && dom) ? true : false;
var ns4 = (document.layers && !dom) ? true : false;
var ie4 = (document.all && !dom) ? true : false;
var nodyn = (!ns5 && !ns4 && !ie4 && !ie5) ? true : false;
var bSearchParamLoaded = false;

var bAllDocuments      = true;
var sDocType           = "all";
var sSearchArea        = "headings";
var sSearchText        = "";
var sSearchMatch       = "exact";
var matches            = 0;
var sCurrentPageDoc     = "";
var CurrentPage       = 0;
var gbReset             = true;
var iHitIndex           = -1;
var oBrowser            = new BrowserDetect();
var output = new Array();
var NavDocument = new Array();
var TimeOutId;

function PageNav(Key, CollectionPrefix, FilePath, Filename, FirstPage, LastPage, IndexPage, PageNumStart)
{
	this.Key = Key;
	this.CollectionPrefix = CollectionPrefix;
	this.FilePath = FilePath;
	this.Filename = Filename;
	this.FirstPage = FirstPage;
	this.LastPage = LastPage;
	this.IndexPage = IndexPage;
	this.PageNumStart = PageNumStart;
}

function SetNavDocParms()
{
	NavDocument[0] = new PageNav("all", "All", "", "", 0, 0, 0, 0);
	NavDocument[1] = new PageNav("dsm", "Modules Datasheet", "dsm", "dsm", 1, 8, 2, 2);
	NavDocument[2] = new PageNav("pd", "Product Description", "pd", "pfg", 1, 161, 2, 2);
	NavDocument[3] = new PageNav("tug_400_50", "PCS400&amp;50 user guide", "tug", "tug_400_50", 1, 92, 3, 5);
    NavDocument[4] = new PageNav("tug_100", "PCS100 user guide", "tug", "tug_100", 1, 48, 3, 5);
	NavDocument[5] = new PageNav("tug_10", "PCS10 user guide", "tug", "tug_10", 1, 32, 5, 7);
    NavDocument[6] = new PageNav("tug_5", "PCS5 user guide", "tug", "tug_5", 1, 13, 1, 1);
	NavDocument[7] = new PageNav("aug", "Analogue User Guide", "aug", "aug", 0, 0, 0, 0);
	NavDocument[8] = new PageNav("irm", "Installation & Reference Manual", "irm", "irm", 1, 262, 2, 6);
	NavDocument[9] = new PageNav("ru", "Reseller Update", "ru", "ru", 0, 0, 0, 0);
	NavDocument[10] = new PageNav("wp", "White Paper", "wp", "wp", 0, 0, 0, 0);
	NavDocument[11] = new PageNav("dst", "Terminals Datasheet", "dst", "dst", 1, 6, 2, 2);
	NavDocument[12] = new PageNav("dsf", "Features Summary", "dsf", "dsf", 1, 4, 2, 2);
	NavDocument[13] = new PageNav("dsi", "IP Datasheet", "dsi", "dsi", 1, 8, 2, 2);
	NavDocument[14] = new PageNav("dssl", "SpliceLog Datasheet", "dssl", "dssl", 1, 4, 2, 2);
	NavDocument[15] = new PageNav("dsoc", "PCS Operators Console datasheet", "dsoc", "dsoc", 1, 4, 2, 2);
	NavDocument[16] = new PageNav("tug_oc", "PCS Operators Console user guide", "tug", "tug_oc", 1, 48, 3, 5);
}

function Initialise()
{
	sDocType     = getParam("lstDocType");
	sSearchMatch = getParam("txtMatchType");
	sSearchArea  = getParam("txtSearchArea");
	sSearchText  = getParam("txtSearchText");

	SetNavDocParms();
	
	if (sSearchText.length > 0)
		PerformSearch();
}

function BrowserDetect() 
{
   var ua = navigator.userAgent.toLowerCase(); 

   // browser name
   this.isGecko     = (ua.indexOf('gecko') != -1 && ua.indexOf('safari') == -1);
   this.isMozilla   = (this.isGecko && ua.indexOf('gecko/') + 14 == ua.length);
   this.isNS        = ( (this.isGecko) ? (ua.indexOf('netscape') != -1) : ( (ua.indexOf('mozilla') != -1) && (ua.indexOf('spoofer') == -1) && (ua.indexOf('compatible') == -1) && (ua.indexOf('opera') == -1) && (ua.indexOf('webtv') == -1) && (ua.indexOf('hotjava') == -1) ) );
   this.isIE        = ( (ua.indexOf('msie') != -1) && (ua.indexOf('opera') == -1) && (ua.indexOf('webtv') == -1) ); 
   this.isSafari    = (ua.indexOf('safari') != - 1);
   this.isOpera     = (ua.indexOf('opera') != -1); 
   this.isKonqueror = (ua.indexOf('konqueror') != -1 && !this.isSafari); 
   this.isIcab      = (ua.indexOf('icab') != -1); 
   this.isAol       = (ua.indexOf('aol') != -1); 
   
   // platform
   this.isWin   = (ua.indexOf('win') != -1);
   this.isWin32 = (this.isWin && ( ua.indexOf('95') != -1 || ua.indexOf('98') != -1 || ua.indexOf('nt') != -1 || ua.indexOf('win32') != -1 || ua.indexOf('32bit') != -1 || ua.indexOf('xp') != -1) );
   this.isMac   = (ua.indexOf('mac') != -1);
   this.isUnix  = (ua.indexOf('unix') != -1 || ua.indexOf('sunos') != -1 || ua.indexOf('bsd') != -1 || ua.indexOf('x11') != -1)
   this.isLinux = (ua.indexOf('linux') != -1);
}

function GetDocObject(Doc, Obj, Level)
{
	var objref;
	
	if (dom)
		objref = Doc.getElementById(Obj);
	else if (ie4)
		objref = Doc.all[Obj];
	else if (ns4)
		objref = Doc.layers[Obj];

	if (Level == "style")
		if (objref.style)
			return objref.style;
		else
			return objref;
	else
		return objref;
}

function ResetForms()
{
	parent.SearchResults.location.replace("searchresultsblank.htm");
	parent.DocView.location.replace("encyclopediawelcome.htm");
	parent.SearchEngine.location.replace("searchengine_headings.htm");
	matches = 0;
	iHitIndex = -1;
	sCurrentPageDoc = "";
}

function GetNavDoc(sSearch, iIndex)
{
	for (var i = 0; i < NavDocument.length; i++)
		switch (iIndex)
		{
			case 0 :
				if (NavDocument[i].Key == sSearch)
					return NavDocument[i];
			case 1 :
				if (NavDocument[i].CollectionPrefix == sSearch)
					return NavDocument[i];
			case 2 :
				if (NavDocument[i].Filename == sSearch)
					return NavDocument[i];
		}
}

function ShowDocument(sLoc, HitIndex)
{
	var sLocSplit = new Array();
	var sHitSource = "";

	sLocSplit = sLoc.split("/");
	sHitSource = sLocSplit[2];

	iHitIndex = parseInt(HitIndex);
	CurrentPage = parseInt(GetDocumentSuffix(sLoc));
	sCurrentPageDoc = sHitSource;
    parent.DocView.location.replace( sLoc );
	
	var NavDoc = GetNavDoc(sCurrentPageDoc.toLowerCase(), 0);

	if (CurrentPage == 1)
		GetDocObject(document, "btn_Previous", "style").visibility = "hidden";
	else		
		GetDocObject(document, "btn_Previous", "style").visibility = "visible";

	if (CurrentPage == NavDoc.LastPage)
		GetDocObject(document, "btn_Next", "style").visibility = "hidden";
	else		
		GetDocObject(document, "btn_Next", "style").visibility = "visible";

	setDocTitle(NavDoc.CollectionPrefix);
	
	GetDocObject(document, "divPageNav", "style").visibility = "visible";

	if (sSearchArea == 'text')
		TimeOutId = window.setTimeout("HighlightWord(parent.DocView.document.body, sSearchText)", 2000);
}

function GetDocumentSuffix(sLoc)
{
	var sFileParam = new Array();
	var sSuffix = "";
	var iPosn;
	
	sFileParam = sLoc.split("/");
	sSuffix = sFileParam[sFileParam.length - 1];
	
	iPosn = sSuffix.lastIndexOf("_");
	
	sSuffix = sSuffix.substr(iPosn + 1, sSuffix.length - iPosn - 5);
	
	return sSuffix;
}

function ShowDocHit(Direction)
{
	if (matches > 0)
	{
		var iNewHitIndex = -1;
		
		switch (Direction)
		{
			case "first" :
				iNewHitIndex = 0;
				break;
			case "previous" :
				iNewHitIndex = iHitIndex - 1;
				break;
			case "next" :
				iNewHitIndex = iHitIndex + 1;
				break;
			case "last" :
				iNewHitIndex = matches - 1;
				break;
		}
	  
		if (iNewHitIndex < 0)
			iNewHitIndex = 0;
			
		if (iNewHitIndex >= matches)
			iNewHitIndex = matches - 1;
			
		ShowDocument(urls[output[iNewHitIndex][0]], iNewHitIndex);
	}
}

function SetPageNum(Page)
{
	parent.SearchEngine.CurrentPage = Page;
}

function ShowNextPage(sMode)
{
	if (sCurrentPageDoc.length > 0)
	{
		var NavDoc = GetNavDoc(sCurrentPageDoc.toLowerCase(), 0);

		switch (sMode)
		{
			case "first" :
				CurrentPage = NavDoc.FirstPage;
				break;
			case "previous" :
				if (CurrentPage > NavDoc.FirstPage)
				CurrentPage = CurrentPage - 1;
				break;
			case "next" :
				if (CurrentPage < NavDoc.LastPage)
					CurrentPage = CurrentPage + 1;
				break;
			case "last" :
				CurrentPage = NavDoc.LastPage;
				break;
		}
		ViewDocument(NavDoc);
	}
}

//function to show a page from the source document
function ViewDocument(NavDoc, namedAnchor)
{
	var sFilename;
	var PageId;
	
	PageId = CurrentPage - NavDoc.PageNumStart + 1;
	
	sFilename = "docs/text/" + NavDoc.FilePath + "/" + NavDoc.Filename + "/css/" + NavDoc.Filename + "_" + CurrentPage + ".htm";
	
	if (namedAnchor != null)
		sFilename += '#' + namedAnchor;

	parent.DocView.location.replace( sFilename );
	
	if (CurrentPage == 1)
		GetDocObject(document, "btn_Previous", "style").visibility = "hidden";
	else		
		GetDocObject(document, "btn_Previous", "style").visibility = "visible";

	if (CurrentPage == NavDoc.LastPage)
		GetDocObject(document, "btn_Next", "style").visibility = "hidden";
	else		
		GetDocObject(document, "btn_Next", "style").visibility = "visible";

	setDocTitle(NavDoc.CollectionPrefix);
	
	GetDocObject(document, "divPageNav", "style").visibility = "visible";
		
}

function LoadDoc(DocType)
{
	var NavDoc = GetNavDoc(DocType, 0);
		
	parent.SearchResults.location.replace("searchresultsblank.htm");
	matches = 0;
	iHitIndex = -1;
	
	CurrentPage = NavDoc.IndexPage;
	sCurrentPageDoc = NavDoc.Key;
	ViewDocument(NavDoc);
}

function ShowPage(DocType, PageNum, namedAnchor)
{
	var NavDoc = GetNavDoc(DocType, 0);
		
	CurrentPage = PageNum;
	sCurrentPageDoc = NavDoc.Key;
	ViewDocument(NavDoc, namedAnchor);
}

// This function will return the value of a GET parameter
function getParam(paramName)
{
	var ret;
	var arg;
	var arg_values;
    var paramStr = document.location.search;

	if (paramStr == "")
      return "";

    // remove '?' in front of paramStr
    if (paramStr.charAt(0) == "?")
        paramStr = paramStr.substring(1, paramStr.length);

    arg = (paramStr.split("&"));

	for (i=0; i < arg.length; i++) {
        arg_values = arg[i].split("=")
        if (unescape(arg_values[0]) == paramName)
		{
        	if (self.decodeURIComponent) // check if decodeURIComponent() is defined
                ret = decodeURIComponent(arg_values[1]);
            else
                ret = unescape(arg_values[1]);  // IE 5.0 and older does not have decodeURI
            return ret;
        }
    }
    return;
}

function pattern2regexp(pattern) {
    pattern = pattern.replace(/\./g, "\\.");
    pattern = pattern.replace(/\*/g, ".*");
    pattern = pattern.replace(/\?/g, ".?");

//if (SearchAsSubstring == 1)
        return pattern;

//    return "^" + pattern + "$";
}

function HighlightDescription(line) {
    res = " " + line + " ";
    for (i = 0; i < matchwords_num; i++) {
        // replace with marker text, assumes [;:] and [:;] is not the search text...
        // can not use \\b due to IE's regexp bug with foreign diacritic characters
        // treated as non-word characters
        res = res.replace(new RegExp("([\\s\.\,\:]+)("+matchwords[i]+")([\\s\.\,\:]+)", "gi"), "$1[;:]$2[:;]$3");
    }
    // replace the marker text with the html text
    // this is to avoid finding previous <span>'ed text.
    res = res.replace(/\[;:\]/g, "<span style=\"background: " + HighlightColor + "\">");
    res = res.replace(/\[:;\]/g, "</span>");
    return res;
}

function PerformSearch() 
{
	var SearchAsSubstring = 0;  // 0 = do not force substring search, word must match entirely
                            // 1 = force substring search for all searchwords
	var ToLowerSearchWords = 1; // 0 = Do not change search words to lowercase (for non-alphabetic languages)
                            // 1 = Change search words to lowercase (for alphanumeric languages)
	var searchWords = new Array();
	var data = new Array();
	output = new Array();
	var iCatIndex;
	var iCatName;
	var sTitle;
	var doc = parent.SearchResults.document;
	var bExactMatch = (sSearchMatch == 'exact');
	var query = sSearchText;
	var pagesCount;
    var SWord;	
	var sDesc;

	iHitIndex = -1;
	query = query.replace(/[\+\_]/g, " "); // replace '+', '_' with spaces.

	//initialise the results document
	doc.open();
	doc.writeln("<html>" );
	doc.writeln("  <head>" );
	doc.writeln("  	<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">" );
	doc.writeln("  </meta>" );
	doc.writeln("  <link rel=stylesheet type=\"text/css\" href=\"css/splicecom.css\">");
	doc.writeln("		<style type=\"text/css\">");
	doc.writeln("				body {background-color: #3C2784; margin-right: 10px; margin-left: 6px;}");
	doc.writeln("				a {font-family: Arial Bold;	font-size: 14px; color: #FFFFFF;}");
	doc.writeln("				a:hover {color: #FFFFFF;}");
	doc.writeln("				a:active {color: #FFFFFF;}");
	doc.writeln("		</style>");
	doc.writeln("<body>" );

	// give up early if no search words provided
    if (query.length != 0) 
	{
		// split search phrase into words
	    searchWords = query.split(" "); // split by spaces.
	    numwords = searchWords.length;
    	kw_ptr = 0;
	    outputline = 0;
    	usewildcards = 0;
	    ipage = 0;
    	matches = 0;
	    pagesCount = urls.length;

		// Initialise a result table the size of all pages
	    res_table = new Array(pagesCount);
    	for (i = 0; i < pagesCount; i++)
	    {
    	    res_table[i] = new Array(2);
        	res_table[i][0] = 0;
	        res_table[i][1] = 0;
    	}

	    // Begin searching...
    	for (sw = 0; sw < numwords; sw++) 
		{
        	if (searchWords[sw].indexOf("*") == -1 && searchWords[sw].indexOf("?") == -1) 
			{
            	UseWildCards = 0;
	        } 
			else 
			{
            	UseWildCards = 1;
	            if (ToLowerSearchWords == 0)
    	            re = new RegExp(pattern2regexp(searchWords[sw]), "g");
        	    else
            	    re = new RegExp(pattern2regexp(searchWords[sw]), "gi");
	        }

    	    for (kw_ptr = 0; kw_ptr < keywords.length; kw_ptr++) 
			{
	            data = keywords[kw_ptr].split(",");

    	        if (UseWildCards == 0) 
				{
        	        if (ToLowerSearchWords == 0)
            	        SWord = searchWords[sw];
                	else
                    	SWord = searchWords[sw].toLowerCase();

                	if (SearchAsSubstring == 0)
                    	//match_result = data[0].lastIndexOf(SWord, 0);
	                    match_result = data[0].search("^" + SWord + "$");
    	            else
        	            match_result = data[0].indexOf(SWord);
            	} 
				else
                	match_result = data[0].search(re);

				if (match_result != -1) 
				{
    	            // keyword found, include it in the output list
	                for (kw = 1; kw < data.length; kw += 2) 
					{
                    	// check if page is already in output list
	                    pageexists = 0;
    	                ipage = data[kw];
        	            if (res_table[ipage][0] == 0) 
						{
                        	matches++;
	                        res_table[ipage][0] += parseInt(data[kw+1]);
    	                }
        	            else 
						{
							if (res_table[ipage][0] > 10000) 
							{
	                            // take it easy if its too big to prevent gigantic scores
    	                        res_table[ipage][0] += 1;
        	                } 
							else 
							{
                            	res_table[ipage][0] += parseInt(data[kw+1]); // add in score
	                            res_table[ipage][0] *= 2;           // double score as we have two words matching
    	                    }
        	            }
            	        res_table[ipage][1] += 1;
                	}
	                if (UseWildCards == 0 && SearchAsSubstring == 0)
    	                break;    // this search word was found, so skip to next

        	    }
	        }
	    }

    	// Count number of output lines that match ALL search terms
	    oline = 0;
	    fullmatches = 0;
	    ResFiltered = false;
    	output = new Array();
	    for (i = 0; i < pagesCount; i++) 
		{
        	IsFiltered = false;
	        if (res_table[i][0] != 0) 
			{
            	if (sDocType != 'all') 
				{
                	// using cats and not doing an "all cats" search
	                if (catnames[catpages[i]] != sDocType) 
					{
	                    IsFiltered = true;
    	            }
        	    }
            	if (IsFiltered == false) 
				{
                	if (res_table[i][1] >= numwords) 
					{
                    	fullmatches++;
	                } 
					else 
					{
                    	if (bExactMatch)
                        	IsFiltered = true;
	                }
    	        }
        	    if (IsFiltered == false) 
				{
                	// copy if not filtered out
	                output[oline] = new Array(3);
    	            output[oline][0] = i;
        	        output[oline][1] = res_table[i][0];
            	    output[oline][2] = res_table[i][1];
                	oline++;
	            }
				else 
				{
                	ResFiltered = true;
	            }
    	    }
	    }
    	if (ResFiltered == true)
        	matches = output.length;

	    //Display search result information
		UpdateHitCount("Results : " + matches + " hit" + ((matches == 1) ? "" : "s"));
		
		// display the results
	    for (var arrayline = 0; arrayline < matches; arrayline++)
		{
        	ipage = output[arrayline][0];
	        score = output[arrayline][1];

			iCatIndex = catpages[ipage];
			iCatName = catnames[iCatIndex];
			sTitle = GetNavDoc(iCatName, 0).CollectionPrefix;
			
			sDesc = descriptions[ipage];
			
			if (sDesc.length > 50)
			{
				var iStopPosn = 49;
			
				while (sDesc.charAt(iStopPosn) != " " && iStopPosn < sDesc.length - 1)
			  		iStopPosn++;

				sDesc = sDesc.substring(0, iStopPosn) + "...";
			}

			doc.writeln("<p>");
			doc.writeln( "<span class=\"SearchResultsDocTitle\"><a href=\"javascript:parent.SearchEngine.ShowDocument(\'", urls[ipage], "\', ", arrayline, ");\">", sTitle, "</a></span><br>" );
			doc.writeln( "<span class=\"SearchResultsDocSummary\">" + sDesc + "</span><br>" );
			doc.writeln("</p>");
	    }
		doc.writeln("<br><br>");
	}
	doc.close();
}

function UpdateHitCount(sText)
{
	var obj = GetDocObject(parent.SearchParams.document, "divHitCount", "root");

	if (obj != null)
		with (obj)
			if (ns4)
			{
				document.write(unescape(sText));
				document.close();
			}
		else
			innerHTML = unescape(sText);
}

function HighlightWord(oSourceObject, sWordList)
{
	var sRegExp;
	var	sHTMLArray;
	var sStrippedHTML;
	var sTemp;

	if (dom)
	{
		//temporarily hide any html tags since we don't want these mixed up in the search
		sRegExp = /<[^<>]*>/ig;  	
		sHTMLArray = oSourceObject.innerHTML.match(sRegExp);
		sStrippedHTML = oSourceObject.innerHTML.replace(sRegExp,"$!$");  //Replace HTML tags
	
		//now highlight the requried words, the word list must be parsed to replace any 'spaces'
		//with the pipe ('|') character since htis is the word seperator
		if (sSearchMatch == 'exact')
			sWordList = sWordList.replace('+', ' ');
		else
			sWordList = sWordList.replace('+', '|');
		sRegExp = new RegExp ("(" + sWordList + ")", "gi");
		sTemp = sStrippedHTML.replace(sRegExp, '<span class="Highlight">$1</span>');
	
		//now rebuild the html
		for(var i = 0; sTemp.indexOf("$!$") > -1; i++)
			sTemp = sTemp.replace("$!$", sHTMLArray[i]);
	
		//pass the html back to the display
		oSourceObject.innerHTML = sTemp;
	}
}

function RemoveHighlight(oSourceObject)
{
	var sRegExp = /(<span class\=Highlight>)([^<>]*)(<\/span>)/ig;
	
	oSourceObject.innerHTML = SourceObject.innerHTML.replace(sRegExp, "$2");
}
					

