/* NOTE this script requires the ieat-util.js script to function */

var as_types = ["1","4","2","3"];

var as_type_rules = new Array();
as_type_rules["1"] = ["1","3","4"];
as_type_rules["2"] = ["5","6"];
as_type_rules["3"] = ["1","2"];
as_type_rules["4"] = ["1","3","4"];

var as_choice_rule = new Array();
as_choice_rule["1"] = [
	["1","1"],
	["2","2"],
	["3","3"],
	["4","4"],
	["5","5"]
	];
as_choice_rule["4"] = [
	["1","1"],
	["2","2"],
	["3","3"],
	["4","4"],
	["5","5"]
	];
	
var as_text_choice_rule = new Array();
//as_text_choice_rule["4"] = true;

var as_help = new Array();
as_help["1"] = '/help.do?key=search.averagerating';
as_help["2"] = '/help.do?key=search.text';
as_help["3"] = '/help.do?key=search.owner';

/**
 * Initialize an advanced search form row.
 * 
 * @param rowNum the form row number to initialize
 */
function initAdvancedSearchRow(rowNum) {
	var form = getAdvancedSearchForm();
	
	
	// init the search type select
	var typeSelect = getEmptySelect(form,"criteria.advanced["+rowNum+"].type");
	typeSelect.onchange = handleAdvancedSearchTypeChange;
	typeSelect.appendChild(document.createElement("option"));
	for ( var i = 0; i < as_types.length; i++ ) {
		var newOption = document.createElement("option");
		newOption.text = getMessage("msg_as_type_" +as_types[i]);
		newOption.value = as_types[i];
		typeSelect.appendChild(newOption);
	}
	
	// clear out the other selects
	advancedSearchClearOp(form,rowNum);
	
	// uncheck the "required" checkbox
	var requiredCheckbox = form.elements["criteria.advanced["+rowNum+"].required"];
	requiredCheckbox.checked = false;
	
	// hide the choice elements
	var choiceSelect = form.elements["criteria.advanced["+rowNum+"].choice"];
	choiceSelect.style.display = 'none';
	var queryText = form.elements["criteria.advanced["+rowNum+"].query"];
	queryText.style.display = 'none';
	
	var opSelect = form.elements["criteria.advanced["+rowNum+"].op"];
	
	// make sure nothing between opSelect and typeSelect, which clears out
	// any existing help link
	while ( opSelect.previousSibling != typeSelect ) {
		opSelect.parentNode.removeChild(opSelect.previousSibling);
	}
		
	if ( advancedCriteria[rowNum] ) {
		// initialize the form using the advancedCriteria array data, which is arranged:
		// 0: type
		// 1: op
		// 2: choice
		// 3: query
		// 4: required
	
		for ( var i = 0; i < typeSelect.options.length; i++ ) {
			if ( typeSelect.options[i].value == advancedCriteria[rowNum][0] ) {
				typeSelect.options[i].selected = true;
				break;
			}
		}
		var event = new Object();
		event.target = typeSelect;
		handleAdvancedSearchTypeChange(event);
		
		for ( var i = 0; i < opSelect.options.length; i++ ) {
			if ( opSelect.options[i].value == advancedCriteria[rowNum][1] ) {
				opSelect.options[i].selected = true;
				break;
			}
		}
		
		for ( var i = 0; i < choiceSelect.length; i++ ) {
			if ( choiceSelect.options[i].value == advancedCriteria[rowNum][2] ) {
				choiceSelect.options[i].selected = true;
				break;
			}
		}
		
		queryText.value = advancedCriteria[rowNum][3];
		
		if ( advancedCriteria[rowNum][4] ) {
			requiredCheckbox.checked = true;
		}
	}
}

function advancedSearchClearOp(form,rowNum) {
	getEmptySelect(form,"criteria.advanced["+rowNum+"].op");
	advancedSearchClearChoice(form,rowNum);
}

function advancedSearchClearChoice(form,rowNum) {
	var choiceSelect = getEmptySelect(form,"criteria.advanced["+rowNum+"].choice");
	choiceSelect.style.display = "none";
	var textText = form.elements["criteria.advanced["+rowNum+"].query"];
	textText.value = "";
	textText.style.display = "none";
}

function handleAdvancedSearchTypeChange(event) {
	var typeSelect = event.target;
	var rowNum = typeSelect.name.match(/\d+/)[0];
	var selectedValue = typeSelect.options[typeSelect.selectedIndex].value;
	//alert("got value: " +selectedValue +" for row num " +rowNum);
	
	if ( !selectedValue ) {
		// clear out other selects, etc
		advancedSearchClearOp(typeSelect.form,rowNum);
	} else {
		// clear out choice data
		advancedSearchClearChoice(typeSelect.form,rowNum);
		
		// populate op select
		var opSelect = getEmptySelect(typeSelect.form,"criteria.advanced["+rowNum+"].op");
		var as_ops = as_type_rules[selectedValue];
		//opSelect.appendChild(document.createElement("option"));
		for ( var i = 0; i < as_ops.length; i++ ) {
			var newOption = document.createElement("option");
			newOption.text = getMessage("msg_as_op_" +as_ops[i]);
			newOption.value = as_ops[i];
			opSelect.appendChild(newOption);
		}
		
		// make sure nothing between opSelect and typeSelect, which clears out
		// any existing help link
		while ( opSelect.previousSibling != typeSelect ) {
			opSelect.parentNode.removeChild(opSelect.previousSibling);
		}
		
		// insert help link if available
		if ( as_help[selectedValue] ) {
			var helpLink = document.createElement("a");
			var sup = document.createElement("sup");
			sup.appendChild(document.createTextNode("?"));
			helpLink.appendChild(sup);
			var linkUrl = webContext+as_help[selectedValue];
			helpLink.setAttribute("class","help");
			helpLink.href = linkUrl;
			helpLink.onclick = popupWin(linkUrl,"width=480,height=175,location=0");
			opSelect.parentNode.insertBefore(helpLink,opSelect);
		}
		
		// populate the choice select or display the text input
		var choice_data = as_choice_rule[selectedValue];
		var choiceSelect = typeSelect.form.elements["criteria.advanced["+rowNum+"].choice"];
		var textText = typeSelect.form.elements["criteria.advanced["+rowNum+"].query"];
		if ( choice_data ) {
			for ( var i = 0; i < choice_data.length; i++ ) {
				var newOption = document.createElement("option");
				newOption.value = choice_data[i][0];
				newOption.text = choice_data[i][1];
				choiceSelect.appendChild(newOption);
			}
			choiceSelect.style.display = "inline";
			textText.style.display = as_text_choice_rule[selectedValue] ? "inline" : "none";
		} else {
			choiceSelect.style.display = "none";
			textText.style.display = "inline";
		}
	}
}

function addAdvancedSearchCriteria() {
	// get the search criteria table
	var row = document.getElementById('criteria_row');
	
	// get the add row to insert the cloned row into
	var addRow = document.getElementById('criteria_add_row');
	
	// clone the ingredient row
	var newRow = row.cloneNode(true);
	
	// remove 'id' attribute
	newRow.removeAttribute('id');
	
	// make the 'minus' button appear
	var minus = findNodeWithAttributeValue(newRow,'class','minus');
	if ( minus && minus.style ) {
		minus.style.display = 'block';
	}
	
	// find all 'name' attributes, and increment index values
	replaceAttribute(newRow,'name','advanced\\[\\d+\\]',
		'advanced[' +numAdvancedCriteria +']');
	replaceAttribute(newRow,'href','javascript:removeAdvancedSearchCriteria\\(\\d+\\)',
		'javascript:removeAdvancedSearchCriteria(' +numAdvancedCriteria +')');
	
	// insert into table
	addRow.parentNode.insertBefore(newRow,addRow);
	
	initAdvancedSearchRow(numAdvancedCriteria);
	
	numAdvancedCriteria++;
}

function removeAdvancedSearchCriteria(criteriaIndex) {
	// loop through all rows in criteria table, removing the 
	// row in question and then re-naming any subsequent rows
	// so index values decrease
	
	if ( criteriaIndex < 1 ) {
		alert(getMessage('msg_noDeleteFirstCriteria'));
		return;
	}
	
	// forward to proper row
	var rowIdx = 0;
	var criteriaRow = document.getElementById('criteria_row');
	if ( !criteriaRow ) {
		alert("Could not get criteria_row!");
		return;
	}
	while ( criteriaRow != null && rowIdx < criteriaIndex ) {
		criteriaRow = criteriaRow.nextSibling;
		if ( criteriaRow.nodeName.toLowerCase() == 'tr' ) {
			rowIdx++;
		}
	}
	
	var currRow = criteriaRow.nextSibling;
	for ( var currIndex = criteriaIndex; currIndex < (numAdvancedCriteria - 1) && currRow != null 
		&& currRow.nextSibling != null; currRow = currRow.nextSibling ) 
	{
		if ( currRow.nodeName.toLowerCase() != 'tr' ) continue;
		
		replaceAttribute(currRow,'name','advanced\\[\\d+\\]',
			'advanced[' +currIndex +']');
		replaceAttribute(currRow,'href','javascript:removeAdvancedSearchCriteria\\(\\d+\\)',
			'javascript:removeAdvancedSearchCriteria(' +currIndex +')');

		currIndex++;
	}
	
	// now remove criteriaRow from table
	if ( criteriaRow.parentNode.removeChild(criteriaRow) ) {
		numAdvancedCriteria--;
	} else {
		alert("Unable to remove criteria node!");
	}
}

function getAdvancedSearchForm() {
	var form = document.getElementById("advancedSearchForm");
	if ( !form ) {
		alert("Could not get advanced search form.");
	}
	return form;
}

function getEmptySelect(form, name) {
	var typeSelect = form.elements[name];
	if ( !typeSelect ) {
		alert("Could not get advanced search select '" +name +"'");
		return;
	}
	
	// remove any options
	if ( typeSelect.options.length > 0 ) {
		removeChildren(typeSelect);
	}
	
	return typeSelect;
}
