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 suggestFilter = {contentTypeFilter: null, onlineContentFilter: false, dvdContentFilter: false, theaterContentFilter: false, contentAffiliates: [] }
//===========================================
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 = "*";

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('searchInput');
	favoriteSearchBox.sb_searchBox = document.getElementById('favoriteBox');
	
	
	mainSearchBox.sb_suggestionsPanel = document.getElementById('suggestionsPanel');
	discoverySearchBox.sb_suggestionsPanel = document.getElementById('suggestionsPanel');
	
	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('topSearchHigh')) + 35 +"px";
		discoverySearchBox.sb_suggestionsPanel.style.top  = getPosY(document.getElementById('topSearchHigh')) + 52 + "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: "; // move this code to addToSearchFromSuggestion()
			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;
			}
			
			var auditTextSearch = userEnteredStr;
			document.getElementById('auditTextSearch').value = auditTextSearch;
			
			// 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;
	if ( suggestFilter.contentTypeFilter != null && suggestFilter.contentTypeFilter == '')
	{
		suggestFilter.contentTypeFilter = null;
	}
	AjaxController.findSuggestionsWithFilters( searchBoxController.activeSearchBox.sb_searchTerm, suggestFilter, searchBoxController.activeSearchBox.showSuggestions );
}


function findTitleSuggestions()
{
	searchBoxController.activeSearchBox.sb_selectedSuggestionIndex = null;
	if ( suggestFilter.contentTypeFilter != null && suggestFilter.contentTypeFilter == '')
	{
		suggestFilter.contentTypeFilter = null;
	}
	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;
	}
	
	var auditSuggestions = '';
	
	/* 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;
		
		var auditSuggestion = '<' + name + '>[' + id + ']';
		
		switch( results[i].entityType )
		{
			case "Title":
				if ( isSimilarityTitleSearch )
				{
					suggestionsMap[id + "_" + name] = "TS";
					auditSuggestion += 'TS';
				}
				else
				{
					suggestionsMap[id + "_" + name] = "T";
					auditSuggestion += 'T';
				}
				break;
			case "Person":
				suggestionsMap[id + "_" + name] = "P";
				auditSuggestion += 'P';
				break;
			case "Category":
				suggestionsMap[id + "_" + name] = "G";
				auditSuggestion += 'G';
				entityType = results[i].categoryType;
				break;
			case "CategorySynonym":
				suggestionsMap[id + "_" + name] = "GS";
				auditSuggestion += 'GS';
				entityType = results[i].categoryType;
				break;
		}
		
		auditSuggestions += auditSuggestion;
		if (i < results.length -1) {
			auditSuggestions += '@#@';
		}
		
		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 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){}
	}
	
	document.getElementById('auditSuggestions').value = auditSuggestions;
	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);
	var cbLoadingAnimation;
	var currentLocation = '' + document.location;
	if (currentLocation.indexOf('/discovery.html') != -1) {
		cbLoadingAnimation = discoveryLoadingAnimation;
	} else {
		cbLoadingAnimation = homepageLoadingAnimation;
	}
	doSearch(cbLoadingAnimation);
}

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, true);
}

function addToSearchFromCloud(searchPhrase, type, id, code){
	addToSearchBox(searchPhrase.decode(), type, id, code);
	doSearch();
	
}

function searchFromTasteScales()
{
	var obscure = -1;
	var serious = -1;
	var fantastic = -1;
	var fast = -1;
	
	var stringValues = "";
	
	if(sliderOB.sliderEnabled == true)
	{
		obscure = Math.floor(sliderOB.sliderValue);
	}
	stringValues += obscure + ",";
	
	if(sliderSE.sliderEnabled == true) 
	{
		serious = Math.floor(sliderSE.sliderValue);
	}
	stringValues += serious + ",";
	
	if(sliderFN.sliderEnabled == true) 
	{
		fantastic = Math.floor(sliderFN.sliderValue);
	}
	stringValues += fantastic + ",";
	
	if(sliderSP.sliderEnabled == true) 
	{
		fast = Math.floor(sliderSP.sliderValue);
	}
	stringValues += fast;
	
	document.getElementById('tunersInput').value = stringValues;

	hideTasteFilters();
	doSearch(discoveryLoadingAnimation);
}

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);
	var auditCode = code;
	var name = searchPhrase.decode();
	if (suggestionsMap && suggestionsMap[id + "_" + name]) {
		auditCode = suggestionsMap[id + "_" + name];
	} 
	
	var auditSelected = '[' + id + ']' + auditCode;
	document.getElementById('auditSelected').value = auditSelected;
	
	// special adjustment to support 'like:' searches
	var searchInputCtrl = document.getElementById( "searchInput" );
	if ( searchInputCtrl.value.match(/^like:/i) && searchBoxData.length == 0 ) {
		var sbText = searchInputCtrl.value.toLowerCase();
		sbText = sbText.substring("like:".length);
		var likePrefix = '';
		for (var i=0;i<sbText.length;i++) {
			if (sbText[i] != ' ') {
				likePrefix = searchInputCtrl.value.substring(0, "like:".length+i);
				break;
			}
		}
		searchPhrase = likePrefix + searchPhrase;
		searchInputCtrl.value = "";
	}
	
	addToSearchBox(searchPhrase, type, id, auditCode);
}

/***
 * This variable is used to store the real status of the search box (there are cases where we don't want
 * to remove fields from the input but we need them in order to continue the calculation of the search phrase)
 * e.g. when removing an element in the refinement tool - we don't want to show it on the input field (it will be reflected after server response)
 * but we want to calculate the search phrase correctly) 
 */
var searchBoxStatus;

/**
 * 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, keepCaretPosition)
{
	if ((typeof keepCaretPosition == 'undefined' || keepCaretPosition == false) && navigator.appName == 'Microsoft Internet Explorer') {
		currentSelectionRange = null;
	}
	
	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 addPhraseToSearchBox(searchPhrase, type, id, code) {

	searchPhrase = searchPhrase.decode();	
	clearWelcomeMessage();
	
	var objID = null;
	var searchName = null;
	var searchCategory = null;
	
	searchName = searchPhrase;
	if (searchName.charAt(searchName.length-1) != ' ') {
		searchName  = searchName + ' ';
	}
	
	// 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 don't add it
	for ( var i = 0; i < searchBoxData.length; i++ )
	{
		if ( searchBoxData[i].itemId == searchCode )
		{
			return;
		}
	}
	
	var box = document.getElementById( "searchInput" );
	
	var start = box.value.length;
	var end = box.value.length + searchName.length -1;
	
	box.value = box.value + searchName.toLowerCase();
	box.style.color = "black";
	
	var searchEntry = new SearchBoxDataEntry();
	searchEntry.displayName = searchPhrase;
	searchEntry.start = start;
	searchEntry.end = end;
	searchEntry.itemId = searchCode;
	searchEntry.type = type;
	searchBoxData.push( searchEntry );
}

function addFreeTextToSearchBox(text) {
	var box = document.getElementById("searchInput");
	var currentInSB = box.value;
	if (text.charAt(text.length-1) != ' ') {
		text = text + ' ';
	}
	box.value = currentInSB + text;
}

function showDiscoveryButton()
{
	document.getElementById('discoversearch').style.display = "block";
}
function hideDiscoveryButton()
{
	try{
	document.getElementById('discoversearch').style.display = "none";
	}catch(e){}
}

function removeFromSearch(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 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 */

var currentFilterType = "";

function filterSearchResults(menuItem)
{
	if(!menuItem) return;

	//change the input hidden field and submit the form
	var filter = menuItem.id.substring(0, menuItem.id.indexOf('_'));
	document.getElementById('contentTypeField').value = filter;
	
	menuItem.className = "typeHighlight menuLink";
	document.getElementById(currentFilterType).className = "menuLink";
	
	suggestFilter.onlineContentFilter = false;
	
	if (!isAnythingInSearchBox()) {
		if (filter == "All") {
			document.getElementById('searchInput').value = SEARCH_WELCOME;
		} else if (filter == "Movies") {
			document.getElementById('searchInput').value = SEARCH_MOVIES;
			suggestFilter.contentTypeFilter = 'FeatureFilm';
		} else if (filter == "TV") {
			document.getElementById('searchInput').value = SEARCH_TV;
			suggestFilter.contentTypeFilter = 'TvSeries';
		} else if (filter == "Shorts") {
			document.getElementById('searchInput').value = SEARCH_SHORTS;
			suggestFilter.contentTypeFilter = 'ShortFilm';
		} else if (filter == "FreeOnline") {
			document.getElementById('searchInput').value = SEARCH_ONLINE;
			suggestFilter.onlineContentFilter = true;
		}
	}
	
	currentFilterType = menuItem.id; 
	
	doSearch();
	
	return true;
}

function refreshSearchLinksInCollage(menuItem) {
	if(!menuItem) return;
	
	var curfilter = currentFilterType.substring(0, currentFilterType.indexOf('_'));
	var newfilter = menuItem.id.substring(0, menuItem.id.indexOf('_'));
	
	try {
		var links = document.getElementById('collageSet').getElementsByTagName('a');
		var curLink = curfilter + "_Content_collageLink";
		var newLink = newfilter + "_Content_collageLink";
		for(var i=0; i<links.length; i++) {
			var link = links[i];
			if (link.id.indexOf(curfilter) != -1) {
				link.style.display = 'none';
			}
			if (link.id.indexOf(newfilter) != -1) {
				link.style.display = '';
			}
		}
		
		var changeLink = function(link) {
			if (newfilter == 'All') {
				link.href = link.href.substring(0, link.href.indexOf('&contentType=')); // for All don't display a link
			} else {
				if (curfilter == 'All') {
					if (link.innerHTML == 'All Topics') {
						link.href = link.href + 'home.html?contentType=' + newfilter;
					} else {
						link.href = link.href + '&contentType=' + newfilter;
					}
				} else {
					var replaceLink = 'contentType=' + curfilter;
					var replaceWith = 'contentType=' + newfilter;
					link.href = link.href.replace(replaceLink, replaceWith);
				}
			}
		}
		
		links = document.getElementById('HomePageLeftMenuTopics').getElementsByTagName('a');
		for(var i=0; i<links.length; i++) {
			changeLink(links[i]);
		}
		
	} catch(e) {alert('refresh failed: ' + e.description);}	
}

function refreshAllTopicsLink(menuItem) {
	if(!menuItem) return;
	
	var curfilter = currentFilterType.substring(0, currentFilterType.indexOf('_'));
	var newfilter = menuItem.id.substring(0, menuItem.id.indexOf('_'));
	
	if (curfilter == newfilter) return;
	
	var changeLink = function(link) {
		if (newfilter == 'All') {
			link.href = link.href.substring(0, link.href.indexOf('&contentType=')); // for All don't display a link
		} else {
			if (curfilter == 'All') {
				link.href = link.href + '&contentType=' + newfilter;
			} else {
				var replaceLink = 'contentType=' + curfilter;
				var replaceWith = 'contentType=' + newfilter;
				link.href = link.href.replace(replaceLink, replaceWith);
			}
		}
	}
	
	try {
		var links = document.getElementById('collageSet').getElementsByTagName('a');
		for(var i=0; i<links.length; i++) {
			changeLink(links[i]);
		}
		links = document.getElementById('HomePageLeftMenuTopics').getElementsByTagName('a');
		for(var i=0; i<links.length; i++) {
			changeLink(links[i]);
		}
	} catch(e) {alert('refresh failed: ' + e.description);}	
}

/* */

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;

		var mainUL = document.createElement("UL");
		mainUL.setAttributeNode(createAttribute("class","tree"));
		refToolRoot.appendChild(mainUL);

		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' alt='jinni' />" );
			}
			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)
				{				
						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", "http://media.jinni.com/images/greenPlus.png"));
						addToSearchImg.setAttributeNode(createAttribute("border","0"));
						addToSearchImg.setAttributeNode(createAttribute("id",genomID + "-img"));
					genom.appendChild(addToSearchImg);
				}
				else
				{
						var addToSearchImg = document.createElement("IMG");
						addToSearchImg.setAttributeNode(createAttribute("class","removeFromSearchImage"));
						addToSearchImg.setAttributeNode(createAttribute("onclick","removeFromSearchFromRefinement('[" + genomID + "]G-search');"));
						addToSearchImg.setAttributeNode(createAttribute("src", "http://media.jinni.com/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);
		}	

		
		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' alt='jinni' />")
			}	
			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", "http://media.jinni.com/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", "http://media.jinni.com/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' alt='jinni' />" )
			}		
			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", "http://media.jinni.com/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", "http://media.jinni.com/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 ), "" ) );
	}
}

searchResultFuncs.getSimilarityInfo = function() {
	for ( var i = 0; i < searchBoxData.length; i++ )
	{
		if ( searchBoxData[i].type == "Similar Titles" )
		{
			var id = searchBoxData[i].itemId.substring(1, searchBoxData[i].itemId.indexOf(']TS'));
			var title = searchBoxData[i].displayName.substring(searchBoxData[i].displayName.indexOf('like: ') + 'like: '.length); 
			return {id: id, title: title};
		}
	}
}

searchResultFuncs.getSimilarityTitleName = function()
{
	for ( var i = 0; i < searchBoxData.length; i++ )
	{
		if ( searchBoxData[i].type == "Similar Titles" )
		{
			return searchBoxData[i].displayName.substring(searchBoxData[i].displayName.indexOf('like: ') + 'like: '.length);
		}
	}
}

searchFuncs.onfocus = function( e )
{
	searchBoxHasFocus = true;
	clearWelcomeMessage();
}

searchFuncs.onblur = function( e )
{
	searchBoxHasFocus = false;
	if (document.getElementById( "searchInput" ).value == "")
	{
		 searchboxFilters();
	}
	if (searchBoxController.activeSearchBox)
	{
		searchBoxController.activeSearchBox.closeSuggestionPanelDelay();	
	}
}	

/**
 * 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 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();
		
		var cbLoadingAnimation;
		var locationpath = document.location.pathname;
		var reducedpath = (locationpath.indexOf('https://') != -1 ? locationpath.substring('https://'.length) : locationpath.substring('http://'.length));
		if (locationpath.indexOf('/discovery.html') != -1 || locationpath.indexOf('/home.html') != -1 || (reducedpath.indexOf("/") == reducedpath.lastIndexOf("/") && reducedpath.indexOf("/") == reducedpath.length-1)) {
			//if we come from discovery or home page - show the discovery loading animation.
			//in case of home page it might be /home.html... or just ending with / - in that case we check that there is only one /
			cbLoadingAnimation = discoveryLoadingAnimation;
		} else {
			cbLoadingAnimation = searchLoadingAnimation;
		}
		doSearch(cbLoadingAnimation);
	}
	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 = "http://media.jinni.com/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(byGeneLoadingAnimation);
}

function registerAffiliate(obj) {
	var affiliateName = obj.id.substring(0, obj.id.indexOf('FilterCheckbox'));
	var affiliatesField = document.getElementById('affiliatesField');
	if (obj.checked) {
		if (affiliatesField.value.length == 0) {
			affiliatesField.value = affiliateName;
		} else {
			affiliatesField.value = affiliatesField.value + "," + affiliateName;
		}
		if (obj.id == "NetflixFilterCheckbox") {
			if (currentFilterType == "Shorts_Filter") {
				filterSearchResults(document.getElementById('All_Filter'));
			}
			document.getElementById('Shorts_Filter').className = "unavailableLink";
			document.getElementById('FreeOnline_Filter').innerHTML = "Watch Instantly"; 
		}
		var affiliate = obj.getAttribute('affiliate');
		suggestFilter.contentAffiliates.push(affiliate);
	} else {
		affiliatesField.value = "";
		if (obj.id == "NetflixFilterCheckbox") {
			document.getElementById('FreeOnline_Filter').innerHTML = "Free Online";
			document.getElementById('Shorts_Filter').className = "menuLink";
			document.getElementById('Shorts_Filter').onclick = function() { filterSearchResults(this); };
		}
		suggestFilter.contentAffiliates.pop();
	}
	if (!isAnythingInSearchBox()) {
		var affiliates = affiliatesField.value;
		AjaxController.setAffiliates(affiliates, null);
	}
	doSearch(discoveryLoadingAnimation);
}

function searchboxFilters() {
	var inputItem = document.getElementById('searchInput');
	if (searchBoxHasFocus) return;
	var filter = currentFilterType.substring(0, currentFilterType.indexOf('_'));
	if (!isAnythingInSearchBox()) {
		if (filter == "All") {
			document.getElementById('searchInput').value = SEARCH_WELCOME;
			document.getElementById('searchInput').style.color = "#666666";
		} else if (filter == "Movies") {
			document.getElementById('searchInput').value = SEARCH_MOVIES;
			document.getElementById('searchInput').style.color = "#666666";
		} else if (filter == "TV") {
			document.getElementById('searchInput').value = SEARCH_TV;
			document.getElementById('searchInput').style.color = "#666666";
		} else if (filter == "Shorts") {
			document.getElementById('searchInput').value = SEARCH_SHORTS;
			document.getElementById('searchInput').style.color = "#666666";
		} else if (filter == "FreeOnline") {
			document.getElementById('searchInput').value = SEARCH_ONLINE;
			document.getElementById('searchInput').style.color = "#666666";
		}
	}
}

function searchLoadingAnimation() {
	var loadingdiv = document.getElementById('loadingResults_searchBox');
	loadingdiv.style.display = 'block';
	var animation = document.getElementById('bg_animation_search');
	animation.style.display = 'block';	
	animation.style.backgroundImage = 'url(/images/loadingResults_white_areas/ajax-loader-snake.gif)';
}

function discoveryLoadingAnimation() {
	var loadingdiv = document.getElementById('loadingResults_discoveryPage');
	loadingdiv.style.display = 'block';	
	if(navigator.appName.indexOf = ('Microsoft Internet Explorer') != -1){
		document.getElementById('animation_img_discoveryPage').style.display = 'none';
		
		var animation = document.getElementById('bg_animation_discoveryPage');
		animation.style.display = 'block';	
		animation.style.backgroundImage = 'url(/images/loadingResults_white_areas/ajax-loader-big_snake.gif)';
	}else{
		document.getElementById('animation_img_discoveryPage').style.display = 'block';
	}
}

function homepageLoadingAnimation() {
	var loadingdiv = document.getElementById('loadingResults_homePage');
	loadingdiv.style.display = 'block';
	if(navigator.appName.indexOf = ('Microsoft Internet Explorer') != -1){
		document.getElementById('animation_img_homePage').style.display = 'none';
		
		var animation = document.getElementById('bg_animation_homePage');
		animation.style.display = 'block';	
		animation.style.backgroundImage = 'url(/images/loadingResults_white_areas/ajax-loader-big_snake.gif)';
	}else{
		document.getElementById('bg_animation_homePage').style.display = 'block';
	}
}

function FeaturedSearchesLoadingAnimation() {
	var loadingdiv = document.getElementById('loadingResults_FeaturedSearches_Featured_Searches');
	loadingdiv.style.display = 'block';	
	var animation = document.getElementById('bg_animation_FeaturedSearches');
	animation.style.display = 'block';	
	animation.style.backgroundImage = 'url(/images/loadingResults_white_areas/ajax-loader-big_snake.gif)';
}

function byGeneLoadingAnimation() {
	var loadingdiv = document.getElementById('loadingResults_pageGenome');
	loadingdiv.style.display = 'block';
	if(navigator.appName.indexOf = ('Microsoft Internet Explorer') != -1){
		document.getElementById('animation_img_pageGenome').style.display = 'none';
	
		var animation = document.getElementById('bg_animation_pageGenome');
		animation.style.display = 'block';	
		animation.style.backgroundImage = 'url(/images/loadingResults_white_areas/ajax-loader-snake.gif)';
	}else{
		document.getElementById('bg_animation_pageGenome').style.display = 'block';
	}
}

function moreLikeitLoadingAnimation() {
	var loadingdiv = document.getElementById('loadingResults_moreLikeIt');
	loadingdiv.style.display = 'block';
	if(navigator.appName.indexOf = ('Microsoft Internet Explorer') != -1){
		document.getElementById('animation_img_moreLikeIt').style.display = 'none';
	
		var animation = document.getElementById('bg_animation_moreLikeIt');
		animation.style.display = 'block';	
		animation.style.backgroundImage = 'url(/images/loadingResults_white_areas/ajax-loader-snake.gif)';
	}else{
		document.getElementById('bg_animation_moreLikeIt').style.display = 'block';
	}
}

function cloudLoadingAnimation(index) {
	var loadingdiv = document.getElementById('loadingResults_moviePersonality_' + index);
	loadingdiv.style.display = 'block';
	var animation = document.getElementById('bg_animation_moviePersonality_' + index);
	animation.style.display = 'block';	
	animation.style.backgroundImage = 'url(/images/loadingResults_white_areas/ajax-loader-big_snake.gif)';
}

function seeMoreLoadingAnimation() {
	var loadingdiv = document.getElementById('loadingResults_seeEvenMore');
	loadingdiv.style.display = 'block';
	if(navigator.appName.indexOf = ('Microsoft Internet Explorer') != -1){
		document.getElementById('animation_img_seeEvenMore').style.display = 'none';
	
		var animation = document.getElementById('bg_animation_seeEvenMore');
		animation.style.display = 'block';	
		animation.style.backgroundImage = 'url(/images/loadingResults_white_areas/ajax-loader-big_snake.gif)';
	}else{
		document.getElementById('bg_animation_seeEvenMore').style.display = 'block';
	}
}

function hideloading(){
	if (document.getElementById('collage_ro').style.display = 'none')
		document.getElementById('loadingResults_discoveryPage').style.display = 'none';
}
