var getRecommendationsMutex = null;
var moreResultsMutex = null;
var updateResultsMutex = null;
var setWotStateMutex = null;

function now() {
	return '&now=' + (new Date()).getTime();
}

function isBusy(mutex) {
	return (mutex != null) && ((new Date()).getTime() - mutex.getTime() < 3000);
}

$(document).ready(function() {
	$("#searchbox_textfield").focus();

	$('.ad').click(function() {
		var url = $(this).attr('href');
		$.ajax({
			type: "GET",
			url: 'selectAdForWebApp?session=' + window.instId + '&ssMapKey=' + window.encodedSSMapKey + '&adUrl=' + encodeURIComponent(url) + now()
		});
	});

	$.ajax({
		type: "GET",
		url: 'updateNorthRefinements?session=' + window.instId + '&ssMapKey=' + window.encodedSSMapKey + now(),
		success: function(data) {
			$('#northRefinements').append(data);
		}
	});

	if (window.isWot) {
		$.ajax({
			type: "GET",
			dataType: "xml",
			url: 'updateWotSerp?session=' + window.instId + '&ssMapKey=' + window.encodedSSMapKey + now(),
			success: function(data) {
				$(data).find('filterDomain').each(function() {
					var domain = $(this).find("domain").text();
					$('tr[domain=' + domain + ']').remove();
					$('div[domain=' + domain + ']').remove();
				});
				$(data).find('wotDomainInfo').each(function() {
					var domain = $(this).find("domain").text();
					var info = $(this).find("info").text();
					$('span.fillInWotDomainInfo[domain=' + domain + ']').html(info);
				});
			}
		});
	}
});

function trFor(initialRank) {
	return $('#trFor' + initialRank);
}

function getHasRecsFlag(initialRank) {
	return trFor(initialRank).attr('hasRecsFlag');
}

function setHasRecsFlag(initialRank, value) {
	trFor(initialRank).attr('hasRecsFlag', value);

	var msg = (value == 1) ? "Click to close recommendations" : "Click for real-time recommendations";
	$('#trgtFor' + initialRank).attr('title', msg);
}

function getRecommendations(resultRow, gesture) {
	var initialRank = resultRow.attr("initialRank");
	if (!isBusy(getRecommendationsMutex) && (initialRank != null) && (initialRank != undefined) && (initialRank >= 0)) {
		getRecommendationsMutex = new Date();

		var contentDivRef = '#recsFor' + initialRank;
		var currentHtml = $(contentDivRef).html();
		if (currentHtml.length <= 16) {
			$.ajax({
				type: "GET",
				url: 'getRecommendations?session=' + window.instId + '&ssMapKey=' + window.encodedSSMapKey + '&initialRank=' + initialRank + '&gesture=' + gesture + now(),
				success: function(data) {
					if (data.indexOf('trFor') > -1) {
						$(contentDivRef).css("display", "none");

						var progressMessage = resultRow.find("div.progressMessage:eq(0)");
						progressMessage.css("display", "block");

						$(contentDivRef).append(data);

						var closeRecsButton = $('#closeRecsButtonFor' + initialRank);
						$(contentDivRef).slideDown(500, function() {
							progressMessage.css("display", "none");
							closeRecsButton.css("display", "block");
						});

						setHasRecsFlag(initialRank, 1);
					} else if (gesture == 'bullseye') {
						$(contentDivRef).append("<i>There are no Surf Canyon recommendations available for this query.</i><p>");
					}
				},
				complete: function(request, success) {
					getRecommendationsMutex = null;
				}
			});
		}
	}
}

function getRecs(initialRank, gesture) {
	var resultRow = trFor(initialRank);
	getRecommendations(resultRow, gesture);
}

function webAppCloseRecs(initialRank) {
	$.get('closeRecommendations?session=' + window.instId + '&ssMapKey=' + window.encodedSSMapKey + '&initialRank=' + initialRank + now());

	$('#recsFor' + initialRank).empty();
	$('#closeRecsButtonFor' + initialRank).css("display", "none");

	setHasRecsFlag(initialRank, 0);
}

function bullseye(initialRank) {
	var resultRow = trFor(initialRank);
	if (getHasRecsFlag(initialRank) == 1) {
		webAppCloseRecs(initialRank);
	} else {
		getRecommendations(resultRow, 'bullseye');
	}
}

function updateResults() {
	if (!isBusy(updateResultsMutex)) {
		updateResultsMutex = new Date();
		$.ajax({
			type: "GET",
			url: 'updateResults?session=' + window.instId + '&ssMapKey=' + window.encodedSSMapKey + now(),
			success: function(data) {
				$('#dynamicContent').empty().append(data);
			},
			complete: function(request, success) {
				updateResultsMutex = null;
				dynamicContentLoaded();
			}
		});
	}
}

function webAppMoreResults() {
	if (!isBusy(moreResultsMutex)) {
		moreResultsMutex = new Date();

		$('#moreResultsMessage').css("display", "block");
		$.ajax({
			type: "GET",
			url: 'moreResultsForWebApp?session=' + window.instId + '&ssMapKey=' + window.encodedSSMapKey + now(),
			success: function(data) {
				$('#dynamicContent').empty().append(data);
				$('#moreResultsMessage').css("display", "none");
			},
			complete: function(request, success) {
				moreResultsMutex = null;
				dynamicContentLoaded();
			}
		});
	}
}

function openWindowAndFocus(url, target, event) {
	try {
		if (!(event.shiftKey || event.ctrlKey)) {
			window.open(url, target).focus();
		}
	} catch(e) {
	}
}

function dynamicContentLoaded() {
	$('#wotFilterOnTrust').click(function() {
		setWotState('Trust');
	});

	$('#wotFilterOnAdult').click(function() {
		setWotState('Adult');
	});

	if (typeof runCloudlet == 'function') {
		runCloudlet();
	}
}

function setWotState(filterName) {
	if (!isBusy(setWotStateMutex)) {
		setWotStateMutex = new Date();
		var checked = $('#wotFilterOn' + filterName).attr('checked') ? '1' : '0';
		$.ajax({
			type: "GET",
			url: 'setWotState?session=' + window.instId + '&ssMapKey=' + window.encodedSSMapKey + '&filter=' + filterName + '&val=' + checked + now(),
			success: function(data) {
				updateResults();
			},
			complete: function(request, success) {
				setWotStateMutex = null;
			}
		});
	}
}

function submit(q) {
	var url = '/search?q=' + q;

	var argsString = window.location.search.substring(1);
	var args = argsString.split('&');
	for (i = 0; i < args.length; i++) {
		var arg = args[i];
		var sepPos = arg.indexOf('=');
		if (sepPos != -1) {
			var name = arg.substring(0, sepPos);
			var value = arg.substring(sepPos + 1);
			if (name != 'q') {
				url = url + '&' + name + '=' + value;
			}
		} else {
			url = url + '&' + arg;
		}
	}

	window.location.href = url;
}

