/*
@@@BUILDINFO@@@ st21MiscUtils.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.
**************************************************************************/

// Utility functions that are not required at startup time...
// Mostly moved from st00Core to here..

stockphoto.MiscUtils = {};

stockphoto.MiscUtils.core = {};
stockphoto.MiscUtils.file = {};
stockphoto.MiscUtils.folder = {};
stockphoto.MiscUtils.search = {};
stockphoto.MiscUtils.metadata = {};
stockphoto.MiscUtils.strings = {};


var item =
{
	Keyword: 		undefined,
	Operation:		undefined,
	Type:			undefined,
};

var const_ItemTypeKeyword			= 0;
var const_ItemTypeOperation			= 1;
var const_ItemTypeCompKeyword		= 2;

const_OpTypeNot					= 0;
const_OpTypeAnd					= 1;
const_OpTypeOr					= 2;


stockphoto.MiscUtils.file.resetFileName=function( name )
{
    var i, Bt, ret={bs:"", alt:"_tmpJpg_", bNeed:false};
    for( i=0; i<name.length; i++ )
    {
        ret.bNeed = true;            
        Bt = name.charAt( i );
        if( Bt == '"' )
        {
                ret.bs   += '\\x22';
                ret.alt  += "_";
        }
        else if( Bt == "'" )
        {
                ret.bs   += '\\x27';
                ret.alt  += "_";
        }
        else if( Bt == "\\" ) 
        {
                ret.bs   += '\\x5C';
                ret.alt  += "_";                            
        }
        else if( Bt == "&" ) 
        {
                ret.bs   += '\\x26';
                ret.alt  += "_";
        }
        else
        {
                ret.bs   += Bt; 
                ret.alt  += Bt;
                ret.bNeed = false;                                  
        }
    }
    return( ret );
}

stockphoto.MiscUtils.metadata.addStockPhotoMetadata = function(thumbPath, params, synch)
{
	var tn = undefined;
	var dolarLevel = $.level;
	$.level=0;
	try
	{	
		if(thumbPath instanceof Thumbnail)
			tn = new Thumbnail(thumbPath);
		else
			tn = new Thumbnail(File(thumbPath));
	}
	catch(e){}
	$.level = dolarLevel ;
	if (tn == undefined)
		return;

    tn.refresh("metadata"); // Request refresh metadata..
	var md;
	
	// Get synchronousMetadata if specifically requested by caller.
	// This is used in the AddToCart & Shopping Cart workflow.
	// Since we are using 'metadata' by default, this flag is important.
	if (("undefined" != typeof synch) && (true == synch))
	{
        md = tn.synchronousMetadata;
    }
    else
    {
        md = tn.metadata;
    }

	if (md != undefined)
	{
		md.namespace = "http://ns.adobe.com/StockPhoto/1.0/";

		var rootFields = new Array();
		rootFields[0] = "KindOfImage";
		rootFields[1] = "MediaID";
		rootFields[2] = "Sequence";

		var suffix = 0;
		var i, v, u;

		for (i in rootFields)
		{
			v = rootFields[i] + "/" + md[rootFields[i]];

			if ((rootFields[i] == "Sequence") && (md[rootFields[0]] == "Purchased"))
			{	//Set Sequence to 0 if HiRes
				params["StockPhotoMetadata" + suffix++] = rootFields[i] + "/0";
			}
			else
			{
				params["StockPhotoMetadata" + suffix++] = v;
			}
	
		}

		var mediaFields = new Array();
		mediaFields[0] = "LanguageID";
		mediaFields[1] = "MediaTitle";
		mediaFields[2] = "PartnerName";

		for (i in mediaFields)
		{
			u = md["Media/bmsp:" + mediaFields[i]];
			if ((mediaFields[i] == "MediaTitle") && ((u == undefined) || (u.length == 0)))
				v = mediaFields[i] + "/ ";
			else
				v = mediaFields[i] + "/" + u;

			params["StockPhotoMetadata" + suffix++] = v;
		}
	}
}

stockphoto.MiscUtils.strings.shortenString=function( inStr, MaxCharNo, NoOfTrailingWordsToRetain )
{
	var outStr="", i, n, MaxChar3, each;
	n = inStr.length;
	if( n <= MaxCharNo )
	{
		return( inStr );
	}
	each = inStr.split( ' ' );
	MaxChar3 = MaxCharNo - 3;
	for( i=each.length-NoOfTrailingWordsToRetain-1; i>=0; i-- )
	{
		n -= ((each[i]).length + 1); // new size
		each[i] = "";
		if( n < MaxChar3 )
		{
			break;
		}
	}
	for( i=0; i<each.length; i++ )
	{
		if( each[i] != "" )
		{
			if( i > 0 )
			{
				outStr += ' ';
			}
			outStr += each[i];
		}
		if( i == ( each.length-NoOfTrailingWordsToRetain-1 ) )
		{
			outStr += "...";
		}
	}
	return( outStr );
}

stockphoto.MiscUtils.folder.createNewSearchFolder = function(isearchKeyword, doc_id)
{
	if ((isearchKeyword == null) || (isearchKeyword == undefined) || (isearchKeyword == ""))
	{
		return null;
	}

	var stockPhotoFolder = stockphoto.core.folder.getMySearchesFolder();

	if (stockphoto.core.folder.isReadOnly(stockPhotoFolder))
	{
		return stockPhotoFolder + "/" + stockphoto.core.consts.ReadOnlyFolder;
	}

	// Replace the following illegal chars for file/dir name with '$' For space, replace with '_'
	// \ / : * ? " < > |

	var searchKeyword="";
	var i;
	for(i = 0; i < isearchKeyword.length; i++)
	{
		switch (isearchKeyword.charCodeAt(i))
		{
			case    32: // ' ' (0x20)
			case 12288: // CJK double-byte space (0x3000)
				searchKeyword += '_';
				break;
			case 165: // yen (0xA5)
			case 92:  // '\' (0x5C)
			case  47: // '/' (0x2F)
			case  58: // ':' (0x3A)
			case  42: // '*' (0x2A)
			case  63: // '?' (0x3F)
			case  34: // '"' (0x22)
			case  37: // '%' (0x25)
			case  60: // '<' (0x3C)
			case  62: // '>' (0x3E)
			case 124: // '|' (0x7C)
			case   9: // TAB (0x09)
				searchKeyword += '$';
				break;
			default:
				searchKeyword += isearchKeyword.charAt(i);
				break;
		}
	}

	var searchKeywordWithOptions;
    if ( searchKeyword.length > stockphoto.core.consts.MaxLengthOfKeywordInSearchFolderName )
    {
    	searchKeywordWithOptions = searchKeyword.slice( 0, stockphoto.core.consts.MaxLengthOfKeywordInSearchFolderName - 3 );
    	searchKeywordWithOptions += "...";
    }
    else
    {
		searchKeywordWithOptions = searchKeyword;
    }
	var oSettings = stockphoto.DL.NavBar.GetDrawerSettings(doc_id);
	
	//collection
	var collectionCount = 0;
	var iColl = 0;
	while( oSettings.collectionSelected[iColl] != undefined )
	{
	    if ( oSettings.collectionSelected[iColl] )
		    collectionCount++;
	    
		iColl++;
 	}
    
 	if ( collectionCount <= 2 )
  	{
   		iColl = 0;
	    while( oSettings.collectionSelected[iColl] != undefined )
	 	{
 	 	  	if ( oSettings.collectionSelected[iColl] )
  		  	{
  		  		var collectionName = stockphoto.providers.collections[iColl].CollectionDisplayName.Value;
  		  		var lengthToConsider = collectionName.toUpperCase().lastIndexOf(" BY ");
				if (lengthToConsider == -1)
				{
					//Not found
					lengthToConsider = collectionName.length;
				}
  		  		
	  	  		searchKeywordWithOptions += "_";
	  	  		var index = 0;
	  	  		while( index < lengthToConsider )
	  	  		{
	  	  			//replace " " with "_"
	  	  			if ( collectionName.charAt(index) == " " )
	  	  				searchKeywordWithOptions += "_";
	  	  			else
		  	  			searchKeywordWithOptions += collectionName.charAt(index);
		  	  			
		  	  		index++;
		  	  	}
  	 	 	}
  	  		
  	  		iColl++;
    	}
    }

	//media type
	if (!oSettings.colorFormat.color)
	{
		searchKeywordWithOptions += "_Ncl";
	}
	if (!oSettings.colorFormat.bw)
	{
		searchKeywordWithOptions += "_Nbw";
	}
	if (!oSettings.mediaType.photography)
	{
		searchKeywordWithOptions += "_Nph";
	}
	if (!oSettings.mediaType.illustration)
	{
		searchKeywordWithOptions += "_Nil";
	}
	if (!oSettings.mediaType.photoobject)
	{
		searchKeywordWithOptions += "_Nmi";
	}
	

	//orientation
	if (!oSettings.orientation.portrait)
	{
		searchKeywordWithOptions += "_Npor";
	}
	if (!oSettings.orientation.square)
	{
		searchKeywordWithOptions += "_Nsqr";
	}
	if (!oSettings.orientation.landscape)
	{
		searchKeywordWithOptions += "_Nlan";
	}
	if (!oSettings.orientation.panoramic)
	{
		searchKeywordWithOptions += "_Npan";
	}
	
	if ( ( collectionCount >= 3 ) && ( collectionCount < iColl ) )
	{
		searchKeywordWithOptions += "_" + collectionCount + "Colls";
	}

	var sk;
	if (searchKeywordWithOptions.length > stockphoto.core.consts.MaxLengthOfSearchFolderName)
	{
		sk = searchKeywordWithOptions.slice(0,stockphoto.core.consts.MaxLengthOfSearchFolderName);
		sk += "~";
	}
	else
	{
		sk = searchKeywordWithOptions;
	}

	var st00_newSearchFolder = stockPhotoFolder + "/" + sk;
	if (st00_newSearchFolder.length > stockphoto.core.consts.MaxLengthOfSearchFolderPath)
	{
		st00_newSearchFolder = st00_newSearchFolder.slice(0,stockphoto.core.consts.MaxLengthOfSearchFolderPath);
		st00_newSearchFolder += "~";
	}
	
	var st00_newSearchFolder1 = st00_newSearchFolder;
	var searchKeyword1 = sk;
	var myFolder;
	i = 0;

	if (stockphoto.st00_deleteOldOne)
	{
		// delete the old thumbnail
	}

	while (true)
	{
		var myFolder = Folder(st00_newSearchFolder1);
		if (!myFolder.exists)
		{
			myFolder.create();
			break;
		}
		else
		{
			i = i + 1;
			st00_newSearchFolder1 = st00_newSearchFolder + "_" + i;
			searchKeyword1 = sk + "_" + i;
		}
	}

	return  myFolder;
}

stockphoto.MiscUtils.search.validateFilterSelection = function (doc_id)
{
  var settings = stockphoto.search.settings[doc_id];
  
	// Validate collections filter
  if ((settings.collectionsAll == false)
        && (settings.collectionNames == ""))
  {
    // Abort the search
    return false;
  }
    
  // Validate other filters
  if ((settings.orientation.portrait == false) && (settings.orientation.square == false)
      && (settings.orientation.landscape == false) && (settings.orientation.panoramic == false))
  {
      // Abort the search
      return false;
  }
  
  if ((settings.colorFormat.color == false) && (settings.colorFormat.bw == false))
  {
      // Abort the search
      return false;
  }

  if ((settings.mediaType.portrait == false) && (settings.mediaType.illustration == false) 
            && (settings.mediaType.photoobject == false) )
  {
      // Abort the search
      return false;
  }

}

stockphoto.MiscUtils.file.partnerNameToFilenameCode = function(partnerName)
{
	var defaultFileCode = "ZZ"; // default bogus file code
	var pn2fc = {};

	var pnrx = /PartnerName.*Value=\"(.*)\"/;
	var fcrx = /PartnerFilenameCode.*Value=\"(.*)\"/;
	var partnersXml = stockphoto.core.init.partnersXMLfsObj.fsName;
	var pn = undefined;

	try
	{
		if( stockphoto.core.init.partnersXMLfsObj == undefined )
		{
			throw( "hopeless" );
		}
		var px = stockphoto.core.init.partnersXMLfsObj;
		px.open();
		while (!px.eof)
		{
			var line = px.readln();
			var mtch = pnrx.exec(line);
			if (mtch != null)
			{
				pn = RegExp.$1;
			}
			mtch = fcrx.exec(line);
			if (mtch != null && pn != undefined)
			{
				pn2fc[pn] = RegExp.$1;
				pn = undefined;
			}
		}
		px.close();
	}
	catch (e)
	{
		// Return the default, bogus file code.
		return defaultFileCode;
	}

	var fc = pn2fc[partnerName];

	if (fc == undefined)
	{
		fc = defaultFileCode;
	}

	return fc;
}


stockphoto.MiscUtils.core.partnerNameToPartnerDisplayName = function(sPartnerName)
{
	var sProviderName =sPartnerName; // In the worst return the same Provider Name as the partner name
	var iPartnersCount=0;
	var iIndex;
	
	if( stockphoto.core.BoxCar.AnalyzeXmlFileObj == undefined )
	{
		stockphoto.core.BoxCar.AnalyzeXmlFileObj = new stockphoto.core.BoxCar.AnalyzeXmlFile( stockphoto.core.init.partnersXMLfsObj, stockphoto.core.BoxCar.HTMLUtil.CheckKeys );
		if( ( stockphoto.core.BoxCar.AnalyzeXmlFileObj == undefined )||
		    ( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners == undefined ) )
		{
			// we failed to load partner's xml
			return;
		}
	}
	if ((stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners != undefined) 
		&& (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0] != undefined) 
		&& (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Partner != undefined))
	{
		iPartnersCount = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Partner.length;
	}
	
	for (iIndex=0; iIndex < iPartnersCount; iIndex++)
	{
		if ((stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Partner == undefined) 
			|| (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Partner[iIndex] == undefined))
		{
			break; //No point looking further
		}
		if ((stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Partner[iIndex].PartnerName != undefined)
			&& (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Partner[iIndex].PartnerName.Value != undefined))
		{
			if (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Partner[iIndex].PartnerName.Value == sPartnerName)
			{
				if ((stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Partner[iIndex].PartnerDisplayName != undefined)
					&& (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Partner[iIndex].PartnerDisplayName.Value != undefined)) 
				{
					sProviderName = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Partner[iIndex].PartnerDisplayName.Value
				}
				break;
			}
		}
	}
	
	return sProviderName;
}

stockphoto.MiscUtils.core.ShoppingCartX=function( doc_id ) 
{
	if( stockphoto._CheckBillingCountry( "st14_ShoppingCart", app.document ) != 2 )
	{
		return; // means the request is denied
	}
	var tempDoc;
	if( ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AddToCart ) )&&
	   ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_ShoppingCart ) ) &&
	   ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AlertBox ) ) ) 
	{
		var docWithShoppingCart = undefined;
		var docs = app.documents;
		var tempDoc;

		for (i = 0; i < docs.length; i++)
		{
			tempDoc = docs[i];
			if (tempDoc == undefined)
			{
				stockphoto.core.log.logString( 0, "[ERROR] Can not get document from doc_id :" + i );
				continue;
			}
			
			stockphoto.core.log.logString( 0, "[st14_ShoppingCartX] doc_id : " + tempDoc.id + " thumbnail.displayPath : " + stockphoto.core.util.getDisplayPath(tempDoc.thumbnail,""));
			if ((stockphoto.core.util.getDisplayPath(tempDoc.thumbnail,"").indexOf(stockphoto.core.consts.ShoppingCartName) > 0) &&  (tempDoc.thumbnail.displayMode == "web"))
			{
				docWithShoppingCart = tempDoc;
				break;
			}
			if (tempDoc.id == doc_id)
			{
				docWithShoppingCart = tempDoc;		
			}
		}
		
		if (docWithShoppingCart != undefined)
		{
			stockphoto.core.log.logString( 0, "[st14_ShoppingCartX] doc_id : " + docWithShoppingCart.id + " doc_id passed in : " + doc_id);
			
			// If it's minimized, bring back the document to life
            docWithShoppingCart.minimized = false;
            
			docWithShoppingCart.bringToFront();
			stockphoto.shoppingCart.shoppingCart_Body( true, docWithShoppingCart.id );
		}
		else
		{
			stockphoto.core.log.logString( 0, "[st14_ShoppingCartX] Can not find document for doc_id passed : " + doc_id);
		}
	}
}


stockphoto.MiscUtils.search.addFiltersToTerms = function( settings, terms )
{
    if (settings == undefined)
    {
        return terms;
    }
  
    var textLandscape = "Landscape";
	var textPanoramic = "Panoramic";
	var textSquare = "Square";
	var textPortrait = "Portrait";
	var textColor = "Color";
	var textBW = "BlackWhite";
	var textPhotography = "Photography";
	var textIllustration = "Illustration";
	var textPhotoObjects = "Masked";
	
	var sOrientation = "";
	var bOrientation = false;
	var sColorFormat = "";
	var bColorFormat = false;
	var sMediaType = "";
	var bMediaType = false;
	//added by aman
	var pMediaType = false;
	
	if (false == settings.orientation.portrait || false == settings.orientation.square ||
        false == settings.orientation.landscape || false == settings.orientation.panoramic)
  {
      if (settings.orientation.portrait == true)
      {
         sOrientation = textPortrait;
         bOrientation = true;
      }
      
      if (settings.orientation.square == true)
      {
        if (true == bOrientation)
        {
          sOrientation = sOrientation + " OR "; // must NOT be localized
        }
        
        sOrientation = sOrientation + textSquare;
        bOrientation = true;
      }
      
      if (settings.orientation.landscape == true)
      {
        if (true == bOrientation)
        {
          sOrientation = sOrientation + " OR "; // must NOT be localized
        }
        
        sOrientation = sOrientation + textLandscape;
        bOrientation = true;
      }
      
      if (settings.orientation.panoramic == true)
      {
        if (true == bOrientation)
        {
          sOrientation = sOrientation + " OR "; // must NOT be localized
        }
        
        sOrientation = sOrientation + textPanoramic;
        bOrientation = true;
      }    
  }
    
  terms.Orientation = sOrientation;
  
  
  if (false == settings.colorFormat.color || false == settings.colorFormat.bw)
  {
      if (settings.colorFormat.color == true)
      {
         sColorFormat = textColor;
         bColorFormat = true;
      }
      
      if (settings.colorFormat.bw == true)
      {
        if (true == bColorFormat)
        {
          sColorFormat = sColorFormat + " OR "; // must NOT be localized
        }
        
        sColorFormat = sColorFormat + textBW;
        bColorFormat = true;
      }
  }
  
  terms.ColorFormat = sColorFormat;
  
  var doc_id = 0;
  if (undefined != app.document && undefined != app.document.id)
  {
		doc_id = app.document.id;
  }
  
  stockphoto.search.searchMediaTypes[doc_id] = "";
  
  if ((false == settings.mediaType.photography) 
       ||(false == settings.mediaType.illustration))
  {
      if (settings.mediaType.photography == true)
      {
         sMediaType = textPhotography;
         bMediaType = true;
      }
      
      if (settings.mediaType.illustration == true)
      {
        if (true == bMediaType)
        {
          sMediaType = sMediaType + " OR "; // must NOT be localized
        }
        
        sMediaType = sMediaType + textIllustration;
        pMediaType = true;
      }
      
      stockphoto.search.searchMediaTypes[doc_id] = sMediaType;
  }
  else
  {
        stockphoto.search.searchMediaTypes[doc_id] = textPhotography + " OR " + textIllustration;
  }

  if (true == settings.mediaType.photoobject)
  {
		stockphoto.search.searchMediaTypes[doc_id] = stockphoto.core.util.appendSearchParam(stockphoto.search.searchMediaTypes[doc_id], textPhotoObjects);
  }

  terms.MediaTypes = sMediaType;
  
  if (false == settings.collectionsAll)
  {
    terms.Collections = settings.collectionNames;
  }
  
  return terms;
}



stockphoto.MiscUtils.search.simplifyKeyword = function( uKeyword , bEscape ) 
{
    // Refresh Search language operators, if it has changed
    stockphoto.search.refreshSearchLangLocale();
    
	//For the time being consider the following sequence of key words and operators
	//keyword1 operation keyword2
	var uSimplifiedKeyword = uKeyword;
	var arrayWord = [];
	var wordCount = 0;
	wordCount = stockphoto.MiscUtils.search.parseKeywords( uKeyword, arrayWord );
	if ( wordCount <= 1 )
	{
		//some error in parsing...or single keyword...no simplification required...return the current keyword
	}
	else
	{
		var set = new stockphoto.MiscUtils.search.orItemsSet();
		var error = false;
		stockphoto.MiscUtils.search.combineKeywords( set, arrayWord, wordCount );
		if ( set.universal )
			error = true;

		if ( error )
		{
			//pass the source as it is
		}
		else
		{
			var finalList = [];
			var finalListCount = 0;
			for ( var i=0; i<set.itemCount; i++ )
			{
				var myItem = 
				{
					Operation:		const_OpTypeOr,
					Type:			const_ItemTypeOperation,
				};
				finalListCount = stockphoto.MiscUtils.search.pushItem( myItem , finalList, finalListCount-1 )
				
				if ( !set.items[i].empty )
				{
					for ( var j=0; j<set.items[i].itemCount; j++ )
					{
						if ( set.items[i].items[j].bNot )
						{
							var myItem = 
							{
								Operation:		const_OpTypeNot,
								Type:			const_ItemTypeOperation,
							};
							finalListCount = stockphoto.MiscUtils.search.pushItem( myItem , finalList, finalListCount-1 )
						}
						else
						{
							var myItem = 
							{
								Operation:		const_OpTypeAnd,
								Type:			const_ItemTypeOperation,
							};
							finalListCount = stockphoto.MiscUtils.search.pushItem( myItem , finalList, finalListCount-1 )
						}
						
						var myItem = 
						{
							Keyword:		set.items[i].items[j].Keyword,
							Type:			const_ItemTypeKeyword,
						};
						finalListCount = stockphoto.MiscUtils.search.pushItem( myItem , finalList, finalListCount-1 )
					}
				}
			}
			
			//remove operations from the end
			while( (finalListCount > 0) && finalList[finalListCount-1].Type == const_ItemTypeOperation)
				finalListCount--;
			
			var uSimplifiedKeyword = "";
			for (var j=0; j<finalListCount; j++)
			{
				if ( finalList[j].Type == const_ItemTypeOperation )
				{
					switch( finalList[j].Operation )
					{
						case const_OpTypeNot:
							uSimplifiedKeyword += stockphoto.search.OP_NOT;
							break;

						case const_OpTypeOr:
							uSimplifiedKeyword += stockphoto.search.OP_OR;
							break;
						
						case const_OpTypeAnd:
							uSimplifiedKeyword += stockphoto.search.OP_AND;
							break;
					}
				}
				else
				{
					uSimplifiedKeyword += finalList[j].Keyword;
				}
				
				if (j != (finalListCount - 1))
				{
					uSimplifiedKeyword += " ";
				}
			}
			
			if ( uSimplifiedKeyword == "" )
			{
				//some problem..use the existing keyword..remove all brackets
				for (var j=0; j<wordCount; j++)
				{
					if ( arrayWord[j].Type == const_ItemTypeOperation )
					{
						switch( arrayWord[j].Operation )
						{
							case const_OpTypeNot:
								uSimplifiedKeyword += stockphoto.search.OP_NOT;
								break;

							case const_OpTypeOr:
								uSimplifiedKeyword += stockphoto.search.OP_OR;
								break;
						
							case const_OpTypeAnd:
								uSimplifiedKeyword += stockphoto.search.OP_AND;
								break;
						}
					}
					else
					{
						uSimplifiedKeyword += arrayWord[j].Keyword;
					}
				
					if (j != (wordCount - 1))
					{
						uSimplifiedKeyword += " ";
					}
				}
			}
		}
		
		set.clearAll();
		delete set;
	}
	
	return ( uSimplifiedKeyword );
}



stockphoto.MiscUtils.search.combineKeywords = function( set, arrayWord, wordCount )
{
	var pos = 0;
	var lastOp = -1;
	var keywordNot = false;
	while ( ( arrayWord[pos].Type == const_ItemTypeOperation ) 
        && ( arrayWord[pos].Operation != const_OpTypeNot ) )
	{
		pos++;
	}
	
	var curStateCmpWord = false;
	while (  pos < wordCount )
	{
		if ( arrayWord[pos].Type == const_ItemTypeOperation )
		{
			if ( arrayWord[pos].Operation == const_OpTypeNot )
			{
				keywordNot = true;
				
				if ( lastOp == -1 )
					lastOp = const_OpTypeAnd;
			}
			else
				lastOp = arrayWord[pos].Operation; 
		}
		else if ( arrayWord[pos].Type == const_ItemTypeKeyword )
		{
			switch( lastOp )
			{
				case const_OpTypeAnd:
					if ( ( set.itemCount > 0 ) && !set.universal )
					{
						if ( (!set.items[set.itemCount - 1].empty && !curStateCmpWord ) )
							set.items[set.itemCount - 1].addItem( arrayWord[pos].Keyword, keywordNot );
						else if ( curStateCmpWord )
						{
							if ( set.universal )
							{
								set.clearAll();
								set.addItem( arrayWord[pos].Keyword, keywordNot );
							}
							else
							{
								//we need to do the marging
								var bMatch = false;
								for ( var setPos=0; (setPos<set.itemCount) && !bMatch; setPos++)
								{
									if ( ( set.items[setPos].itemCount == 1) && 
										( set.items[setPos].items[0].Keyword == arrayWord[pos].Keyword) && 
										( set.items[setPos].items[0].bNot == keywordNot) )
									{
										bMatch = true;
									}
								}
								
								if ( bMatch )
								{
									//(A OR B) AND A => A
									set.clearAll();
									set.addItem( arrayWord[pos].Keyword, keywordNot );
								}
								else
								{
									for ( var setPos=0; setPos<set.itemCount; setPos++)
									{
										set.items[setPos].addItem( arrayWord[pos].Keyword, keywordNot );
									}
								}
							}
						}
					}
					else if ( !set.universal )
					{
						set.addItem( arrayWord[pos].Keyword, keywordNot );
					} 
					break;
				
				default:
				case const_OpTypeOr:
					if ( !set.universal )
						set.addItem( arrayWord[pos].Keyword, keywordNot );
					break;

			}
			lastOp = -1;
			curStateCmpWord = false;
		}
		else
		{
			//compound keyword
			var comWordList = [];
			var comWordListCount = stockphoto.MiscUtils.search.parseKeywords( arrayWord[pos].Keyword, comWordList );
			
			var wordList = [];
			wordListCount = 0;
			if ( keywordNot )
			{
				keywordNot = false;
				
				for ( var l=0; l<comWordListCount; l++ )
				{
					//NOT ( A AND B ) => NOT A OR NOT B
					//NOT ( A OR B ) => NOT A AND NOT B
					//NOT ( A NOT B ) => NOT A OR B
					if ( comWordList[l].Type == const_ItemTypeOperation )
					{
						switch( comWordList[l].Operation )
						{
							case const_OpTypeOr:
								comWordList[l].Operation = const_OpTypeAnd;
								wordList[wordListCount++] = comWordList[l];
								
								var myItem = 
								{
									Type:			const_ItemTypeOperation,
									Operation:		const_OpTypeNot
								};
								wordList[wordListCount++] = myItem;
								break;
							case const_OpTypeAnd:
								comWordList[l].Operation = const_OpTypeOr;
								wordList[wordListCount++] = comWordList[l];
								
								var myItem = 
								{
									Type:			const_ItemTypeOperation,
									Operation:		const_OpTypeNot
								};
								wordList[wordListCount++] = myItem;
								break;
							case const_OpTypeNot:
								comWordList[l].Operation = const_OpTypeOr;
								wordList[wordListCount++] = comWordList[l];
								break;
						}
					}
					else
					{
						if (l == 0 )		//first keyword
						{
							var myItem = 
							{
								Type:			const_ItemTypeOperation,
								Operation:		const_OpTypeNot
							};
							wordList[wordListCount++] = myItem;
						}
								
						wordList[wordListCount++] = comWordList[l];
					}
				}
			}
			else
			{
				for ( var l=0; l<comWordListCount; l++ )
				{
					wordList[l] = comWordList[l];
				}
				wordListCount = comWordListCount;
			}

			switch( lastOp )
			{
				case const_OpTypeAnd:
					if ( set.universal )
					{
						set.clearAll();
						stockphoto.MiscUtils.search.combineKeywords( set, wordList, wordListCount );
					}
					else
					{
						var itemsToCombine = new stockphoto.MiscUtils.search.orItemsSet();
						stockphoto.MiscUtils.search.combineKeywords( itemsToCombine, wordList, wordListCount );
				
						if ( !itemsToCombine.universal && ( itemsToCombine.itemCount > 0 ) )
						{
							var start = 0;
							var end = set.itemCount - 1;
							
							//we should leave multiplication of the first element for the time being
							//it should be done online
							for (var i=0; i<itemsToCombine.itemCount; i++ )
							{
								var bMatch = false;
								for ( var setPos=start; (setPos<=end) && !bMatch; setPos++)
								{
									if ( set.items[setPos].isEqualTo( itemsToCombine.items[i] ) )
									{
										bMatch = true;
									}
								}
								
								if ( bMatch )
								{
									//(A OR B) AND A => A
									set.addAndItemSet( itemsToCombine.items[i] );
								}
								else
								{
									for ( var setPos=start; setPos<=end; setPos++)
									{
										var bRet = set.addAndItemSet( set.items[setPos] );
										
										if (bRet)
										{
											for ( var j=0; j<itemsToCombine.items[i].itemCount; j++ )
												set.items[set.itemCount-1].addItem( itemsToCombine.items[i].items[j].Keyword, itemsToCombine.items[i].items[j].bNot );
										}
									}
								}
							}
							
							//invalidate all the elements from start to end
							for ( var setPos=start; (setPos<=end) && !bMatch; setPos++)
							{
								set.items[setPos].empty = true;
							}
						}
						itemsToCombine.clearAll();
						delete itemsToCombine;
					}
					break;
			
				default:
				case const_OpTypeOr:
					if ( !set.universal )
						stockphoto.MiscUtils.search.combineKeywords( set, wordList, wordListCount );
					break;
			}

			lastOp = -1;
			curStateCmpWord = true;
		}

		if ( ( arrayWord[pos].Type == const_ItemTypeOperation ) 
                && ( arrayWord[pos].Operation == const_OpTypeNot ) )
			keywordNot = true;
		else
			keywordNot = false;
			
		pos++;
	}
	
	//now we have the complete set..remove the reduendent one
	if ( !set.universal )
	{
		for( var i=0; i<set.itemCount; i++ )
		{
			if ( !set.items[i].empty )
			{
				for ( var j=i+1; j<set.itemCount; j++ )
				{
					if ( !set.items[j].empty )
					{
						if ( set.items[i].subSetOf( set.items[j] ) )
						{
							//A OR (A AND B)=>A
							set.items[j].empty = true;
						}
					}
				}
			}
		}
	}
}

stockphoto.MiscUtils.search.parseKeywords = function( uKeyword, outWordList )
{
	var i=0;
	var outWordCount = 0;
	var done = false;
	var wordProcessing = false;
	var quoteProcessing = false;
	var currentWord = "";
	var currentCompoundWord = "";
	var compoundKeywordLevel = 0;
	while( !done )
	{
		//start of a new word....ship spaces
		if ( uKeyword[i] == undefined )
		{
			if (wordProcessing)
			{
				//end the current word			
				 outWordCount = stockphoto.MiscUtils.search.pushItem(stockphoto.MiscUtils.search.processWord(currentWord), outWordList, outWordCount-1 );
			}
			
			done = true;
		}
		else if ( ( uKeyword[i] == ' ') && !quoteProcessing && !compoundKeywordLevel)
		{
			if (!wordProcessing)
			{
				//skip it
			}
			else
			{
				//end the current word			
				 outWordCount = stockphoto.MiscUtils.search.pushItem(stockphoto.MiscUtils.search.processWord( currentWord ), outWordList, outWordCount-1 );
				
				//Start a new one
				currentWord = "";
			}
		}
		else if ( ( uKeyword[i] == "(") && !quoteProcessing )
		{
			if ( (compoundKeywordLevel == 0 ) && wordProcessing)
			{
				//end the current word			
				 outWordCount = stockphoto.MiscUtils.search.pushItem(stockphoto.MiscUtils.search.processWord( currentWord ), outWordList, outWordCount-1 );
				
				//Start a new one
				currentWord = "";
				currentCompoundWord = "";
			}
			else if ( (compoundKeywordLevel > 0 ) && wordProcessing)
			{
				currentCompoundWord += uKeyword[i];
			}

			currentWord += uKeyword[i];
			compoundKeywordLevel++;
		}
		else if ( ( uKeyword[i] == ")" ) && !quoteProcessing )
		{
			compoundKeywordLevel--;
			currentWord += uKeyword[i];
			
			if ( compoundKeywordLevel == 0 )
			{
				//end the existing word
				var myItem = 
				{
					Keyword: 		currentCompoundWord,
					Type:			const_ItemTypeCompKeyword
				};
					
				outWordCount = stockphoto.MiscUtils.search.pushItem( myItem, outWordList, outWordCount-1 );
				
				//Start a new one
				currentWord = "";
				currentCompoundWord = "";
			}
			else if ( (compoundKeywordLevel > 0 ) && wordProcessing)
			{
				currentCompoundWord += uKeyword[i];
			}
		}
		else 
		{
			if ( uKeyword[i] == '"' )
			{
				quoteProcessing = !quoteProcessing;
			}
			
			currentWord += uKeyword[i];
			if (compoundKeywordLevel)
			{
				currentCompoundWord += uKeyword[i];
			}
		}
		
		wordProcessing = ( currentWord == "" ) ? false : true;
		
		i++;
	}
	
	return outWordCount;
}

stockphoto.MiscUtils.search.pushItem = function( item , itemList, curPosition )
{
	var newPos = curPosition;
	
	if ( item.Type == const_ItemTypeOperation )
	{
		if ( ( newPos >= 0) && ( itemList[ newPos ].Type == const_ItemTypeOperation ) )
		{
			if ( ( itemList[ newPos ].Operation == const_OpTypeAnd )
                     && ( item.Operation == const_OpTypeAnd ) )
			{
				//A AND AND B => A AND B
				//ignore
			}
			else if ( ( itemList[ newPos ].Operation == const_OpTypeAnd ) 
                    && ( item.Operation == const_OpTypeOr ) )
			{
				//A AND OR B...actually error..let's make it A OR B
				itemList[ newPos ].Operation = const_OpTypeOr;
			}
			else if ( ( itemList[ newPos ].Operation == const_OpTypeAnd )
                     && ( item.Operation == const_OpTypeNot ) )
			{
				//A AND NOT B => A NOT B
				itemList[ newPos ].Operation = const_OpTypeNot
			}
			
			else if ( ( itemList[ newPos ].Operation == const_OpTypeOr ) 
                    && ( item.Operation == const_OpTypeAnd ) )
			{
				//A OR AND B => A OR B
				//ignore
			}
			else if ( ( itemList[ newPos ].Operation == const_OpTypeOr )
                    && ( item.Operation == const_OpTypeOr ) )
			{
				//A OR OR B => A OR B
				//ignore
			}
			else if ( ( itemList[ newPos ].Operation == const_OpTypeOr )
                    && ( item.Operation == const_OpTypeNot ) )
			{
				//A OR NOT B
				var myItem = 
				{
					Operation:		const_OpTypeNot,
					Type:			const_ItemTypeOperation,
				};
				newPos++;
				itemList[ newPos ] = myItem;
			}
			else if ( ( itemList[ newPos ].Operation == const_OpTypeNot )
                    && ( item.Operation == const_OpTypeAnd ) )
			{
				//A NOT AND B => A NOT B
				//ignore
			}
			else if ( ( itemList[ newPos ].Operation == const_OpTypeNot )
                    && ( item.Operation == const_OpTypeOr ) )
			{
				//A NOT OR B..error..consider A NOT B
				//ignore
			}
			else if ( ( itemList[ newPos ].Operation == const_OpTypeNot )
                    && ( item.Operation == const_OpTypeNot ) )
			{
				//A NOT NOT B => A AND B
				itemList[ newPos ].Operation = const_OpTypeAnd
			}
		}
		else if ( ( newPos < 0) && ( item.Operation != const_OpTypeNot ) )
		{
			//ignore
		}
		else
		{
			var myItem = 
			{
				Operation:		item.Operation,
				Type:			const_ItemTypeOperation,
			};
			newPos++;
			itemList[ newPos ] = myItem;
		}
	}
	else
	{
		//keyword or compound keyword
		if ( ( newPos >= 0) && ( itemList[ newPos ].Type != const_ItemTypeOperation ) )
		{
			itemList[ newPos ].Keyword += " " + item.Keyword;
		}
		else
		{
			var myItem = 
			{
	 		 	Keyword: 		item.Keyword,
				Operation:		item.Operation,
				Type:			item.Type,
			};
			newPos ++;
			itemList[newPos] = myItem;
		}
	}
	
	return (newPos+1);
}

stockphoto.MiscUtils.search.andItemsSet = function()
{
	this.items = [];
	this.itemCount = 0;
	this.empty = false;

	this.addItem = function( keyword, bNot )
	{
		if ( this.empty )
			return;
		
		if ( ( keyword == undefined) || ( bNot == undefined ) || ( keyword == "" ) )
			return;
			
		var i = 0;
		var bFound = false;
		while( !bFound && ( i < this.itemCount ) )
		{
			if ( this.items[i].Keyword == keyword )
			{
				bFound = true;
				
				if ( this.items[i].bNot != bNot )
					this.empty = true;
			}
			i++;
		}
		
		if ( !bFound )
		{
			var keywordItem =
			{
				Keyword: keyword,
				bNot: bNot
			};
			this.items[this.itemCount++] = keywordItem;
		}
	}

	this.isEqualTo = function( anotherAndItem )
	{
		var bEqual = false;
		
		if ( ( this.empty || !this.itemCount ) && 						
			( anotherAndItem.empty || !anotherAndItem.itemCount ) )		//both are empty	?
			bEqual = true;
		else if ( ( this.empty || !this.itemCount ) &&
			( !anotherAndItem.empty && anotherAndItem.itemCount ) )		//this empty, anotherAndItem non-empty
			bEqual = false;
		else if ( ( !this.empty && this.itemCount ) && 
			( anotherAndItem.empty || !anotherAndItem.itemCount ) )		//this non-empty, anotherAndItem empty
			bEqual = false;
		else if ( ( this.itemCount == anotherAndItem.itemCount ) && 	//both the sets are non-empty
			this.subSetOf( anotherAndItem ) )
			bEqual = true;
		
		return bEqual;
	}

	this.subSetOf = function( anotherAndItem )
	{
		var bSubSet = true;
		if ( this.empty || !this.itemCount ) 
			bSubSet = true;
		else if ( anotherAndItem.empty || !anotherAndItem.itemCount )
			bSubSet = false;
		else
		{
			for (var i=0; (i<this.itemCount) && bSubSet; i++)
			{
				var bMatch = false;
				for(var j=0; (j<anotherAndItem.itemCount) && !bMatch; j++)
				{
					if ( ( anotherAndItem.items[j].Keyword == this.items[i].Keyword ) &&
						( anotherAndItem.items[j].bNot == this.items[i].bNot ) )
					{
						bMatch = true;
					}
				}
				
				if (!bMatch)
					bSubSet = false;
			}
		}
		return bSubSet;
	}

	this.clearAll = function()
	{
		this.itemCount = 0;
		this.empty = false;
	}
}

stockphoto.MiscUtils.search.orItemsSet = function()
{
	this.items = [];
	this.itemCount = 0;
	this.universal = false;

	this.addItem = function( keyword, bNot )
	{
		if ( this.universal )
			return;
			
		if ( ( keyword == undefined) || ( bNot == undefined ) || ( keyword == "" ) )
			return;

		var i = 0;
		var bFound = false;
		while( i < this.itemCount )
		{
			if ( ( this.items[i].itemCount == 1 ) && ( this.items[i].items[0].Keyword == keyword ) )
			{
				bFound == true;
				if ( this.items[i].items[0].bNot != bNot )
					this.universal = true;
			}
			else if ( ( this.items[i].itemCount > 1 ) && !this.items[i].empty )
			{
				var bMatch = false;
				var j = 0;
				while( !bMatch && ( j < this.items[i].itemCount ) )
				{
					if ( ( this.items[i].items[j].Keyword == keyword) && ( this.items[i].items[j].bNot == bNot ) )
					{
						bMatch = true;
						this.items[i].empty = true;
					}
					
					j++;
				}
			}
			
			i++;
		}
		if ( !bFound )
		{
			this.items[this.itemCount] = new stockphoto.MiscUtils.search.andItemsSet();
			this.items[this.itemCount].addItem( keyword, bNot );
			this.itemCount++;
		}
	}

	this.addAndItemSet = function( itemSet )
	{
		var bRet = false;
		if ( itemSet.empty || ( itemSet.itemCount == 0 ) )
			return bRet;
		
		bRet = true;
		this.items[this.itemCount] = new stockphoto.MiscUtils.search.andItemsSet();

		for (var i=0; i<itemSet.itemCount; i++)
		{
			this.items[this.itemCount].addItem( itemSet.items[i].Keyword, itemSet.items[i].bNot );
		}

		this.itemCount++;	
		
		return bRet;
	}

	this.clearAll = function()
	{
		for (var i=0; i<this.itemCount; i++)
		{
			this.items[i].clearAll();
			
			delete this.items[i];
			this.items[i] = undefined;
		}
		
		this.itemCount = 0;
		this.universal = false;
	}
}

stockphoto.MiscUtils.search.processWord = function( uword )
{
	var myItem = eval(item.toSource());
	var word = uword.toUpperCase();
	
	if ( word == stockphoto.search.OP_AND )
	{
		myItem.Operation = const_OpTypeAnd;
		myItem.Type = const_ItemTypeOperation;
	}
	else if ( word == stockphoto.search.OP_OR )
	{
		myItem.Operation = const_OpTypeOr;
		myItem.Type = const_ItemTypeOperation;
	}
	else if ( word == stockphoto.search.OP_NOT )
	{
		myItem.Operation = const_OpTypeNot;
		myItem.Type = const_ItemTypeOperation;
	}
	else
	{
		myItem.Keyword = uword;
		myItem.Type = const_ItemTypeKeyword;
	}
	
	return ( myItem );
}

stockphoto.MiscUtils.file.convertToPOSIXCompliant = function(name, toHex, retainSpaces)
{
	// POSIX compliant chars: 0-9, a-z, A-Z, '.', '_', and '-'

	var newname = "";

    if (name == undefined)
    {
        return newname;
    }
    
	// For each char of the given name, if the char code is
	// 0x0000~0x00FF: make it POSIX compilant
	// 0x0100~: convert to char or its hex value if toHex is true

	var len = name.length;

	for (var i = 0; i < len; i++)
	{
		var uc = name.charCodeAt(i);

		if (uc < 0x0100)
		{
			var nuc = 0x005F; // Default '_'

			if ((uc == 0x002D) || (uc == 0x002E))		// '-' or '.'
			{
				nuc = uc;
			}
			else if ((0x0030 <= uc) && (uc <= 0x0039))	// 0-9
			{
				nuc = uc;
			}
			else if ((0x0041 <= uc) && (uc <= 0x005A))	// A-Z
			{
				nuc = uc;
			}
			else if ((0x0061 <= uc) && (uc <= 0x007A))	// a-z
			{
				nuc = uc;
			}
			else if ((retainSpaces == true) && (uc == 0x0020)) // ' '
			{
                nuc = uc;
            }

			newname += String.fromCharCode(nuc);
		}
		else
		{
			if (toHex)
			{
				newname += uc.toString(16);
			}
			else
			{
				newname += String.fromCharCode(uc);
			}
		}
	}

	return newname;
}
