var searchCriteriaFormTypeId;

var container;

var form;
var allComponents;

   
function initSearchCriteriaForm(containerId, searchCriteriaFormTypeId, theaterId) {
	this.searchCriteriaFormTypeId = searchCriteriaFormTypeId;
	this.theaterId = theaterId;

	container = $("#" + containerId);

	loadSearchCriteriaForm();
}

function loadSearchCriteriaForm() {
	$.ajax({
		async: false,
        url: "searchCriteriaFormRenderer",
        dataType: "json",
        data: {
			searchCriteriaFormTypeId:searchCriteriaFormTypeId, 
			theaterId:theaterId
		},
		type: "POST",   
		success: function (data, textStatus) {
			setTranslations(data.Translations);
			buildSearchCriteriaForm(data.Form);
			
			initAllHeadersAndFooters();
			initAllCheckboxComponents();
		}   
	});
}

function buildSearchCriteriaForm(data) {
 	this.form = eval(data);
 	
 	var containerHTML = "";
 	for (var i = 0; i < form.length; i++) {
 		containerHTML += buildFormComponent(form[i],true);
	}
	
	container.html(containerHTML);
}

function buildFormComponent(component,isContentEmbedded) {
	var componentId = component.componentId;
	var componentTypeId = component.componentTypeId;
	
	component.status = "empty";
	component.isOpen = !component.isCollapsible;
	
	component.displayHtml = "";
	
	// Component [START]
	var componentHTML = "<div id='" + componentId + "' class='componentContainer'>";
	
	// Title
	if (component.title != null) {
		if (component.isCollapsible) {
            componentHTML += "<div id='" + componentId + "-title' class='collapsibleTitle' onclick=onToggleComponent('" + componentId + "')>";
			componentHTML += "<div id='" + componentId + "-expander' class='expander'>[+]&nbsp;</div>";
			componentHTML += component.title;
			componentHTML += "<div id='" + componentId + "-titleMessage' class='titleMessage'>" + (component.usesNoCriteriaSelectedMessage ? (" - " + getTranslationMessage("PageElements.page_include_all")):"") + "</div>";
			componentHTML += "</div>";
		}
		else {
			componentHTML += "<div id='" + componentId + "-title' class='nonCollapsibleTitle'>";
			if (componentTypeId != "checkbox") {
				componentHTML += component.title;
				componentHTML += "<div id='" + componentId + "-titleMessage' class='titleMessage'>" + (component.usesNoCriteriaSelectedMessage ? (" - " + getTranslationMessage("PageElements.page_include_all")):"") + "</div>";
			}
			componentHTML += "</div>";
		}
	}
	
	if (isContentEmbedded) {
		componentHTML += buildFormComponentContent(component);
	}
	
	// Display
	componentHTML += "<div id='" + componentId + "-display' class='selectedCriteria' style='display:none;'></div>";
	
	// Component [END]
	componentHTML += "</div>";
	
	return componentHTML;
}

function buildFormComponentContent(component) {
	var componentId = component.componentId;
	var componentHTML = "";
	
	// Collapsible Content [START]
	if (component.title != null && component.isCollapsible) {
		componentHTML += "<div id='" + componentId + "-collapsibleContent' class='collapsibleContent' style='display:" + (component.isOpen ? "block":"none") + ";'>";
	}
	
	// Content [START]
	componentHTML += "<div id='" + componentId + "-content' class='content' style='display:" + (component.isOpen ? "block":"none") + ";'>";
	
	// Header
	componentHTML += "<div id='" + componentId + "-header' class='header' style='display:none'></div>";
	
	
	// Body [START]
	componentHTML += "<div id='" + componentId + "-body' class='body'>";
	
	var componentTypeId = component.componentTypeId;
	
	if (componentTypeId == "gridContainer") {
		componentHTML += buildGridContainerComponent(component);
	}
	else if (componentTypeId == "treeContainer") {
		componentHTML += buildTreeContainerComponent(component);
	}
	else if (componentTypeId == "checkbox") {
		componentHTML += buildCheckboxComponent(component);
	}
	else if (componentTypeId == "suggestion") {
		componentHTML += buildSuggestionComponent(component);
	}
	else if (componentTypeId == "keyword") {
		componentHTML += buildKeywordComponent(component);
	}
	
	// Body [END]
	componentHTML += "</div>";
	
	// Footer
	componentHTML += "<div id='" + componentId + "-footer' class='footer' style='display:none'></div>";
	
	// Content [END]
	componentHTML += "</div>";
	
	// Collapsible Content [END]
	if (component.title != null && component.isCollapsible) {
		componentHTML += "</div>";
	}
	
	return componentHTML;
}

function onToggleComponent(componentId) {
	var component = findComponent(componentId);
	thisColor = null;
	
	if (component.isOpen) {
		component.isOpen = false;
		$("#" + componentId + "-content").css({"display":"none"});
		$("#" + componentId + "-expander").html("[+]&nbsp;");		
		
		if ($("#" + componentId + "-display").html() != "") {
			$("#" + componentId + "-display").css({"display":"block"});
		}
		
		if (component.isCollapsible) {
			$("#" + componentId + "-collapsibleContent").css({"display":"none"});
		}
		
		//removes tab appearance to category title
		$('#' + componentId + '-title').css({'borderWidth':'0px','margin-top':'0'}); 
		$('#' + componentId + '-scrollingCheckboxPane').css({'margin-top':'0px'});;
	}
	else {
		component.isOpen = true;
		$("#" + componentId + "-content").css({"display": "block"});
		$("#" + componentId + "-expander").html("[ - ]&nbsp;");
		$("#" + componentId + "-display").css({"display":"none"});
		 		
		if (component.isCollapsible) {
			$("#" + componentId + "-collapsibleContent").css({"display":"block"});
		}
		
		var allComponents = getAllFormComponents();		
		for (var i = 0; i < allComponents.length; i++) {
			if (allComponents[i].isCollapsible && allComponents[i].isOpen && allComponents[i].componentId != componentId) {
				if (!isAncestor(allComponents[i],component)) {
					onToggleComponent(allComponents[i].componentId);
				}
			}
		}
		
		if (component.componentTypeId == "checkbox" && component.status == "empty") {
			initCheckboxComponent(component);
		}
		
		// start - creates tab appearance to category title (makes bottom border match background color)
		var borderColor;
		thisEl = $('#' + componentId + '-title');
		isIE = $.browser.msie;
		
		//check sibling height to position tab correctly
		if(thisEl.parent().next().attr('class') != 'collapsibleContent'){
			criteriaHeight = thisEl.parent().next().children('.selectedCriteria').innerHeight();
			if(isIE == true){criteriaHeight += 4;}
			
			thisEl.css({'marginTop': criteriaHeight});
		} else {
			criteriaHeight = thisEl.parent().prev().children('.selectedCriteria').innerHeight();
			if(isIE == true){criteriaHeight += 4;}
			
			thisEl.css({'marginTop': criteriaHeight});
		}
		
		//loop through parents until hit background color
		while(thisColor == null){
			if(thisEl.css('backgroundColor') != 'transparent'){
				borderColor = thisEl.css('backgroundColor');
				$('#' + componentId + '-title').css({'borderBottomColor': borderColor});
				break;
			}
			
			thisEl = thisEl.parent();
		}
		
		$('#' + componentId + '-title').css({'borderWidth':'1px'}); 
		$('#' + componentId + '-scrollingCheckboxPane').css({'margin-top':'-1px'});  
	}
}

function initAllHeadersAndFooters() {

	var allComponents = getAllFormComponents();
	
	for (var i=0; i<allComponents.length; i++) {
		loadHeaderHtml(allComponents[i]);
		loadFooterHtml(allComponents[i]);
	}
}

function loadHeaderHtml(component) {
	if (component.headerViewAction != null) {
		$.ajax({
	        url: component.headerViewAction,
	        dataType: "html",
	        data: {
				theaterId:theaterId
			},
			type: "POST",   
			success: function (data, textStatus) {
				if (data != "") {
					$("#" + component.componentId + "-header").html(data);
					$("#" + component.componentId + "-header").css("display","block");
				}
			}   
		});
	}
}

function loadFooterHtml(component) {
	if (component.footerViewAction != null) {
		$.ajax({
	        url: component.footerViewAction,
	        dataType: "html",
	        data: {
				theaterId:theaterId
			},
			type: "POST",   
			success: function (data, textStatus) {
				if (data != "") {
					$("#" + component.componentId + "-footer").html(data);
					$("#" + component.componentId + "-footer").css("display","block");
				}
			}   
		});
	}
}


//------------------------------------------------------------------------------
// Grid Container Component
//------------------------------------------------------------------------------

function buildGridContainerComponent(component) {
	var componentHTML = "<table style='width:100%'>";
	
	var columns = component.columns;
	var column = 0;
	for (var i = 0; i < component.children.length; i++) {
		column++;
		if (column == 1) {
			componentHTML += "<tr>";
		}
		componentHTML += "<td>" + buildFormComponent(component.children[i],true) + "</td>";
		if (column == columns) {
			componentHTML = componentHTML + "</tr>";
			column = 0;
		}
	}
	
	componentHTML = componentHTML + "</table>";
	
	return componentHTML;
}

//------------------------------------------------------------------------------
// Tree Container Component
//------------------------------------------------------------------------------

function buildTreeContainerComponent(component) {
	var columns = component.columns;
	if (columns == null) {
		columns = 1;
	}
	
	var componentHTML = "";
	for (var i = 0; i < component.children.length; i++) {
		componentHTML += buildFormComponent(component.children[i],false);
		if (i > 0 &&  (i+1) % columns == 0) {
			for (var j = (i+1) - columns; j < (i+1); j++) {
				componentHTML += buildFormComponentContent(component.children[j]);
			}
			componentHTML += "<br class='clear'/>";
		}
		else if (i == component.children.length - 1) {
			componentHTML += buildFormComponentContent(component.children[i]);
			componentHTML += "<br class='clear'/>";
		}
	}
	
	return componentHTML;
}

//------------------------------------------------------------------------------
// Keyword Search Component
//------------------------------------------------------------------------------

function buildKeywordComponent(component) {
	var componentHTML = "";
	
	componentHTML += "<div class='keywordSearchTitle'>";
	componentHTML += "<label for='searchIn'>" + getTranslationMessage("PageElements.page_elem_search_in") + "</label>";
	
	componentHTML += "<select id='searchIn' name='searchType'>";
	for (var i = 0; i < component.availableSearchTypes.length; i++) {
		componentHTML += "<option value='" + component.availableSearchTypes[i].searchType + "'>" + getTranslationMessage(component.availableSearchTypes[i].messageKey) + "</option>";
	}
	componentHTML += "</select>";
	
	componentHTML += "<input type='text' name='searchString' size='30' maxlength='50' class='searchText'/>";
	
	componentHTML += "<input type='submit' value='" + getTranslationMessage("PageElements.page_search") + "' class='searchButton'/>";
	componentHTML += "</div>";
	
	return componentHTML;
}


//------------------------------------------------------------------------------
// Checkbox Component
//------------------------------------------------------------------------------

function buildCheckboxComponent(component) {
	var componentId = component.componentId;
	
	$('#selectedCriteria').append("<div id='" + componentId + "-selectedCriteria'></div>");
	
	component.allCheckboxCriteria = new Array();
	component.selectedCheckboxCriteria = new Array();

	return "Loading...";
}

function initAllCheckboxComponents() {
	var allComponents = getAllFormComponents();
	for (var i=0; i<allComponents.length; i++) {
		var component = allComponents[i];
		
		if (component.componentTypeId == "checkbox" && component.status == "empty" && component.isOpen) {
			initCheckboxComponent(component);
		}
	}
	loadAllSelectedCheckboxCriteriaFromSession();
}

function initCheckboxComponent(component) {
	$.ajax({
		async: false,
        url: "checkboxCriteriaRequest",
        dataType: "json",
        data: {
			searchCriteriaFormTypeId:searchCriteriaFormTypeId, 
			theaterId:theaterId,
			checkboxCriteriaTypeId:component.checkboxCriteriaTypeId,
			componentId:component.componentId 
		},
		type: "POST",   
		success: function (data, textStatus) {
			buildCheckboxCriteria(component,data);
			component.status = "loaded";
		}   
	});
}

function buildCheckboxCriteria(component, data) {
	var componentId = component.componentId;
	
 	var results = data.Results;
 	component.allCheckboxCriteria = results;
 	
 	var titleComponent = $("#" + componentId + "-title");
 	
 	if (results.length > 0 && titleComponent.attr("class") == "nonCollapsibleTitle") {
 		var titleHTML = component.title;
 		titleHTML += "<div id='" + componentId + "-titleMessage' class='titleMessage'>" + (component.usesNoCriteriaSelectedMessage ? (" - " + getTranslationMessage("PageElements.page_include_all")):"") + "</div>";
 		
 		titleComponent.html(titleHTML);
 	}
 	
 	var thisChildHtml = "<div id='" + componentId + "-limitedCheckboxPane' class='limitedCheckboxPane overTransparent'>";
	thisChildHtml += "<div id='" + componentId + "-scrollingCheckboxPane' class='scrollingCheckboxPane'>";
	
	var numCheckboxItems = results.length;
	var columns = component.columns;
	var colWidth = Math.floor(100/columns);
		
	var rows = new Array();
	
	rows[columns-1] = (numCheckboxItems / columns - numCheckboxItems % columns / columns);
	for (var i=0; i<columns-1; i++) {
		rows[i] = rows[columns-1] + ((numCheckboxItems % columns) > i ? 1:0);
	}
		
	var index = 0;
	var indexes = new Array();
	for (var j=0; j<columns; j++) {
		for (var k=0; k<rows[j]; k++) {
			if (k == 0) {
				indexes[j] = new Array();
			}
			indexes[j][k] = index++;
		}
	}
	
	thisChildHtml = thisChildHtml + "<table style='width:97%'>";
	for (var m=0; m < rows[0]; m++) {
		thisChildHtml = thisChildHtml + "<tr>";
		for (var n=0; n<columns; n++) {
			if (indexes[n] != null && indexes[n][m] != null) {
				index = indexes[n][m];
				
				thisChildHtml += "<td class='checkboxWrapper' style='vertical-align: top;width: " + colWidth + "%'>";
				
				var inputHtml = "<input type='checkbox' id='" + componentId + "-" + results[index].id + "' value='" + index + "' onclick=onCheckboxCriterionSelected('" + componentId + "','" + results[index].id + "',event) style='vertical-align: middle; background-color: transparent; border:none;'/>";
				
				var titleHtml = "";
				if (component.usesTitle) {
					titleHtml += "<label for='" + results[index].name + "'";
			        if (results[index].hasDescription) {
			            titleHtml += " class='labelWithPopup' onmouseover='showTagDetailsPopUp(\"tagPopupController?tagId=" + results[index].id + "&property=" + component.property + "&searchCriteriaFormTypeId=" + searchCriteriaFormTypeId + "&theaterId=" + theaterId + "\",\"" +  results[index].id + "\",event)' onmouseout='killPopUp()'";
					}
					titleHtml += ">" + results[index].title + "</label>";
				}
				
				if (component.usesCheckboxIcon) {
					thisChildHtml += "<table cellspacing=0 cellpadding=0>";
					
					var iconHtml = "<img src='" + results[index].iconUrl + "'/>";
					
					if (component.checkboxIconPlacement == "Right") {
						thisChildHtml += "<tr><td>" + inputHtml + "</td><td>" + iconHtml + "</td><td class='checkboxTitle'>" + titleHtml + "</td></tr>" ;
					}
					else if (component.checkboxIconPlacement == "Left") {
						thisChildHtml += "<tr><td>" + iconHtml + "</td><td>" + inputHtml + "</td><td class='checkboxTitle'>" + titleHtml + "</td></tr>" ;
					}
					else if (component.checkboxIconPlacement == "Top") {
						thisChildHtml += "<tr><td>" + iconHtml + "</td><td class='checkboxTitle'>" + titleHtml + "</td></tr>";
						thisChildHtml += "<tr><td colspan=2>" + inputHtml + "</td></tr>";
					}
					else if (component.checkboxIconPlacement == "Bottom") {
						thisChildHtml += "<tr><td colspan=2>" + inputHtml + "</td></tr>";
						thisChildHtml += "<tr><td>" + iconHtml + "</td><td class='checkboxTitle'>" + titleHtml + "</td></tr>";
					}
					
					thisChildHtml += "</table>";
				}
				else {
					thisChildHtml += inputHtml + titleHtml;
				}
				
				thisChildHtml += "</td>";
				
			}
			else {
				thisChildHtml += "<td>&nbsp;</td>";
			}
		}		
		thisChildHtml += "</tr>";
	}	
	thisChildHtml += "</table>";
	
	thisChildHtml += "</div>";
	
	var checkboxStagingDiv = $("#checkboxStaging");
	checkboxStagingDiv.html(thisChildHtml);
	
	var targetDivWidth = $("#" + componentId + "-limitedCheckboxPane").attr("offsetWidth");
	checkboxStagingDiv.css("width",targetDivWidth + "px");
	
	var scrollingHeight = checkboxStagingDiv.attr("offsetHeight");
	checkboxStagingDiv.html("");

	$("#" + componentId + "-body").html(thisChildHtml);
	
	numberOfTbleRows = $('#' + componentId + '-collapsibleContent tr').length;
	
	if(numberOfTbleRows > 8) {
		$("#" + componentId + "-limitedCheckboxPane").css("height","229px");
		$("#" + componentId + "-scrollingCheckboxPane").css("height","219px");
	} else if ($.browser.msie && $.browser.version == '6.0') {
		//ie6 layout fixes
		$('#' + componentId + '-title').click(function(){
			ie6ScrollingCheckboxPane = $('#' + componentId + '-limitedCheckboxPane table').height() + 10;
			$('#' + componentId + '-scrollingCheckboxPane').height(ie6ScrollingCheckboxPane);
		});
	}		

	$('#' + componentId + '-collapsibleContent').css({'clear':'both'});
	
	//fix for bit-rate labels on advanced search
	 if ($.browser.msie && $.browser.version == '6.0'){
	 	$('#videoFormatOptions').parent().css({'padding-left':'85px','width':'250px'});
	 } else {
	 	$('#videoFormatOptions').parent().css({'width':'250px'});
	 }
	
	
}

function onCheckboxCriterionSelected(componentId, criterionId) {
	var component = findComponent(componentId);
	var property = component.property;
	
	var index = $("#" + componentId + "-" + criterionId).attr("value");
	var criterion = component.allCheckboxCriteria[index];
	
	if ($("#" + componentId + "-" + criterionId).attr("checked")) {
		if (addCheckboxCriterion(component,criterion)) {
			compileAllCheckboxCriteria(component);
			updateSelectedCheckboxCriteriaInSession(property,criterionId,true);
		}
	}
	else {
		onCheckboxCriterionRemoved(componentId,criterionId);
	}
}

function onClearCheckboxCriteria(componentId) {
    $("#" + componentId + "-scrollingCheckboxPane").find("input:checkbox").attr("checked",false);
}

function onToggleCheckboxCriterion(componentId, criterionId, checked) {
	var component = findComponent(componentId);
	
	if (component.componentTypeId == "checkbox" && component.status == "empty") {
		initCheckboxComponent(component);
	}
	
	var checkbox = $("#" + componentId + "-" + criterionId);
	if (checkbox) {
    	checkbox.attr("checked",checked);
    	onCheckboxCriterionSelected(componentId,criterionId);
    }
}

function addCheckboxCriterion(component, criterion) {
	var selectedCheckboxCriteria = component.selectedCheckboxCriteria;
	
	var index = -1;
	for (var i=0; i<selectedCheckboxCriteria.length; i++) {
		if (selectedCheckboxCriteria[i].id == criterion.id) {
			index = i;
			break;
		}
	}
	
	if (index > -1) {
		return false;
	}
	else {
		selectedCheckboxCriteria[selectedCheckboxCriteria.length] = criterion;
		return true;
	}
}

function onCheckboxCriterionRemoved(componentId, criterionId) {
	var component = findComponent(componentId);
	var property = component.property;
	
	if (removeCheckboxCriterion(component,criterionId)) {
		$("#" + componentId + "-" + criterionId).attr("checked",false)
		compileAllCheckboxCriteria(component);
	}
	
	updateSelectedCheckboxCriteriaInSession(property,criterionId,false);
}

function onCheckboxCriterionRemovedByProperty(property, criterionId) {
	var component = findComponentByProperty(property);
	if (component != null) {
		onCheckboxCriterionRemoved(component.componentId,criterionId);
	}
	else {
		updateSelectedCheckboxCriteriaInSession(property,criterionId,false);
	}
}

function removeCheckboxCriterion(component, criterionId) {
	selectedCheckboxCriteria = component.selectedCheckboxCriteria;
	
	var index = -1;
	for (i=0; i<selectedCheckboxCriteria.length; i++) {
		if (selectedCheckboxCriteria[i].id == criterionId) {
			index = i;
			break;
		}
	}
	
	if (index > -1) {
		selectedCheckboxCriteria.splice(i,1);
		return true;
	}
	else {
		return false;
	}
}

function compileAllCheckboxCriteria(component) {
	componentId = component.componentId;
	
	selectedCheckboxCriteria = component.selectedCheckboxCriteria;
	
	var displayHtml = "";
	var selectedCriteriaHtml = "";
	
	for (var i=0; i<selectedCheckboxCriteria.length; i++) {
		if (displayHtml != "") {
			displayHtml = displayHtml + " ";
		}
		else {
			displayHtml = component.title + ": ";
		}
		
		displayHtml += selectedCheckboxCriteria[i].title + "<a href=\"javascript:onCheckboxCriterionRemoved('" + componentId + "','" + selectedCheckboxCriteria[i].id + "')\">[x]</a>";
		selectedCriteriaHtml = selectedCriteriaHtml + "<input type='hidden' name='" + component.property + "' value='" + selectedCheckboxCriteria[i].id + "'/>";
	}
	
	$("#" + componentId + "-selectedCriteria").html(selectedCriteriaHtml);
			
	setDisplayHtml(component,displayHtml);
	
	var ancestors = getAncestors(component);
	for (var j=0; j<ancestors.length; j++) {
		var ancestorDisplayHtml = "";
		for (var k=0; k<ancestors[j].children.length; k++) {
			
			var childDisplayHtml = ancestors[j].children[k].displayHtml;
			ancestorDisplayHtml = ancestorDisplayHtml + childDisplayHtml;
		}
		setDisplayHtml(ancestors[j],ancestorDisplayHtml);
	}
}

function setDisplayHtml(component, displayHtml) {
	var componentId = component.componentId;
	
	if (displayHtml != "") {
		component.displayHtml = displayHtml + "<br/>";
		
		if (component.title != null) {
			$("#" + componentId + "-titleMessage").html("");
		}
		
		if (component.isOpen) {
			$("#" + componentId + "-display").css("display","none");
		}
		else {
			$("#" + componentId + "-display").css("display","block");
		}
	}
	else {
		component.displayHtml = "";
		if (component.title != null) {
			$("#" + componentId + "-titleMessage").html(component.usesNoCriteriaSelectedMessage ? (" - " + getTranslationMessage("PageElements.page_include_all")):"");
		}
		
		$("#" + componentId + "-display").css("display","none");
	}

	$("#" + componentId + "-display").html(component.displayHtml);
}

function updateSelectedCheckboxCriteriaInSession(property, criterionId, isSelected) {
	$.ajax({
		async: false,
        url: "checkboxCriteriaSelection",
        dataType: "json",
        data: {
			searchCriteriaFormTypeId: searchCriteriaFormTypeId,
			action: "update",
			property: property,
			criterionId: criterionId,
			isSelected: isSelected,
			theaterId: theaterId
		},
		type: "POST",
		success: function (data, textStatus) {
		}
	});
}

function clearAllSelectedCheckboxCriteriaInSession() {
	$.ajax({
		async: false,
        url: "checkboxCriteriaSelection",
        dataType: "json",
        data: {
			searchCriteriaFormTypeId: searchCriteriaFormTypeId,
			action: "clear",
			theaterId: theaterId
		},
		type: "POST",
		success: function (data, textStatus) {
		}
	});
}

function loadAllSelectedCheckboxCriteriaFromSession() {
	$.ajax({
		async: true,
        url: "sessionAttribute",
        dataType: "json",
        data: {
        	sessionAttribute: "CheckboxSearchCriteria",
			theaterId: theaterId
		},
		type: "POST",
		success: function (data, textStatus) {
			for (var i=0; i<data.length; i++) {
				if (data[i].searchCriteriaFormType == searchCriteriaFormTypeId) {
					for (var j=0; j<data[i].criteria.length; j++) {
						var property = data[i].criteria[j].property;
						var component = findComponentByProperty(property);
						
						if (component != null) {
							for (var k=0; k<data[i].criteria[j].criterionIds.length; k++) {
								var criterionId = data[i].criteria[j].criterionIds[k];
								onToggleCheckboxCriterion(component.componentId,criterionId,true);
							}
						}
					}
				}
			}
		}
	});
}


//------------------------------------------------------------------------------
// Suggestion Component
//------------------------------------------------------------------------------

function buildSuggestionComponent(component) {
	var componentId = component.componentId;
	
	$('#selectedCriteria').append("<div id='" + componentId + "-selectedCriteria'></div>");
	
	component.allSuggestionCriteria = new Array();
	component.selectedSuggestionCriteria = new Array();
	component.displayHtml = "";
	
	var componentHTML = "";
	componentHTML += "<div class='MYtextFieldWrapper overTransparent'><div class='electricBallGag'>";
	
	componentHTML += "<label><input name='" + componentId + "-searchMethod' type=radio " + (component.searchMethod == "BeginsWith" ? "checked ":"") + "class='searchIn' onclick=changeSuggestionSearchMethod('" + componentId + "','BeginsWith')>" + getTranslationMessage("PageElements.page_begins_with") + "</label>&nbsp;";
    componentHTML += "<label><input name='" + componentId + "-searchMethod' type=radio " + (component.searchMethod == "Includes" ? "checked ":"") + "class='searchIn' onclick=changeSuggestionSearchMethod('" + componentId + "','Includes')>" + getTranslationMessage("PageElements.page_includes") + "</label>";
    
	componentHTML += "<input id='" + componentId + "-searchString' type=text onkeyup=onSuggestionCriteriaRequest('" + componentId + "',event) autocomplete=off class='boxWidth' onmouseover=detectSuggestionMouseStatus('" + componentId + "','over') onmouseout=detectSuggestionMouseStatus('" + componentId + "','out')>";
	
	componentHTML += "<br class='clear'/></div>";
	
	componentHTML += "<div id='" + componentId + "-selectedSuggestionCriteria'></div>";
	
	componentHTML += "<div id='" + componentId + "-comboBoxContainer' class='comboBoxBorder boxWidth' style='display:none;' onmouseover=detectSuggestionMouseStatus('" + componentId + "','over') onmouseout=detectSuggestionMouseStatus('" + componentId + "','out')>";
	componentHTML += "<div id='" + componentId + "-comboBoxContent'></div>";
	componentHTML += "<div id='" + componentId + "-comboBoxFooter' class='comboBoxFooter boxWidth' onmouseover=detectSuggestionMouseStatus('" + componentId + "','over')></div>";
	componentHTML += "</div></div>";
	
	return componentHTML;
}

function onSuggestionCriteriaRequest(componentId, event){
	
	if ($("#" + componentId + "-comboBoxContent").html() != "") {
		var comboBox = $("#" + componentId + "-comboBox");
		
		if (event.keyCode == 40 && comboBox.attr("length") > 0) {
			comboBox.focus();
			comboBox.attr("selectedIndex",0);
			return;
		}
	}

    var searchString = $("#" + componentId + "-searchString").attr("value");
	
	if (searchString.length >= minSuggestionSearchStringLength(componentId)) {
		var component = findComponent(componentId);
		
        $.ajax({
	        url: "suggestionCriteriaRequest",
	        dataType: "json",
	        data: {
				searchCriteriaFormTypeId:searchCriteriaFormTypeId, 
				componentId:component.componentId, 
				theaterId:theaterId,
				searchMethod:component.searchMethod,
				searchString:$("#" + componentId + "-searchString").attr("value")
			},
			type: "POST",   
			success: function (data, textStatus) {
				buildSuggestionComboBox(component,data);
			}   
		});
    }
    else {
    	toggleSuggestionComboBoxStatus(componentId,"close");
    }
}

function buildSuggestionComboBox(component, data) {
	var componentId = component.componentId;
	
	var results = data.Results;
	
	component.allSuggestionCriteria = results;
	
	var selectHtml = "<select id='" + componentId + "-comboBox' size='" + suggestionComboBoxHeight(component,results) + "' class='comboBoxElement' onmouseup=onDelayedSuggestionCriterionSelected('" + componentId + "') onkeyup=onSuggestionCriterionSelected('" + componentId + "',event) onmouseover=detectSuggestionMouseStatus('" + componentId + "','over')>";
	
	for (var i=0; i<results.length; i++) {
		selectHtml += "<option value='" + i + "'>" + results[i].title + "</option>";
	}
	
	selectHtml += "</select>";
	
	if (results.length > 10) {
		$("#" + componentId + "-comboBoxFooter").html("<a href='javascript:changeSuggestionComboBoxToFull(\"" + componentId + "\")'>View the [" + results.length + "] items</a>");
	}
	else {
		$("#" + componentId + "-comboBoxFooter").css("display","none");
	}

	if (results.length > 0) {
	    $("#" + componentId + "-comboBoxContent").html(selectHtml);
	    toggleSuggestionComboBoxStatus(componentId,"open");
	}
	else {
	    toggleSuggestionComboBoxStatus(componentId,"close");
	}
}

function onSuggestionCriterionSelected(componentId, event) {
	var component = findComponent(componentId);
	
	var index = $("#" + componentId + "-comboBox").attr("value");
	var criterion = component.allSuggestionCriteria[index];
		
	if ((event == null || event.keyCode == 13) && addSuggestionCriterion(component, criterion)) {
		compileAllSuggestionCriteria(component);
	}
}

function onDelayedSuggestionCriterionSelected(componentId) {
	var timeoutString = "onSuggestionCriterionSelected('" + componentId + "',null)";
	setTimeout(timeoutString, 2);
}

function addSuggestionCriterion(component, criterion) {
	selectedSuggestionCriteria = component.selectedSuggestionCriteria;
	
	var index = -1;
	for (i=0; i<selectedSuggestionCriteria.length; i++) {
		if (selectedSuggestionCriteria[i].id == criterion.id) {
			index = i;
			break;
		}
	}
	
	if (index > -1) {
		return false;
	}
	else {
		selectedSuggestionCriteria[selectedSuggestionCriteria.length] = criterion;
		return true;
	}
}

function onSuggestionCriterionRemoved(componentId, criterionId) {
	var component = findComponent(componentId);
	
	if (removeSuggestionCriterion(component,criterionId)) {
		compileAllSuggestionCriteria(component);
	}
}

function removeSuggestionCriterion(component, criterionId) {
	selectedSuggestionCriteria = component.selectedSuggestionCriteria;
	
	var index = -1;
	for (i=0; i<selectedSuggestionCriteria.length; i++) {
		if (selectedSuggestionCriteria[i].id == criterionId) {
			index = i;
			break;
		}
	}
	
	if (index > -1) {
		selectedSuggestionCriteria.splice(i,1);
		return true;
	}
	else {
		return false;
	}
}

function compileAllSuggestionCriteria(component) {
	componentId = component.componentId;
	
	selectedSuggestionCriteria = component.selectedSuggestionCriteria;
	
	var displayHtml = "";
	var selectedCriteriaHtml = "";
	
	for (var i=0; i<selectedSuggestionCriteria.length; i++) {
		displayHtml += selectedSuggestionCriteria[i].title + "<a href=\"javascript:onSuggestionCriterionRemoved('" + componentId + "','" + selectedSuggestionCriteria[i].id + "')\">[x]</a> ";
		selectedCriteriaHtml += "<input type='hidden' name='" + component.property + "' value='" + selectedSuggestionCriteria[i].id + "'/>";
	}
	
	$("#" + componentId + "-selectedCriteria").html(selectedCriteriaHtml);
	
	$("#" + componentId + "-display").html(displayHtml);
	$("#" + componentId + "-selectedSuggestionCriteria").html(displayHtml);
	
	if (displayHtml != "") {
		$("#" + componentId + "-titleMessage").html("");
		
		if (component.isOpen) {
			$("#" + componentId + "-display").css("display","none");
		}
		else {
			$("#" + componentId + "-display").css("display","block");
		}
	}
	else {
		$("#" + componentId + "-titleMessage").html(component.usesNoCriteriaSelectedMessage ? (" - " + getTranslationMessage("PageElements.page_include_all")):"");
		$("#" + componentId + "-display").css("display","none");
	}
	
	component.displayHtml = displayHtml;
}


function suggestionComboBoxHeight(component,options){
    if (options.length > 0 && options.length <= 10) {
   		if (options.length == 1) {
   			return 2;
    	}
       	return options.length;
    }
    else if (options.length > 10) {
        return 10;
    }
    else {
        toggleSuggestionComboBoxStatus(component.componentId,"close")
        return 0;
    }
}

function toggleSuggestionComboBoxStatus(componentId, status) {
	switch(status) {
		case "open":
			$("#" + componentId + "-comboBox").attr("className","comboBoxElement");
			$("#" + componentId + "-comboBox").css("height","auto");
			$("#" + componentId + "-comboBoxFooter").css("display","block");
			$("#" + componentId + "-comboBoxContainer").css("display","block");
			break;
		case "close":
			$("#" + componentId + "-comboBoxContainer").css("display","none");
		break;
	}
}

function changeSuggestionComboBoxToFull(componentId) {
	$("#" + componentId + "-comboBox").attr("className","comboBoxElementFull");
	$("#" + componentId + "-comboBox").css("height","290px");
	$("#" + componentId + "-comboBoxFooter").css("display","none");
}

function minSuggestionSearchStringLength(componentId) {
	var component = findComponent(componentId);

	if (component.searchMethod == "Includes") {
		return 3; /*return 4; We may want to re-implement this in future.*/
	}
	else {
		return 3;
	}
}

function changeSuggestionSearchMethod(componentId, searchMethod) {
	var component = findComponent(componentId);
	component.searchMethod = searchMethod;
	
	toggleSuggestionComboBoxStatus(componentId,"close");
}

function detectSuggestionMouseStatus(componentId, status) {
	var component = findComponent(componentId);
	
	component.mouseStatus = status;
	if (component.mouseStatus != "over") {
		setTimeout("timedSuggestionComboBoxClose('" + componentId + "')",1000);
	}
}

function timedSuggestionComboBoxClose(componentId) {
	var component = findComponent(componentId);
	
	var comboBox = $("#" + componentId + "-comboBox");
	if (component.mouseStatus != "over" && comboBox != null) {
	    comboBox.css("height","auto");
		toggleSuggestionComboBoxStatus(componentId,"close");
		$("#" + componentId + "-searchString").attr("value","");
	}
}


//------------------------------------------------------------------------------
// Utilities
//------------------------------------------------------------------------------

function findComponent(componentId) {
	var allComponents = getAllFormComponents();
	
	for (var i = 0; i < allComponents.length; i++) {
		if (allComponents[i].componentId == componentId) {
			return allComponents[i];
		}
	}
	return null;
}

function findComponentByProperty(property) {
	var allComponents = getAllFormComponents();
	
	for (var i = 0; i < allComponents.length; i++) {
		if (allComponents[i].property == property) {
			return allComponents[i];
		}
	}
	return null;
}

function getAncestors(component) {
	var ancestors = new Array();
	
	var ancestorId = component.parentId;
	while (ancestorId != null) {
		ancestors[ancestors.length] = findComponent(ancestorId);
		ancestorId = ancestors[ancestors.length-1].parentId;
	}
	
	return ancestors;
}

function isAncestor(possibleAncestor, component) {
	var ancestors = getAncestors(component);
	
	var isAncestor = false;
	for (var i = 0; i < ancestors.length; i++) {
		if (ancestors[i].componentId == possibleAncestor.componentId) {
			isAncestor = true;
			break;
		}
	}
	return isAncestor;
}

function getAllFormComponents() {
	if (this.allComponents == null) {
		this.allComponents = getAllComponents(this.form);
	}
	return this.allComponents;
}

function getAllComponents(components) {
	var allComponents = new Array();
	for (var i = 0; i < components.length; i++) {
		allComponents[allComponents.length] = components[i];
		
		if (components[i].children != null) {
			var allChildren = getAllComponents(components[i].children);
			for  (var j = 0; j < allChildren.length; j++) {
				allComponents[allComponents.length] = allChildren[j];
			}
		}
	}
	return allComponents;
}

