var login_billing_sticky_win, soundManager, req2, req1, chatScroller, searchScroller,
	mini_chatScroller, chat_request, chat_check_request;
var userDefinedSection = {};

function complainSend(messageId, flag){
	var ta = document.complainForm.ta.value;
	var complain_request = new Request({
		url: 'modules/complain_send_ajax.php',
		data: {message_id: messageId,flag: flag,descr: ta},
		method: 'post',
		noCache: true,
		onSuccess: function(responseText, responseXML) {

		}
	});
	complain_request.send();
	$('complain_link'+messageId).set('html', '');
	$('ajax_complain_window').style.display = 'none';
	return false;
}

function complainSend2(topic, messageId, flag){
	var ta = document.complainForm.ta.value;
	var complain_request = new Request({
		url: 'modules/complain_send_ajax2.php',
		data: {message_id: messageId,flag: flag,descr: ta, topic:topic},
		method: 'post',
		noCache: true,
		onSuccess: function(responseText, responseXML) {

		}
	});
	complain_request.send();
	$('complain_link'+messageId).set('html', '');
	$('ajax_complain_window').style.display = 'none';
	return false;
}

function complainSend3_1(type, messageId, descr, flag){
	var complain_request = new Request({
		url: 'modules/complain_send_ajax.php',
		data: {message_id: messageId,flag: flag,descr: descr},
		method: 'post',
		noCache: true,
		onSuccess: function(responseText, responseXML) {

		}
	});
	complain_request.send();
	$('complain_link'+messageId+type).set('html', '');
//	$('ajax_complain_window').style.display = 'none';
	return false;
}

function complainSend3_2(type, messageId, topic, descr, flag){
	var complain_request = new Request({
		url: 'modules/complain_send_ajax2.php',
		data: {message_id: messageId,flag: flag,descr: descr, topic:topic},
		method: 'post',
		noCache: true,
		onSuccess: function(responseText, responseXML) {

		}
	});
	complain_request.send();
	$('complain_link'+messageId+type).set('html', '');
//	$('ajax_complain_window').style.display = 'none';
	return false;
}



function openAjaxComplainWindow(object_id,flag) {
	$('ajax_complain_window').style.display = 'block';
	$('ajax_complain_window_content').set('html', '<p style="text-align: center; margin-top: 200px; font-size: 38px; text-indent: 0px;"><img src="templates/default/images/Waiter/loading.gif" width="32" height="32" hspace="10" vspace="0"/></p>');
	var ajax_complain_sticky_win = new StickyWin.Fx({
		content: $('ajax_complain_window'),
		draggable: true,
		dragHandleSelector: 'div.ajax_complain_window_drag_handle',
		zIndex: 100001,
		fadeDuration: 500
	});

	ajax_complain_sticky_win.pin();

	var complain_request = new Request({
		url: 'modules/complain_ajax.php',
		data: {id: object_id,flag: flag},
		method: 'post',
		noCache: true,
		onSuccess: function(responseText, responseXML) {
			$('ajax_complain_window_content').set('html', responseText);			
			$('ta').focus();
		}
	});

	complain_request.send();
}


function openAjaxComplainWindow2(topic, object_id,flag) {
	$('ajax_complain_window').style.display = 'block';
	$('ajax_complain_window_content').set('html', '<p style="text-align: center; margin-top: 200px; font-size: 38px; text-indent: 0px;"><img src="templates/default/images/Waiter/loading.gif" width="32" height="32" hspace="10" vspace="0"/></p>');
	var ajax_complain_sticky_win = new StickyWin.Fx({
		content: $('ajax_complain_window'),
		draggable: true,
		dragHandleSelector: 'div.ajax_complain_window_drag_handle',
		zIndex: 100001,
		fadeDuration: 500
	});

	ajax_complain_sticky_win.pin();

	var complain_request = new Request({
		url: 'modules/complain_ajax2.php',
		data: {id: object_id,flag: flag, topic:topic},
		method: 'post',
		noCache: true,
		onSuccess: function(responseText, responseXML) {
			$('ajax_complain_window_content').set('html', responseText);			
			$('ta').focus();
		}
	});

	complain_request.send();
}


function hideBillingWindow() {
	//alert ('bla');
	login_billing_sticky_win.hide();
}
function checkNewMail()
{
	req1.send();
	setTimeout('checkNewMail()', 60000);
}
function scrollDownChat(__scroll_duration)
{
	var scroll_duration = __scroll_duration;
	if ($('chat_window_messages_div') != null) {
		if (!chatScroller) {
			chatScroller = new MooScroller($E('div.chat_scroller div.chat_content'), $E('div.chat_scroller .scrollKnob'), {
				scrollLinks: {
					forward: $E('div.chat_scroller div.scrollForward'),
					back: $E('div.chat_scroller div.scrollBack')
				}
			});
		}

		if (chatScroller) {
			if ($('stop_chat_scroll') != null) {
				if (!$('stop_chat_scroll').checked) {
					var contentToScroll = $('chat_window_messages_div');
					var fx = new Fx.Scroll(contentToScroll, {
						duration: scroll_duration
					});
					fx.toBottom();
					chatScroller.update();
				}
			}
		}
	}

	if ($('mini_chat_window_messages_div') != null) {
		if (!mini_chatScroller) {
			mini_chatScroller = new MooScroller($E('div.mini_chat_scroller div.mini_chat_content'), $E('div.mini_chat_scroller .mini_scrollKnob'), {
				scrollLinks: {
					forward: $E('div.mini_chat_scroller div.mini_scrollForward'),
					back: $E('div.mini_chat_scroller div.mini_scrollBack')
				}
			});
		}

		if (mini_chatScroller) {
			var contentToScroll = $('mini_chat_window_messages_div');
			var fx = new Fx.Scroll(contentToScroll, {
				duration: scroll_duration
			});
			fx.toBottom();
			mini_chatScroller.update();
		}
	}
}

function scrollDownSearch(__scroll_duration)
{
	var scroll_duration = __scroll_duration;
	if ($('chat_search_content') != null) {
		if (!searchScroller) {
			searchScroller = new MooScroller($E('div.chat_scroller div.search_content'), $E('div.chat_scroller .search_scrollKnob'), {
				scrollLinks: {
					forward: $E('div.chat_scroller div.search_scrollForward'),
					back: $E('div.chat_scroller div.search_scrollBack')
				}
			});
		}

		/*if (searchScroller) {
			if ($('stop_chat_scroll') != null) {
				if (!$('stop_chat_scroll').checked) {
					var contentToScroll = $('chat_search_content');
					var fx = new Fx.Scroll(contentToScroll, {
						duration: scroll_duration
					});
					fx.toBottom();
					chatScroller.update();
				}
			}
		}
		*/
	}
}



function openChatWindow()
{
	$('chat_window').style.display = 'block';
	var chat_sticky_win = new StickyWin.Fx({
		content: $('chat_window'),
		draggable: true,
		dragHandleSelector: 'div.chat_window_drag_handle',
		zIndex: 100000,
		fadeDuration: 500
	});

	chat_sticky_win.pin();

	if ($('chat_window_messages_div') != null) {
		if (!chatScroller) {
			chatScroller = new MooScroller($E('div.chat_scroller div.chat_content'), $E('div.chat_scroller .scrollKnob'), {
				scrollLinks: {
					forward: $E('div.chat_scroller div.scrollForward'),
					back: $E('div.chat_scroller div.scrollBack')
				}
			});

			chatScroller.update();

			var contentToScroll = $('chat_window_messages_div');
			var fx = new Fx.Scroll(contentToScroll, {
				duration: 0
			});
			fx.toBottom();
			chatScroller.update();
		} else {
			chatScroller.update();

			var contentToScroll = $('chat_window_messages_div');
			var fx = new Fx.Scroll(contentToScroll, {
				duration: 0
			});
			fx.toBottom();
			chatScroller.update();
		}
	}
	setTimeout('scrollDownChat(0)', 550);
	setTimeout('scrollDownChat(0)', 650);
	setTimeout('scrollDownSearch(0)', 550);
	setTimeout('scrollDownSearch(0)', 650);
}
function update_chat()
{
	if ($('mini_chat_window_messages_div') != null) {
		chat_check_request.send();
		setTimeout('update_chat()', 15000);
	}
}
function playChatSound() {
	if ($('sound_status').checked) {
		try {
			soundManager.play('new_message');
		} catch (e) {

		}
	}
}
function redirectToLocation(location) {
	document.location = location;
}
function redirectToLocationWithDelay(location, delay) {
	setTimeout('redirectToLocation("'+location+'")', delay);
}

window.addEvent('domready', function() {
	$E = document.getElement.bind(document);

	login_billing_sticky_win = new StickyWin();
	/*var login_billing_sticky_win = new StickyWin.Fx({
				content: $('login_billing_window'),
				draggable: true,
				dragHandleSelector: 'div.login_billing_window_drag_handle',
				zIndex: 100000,
				fadeDuration: 500
			});*/

	soundManager.debugMode = false; // disable debug output
	soundManager.url = 'modules/soundmanager2/swf/'; // path to directory containing SoundManager2 .SWF file
	soundManager.flashVersion = 8;

	soundManager.onload = function() {
		//soundManager.createSound() etc. may now be called
		//soundManager._writeDebug('soundManager.onload() - your code executes here');
		//soundManager.createSound('new_message','templates/default/sounds/new_message.mp3');
		//soundManager.play('new_message');

		var newMessageSound = soundManager.createSound({
			id: 'new_message',
			autoLoad: true,
			url: 'templates/default/sounds/new_message.mp3'
		// onload: [ event handler function object ],
		// other options here..
		});
	}


	req2 = new Request({
		url: 'modules/messages.php',
		data: {
			mode: 'check_not_viewed_mail'
		},
		method: 'post',
		noCache: true,
		onSuccess: function(responseText, responseXML) {
			$('new_private_mail_span').set('html', '<img width="14" height="9" src="templates/default/images/mail_anim.gif" />('+responseText+')');
		}
	});

	req1 = new Request({
		url: 'modules/messages.php',
		data: {
			mode: 'check_new_mail'
		},
		method: 'post',
		noCache: true,
		onSuccess: function(responseText, responseXML) {
			if (parseInt(responseText) > 0)
			{
				req2.send();
			}
		}
	});

	chat_request = new Request({
		url: 'modules/chat.php',
		data: {
			chat_mode: 'get_messages'
		},
		method: 'post',
		noCache: true,
		onSuccess: function(responseText, responseXML) {
			if ($('chat_window_messages_div') != null) {
				$('chat_window_messages_div').set('html', responseText);
			}

			if ($('mini_chat_window_messages_div') != null) {
				$('mini_chat_window_messages_div').set('html', responseText);
			}

			setTimeout('scrollDownChat(0)', 500);
		}
	});

	chat_check_request = new Request({
		url: 'modules/chat.php',
		data: {
			chat_mode: 'get_new_messages_avail'
		},
		method: 'post',
		noCache: true,
		onSuccess: function(responseText, responseXML) {
			if (responseText == "1") {
				chat_request.send();
				playChatSound();
			}
			if (responseText == "2") {
				chat_request.send();
			}
		}
	});

	if ($('mini_chat_window_messages_div') != null) {
		if (!mini_chatScroller) {
			mini_chatScroller = new MooScroller($E('div.mini_chat_scroller div.mini_chat_content'), $E('div.mini_chat_scroller .mini_scrollKnob'), {
				scrollLinks: {
					forward: $E('div.mini_chat_scroller div.mini_scrollForward'),
					back: $E('div.mini_chat_scroller div.mini_scrollBack')
				}
			});
		}
	}

	chat_request.send();
	update_chat();
	setTimeout('scrollDownChat(0)', 100);
	//setTimeout('scrollDownChat(0)', 1000);

	if(userDefinedSection.domReadyFunction != undefined){
		userDefinedSection.domReadyFunction();
	}
	
});

function renderMessages(){
	//todo

}

function updateCounter(topic, messageId) {
	
	new Request({
		url: 'update_counters.php',
		data: {
			topic: topic,
			messageId: messageId
		},
		method: 'post',
		noCache: true,
		onSuccess: function(responseText, responseXML) {
			//alert(responseText)
		},
		onComplete: function(transport) {
			//alert(transport.status)
		},
		onFailure: function(transport) {
			//alert(transport.status)
		}
	}).send();
	//alert(update_counter_request);
}

function toggleMessageDescription(mid, topic){
	if (document.getElementById("desc_div_"+mid).style.display=="none")
	{
		//$("desc_link_"+id).set("html", "Скрыть описание");
		document.getElementById("desc_div_"+mid).style.display="block";
		updateCounter(topic, mid);
	} else {
		//$("desc_link_"+id+"").set("html", "Открыть описание");
		document.getElementById("desc_div_"+mid).style.display="none";
	}

}

function addToFavorities(mid,old,color){
	var u = "_u";
	if(old)
		u = "";
	new Request({url: "modules/favorites.php",
		data: {mode: "add_to_favorites"+u, id: mid},
		noCache: true,
		onSuccess: function(responseText, responseXML){
			if (responseText == "0"){
				alert("Невозможно добавить в избранное. Ошибка базы данных.");
			}		
		}
	}).send();

	var myEffect = new Fx.Morph($("tr"+mid), {duration: 250});
	if (($("asunread_link_"+mid).get("style") == "display: none;") ||
		($("asunread_link_"+mid).get("style") == "DISPLAY: none")) {
		myEffect.start({"background-color": "#9FAED2"}).chain(
			function() { this.start({"background-color": "#"+color}); }
		);
	} else {
		myEffect.start({"background-color": "#9FAED2"}).chain(
			function() { this.start({"background-color": "#E2F6FF"}); }
		);
	}

	$("add_to_favorites_link_span_"+mid).set("html", "В избранном");
}

function addToFavorities2(topic, mid, uid, old, color){
	var u = "_u";
	if(old)
		u = "";
	new Request({url: "modules/favorites2.php",
		data: {mode: "add_to_favorites", mid: mid, topic: topic, uid: uid},
		noCache: true,
		onSuccess: function(responseText, responseXML){
			if (responseText == "0"){
				alert("Невозможно добавить в избранное. Ошибка базы данных.");
			}		
		}
	}).send();

	var myEffect = new Fx.Morph($("tr"+mid), {duration: 250});
	if (($("asunread_link_"+mid).get("style") == "display: none;") ||
		($("asunread_link_"+mid).get("style") == "DISPLAY: none")) {
		myEffect.start({"background-color": "#9FAED2"}).chain(
			function() { this.start({"background-color": "#"+color}); }
		);
	} else {
		myEffect.start({"background-color": "#9FAED2"}).chain(
			function() { this.start({"background-color": "#E2F6FF"}); }
		);
	}

	$("add_to_favorites_link_span_"+mid).set("html", "В избранном");
}

function markAsRead2(topic, mid){
	new Request({url: 'modules/messages.php',
		data: {mode: 'mark_as_read2', id: mid, topic: topic},
		noCache: true,
		onSuccess: function(responseText, responseXML){
			if (responseText == '0'){
				alert('Невозможно пометить как прочитанное. Ошибка базы данных.');
			}
		}
	}).send();

	var myEffect = new Fx.Morph($('tr'+mid), {duration: 500});
	myEffect.start({'background-color': '#E2F6FF'});

	$('asread_link_'+mid).set('style', 'display: none;');
	$('asunread_link_'+mid).set('style', 'display: inline;');
}


function markAsRead(mid){
	new Request({url: 'modules/messages.php',
		data: {mode: 'mark_as_read', id: mid},
		noCache: true,
		onSuccess: function(responseText, responseXML){
			if (responseText == '0'){
				alert('Невозможно пометить как прочитанное. Ошибка базы данных.');
			}
		}
	}).send();

	var myEffect = new Fx.Morph($('tr'+mid), {duration: 500});
	myEffect.start({'background-color': '#E2F6FF'});

	$('asread_link_'+mid).set('style', 'display: none;');
	$('asunread_link_'+mid).set('style', 'display: inline;');
}

function markAsUnRead2(topic, mid, color){
	new Request({url: 'modules/messages.php',
		data: {mode: 'unmark_as_read2', id: mid, topic: topic},
		noCache: true,
		onSuccess: function(responseText, responseXML){
			if (responseText == '0'){
				alert('Невозможно снять отметку. Ошибка базы данных.');
			}
		}
	}).send();

	var myEffect = new Fx.Morph($('tr'+mid), {duration: 500});
	myEffect.start({'background-color': '#'+color});

	$('asunread_link_'+mid).set('style', 'display: none;');
	$('asread_link_'+mid).set('style', 'display: inline;');
}


function markAsUnRead(mid, color){
	new Request({url: 'modules/messages.php',
		data: {mode: 'unmark_as_read', id: mid},
		noCache: true,
		onSuccess: function(responseText, responseXML){
			if (responseText == '0'){
				alert('Невозможно снять отметку. Ошибка базы данных.');
			}
		}
	}).send();

	var myEffect = new Fx.Morph($('tr'+mid), {duration: 500});
	myEffect.start({'background-color': '#'+color});

	$('asunread_link_'+mid).set('style', 'display: none;');
	$('asread_link_'+mid).set('style', 'display: inline;');
}

function addToBlacklist(phone){
	var to_blacklist = confirm("Объявления данного автора отображаться у Вас не будут!\nДобавить автора в личный черный список?");
	if (to_blacklist == true){
		window.location="index.php?mode=addtoblacklist&phone="+phone;
	} else {
		return false;
	}
}
