var artId		= 0;
var userId		= 0;
var userCanRate	= false;

$(document).ready(function() {
	// artId		= /\-(\d+)\.html/.exec(document.location);
	artId		= /articles\/(\d+)/.exec(document.location);
	artId		= parseInt(artId[1]);
	userId		= parseInt(document.getElementById('user_id').value);
	userCanRate	= ( ! $("input.star:first").attr("disabled") );

	if (userCanRate) {
		$('form.star_rating :radio.star').rating();

		$('form.star_rating a').bind('click', function() {
			var rating = this.title;
			if (!confirm( lang_rate_article_to_rating.replace(/__RATING__/, rating) )) return;

			$.ajax({
				type: 'POST',
				url: '/community/ajax/user.php',
				data: 'action=rate_article&art_id=' + artId + '&ranked_user_id=' + userId + '&rating=' + parseInt(rating),
				cache: false,
				success: function(response) {
					if (response == 'done')
						$('div.star_rating').html(lang_your_rate + ": " + rating + ".");
					else
						alert(lang_error_text_js);
				}
			});
		});
	}
	else {
		$('form.star_rating :radio.star').rating('readOnly');
	}
});


function openComment() {
	$("#comment_div").show("slow");
}

function saveComment() {
	if (document.getElementById('user_comment').value.length > 0)
		document.comment_form.submit();
	else
		alert(lang_cant_add_empty_comment);
}


function cancelComment() {
	$("#comment_div").hide("slow");
}


function removeSharing(username, art_id) {
	if (confirm(remove_art_sharing_confirm)) {
		var params = "type=article&username=" + username + "&id=" + art_id;
		makeRequest("/community/add_share_remove_ajax.php?" + params, "sharing");
	}
}

function attachGallery(artId) {
	if (!document.getElementById('free_gallery')) return;

	var galId = document.getElementById('free_gallery')[document.getElementById('free_gallery').selectedIndex].value;
	makeRequest("/community/ajax/attach.php?action=attach_gallery&gallery_id=" + galId + "&article_id=" + artId, "attach_gallery");
}


function makeRequest(url, type) {
	var http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) http_request.overrideMimeType('text/xml');
	}
	else if (window.ActiveXObject) { // IE
		try { http_request = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (e) {
			try { http_request = new ActiveXObject("Microsoft.XMLHTTP"); }
			catch (e) {}
		}
	}

	if (!http_request) { alert('Giving up :( Cannot create an XMLHTTP instance'); return false; }

	http_request.onreadystatechange = function () {
		if (http_request.readyState == 4) {
			if (type == "attach_gallery") {
				location.reload(true);
			}
			else if (type == "sharing") {
				if (http_request.responseText == "ok") {
					alert(lang_article_unlinked_ok);
					location.reload(true);
				}
			}
		}
	}

	http_request.open('GET', url, true);
	http_request.send(null);
}