function gosearch(q, s, t) {
	return $.post("log.php", {
		query : q,
		site : s,
		tab : t
	});
}

function revealOptionalFields() {
	$("tr[isq='0']").show();
}

function hideOptionalFields() {
	$("tr[isq='0']").hide();
}

function initHideQueryFields() {
	$("input[id^='savechk_']:checked").each(function(i) {
		$("#masterQueryField").val($("input[qsf='" + $(this).attr('rsf') + "']").val());
		return;
	});
	$("tr[isq='1']").hide();
	$("#tfSpacer").show();
}

function updateQueryFieldsWithValue(value) {
	$("input[qsa='q']").val(value);
}

function submitCheckedForms() {
	$("input[id^='savechk_']:checked").each(function(i) {
		$("form[id='rsf_" + $(this).attr('rsf') + "']").submit();
	});
}

function serializeCheckedForms() {
	var list = {};
	$("input[id^='savechk_']:checked").each(function(i) {
		var rsf = $(this).attr('rsf');
		list[rsf] = $("form[id='rsf_" + rsf + "']").serialize();
	});
	return list;
}

function login(username, password) {
	var result = '';
	$.post("login.php", {
		'username' : username,
		'password' : password
	}, function(data) {
		result = data;
	});
	return result;
}

function logout() {
	$.get("logout.php", function(data) {
		window.location = '/?tab=default';
	});
}

function clickLoginButton() {
	$('#username').removeClass('ui-state-error');
	$('#password').removeClass('ui-state-error');
	$.post(
			'login.php',
			{
				'username' : $("#username")
						.val(),
				'password' : $("#password")
						.val()
			},
			function(data) {
				switch (data) {
				case 'ls':
					$("#loginDialog")
							.dialog('close');
					window.location = '/?tab=searches';
					break;
				case 'bp':
					// bad password
					$("#password")
							.addClass(
									'ui-state-error');
					$("#validateTips")
							.html(
									'You have entered an invalid password. Please try again.');
					break;
				case 'uu':
					// unknown user
					$("#username")
							.addClass(
									'ui-state-error');
					$("#validateTips")
							.html(
									'The e-mail address you have entered is not recognized. Please try again.');
					break;
				case '0':
					// account not
					// initialized
					$("#username")
							.addClass(
									'ui-state-error');
					$("#password")
							.addClass(
									'ui-state-error');
					$("#validateTips")
							.html(
									'The account you are trying to access has not been confirmed. Please check your e-mail and click on the confirmation link in the welcome e-mail.');
					break;
				case '2':
					// account compromised
					$("#username")
							.addClass(
									'ui-state-error');
					$("#validateTips")
							.html(
									'The account you are trying to access has been flagged as compromised. Please check your e-mail for more information.');
					break;
				}
			});
}

function showLoginDialog() {
	$("#loginDialog")
			.dialog(
					{
						bgiframe : true,
						dialogClass : 'stdDialog',
						modal : true,
						buttons : {
							'Log-in' : function() {
								var bValid = true;
								$('#username').removeClass('ui-state-error');
								$('#password').removeClass('ui-state-error');

								// bValid = bValid &&
							// checkLength($("#username"), "username", 6,
							// 80);
							// bValid = bValid && checkLength($("#password"),
							// "password", 5, 16);
							// bValid = bValid &&
							// checkRegexp($("#username"),/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg.
							// ui@jquery.com");
							// bValid = bValid &&
							// checkRegexp($("#password"),/^([0-9a-zA-Z])+$/,"Password
							// field only allow : a-z 0-9");

							if (bValid) {
								clickLoginButton();
							}
						},
						/*'Register' : function() {
							$(this).dialog('close');
							window.location = '/?tab=register';
						},*/
						Cancel : function() {
							$(this).dialog('close');
						}
						},
						close : function() {
							$("#username").val('')
									.removeClass('ui-state-error');
							$("#password").val('')
									.removeClass('ui-state-error');
							$("#validateTips")
									.html(
											'If you have an account, enter your e-mail address and password below. If you do not, click to <a href="/?tab=register">register</a> for a free account.');
						}
					});
}

function saveSearchAs(title) {
	$('dialog').html('Loading...');
	var postVars = {
		'title' : title,
		'tab' : $("div.fulltab").attr('tsi'),
		'data' : $.toJSON(serializeCheckedForms())
	};

	$
			.post(
					"savesearch.php",
					postVars,
					function(data) {
						if (data == "+OK") {
							$('#dialog')
									.html(
											'<p><span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>Your search has been saved successfully.</p>');
						} else {
							$('#dialog')
									.html(
											'<p>There was an error saving your search.</p>');
						}
					});
	$("#dialog").dialog( {
		bgiframe : true,
		modal : true,
		title : 'Save Search Result',
		dialogClass : 'stdDialog',
		buttons : {
			Ok : function() {
				$(this).dialog('close');
			}
		}
	});
}

function deleteDialog(id, title) {
	$('#dialog').html('Are you sure you want to delete your search: ' + title + '?');
	$("#dialog").dialog( {
		bgiframe : true,
		modal : true,
		title : 'Delete Search Confirmation',
		dialogClass : 'stdDialog',
		buttons : {
			Yes : function() {
				$.post('deletesearch.php', {
					'id': id
				}, function(data) {
					if(data == "+OK") {
						$("#dialog").dialog('close');
						window.location = '/?tab=searches';
					} else {
						//alert(data);
					}
			}
				);
	},
			No : function() {
				$(this).dialog('close');
			}
		}
	});
}

function editSearch(id, title) {
	$('#dialog').html('Loading...');
	var postVars = {
		'title' : title,
		'tab' : $("div.fulltab").attr('tsi'),
		'mode' : 'edit',
		'search' : id,
		'data' : $.toJSON(serializeCheckedForms())
	};

	$
			.post(
					"savesearch.php",
					postVars,
					function(data) {
						if (data == "+OK") {
							$('#dialog')
									.html(
											'<p><span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>Your search has been saved successfully.</p>');
						} else {
							$('#dialog')
									.html(
											'<p>There was an error saving your search.</p>');
						}
					});
	$("#dialog").dialog( {
		bgiframe : true,
		modal : true,
		title : 'Save Search Result',
		dialogClass : 'stdDialog',
		buttons : {
			Ok : function() {
				$(this).dialog('close');
			}
		}
	});
}

function checkRegexp(o, regexp, n) {
	if (!(regexp.test(o.val()))) {
		o.addClass('ui-state-error');
		return false;
	} else {
		return true;
	}
}

function checkLength(o, n, min, max) {
	if (o.val().length > max || o.val().length < min) {
		o.addClass('ui-state-error');
		return false;
	} else {
		return true;
	}
}
