var triggered = false;
var ajaxBusy = false;
var availableTags = [ "none" ];
var containerdata = "";
var containerdata2 = "";
var last_user;

$(document).ready(function() {
	$("header").fadeTo(600, 1, function(){
		$("#login_content").html($("#login_credentials_text").html());
		$("#content").fadeTo(600, 1);
	});
	
	/*$.post("index.php/search/suggestions/keyword", function(data){
		availableTags  = eval("(" + data + ")");
		
		$("#keyword").autocomplete({
			source: availableTags,
			minLength: 2
		});
	});*/
	
	initSimpletips();
});

function initSimpletips()
{
	$("#must_include").simpletip({
	   // Configuration properties
	   content: 'Any word entered here will instruct us to only show<br />results that include that word.<br /><br />For example, you could enter the word &quot;iPhone&quot; as a<br />filter for the keyword &quot;Apple&quot;, and you will see only<br /> iPhone-related results.<br /><br />You can also use this field to narrow results to country<br />specific domains such as &quot;.com.au&quot;',
	   fixed: true
	});
	
	$("#do_not_include").simpletip({
		content: 'Any word entered here will instruct us to ignore any<br /> results that include that word.<br /><br />For example, you could enter the word &quot;Mac&quot; as a<br />filter for the keyword &quot;Apple,&quot; and we will exclude<br /> any results that mention &quot;Mac.&quot;<br /><br />You can also use this field to filter out specific domain<br />names; for example &quot;mydomain.com&quot;',
		fixed: true
	});
	
	$("#exclude_domains").simpletip({
		content: 'Any domain entered here will instruct us to ignore any<br /> results from that domain.<br /><br />For example you could enter &quot;digg.com&quot; and any results<br />from that domain will not show, but if that domain is<br /> mentioned in a result it will still show.',
		fixed: true
	});
	
	$("#filter_sources").simpletip({
		content: 'These checkboxes determine what kind of results you\'ll see.<br /> Uncheck them to exclude entire content services from showing in your results panel.',
		fixed: true
	});

	$("#date_warning").simpletip({
		content: 'You can only filter as far back as the date you first saved your search to the dashboard. We do not keep an archive of any results published prior to this date.',
		fixed: true
	});
}

function ajaxClear()
{
	if (ajaxBusy == true)
	{
		return false;
	}
	
	$("#loader_alert").fadeIn(300);
	ajaxBusy = true;
	return true;
}

function ajaxClearNoPop()
{
	if (ajaxBusy == true)
	{
		return false;
	}
	
	ajaxBusy = true;
	return true;
}

function ajaxFinished()
{
	ajaxBusy = false;
	$("#loader_alert").fadeOut(300);
}

function resetPass()
{
	var username = last_user;

	var url = "http://track.trackur.com/register/forgot_pass.php?task=forgot_pass&username=" + username
	$.post(url, function(data){
		alert("Please check the email address associated with your account.");
	});
}

function ajaxDeleteProfile(id)
{
	$.post('index.php/settings/delete_profile/' + id, function(data){
		settingsPage('manageprofiles');
	});
}

function cleanKeyword(keyword)
{
	return keyword.replace(/[^a-zA-Z 0-9\.+\-&ç#']/g,'');
}

function toggleAll()
{
	$('.result_expanded').slideToggle(1);
	$('.result_expanded').each(function() {
		var id = this.id;
		id = id.substring(6, id.length);
		$.post("index.php/search/read/" + id);
		$('#title' + id).css('fontWeight', 'normal');
	});
}

function centered_popup(page, w, h) 
{
	$.post("index.php/popup/" + page, function(data){
			$('.popup').html(data);
			$(".overlay").fadeTo(400, 0.5);
			$('.popup').width(w);
			$('.popup').height(h);
			$('.popup').css('margin-left', w * -0.5);
			$('.popup').fadeTo(800, 1);
		});
}

function closePopup()
{
	$(".popup").fadeTo(400, 0);
	$(".overlay").fadeTo(600, 0, function(){
			$(".overlay").hide();
			$(".popup").hide();
			$(".popup").html("");
		});
}

function shareArticle()
{
	var regex = /^((([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;
	var isValid = regex.test($('#share_email').val());

	if (isValid)
	{
		$.post('index.php/popup/send_article', $("#shareForm").serialize(), function(data){
			$(".share_body").fadeTo(400, 0, function(){
				$('.share_body').html(data);
				$(".share_body").fadeTo(400, 1, function(){
						//setTimeout("closePopup()",1250);
					});
			});
		});
	}
	else
	{
		$(".validateTips").html("Valid email required! (I.E. Address@Service.com)");
	}
}

function setSorting(filter, value)
{
	if (ajaxClear() == true)
	{
		$.post('index.php/query/setsorting/' + filter + '/' + value, function(data){
			ajaxFinished();
			refineSearch();
		});
	}
}

function unsetSorting()
{
	if (ajaxClear() == true)
	{
		$.post('index.php/query/unsetsorting', function(data){
			ajaxFinished();
			refineSearch();
		});
	}
}

function setDateFilter(keyword)
{
	if (ajaxClear() == true)
	{
		var day1 = $("#day1").val();
		var day2 = $("#day2").val();
		var month1 = $("#month1").val();
		var month2 = $("#month2").val();
		var year1 = $("#year1").val();
		var year2 = $("#year2").val();
		var url = "index.php/query/datesort/" + day1 + "/" + day2 + "/" + month1 + "/" + month2 + "/" + year1 + "/" + year2;
		$.post(url, function(data, textStatus, XMLHttpRequest){
			ajaxFinished();
			refineSearch();
		});
	}
}

function clearFilters(keyword)
{
	if (ajaxClear() == true)
	{
		var url = "index.php/query/clear_filters";
		$.post(url, function(data, textStatus, XMLHttpRequest){
			ajaxFinished();
			refineSearch();
		});
	}
}

function loadSettings()
{
	if (containerdata == "")
	{
		$('#dashboard_right').fadeTo(600, 0, function(){
			containerdata = $('#dashboard_right').html();
			$("#settingslink").html('<span class="theme_color">Search Results</span>');
			$('#dashboard_right').load('index.php/settings/settingsmain', function(){
				$('#dashboard_right').fadeTo(600, 1);
			});
		});
	}
	else
	{
		$('#dashboard_right').fadeTo(600, 0, function(){
			$("#settingslink").html('<span class="theme_color">Settings</span>');
			$('#dashboard_right').html(containerdata);
			containerdata = "";
			$('#dashboard_right').fadeTo(600, 1);
		});
	}
}

function excludeDomain(url, id)
{
	if (ajaxClear() == true)
	{
		$.post("index.php/settings/add_exclude", {url: url}, function(data, textStatus, XMLHttpRequest){
			ajaxFinished();
			$('#preview' + id).slideToggle();
		});
	}
}

function editProfile(id)
{
	if (ajaxClear() == true)
	{
		$('#edit_area').fadeTo(300, 0, function(){
			$.post("index.php/settings/view_profile/" + id, function(data, textStatus, XMLHttpRequest){
				ajaxFinished();
				$('#edit_area').html(data);
				$('#edit_area').fadeTo(300, 1);
			});
		});
	}
}

function addProfile()
{
	if (ajaxClear() == true)
	{
		$('#edit_area').fadeTo(300, 0, function(){
			$.post("index.php/settings/view_addprofile", function(data, textStatus, XMLHttpRequest){
				ajaxFinished();
				$('#edit_area').html(data);
				$('#edit_area').fadeTo(300, 1);
			});
		});
	}
}

function ajaxCreateProfile()
{
	if (ajaxClear() == true)
	{
		var name = $("input:text[name=name]").val();
		var custom_username = $("input:text[name=custom_username]").val();
		var custom_password = $("input:password[name=custom_password]").val();
		var email = $("input:text[name=email]").val();
		var from_email = $("input:text[name=from_email]").val();
		var read_only = $("input:checkbox[name=read_only]:checked").val();
		var alert_daily = $("input:radio[name=alert_daily]:checked").val();
		var smtp_host = $("input:text[name=smtp_host]").val();
		var smtp_user = $("input:text[name=smtp_user]").val();
		var smtp_pass = $("input:text[name=smtp_pass]").val();
		var alert_time = $("#alert_time").val();

		if (name == "")
		{
			settingsAlert('.upload_alert', "<h3>You must choose a profile name.</h3>");
			return;
		}
		else
		{
			var json = {
				name: name,
				custom_username: custom_username,
				custom_password: custom_password,
				email: email,
				from_email: from_email,
				read_only: read_only,
				alert_daily: alert_daily,
				smtp_host: smtp_host,
				smtp_user: smtp_user,
				smtp_pass: smtp_pass,
				alert_time: alert_time
			};

			$.post("index.php/settings/add_profile", json, function(data, textStatus, XMLHttpRequest){
				ajaxFinished();
				alert(data);
				if (data != "Successfully updated profile!")
				{
					settingsAlert('.upload_alert', "<h3>" + data + "</h3>");
				}
				else
				{
					$('.upload_alert').html("<h3>" + data + "</h3");
					$('.upload_alert').fadeTo(200, 1, function(){
						settingsPage('manageprofiles');
					});
				}
			});
		}
	}
}

function ajaxSaveProfile(id)
{
	if (ajaxClear() == true)
	{
		var name = $("input:text[name=name]").val();
		var custom_username = $("input:text[name=custom_username]").val();
		var custom_password = $("input:password[name=custom_password]").val();
		var email = $("input:text[name=email]").val();
		var from_email = $("input:text[name=from_email]").val();
		var alert_daily = $("input:radio[name=alert_daily]:checked").val();
		var read_only = $("input:checkbox[name=read_only]:checked").val();
		var smtp_host = $("input:text[name=smtp_host]").val();
		var smtp_user = $("input:text[name=smtp_user]").val();
		var smtp_pass = $("input:text[name=smtp_pass]").val();
		var alert_time = $("#alert_time").val();

		if (name == "")
		{
			settingsAlert('.upload_alert', "<h3>You must choose a profile name.</h3>");
			return;
		}
		else
		{
			var json = {
				id: id,
				name: name,
				custom_username: custom_username,
				custom_password: custom_password,
				email: email,
				from_email: from_email,
				alert_daily: alert_daily,
				read_only: read_only,
				smtp_host: smtp_host,
				smtp_user: smtp_user,
				smtp_pass: smtp_pass,
				alert_time: alert_time
			};

			$.post("index.php/settings/edit_profile/" + id, json, function(data, textStatus, XMLHttpRequest){
				ajaxFinished();
				if (data != "Successfully updated profile!")
				{
					settingsAlert('.upload_alert', "<h3>" + data + "</h3>");
				}
				else
				{
					$('.upload_alert').html("<h3>" + data + "</h3");
					$('.upload_alert').fadeTo(200, 1, function(){
						settingsPage('manageprofiles');
					});
				}
			});
		}
	}
}

function submitComment(url)
{
	if (ajaxClear() == true)
	{
		var txt = $('#comment').val();
		$.post("index.php/influence/comment", {url: url, comment: txt}, function(data, textStatus, XMLHttpRequest){
			ajaxFinished();
			$("#dashboard_right").fadeTo(600, 0, function(){
				$.post("index.php/influence/traffic/" + url, function(data){
					$("#dashboard_right").html(data);
					$("#dashboard_right").fadeTo(600, 1);
				});
			});
		});
	}
}

function submitKlout(url, twit)
{
	if (ajaxClear() == true)
	{
		var txt = $('#comment').val();
		$.post("index.php/influence/comment", {url: url, comment: txt}, function(data, textStatus, XMLHttpRequest){
			ajaxFinished();
			$("#dashboard_right").fadeTo(600, 0, function(){
				$.post("index.php/influence/traffic/" + twit, function(data){
					$("#dashboard_right").html(data);
					$("#dashboard_right").fadeTo(600, 1);
				});
			});
		});
	}
}

function verifyFeed(txt)
{
	if (ajaxClear() == true)
	{
		txt = $('#feedurl').val();
		$.post("index.php/settings/valid_feed/", {url: txt}, function(data, textStatus, XMLHttpRequest){
			ajaxFinished();
			if (data == "1")
			{
				$("#verify_pass").css("display", "block");
				$("#verify_fail").css("display", "none");
				$("#addfeed_button").html("<button class=\"button\" onclick=\"return ajaxAddFeed();\">Add Feed</button>");
			}
			else
			{
				$("#verify_pass").css("display", "none");
				$("#verify_fail").css("display", "block");
				$("#addfeed_button").html("");
			}
		});
	}
}

function ajaxAddFeed()
{
	if (ajaxClear() == true)
	{
		var txt = $('#feedurl').val();
		$.post("index.php/settings/add_custom_feed", {url: txt}, function(data, textStatus, XMLHttpRequest){
			ajaxFinished();
			settingsPage('customfeeds');
		});
	}
}

function toggleFeed(id)
{
	if (ajaxClear() == true)
	{
		$.post("index.php/settings/toggle_active_feed/" + id, function(data, textStatus, XMLHttpRequest){
			ajaxFinished();
			settingsPage('customfeeds');
		});
	}
}

function removeFeed(id)
{
	if (ajaxClear() == true)
	{
		$.post("index.php/settings/remove_feed/" + id, function(data, textStatus, XMLHttpRequest){
			ajaxFinished();
			settingsPage('customfeeds');
		});
	}
}

function startTypeWatch()
{
	var options = {
		callback: verifyFeed,
		highlight:true
	}

	$("input:text[name=url]").typeWatch(options);
}

function loadInfluence(url)
{
	if (containerdata2 == "")
	{
		$("#dashboard_right").fadeTo(600, 0, function(){
			containerdata2 = $("#dashboard_right").html();
			$.post("index.php/influence/traffic/" + url, function(data){
				$("#dashboard_right").html(data);
				$("#dashboard_right").fadeTo(600, 1);
			});
		});
	}
	else
	{
		$('#dashboard_right').fadeTo(600, 0, function(){
			$('#dashboard_right').html(containerdata2);
			containerdata2 = "";
			$('#dashboard_right').fadeTo(600, 1);
		});
	}
}

function settingsPage(page)
{
	$('#dashboard_right').fadeTo(600, 0, function(){
		$('#dashboard_right').load('index.php/settings/settings' + page, function(){
			$('#dashboard_right').fadeTo(600, 1);
		});
	});
}

function swapProfiles()
{
	$.post("index.php/dashboard/setprofile/" + $("#active_profile").val(), function(){
		javascript:location.reload(true);
	});
}

function refreshSearches(id)
{
	$('#reload_msg').html("<img style='border: 1px solid black; background-color: white;' src='../images/reload_spin.gif' />Checking for new results</div>");
	$.post("index.php/cron/userAppease/" +  id, function(data){
		if (data != "error")
			$('#reload_msg').html("<img style='border: 1px solid black; background-color: white;' src='../images/reload_static.png' />Results Updated");
		else
			$('#reload_msg').html("Please try again in 30 minutes.");
	});
}

function ajaxSaveDetails()
{
	if (ajaxClear() == true)
	{
		var fname = $("input:text[name=fname]").val();
		var lname = $("input:text[name=lname]").val();
		var pass = $("input:password[name=pass]").val();
		var pass2 = $("input:password[name=pass2]").val();
		var email = $("input:text[name=email]").val();
		var plain = $("input:checkbox[name=plaintext]:checked").val();

		if (pass == pass2)
		{
			$.post("index.php/settings/update_user", {first_name: fname, last_name: lname, password: pass, emailaddr: email, plaintext: plain}, function(data, textStatus, XMLHttpRequest){
				ajaxFinished();
				if (data != "Successfully updated account details!")
				{
					settingsAlert('.upload_alert', "<h3>" + data + "</h3>");
				}
				else
				{
					$('.upload_alert').html("<h3>" + data + "</h3");
					$('.upload_alert').fadeTo(200, 1, function(){
						swapContents('ajax_settings.php');
					});
				}
			});
		}
		else
		{
			alert("Your passwords don't match.");
		}
	}
}

function ajaxUpdateExcludes()
{
	if (ajaxClear() == true)
	{
		var url = "index.php/settings/update_excludes/" + $("#pid").val() + "/";
		var exclude_string = escape($("#domains").val());
		
		$.post(url, {excludes: exclude_string}, function(data, textStatus, XMLHttpRequest){
			ajaxFinished();
			if (data != "Successfully updated excluded domains list!")
			{
				settingsAlert('.upload_alert', "<h3>" + data + "</h3>");
			}
			else
			{
				$('.upload_alert').html("<h3>" + data + "</h3");
				$('.upload_alert').fadeTo(200, 1, function(){
					settingsPage('excludes');
				});
			}
		});
	}
}

function ajaxSwapExcludeProfile()
{
	$('#dashboard_right').fadeTo(600, 0, function(){
		$('#dashboard_right').load('index.php/settings/settingsexcludes/' + $("#pid").val(), function(){
			$('#dashboard_right').fadeTo(600, 1);
		});
	});
}

function ajaxUpdateSubscription()
{
	$('#dashboard_right').fadeTo(600, 0, function(){
		$.post('index.php/settings/updatesubscription/', $(".subscriptionForm").serialize(), function(data){
			$('#dashboard_right').fadeTo(600, 1);
		});
	});
}

function setColor(color)
{
	ajaxFinished();
	$('.colorbox').fadeTo(200, 0, function(){
		$('.colorbox').css('backgroundColor', color);
		$('.colorbox').fadeTo(200, 1);
	});
}

function ajaxSaveSubdom()
{
	var subdom = $("input:text[name=subdomain]").val();

	$.post("index.php/settings/subdomain/" + subdom, function(data, textStatus, XMLHttpRequest){
		
		if (data != "Domain successfully added to system.")
		{
			settingsAlert('.settings_alert', "<h3>" + data + "</h3>");
		}
		else
		{
			settingsAlert('.settings_alert', "<h3>Your new URL is http://" + subdom + ".trackur.com/</h3>");
		}
	});
}

function ajaxSaveDomain()
{
	var domain = $("input:text[name=domain]").val();
	
	$.post("index.php/settings/domain/" + domain, function(data, textStatus, XMLHttpRequest){
		
		if (data != "Domain successfully added to system.")
		{
			settingsAlert('.settings_alert', "<h3>" + data + "</h3>");
		}
		else
		{
			$('.settings_alert').html("<h3>Domain successfully added to system.</h3>");
			alert("Please make sure your systems administrator adds an A RECORD in the DNS of your domain pointing to 199.168.184.90 -- This feature will NOT work until this step is completed.");
		}
	});
}

function ajaxSaveEmail()
{
	var email = $("input:text[name=email]").val();
	
	$.post("index.php/settings/from_email", {email_address: email}, function(data, textStatus, XMLHttpRequest){
		
		if (data != "Notification Email successfully changed.")
		{
			settingsAlert('.settings_alert', "<h3>" + data + "</h3>");
		}
		else
		{
			$('.settings_alert').html("<h3>Notification Email successfully changed.</h3>");
			
		}
	});
}

function ajaxSaveTitle()
{
	var pagetitle = $("input:text[name=pagetitle]").val();
	
	$.post("index.php/settings/title/" + escape(pagetitle), function(data, textStatus, XMLHttpRequest){
		
		if (data != "Page title successfully changed.")
		{
			settingsAlert('.settings_alert', "<h3>" + data + "</h3>");
		}
		else
		{
			$('.settings_alert').html("<h3>Page title successfully changed.</h3>");
			
		}
	});
}

function updateTheme()
{
	if (ajaxClear() == true)
	{
		settingsAlert('.settings_alert', "<h3>Updating settings.. Please wait <img src='images/ajaxSpinner.gif' alt='loading' /></h3>");
		
		var color = $('input:radio[name=theme]:checked').val();
		var url = "index.php/settings/color/" + color;
		$.post(url, function(){
			ajaxFinished();
			settingsAlert('.settings_alert', "<h3>Theme updated. Refresh your browser to see changes.</h3>");
		});
	}
}

function settingsAlert(element, message)
{
	ajaxFinished();
	$(element).fadeTo(300, 0, function(){
		$(element).html(message);
		$(element).fadeTo(300, 1);
	});
}

function checkForLogin(event)
{
	if (event.keyCode == '13') {
			processLogin();
		}
}

function checkForSearch(event)
{
	if (event.keyCode == '13') {
			doSearch();
		}
}
//--------------------------------------------------------------------------------------------
function createSearch(keyword)
{
	$('#keyword').val(keyword);
	doSearch();
}


function ajaxLogout()
{
	$.post("index.php/dashboard/logout/", function(data, textStatus, XMLHttpRequest){
		javascript:location.reload(true);
	});
}

function toggleAdvanced()
{
	$('#advanced').slideToggle(300);
}

function ajaxFileUpload(id)
{
	if (ajaxClear() == true)
	{
		settingsAlert('.upload_alert', "<h3>Uploading image.. Please wait <img src='images/ajaxSpinner.gif' alt='loading' /></h3>");
		
		$.ajaxFileUpload
		(
			{
				url: 'ajax_fileupload.php?user=' + id, 
				secureuri: false,
				fileElementId: 'fileToUpload',
				dataType: 'json',
				success: function (data, status)
				{
					if(typeof(data.error) != 'undefined')
					{
						if(data.error != '')
						{
							settingsAlert('.upload_alert', "<h3> Error: " + data.error + "</h3>");
						}
						else
						{
							settingsAlert('.upload_alert', "<h3>File upload successful.</h3>");
							settingsAlert('.settings_alert', "<h3>Logo updated. Refresh your browser to see changes.</h3>");
						}
					}
				},
				error: function (data, status, e)
				{
					settingsAlert('.upload_alert', "<h3> Error: " + e + "</h3>");
				}
			}
		)
		ajaxFinished();
		return false;
	}
} 

function resetLogin()
{
	$("#login_reset").fadeTo(400, 0, function(){
		$("#userid").val("");
		$("#passwd").val("");
		
		$("#login_loader").fadeTo(600, 0, function(){
			$("#login_loader").attr("id", "login_content");
			$("#login_content").html($("#login_credentials_text").html());
			$("#login_content").fadeTo(600, 1);
		});
	});
}

function toggleElement(id)
{
	$('#result' + id).slideToggle(0);
	$('#title' + id).css('fontWeight', 'normal');
	$.post("index.php/search/read/" + id);
}

function deleteResult(id)
{
	$.post("index.php/query/deleteResult/" + id, function(data){
			ajaxFinished();
			$('#preview' + id).slideToggle();
		});
}

function addFavorite(id)
{
	$.post("index.php/query/favorite/" + id);
	$("#favorite" + id).fadeTo(600, 1);
	$("#addremovefavorite" + id).html("<a href=\"javascript: removeFavorite('" + id + "');\" onclick=\"\"><img src=\"../images/icon_grey_pin.gif\" alt=\"Remove as Favorite\" border=\"0\" /> Remove Bookmark</a>");
}

function removeFavorite(id)
{
	$.post("index.php/query/unfavorite/" + id);
	$("#favorite" + id).fadeTo(600, 0);
	$("#addremovefavorite" + id).html("<a href=\"javascript: addFavorite('" + id + "');\" onclick=\"\"><img src=\"../images/icon_red_pin.gif\" alt=\"Save to Favorites\" border=\"0\" />Bookmark</a>");
}

function saveSearch(id)
{
	if (ajaxClear() == true)
	{
		var keyword = $('#keyword').val();
		var title = prompt("Please name this saved search", keyword);
		if ((title == null)||(title == "")||(title == "null"))
		{		
			ajaxFinished();
			return;
		}
		var url = "index.php/search/save_search/" + escape(id) + "/" + escape(title) + "/" + escape(keyword);
		
		$.post(url, function(data){
			$("#ss_container").fadeTo(600, 0, function(){
				$.post("index.php/dashboard/searches/", function(data){
					$("#ss_container").html(data);
					$("#ss_container").fadeTo(600, 1);
					ajaxFinished();
				});
			});
		});
	}
}

function loadSearch(id, keyword)
{
	keyword = cleanKeyword(keyword);
	if (ajaxClear() == true)
	{
		$.post("index.php/query/loadsearch/" + escape(id), function(data){
			$('#search_container').slideToggle(600, function(){
				$.post('index.php/dashboard/interfaces', function(data){
					ajaxFinished();
					$('#search_container').html(data);
					$('#search_container').slideToggle(600, function(){
						$('#dashboard_right').fadeTo(600, 0, function(){
							$.post('index.php/search/loader', function(data){
								$('#dashboard_right').html(data);
								$('#dashboard_right').fadeTo(600, 1, function(){
									$.post('index.php/query/results/' + escape(keyword), function(data){
										$('#dashboard_right').fadeTo(600, 0, function(){
											$('#dashboard_right').html(data);
											$('#dashboard_right').fadeTo(600, 1, function(){
												$('#save').fadeTo(600, 1);
												$('#trending_loader').fadeTo(600, 0, function(){
													$.post('index.php/trending/chart/' + id, function(data){
														$('#trending_loader').html(data);
														$('#trending_loader').fadeTo(600, 1);
													});
												});
												ajaxFinished();
											});
										});
									});
								});
							});
						});
					});
					initSimpletips();
				});
			});
		});
	}
}

function delSearch(userid, name)
{
	if (ajaxClear() == true)
	{
		$.post("index.php/query/delsearch/" + escape(userid) + "/" + escape(name), function(data){
			$("#ss_container").fadeTo(600, 0, function(){
				$.post("index.php/dashboard/searches/", function(data){
					$("#ss_container").html(data);
					$("#ss_container").fadeTo(600, 1);
					ajaxFinished();
				});
			});
		});
	}
}

function addEmail(userid, name)
{
	if (ajaxClear() == true)
	{
		$.post("index.php/query/togglesearch/" + escape(userid) + "/" + escape(name), function(data){
			$("#ss_container").fadeTo(600, 0, function(){
				$.post("index.php/dashboard/searches/", function(data){
					$("#ss_container").html(data);
					$("#ss_container").fadeTo(600, 1);
					ajaxFinished();
				});
			});
		});
	}
}

function setSentiment(sentiment, id)
{
	if (ajaxClearNoPop() == true)
	{
		$.post("index.php/search/sentiment/" + id + "/" + sentiment, function(){
			$("#sentiment_green" + id).attr("src", "../images/sentiment_green.png");
			$("#sentiment_yellow" + id).attr("src", "../images/sentiment_yellow.png");
			$("#sentiment_red" + id).attr("src", "../images/sentiment_red.png");
			
			if (sentiment == 'green')
				$("#sentiment_green" + id).attr("src", "../images/sentiment_green_on.png");
				
			if (sentiment == 'yellow')
				$("#sentiment_yellow" + id).attr("src", "../images/sentiment_yellow_on.png");
				
			if (sentiment == 'red')
				$("#sentiment_red" + id).attr("src", "../images/sentiment_red_on.png");
				
			$("#sentiment" + id).fadeTo(600, 0, function(){
				$("#sentiment" + id).attr("src", "../images/sentiment_" + sentiment + ".png");
				$("#sentiment" + id).fadeTo(600, 1);
			});
			
			ajaxFinished();
		});
	}
}

function addField(div, value)
{
	var content = '<input class="search_box" name="' + div + '[]" id="' + div + '_x" type="text" value="' + value + '" onKeyUp="checkForSearch(event)"/><br />';
	$('#' + div).prepend(content);
}

function removeField(id)
{
	$("input[id*='" + id + "']").remove();
}

function updateFilters()
{
	$.post('index.php/query/set_filters/', $(".searchForm").serialize(), function(data){
	});
}

function doSearch()
{
	if (ajaxClearNoPop() == true)
	{
		$.post('index.php/query/set_filters/', $(".searchForm").serialize(), function(data){
			$('#dashboard_right').fadeTo(600, 0, function(){
				$.post('index.php/search/loader', function(data){
					$('#dashboard_right').html(data);
					$('#dashboard_right').fadeTo(600, 1, function(){
						var keyword = $('#keyword').val();
						keyword = cleanKeyword(keyword);
						$.post('index.php/query/results/' + escape(keyword), function(data){
							$('#dashboard_right').fadeTo(600, 0, function(){
								$('#dashboard_right').html(data);
								$('#dashboard_right').fadeTo(600, 1, function(){
									$('#save').fadeTo(600, 1);
									$('#trending_loader').fadeTo(600, 0, function(){
										/*$.post('index.php/trending/chart/' + escape(keyword), function(data){
											$('#trending_loader').html(data);
											$('#trending_loader').fadeTo(600, 1);
										});*/
									});
									$('#dashboard_right').prepend("<div class='search_warning'><img style='float: left;' src='images/warning.png' />Attention: This is only a sample of results that match your keyword. To ensure full monitoring, please save this search to your dashboard.</div>");
									ajaxFinished();
								});
							});
						});
					});
				});
			});
		});
	}
}

function refineSearch()
{
	if (ajaxClearNoPop() == true)
	{
		$.post('index.php/query/set_filters/', $(".searchForm").serialize(), function(){
			$('#dashboard_right').fadeTo(600, 0, function(){
				$.post('index.php/search/loader', function(data){
					$('#dashboard_right').html(data);
					$('#dashboard_right').fadeTo(600, 1, function(){
						var keyword = $('#keyword').val();
						keyword = cleanKeyword(keyword);
						$.post('index.php/query/results/' + escape(keyword), function(data){
							$('#dashboard_right').fadeTo(600, 0, function(){
								$('#dashboard_right').html(data);
								$('#dashboard_right').fadeTo(600, 1, function(){
									$('#save').fadeTo(600, 1);
									ajaxFinished();
								});
							});
						});
					});
				});
			});
		});
	}
}

function paginateResults(limit, offset)
{
	if (ajaxClear() == true)
	{
		var keyword = $('#keyword').val();
		$.post('index.php/query/results/' + escape(keyword) + "/" + limit + "/" + offset, function(data){
			$('#dashboard_right').html(data);
			ajaxFinished();
			window.scrollTo(0,0);
		});
	}
}
 
function processLogin()
{
	var username = $("#userid").val();
	var password = $("#passwd").val();
	
	last_user = username;
	
	if (ajaxClearNoPop() == true)
	{
		$("#login_content").fadeTo(600, 0, function(){
			$('#login_content').attr("id", "login_loader");
			
			if (username == "" || password == "")
			{
				ajaxFinished();
				
				$('#login_loader').html($('#login_fail_text').html());
				$('#login_loader').fadeTo(600, 1, function(){
					$('#login_reset').fadeTo(600, 1);
				});
			}
			else
			{
				$('#login_loader').html($('#login_loader_text').html());
				$('#login_loader').fadeTo(600, 1, function(){
					$.post("index.php/dashboard/login/", {username: username, password: password}, function(data, textStatus, XMLHttpRequest){
						ajaxFinished();
						
						if (data == "FALSE")
						{
							$('#login_loader').fadeTo(600, 0, function(){
								$('#login_loader').html($('#login_fail_text').html());
								$('#login_loader').fadeTo(600, 1, function(){
									$('#login_reset').fadeTo(600, 1);
								});
							});
						}
						else if (data == "TRUE")
						{
							$("#login_loader_notice").fadeTo(600,0, function(){
								$("#login_loader_notice").html("Loading Dashboard ...");
								$("#login_loader_notice").fadeTo(600, 1, function(){
									$("#content").fadeTo(600, 0, function(){
										javascript:location.reload(true);
									});
								});
							});
						}
					});
				});
			}
		});
	}
}
