/*
@@@BUILDINFO@@@ st03BasicSearch.jsx 466 16-March-2007
*/

/*************************************************************************
*
* ADOBE CONFIDENTIAL
* ___________________
*
*  Copyright 2005 Adobe Systems Incorporated
*  All Rights Reserved.
*
* NOTICE:  All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any.  The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
**************************************************************************/

if( ( stockphoto.timeKeeperOn != undefined )&&( stockphoto.timeKeeperOn ) )
{
	stockphoto.timeKeeper.st03BasicSearch        = {};
	stockphoto.timeKeeper.st03BasicSearch.StTime = new Date();
}

// Add zstringCache instance.
stockphoto.search.zc = new stockphoto.zstringCache("st03BasicSearch");
stockphoto.search.zc.dict = "Search.txt";

stockphoto.search.resultFolderMissing = stockphoto.search.zc.get("$$$/Search/ErrorMessage/ResultFolderMissing=Result folder is missing");
stockphoto.search.keywordMissing      = stockphoto.search.zc.get("$$$/Search/ErrorMessage/KeywordMissing=Keyword is undefined or invalid entry");
stockphoto.search.itemsPerPgInvalid   = stockphoto.search.zc.get("$$$/Search/ErrorMessage/ItemsPerPageInvalid=number per page is less than 0");

// Since NavBar itself may not have been loaded at this time, we'll just instantiate a new zstring cache
// which is much faster than dyn-loading NavBar.jsx itself
stockphoto.search.NavBar = {};
stockphoto.search.NavBar.zcSearch  = new stockphoto.zstringCache(stockphoto.core.zstringFiles.NavBar, stockphoto.core.getASPSearchLangLocale());
stockphoto.search.NavBar.zcSearch.dict = stockphoto.core.zstringFiles.NavBar + '.txt';
// Operators
stockphoto.search.OP_AND        =stockphoto.search.NavBar.zcSearch.get("$$$/NavBar/Operations/OP_AND=AND");
stockphoto.search.OP_OR 		=stockphoto.search.NavBar.zcSearch.get("$$$/NavBar/Operations/OP_OR=OR");
stockphoto.search.OP_NOT		=stockphoto.search.NavBar.zcSearch.get("$$$/NavBar/Operations/OP_NOT=NOT");

stockphoto.search.isAsynchronous = function()
{
	stockphoto.log("Iterator: isAsynchronous");
	return true;
}

stockphoto.search.startIteration = function()
{
	stockphoto.log("Iterator: startIteration");
}

stockphoto.search.getNext = function()
{
	var result;
	stockphoto.log("Iterator: getNext, length: " + this.request.results.length + ", index: " + this.request.resultsIndex);
	stockphoto.log(this.request.results);
	if (this.request.resultsIndex < this.request.results.length)
	{
		f = this.request.results[this.request.resultsIndex++];  // what is f and should it be a global / MRB041202
		if (f.exists)
		{
			result = new Thumbnail(f);
		}
	}
	if (result != undefined)
	{
		stockphoto.log("getNext result: \"" + result.path + "\"");
	}
	return result;
}

stockphoto.search.isComplete = function()
{
	var result = !(this.request.resultsIndex < this.request.results.length);
	stockphoto.log("Iterator: isComplete = " + result);
	return result;
}

stockphoto.search.abortIteration = function()
{
	stockphoto.log("Iterator: abortIteration");
}

stockphoto.search.invalidate = function()
{
	stockphoto.log("Iterator: invalidate");
}

// <BoxCar3>
// Scrolls the bridge window to the last thumbnail
// currently visible
stockphoto.search.scrollToLastThumbnail = function(doc_id)
{
	if ((stockphoto.documents[doc_id] == undefined) || (stockphoto.documents[doc_id].document == undefined))
	{
  	return;
  }

	var oDoc = stockphoto.documents[doc_id].document;
	
  if ((oDoc.visibleThumbnails == undefined) || (oDoc.visibleThumbnails.length < 1))
	{
    return;
  }
	else
	{
	   var oLastThumbnail = oDoc.visibleThumbnails[oDoc.visibleThumbnails.length - 1];
	   oDoc.reveal(oLastThumbnail);
	}
}

stockphoto.search.removeEmptyFolder=function( fs )
{
	var j, f;
	f = fs.getFiles("*");
	if( f != null )
	{
		for( j=0; j<f.length; j++ )
		{ 
			if( f[j] instanceof File )
			{
				f[j].remove();
			}
			else
			{
				stockphoto.search.removeEmptyFolder( f[j] );
			}
		}
		fs.remove();
	}
}

stockphoto.search.eventHandler = function (event)
{
	var rmvFolderNm, rmvFolderFs, rmvFolderFls, doc_id, searchID, j, n;  // needed to handle multiple windows

	if  ( this.doc_id != undefined ) // check to see if window closed MRB041129
	{
		doc_id = this.doc_id;
	} 
	else // window closed MRB041129
	{
		if( event.doc_id == undefined )
		{
			doc_id = app.document.id;
		}
		else 
		{
			doc_id = event.doc_id;
		}
	};
	if( this.searchID != undefined )
	{
		searchID = this.searchID;
	}
	else
	{
		searchID = 0; // -1 for do-not-care, 1,2,3 for valid ID
	}

	if (event.eventClass == "search")  // Always defined MRB041129
	{
		if (event.eventName == "status")  // Always defined MRB041129
		{
			if (event.status == "thumbnailsReady")  // dead code ? MRB041129
			{
				stockphoto.search.handleThumbnailsReady(event, this);
			}
			if (event.status == "thumbnailReady")  // dead code ?  MRB041129
			{
				stockphoto.search.handleThumbnailReady(event, this);
			}
			if ((event.count != undefined) && (event.total != undefined))  // count = x , total = y  MRB041129
			{
				var target;  // ask Alex what target is  MRB041129
				var doc = stockphoto.documents[doc_id].document;
				if( doc == undefined )
				{
					return;
				}
				var t = doc.thumbnail  // thumbnail may be a folder of thumbnails
				if (t != undefined)
				{
					//target = t.spec;
				}
                // NOTE: The events from Grinder must be processed to keep search
                // folder counts in sync. The following check is not required
                // as it excludes bridge URLs (e.g. bridge://startpage), among others.
                // if (target instanceof Folder)
				{
                    // NOTE: updateXofY is no longer required
                    // var updateXofY = (this.folder.fsName == target.fsName);

					if (true/*updateXofY*/)
					{
						switch (event.status)
						{
							case "initializing":
							{
							    stockphoto.core.util.startTimer("Search - First Result");
								stockphoto.DL.NavBar.updateXofY("beginSearch", "0", "0", event.status, doc_id, searchID, "BasicSearch #.1" );
								break;
							}
							case "foundCount":
							case "thumbnailMoved":
							case "thumbnailReady":
							case "thumbnailsReady":
							{
								event.count = stockphoto.core.getjpgImagecount(stockphoto.core.folder.getMySearchesFolder()+"/"+stockphoto.NavExtFnc.GetFolderName( doc_id ));
								if( event.count > event.total ){
									event.total = event.count
								}
							  	stockphoto.DL.NavBar.updateXofY("show", ""+event.count, ""+event.total, event.status, doc_id, searchID, "BasicSearch #.2" );
                
                				if ((event.firstThumbnail != undefined) && this.first == undefined)
								{
								    stockphoto.core.util.writeTimer("Search - First Result");
									var srcFile = new File(event.firstThumbnail);
									var dstFile = new File(this.folder + "/" + srcFile.name);
									this.first = dstFile;
								}

								break;
							}
							case "YFinal":
							{
								if( stockphoto.Burp.doIt ) // in stockphoto.core.html.doPhotoDirInDefaultBrowser
								{
								/*B*/	try
								/*B*/	{
								/*B*/		if( event.details != undefined )
								/*B*/			stockphoto.Burp.XofY( doc.id, 2, event.details, 0 ); 
								/*B*/	} catch(e) { ; }
								}
								// KR - Change
								event.count = stockphoto.core.getjpgImagecount(stockphoto.core.folder.getMySearchesFolder()+"/"+stockphoto.NavExtFnc.GetFolderName( doc_id ));
								if( event.count > event.total ){
									event.total = event.count
								}
								
								stockphoto.DL.NavBar.updateXofY("show", ""+event.count, ""+event.total, event.status, doc_id, searchID, "BasicSearch #.2a" );
								break;
							}
							case "pageFull":
							{
								if( stockphoto.Burp.doIt ) // in stockphoto.core.html.doPhotoDirInDefaultBrowser
								{
								/*B*/	try
								/*B*/	{
								/*B*/		if( event.details != undefined )
								/*B*/			stockphoto.Burp.XofY( doc.id, 0, event.details, stockphoto.Burp.searchPageNo[ doc.id ] ); 
								/*B*/	} catch(e) { ; }
								}
								
								if ((event.count > 0) && (event.total > 0))
								{
									// KR - Change
									event.count = stockphoto.core.getjpgImagecount(stockphoto.core.folder.getMySearchesFolder()+"/"+stockphoto.NavExtFnc.GetFolderName( doc_id ));
									if( event.count > event.total ){
										event.total = event.count
									}
								
								    stockphoto.DL.NavBar.updateXofY("endSearch", ""+event.count, ""+event.total, event.status, doc_id, searchID, "BasicSearch #.3" );
								}
								else
								{
								    stockphoto.search.handleNoSearchResults(event, this, doc, doc_id, searchID);
								}
								break;
							}
							case "allThumbnailsMoved":
							{
								if( stockphoto.Burp.doIt ) // in stockphoto.core.html.doPhotoDirInDefaultBrowser
								{
								/*B*/	try
								/*B*/	{
								/*B*/		if( event.details != undefined )
								/*B*/			stockphoto.Burp.XofY( doc.id, 1, event.details, stockphoto.Burp.searchPageNo[ doc.id ] ); 
								/*B*/	} catch(e) { ; }
								}
								if (event.total > 0)
								{
									// KR - Change
									event.count = stockphoto.core.getjpgImagecount(stockphoto.core.folder.getMySearchesFolder()+"/"+stockphoto.NavExtFnc.GetFolderName( doc_id ));
									if( event.count > event.total ){
										event.total = event.count
									}
									
									stockphoto.DL.NavBar.updateXofY("endSearch", ""+event.count, ""+event.total, event.status, doc_id, searchID, "BasicSearch #.4b" );
								}
								else 
								{ 
									stockphoto.search.handleNoSearchResults(event, this, doc, doc_id, searchID);
								}
								break;
							}
						}
					}
					else
					{
						stockphoto.DL.NavBar.updateXofY("hide", "0", "0", "error", doc_id, searchID, "BasicSearch #.5" );  // 0 of 0 MRB041129
					}
				}
			}
		}
		else if (event.eventName == "error")
		{
			if (stockphoto.DL.alertBox( event.errorCode) == false)
			{
				stockphoto.DL.generalAlertBox(stockphoto.alertBox.localizedStr4ErrMsg.MESSAGE_ES_ERROR_OCCURED, 2); // 2 means what? MRB041129
			}
			stockphoto.core.checkProxyOnFail();
		}
	}
} 

stockphoto.search.handleThumbnailsReady = function (event, obj)
{
	var paths = eval(event.paths);
	while (paths.length > 0)
	{
		var srcFile = new File(paths.shift());
		var dstFile = new File(obj.folder + "/" + srcFile.name);
                    
		srcFile.copy(dstFile);
		srcFile.remove();

		obj.results.push(dstFile);
		if (obj.first == undefined)
		{
			obj.first = dstFile;
		}   
	} 
	if (obj.iterator != undefined)
	{
		stockphoto.log("iterator: refreshing");
		obj.iterator.refresh();
	}
}

stockphoto.search.handleThumbnailReady = function (event,obj)
{
	var srcFile = new File(event.path);
	var dstFile = new File(obj.folder + "/" + srcFile.name)
	stockphoto.log("dstFile: \"" + dstFile.fsName + "\"");
	if( ("undefined" != typeof scrFile) && srcFile.exists)
	{
		srcThumb = new Thumbnail(unescape(File.decode(srcFile.fsName)));
		srcThumb.moveTo(obj.folder);
		obj.results.push(dstFile);
		if (obj.iterator != undefined)
		{
			stockphoto.log("iterator: refreshing");
			obj.iterator.refresh();
		}
	}
}
stockphoto.search.showNoConnectionPage = function(doc_id, path)
{

	if("undefined" == typeof(doc_id) || "undefined" == typeof(path))
	{
		return;
	}
	var newNm;
	var filePath = unescape(path);
	var doc = stockphoto.core.findDoc( doc_id );
	var oFile, disFile

    if ("undefined" != typeof doc)
    {
		doc.visitUrl = stockphoto.core.noConnectionFilter;

		(stockphoto.core.BoxCar.cntHomePage)++;
		var	oThumb = new Thumbnail("stockphoto://webpagefailed"+stockphoto.core.BoxCar.cntHomePage);
		oThumb.displayMode = "web";
		newNm = stockphoto.core.folder.getTempFolder()+"/"+stockphoto.core.CurrentProcessID+"/"
				+ "noConn"+( stockphoto.core.BoxCar.cntHomePage )+".htm";
		
		oFile = File( filePath );
		
		if ("undefined" != oFile)
		{		
			oFile.copy( newNm );

            disFile = File( newNm );

			if ("undefined" != disFile)
			{		            
				oThumb.displayPath = unescape( disFile.fsName );
				stockphoto.core.BoxCar.NavBar.SetInTheHPLoadError( true, doc.id );
				doc.thumbnail = oThumb;
				stockphoto.core.BoxCar.szInFailedHomePage = stockphoto.core.util.getDisplayPath(oThumb,"");
			}
		}
	}
}


stockphoto.search.basicSearch = function( terms, resultsFolder, thumbsPerPage, doc_id, sDisplayKeyword )  // need better param names  MRB041129
{

	var doc, searchID;
	if (stockphoto.documents[doc_id] == undefined)
	{
		return;
	}

	doc = stockphoto.documents[doc_id].document;
	if( doc == undefined )
	{
		return;
	}

	if ((terms == undefined)|| (terms == null) || (terms == "") )
	{
		stockphoto.DL.generalAlertBox(stockphoto.search.keywordMissing, 1);	
		return;
	}

	if (resultsFolder == null) 
	{
		stockphoto.DL.generalAlertBox(stockphoto.search.resultFolderMissing, 1);
		return;
	}
	else if (resultsFolder.name == stockphoto.core.consts.ReadOnlyFolder)
	{
		stockphoto.core.util.alertReadOnlyFolder(resultsFolder.path);
		return;
	}

	if (thumbsPerPage  <= 0) 
	{
		stockphoto.DL.generalAlertBox(stockphoto.search.itemsPerPgInvalid, 1);
		return;
	}

	if( stockphoto.DL.isAlreadyLoaded( stockphoto.DL.jsx_NavBar ) ) 
	{
		stockphoto.NavExtFnc.GetFolderAndNumbers_NEW( resultsFolder, doc_id, true, "search.basicSearch" );
		searchID = stockphoto.NavIntDt_t[doc_id].FaN.Last_i;
		stockphoto.NavIntDt.FldAndNumTab[ searchID ].x = -1;
		stockphoto.NavIntDt.FldAndNumTab[ searchID ].y = -1;
		stockphoto.DL.NavBar.updateXofY( "show", "0", "0", "search-start", doc_id, -1, "stockphoto.DL.search.basicSearch - zero clear" );
	}
	else
	{
		searchID = 0;
	}
		
	var request =	   // pass to c code MRB041129
	{
		searchTerms:    (terms instanceof Object) ? terms : { Keyword: terms },  // MRB041202  this is a little ugly
		folder:         resultsFolder,
		numberPerPage:  thumbsPerPage,
		eventHandler:   stockphoto.search.eventHandler,
		results:        [ ],
		resultsIndex:   0,
		iterator:       undefined,
		first:          undefined,
		document:       doc,
		doc_id:         doc_id,
		searchID:       searchID
	};
	var SearchKeyWords;  // start with lower case s MRB041129
	var ik;  // ??   Check to find out what the flock  image key word  MRB041129
	if( request.searchTerms.keywordForPromotion == undefined ) 
	{
		SearchKeyWords = request.searchTerms.Keyword;
	} 
	else 
	{
		SearchKeyWords = request.searchTerms.keywordForPromotion; // key word has nothing to do with images MRB041129	
	};

    ik = stockphoto.NavExtFnc.SetFolderAndKey( resultsFolder, SearchKeyWords /* unescaped */, doc_id, sDisplayKeyword );
    
	stockphoto.core.folder.openVirtualFolder(doc, resultsFolder);

	// The following code is same as the one in event handler
	stockphoto.NavExtFnc.SetPreviousKeyIndex( ik, doc_id );
	stockphoto.NavExtFnc.SetRecent_s_Folder( ik, doc_id );
	stockphoto.NavExtFnc.RefreshBMNavBar( request.searchTerms.LangID, doc );
	stockphoto.core.log.logString( 0, "\n[search.basicSearch] key="
									 +request.searchTerms.Keyword+" f="+request.folder+" n="
									 +request.numberPerPage+" lang="+request.searchTerms.LangID
									 +" doc_id="+request.doc_id );
	if( stockphoto.Burp.doIt ) { // search main entry
/*B*/			try
/*B*/			{
/*B*/				stockphoto.Burp.search( doc_id, request ); // must be before SwitchNavBar
/*B*/			} catch(e) { ; }
	}
   	stockphoto.core.NavBar.SwitchNavBar( "st03_BasicSearch", 0, 1, doc );

	if( stockphoto.core.BoxCar.NavBar.GetRecentSearchFolder( doc_id ) == "" ) 
	{
		var wPath = resultsFolder.path;
		stockphoto.core.BoxCar.NavBar.SetRecentSearchFolder( ( File( wPath ).fsName ).toUpperCase(), doc_id );
	};
		var searchIndex = stockphoto.core.getFolderNameFromPath(unescape(resultsFolder.fsName.toLowerCase()));
	stockphoto.search.active[searchIndex] = request;

	//doc.topNavbar.visible = true; 
	stockphoto.eventHandler.pathAnalyzer.ChangeNavVisiblity( doc, true, "DL.stockphoto.search.basicSearch" ); 
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) )
	{
		stockphoto.NavExtFnc.PrepareForSearch( doc_id );
	}

	// record search folder name for this doc_id
	stockphoto.NavExtFnc.SetFolderName( request.folder, doc_id );

	if (sDisplayKeyword == undefined)
	{
        if (request.searchTerms.Keyword != undefined)
        {
            sDisplayKeyword = request.searchTerms.Keyword;
        }
        else
        {
            sDisplayKeyword = '';
        }
    }

	// failing keyword update for Promotion
	if( request.searchTerms.Keyword == undefined )
	{
		stockphoto.NavIntFnc.SetKeyWord( "Promotion", false /*=unescaped*/, doc_id, true );
	}
	else
	{
	   stockphoto.NavIntFnc.SetKeyWord( sDisplayKeyword, false /*=unescaped*/, doc_id, true );
	}
	
	stockphoto.impl.deleteSearch(request.folder);

    // <BoxCar3>
    var oCacheFolder = new Folder(request.folder.fsName + '/CACHE');
    var oCreateResult = oCacheFolder.create(); // Create the folder now. It will be set to Hidden in Stock Core.
    oCacheFolder.hidden = true;
    
    var oSearchInfo = new File(oCacheFolder.fsName + '/SearchInfo.txt');
    oSearchInfo.encoding = 'UTF-16'; // To support all locales correctly
    oCreateResult = oSearchInfo.open('w');

    if (request.searchTerms instanceof Object)
    {
        var oCollectionList;
    
        if (request.searchTerms.Collections != undefined)
        {
            oCollectionList = request.searchTerms.Collections.split(','); // must NOT be localized
        }
        else
        {
            oCollectionList = [];
      
            for (var nCollIter = 0; nCollIter < stockphoto.providers.collections.length; ++nCollIter)
            {
                oCollectionList[nCollIter] = stockphoto.providers.collections[nCollIter].CollectionName.Value;
            }
        }
    
        oSearchInfo.writeln('[ProviderCollections]');
        for (var nCollIter = 0; nCollIter < oCollectionList.length; ++nCollIter)
        {
            oSearchInfo.writeln(oCollectionList[nCollIter]);
        }
  
        oSearchInfo.writeln('[OriginalKeyword]');
        oSearchInfo.writeln(sDisplayKeyword);

        // Replace keyword with the simplified version...
        if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscUtils ) ) 
        {
            request.searchTerms.Keyword = stockphoto.MiscUtils.search.simplifyKeyword(request.searchTerms.Keyword);
        }

        oSearchInfo.writeln('[SimplifiedKeyword]');
        oSearchInfo.writeln(request.searchTerms.Keyword);
        
        //AK:added by aman
        // isMaskedImageCheckBoxSelected can 3 values
        // "notSeleced" means masked image not selected.
        // "OnlyMISelected" means only masked image selected 
        // "AllSelected" means all selected
        
        var isMaskedImageCheckBoxSelected = "notSelected";
		var bPhotoObject = false;

		if (undefined == stockphoto.search.searchMediaTypes[doc_id])
        {
			stockphoto.search.searchMediaTypes[doc_id] = "";
        }

        if ( true == stockphoto.core.displayPhotoObjectCollectionFeatureflag)
		{

        	bPhotoObject = ( ("" == stockphoto.search.searchMediaTypes[doc_id] ) || (-1 != stockphoto.search.searchMediaTypes[doc_id].indexOf(stockphoto.search.textPhotoObjects)));
        	if (true == bPhotoObject)
        	{
        	    var bPhotography = (("" == stockphoto.search.searchMediaTypes[doc_id] ) || (-1 != stockphoto.search.searchMediaTypes[doc_id].indexOf(stockphoto.search.textPhotography)) );
                var bIllustrations = (("" == stockphoto.search.searchMediaTypes[doc_id] ) || (-1 != stockphoto.search.searchMediaTypes[doc_id].indexOf(stockphoto.search.textIllustration)) );
             	if ((true == bPhotography) && (true == bIllustrations))
        		{
				 	isMaskedImageCheckBoxSelected = "AllSelected";        		
        		}
        		else if ((false == bPhotography) && (false == bIllustrations))
        		{
				  isMaskedImageCheckBoxSelected = "OnlyMISelected";        		
        		}
        		else
        		{
					isMaskedImageCheckBoxSelected = "MISelected";       		
        		}      	
    	    }
    	}
  	    
  	    oSearchInfo.writeln('[MaskedImageSelected]');
  	    oSearchInfo.writeln(isMaskedImageCheckBoxSelected);
        //AK:end of added by aman

        stockphoto.search.searchKeyword[doc_id] = request.searchTerms.Keyword;
    }

    oSearchInfo.close();
   
    //AK:added by aman 
  	
	// Updating the terms variable
	// if ( true == stockphoto.core.displayPhotoObjectCollectionFeatureflag)
	// {
	
    	 request.searchTerms.Collections  = stockphoto.search.updateCollectionListForSearch(doc_id, request.searchTerms);
    	 
    	 if("" == request.searchTerms.Collections) // the result would be 'undefined' if all collections are selected. "" if none selected.
    	 {
            // We should change to the Previous Search folder first, and then scheduleTask
            // (this achieves the designed functionality - just like in the case of Normal 'No Search Results' case)
    	    // [workaround - don't use this directly] doc.thumbnail = unescape( stockphoto.core.folder.getMySearchesFolder() );
    	    app.scheduleTask("if (undefined != app.document) { app.document.thumbnail = unescape(stockphoto.core.folder.getMySearchesFolder()); } stockphoto.search.scheduleNoSearchResults(" + doc_id + ");", 10, false);
    		return;
    	 }
	
    // }
   
  stockphoto.search.searchMediaTypes[doc_id] = undefined; // reset
  
  //AK:end of added. 
  var bSendProxyResult = true; 
  
  		bSendProxyResult = stockphoto.core.SendProxyCredentials();
 
    if (undefined == request.searchTerms.Collections) // should not send 'undefined' as the search request...
    {
        request.searchTerms.Collections = "";
    }
 
	if ("undefined" != typeof(bSendProxyResult) && bSendProxyResult)
	{
		stockphoto.impl.search(request);
	}
	else
	{
	   app.scheduleTask( "stockphoto.search.scheduleProxyNoSearchResults("+doc_id+")", 10, false );
	}	
}

stockphoto.search.scheduleProxyNoSearchResults = function (doc_id)
{
	if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) )
	{
		var doc = stockphoto.documents[doc_id];
		doc.thumbnail = unescape( stockphoto.core.folder.getMySearchesFolder() );
		stockphoto.search.removeSearchFolder( doc_id );
		
		
		stockphoto.search.showNoConnectionPage(doc_id,stockphoto.NavExtFnc.PrepareNoConnectionHTM( doc.id ));
		if ( ( doc.topNavbar != undefined )&& ( doc.topNavbar.visible != undefined ) )
		{
			stockphoto.eventHandler.pathAnalyzer.ChangeNavVisiblity( doc, true, "stockphoto.core.doDocEvent #1" );
		}		
	}
}

//This function dispalys no search result in case of masked images,where no request is sent. 
stockphoto.search.scheduleNoSearchResults = function(doc_id)
{
	if (undefined != doc_id)
	{
        var wKeyWd1 = stockphoto.DL.NavBar.GetKeywordFromES( "error" /* must be this keyword */, doc_id );
        wKeyWd1 = wKeyWd1.replace(/\\/g,'\\\\');
        
        doc = stockphoto.documents[doc_id];
        if (undefined != doc)
        {
        	stockphoto.DL.MiscDlgs.NoSearchResults( wKeyWd1, doc );
        }
        
        stockphoto.search.removeSearchFolder(doc_id);
    }
}

// Return the list of collections which need to be searched.
stockphoto.search.updateCollectionListForSearch = function( doc_id, searchTerms )
{
    var collections = (undefined != searchTerms)? searchTerms.Collections:undefined;
	var bAllCollSelected = (undefined == collections);

	
	var sFinalResList = collections;
	
    var bIsUpdateRequired = true;
	var bPhotoObject = true;
	var bOtherMediaTypes = true;
	
	if (undefined == stockphoto.search.searchMediaTypes[doc_id])
    {
		stockphoto.search.searchMediaTypes[doc_id] = "";
    }
        
	// Check if an update of collection list is really required...
	if ((undefined != searchTerms) && (undefined != searchTerms.MediaTypes))
	{
        
		bPhotoObject = (-1 != stockphoto.search.searchMediaTypes[doc_id].indexOf(stockphoto.search.textPhotoObjects));
		
        bOtherMediaTypes = (("" == searchTerms.MediaTypes) && (false == bPhotoObject)) 
                        || (-1 != stockphoto.search.searchMediaTypes[doc_id].indexOf(stockphoto.search.textPhotography)) ||
                            (-1 != stockphoto.search.searchMediaTypes[doc_id].indexOf(stockphoto.search.textIllustration));
                            
        bIsUpdateRequired = true; // (bPhotoObject ^ bOtherMediaTypes);
    }
	
	var arCollsSelected = new Array();

	if (true == bAllCollSelected)
	{
		collections = "";
	}
	else
	{
		var arCollsList = collections.split(",");
		
		for (var nCollIter = 0; nCollIter < stockphoto.providers.collections.length; ++nCollIter)
		{
			var bFound = false;
			for (var nAvailIter = 0, nTotalAvail = arCollsList.length; nAvailIter < nTotalAvail; ++nAvailIter)
			{
				if (stockphoto.providers.collections[nCollIter].CollectionName.Value == arCollsList[nAvailIter])
				{
					bFound = true;
					arCollsList.splice(nAvailIter, 1);
					break;
				}
			}
			
			arCollsSelected.push(bFound);
		}
	}

	var arFinalCollsList = new Array();
	var iTotalColl = 0;
	
	if (true == bIsUpdateRequired)
    {
        // Inside this block, listObj should not+ be undefined (ensured by the above conditionals)

  		for (var nCollIter = 0; nCollIter < stockphoto.providers.collections.length; ++nCollIter)
		{
			if ( true == bAllCollSelected || true == arCollsSelected[nCollIter] ) // If the collection is selected
			{
                // Is this a Photo Object Collection?
				var bIsCurrentPhotoObjColl = ((undefined != stockphoto.providers.collections[nCollIter].MaskedImage)
                   && (undefined != stockphoto.providers.collections[nCollIter].MaskedImage.Value)
                   && ("0" != stockphoto.providers.collections[nCollIter].MaskedImage.Value));
                
                if ( (true == bPhotoObject && true == bIsCurrentPhotoObjColl) ||
                    (true == bOtherMediaTypes && false == bIsCurrentPhotoObjColl) )
                {
                    // Add the collection to the final list
                    arFinalCollsList[iTotalColl++] = stockphoto.providers.collections[nCollIter].CollectionName.Value;
                }
                
			} // if ( true == listObj.collectionSelected[nCollIter] )
		} // for
	
		sFinalResList =  arFinalCollsList.join(",");
	} // if (true == bIsUpdateRequired)
	
	// Get Comma Separated list from array
	return sFinalResList;
}

stockphoto.search.moreThumbs = function( resultsFolder, thumbsPerPage, doc_id )
{
	if (stockphoto.documents[doc_id] == undefined)
	{
		return;
	}

	var doc = stockphoto.documents[doc_id].document;
	if( doc == undefined )
	{
	        return;
	}

	var ik, keyword  = ""; //must be empty.

	if ((resultsFolder == null) || (resultsFolder == undefined))
	{
		stockphoto.DL.generalAlertBox(stockphoto.search.resultFolderMissing, 1);
		returned;
	}

	if (thumbsPerPage  <= 0) 
	{	
		stockphoto.DL.generalAlertBox(stockphoto.search.itemsPerPgInvalid, 1);
		return;
	}

   	var searchKey = stockphoto.core.getFolderNameFromPath(unescape(resultsFolder.fsName.toLowerCase()))
//	var searchKey = unescape(resultsFolder.fsName.toLowerCase());

	if (stockphoto.search.active[searchKey] != undefined)
	{
		requestMore = stockphoto.search.active[searchKey];
		requestMore.searchTerms = { };
		requestMore.numberPerPage = thumbsPerPage;
		requestMore.first = undefined;
		requestMore.doc_id = doc_id;
	}
	else
	{
		requestMore =
		{
			searchTerms:    { },
			folder:         resultsFolder,
			numberPerPage:  thumbsPerPage,
			eventHandler:   stockphoto.search.eventHandler,
			results:        [ ],
			resultsIndex:   0,
			iterator:       undefined,
			first:          undefined,
			document:       doc,
			doc_id:         doc_id
		};

		stockphoto.search.active[searchKey] = requestMore;
	}

	stockphoto.NavExtFnc.GetFolderAndNumbers_NEW( requestMore.folder, doc_id, false, "search.moreThumbs" );
	requestMore.searchID = stockphoto.NavIntDt_t[doc_id].FaN.Last_i;
	stockphoto.NavIntDt.FldAndNumTab[ ( requestMore.searchID ) ].noMoreImg = false;

	// The below is not always correct
	// x and y value of "x of y" needs to be recalculated for display
	if( ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) )&&
	    ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_HTMUtil ) ) ) 
	{
		var fldr   =requestMore.folder; 
		var DOSfldr=unescape( ( Folder( fldr ) ).fsName );
		var bRet   ={};
		bRet = stockphoto.eventHandler.pathAnalyzer.AnalyzingPath( DOSfldr, false, false, doc, true );
		if( ( bRet.kKeyWd == undefined )||( bRet.kKeyWd == "" ) )
		{
			bRet.kKeyWd = "unknown";
		}
		ik = stockphoto.NavExtFnc.SetFolderAndKey( DOSfldr, bRet.kKeyWd /* unescaped */, doc_id );
		// The following code is same as the one in event handler
		stockphoto.NavExtFnc.SetPreviousKeyIndex( ik, doc_id );
		stockphoto.NavExtFnc.SetRecent_s_Folder( ik, doc_id );
	};

	stockphoto.core.folder.openVirtualFolder(doc, resultsFolder);

	stockphoto.core.log.logString( 0, "\n[search.moreThumbs]  f="
	+requestMore.folder+" n="+requestMore.numberPerPage
	+" doc_id="+requestMore.doc_id );
	stockphoto.core.NavBar.SwitchNavBar( "st03_MoreSearch", 0, 1, doc );
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) {
		stockphoto.NavExtFnc.PrepareForMoreThumb( requestMore.folder, requestMore.searchTerms.Keyword, doc_id );
	};

	// record search folder name for this doc_id
	stockphoto.NavExtFnc.SetFolderName( requestMore.folder, doc_id );

  // Before firing the 'More Search' request w/ Live Object,
  // Scroll to the last image in this folder, so user can see the new
  // images being added...
  stockphoto.search.scrollToLastThumbnail( doc_id );
  
	if( stockphoto.Burp.doIt ) { // more-search main entry
/*B*/			try
/*B*/			{
/*B*/				stockphoto.Burp.moreSearch( doc_id, requestMore ); // must be before SwitchNavBar
/*B*/			} catch(e) { ; }
	}
	stockphoto.core.SendProxyCredentials();
	stockphoto.impl.search(requestMore);
	stockphoto.eventHandler.pathAnalyzer.ChangeNavVisiblity( doc, true, "stockphoto.search.moreThumbs" );
}

if( ( stockphoto.timeKeeperOn != undefined )&&( stockphoto.timeKeeperOn ) )
{
	stockphoto.core.util.edTime( stockphoto.DL.jsx_BasicSearch );
}

// Returns: array containing all lines with [sInfoTag]
stockphoto.search.LoadSearchInfoFromFS = function( oFSObj, sInfoTag )
{
    var arInfoLines = [ ];
    
    if ((oFSObj == undefined) || (oFSObj.exists == false) || (oFSObj.open('r') == false))
    {
        return arInfoLines;    
    }
    
    var bInfoTagEncountered = false;
    
    while (oFSObj.eof == false)
    {
        var sLine = oFSObj.readln();
        
        if ((bInfoTagEncountered == false) && (sLine != sInfoTag))
        {
            continue;
        }
        
        if (bInfoTagEncountered == false)
        {
            bInfoTagEncountered = true;
            continue;
        }
        
        if (sLine.length > 0)
        {
            if (sLine[0] != '[')
            {
                arInfoLines.push(sLine);
            }
            else
            {
                break;
            }
            
        }
    }
    
    oFSObj.close();
    
    return arInfoLines;
}

stockphoto.search.refreshSearchLangLocale = function()
{
    var sSearchLangLocale = stockphoto.core.getASPSearchLangLocale();
    
    // Refresh only if the search locale has changed...
    if ((stockphoto.search.NavBar.zcSearch == undefined)
        || (stockphoto.search.NavBar.zcSearch.locale != sSearchLangLocale))
    {
        if (stockphoto.search.NavBar.zcSearch != undefined)
        {
            delete stockphoto.search.NavBar.zcSearch;
        }
        
        stockphoto.search.NavBar.zcSearch       = new stockphoto.zstringCache(stockphoto.core.zstringFiles.NavBar, sSearchLangLocale);
        stockphoto.search.NavBar.zcSearch.dict  = stockphoto.core.zstringFiles.NavBar + '.txt';

        // Operators
        stockphoto.search.OP_AND                = stockphoto.search.NavBar.zcSearch.get("$$$/NavBar/Operations/OP_AND=AND");
        stockphoto.search.OP_OR                 = stockphoto.search.NavBar.zcSearch.get("$$$/NavBar/Operations/OP_OR=OR");
        stockphoto.search.OP_NOT                = stockphoto.search.NavBar.zcSearch.get("$$$/NavBar/Operations/OP_NOT=NOT");
    }
}

// Handle No Search Results
// (functionality moved from eventhandler switch-case to a separate function)
stockphoto.search.handleNoSearchResults = function(event, obj, doc, doc_id, searchID)
{
    stockphoto.DL.NavBar.updateXofY("endSearch", "0", "0", event.status, doc_id, searchID, "BasicSearch #.4a" );
    
    //****Watson 1259364,1170877 	
    if (("undefined" != typeof stockphoto) && ("undefined" != typeof stockphoto.NavIntDt_t[doc_id]) && ("undefined" != typeof stockphoto.NavIntDt_t[doc_id].FaN) && ("undefined" != typeof stockphoto.NavIntDt_t[doc_id].FaN.Last_i))
    {
		if(searchID == stockphoto.NavIntDt_t[doc_id].FaN.Last_i)
		{  
			var wKeyWd1 = stockphoto.DL.NavBar.GetKeywordFromES( "error" /* must be this keyword */, doc_id );
			wKeyWd1 = wKeyWd1.replace(/\\/g,'\\\\');
 			doc.thumbnail = unescape( stockphoto.core.folder.getMySearchesFolder() );
  			stockphoto.DL.MiscDlgs.NoSearchResults( wKeyWd1, doc );
  		}
  	}
    
    //****Watson 1259364,1170877
    if ( ("undefined" != stockphoto) && ("undefined" != stockphoto.NavIntDt) &&
		 ("undefined" != stockphoto.NavIntDt.FldAndNumTab) && ("undefined" != stockphoto.NavIntDt.FldAndNumTab[searchID]) &&
		 ("undefined" != stockphoto.NavIntDt.FldAndNumTab[searchID].FolderName))
	{
		stockphoto.search.removeSearchFolder(doc_id, searchID);
    }
    
    stockphoto.impl.deleteSearch(obj.folder);
    
}

//This function removes the search folder in case no search results case.
stockphoto.search.removeSearchFolder = function(doc_id, searchID)
{
    if (undefined != doc_id)
    {
        var rmvFolderNm;
        
        if (undefined != searchID)
        {
			rmvFolderNm = stockphoto.core.folder.getMySearchesFolder()+"/"+stockphoto.NavIntDt.FldAndNumTab[searchID].FolderName;
        }
        else
        {
            rmvFolderNm = stockphoto.core.folder.getMySearchesFolder()+"/"+stockphoto.NavExtFnc.GetFolderName( doc_id );
        }
        
        var rmvFolderFs = Folder( rmvFolderNm );
        
        if( rmvFolderFs.exists )
        {
        	rmvFolderFls = rmvFolderFs.getFiles("*");
        	if( rmvFolderFls != null )
        	{
        		var iOtherFiles = 0;
        		for(var iFileIter=0; iFileIter<rmvFolderFls.length; iFileIter++ )
        		{
        			if( rmvFolderFls[iFileIter].name != "CACHE" )
        			{
        				iOtherFiles++;
        			}
        		}
        		if (iOtherFiles == 0) // folder contains only "CACHE" subfolder
        		{
        			stockphoto.search.removeEmptyFolder( rmvFolderFs );
        		}
        	}
        }
    }
}
