window.onError = function(){}
if( !searchBoxAtt )  var searchBoxAtt = {
											selectedGlobalFilter: "",
											typingTimeout: null
										
										};
 								
function SearchBox()
{
	this.sb_searchBox = null;
	this.sb_typeingTimeout ;
	this.sb_searchTerm = "";
	this.sb_selectedSuggestionIndex = null;
	this.sb_suggestionsPanel = null;
	this.sb_oldSearchTerm = null;
	this.sb_selectedSuggestionColor = "#EDF4C6";
	this.sb_notSelectedSuggestionColor = "white";
	this.keyNavigate = keyNavigate;
	this.setSelected = setSelected;
	this.unsetSelected = unsetSelected;
	this.getSuggestions = getSuggestions;
	this.findSuggestions = findSuggestions;
	this.showSuggestions = showSuggestions;
	this.showSuggestionPanel = showSuggestionPanel;
	this.hideSuggestionsPanel = hideSuggestionPanel;
	this.clearSuggestionsPanel = clearSuggestionsPanel;
	this.addSuggestionToSearch = addSuggestionToSearch;
	this.closeSuggestionPanel = closeSuggestionPanel;
	this.closeSuggestionPanelDelay = closeSuggestionPanelDelay;
}
var suggestPanelTimer = null;
var searchBoxController = {activeSearchBox:null};
var mainSearchBox = new SearchBox();
var discoverySearchBox = new SearchBox();
var contentsSearchBox = new SearchBox();
var favoriteSearchBox = new SearchBox();
var searchResponseObject = null;
var searchTypeDropState = 1;
var suggestionsMap = null;
var searchBoxHasFocus = false;


// IE selection range holder
var currentSelectionRange = null;

var filterName = null;
var filterId = null;
var collageSort = null;
var globalFilterType = null;
var prevGlobalFilterType = null;
var findSimilarTo = null;
var searchLiterals = new Array();

var searchBoxData = [];
function SearchBoxDataEntry()
{
	this.displayName = null;
	this.start = 0;
	this.end = 0;
	this.itemId = null;
	this.type = null;
}

var newSearch = false;
var searchResultFuncs = {};
//========================================
function searchElement(title,type,id,url)
{
	
	this.title = title;
	this.type = type;
	this.id = id;
	this.url = url;
}
var affilateFilters = {netflix: 'Netflix', cookieDelimiter:'_'};
var SearchBean = {searchFilter:null, userSearchPhrase:null, htmlCode:null};
var SearchFilter = {tasteFilter: null, globalFilter:null, searchFilter:null, searchType:1};
var TasteFilter = {obscure:-1, pace:-1, realistic:-1, serious:-1};
var suggestFilter = {contentTypeFilter: null, onlineContentFilter: false, dvdContentFilter: false, theaterContentFilter: false }
//===========================================
var searchFuncs = {};

var SEARCH_WELCOME = "Enter plots, moods, titles, people and more";
var SEARCH_MOVIES = "Search movies";
var SEARCH_DVD = "Search by what's on DVD";
var SEARCH_TV = "Search TV shows";
var SEARCH_SHORTS = "Search short films";
var SEARCH_ONLINE = "Search by what's watchable online";
var SEARCH_TITLES = "Enter Titles";
var FREE_SEARCH_DELIMITER = "*";


/* REMOVED - new search box
window.onkeydown = submitSearchForm;


function submitSearchForm(event)
{
	//try{
	var key = getKeyboard(event);
	if(key ==13 && searchBoxController.activeSearchBox.sb_searchBox.id.toLowerCase().indexOf('discovery')>-1)
	{
		findSimilarClick(document.getElementById('discoveryBox').value);
	}
	else
	 if(key ==13 && searchBoxController.activeSearchBox.sb_searchBox.id.indexOf('searchInput')>-1)
	{
		doSearch();
		
	}
//	}catch(e)
//	{
//	
//		alert(e);
//	}
}
*/

function initSearchBox(pageName)
{
	searchBoxAtt.selectedGlobalFilter =  document.getElementById( getCookieValue('gfilter') );
	if( searchBoxAtt.selectedGlobalFilter == '') searchBoxAtt.selectedGlobalFilter = "all";
	
	
	mainSearchBox.sb_searchBox = document.getElementById('searchInput');
	discoverySearchBox.sb_searchBox = document.getElementById('discoveryBox');
	favoriteSearchBox.sb_searchBox = document.getElementById('favoriteBox');
	
	
	mainSearchBox.sb_suggestionsPanel = document.getElementById('suggestionsPanel');
	discoverySearchBox.sb_suggestionsPanel = document.getElementById('discoverySuggestionsPanel');
	
	contentsSearchBox.sb_suggestionsPanel = document.getElementById('suggestionsPanel');
	favoriteSearchBox.sb_suggestionsPanel = document.getElementById('discoverySuggestionsPanel');
	
	
	
	try{
		
		discoverySearchBox.sb_suggestionsPanel.style.display = "none";
		discoverySearchBox.findSuggestions = findTitleSuggestions;
	
	}
	catch(e){
		/* in discovery page. no discovery search box */
		
	}
	try{
	
		mainSearchBox.sb_suggestionsPanel.style.left = getPosX(document.getElementById('searchboxContainer')) + 5 + "px";
		mainSearchBox.sb_suggestionsPanel.style.top  = getPosY(document.getElementById('searchboxContainer')) + 34 + "px";
	}
	catch(e){
		/* not home or discovery*/
		
	}
	try{
		discoverySearchBox.sb_suggestionsPanel.style.left = getPosX(document.getElementById('discoveryBox')) + "px";
		discoverySearchBox.sb_suggestionsPanel.style.top  = getPosY(document.getElementById('discoveryBox')) + 20 + "px";
	}
	catch(e){
		/* not home */
		
	}
	try{
		contentsSearchBox.sb_suggestionsPanel.style.left = getPosX(document.getElementById('contentSearchbox')) + "px";
		contentsSearchBox.sb_suggestionsPanel.style.top  = getPosY(document.getElementById('contentSearchbox')) + 37 + "px";
	}
	catch(e){
		
		/* in home or discovery*/
	}
	try{
//		favoriteSearchBox.sb_suggestionsPanel.style.left = getPosX(document.getElementById('favoriteBox')) + "px";
//		favoriteSearchBox.sb_suggestionsPanel.style.top  = getPosY(document.getElementById('favoriteBox')) + 20 + "px";
	}
	catch(e){
		
		/* in home or discovery*/
	}
	
}
function keyNavigate(e,inputObj)
{
	if( !searchBoxController.activeSearchBox.sb_suggestionsPanel ) return;
	searchBoxController.activeSearchBox = this;
//	if(searchBoxController.activeSearchBox.sb_searchBox == null)
//	{
//		searchBoxController.activeSearchBox.sb_searchBox = inputObj;		
//	}
	searchBoxController.activeSearchBox.sb_searchBox = inputObj;	
	var previousIndex = null;
	var key = getKeyboard(e)
	if(key == 40 || key == 38 || key==13) //down/up arrow
	{
		if(searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes.length == 0) return true;
		
		if(key==40)
		{	
			if(searchBoxController.activeSearchBox.sb_selectedSuggestionIndex == null)
				searchBoxController.activeSearchBox.sb_selectedSuggestionIndex = 0;
			else
			{	
				previousIndex = searchBoxController.activeSearchBox.sb_selectedSuggestionIndex;
				searchBoxController.activeSearchBox.sb_selectedSuggestionIndex = (searchBoxController.activeSearchBox.sb_selectedSuggestionIndex + 1)%searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes.length;
				//previousIndex = (sb_selectedSuggestionIndex -1)%sb_suggestionsPanel.childNodes.length;
			}
		}
		else if(key==38)
		{
			if(searchBoxController.activeSearchBox.sb_selectedSuggestionIndex == null)
				searchBoxController.activeSearchBox.sb_selectedSuggestionIndex = searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes.length-1;
			else
			{
				previousIndex = searchBoxController.activeSearchBox.sb_selectedSuggestionIndex;
				if(previousIndex ==0) searchBoxController.activeSearchBox.sb_selectedSuggestionIndex = searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes.length;
				searchBoxController.activeSearchBox.sb_selectedSuggestionIndex = (searchBoxController.activeSearchBox.sb_selectedSuggestionIndex - 1)%searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes.length;
				//previousIndex = (sb_selectedSuggestionIndex +1)%sb_suggestionsPanel.childNodes.length;	
			}
			
		}
		else if(key == 13)
		{
			
			addSuggestionToSearchBox();
			
			if(needToShowDiscovery() == true) showDiscoveryButton();
			else hideDiscoveryButton();
			
			return false;
		}
		
		
		searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes[searchBoxController.activeSearchBox.sb_selectedSuggestionIndex].style.backgroundColor = searchBoxController.activeSearchBox.sb_selectedSuggestionColor;
		if(previousIndex != null)
			searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes[previousIndex].style.backgroundColor = searchBoxController.activeSearchBox.sb_notSelectedSuggestionColor;
	
				
	}
	else if(key == 46 && inputObj.value == "")
		document.getElementById('txt').removeChild(inputObj);
	
}
function addSuggestionToSearchBox()
{
	
	if(searchBoxController.activeSearchBox.sb_selectedSuggestionIndex != null)
	{
		var searchInputCtrl = document.getElementById( "searchInput" );

		if ( searchInputCtrl.value.match(/^like:/i) && searchBoxData.length == 0 )
		{
			searchInputCtrl.value = "Like: ";
			var seletedDiv = searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes[searchBoxController.activeSearchBox.sb_selectedSuggestionIndex];
			searchBoxController.activeSearchBox.addSuggestionToSearch(seletedDiv);			
		}
		else
		{
			// First, find where the last search-term (not user typed) ends.
			var lastTermEnd = 0;
			for ( var i = 0; i < searchBoxData.length; i++ )
			{
				if ( searchBoxData[i].end > lastTermEnd )
				{
					lastTermEnd = searchBoxData[i].end;
				}
			}
	
			// get the last user typed text.
			var userEnteredStr = null;
			if ( searchBoxData.length > 0 )
			{
				userEnteredStr = searchInputCtrl.value.substring( lastTermEnd + 1, searchInputCtrl.value.length );
			}
			else
			{
				userEnteredStr = searchInputCtrl.value;
			}
			// delete the text from the input
			var searchBoxInput = searchBoxController.activeSearchBox.sb_searchBox;
			if ( document.all )
			{
				searchBoxInput.value = searchBoxInput.value.substring( 0, searchBoxInput.value.length - userEnteredStr.length );
				searchBoxInput.focus();
				currentSelectionRange = document.selection.createRange();
				
			}
			else // gecko
			{
				searchBoxInput.value = searchBoxInput.value.substring( 0, searchBoxInput.value.length - userEnteredStr.length );
				
			}
			searchBoxInput.style.color = "black";		
			
			var seletedDiv = searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes[searchBoxController.activeSearchBox.sb_selectedSuggestionIndex];
			searchBoxController.activeSearchBox.addSuggestionToSearch(seletedDiv);
		}
	
//		if(searchBoxController.activeSearchBox.sb_searchBox.id=='searchInput')
//			removeTheDiv(searchBoxController.activeSearchBox.sb_searchBox);

	}
	
	searchBoxController.activeSearchBox.closeSuggestionPanelDelay();
}

/**
 * obj - the suggestion div
 * 
 */
function setSelected(obj)
{
	for(var i=0;i<searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes.length; i++)
	{
		if(searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes[i] == obj) break;
	}
	/* unmark current highlighted row */
	if(searchBoxController.activeSearchBox.sb_selectedSuggestionIndex != null)
		searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes[searchBoxController.activeSearchBox.sb_selectedSuggestionIndex].style.backgroundColor = searchBoxController.activeSearchBox.sb_notSelectedSuggestionColor;
	
	/* highlight the current row */
	searchBoxController.activeSearchBox.sb_selectedSuggestionIndex = i;
	obj.style.backgroundColor = searchBoxController.activeSearchBox.sb_selectedSuggestionColor;
	
}
function unsetSelected(obj)
{
	obj.style.backgroundColor = searchBoxController.activeSearchBox.sb_selectedSuggestionColor;
}



function getSuggestions(e)
{
	activeSearchBox = searchBoxController.activeSearchBox;
	window.clearTimeout(searchBoxController.activeSearchBox.sb_typeingTimeout);
	var searchTerm = searchBoxController.activeSearchBox.sb_searchBox.value;
	
	/* if there is nothing to search for */
	if(searchTerm == "" || getKeyboard(e) == 13) 
	{
		searchBoxController.activeSearchBox.clearSuggestionsPanel();
		searchBoxController.activeSearchBox.hideSuggestionsPanel();
		return;
	}
	
	/* if nothing was change since last search */
	if(searchTerm == searchBoxController.activeSearchBox.sb_oldSearchTerm)
	{
		return;
	}
	
	searchBoxController.activeSearchBox.sb_oldSearchTerm = searchTerm;
	
	searchBoxController.activeSearchBox.sb_searchTerm = searchTerm;
	if(searchBoxController.activeSearchBox.sb_searchTerm.length < 3) 
	{
		searchBoxController.activeSearchBox.closeSuggestionPanel();
		return;
	}
	searchBoxController.activeSearchBox.sb_typeingTimeout = window.setTimeout("searchBoxController.activeSearchBox.findSuggestions()",500);
}

function findSuggestions()
{
	searchBoxController.activeSearchBox.sb_selectedSuggestionIndex = null;
	//suggestFilter.contentTypeFilter = globalFilterType == 'all' ? null : globalFilterType;
	AjaxController.findSuggestionsWithFilters( searchBoxController.activeSearchBox.sb_searchTerm, suggestFilter, searchBoxController.activeSearchBox.showSuggestions );
}


function findTitleSuggestions()
{
	searchBoxController.activeSearchBox.sb_selectedSuggestionIndex = null;
	//suggestFilter.contentTypeFilter = globalFilterType == 'all' ? null : globalFilterType;
	AjaxController.findTitleSuggestions(searchBoxController.activeSearchBox.sb_searchTerm, suggestFilter, searchBoxController.activeSearchBox.showSuggestions);
}

function showSuggestions(suggestResponse)
{
	suggestionsMap = [];
	var numSuggstions = suggestResponse.results.length;
	var results =  suggestResponse.results;

	/* if there are no results remove current results from the panel. keep the panel visible */
	if(results.length == 0) 
	{
		//searchBoxController.activeSearchBox.clearSuggestionsPanel();
		searchBoxController.activeSearchBox.closeSuggestionPanel();
		return;
	}

	var sugArea = searchBoxController.activeSearchBox.sb_suggestionsPanel;
	
	/* clear the suggestion area */
	searchBoxController.activeSearchBox.clearSuggestionsPanel();
	
	// Check whether this is a title for a similarity search
	var isSimilarityTitleSearch = false;
	var inputTxt = document.getElementById( "searchInput" ).value;
	var regExp = new RegExp( "^like:\s*" + suggestResponse.criteria.searchPhrase, "i" );
	if ( inputTxt.match( regExp ) )
	{
		isSimilarityTitleSearch = true;
	}
	
	/* populate the suggestion area */
	for(var i=0;i<results.length;i++)
	{
		var year = results[i].year;
		var name = results[i].name;
		var id = results[i].id;
		var entityType = results[i].entityType;
		
		switch( results[i].entityType )
		{
			case "Title":
				if ( isSimilarityTitleSearch )
				{
					suggestionsMap[id + "_" + name] = "TS";
				}
				else
				{
					suggestionsMap[id + "_" + name] = "T";
				}
				break;
			case "Person":
				suggestionsMap[id + "_" + name] = "P";
				break;
			case "Category":
				suggestionsMap[id + "_" + name] = "G";
				entityType = results[i].categoryType;
				break;
			case "CategorySynonym":
				suggestionsMap[id + "_" + name] = "GS";
				entityType = results[i].categoryType;
				break;
		}
		
		if ( document.all )
		{
			var suggestion = document.createElement( "<DIV onmousedown='suggestPanelTimer = -1;' onclick='addSuggestionToSearchBox(); suggestPanelTimer = null; searchBoxController.activeSearchBox.closeSuggestionPanel(); doSearch();' onmouseover='setSelected(this);' class='suggestionDiv'></DIV>" );
		}
		else
		{
	//		var anchor = document.createElement("A");
	//		anchor.setAttributeNode(createAttribute("href","javascript:addSuggestionToSearchBox();"));
	//		anchor.setAttributeNode(createAttribute("style","text-decoration: none;"));
			var suggestion = document.createElement("DIV");
			// Bug fix - Nimrod - 18/6/08 Since search box blur event closes suggestion box, 
			// need to cancel the event before that happens. After that the click event will close the box.
			var attr = document.createAttribute( "onmousedown" );
			attr.nodeValue = "suggestPanelTimer = -1;";
			suggestion.setAttributeNode( attr );
			
			//add onclick event
			attr = document.createAttribute("onclick");
			//attr.nodeValue = "addSuggestionToSearch(this);"
			attr.nodeValue = "addSuggestionToSearchBox(); suggestPanelTimer = null; searchBoxController.activeSearchBox.closeSuggestionPanel(); doSearch();";
			suggestion.setAttributeNode(attr);
			
			//add on mouseover event
			attr = document.createAttribute("onmouseover");
			attr.nodeValue = "setSelected(this);"
			suggestion.setAttributeNode(attr);
			
			suggestion.setAttributeNode(createAttribute("class","suggestionDiv"));
		}
		
		//add id
		//attr = document.createAttribute("id");
		//attr.nodeValue = "suggestion"
		//suggestion.setAttributeNode(attr);
		
		
		//add suggestion name span
		var suggestionName = document.createElement("SPAN");
		attr = document.createAttribute("id");
		attr.nodeValue = "suggestName";
		suggestionName.setAttributeNode(attr);
		suggestionName.innerHTML = name;
		
		suggestion.appendChild(suggestionName);

		if ( document.all )
		{
			var idNode = document.createElement( "<SPAN style='display:none;' id='typeID-" + id + "'></SPAN>" );
		}	
		else
		{	
			var idNode = document.createElement("SPAN");
			idNode.setAttributeNode(createAttribute("style","display: none;"));
			idNode.setAttributeNode(createAttribute("id","typeID-" + id));
		}
		
		suggestion.appendChild(idNode);
		
	
		
		switch(results[i].entityType)
		{
			case "Title":
				var suggestionYear = document.createElement("SPAN");
				attr = document.createAttribute("id");
				attr.nodeValue = "suggestYear";
				suggestionYear.setAttributeNode(attr);
				if( year > 0 )
					suggestionYear.innerHTML = "\\" + year;
				
				suggestion.appendChild(suggestionYear);
				
				var suggestionType = document.createElement("SPAN");
				attr = document.createAttribute("id");
				attr.nodeValue = "suggestType";
				suggestionType.setAttributeNode(attr);
				suggestionType.setAttributeNode(createAttribute('class','title'));
				switch( results[i].contentType )
				{
					case "FeatureFilm":
						suggestionType.innerHTML = "(Movie)";
						break;
					case "TvSeries":
						suggestionType.innerHTML = "(TV)";
						break;
					case "ShortFilm":
						suggestionType.innerHTML = "(Short)";
						break;
				}
				
				suggestion.appendChild(suggestionType);
				
			break;
			
			case "Person":
				var suggestionType = document.createElement("SPAN");
				attr = document.createAttribute("id");
				attr.nodeValue = "suggestType";
				suggestionType.setAttributeNode(attr);
				suggestionType.innerHTML = "(People)";
				
				suggestion.appendChild(suggestionType);
			break;
			
			default:
				var suggestionType = document.createElement("SPAN");
				attr = document.createAttribute("id");
				attr.nodeValue = "suggestType";
				suggestionType.setAttributeNode(attr);
				suggestionType.innerHTML = "(" + entityType + ")";
				
				suggestion.appendChild(suggestionType);
			break;
		
		}
		try{
		sugArea.appendChild(suggestion);
		}catch(e){}
	}
	searchBoxController.activeSearchBox.showSuggestionPanel();
}



function addSuggestionToSearch(obj)
{
	var elements = obj.childNodes;
	var textToAdd = "";
	var suggestName = null;
	var suggestType = null;
	for(i=0;i<elements.length;i++)
	{
		if(elements[i].id == "suggestName") suggestName = elements[i].innerHTML;
		
		if(elements[i].id == "suggestType") suggestType = elements[i].innerHTML;
		
		if(elements[i].id.indexOf("typeID")==0) suggestID = elements[i].id.split("-")[1];
	}
	
	if(searchBoxController.activeSearchBox.sb_searchBox.id.indexOf('discovery')>-1)
	{
		addToDiscoverySearchBox(null,null,true,suggestName,suggestType,suggestID);
	}
	else if(searchBoxController.activeSearchBox.sb_searchBox.id.indexOf('favorite')>-1)
	{
		addToFavoriteSearchBox(suggestName,suggestType,suggestID);
	}
	else if(searchBoxController.activeSearchBox.sb_searchBox.id == 'searchInput')
	{
		addToSearchFromSuggestion(suggestName,suggestType,suggestID);
	}
	
}
function hideSuggestionPanel()
{
	/*searchBoxController.activeSearchBox.sb_suggestionsPanel.style.display = "none";*/
	try{
	this.sb_suggestionsPanel.style.display = "none";
	}catch(e){}
}
function showSuggestionPanel()
{
	searchBoxController.activeSearchBox.sb_suggestionsPanel.style.display = "block";
}
function clearSuggestionsPanel()
{
	while(this.sb_suggestionsPanel && this.sb_suggestionsPanel.firstChild)
		this.sb_suggestionsPanel.removeChild(searchBoxController.activeSearchBox.sb_suggestionsPanel.firstChild);
	searchBoxController.activeSearchBox.sb_selectedSuggestionIndex = null;
}

function closeSuggestionPanelDelay()
{
	// Bug fix - Nimrod 18/6/08 - If the blur event was caused by the suggestion box being clicked, we don't want to close it.
	// It will then close itself and reset the suggestPanelTimer variable for next time.
	if ( suggestPanelTimer != -1 )  
	{
		suggestPanelTimer = window.setTimeout("searchBoxController.activeSearchBox.closeSuggestionPanel()",300);
	}
	
}
	
function closeSuggestionPanel()
{
	
	this.clearSuggestionsPanel();
	this.hideSuggestionsPanel();
	
}


function setSearchResults(results)
{
	var searchResult = results;
}
function getSearchCodeName(searchCode)
{
	var code = null;
	if(searchCode.indexOf("]") != -1)
	{
		var start = searchCode.lastIndexOf("]");
		code = searchCode.substr(start+1);
	}
	switch(code){
		
		case code.indexOf("(")>-1:
			return code;
		case "T" || "(Title)":
			return "Title";
		case "P" || "(People)":
			return "People";
	
	}
	
}
function getCodeFromString(type)
{
	switch(type){
		
		case "Title":
			return "T";
		case "People":
			return "P";
		default :
			return "G";
		
	
	}
}
function needToShowDiscovery()
{
//	var toShow = false;
//	var foundTitle = false;
//	
//	var searchContent =  document.getElementById('txt').childNodes;
//	
//	for(var index=0; index<searchContent.length; index++) {
//	
//		if(searchContent[index].id != null && searchContent[index].id.indexOf("]")>0)
//		{
//			if(searchContent[index].id.indexOf(']T')>-1)
//			{
//				if(foundTitle==true) return false;
//				
//				foundTitle = true;
//			}
//			else
//			{
//				return false;
//			}
//			
//		}
//		
//	}
	
	//return toShow || foundTitle;
	return false;	
}
function addToDiscoverySearchBox(objToAdd,searchCode,isFromSuggestion,text,type,suggestionID)
{
	var objID = null;
	var objValue = null;
	
	if(!isFromSuggestion)
	{
			objID = objToAdd.id.split('-')[0];
			objValue = document.getElementById(objID+"-text").innerHTML;
	}
	else
	{
			objID = suggestionID;
			searchCode = "[" + suggestionID + "]" + getCodeFromString( type );
			objValue = text;
	}
	
	document.getElementById("discoveryBox").value = objValue;
	
	
	discoveryCode = objID;
	
	findSimilarTo = objValue;
	
	
}
function addToFavoriteSearchBox(text,type,suggestionID)
{
	var objID = null;
	var objValue = null;
	
	objID = suggestionID;
	searchCode = "[" + suggestionID + "]" + getCodeFromString( type );
	objValue = text;
	
	
	document.getElementById("favoriteBox").value = objValue;
	
	
	discoveryCode = objID;
	
	findSimilarTo = objValue;
	
	
}

function rollOverSearch(searchPhrase, type, id, code)
{
	searchPhrase = searchPhrase.replace(/&#39/,'\'');
	cleanearchBox();
	addToSearchFromRollover(searchPhrase, type, id, code);
	doSearch();
}

function addToSearchFromRollover(searchPhrase, type, id, code)
{
	type = type.substring(1,type.length-1);
	addToSearchBox(searchPhrase, type, id, code);
}
function addToSearchFromRefinementTool(searchPhrase, type, id, code)
{
	addToSearchBox(searchPhrase.decode(), type, id, code);
}
function addToSearchFromCloud(searchPhrase, type, id, code){
	addToSearchBox(searchPhrase.decode(), type, id, code);
	doSearch();
	
}

function searchFromRefinementTool(searchPhrase, type, id, code)
{
	addToSearchFromRefinementTool(searchPhrase, type, id, code);
	doSearch();
}

function resetTasteSliders()
{
	try{
	sliderOB.sliderEnabled = false;
	sliderSE.sliderEnabled = false;
	sliderFN.sliderEnabled = false;
	sliderSP.sliderEnabled = false;
	}catch(e){}
	document.getElementById('tasteFilter').value = "";
}
function searchFromTasteScales()
{
	var obscure = null;
	var serious = null;
	var fantastic = null;
	var fast = null;
	var stringValues = "";
	
	TasteFilter.obscure = -1;
	TasteFilter.pace = -1;
	TasteFilter.realistic = -1;
	TasteFilter.serious = -1;
	
	
	if(sliderOB.sliderEnabled == true)
	{
		obscure = sliderOB.sliderValue;
		obscure = Math.floor( obscure/20 );
		if(obscure == 0) obscure=1; 
		
		TasteFilter.obscure = obscure;
	}
	if(sliderSE.sliderEnabled == true) 
	{
		serious = sliderSE.sliderValue;
		serious = Math.floor( serious/33 );
		if(serious == 0) serious=1; 
		
		TasteFilter.serious = serious;
	}
	if(sliderFN.sliderEnabled == true) 
	{
		fantastic = sliderFN.sliderValue;
		fantastic = Math.floor( fantastic/33 );
		if(fantastic == 0) fantastic=1;
		
		TasteFilter.realistic = fantastic; 
	}
	if(sliderSP.sliderEnabled == true) 
	{
		fast = sliderSP.sliderValue;
		fast = Math.floor( fast/33);
		if(fast == 0) fast=1; 
		
		TasteFilter.pace = fast;
	}
	
	stringValues = "obscure-" + obscure + "," + "serious-" + serious + "," + "fantastic-" + fantastic + "," + "fast-" + fast;
	document.getElementById('tasteFilter').value = stringValues;
	hideTasteFilters();
	doSearch();

}
function hideTasteFilters()
{
	document.getElementById('taste_menu').style.display = "none";
	discoveryShow = false;
}

function addToSearchFromSuggestion(searchPhrase, type, id)
{
	type = type.substring(1,type.length-1);
	code = getCodeFromString(type)
	addToSearchBox(searchPhrase, type, id, code);
}
/**
 * obj is the LI tag
 * isFromSuggestion - true if we adding a suggestion
 * text - suggestion text
 * type - suggestion type (people,title,etc..)
 * suggestionID = type id.
 */
function addToSearchBox(searchPhrase, type, id, code)
{
	searchPhrase = searchPhrase.decode();
	
	clearWelcomeMessage();
	
	var objID = null;
	var searchName = null;
	var searchCategory = null;
	
	searchName = searchPhrase;
	
	// WARNING: the parameter [code] is overridden if we came from the suggestion box and it is a synonym.
	if ( suggestionsMap && suggestionsMap[id + "_" + searchPhrase] )
	{
		code = suggestionsMap[id + "_" + searchPhrase];
	}
	searchCode = "[" + id + "]" +  code;

	//if already exist in search then dont add it
	for ( var i = 0; i < searchBoxData.length; i++ )
	{
		if ( searchBoxData[i].itemId == searchCode )
		{
			return;
		}
	}
	
	// Get caret position
	var box = document.getElementById( "searchInput" );
	var caretStart = 0;
	var caretEnd = 0;
	var prefixSpaceNeeded = false;
	var caretPos = getCaretPosition( box );
	if ( document.all )
	{
		if ( !currentSelectionRange )
		{
			document.getElementById('searchInput').focus();
			currentSelectionRange = document.selection.createRange();
			currentSelectionRange.move('character', document.getElementById('searchInput').value.length );
		}
		var r2 = currentSelectionRange.duplicate();
		caretPos.start = 0 - r2.moveStart('character', -100000);
	}
	var prefix = "";
	if ( caretPos.start > 0 && box.value.charAt( caretPos.start - 1 ) != ' ' )
	{
		prefix = " ";
	}
	
	if ( document.selection ) // IE
	{
		caretStart = caretPos.start;
		document.getElementById('searchInput').focus();
		currentSelectionRange.text = prefix + searchPhrase.toLowerCase() + " ";
		currentSelectionRange.select();
		currentSelectionRange.collapse(false);
		
	}
	else // Gecko
	{
		caretStart = box.selectionStart;
		caretEnd = box.selectionEnd;
		box.value = box.value.substring(0, caretStart) + prefix + searchPhrase.toLowerCase() + " " +  box.value.substring(caretEnd, box.value.length);
	}
	// update the search box color.
	box.style.color = "black";
	
	var searchEntry = new SearchBoxDataEntry();
	searchEntry.displayName = searchPhrase;
	searchEntry.start = caretStart;
	searchEntry.end = searchEntry.start + searchPhrase.length;
	searchEntry.itemId = searchCode;
	searchEntry.type = type;
	searchBoxData.push( searchEntry );

}

function showDiscoveryButton()
{
	document.getElementById('discoversearch').style.display = "block";
}
function hideDiscoveryButton()
{
	try{
	document.getElementById('discoversearch').style.display = "none";
	}catch(e){}
}

function removeFromSearch(objID)
{	
	var objToRemove = document.getElementById(objID);
	var objid = objID.split('-')[0];
	var box = document.getElementById("searchInput");
	for ( var i = 0; i < searchBoxData.length; i++ )
	{
		if ( searchBoxData[i].itemId == objid )
		{
			box.value = box.value.substring( 0, searchBoxData[i].start ) + 
					box.value.substring( searchBoxData[i].end + 1, box.value.length );
			searchBoxData.splice(i,1);
			searchFuncs.relocateSearchTerms();
			if ( document.selection )
			currentSelectionRange = null;
			break;
		}
	}
}

function removeFromSearchFromRefinement(objId)
{
	removeFromSearch( objId );
	doSearch();
}


function clearWelcomeMessage()
{

	if ( document.getElementById( "searchInput" ).value == SEARCH_WELCOME || 
		 document.getElementById( "searchInput" ).value == SEARCH_MOVIES || 
		 document.getElementById( "searchInput" ).value == SEARCH_TV || 
		 document.getElementById( "searchInput" ).value == SEARCH_SHORTS || 
		 document.getElementById( "searchInput" ).value == SEARCH_ONLINE ||
		 document.getElementById( "searchInput" ).value == SEARCH_TITLES ||
		 document.getElementById( "searchInput" ).value == SEARCH_DVD
		)
	{
		document.getElementById( "searchInput" ).value = "";
		document.getElementById( "searchInput" ).style.color = "black";
	}
}

/* function for search box */
function filterSearchResults(menuItem)
{
	if(!menuItem) return;

	//if( menuItem.className == undefined || menuItem.className.indexOf('unavailableLink') > -1 ) return;
	
	var isPageLoading = false;
	if(menuItem == 'pageLoading')
	{
		isPageLoading = true;
		try{ 
		
			filterMenuItem = document.getElementById(getCookieValue('gfilter'))
			menuItem = document.getElementById(getCookieValue('gfilter'));
		}
		catch(e){}
		
		if(filterMenuItem == '') filterMenuItem = document.getElementById('all');
		
		if(menuItem == null) menuItem = document.getElementById('all');
	}
	else
	{
		try{
		menuItem.className = 'typeHighlight';
		}catch(e){
			
			return;
		}
		if(filterMenuItem != null)
		{	
				filterMenuItem.className = 'menuLink';
		}
		
		
		
	}
		try{
		menuItem.className = 'typeHighlight';
		}catch(e){
			
			return;
		}
	
		filterMenuItem = menuItem;
		filterMenuItem.className = 'typeHighlight';
		
		prevGlobalFilterType = globalFilterType;
	
		suggestFilter.contentTypeFilter = null;
		suggestFilter.onlineContentFilter = false;
		
		
		if(menuItem.id == 'all') globalFilterType = "all";	
		else if(menuItem.id == 'movieFilter')
		{
			 globalFilterType = "FeatureFilm";
			 suggestFilter.contentTypeFilter = "FeatureFilm";
		} 
		else if(menuItem.id == 'tvFilter') {
		
			globalFilterType= "TvSeries";
			suggestFilter.contentTypeFilter = "TvSeries";
		}
		else if(menuItem.id == 'shortsFilter') 
		{ 
			globalFilterType= "ShortFilm"; 
			suggestFilter.contentTypeFilter = "ShortFilm";
		}
		else if(menuItem.id == 'onlineFilter') 
		{
			globalFilterType= 'online'; 
			suggestFilter.onlineContentFilter = true;
		}
	
		searchboxFilters();
		document.getElementById('globalFilter').value = globalFilterType;
		
		setSessionCookie('gfilter',menuItem.id);
		
		//affilateFilters.updatePageWithAfiliateFilter();	
		if( !isPageLoading )
			doSearch();
	
}
/* */

affilateFilters.setAffiliatesFilter = function( obj, affiliateName )
{
	
	if( obj.id == 'netflixFilterCheckbox')
	{
		if(obj.checked)
		{
			if( ! affilateFilters.isFilterExist( affilateFilters.netflix ) )
			{
				affilateFilters.addAffiliateFilter( affilateFilters.netflix )
				
				
				
				if(filterMenuItem == document.getElementById('shortsFilter'))
				{
					filterSearchResults(document.getElementById('all'));
				}
				document.getElementById('shortsFilter').className = "unavailableLink";
				document.getElementById('onlineFilter').innerHTML = "Watch Instantly" 
				
			}
		}
		else
		{
			if( affilateFilters.isFilterExist( affilateFilters.netflix ) )
			{
				affilateFilters.removeAffiliateFilter( affilateFilters.netflix );
				document.getElementById('onlineFilter').innerHTML = "Online" 
				document.getElementById('shortsFilter').className = "menuLink";
			}	
			
		}
		
	}
	
}
affilateFilters.addAffiliateFilter = function( filter )
{
	var cookieValue = affilateFilters.filtersAsString() + "_" + filter;
	
	//setPersistanteCookie('aFilter', cookieValue, 1000*3600*24*360, null);
	setSessionCookie('aFilter', cookieValue);
}

affilateFilters.removeAffiliateFilter = function( filter )
{
	var cookieFilters = getCookieValue('aFilter');
	if(cookieFilters == "") return;
	var filtersArray = affilateFilters.filtersAsArray()
	
	for(var index=0; index<filtersArray.length && filtersArray[index] != filter; index++);
	
	try{
		filtersArray.splice(index,1);
	}
	catch(e){}
	
	var cookieValue = affilateFilters.filtersAsString( filtersArray);
	
	if( cookieValue.length < 2 )
		removeCookie('aFilter');
	else
		setSessionCookie('aFilter', cookieValue);
	
}


affilateFilters.updatePageWithAfiliateFilter = function()
{
	/* this method is used when the page loads */
	var affiliateFilters = getCookieValue('aFilter');
	var filtersArray = null;
	if(affiliateFilters != undefined && affiliateFilters != '')
	{
		filtersArray = affiliateFilters.split( affilateFilters.cookieDelimiter );
		for(var index=0; index<filtersArray.length; index++) {
		
			if(filtersArray[index] == affilateFilters.netflix)
			{
				document.getElementById('netflixFilterCheckbox').checked = true;
			}
		}
	}
}
affilateFilters.filtersAsArray = function()
{
	var affiliateFilters = getCookieValue('aFilter');
	var filtersArray = null;
	
	if(affiliateFilters != undefined && affiliateFilters != '')
	{
		filtersArray = affiliateFilters.split( affilateFilters.cookieDelimiter );
	}
	
	return filtersArray ;
}
affilateFilters.filtersAsString = function( arrayValue )
{
	var affiliateString = "";
	
	var filtersArray = null;
	
	if ( arrayValue == undefined )
		filtersArray = getCookieValue('aFilter').split( affilateFilters.cookieDelimiter );
	else
		filtersArray = arrayValue;
	
	for(var index=0; index< filtersArray.length; index++) {
	
		affiliateString += "_" + filtersArray[index];	
	}
	
	return affiliateString == null ? null : affiliateString.substring( 1 );
}

affilateFilters.isFilterExist = function( filterName )
{
	var affiliateFilters = getCookieValue('aFilter');
	
	if(affiliateFilters.indexOf( filterName ) > -1)
		return true;
	else
		return false;
}



function saveSearchCookie()
{
	var searchInput = document.getElementById( "searchInput" );
	var cookieStr = searchInput.value;
	cookieStr += "~#~";
	cookieStr += searchTypeDropState;
	for( var i = 0; i < searchBoxData.length; i++ )
	{
		cookieStr += "#~#";
		cookieStr += searchBoxData[i].displayName + ",";
		cookieStr += searchBoxData[i].start + ",";
		cookieStr += searchBoxData[i].end + ",";
		cookieStr += searchBoxData[i].itemId + ",";
		cookieStr += searchBoxData[i].type;
	}
	
	if ( searchInput.value.length > 0 )
	{
		setSessionCookie( "freesearch", escape( cookieStr ));
	}
}

function getFreeSearchFromCookie()
{
	var cookieValue = "";
	try{
		cookieValue = unescape( getCookieValue("freesearch") );
		if( cookieValue.startsWith("\""))
			cookieValue = cookieValue.substr(1);
		if( cookieValue.endsWith("\""))
			cookieValue = cookieValue.substr(0, cookieValue.length-1);
		
		if(cookieValue != "" && cookieValue.length >1)
		{
			var delimIndex = cookieValue.indexOf("~#~");
			document.getElementById("searchInput").value = cookieValue.substring(0, delimIndex );
			document.getElementById("searchInput").style.color = "black";
			var searchType = parseInt( cookieValue.substring( delimIndex + 3, delimIndex + 4 ) )
			if ( searchType == 1 )
			{
				document.getElementById( "searchTypeDropdown" ).innerHTML = "content";
				searchTypeDropState = searchType;
			}
			else if ( searchType == 2 )
			{
				document.getElementById( "searchTypeDropdown" ).innerHTML = "titles";
				searchTypeDropState = searchType;
			}
			else
			{
				throw "getFreeSearchFromCookie: found unsupported search type: " + searchType;
			}
			var searchBoxDataDelim = cookieValue.indexOf( "#~#" );
			if ( searchBoxDataDelim > -1 )
			{
				var entries = cookieValue.substring( searchBoxDataDelim + 3, cookieValue.length ).split("#~#");
				if ( entries != null )
				{
					searchBoxData.length = 0; 	// clears the array
					for ( var i = 0; i < entries.length; i++ )
					{
						var dataParts = entries[i].split(",");
						var entry = new SearchBoxDataEntry();
						entry.displayName = dataParts[0];
						entry.start = parseInt( dataParts[1] );
						entry.end = parseInt( dataParts[2] );
						entry.itemId = dataParts[3];
						entry.type = dataParts[4];
						searchBoxData.push( entry );
					}
				}
			}
		}
	}
	catch(e){}
	
}

function isAnythingInSearchBox()
{
	var searchBox = document.getElementById( "searchInput" );
	
	return ( 	searchBox.value.length > 0 && 
				searchBox.value != SEARCH_WELCOME 	&& 
				searchBox.value != SEARCH_WELCOME 	&&
				searchBox.value != SEARCH_MOVIES 	&& 
				searchBox.value != SEARCH_DVD 		&&
				searchBox.value != SEARCH_TV 		&&
		 		searchBox.value != SEARCH_SHORTS 	&&
		 		searchBox.value != SEARCH_ONLINE	&&
		 		searchBox.value != SEARCH_TITLES
		 		
		 	);
	
}
function doDiscover()
{
	document.getElementById("searchCriteria").value = document.getElementById("searchInput").value;
	document.getElementById('buttonType').value = "discover";
	document.getElementById('searchForm').submit();
}

function cleanSearchTree()
{
	
}

function calcSearchTreeLeaves(tree)
{
	var size = 0;
	for( var i = 0; i < tree.length; i++ )
	{
		size += tree[i].categoryNodes.length;
	}
	return size;
}

function buildSearchTree(tree)
{
	var highLightedMenuItems = new Array();
	expandedNode = new Array(); //this is used when expanding and shrinking the tree
	for( var idx=0; idx < searchResponseObject.expression.idCriterias.length; idx++ )
	{
		if( searchResponseObject.expression.idCriterias[idx].type == 'Category' )
		{
			highLightedMenuItems["G" + searchResponseObject.expression.idCriterias[idx].id] = 1;
		}
		else if(searchResponseObject.expression.idCriterias[idx].type=='Person')
		{
			highLightedMenuItems["P" + searchResponseObject.expression.idCriterias[idx].id] = 1;
		}		
	}
		
	
	var refTitle =  document.getElementById('refToolTitle').cloneNode(true);
	//refTitle.innerHTML = "Squeeze your search";
	
	var refToolRoot = document.getElementById('refTool');
	if ( calcSearchTreeLeaves(tree) + searchResponseObject.commonDirectorsList.length + 
		 searchResponseObject.commonStarringList.length - searchResponseObject.expression.idCriterias.length == 0 )
	{
		var refTitleChildren = refTitle.getElementsByTagName("div");
		for ( var i = 0; i < refTitleChildren.length; i++ )
		{
			if ( refTitleChildren[i].className == 'leftTxt' )
			{
				refTitleChildren[i].innerHTML = "This search can't be narrowed down any more.";
				break;
			}
		}
		
	}
	refToolRoot.innerHTML = "";
	refToolRoot.appendChild(refTitle);
	
	var attr = null;
	var element = null;
	
//	if(tree.length > 0)
//	{
		var mainUL = document.createElement("UL");
		mainUL.setAttributeNode(createAttribute("class","tree"));
		refToolRoot.appendChild(mainUL);
		
//		var genomIcon = document.createElement("IMG");
//		genomIcon.setAttributeNode(createAttribute("class",""));
//		genomIcon.setAttributeNode(createAttribute("style","margin-right: 5px;"));
//		genomIcon.setAttributeNode(createAttribute("src",imagePath + "16_gene_red.png"));
//		
//		
//		element = document.createElement("LI");
//		element.setAttributeNode(createAttribute("class","allGenom"));
//		
//		element.appendChild(genomIcon);
//		element.appendChild( document.createTextNode("All Genom") );
		
		
		
//		mainUL.appendChild(element);
		

		for(var cateogyNode =0;tree != null && cateogyNode < tree.length; cateogyNode++)
		{
			if ( document.all )
			{
				var newLI = document.createElement("<LI id='" + tree[cateogyNode].name + "' class='cateogryTypeNode'" +
						" onclick='exposeGenom(\"" + tree[cateogyNode].name + "Categories\",this);'></LI>" );
				newLI.appendChild(document.createTextNode(tree[cateogyNode].name));
				
			}
			else
			{
				var newLI = document.createElement("LI");
				newLI.setAttributeNode(createAttribute("id",tree[cateogyNode].name));
				newLI.appendChild(document.createTextNode(tree[cateogyNode].name));
				newLI.setAttributeNode(createAttribute("class","cateogryTypeNode"));
				newLI.setAttributeNode(createAttribute("onclick","exposeGenom('" + tree[cateogyNode].name + "Categories',this);"));
			}
			if ( document.all )
			{
				element = document.createElement( "<img style='cursor:pointer;' src='" + imagePath + 
					"arrToBotMenu.png' border='0' />" );
			}
			else
			{
				element = document.createElement("IMG");
				element.setAttributeNode(createAttribute("style","cursor:pointer"));
				element.setAttributeNode(createAttribute("src",imagePath + "arrToBotMenu.png"));
				element.setAttributeNode(createAttribute("border","0"));
			}
			newLI.appendChild(element);

			var newUL;
			if ( document.all )
			{
				newUL = document.createElement( "<UL id='" + tree[cateogyNode].name + "Categories' class='menuList' style='height:0;'></UL>" );
			}
			else
			{
				newUL = document.createElement("UL");
				newUL.setAttributeNode(createAttribute("id",tree[cateogyNode].name + "Categories"));
				newUL.setAttributeNode(createAttribute("class","menuList"));
				newUL.setAttributeNode(createAttribute("style","height:0"));
			}
			for(var categoryGene = 0; categoryGene < tree[cateogyNode].categoryNodes.length; categoryGene++)
			{
				var genomID = tree[cateogyNode].categoryNodes[categoryGene].category.id;
				if ( document.all )
				{
					if(highLightedMenuItems["G" + genomID] != null)
					{
						var genom = document.createElement( "<LI class='selectedMenu' onclick='event.cancelBubble=true;' " +
								"id='["+ genomID +"]G'></LI>" );
						if ( newUL.style )
						{
							newUL.style.height = "";
						}
						newLI.setAttributeNode(createAttribute("class","selectedCategory"));
						expandedNode.push(newUL);
						element.setAttribute("src","/images/arrToTopMenu.png");
					}
					else
					{
 						var genom = document.createElement( "<LI onclick='event.cancelBubble=true;' " +
								"id='["+ genomID +"]G'></LI>" );
					}
				}
				else
				{
					var genom = document.createElement("LI");
					
					if(highLightedMenuItems["G" + genomID] != null)
					{
						genom.setAttributeNode(createAttribute("class","selectedMenu"));
						if ( newUL.style )
						{
							newUL.style.height = "";
						}
						newLI.setAttributeNode(createAttribute("class","selectedCategory"));
						expandedNode.push(newUL);
						element.setAttribute("src","/images/arrToTopMenu.png");
					}
					genom.setAttributeNode(createAttribute("onclick","event.cancelBubble=true;"));
					genom.setAttributeNode(createAttribute("id","["+ genomID +"]G"));
				}
				
				if ( document.all )
				{
					if ( highLightedMenuItems["G" + genomID] == null )
					{
						var textSpan = document.createElement( "<SPAN id='" + genomID + "-text' " +
								"onmouseover='document.getElementById(\"" + genomID + "-img\").style.visibility=\"visible\";' " +
								"onmouseout='if (document.getElementById(\"" + genomID + 
								"-img\").className==\"addToSearchImage\")document.getElementById(\"" + genomID + "-img\").style.visibility=\"hidden\";' " +
								"onclick='searchFromRefinementTool(\"" + tree[cateogyNode].categoryNodes[categoryGene].category.name.encode() + "\", \"" + 
								tree[cateogyNode].name + "\", \"" + genomID + "\", \"G\");'></SPAN>" );	
					}
					else
					{
						var textSpan = document.createElement( "<SPAN id='" + genomID + "-text' " +
								"onclick='removeFromSearchFromRefinement(\"[" + genomID + "]G-search\");' " +
								"onmouseover='document.getElementById(\"" + genomID + "-img\").style.visibility=\"visible\";' " +
								"onmouseout='if (document.getElementById(\"" + genomID + "-img\").className==\"addToSearchImage\")document.getElementById(\"" + 
								genomID + "-img\").style.visibility=\"hidden\";'></SPAN>" );
					}
				}
				else
				{				
					var textSpan = document.createElement("SPAN");
					textSpan.setAttributeNode(createAttribute("id",genomID+"-text"));
					if(highLightedMenuItems["G" + genomID] == null)
					{				
						textSpan.setAttributeNode(createAttribute("onclick","searchFromRefinementTool(\""+tree[cateogyNode].categoryNodes[categoryGene].category.name+"\",\"" + tree[cateogyNode].name +"\",\"" + genomID + "\",\"G\");"));
					}
					else
					{
						textSpan.setAttributeNode(createAttribute("onclick","removeFromSearchFromRefinement('[" + genomID + "]G-search');"));
					}
					textSpan.setAttributeNode(createAttribute("onmouseover","document.getElementById('" + genomID + "-img').style.visibility='visible';"));
					textSpan.setAttributeNode(createAttribute("onmouseout","if (document.getElementById('" + genomID + "-img').className=='addToSearchImage')document.getElementById('" + genomID + "-img').style.visibility='hidden';"));
				}
				textSpan.appendChild(document.createTextNode(tree[cateogyNode].categoryNodes[categoryGene].category.name));
			
				
				genom.appendChild(textSpan);
				
				if(highLightedMenuItems["G" + genomID] == null)
				{				
//					if ( document.all )
//					{
//						var addToSearchImg = document.createElement("<IMG class='addToSearchImage' onclick='searchFromRefinementTool(\"" + tree[cateogyNode].categoryNodes[categoryGene].category.name + "\",\"" + genomID + "\",\"G\");' src='/images/greenPlus.png' border='0' id='" + genomID + "-img' />");
//					}
//					else
//					{
						var addToSearchImg = document.createElement("IMG");
						addToSearchImg.setAttributeNode(createAttribute("class","addToSearchImage"));
						addToSearchImg.setAttributeNode(createAttribute("onclick","searchFromRefinementTool('"+tree[cateogyNode].categoryNodes[categoryGene].category.name+"','" + tree[cateogyNode].name +"','" + genomID + "','G');"));
						addToSearchImg.setAttributeNode(createAttribute("src", "/images/greenPlus.png"));
						addToSearchImg.setAttributeNode(createAttribute("border","0"));
						addToSearchImg.setAttributeNode(createAttribute("id",genomID + "-img"));
//					}
					genom.appendChild(addToSearchImg);
				}
				else
				{
//					if ( document.all )
//					{
//						var addToSearchImg = document.createElement("<IMG class='removeFromSearchImage' onclick='removeFromSearchFromRefinement(\"[" + genomID + 
//									"]G-search\");' src='/images/redx.png' border='0' id='" + genomID + "-img' />");
//					}
//					else
//					{
						var addToSearchImg = document.createElement("IMG");
						addToSearchImg.setAttributeNode(createAttribute("class","removeFromSearchImage"));
						addToSearchImg.setAttributeNode(createAttribute("onclick","removeFromSearchFromRefinement('[" + genomID + "]G-search');"));
						addToSearchImg.setAttributeNode(createAttribute("src", "/images/redx.png"));
						addToSearchImg.setAttributeNode(createAttribute("border","0"));
						addToSearchImg.setAttributeNode(createAttribute("id",genomID + "-img"));
//					}
					genom.appendChild(addToSearchImg);
				}
				genom.setAttributeNode(createAttribute("onmouseover","document.getElementById('" + genomID + "-img').style.visibility='visible';"));
				genom.setAttributeNode(createAttribute("onmouseout","if (document.getElementById('" + genomID + "-img').className=='addToSearchImage')document.getElementById('" + genomID + "-img').style.visibility='hidden';"));

				
				newUL.appendChild(genom);
				
				
			}
			
			newLI.appendChild(newUL);
			mainUL.appendChild(newLI);
		}	
		
//		document.createElement("");
//		mainUL.appendChild(element);
//		element.setAttributeNode(createAttribute("",""));
		
//		var cast = document.createElement("UL");
//		cast.setAttributeNode(createAttribute("class","tree"));
//		refToolRoot.appendChild(cast);
		
//		element = document.createElement("LI");
//		element.setAttributeNode(createAttribute("class","castCrew"));
		
//		var castIcon = document.createElement("IMG");
//		castIcon.setAttributeNode(createAttribute("class",""));
//		castIcon.setAttributeNode(createAttribute("style","margin-right: 5px;"));
//		castIcon.setAttributeNode(createAttribute("src",imagePath + "16_actor_red.png"));
//		
//		element.appendChild(castIcon)
//		element.appendChild( document.createTextNode("Cast & Crew") );
		
		
		
//		mainUL.appendChild(element);

		
		if(searchResponseObject.commonStarringList!=null && searchResponseObject.commonStarringList.length >0)
		{
			if ( document.all )
			{
				var mainActors = document.createElement("<LI class='cateogryTypeNode' onclick='exposeGenom(\"starsCategories\",this);' id='stars'></LI>");
				mainActors.appendChild(document.createTextNode("Actors"));
			}
			else
			{
				var mainActors = document.createElement("LI");
				//newLI.setAttributeNode(createAttribute("id",tree[idx].name));
				mainActors.appendChild(document.createTextNode("Actors"));
				mainActors.setAttributeNode(createAttribute("class","cateogryTypeNode"));
				mainActors.setAttributeNode(createAttribute("onclick","exposeGenom('starsCategories',this);"));
				mainActors.setAttributeNode(createAttribute("id","stars"));
			}

			if ( document.all )
			{
				element = document.createElement("<IMG style='cursor:pointer' src='" + imagePath + "arrToBotMenu.png' border='0' />")
			}	
			else
			{		
				element = document.createElement("IMG");
				element.setAttributeNode(createAttribute("style","cursor:pointer"));
				//var method = "exposeGenom(" + tree[cateogyNode].name + "Categories"
				//element.setAttributeNode(createAttribute("onclick","exposeGenom('stars',this);"));
				element.setAttributeNode(createAttribute("src",imagePath + "arrToBotMenu.png"));
				element.setAttributeNode(createAttribute("border","0"));
			}
			
			mainActors.appendChild(element);
			mainUL.appendChild(mainActors);

			if ( document.all )
			{
				var foundActor = false;
				for(var idx =0; idx < searchResponseObject.commonStarringList.length;idx++)
				{
					if ( highLightedMenuItems["P" + searchResponseObject.commonStarringList[idx].id] )
					{
						foundActor = true;
						break;
					}
				}
				if ( foundActor )
				{
					var actorsList = document.createElement("<UL id='starsCategories' class='menuList'></UL>");
				}
				else
				{
					var actorsList = document.createElement("<UL id='starsCategories' class='menuList' style='height:0;'></UL>");
					
				}
			}	
			else
			{		
				var actorsList = document.createElement("UL");
				actorsList.setAttributeNode(createAttribute("id","starsCategories"));
				actorsList.setAttributeNode(createAttribute("class","menuList"));
				actorsList.setAttributeNode(createAttribute("style","height:0"));
			}
			
			for(var idx =0; idx < searchResponseObject.commonStarringList.length;idx++)
			{
				var actorID = searchResponseObject.commonStarringList[idx].id;
				var actors = searchResponseObject.commonStarringList;
				if ( document.all )
				{
					if ( highLightedMenuItems["P" + actorID] != null )
					{
						var actor = document.createElement( 
							"<LI class='selectedMenu' onclick='event.cancelBubble=true;' id='["+ actors[idx].id +"]P'></LI>" );
						mainActors.className = "selectedCategory";
						expandedNode.push(actorsList);
					}
					else
					{
						var actor = document.createElement( 
							"<LI class='' onclick='event.cancelBubble=true;' id='["+ actors[idx].id +"]P'></LI>" );
					}
				}
				else
				{
					var actor = document.createElement("LI");
					actor.setAttributeNode(createAttribute("class",""));
					if(highLightedMenuItems["P" + actorID] != null)
					{
						mainActors.setAttributeNode(createAttribute("class","selectedCategory"));
						actorsList.setAttributeNode(createAttribute("style",""));
						actor.setAttributeNode(createAttribute("class","selectedMenu"));
						expandedNode.push(actorsList);
					}					
					actor.setAttributeNode(createAttribute("onclick","event.cancelBubble=true;"));
					actor.setAttributeNode(createAttribute("id","["+ actors[idx].id +"]P"));
				}
				
				if ( document.all )
				{
					if ( highLightedMenuItems["P" + actorID] == null )
					{
						textSpan = document.createElement("<SPAN is='" + actors[idx].id + "-text' onmouseover='document.getElementById(\"" + actors[idx].id + "-img\").style.visibility=\"visible\";' onmouseout='if (document.getElementById(\"" + actors[idx].id + "-img\").className==\"addToSearchImage\")document.getElementById(\"" + actors[idx].id + "-img\").style.visibility=\"hidden\";' onclick='searchFromRefinementTool(\""+actors[idx].name+"\",\"People\",\"" + actors[idx].id + "\",\"P\");'></SPAN>");
					}
					else
					{
						textSpan = document.createElement("<SPAN is='" + actors[idx].id + "-text' onmouseover='document.getElementById(\"" + actors[idx].id + "-img\").style.visibility=\"visible\";' onmouseout='if (document.getElementById(\"" + actors[idx].id + "-img\").className==\"addToSearchImage\")document.getElementById(\"" + actors[idx].id + "-img\").style.visibility=\"hidden\";' onclick='removeFromSearchFromRefinement(\"[" + actorID + "]P-search\");'></SPAN>");
					}
				}
				else
				{
					textSpan = document.createElement("SPAN");
					textSpan.setAttributeNode(createAttribute("id",actors[idx].id+"-text"));
					if(highLightedMenuItems["P" + actorID] == null)
					{				
						textSpan.setAttributeNode(createAttribute("onclick","searchFromRefinementTool('"+actors[idx].name+"','People','" + actors[idx].id + "','P');"));
					}
					else
					{
						textSpan.setAttributeNode(createAttribute("onclick","removeFromSearchFromRefinement('[" + actorID + "]P-search');"));
					}
					textSpan.setAttributeNode(createAttribute("onmouseover","document.getElementById('" + actors[idx].id + "-img').style.visibility='visible';"));
					textSpan.setAttributeNode(createAttribute("onmouseout","if (document.getElementById('" + actors[idx].id + "-img').className=='addToSearchImage')document.getElementById('" + actors[idx].id + "-img').style.visibility='hidden';"));
				}
				textSpan.appendChild(document.createTextNode(actors[idx].name));
				
				if(highLightedMenuItems["P" + actorID] == null)
				{				
					addToSearchImg = document.createElement("IMG");
					addToSearchImg.setAttributeNode(createAttribute("class","addToSearchImage"));
					addToSearchImg.setAttributeNode(createAttribute("onclick","searchFromRefinementTool('"+actors[idx].name +"','People','" + actors[idx].id + "','P');"));
					addToSearchImg.setAttributeNode(createAttribute("src", "/images/greenPlus.png"));
					addToSearchImg.setAttributeNode(createAttribute("border","0"));
					addToSearchImg.setAttributeNode(createAttribute("id",actorID + "-img"));
				}
				else
				{
					addToSearchImg = document.createElement("IMG");
					addToSearchImg.setAttributeNode(createAttribute("class","removeFromSearchImage"));
					addToSearchImg.setAttributeNode(createAttribute("onclick","removeFromSearchFromRefinement('[" + actorID + "]P-search');"));
					addToSearchImg.setAttributeNode(createAttribute("src", "/images/redx.png"));
					addToSearchImg.setAttributeNode(createAttribute("border","0"));
					addToSearchImg.setAttributeNode(createAttribute("id",actorID + "-img"));
				}
					actor.setAttributeNode(createAttribute("onmouseover","document.getElementById('" + actors[idx].id + "-img').style.visibility='visible';"));
					actor.setAttributeNode(createAttribute("onmouseout","if (document.getElementById('" + actors[idx].id + "-img').className=='addToSearchImage')document.getElementById('" + actors[idx].id + "-img').style.visibility='hidden';"));
				
				actor.appendChild(textSpan);
				actor.appendChild(addToSearchImg);
				actorsList.appendChild(actor);
			}
			
			mainActors.appendChild(actorsList);
	
		}
		
		if(searchResponseObject.commonDirectorsList!=null && searchResponseObject.commonDirectorsList.length >0)
		{
			if ( document.all )
			{
				var mainDirectors = document.createElement("<LI id='directors' onclick='exposeGenom(\"directorsCategories\",this);' class='cateogryTypeNode'></LI>");
			}
			else
			{
				var mainDirectors = document.createElement("LI");
				//newLI.setAttributeNode(createAttribute("id",tree[idx].name));
				mainDirectors.setAttributeNode(createAttribute("class","cateogryTypeNode"));
				mainDirectors.setAttributeNode(createAttribute("onclick","exposeGenom('directorsCategories',this);"));
				mainDirectors.setAttributeNode(createAttribute("id","directors"));
			}
			mainDirectors.appendChild(document.createTextNode("Directors"));

			if ( document.all )
			{
				element = document.createElement( "<IMG style='cursor:pointer' src='" + imagePath + "arrToBotMenu.png' border='0' />" )
			}		
			else
			{
				element = document.createElement("IMG");
				element.setAttributeNode(createAttribute("style","cursor:pointer"));
				//var method = "exposeGenom(" + tree[cateogyNode].name + "Categories"
				//element.setAttributeNode(createAttribute("onclick","exposeGenom('stars',this);"));
				element.setAttributeNode(createAttribute("src",imagePath + "arrToBotMenu.png"));
				element.setAttributeNode(createAttribute("border","0"));
			}
			
			mainDirectors.appendChild(element);
			mainUL.appendChild(mainDirectors);
	
			if ( document.all )
			{
				var foundDirector = false;
				for(var idx =0; idx < searchResponseObject.commonDirectorsList.length;idx++)
				{
					if ( highLightedMenuItems["P" + searchResponseObject.commonDirectorsList[idx].id] )
					{
						foundDirector = true;
						break;
					}
				}
				if ( foundDirector )
				{
					var directorList = document.createElement("<UL id='directorsCategories' class='menuList'></UL>");
				}
				else
				{
					var directorList = document.createElement("<UL id='directorsCategories' class='menuList' style='height:0'></UL>");
				}
			}				
			else
			{
				var directorList = document.createElement("UL");
				directorList.setAttributeNode(createAttribute("id","directorsCategories"));
				directorList.setAttributeNode(createAttribute("class","menuList"));
				directorList.setAttributeNode(createAttribute("style","height:0"));
			}
			
			for(var idx =0; idx < searchResponseObject.commonDirectorsList.length;idx++)
			{
				var directorID = searchResponseObject.commonDirectorsList[idx].id;
				var directors = searchResponseObject.commonDirectorsList;
				
				if ( document.all )
				{
					if ( highLightedMenuItems["P" + directorID] )
					{
						var director = document.createElement("<LI onclick='event.cancelBubble=true;' id='["+ directors[idx].id +"]P' class='selectedMenu'></LI>");
						mainDirectors.setAttributeNode(createAttribute("class","selectedCategory"));
						expandedNode.push(directorList);
					}
					else
					{
						var director = document.createElement("<LI onclick='event.cancelBubble=true;' id='["+ directors[idx].id +"]P'></LI>");
					}
				}
				else
				{
					var director = document.createElement("LI");
					director.setAttributeNode(createAttribute("class",""));				
					if(highLightedMenuItems["P" + directorID] != null){
						
						mainDirectors.setAttributeNode(createAttribute("class","selectedCategory"));
						directorList.setAttributeNode(createAttribute("style",""));
						director.setAttributeNode(createAttribute("class","selectedMenu"));
						expandedNode.push(directorList);
					}					
					director.setAttributeNode(createAttribute("onclick","event.cancelBubble=true;"));
					director.setAttributeNode(createAttribute("id","["+ directors[idx].id +"]P"));
				}
				
				textSpan = document.createElement("SPAN");
				textSpan.setAttributeNode(createAttribute("id",directors[idx].id+"-text"));
				textSpan.appendChild(document.createTextNode(directors[idx].name));
				if(highLightedMenuItems["P" + directorID] == null)
				{
					textSpan.setAttributeNode(createAttribute("onclick","searchFromRefinementTool('"+directors[idx].name+"','People','" + directors[idx].id + "','P');"));
				}
				else
				{
					textSpan.setAttributeNode(createAttribute("onclick","removeFromSearchFromRefinement('[" + directors[idx].id + "]P-search');"));														
				}
				textSpan.setAttributeNode(createAttribute("onmouseover","document.getElementById('" + directors[idx].id + "-img').style.visibility='visible';"));
				textSpan.setAttributeNode(createAttribute("onmouseout","if (document.getElementById('" + directors[idx].id + "-img').className=='addToSearchImage')document.getElementById('" + directors[idx].id + "-img').style.visibility='hidden';"));

				
				if(highLightedMenuItems["P" + directorID] == null)
				{
					addToSearchImg = document.createElement("IMG");
					addToSearchImg.setAttributeNode(createAttribute("class","addToSearchImage"));
					addToSearchImg.setAttributeNode(createAttribute("onclick","searchFromRefinementTool('"+directors[idx].name +"','People','" + directors[idx].id + "','P');"));														
					addToSearchImg.setAttributeNode(createAttribute("src", "/images/greenPlus.png"));
					addToSearchImg.setAttributeNode(createAttribute("border","0"));
					addToSearchImg.setAttributeNode(createAttribute("id",directors[idx].id + "-img"));
				}
				else
				{
					addToSearchImg = document.createElement("IMG");
					addToSearchImg.setAttributeNode(createAttribute("class","removeFromSearchImage"));
					addToSearchImg.setAttributeNode(createAttribute("onclick","removeFromSearchFromRefinement('[" + directors[idx].id + "]P-search');"));														
					addToSearchImg.setAttributeNode(createAttribute("src", "/images/redx.png"));
					addToSearchImg.setAttributeNode(createAttribute("border","0"));
					addToSearchImg.setAttributeNode(createAttribute("id",directors[idx].id + "-img"));
				}
				director.setAttributeNode(createAttribute("onmouseover","document.getElementById('" + directors[idx].id + "-img').style.visibility='visible';"));
				director.setAttributeNode(createAttribute("onmouseout","if (document.getElementById('" + directors[idx].id + "-img').className=='addToSearchImage')document.getElementById('" + directors[idx].id + "-img').style.visibility='hidden';"));
				
				director.appendChild(textSpan);
				director.appendChild(addToSearchImg);
				directorList.appendChild(director);
			}
			
			mainDirectors.appendChild(directorList);
		}
//	}//end tree.length
	else if(tree==null || tree.length ==0)
	{
		
	}

}

/**
 * move to global
 */
function createAttribute(aName, aValue)
{
	var attr = document.createAttribute(aName);
	attr.nodeValue = aValue;
	
	return attr;
}

function setFilter(filter)
{
	filterName = filter.split("-")[0];
	filterId = filter.split("-")[1];
	
	var filterCode = "[" + filterId + "]FG";
	
	document.getElementById('globalFilter').value = globalFilterType;
	document.getElementById('searchFilter').value = filterCode;
	hide(document.getElementById('type_popup_menu'));
	doSearch();
}

function resetFilterForm()
{
	filterName = null;
	//document.getElementById('globalFilter').value = 'all';
	document.getElementById('searchFilter').value = '';
}
function  resetSort()
{
	collageSort = null;
}

function setCollageSort(sortBy)
{
	
	collageSort = sortBy;
	//displayFilter();
	sortCollage();
	
}
function initStatusLine( similarMovieUniqueName )
{
	searchLiterals = new Array();
	
	var searchTextCopy = document.getElementById("searchInput").value;
	
	// sort the search terms by location.
	searchBoxData.sort( function(a,b){ return a.start - b.start; } );
	
	var inputIndex = 0;
	for ( var i = 0; i < searchBoxData.length; i++ )
	{
		if ( searchBoxData[i].start > inputIndex )
		{
			var searchElementText = searchTextCopy.substring( inputIndex, searchBoxData[i].start );
			if ( !searchElementText.match(/^\s+$/) )
			{
				searchLiterals.push( new searchElement( searchElementText, "" ) );
			}
		}
		
		if ( searchBoxData[i].type != "Similar Titles" )
		{
			searchLiterals.push( new searchElement( searchBoxData[i].displayName, searchBoxData[i].type, searchBoxData[i].itemId ) );
		}
		else
		{
			searchLiterals.push( new searchElement( searchBoxData[i].displayName.substring(5), 
					searchBoxData[i].type, searchBoxData[i].itemId, similarMovieUniqueName ) );
		}
		inputIndex = searchBoxData[i].end + 1;
	}
	if ( inputIndex < searchTextCopy.length )
	{
		searchLiterals.push( new searchElement( searchTextCopy.substring( inputIndex, searchTextCopy.length ), "" ) );
	}

//	var requiredSearch = document.getElementById('txt').childNodes;
//	
//	
//	for(var index=0; index<requiredSearch.length; index++) {
//		
//		if(requiredSearch[index].tagName && requiredSearch[index].tagName.toLowerCase() == 'div')
//		{
//			var theDivElement = requiredSearch[index];
//			var theDivChilds = requiredSearch[index].childNodes;
//			
//			for(var idx=0; idx<theDivChilds.length; idx++) {
//			
//				if( theDivChilds[idx].tagName && theDivChilds[idx].tagName.toLowerCase() == 'span' )
//				{
//					contentName = theDivChilds[idx].className.split("-")[0];
//					contentType = theDivChilds[idx].className.split("-")[1].split("#")[0];
//					contentID = theDivChilds[idx].className.split("-")[1].split("#")[1];
//					searchLiterals.push(new searchElement(contentName,contentType,contentID));
//					break;
//				}
//				
//			}
//			
//		}
//		else if(requiredSearch[index].tagName && requiredSearch[index].tagName.toLowerCase() == 'input' && requiredSearch[index].type == "text")
//		{
//			if(requiredSearch[index].value && trim(requiredSearch[index].value) != "")
//				searchLiterals.push(new searchElement(requiredSearch[index].value,""));
//			
//		}
//	}
}

/**
 * Resets the filters that were selected and refreshes the search results accordingly.
 */
function resetFilterSettings()
{
	resetFilterForm();
	doSearch();
}

/**
 * This function creates the HTML elements that are inserted into the status bar at the Discovery page.
 * The HTML can then be plugged into resultsSummaryBar.
 * 
 * TODO: Delete this, it's for reference only.
 *
 * 			<div id="resultsSummaryFilters">
 *				<span class="filterPrefix"> that are </span>
 *				<span class="filter">In Theaters</span>
 *				<span class="filterReset">(reset)</span>
 *			</div>
 *			<div id="resultsSummaryContent">
 *				<span class="resultsPrefix">Results for: </span>
 *				<span class="similarType">Movies </span>
 *				<span class="similarTo">similar to </span>
 *				<a class="TitleLink" href="#">Terminator</a>
 *				<span class="category"> Killing</span>
 *				<span class="categoryType"> (Theme)</span>      -- This line is now commented out.
 *			</div>
 */
searchResultFuncs.renderResultsSummary = function()
{
	var result = "";
	// Get the active filters
/*	if ( filterName != null )
	{
		result += '<div id="resultsSummaryFilters">' + 
			'<span class="filterPrefix"> that are </span>' + 
			'<span class="filter">' + filterName + '</span>' + 
				'<span class="filterReset" onclick="resetFilterSettings();"> (reset)</span>' +
			'</div>';
	}*/
	
	// Create the summary content
	result += '<div id="resultsSummaryContent" class="resultsSummaryContent';
	if ( filterName != null )
	{
		result += 'Narrow'; 
	}
	else
	{
		result += 'Full';
	}
	result += '">' + 
		'<span id="numOfResults"></span>'+
		'<span class="resultsPrefix">Results for: </span>';
		
	// Add similar-to if there is any
	var similarIncluded = false;
	for ( var i = 0; i < searchLiterals.length; i++ )
	{
		if ( searchLiterals[i].type == "Similar Titles" )
		{
			
			similarIncluded = true;
			result += '<span class="similarType">';
			if ( globalFilterType == null || globalFilterType == 'all' )
			{
				result += "Titles ";
			}
			else if ( globalFilterType == 'FeatureFilm' )
			{
				result += "Movies ";
			}
			else if ( globalFilterType == 'DVD' )
			{
				result += "DVD ";
			}
			else if ( globalFilterType == 'TvSeries' )
			{
				result += "TV shows ";
			}
			else if ( globalFilterType == 'ShortFilm' )
			{
				result += "Shorts ";
			}
			else
			{
				result += "Online videos ";
			}
			result += '</span>';
			result += '<span class="similarTo">like </span>';
			result += '<a class="TitleLink" href="#" onclick="location.href=\'/movies/' + searchLiterals[i].url + '\';">'+
				searchLiterals[i].title + '</a>';	
//			result += searchLiterals[i].title;	
			
			break;
		}
	}
	// Add search terms
	var searchTermAdded = false;
	for ( var i = 0; i < searchLiterals.length; i++ )
	{
		if ( searchLiterals[i].type != "Similar Titles" && searchLiterals[i].type != "" )
		{
			if ( similarIncluded || searchTermAdded )
			{
				result += '<span class="comma">,</span> ';
			}
			result += '<span class="category">' + searchLiterals[i].title + '</span>';
			result += '<span class="categoryType"> (' + searchLiterals[i].type + ')</span>';
			searchTermAdded = true;
		}
	}
	
	
	

	
	
	
	
	result += '<ul id="discoveryPaging"><li id="topBackLink">&lt;&lt;Back</li><li id="divider">|</li><li id="topNextLink">Next&gt;&gt;</li></ul>';
	// Add user entered literals
	for ( var i = 0; i < searchLiterals.length; i++ )
	{
		if ( searchLiterals[i].type == "" )
		{
			if ( similarIncluded || searchTermAdded )
			{
				result += '<span class="comma">,</span> ';
			}
			result += '<span class="category">' + searchLiterals[i].title + '</span>';
		}
	}	
	

//		result += 	"<div 	class='discoveryShare' 	onlick=''  >" +
//						"<span class='label'> Share Search:</span" +
//						"<span 	class='share envelop' 			onclick='shareModule.email();' ></span>" +
//						"<span 	class='share share-link-icon' 	onclick='shareModule.shareLink();' ></span>" +
//					"</div>"
			
	


	result += '</div>';
	
	return result;
}

searchResultFuncs.getSimilarityTitleName = function()
{
	for ( var i = 0; i < searchLiterals.length; i++ )
	{
		if ( searchLiterals[i].type == "Similar Titles" )
		{
			return searchLiterals[i].title;
		}
	}
}

/**
 * Event handler for the focus event of the search box.
 */
function searchboxFilters()
{
	var inputItem = document.getElementById('searchInput');
	if ( searchBoxHasFocus )
	{
		return;
	}
	
	if ( searchTypeDropState == 1 )
	{
		if ( prevGlobalFilterType != null && isAnythingInSearchBox())
		{
			return;
			/*switch (prevGlobalFilterType)
			{
				case "all":
					if ( inputItem.value != SEARCH_WELCOME ) return;
					break;
				case "FeatureFilm":
					if ( inputItem.value != SEARCH_MOVIES ) return;
					break;
				case "DVD":
					if ( inputItem.value != SEARCH_DVD ) return;
					break;
				case "TvSeries":
					if ( inputItem.value != SEARCH_TV ) return;
					break;
				case "ShortFilm":
					if ( inputItem.value != SEARCH_SHORTS ) return;
					break;
				case "online":
					if ( inputItem.value != SEARCH_ONLINE ) return;
					break;
			}*/
		}
		if ( globalFilterType == "all" ){
			inputItem.value = SEARCH_WELCOME;
		}
		if ( globalFilterType == "FeatureFilm" ){
			inputItem.value = SEARCH_MOVIES;
		}
		if ( globalFilterType == "DVD" ){
			inputItem.value = SEARCH_DVD;
		}
		if ( globalFilterType == "TvSeries" ){
			inputItem.value = SEARCH_TV;
		}
		if ( globalFilterType == "ShortFilm" ){
			inputItem.value = SEARCH_SHORTS;
		}
		if ( globalFilterType == "online" ){
			inputItem.value = SEARCH_ONLINE;
		}
	}
	else
	{
		if ( prevGlobalFilterType != null && inputItem.value == SEARCH_TITLES )
		{
			return;
		}
		else
		{
			switch( globalFilterType )
			{
				case "all":
					inputItem.value = SEARCH_TITLES;
					break;
				case "FeatureFilm":
					inputItem.value = SEARCH_TITLES;
					break;
				case "DVD":
					inputItem.value = SEARCH_TITLES;
					break;
				case "TvSeries":
					inputItem.value = SEARCH_TITLES;
					break;
				case "ShortFilm":
					inputItem.value = SEARCH_TITLES;
					break;
				case "online":
					inputItem.value = SEARCH_TITLES;
					break;
			}
		}
	}
	
	// Set color in case of default text.
	if ( inputItem.value == SEARCH_WELCOME || inputItem.value == SEARCH_MOVIES || inputItem.value == SEARCH_DVD || inputItem.value == SEARCH_TV ||
		 inputItem.value == SEARCH_SHORTS || inputItem.value == SEARCH_ONLINE )
	{
		inputItem.style.color = "#666666";
	}
}
searchFuncs.onfocus = function( e )
{
	searchBoxHasFocus = true;
	clearWelcomeMessage();
//	if ( document.getElementById( "searchInput" ).value == SEARCH_WELCOME )
//	{
//		// Default text. Delete it.
//		document.getElementById( "searchInput" ).value = "";
//	}
//	else if ( document.getElementById( "searchInput" ).value == SEARCH_MOVIES )
//	{
//		// Default text. Delete it.
//		document.getElementById( "searchInput" ).value = "";
//	}
//	else if ( document.getElementById( "searchInput" ).value == SEARCH_DVD )
//	{
//		// Default text. Delete it.
//		document.getElementById( "searchInput" ).value = "";
//	}
//	else if ( document.getElementById( "searchInput" ).value == SEARCH_TV )
//	{
//		// Default text. Delete it.
//		document.getElementById( "searchInput" ).value = "";
//	}
//	else if ( document.getElementById( "searchInput" ).value == SEARCH_SHORTS )
//	{
//		// Default text. Delete it.
//		document.getElementById( "searchInput" ).value = "";
//	}
//	else if ( document.getElementById( "searchInput" ).value == SEARCH_ONLINE )
//	{
//		// Default text. Delete it.
//		document.getElementById( "searchInput" ).value = "";
//	}
//	document.getElementById( "searchInput" ).style.color = "black";
}

searchFuncs.onblur = function( e )
{
	searchBoxHasFocus = false;
	if ( document.getElementById( "searchInput" ).value == "" )
	{
		 searchboxFilters();
	}
	if ( searchBoxController.activeSearchBox )
	{
		searchBoxController.activeSearchBox.closeSuggestionPanelDelay();	
	}
}	

// Opens the search type drop down for selection.
searchFuncs.openSearchTypeDrop = function( e )
{
	var drop = document.getElementById( "searchTypeDropdown" );
	var over = document.getElementById( "searchTypeDropdownOver" );
	if ( document.all )
	{
		if ( document.getElementById("searchForm").className == "normal" )
		{
			if ( BrowserDetect.version == 6 )
			{
				over.style.left = getPosX( drop ) + 0 + "px";
			}
			else
			{
				over.style.left = getPosX( drop ) + 0 + "px";
			}
		}
		else
		{
			over.style.left = getPosX( drop ) + 0 + "px";
		}
		over.style.top = getPosY( drop ) + 5 + "px";			
	}
	else
	{
		if ( document.getElementById("searchForm").className == "normal" )
		{
			over.style.left = getPosX( drop ) + 0 + "px";
		}
		else
		{
			over.style.left = getPosX( drop ) + 0 + "px";
		}
		over.style.top = getPosY( drop ) + "px";
	}
	over.style.display = "block";
}

searchFuncs.closeSearchTypeDrop = function()
{
	document.getElementById( "searchTypeDropdownOver" ).style.display = "none";
}

// Sets the search type from the drop down and closes the menu.
searchFuncs.setSearchType = function( e, searchType )
{
	if ( searchType == 1 )
	{
		document.getElementById("searchTypeDropdown").innerHTML = "content";
	}
	else if ( searchType == 2 )
	{
		document.getElementById("searchTypeDropdown").innerHTML = "titles";
	}
	else
	{
		return;
	}
	
	searchTypeDropState = searchType;
	searchboxFilters();
	searchFuncs.closeSearchTypeDrop();
}

searchFuncs.onkeydown = function( e )
{
	// This is an IE fix, since the idiots aren't sending arrow-key presses to onkeypress. *sigh*
	if ( document.all )
	{
		var key = getKeyboard( e );
		if ( key == 38 || key == 40 || key == 8 )
		{
			searchFuncs.onkeypress( e );
		}
	}
}

/**
 * This event handler is responsible for all interaction with the keyboard on the search bar.
 */
searchFuncs.onkeypress = function( e )
{
	var searchInputCtrl = document.getElementById( "searchInput" );
	searchBoxController.activeSearchBox = mainSearchBox;
	var key = getKeyboard( e );
	var previousIndex = null;
	var selectedSuggestionMovieName = null;
	
	if ( key == 13 ) // Enter - if suggest is open, add it and search. Otherwise, just search.
	{
		// If the search text begins with "Like:" then we need to make sure the search is sent 
		// as meaning and not title.
		if ( searchInputCtrl.value.match( /^like:/i ) )
		{
			searchFuncs.setSearchType( 1 ); // 1 = meaning (and not titles)
		}
		
		// If the suggestiong box is open and one of the suggestions is highlighted, add it to 
		// the search before submiting.
		if ( searchBoxController.activeSearchBox.sb_selectedSuggestionIndex != null )
		{
			addSuggestionToSearchBox();
		}
		searchBoxController.activeSearchBox.closeSuggestionPanel();
		if ( searchInputCtrl.value.match( /^like:/i ) )
		{
			doSearch(); //TODO change this to findSimilarClick( moviename )
		}
		else
		{
			doSearch();
		}
	}
	else if ( key == 27 ) // Escape - if suggest is open, close it.
	{
		searchBoxController.activeSearchBox.sb_selectedSuggestionIndex = null;
		searchBoxController.activeSearchBox.closeSuggestionPanel();
	}
	else if ( key == 38 || key == 40 ) // up/down arrows
	{
		if ( key == 38 ) // up arrow - if suggest is open move in it.
		{
			if(searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes.length == 0) return true;
			if(searchBoxController.activeSearchBox.sb_selectedSuggestionIndex == null)
				searchBoxController.activeSearchBox.sb_selectedSuggestionIndex = searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes.length-1;
			else
			{
				previousIndex = searchBoxController.activeSearchBox.sb_selectedSuggestionIndex;
				if(previousIndex ==0) searchBoxController.activeSearchBox.sb_selectedSuggestionIndex = searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes.length;
				searchBoxController.activeSearchBox.sb_selectedSuggestionIndex = (searchBoxController.activeSearchBox.sb_selectedSuggestionIndex - 1)%searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes.length;
			}
		}
		
		if ( key == 40 ) // down arrow - if suggest is open move in it.
		{
			if(searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes.length == 0) return true;
			if(searchBoxController.activeSearchBox.sb_selectedSuggestionIndex == null)
				searchBoxController.activeSearchBox.sb_selectedSuggestionIndex = 0;
			else
			{	
				previousIndex = searchBoxController.activeSearchBox.sb_selectedSuggestionIndex;
				searchBoxController.activeSearchBox.sb_selectedSuggestionIndex = (searchBoxController.activeSearchBox.sb_selectedSuggestionIndex + 1)%searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes.length;
			}
		}

		searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes[searchBoxController.activeSearchBox.sb_selectedSuggestionIndex].style.backgroundColor = 
				searchBoxController.activeSearchBox.sb_selectedSuggestionColor;
		if( previousIndex != null )
		{
			searchBoxController.activeSearchBox.sb_suggestionsPanel.childNodes[previousIndex].style.backgroundColor = 
				searchBoxController.activeSearchBox.sb_notSelectedSuggestionColor;
		}
		
	}
	else // any other key
	{
		// First, find where the last search-term (not user typed) ends.
		var lastTermEnd = 0;
		for ( var i = 0; i < searchBoxData.length; i++ )
		{
			if ( searchBoxData[i].end > lastTermEnd )
			{
				lastTermEnd = searchBoxData[i].end;
			}
		}
		
		// Now check if the caret position is after the last search term.
		var afterLast = false;
		var caretPos = getCaretPosition( searchInputCtrl );
		if ( caretPos.start > lastTermEnd )
		{
			afterLast = true;
		}
				
		// Keyboard analysis of changes to the input box
		// ---------------------------------------------
		
		if ( afterLast == false )
		{
			// First, check if the change is made inside a search term, if so change it to free text.
			// Note, that there could be a change in more than one term. Also, if a term was deleted, remove it.
			for ( var i = 0; i < searchBoxData.length; i++ )
			{
				if ( caretPos.start > searchBoxData[i].start && caretPos.start <= searchBoxData[i].end ||
					 caretPos.end > searchBoxData[i].start && caretPos.end <= searchBoxData[i].end ||
					 caretPos.start <= searchBoxData[i].start && caretPos.end > searchBoxData[i].end )
				{
						
					// And update the view.
					var elem = document.getElementById( searchBoxData[i].itemId );
					if ( elem )
					{
						elem.className = "";
						elem.onclick = "searchFromRefinementTool('" + elem.parentNode.parentNode.id + 
									"', '" + elem.parentNode.id +	"', '" + searchBoxData[i].itemId + "', 'G');"
					} 
					var plusSign = document.getElementById( searchBoxData[i].itemId.substring(1, searchBoxData[i].itemId.indexOf("]")) + "-img" );
					if ( plusSign )
					{
						plusSign.style.visibility = "hidden";
						plusSign.className = "addToSearchImage";
						plusSign.src = "/images/greenPlus.png";
					}
					
					searchBoxData.splice(i,1); // remove the element, renumbering the rest
				}
			}
		}
	}
}

searchFuncs.onkeyup = function( e )
{
	if ( document.selection )
	{
		currentSelectionRange = document.selection.createRange();
	}
	var searchInputCtrl = document.getElementById( "searchInput" );
	searchBoxController.activeSearchBox = mainSearchBox;
	var key = getKeyboard( e );
	
	var newIndex = 0;
	
	for ( var i = 0; i < searchBoxData.length; i++ )
	{
		// Since the term might have moved, find and relocate it.
		newIndex = searchInputCtrl.value.toLowerCase().indexOf( searchBoxData[i].displayName.toLowerCase() );
		if ( newIndex == -1 )
		{
			// we missed it being altered, now remove it.
			searchBoxData.splice(i,1);
		}
		else
		{
			// check if the location changed, if so update it.
			if ( searchBoxData[i].start != newIndex )
			{
				searchBoxData[i].start = newIndex;
				searchBoxData[i].end = newIndex + searchBoxData[i].displayName.length; 
			}
		}
	}

	// First, find where the last search-term (not user typed) ends.
	var lastTermEnd = 0;
	for ( var i = 0; i < searchBoxData.length; i++ )
	{
		if ( searchBoxData[i].end > lastTermEnd )
		{
			lastTermEnd = searchBoxData[i].end;
		}
	}
	
	// Now check if the caret position is after the last search term.
	var afterLast = false;
	var caretPos = getCaretPosition( searchInputCtrl );
	if ( caretPos.start > lastTermEnd )
	{
		afterLast = true;
	}

	// get the last user typed text.
	var userEnteredStr = null;
	var isUserEnteredSimilar = false;
	if ( searchBoxData.length > 0 )
	{
		userEnteredStr = searchInputCtrl.value.substring( lastTermEnd + 1, searchInputCtrl.value.length );
	}
	else
	{
		if ( searchInputCtrl.value.match(/^like:/i) )
		{
			userEnteredStr = searchInputCtrl.value.substring( 5 );
			isUserEnteredSimilar = true;
		}
		else
		{
			userEnteredStr = searchInputCtrl.value;
		}
	}
	
	// Check that we are on the last text and that it is at least 3 characters long
	if ( key > 32 && key < 37 || key > 40 || key == 8 )
	{
		if ( afterLast == true )
		{
			if ( userEnteredStr.length > 2 )
			{
				// Run the suggestion search and show the suggestion box.
				
				searchBoxController.activeSearchBox.sb_searchTerm = userEnteredStr;
				if ( searchTypeDropState == 1 ) // by meaning
				{
					if ( isUserEnteredSimilar )
					{
						findTitleSuggestions();
					}
					else
					{	window.clearTimeout( searchBoxAtt.typingTimeout );
						if( userEnteredStr.length > 3 )
							searchBoxAtt.typingTimeout = window.setTimeout("findSuggestions()", 400);
						else
							findSuggestions();
					}
				}
				else if ( searchTypeDropState == 2 ) // by title
				{
					window.clearTimeout( searchBoxAtt.typingTimeout );
					if( userEnteredStr.length > 3 )
						searchBoxAtt.typingTimeout = window.setTimeout("findSuggestions()", 400);
					else
						findTitleSuggestions();
				}
				else
				{
					throw "Unsupported searchTypeDropState: " + searchTypeDropState;
				}
			}
			else
			{
				// hide the suggestion if it's open
				searchBoxController.activeSearchBox.closeSuggestionPanel();
			}
		}
	}
}
	
/**
 * This function goes over the terms in the search and finds their updated location on the search input line.
 */
searchFuncs.relocateSearchTerms = function()
{
	var inputStr = document.getElementById("searchInput").value;
	inputStr = inputStr.toLowerCase();
	var index = -1;
	
	for ( var i = 0; i < searchBoxData.length; i++ )
	{	 
		index = inputStr.indexOf( searchBoxData[i].displayName.toLowerCase() );
		if ( index != -1 )
		{
			searchBoxData[i].start = index;
			searchBoxData[i].end = index + searchBoxData[i].displayName.length;
		}
	}
}

/**** see search examples ****/


function goScroll(){
	coords = 0;
	Int = self.setInterval("myScroll()",10);
}

function myScroll()
{
	var pixels = 720;
	if( document.getElementById('homePageInfo') == undefined )
	 pixels = 650;
	
	if ( coords <= pixels )
	{
		window.scroll(0,coords);
		coords+=10;
		return;
	}
	else
	{
		Int = clearInterval(Int);
	}
}

// the gene search in the content page

function searchByMovieGene(geneName,geneGroup,geneId,code)
{

	addToSearchBox(geneName, geneGroup, geneId, code)
	doSearch();

}

/*  */