//onready routines for advanced search
$(function(){
	moreOptions=false;
	doMoreOptionDisplay=!($("#getMoreOptions:not(.filled)").length);
	startLoadingMoreOptions();
	
	$("#advancedSearch")
		.find(".remove-filter")
			.click(removeLinkedFilter)
			.end()
		.find("#getMoreOptions")
			.click(function(){
				if(!$(this).hasClass("filled")) {
					//show extra options
					doMoreOptionDisplay=true;
					//set the link text to "loading..." and set the more options preference to 1
					setMoreOptionPreference($(this).text("loading...").parent(), 1);
					if(moreOptions)
					{
						displayMoreOptions(moreOptions);
					} 
				} else {
					//hide extra options
					displayFewerOptions();
					setMoreOptionPreference($(this).parent(),0);
				}
				return false;
			})
			.end()
		.find("input.add")
			.click(function(){
				/* 
				 * get the searchterm box preceding this add button and 
				 * add the term to the search filters, then erase the searchterm
				 * box.  
				 */
				$(this).prev(".searchterm").each(function(){
					if (this.value!=="") {
						addFilterSummary(this.getAttribute("title"),
						this.value,
						this.getAttribute("id"))
						.append("<input type='hidden' />")
						.find("input")
						.attr("name", this.getAttribute("name"))
						.attr("value", this.value.replace(",","\\com"));
						this.value="";
					}
					
				});
				$(this).prev().blur();
				$("#advSearchSubmit1").focus();
				return false;
			})
			.end()
		.keypress(function(e)
			{
				/*
				 *we may need this IE code, try without it first 
				 *	if(window.event)
						key = window.event.keyCode; //IE
					else
				* 		key=e.which
				* */
				if(e.which==13)
				{
					$(this).nextAll(".add").click().end().blur();
					$("#advSearchSubmit1").focus();
					return false;
				}
			})
			.end();
		setupControls($("#advancedSearch"));
		/*
		 * the mozilla pageshow event works a lot better than beforeunload, so here's some 
		 * browser-specific code for you
		 */
		if(!$.browser.mozilla)
		{
			//on submit, disable empty inputs
			$("#advancedSearch").submit(function(){
				$("select[value=''],input[value='']", 
					"#advancedSearch").attr("disabled",true);
			});
			//before unload, revert controls so that the page will work if user hits back
			$(window).bind('beforeunload',function(oEvent){
				$("select[value=''],input[value='']", 
					"#advancedSearch").removeAttr("disabled");
				$("#advancedFilterList li.scripted a.remove-filter").each(revertLinkedFilterForSubmit);
			});
		}
		else
		{
			//on submit, remove name attributes of blank inputs 
			$("#advancedSearch").submit(function(){
					$("select[value=''],input[value='']", 
						"#advancedSearch")
						.each(function(){
							this.setAttribute("tempname", this.name);
						})
						.removeAttr("name");
				});
			//on pageshow, restore any removed name attributes from a cached view of the page
			$(window).bind('pageshow',function(){
					$("#advancedSearch [tempname]")
					.attr("name", function(){
						return $(this).attr("tempname");
					})
					.removeAttr("tempname");
				});
		}
			
})

function setMoreOptionPreference($moreDiv, pref)
{
	//set the preferMoreOptions control to 1 if it exists
	if(!$moreDiv.find("[name=preferMoreOptions]").val(pref).length)
	{
		//create preferMoreOptions and set it to 1 if it doesn't exist
		$moreDiv.prepend("<input type='hidden' name='preferMoreOptions' value='"+ pref +"'/>");
	}
}

function setupControls($selection)
{
	$selection.find(":checkbox")
		.click(function(){
			if(this.checked)
				{
					addFilterSummary(this.getAttribute("title"),
					false, this.getAttribute("id"));
				} else {
					removeFilterSummary(this.getAttribute("id"));
				}
		})
		.each(function(){
			//add a revert() method to checkboxes
			$.extend(this, 
			{revert: function(){
				this.checked=false;
			},revertForSubmit: function(){
				$("label[for="+this.getAttribute("id")+"]").text("submitting...")
				this.checked=false;
			}});
		})
		.end()
	.find("input.year")
		.keypress(function(e)
		{
			if(e.which==13)
			{
				$(this).blur();
				$("#advSearchSubmit1").focus();
				return false;
			}
		})
		.blur(function(){
			/*
			 * edit the filter summary on blur for the year controls
			 * */
			var startYear=$.trim($("#advStartYear").val());
			var endYear=$.trim($("#advEndYear").val());
			var oneYear=String(startYear)+String(endYear);
			if(!oneYear.length)
			{
				removeFilterSummary("advStartYear");
			}
			else if(startYear.length && endYear.length)
			{
				updateFilterSummary("years", 
					String(startYear)+"-"+String(endYear), "advStartYear");
			} else {
				updateFilterSummary("year", oneYear, "advStartYear");
			}
		})
		.filter("#advStartYear").each(function(){
			//add a revert() method to the start year control
			$.extend(this, 
			{revert: function(){
				$(this).val("");
				$("#advEndYear").val("");
			}});
		}).end()
		.end()
	.find("select")
		.change(function(){
			/*
			 * when the user changes a dropdown selection, update the filter 
			 * summary at the top of the advanced form accordingly
			 */
			 $(this).find("option:selected").each(function(){
			 	var parSelect=$(this).parent()[0];
		 		if(this.value.length){
			 		updateFilterSummary(parSelect.getAttribute("title"),
						this.firstChild.nodeValue,
						parSelect.getAttribute("id"));
		 		} else {
			 		removeFilterSummary(parSelect.getAttribute("id"));
		 		}
			 });
		})
		.each(function(){
			//add a revert() method to all select controls
			$.extend(this, 
			{revert: function(){
				$(this)
					.find("option:selected").removeAttr("selected").end()
					.find("option:first").attr("selected", "selected");
			},revertForSubmit: function(){
				$first=$(this).find("option:first");
				$selected=$(this).find("option:selected");
				$first.text($selected.text());
				$selected.removeAttr("selected");
				$first.attr("selected", "selected");
			}});
		})
		.end();
}

function startLoadingMoreOptions()
{
	$("#advMoreOptionParams").each(function(){
		var linkParams=this.value;
		$.ajax({
			dataType: "html",
			url: "../com/tlavideo/results/advancedform.cfc?method=getMoreOptions&" + linkParams,
			success: finishLoadingMoreOptions
		});
	})
}

function finishLoadingMoreOptions(data)
{
	moreOptions=data;
	if(doMoreOptionDisplay)
	{
		displayMoreOptions(moreOptions);
	} 
}

function displayMoreOptions(data)
{
	$("#advancedSearch div.more").find("div.options").remove().end().prepend(data);
	setupControls($("#advancedSearch div.more"));
	$("#getMoreOptions").text("hide extra options")
	.addClass("filled");
}

function displayFewerOptions()
{
	doMoreOptionDisplay=false;
	$("#advancedSearch div.more")
		.find("div.options").remove().end()
		.find("#getMoreOptions").text("more options")
		.removeClass("filled");
}

function removeLinkedFilter()
{
	if(revertLinkedFilter(this))
	{
		$(this).parent()
		.hide("fast", removeCurrentFilter);
		return false;
	}
}

//returns false if there's no filter named by this link
function revertLinkedFilter(link)
{
	/*search for a control with the ID or name specified in this 
	 * link's name attribute*/
	var filterControl=$("#"+link.getAttribute("name"))[0];
	if(filterControl)
	{
		if(filterControl.revert)
		{
			//call the filter control's revert() method, if we've defined one
			filterControl.revert();
		}
		return true;
	}
	return false;
}

function revertLinkedFilterForSubmit()
{
	var filterControl=$("#"+this.getAttribute("name"))[0];
	if(filterControl.revertForSubmit)
	{
		//call the filter control's revertForSubmit() method, if we've defined one
		filterControl.revertForSubmit();
	} else if(filterControl.revert) {
		//try for a revert() method
		filterControl.revert();
	}
}

function removeFilterSummary(controlId)
{
	$("#advancedFilterList a[name='"+controlId+"']").parent()
	.hide("fast", removeCurrentFilter);
}

function updateFilterSummary(title, value, controlId)
{
	var $curFilterSummary=$("#advancedFilterList a[name='"+controlId+"']").parent();
	if(!$curFilterSummary.length)
	{
		return addFilterSummary(title,value,controlId);
	} else {
		return $curFilterSummary
		.find("span")
		.text(" "+title+(value ? (": "+value) : ""))
		.end();
	}
}

function addFilterSummary(title,value,controlId)
{
	/*give the summary the class "more" if it comes from a 
	 *control in the more section*/
	var positionClass="";
	if($("#advancedSearch div.more #" + controlId).length)
	{
		positionClass=" more";
		$("#advancedSearch div.more").addClass("in-use");	
	}
	return $("#advancedFilterList")
	.parent().addClass("filled").end()
	.append("<li class='noPrint scripted"+ positionClass +"'></li>").find("li:last")
	.append("<a title='remove' class='remove-filter'>[x]</a>").find("a")
	.attr("href","remove_filter")
	.attr("name", controlId).click(removeLinkedFilter)
	.end().append("<span>"+title+(value ? (": "+value) : "")+"</span>")
	.show("fast").removeClass("noPrint");
}

function removeCurrentFilter()
{
	$(this).remove();
	if(!$("#advancedFilterList li.more").length)
	{
		$("#advancedSearch div.more").removeClass("in-use");	
	}
	$("#advancedFilterList:empty").parent().removeClass("filled");
}

