function closeForm(formId, callback) {
	formToClose = $("#" + formId);
	if (formToClose.length != 0) {
		formToClose.slideUp("fast", function() {
			formToClose.remove();
			callback();
		});	
	} else {
		callback();
	}
}
function showEditForm(itemID) {
	closeForm("requestform", function() {
		divItem = $('#item' + itemID);	
		saveText = $('#itemtext' + itemID).html();
		divItem.append('<div id="requestform"><textarea id="editformtext" rows="5">' + saveText + '</textarea>' + 
			'<input type="button" value="Сохранить изменения" onClick="JavaScript:modifyItem(' + itemID + ');" />&nbsp;&nbsp;' + 
			'<input type="button" value="Отмена" onClick="JavaScript:closeForm(\'requestform\', function() {});" /></div>');
		$("#requestform").slideDown("normal");
	});
}
function showAnswerForm(itemID) {
	closeForm("requestform", function() {
		divItem = $('#item' + itemID);
		divItem.append('<div id="requestform" style="display: none;"><form><textarea rows="5" id="answertext"></textarea>' + 
			'<input type="button" value="Ответить на вопрос" onClick="JavaScript:appendAnswer(' + itemID + ');"/>&nbsp;&nbsp;'+ 
			'<input type="button" value="Отмена" onClick="JavaScript:closeForm(\'requestform\', function() {});"/></form></div>');
		$("#requestform").slideDown("normal");
	});
}
function appendQuestion() {
	qtext = $("#qtext").val();
	if (qtext == '') {
		alert('Вы не ввели текст вопроса !');
	} else {
		$.ajax({
			type: "POST",
			url: "/ibridges/addquestion/"+bridgeID+"/",
			timeout: 5000,
			data: "text=" + qtext + "&lastItemID=" + lastItemID,
			success: function(msg){
				doSync(msg);
				$("#qtext").val('');
			},
			error: function() {
				alert('Извините, произошла ошибка - ваше сообщение не доставлено');
			}
		});			
	}
}
function appendAnswer(qid) {
	atext = $('#answertext').val();
	if (atext == '') {
		alert('Вы не ввели текст ответа !');
	} else {
		closeForm('requestform', function() {
			$.ajax({
				type: "POST",
				url: "/ibridges/addanswer/"+bridgeID+"/",
				timeout: 5000,
				data: "text=" + atext + "&qid=" + qid + "&lastItemID=" + lastItemID,
				success: function(msg){
					doSync(msg);
					$("#qtext").val('');
				},
				error: function() {
					alert('Извините, произошла ошибка - ваше сообщение не доставлено');
				}
			});			
		});
	}
}
function deleteItem(itemID, isQuestion) {
	if (window.confirm((isQuestion) ? 'Удалить вопрос и все ответы на него ?' : 'Удалить ответ на вопрос ?')) {
		$.ajax({
			type: "POST",
			url: (isQuestion ? '/ibridges/deletequestion/'+bridgeID+'/' : '/ibridges/deleteanswer/'+bridgeID+'/'), 
			timeout: 5000,
			data: "id=" + itemID + "&lastItemID=" + lastItemID,
			success: function(msg){
				doSync(msg);
			},
			error: function() {
				alert('Извините, произошла ошибка - элемент не удален.');
			}
		});			
	}
}
function modifyItem(itemID) {
	atext = $('#editformtext').val();
	if (atext == '') {
		alert('Вы не ввели текст !');
	} else {
		closeForm('requestform', function() {
			$.ajax({
				type: "POST",
				url: '/ibridges/edititem/'+bridgeID+'/', 
				timeout: 5000,
				data: "id=" + itemID + "&text=" + atext + "&lastItemID=" + lastItemID,
				success: function(msg){
					doSync(msg);
				},
				error: function() {
					alert('Извините, произошла ошибка - элемент не изменен.');
				}
			});
		});
	}
}
function Sync() {
	$.ajax({
		type: "POST",
		url: '/ibridges/sync/'+bridgeID+'/', 
		timeout: 5000,
		data: "lastItemID=" + lastItemID,
		success: function(msg){
			doSync(msg);
			setTimeout("Sync()", 10000);
		}
	});	
}
function doSync(xml) {
	var ibridgeDIV = $("#ibridgeitems");
	var items = xml.getElementsByTagName("item");
	for (var i=0; i<items.length; i++) {
		var itemID = items[i].childNodes[0].firstChild.nodeValue;
		var itemStatus = items[i].childNodes[1].firstChild.nodeValue;
		var itemQID = items[i].childNodes[2].firstChild.nodeValue;
		if (itemStatus == 0) {
			var itemAuthor = items[i].childNodes[3].firstChild.nodeValue;
			var itemtext = items[i].childNodes[4].firstChild.nodeValue;
		}

		if (itemID == itemQID) { // Это вопрос
			qDIV = $("#question"+itemQID);
			if (itemStatus == 1) {
				if (qDIV.length != 0)
					qDIV.hide();
			} else {
				itemObj = $("#item"+itemQID);
				HTMLText = '<b>' + itemAuthor + ':</b>' +
					'<pre id="itemtext' + itemID + '">' + itemtext + '</pre>';
				if (allowAnswer) 
					HTMLText += '<span onClick="JavaScript:showAnswerForm(' + itemID + ');">Ответить на вопрос</span>';
				if (allowEdit) {
					HTMLText += '<span onClick="JavaScript:showEditForm(' + itemID + ');">Редактировать текст вопроса</span>';
					HTMLText += '<span onClick="JavaScript:deleteItem(' + itemID + ', true);">Удалить вопрос</span>';
				}
				if (itemObj.length != 0) {
					itemObj.html(HTMLText);
				} else {
					HTMLText = '<div id="question' + itemID + '"><div class="question" id="item' + itemID + '">' + HTMLText + '</div></div>';
					ibridgeDIV.html(ibridgeDIV.html() + HTMLText);
				}
			}
		} else {
			qDIV = $("#question"+itemQID);
			if (qDIV.length != 0) {
				itemObj = $('#item' + itemID);	
				if (itemStatus == 1) {
					itemObj.hide();
				} else {
					HTMLText = '<b>' + itemAuthor + ':</b>' + 
						'<pre id="itemtext' + itemID + '">' + itemtext + '</pre>';
					if (allowEdit) {
						HTMLText += '<span onClick="JavaScript:showEditForm(' + itemID + ');">Редактировать текст ответа</span>';
						HTMLText += '<span onClick="JavaScript:deleteItem(' + itemID + ', false);">Удалить ответ</span>';
					}				
					if (itemObj.length != 0) {
						itemObj.html(HTMLText);
					} else {
						qDIV.append('<div class="answer" id="item' + itemID + '">' + HTMLText + '</div>');
					}
				}
			}
		}
		if (lastItemID < itemID)
			lastItemID = itemID;
    }	
}
