var bodyClickListeners = [];

function bodyClick() {
	for (var i = 0; i < bodyClickListeners.length; ++i)
		bodyClickListeners[i]();
}

var searchTimer;
var searchLast;
var searchCount = 10;
var searchOffset = 0;
var recentCountry = '';
var nrecent = 10;

function toggleDisplay(divname) {
	var el = document.getElementById(divname);
	if (el.style.display == "block")
		el.style.display = "none";
	else
		el.style.display = "block";
	return false;
}

function popupWindow(url, name, width, height) {
	window.open(url, name, "status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=1,height=" + height + ",width=" + width);
}

function quickSearch() {
	var q = $F('q');

	if (!q) {
		$('quicksearch_results').hide();
		$('quicksearch_more').hide();
		$('quicksearch_noresults').hide();
		searchLast = '';
		return;
	}
	
	if (q == searchLast)
		return;
	
	searchOffset = 0;
	searchLast = q;
	
	new Ajax.Request("/ajax/quickSearch", {
		method: 'post',
		parameters: {q: q, count: searchCount},
		onSuccess: function(transport) {
			if (transport.responseText) {
				var html = quickSearchGetHtml(transport.responseText);
				$('quicksearch_results').show();
				$('quicksearch_noresults').hide();
				$('quicksearch_results_tbody').update(html);
			} else {
				$('quicksearch_results').hide();
				$('quicksearch_more').hide();
				$('quicksearch_noresults').update("No results were found for '<strong>" + q.escapeHTML() + "</strong>'. Please try again.");
				$('quicksearch_noresults').show();
			}
		}
	});
}

function quickSearchMore() {
	searchOffset += searchCount;
	new Ajax.Request("/ajax/quickSearch", {
		method: 'post',
		parameters: {q: $F('q'), count: searchCount, offset: searchOffset},
		onSuccess: function(transport) {
			if (transport.responseText.length > 1) {
				var html = quickSearchGetHtml(transport.responseText);
				$('quicksearch_results_tbody').insert(html);
			} else
				$('quicksearch_more').hide();
		}
	});
}

function quickSearchGetHtml(response) {
	var havemore = response.substr(0, 1);
	var html = response.substr(1);
	
	if (havemore == "1")
		$('quicksearch_more').show();
	else
		$('quicksearch_more').hide();
	
	return html;
}

function searchChanged() {
	if (searchTimer != null) {
		clearTimeout(searchTimer);
	}
	searchTimer = setTimeout("quickSearch()", 300);
}

function showMoreRecent(doupdate) {

	new Ajax.Request("/ajax/moreRecent", {
		method: 'post',
		parameters: {offset: nrecent, count: 10, country: recentCountry},
		onSuccess: function(transport) {
			if (transport.responseText) {
				if (doupdate)
					$('recentsites_tbody').update(transport.responseText);
				else
					$('recentsites_tbody').insert(transport.responseText);
			} else
				$('recentsites_more').hide();
		}
	});	
	
	nrecent += 10;
}

function setRecentCountryFilter(country) {
	recentCountry = country;
	nrecent = 0;
	$('recentsites_more').show();
	showMoreRecent(true);
}

/***** Add new site page *****/
var RecaptchaOptions = {
   theme : 'clean'
};

function updateTitle() {
	$('description').setValue("wait...");
	$('description').disable();
	
	new Ajax.Request("/ajax/getTitle", {
		method: 'post',
		parameters: {hostname: $F('hostname'), scheme: $F('scheme')},
		onSuccess: function(transport) {
			var result = transport.responseText.evalJSON(true);
			if (result.result) {
				$('description').enable();
				$('description').setValue(result.title);
				$('tags').setValue(result.tags_fmt);
				$('status').hide();
			} else {
				$('description').setValue("");
				$('description').enable();
				$('status').update(result.message).show();
			}
		}
	});
}

/****** Dialog boxes ******/

bodyClickListeners.push(hideDialog);

function popupDetails(hostname, e) {
	
	var cursor = getCursorPos(e);
	
	new Ajax.Request("/ajax/getDetails", {
		method: 'post',
		parameters: {hostname: hostname},
		onSuccess: function(transport) {
			showDialog(hostname, transport.responseText, cursor.x, cursor.y, '35em', '15em');
		}
	});
}

function showDialog(title, content, xpos, ypos, width, height) {
	hideDialog();
	hideCountryMenu();
	
	var dialog = $('dialog_tpl');
	
	title = '<a style="float: right" href="#" onclick="hideDialog(); return false;">close</a>' + title;
	$('dialog_tpl_title').update(title);
	$('dialog_tpl_content').update(content);
	
	dialog.style.left = xpos + 'px';
	dialog.style.top = ypos + 'px';
	dialog.style.width = width;
	$('dialog_tpl_content').style.height = height;
	
	dialog.show();
	showShadow(dialog);
}

function hideDialog() {
	if ($('dialog_tpl'))
		$('dialog_tpl').hide();
	hideShadow();
}

function showShadow(ddiv) {
	var ofs = ddiv.cumulativeOffset();
	var dim = ddiv.getDimensions();
	
	$('shadowbox').style.top = ofs.top + 'px';
	$('shadowbox').style.left = ofs.left +'px';
	$('shadowbox').style.width = (dim.width + 16) + 'px';
	$('shadowbox').style.height = (dim.height + 16) + 'px';
	$('shadowbox_td2').style.height = (dim.height - 16) + 'px';	
	$('shadowbox').show();
}

function hideShadow() {
	if ($('shadowbox'))
		$('shadowbox').hide();
}

/****** Country selection menu ******/

bodyClickListeners.push(hideCountryMenu);

var curCountrySel;

function popupCountryMenu(sel) {
	if ($('countrypopup').visible())
		hideCountryMenu();
	else
		showCountryMenu(sel);
}

function hideCountryMenu() {
	if ($('countrypopup')) {
		$('countrypopup').hide();
		hideShadow();
	}
	curCountrySel = undefined;
}

function showCountryMenu(sel) {
	curCountrySel = sel;
	
	hideDialog();
	
	var ot = 16;
	var ol = 0;
	
	if (navigator.userAgent.toLowerCase().indexOf("safari/") != -1) {
		ot++;
		ol++;
	}
	
	$('countrypopup').clonePosition(sel, {setWidth: false, setHeight: false, offsetTop: ot, offsetLeft: ol});
	$('countrypopup').show();
	$('countrypopup').setOpacity(0.9);
	showShadow($('countrypopup'));
}

function selCountry(country) {
	if (!curCountrySel)
		return;
	
	var img = curCountrySel.getElementsByTagName('img')[0];
	if (country)
		img.src = '/images/flags/' + country + '.gif';
	else
		img.src = '/images/flags/all.png';
	hideCountryMenu();
	setRecentCountryFilter(country);
}

function getCursorPos(e) {
	var e = e || window.event;
	var cursor = {x:0, y:0};
	if (e.pageX || e.pageY) {
		cursor.x = e.pageX;
		cursor.y = e.pageY;
	} else {
		var de = document.documentElement;
		var b = document.body;
		cursor.x = e.clientX + 
			(de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
		cursor.y = e.clientY + 
			(de.scrollTop || b.scrollTop) - (de.clientTop || 0);
	}
	
	return cursor;
}
