// при загрузке документа

$(function() {
	var vi=-1;
	var q=-1;
	var va = new Array();	
	var mlis = new Array();
	$('.colorbox').colorbox({maxWidth:500});
	
	if ( main_page ) {
		get_course();
	}
});

var cnt = '';
var curTab = [];
var USD = 0;
var EUR = 0;
var DAT = '';
var usdrub = 0;
var eurrub = 0;

function get_course()
{
	$.post("/modules/valute/load_xml.php", function(jsn){
		var data = eval(jsn);
		curTab[0] = 1;
		USD = curTab[1] = parseFloat(data[1]);
		EUR = curTab[2] = parseFloat(data[2]);
		DAT = data[0];
			
		$("#cdt").text(DAT);
		usdrub = USD.toFixed(2);  
		$("#usdrub").text(usdrub);
		eurrub = EUR.toFixed(2); 
		$("#eurrub").text(eurrub);
	});	
}

function doCalc() {
	var itog=$('#summa').val()*curTab[$('#currFrom').val()]/curTab[$('#currTo').val()];
	$('#result_convert').html( isNaN(itog)? 'Ошибка' :(itog>100?parseInt(itog):Math.round(itog*100)/100) );
	$('#result_convert').show();
}	

function gotoURL(object) {
    window.location.href = object;
}

// новости: версия для печати

function print_news(id)
{
	$.post( "/modules/news/print_news.php", { id: id },
		   function(data) {
				var to_print = open("", "displayWindow", "width=780,height=800,status=no,scrollbars=yes,toolbar=yes,menubar=no");

				var content = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//RU" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
				+ '<head><meta http-equiv="Content-Type" content="text/html; charset=windows-1251" />'
				+ '<title>НОЯБРЬСК ИНФОРМ - Информационный портал города Ноябрьска</title>'
				+ '<link href="/styles/print.css" rel="stylesheet" type="text/css" />'
				+ '</head><body>'
				+ data
				+ '</body></html>';

				to_print.document.open(); 
				to_print.document.write(content);
				to_print.document.close();
		   }
	);
}

// новости: комментарии

function show_comments(id)
{	
	$("#dcmt").html('<p>Пожалуйста, подождите...</p>');

	$.post( "/modules/news/comments.php", { id: id },
		   function(data) {
			   $("#dcmt").html(data);
		   }
	);
}

// добавление комментария

function send_cmt()
{
	var cname = $("#cname").val();
	var ctext = $("#ctext").val();
	var ip = $("#cip").val();
	var nid = $("#nid").val();
	var drt = ( $("#direct").val() == 'y' ) ? 'y' : 'n';
	var cid = $("#cuser_id").val();
	
	if ( cname == '' )
	{
		alert("Вы забыли представиться.");
		return false;
	}
	
	if ( ctext == '' )
	{
		alert("Текст комментария пустой.");
		return false;
	}

	$.post( "/core/proc_cmt.php", { nid: nid, ip: ip, drt : drt, cmd: 'post_cmt', cname: cname, ctext: ctext, cid: cid },
		   function(data) {
			   if ( data != 'error' )
			   {
				   if ( drt == 'y' )
				   {
						alert('Комментарий добавлен.');   
						$("#ccmt").prepend(data);
				   }
					else
						alert('Ваш комментарий будет добавлен после проверки администрацией сайта.');
						
					$("#dcmt").html('');
			   }
			   else
			   		alert('При добавлении комментария произошла ошибка.');
		   }
	);
}

function show_group(gid)
{
	s = $('#dgroup'+gid).css("display");
	
	if ( s == 'none' )
		$('#dgroup'+gid).show('slow');
	else
		$('#dgroup'+gid).hide('slow');
}

function showdocs()
{
	s = $("#documents").css("display");
	
	if ( s == 'none' )
		$("#documents").show('slow');
	else
		$("#documents").hide('slow');
}

// добавление уровня в левое меню

function add_level( id )
{
	var dl = 'mli'+id;
	var du = 'mul'+id;
	var elem = document.getElementById(dl);
	var ulelem = document.getElementById(du);
		
	if ( ulelem == null )
	{
		elem.innerHTML += '<ul id="temp"><li>загрузка...</li></ul>';
		
		$.post('/core/add_level.php', { id: id },
			   function(data) {
				   	$("#temp").remove();
				   	elem.innerHTML += data;
					mlis[id] = 'y';
			   }
		);
	}
	else
	{
		ulelem.removeNode(true);
		mlis[id] = 'n';
	}
}

function get_full_path(id)
{
	var path = $.ajax({
		type: "POST",
		url: "/core/get_full_path.php",
		data: "id="+id,
		async: false
	});

	return path.responseText;
}

function show_docs(id)
{
	var l = '#doc_ref_'+id;
	
	if ( $(l).css("display") == 'none' )
		$(l).css("display", "block");
	else
		$(l).css("display", "none");
}

function td_ref_ch(td)
{
	if ( (td.style.background == 'rgb(224, 234, 243)') || (td.style.background == '#e0eaf3' ) )
		td.style.background = '#94b7d3';
	else
		td.style.background = '#e0eaf3';
}

// загрузка ленты новостей

function show_news_lenta( rid, str, stp )
{
	$("#lenta").html('<p><img src="/images/loading.gif" align="absmiddle" />&nbsp;Загрузка новостей...</p>');
	
	$.post( "/modules/news/ajax_news.php", { rid: rid, start: str, stop: stp },
		   function(nlenta) {
			   $("#lenta").html(nlenta);
		   }
	);
}

function user_exit()
{
	gotoURL("/modules/user/exit.php");
}

function searchnews(str)
{
	if ( document.sform.find.value != "" )
	{
		if ( document.sform.find.value.length > 3 )
		{
			document.sform.submit();
		}
		else
		{
			alert("Строка для поиска не должна быть менее трех символов!");
			return false;
		}
	}
}

function callvote(vid)
{
	if ( vi < 0 )
		alert("Вы не выбрали пункт голосования!");
	else
	{
		$("#dvote").html("<h1>Думаю...</h1>");
		$.post( "/modules/votes/res.php", { vid: vid, qid: q },
			function(vdata) {
				$("#dvote").hide();
				$("#dvote").html(vdata);
				$("#dvote").show("slow");
			}
		);
	}
}

function checkvote(index,qid)
{
	$('#dvote > table > tbody > tr > td > img').each( function(i) 
	{
		if ( index == i )
		{
			document.getElementById("v"+i).src="/images/vote_cb_fill.jpg";
			vi = i;
			q = qid;
		}
		else
			document.getElementById("v"+i).src="/images/vote_cb_empty.jpg";
	} );
}

// показ фотографии в увеличенном виде

function show_foto(id)
{
	$("#content_big_foto").html('<p>Загрузка фотографии...</p>');   
		
	$.post("/modules/foto/show_one.php", { id: id },
		   function(data) {
				$("#content_big_foto").html(data);   
		   }
	);
}
	
// вывод списка фотографий для новостей (отдельная новость!)
	
function show_foto_list(id, nid)
{
	$("#nfotos").html("<p>Подождите, загрузка фотографий...</p>");
	
	$.post( "/modules/foto/show_foto.php", { id: id, nid: nid },
		function(data) {
			$("#nfotos").html(data);
		}
	);
}
	
// построение элемента списка товаров и услуг
	
function draw_info_list(pid, sid)
{
	if ( ($("#ulnode"+sid).html() == '') || ($("#ulnode"+sid).html() == null) )
	{
		if ( sid == 0 )
			$("#info"+sid).html('<p>Загрузка...</p>');
		else
			$("#linode"+sid).append('<div id="iajax"><p>Загрузка...</p></div>');

		$.post( "/modules/info/draw.php", { pid: pid, sid: sid },
			function(data) {
				if ( sid == 0 )
					$("#info"+sid).html(data);	
				else
				{
					$("#iajax").remove();
					$("#linode"+sid).append(data);
				}
			}
		);	
	}
	else
		$("#ulnode"+sid).remove();
}
	
// отображение пункта информации "ТОВАРЫ И УСЛУГИ"
	
function show_info_item( id, isid )
{
	if ( ($("#ulinfo"+id).html() == '') || ($("#ulinfo"+id).html() == null) )
	{
		$("#liitem"+id).append('<div id="iajax"><p>Загрузка...</p></div>');		
	
		$.post( "/modules/info/show_item.php", { id: id, sid: isid },
			function(data) {
				$("#iajax").remove();
				$("#liitem"+id).append(data);
			}
		);
	}
	else
		$("#ulinfo"+id).remove();
}

function delnew()
{
	return ( window.confirm("Вы уверены, что хотите удалить эту новость?") ) ? true : false;	
}