	var lastsearch = "";
	var qidPosted = false;
	
	$(document).ready(function()
	{
		var cacheDir = {},
			cacheAct = {},
			cacheCat = {},
			lastXhr;
		
		/*	//disabled autocomplete because it was kind of annoying and easier to just use search.
		$( "#flixsearch" ).autocomplete({
			minLength: 3,
			source: function( request, response ) {
				var url = "autocomplete.php?type=title" + GetSources();
				lastXhr = $.getJSON(url, request, function( data, status, xhr ) {
					if ( xhr === lastXhr ) {
						response( data );
					}
				});
			},
			focus: function( event, ui ) {
				$( "#flixsearch" ).val( ui.item.label);
				return false;
			},
			select: function( event, ui ) {
				//redirect to ui.item.value
				PlayQuickSearch(ui.item);
				return false;
			}
		})
		.data( "autocomplete" )._renderItem = function( ul, item ) {
			return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( "<a title='" + item.source + "'>" + item.label + "</a>" )
				.appendTo( ul );
		};
		*/
		
		$( "#flixsearch" ).keypress(function(e)
		{
			if (e.keyCode == 13) 
			{
				//$(this).autocomplete("close");
				if($(this).val().length > 0){ BuildSearch($(this).val()); }
			}
		});

		$("#searchButton").click(function()
		{
			//$(this).autocomplete("close");
			if($("#flixsearch").val().length > 0){ BuildSearch($("#flixsearch").val()); }
		});
		
		$( "#category" ).autocomplete({
			minLength: 3,
			source: function( request, response ) {
				var term = request.term;
				if ( term in cacheCat ) {
					response( cacheCat[ term ] );
					return;
				}

				lastXhr = $.getJSON( "autocomplete.php?type=category", request, function( data, status, xhr ) {
					cacheCat[ term ] = data;
					if ( xhr === lastXhr ) {
						response( data );
					}
				});
			},
			focus: function( event, ui ) {
				$( "#category" ).val( ui.item.label);
				return false;
			}
		})
		.data( "autocomplete" )._renderItem = function( ul, item ) {
			return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( "<a>" + item.label + "</a>" )
				.appendTo( ul );
		};

		$( "#actorname" ).autocomplete({
			minLength: 3,
			source: function( request, response ) {
				var term = request.term;
				if ( term in cacheAct ) {
					response( cacheAct[ term ] );
					return;
				}

				lastXhr = $.getJSON( "autocomplete.php?type=actor", request, function( data, status, xhr ) {
					cacheAct[ term ] = data;
					if ( xhr === lastXhr ) {
						response( data );
					}
				});
			},
			focus: function( event, ui ) {
				$( "#actorname" ).val( ui.item.label);
				return false;
			}
		})
		.data( "autocomplete" )._renderItem = function( ul, item ) {
			return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( "<a>" + item.label + "</a>" )
				.appendTo( ul );
		};

		$( "#director" ).autocomplete({
			minLength: 3,
			source: function( request, response ) {
				var term = request.term;
				if ( term in cacheDir ) {
					response( cacheDir[ term ] );
					return;
				}

				lastXhr = $.getJSON( "autocomplete.php?type=director", request, function( data, status, xhr ) {
					cacheDir[ term ] = data;
					if ( xhr === lastXhr ) {
						response( data );
					}
				});
			},
			focus: function( event, ui ) {
				$( "#director" ).val( ui.item.label);
				return false;
			}
		})
		.data( "autocomplete" )._renderItem = function( ul, item ) {
			return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( "<a>" + item.label + "</a>" )
				.appendTo( ul );
		};
		
		$( "#accordion" ).accordion
		({
				autoHeight: false
		});
		
		$('#searchwizard input:button').button();
			
		//DO NOT DELET, THIS IS FOR THE BIG BUTTON, searchButton is for the smaller search button
		$('#searchbutton').click(function()
		{
			BuildSearch();
		});
		
		$('#clearbutton').click(function()
		{
			ClearSearch();
		});
		
		$('#view').change(function()
		{
			if(lastsearch !== ""){ RebuildSearch(); }
			SetPref('view');
		});
		
		$('#maxresults').change(function()
		{
			if(lastsearch !== ""){ RebuildSearch(); }
			SetPref('maxres');
		});
		
		$('.videosource').change(function()
		{
			SetPref('sources');
		});
		
		/*
		$('#queueDialog').dialog({
			title: 'Watch Queue',
			autoOpen: false,
			height:150,
			modal: true
		});
		
		$('#userDialog').dialog({
			autoOpen: false,
			modal: true
		});
		*/
		
		LoadPrefs();
		CheckHash();
		//ClearCookies();
	});
	
	function CheckHash()
	{
		//temporary - to allow bookmarks and linking direct to title searches
		var hash = window.location.hash.toString();
		if(hash != null && hash.replace('#', '').length > 0)
		{
			hash = decodeURI(hash.replace('#', ''));//decode so it's not encoded twice
			if(hash.indexOf('special:') == 0){ GetSpecial(hash.replace('special:', '')); }
			else
			{ 
				BuildSearch(hash); 
				$('#flixsearch').val(hash.replace('+', ' '));	//remove + type encoding
			}
			
		}
	}
	
	function SetHash(title)
	{
		if(title != null && title.length > 0)
		{
			var hash = window.location.hash;
			if(hash != null)
			{
				hash = hash.replace('#', '');
				if(hash != title)
				{
					window.location.hash = "#" + encodeURI(title);
				}
			}else{ window.location.hash = "#" + encodeURI(title); }
		}
	}
	
	function ClearCookies()
	{
		$.cookie('queue', null, { expires: 365, path: '/', raw : true});
	}
	/*
	function CreateQueue()
	{
		$("#queueDialog").html("<img src='images/ajax-loader-sm.gif'>");

		var link = "queue.php?fn=create";
		var ajaxreq = $.ajax({ url: link});

		ajaxreq.success(OnCreateQueueSuccess);
		ajaxreq.error(OnCreateQueueError);
	}
	
	function OnCreateQueueError(data)
	{
		$("#queueDialog").html("<p class='errortext'>ERROR: </p><p>An error occurred while processing your request.</p>");
		LoadQueueButtons();
		LoadQueueInfo();
	}
	
	function OnCreateQueueSuccess(data)
	{
		//TODO - parse json data
		var queue = $.parseJSON(data);
		if(queue.result !== "SUCCESS"){ Confirm("An error occurred while creating the local watch queue. Please wait a few moments and try again."); }
		else
		{
			$.cookie('queue', data, { expires: 365, path: '/' });
		}
		
		LoadQueueButtons();
		LoadQueueInfo();
	}
	
	function ManageQueue()
	{
		LoadQueueButtons();
		LoadQueueInfo();

		$('#queueDialog').dialog('open');
	}
	
	function LoadQueueInfo()
	{
		if(QueueExists())
		{
			try
			{
				var queue = $.parseJSON($.cookie('queue'));
				if(queue !== null)
				{
					var queueName = queue.name.length > 0 ? queue.name : "Default Local";
					$("#queueDialog").html("<p>Local Watch Queue: " + queueName + "</p>");
				}
				else{ $("#queueDialog").html("<p>ERROR: An error occurred while loading the watch queue info</p>"); }	
			}
			catch(err)
			{
				$("#queueDialog").html("<p>ERROR: " + err + "</p>");
			}
		}
		else
		{
			$("#queueDialog").html("<p>Click 'Create' to create a local watch queue.</p>");
		}
	}
	
	function LoadQueueButtons()
	{
		var buttons = [
				{
					text: "Help",
					click: function() { Go('help.php#queue', '_self'); }
				}];
			
		if(QueueExists())
		{
			buttons.push(
				{
					text: "Clear",
					click: function() { ClearQueue(); }
				}
			);
		}
		else
		{
			buttons.push(
				{
					text: "Create",
					click: function() { CreateQueue(); }
				}
			);
		}
		
		buttons.push(
			{
				text: "Manage",
				click: function() { GotoQueue('manage'); }
			},
			{
				text: "Play",
				click: function() { GotoQueue('play'); }
			}
		);
		
		$('#queueDialog').dialog( "option", "buttons", buttons);
	}
	
	function GotoQueue(fn)
	{
		if(QueueExists())
		{
			var queue = $.parseJSON($.cookie('queue'));
			var link = "queue.php";
			link += MakeUrlParam('fn', fn, true) + MakeUrlParam("qid", queue.id, false) + MakeUrlParam("qkey", queue.key, false);
			Go(link, '_self');
		}
	}
	
	function ClearQueue()
	{
		$.cookie('queue', null, { expires: 365, path: '/', raw : true});
	}
	
	function ManageUser()
	{
		//present login box with button to register or retrieve password
		var buttons = [
				{
					text: "Login",
					click: function() { Go('help.php#queue', '_self'); }
				},
				{
					text: "Cancel",
					click: function() { Go('help.php#queue', '_self'); }
				}];
		$('#userDialog').dialog( "option", "buttons", buttons);
		$('#userDialog').dialog('open');
	}
	*/
	
	function Page(p)
	{
		if(lastsearch != null && lastsearch != '' && p > 0)
		{
			var url = lastsearch;
			
			if($("#view option:selected").val().length > 0){ url += "&view=" + encodeURI($("#view option:selected").val()); }
			if($("#maxresults option:selected").text().length > 0){ url += "&maxresults=" + encodeURI($("#maxresults option:selected").text()); }
			else{ url += "maxresults=25"; }
			
			url += "&page=" + p;
			
			GetRemoteData(url);
		}
		
	}
	
	function LoadPrefs()
	{
		var viewPref = $.cookie('view');
		if(viewPref != null)
		{
			$('#view option[value=' + viewPref + ']').attr('selected', 'selected');
		}
		
		var maxResPref = $.cookie('maxres');
		if(maxResPref != null)
		{
			$('#maxresults option[value=' + maxResPref + ']').attr('selected', 'selected');
		}
		
		var sourcesPref = $.cookie('sources');
		if(sourcesPref != null)
		{
			//uncheck all first
			$('#videosourcebox input').attr('checked', false);
			var sources = sourcesPref.split('|');
			for(var i in sources)
			{
				$('#videosourcebox input[value=' + sources[i] + ']').attr('checked', true);
			}
		}
				
		/*
		var homePref = $.cookie('homepage');
		if(homePref != null)
		{
			GetSpecial(homePref);
		}
		*/
	}
	
	function SetPref(pref, prefValue)
	{
		switch(pref)
		{
			case 'view':
				if($("#view option:selected").val().length > 0)
				{ 
					$.cookie('view', $("#view option:selected").val(), { expires: 365, path: '/', raw : true });
				}
				break;
			case 'maxres':
				if($("#maxresults option:selected").val().length > 0)
				{ 
					$.cookie('maxres', $("#maxresults option:selected").val(), { expires: 365, path: '/', raw : true });
				}
				break;
			case 'sources':
				var sources = GetSourcesArray();
				if(sources != null){ $.cookie('sources', sources.join('|'), { expires: 365, path: '/', raw : true }); }
				else{ $.cookie('sources', null); }
				break;
			case 'homepage':
				$.cookie('homepage', prefValue);
				break;
			default:
				break;
		}
	}
	
	function GetSpecial(special, page)
	{
		var url = "search.php?";
		
		if(special == "watchfavs"){ PostQid(); }
		
		url += "special=" + special;
		url += GetSources();
		
		lastsearch = url;
		if(page != null & page > 0){ url += "&page=" + page; }
		
		if($("#view option:selected").val().length > 0){ url += "&view=" + encodeURI($("#view option:selected").val()); }
		if($("#maxresults option:selected").text().length > 0){ url += "&maxresults=" + encodeURI($("#maxresults option:selected").text()); }
		else{ url += "maxresults=25"; }

		GetRemoteData(url);
		
		SetPref('homepage', special);
		SetHash("special:" + special);
	}

	function PostQid()
	{
		if(QueueExists() && !qidPosted)
		{
			if(qid == null || qkey == null)
			{
				var queue = $.parseJSON($.cookie('queue'));
				qid = queue.id;
				qkey = queue.key;
			}
			
			var ajaxreq = $.ajax
			({ 
				url: baseUrl + "favs.php", 
				type : "POST", 
				data : {fn : "register", qid : qid, qkey : qkey},
				async : false,
				success : function(data)
					{
						qidPosted = true;
					},
				error : function(data)
					{
						Confirm("An error occurred while trying to submit. To add shows to your favs, use the ManageQueue page.");
					}
			});
		}
	}
	
	function PlayQuickSearch(item)
	{
		//if(item.source.toLowerCase() == "netflix"){ PlayFlix(item.value); } else //removed because of netflix broken api
		if(item.source.toLowerCase() == "error"){ return false; }
		else { Go(item.value); }
	}
	
	function PlayFlix(id)
	{
		//GO(http://movies.netflix.com/WiPlayer?movieid=70140443);
		nflx.openPlayer(id, 0, 0, '4gqzw7wqncjjxv79e28r2zj8');
	}
	
	function QueueFlix(id, type)
	{
		//type = disc or instant
		var xpos = ($(window).width() /2) - (434/2);
		var ypos = ($(window).height() /2) - (230/2);
		
		nflx.addToQueue(id, xpos, ypos, '4gqzw7wqncjjxv79e28r2zj8', type, 'addMe');
	}
	
	function RebuildSearch()
	{
		var url = lastsearch;
		if($("#view option:selected").val().length > 0){ url += "&view=" + encodeURI($("#view option:selected").val()); }
		if($("#maxresults option:selected").text().length > 0){ url += "&maxresults=" + encodeURI($("#maxresults option:selected").text()); }
		else{ url += "maxresults=25"; }
		
		GetRemoteData(url);
	}

	function ChangePage(page)
	{
		var url = "";
		if(lastsearch != null && lastsearch != '')
		{ 
			url = lastsearch + "&page=" + page;
			if($("#view option:selected").val().length > 0){ url += "&view=" + encodeURI($("#view option:selected").val()); }
			if($("#maxresults option:selected").text().length > 0){ url += "&maxresults=" + encodeURI($("#maxresults option:selected").text()); }
			else{ url += "maxresults=25"; }
		
			GetRemoteDate(url);
		}
		else
		{
			BuildSearch();
		}
		
	}
	
	function GetSourcesArray()
	{
		if($("#videosourcebox input:checked").length > 0)
		{
			var sources = [];
			$("#videosourcebox input:checked").each(function(i)
			{
				sources[i] = $(this).val();
			});
			return sources;
		}
		else{ return null; }
	}
	
	function GetSources()
	{
		if($("#videosourcebox input:checked").length > 0)
		{
			var sources = GetSourcesArray();
			return "&source=" + encodeURI(sources.join('|'));
		}
		else
		{
			return "";
		}
	}
	
	function BuildSearch(title)
	{
		var url = "search.php?";
		if($("#sort option:selected").val().length > 0){ url += "sort=" + encodeURI($("#sort option:selected").val()); } //first because it should always have a value
		if($("input[name='sortdir']:checked").val().length > 0){ url += "&sortdir=" + encodeURI($("input[name='sortdir']:checked").val()); }
		
		url += GetSources();
		
		if($("#delivery option:selected").val().length > 0)
		{
			var delivs = [];
			$('#delivery option:selected').each(function(i, selected)
			{
				delivs[i] = $(selected).val();
			});
			url += "&delivery=" + encodeURI(delivs.join('|')); 
		}
		
		if($("#videotype option:selected").val().length > 0)
		{
			var vidtypes = [];
			$('#videotype option:selected').each(function(i, selected)
			{
				vidtypes[i] = $(selected).val();
			});
			url += "&videotype=" + encodeURI(vidtypes.join('|')); 
		}
		
		/*
		if($("#mpaa option:selected").val().length > 0)
		{
			var mpaa = [];
			$('#mpaa option:selected').each(function(i, selected)
			{
				mpaa[i] = $(selected).val();
			});
			url += "&mpaa=" + encodeURI(vidtypes.join('|')); 
		}
		*/
		
		var t = '';
		if(title == null)
		{
			if($("#flixsearch").val().length > 0){ t = $("#flixsearch").val(); }
		}
		else if(title.length > 0){ t = title; }
		
		if(t.length > 0)
		{ 
			url += "&title=" + encodeURIComponent(t);
			SetHash(t);	
		}
				
		if($("#minyear").val().length > 0){ url += "&minyear=" + encodeURI($("#minyear").val()); }
		if($("#maxyear").val().length > 0){ url += "&maxyear=" + encodeURI($("#maxyear").val()); }
		if($("#category").val().length > 0){ url += "&category=" + encodeURI($("#category").val()); }
		if($("#minrating").val().length > 0){ url += "&minrating=" + encodeURI($("#minrating").val()); }
		if($("#actorname").val().length > 0){ url += "&actorname=" + encodeURI($("#actorname").val()); }
		if($("#director").val().length > 0){ url += "&director=" + encodeURI($("#director").val()); }
		
		lastsearch = url;
		
		if($("#view option:selected").val().length > 0){ url += "&view=" + encodeURI($("#view option:selected").val()); }
		if($("#maxresults option:selected").text().length > 0){ url += "&maxresults=" + encodeURI($("#maxresults option:selected").text()); }
		else{ url += "maxresults=25"; }
		
		GetRemoteData(url);
	}
	
	function ClearSearch()
	{
		$("#delivery option:selected").attr("selected", false);
		$("#videotype option:selected").attr("selected", false);

		$("#sortorder option:contains(Release Year)").attr("selected", true);
		$("#delivery option:contains(All)").attr("selected", true);
		$("#videotype option:contains(All)").attr("selected", true);
		
		$("#flixsearch").val('');
		$("#minyear").val('');
		$("#maxyear").val('');
		$("#category").val('');
		$("#minrating").val('');
		$("#actorname").val('');
		$("#director").val('');
	}
	
	function GetRemoteData(link)
	{
		//wait cursor
		//$("body").css("cursor", "wait");				
		//reset cursor
		//$("body").css("cursor", "auto");

		$("#results").html("<img src='images/ajax-loader.gif'>");

		var ajaxreq = $.ajax({ url: link, cache : false});

		ajaxreq.success(OnSearchSuccess);
		ajaxreq.error(OnSearchError);
	}

	function OnSearchSuccess(data)
	{
		//load the content
		 $("#results").html(data);
	}

	function OnSearchError()
	{
		$("#results").html("<p class='errortext'>ERROR: </p><p>An error occurred while processing your request. Please wait a few moments and try again.</p>");
	}
