$(document).ready(
	function()
	{
		$('DIV.menu_main A IMG').bind('mouseover', menu_over);
		$('DIV.menu_main A IMG').bind('mouseout', menu_out);
		
		var options = {
				 // элемент, который будет обновлен по ответу сервера
				 target: "#news_comments_err",
				 //beforeSubmit: showRequest, // функция, вызываемая перед передачей
				 success: showResponse, // функция, вызываемая при получении ответа
				 clearForm: true,
				 timeout: 3000 // тайм-аут
				 };

				 // привязываем событие submit к форме
		
				
				$('#CommentForm').ajaxForm(options);

/// все коменты
				
				// обработка формы комента
				var myoptions = {
						 // элемент, который будет обновлен по ответу сервера
						 target: "#comments_err",
					//	 beforeSubmit: mycommentResponse, // функция, вызываемая перед передачей
						 success: mycommentResponse, // функция, вызываемая при получении ответа
						 clearForm: true,
						 timeout: 3000 // тайм-аут
						 };

						 // привязываем событие submit к форме
						$('#myCommentForm').ajaxForm(myoptions);
						


						
						

				
			
//poll
$("#poll").submit(formProcess); // setup the submit handler



if ($("#poll-results").length > 0 ) {
    animateResults();
  }


var pollid = $("input[name$='pollid']").attr("value");



// если установлено кука то проказываем опрос
if ($.cookie('portal_vote_id')==pollid) {
    $("#poll-container").empty();
    votedID = $.cookie('portal_myvote_id');
    $.getJSON("/ax/poll.php",myloadResults);
  }  



// графики

$('.bank_name').change(function() {
	my_bank_name = $('.bank_name option:selected').val();
	
	// load_chart функция в файле tpl_page_currency
	
	load_chart('USD',my_bank_name,'usd_chart'); 
	load_chart('EUR',my_bank_name,'eur_chart');
	load_chart('RUB',my_bank_name,'rub_chart');
	
	});


		
	});


// ------------------------------------------------------------------
// ---- POLL --------------------------------------------------------
function formProcess(event){
	  event.preventDefault();
	  
	  var id = $("input[@name='poll']:checked").attr("value");
	  id = id.replace("opt",'');
	  
	  var pollid = $("input[name$='pollid']").attr("value");
	  
	
	  votedID=id;
	  
	 //alert("/ax/poll.php?vote="+id+"&pollid="+pollid);
		
		  $("#poll-container").fadeOut("slow",function(){
			    $(this).empty();
			    $.getJSON("/ax/poll.php?vote="+id+"&pollid="+pollid,myloadResults);
			   //$.cookie('portal_vote_id', pollid, {expires: 2});
			    $.cookie('portal_myvote_id', id, {expires: 2});
			    });
		  
	
	  
	  
}

	function animateResults(){
	  $("#poll-results div").each(function(){
	      var percentage = $(this).next().text();
	          $(this).css({width: "0%"}).animate({
					width: percentage}, 'slow');
	  });
	}

	function myloadResults(data) {
		
		var total_votes = 0;
		var percent;
		var qust;
		  total_votes = total_votes+parseInt(data['total']);
		  
		  var results_html = "<div id='poll-results'>" + data['question'] +
		  			"<br><br><b>Результат голосования</b>\n" +
		  			"<dl class='graph'>\n";
		  // итого у нас максимум 5ть вопросов
		  for (a=1;a<=5;a++) {
			
			  qust = data['q'+a]; 
			  _votes = data['a'+a];
			   if (qust !='') {
				
				percent = Math.round((parseInt(_votes)/parseInt(total_votes))*100);
				
				 if (a != votedID) {
				results_html = results_html+"<dt class='bar-title'>"+qust+"</dt><dd class='bar-container'><div id='bar"+a+"' style='width:0%;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
				 }
				 else {
					 results_html = results_html+"<dt class='bar-title'>"+qust+"</dt><dd class='bar-container'><div id='bar"+a+"' style='width:0%;background-color:#0066cc;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
				 }
				   
			   }
			  
		  }		  
		  results_html = results_html+"</dl><p>Голосов: "+total_votes+"</p></div>\n";
		  
		  $("#poll-container").append(results_html).fadeIn("slow",function(){
			    animateResults();});
			
	
	}
		
	
//------------------------------------------------------------------	  



// вызов после получения ответа
function showResponse(responseText, statusText) {
	
	
	 get_news_comment($('#idnews').val());
	 $('#news_comments').fadeIn('slow'); 
	 
	 return false;
	 
	 
} 

/**
 * 
 *репа нужных нам разделов
 * 
 * @param idcommnet
 * @param idnews
 * @return
 */
function rate_plus(idcommnet,idnews) 
{
	
	

	$.get("/ax/functions_comments.php",{rateidcomment:idcommnet,rateidnews:idnews,plus:1},function(data){ 
		if ($('#rate_val'+idcommnet).text()== data)
			
		{
			alert('С Вашего IP-адреса уже был голос за эту запись, повторное голосование невозможно');
			
		}
		
		
		$('#rate_val'+idcommnet).html(data);
		alert('Спасибо, Ваш голос учтен!');
		
		return false;
	});

}

/**
 * репа нужных нам разделов
 * @param idcommnet
 * @param idnews
 * @return
 */

function rate_minus(idcommnet,idnews) 
{
	$.get("/ax/functions_comments.php",{rateidcomment:idcommnet,rateidnews:idnews},function(data){ 
		
		if ($('#rate_val'+idcommnet).text()== data)
		{
			alert('С Вашего IP-адреса уже был голос за эту запись, повторное голосование невозможно');
		}
		$('#rate_val'+idcommnet).html(data);
		alert('Спасибо, Ваш голос учтен!');
		return false;
	});

}

/**
 * 
 * @param iddoc ид ретингуемого
 * @param someid чет пока не ипольземое
 * @param razdel название раздела
 * @param rate_type plus minus
 * @return
 */

function my_rate(iddoc,someid,razdel,rate_type) 
{
	
$.get("/ax/function_rate.php",{rateidcomment:iddoc,someid:someid,razdel:razdel,rate_type:rate_type},function(data){ 
		
		if ($('#rate_val'+iddoc).text()== data)
		{
			alert('С Вашего IP-адреса уже был голос за эту запись, повторное голосование невозможно');
		}
		else {
		$('#rate_val'+iddoc).html(data);
		alert('Спасибо, Ваш голос учтен!');
		return false;
		}
	});

	
	
	
}



window.menu_last_status = '1';

function menu_over()
{
	var src = $(this).attr('src');
	var curr_status = src.substr( src.length - 5, 1 );

	window.menu_last_status = curr_status;

	var new_path = src.substr(0, src.length - 5) + '1' + src.substr(src.length - 4);
//		alert(curr_status);
	$(this).attr('src', new_path);
}

function menu_out()
{
	var src = $(this).attr('src');
	var curr_status = src.substr( src.length - 5, 1 );
//	alert(curr_status);
	var new_path = src.substr(0, src.length - 5) + window.menu_last_status + src.substr(src.length - 4);
	
	$(this).attr('src', new_path);
}


imgx1 = new Image(); 
imgx1.src = "/design/images/btn_main_1.gif";
imgx1 = new Image(); 
imgx1.src = "/design/images/btn_news_1.gif";
imgx1 = new Image(); 
imgx1.src = "/design/images/btn_playbill_1.gif";
imgx1 = new Image(); 
imgx1.src = "/design/images/btn_tv_1.gif";
imgx1 = new Image(); 
imgx1.src = "/design/images/btn_weather_1.gif";
imgx1 = new Image(); 
imgx1.src = "/design/images/btn_horoscope_1.gif";
imgx1 = new Image(); 
imgx1.src = "/design/images/btn_odessa_1.gif";
imgx1 = new Image(); 
imgx1.src = "/design/images/btn_main_0.gif";
imgx1 = new Image(); 
imgx1.src = "/design/images/btn_news_0.gif";
imgx1 = new Image(); 
imgx1.src = "/design/images/btn_playbill_0.gif";
imgx1 = new Image(); 
imgx1.src = "/design/images/btn_tv_0.gif";
imgx1 = new Image(); 
imgx1.src = "/design/images/btn_weather_0.gif";
imgx1 = new Image(); 
imgx1.src = "/design/images/btn_horoscope_0.gif";
imgx1 = new Image(); 
imgx1.src = "/design/images/btn_odessa_0.gif";


function set_horo_box(sign)
{
	var send_data = {}

	send_data['MODE'] = 'horo_get';
	send_data['sign'] = sign;

	JsHttpRequest.query
	(
		'POST /ax/functions.php', send_data,
		function(result, errors)
		{
			if (result["error_message"] != 'ok')
			{
				alert(result["error_message"]);
			}
			else
			{
				$('#horo_today').html( result.res.today )
				$('#horo_tomorrow').html( result.res.tomorrow )
			}
		},
		true
	);
}


function set_tv_box(channel)
{
	var send_data = {}

	send_data['MODE'] = 'tv_get';
	send_data['channel'] = channel;

	$('#datas_tv').html("Загрузка...");

	JsHttpRequest.query
	(
		'POST /ax/functions.php', send_data,
		function(result, errors)
		{
			if (result["error_message"] != 'ok')
			{
				alert(result["error_message"]);
			}
			else
			{
				$('#datas_tv').html(result.res.text);

				$('.scroll-pane-tv').jScrollPane({showArrows:true, scrollbarWidth: 24, arrowSize: 24});
			}
		},
		true
	);
}

function tv_box_clear() //очищаем список показываемых каналов
{
	navRoot = document.getElementById("tv_channels_ul");
	for (i=0; i<navRoot.childNodes.length; i++) 
	{
		node = navRoot.childNodes[i];
		if (node.nodeName=="LI") 
		{
			node.style.display = 'none';
		}
	}
}

function tv_box_show(channel) //показываем выбраный канал
{
	document.getElementById("channel_"+channel).style.display = "block";
}


// функция вывода комментов к определенной новости
function  get_comments(id)
{
	var send_data = {}

	send_data['MODE'] = 'get_comment';
	send_data['sign'] = id;

	JsHttpRequest.query
	(
		'POST /ax/functions_comments.php', send_data,
		function(result, errors)
		{
			if (result["error_message"] != 'ok')
			{
				alert(result["error_message"]);
			}
			else
			{
				//$('#horo_today').html( result.res.today )
				//$('#horo_tomorrow').html( result.res.tomorrow )
			}
		},
		true
	);
}


//=============== КОМЕНТЫ для ВСЕХ ============
//функция вывода комментов к определенному посту и разделу
// id - id коментируемого поста
// razdel = название раздела  см config.php

function  get_comment_all(id,razdel)
{
	
	MODE = 'list_comment';
	$.post("/ax/functions_comments_all.php",{id_comment:id,razdel:razdel,mode:MODE},function(data){ 
		$('#all_comments').fadeIn('slow');
		$('#all_comments').html(data);
		return false;
	});

}



		
		// вызов после получения ответа
		function mycommentResponse(responseText, statusText) {
			get_comment_all($('#id_comment').val(),$('#razdel').val());
			 $('#all_comments').fadeIn('slow'); 
			 return false;
			
			 
		} 

		

		
			function delete_comment_all(idcomment) {
					$.get("/ax/functions_comments_all.php",{idcommentdelete:idcomment},function(data){ 
						//alert(data);
					get_comment_all($('#id_comment').val(),$('#razdel').val());
						
					
				});
					
				}


//================ коменты для всех ЕНД ======================











//вывод комментов для новостей
// by ramzes
function get_news_comment(idnews) {
	
		$.get("/ax/functions_comments.php",{idnews:idnews},
			function(data){ 
			$('#news_comments').fadeIn('slow');
			$('#news_comments').html(data);	}
		);

}


// удаление коментоф админом
// не паримся проверка на пхп стороне  стороне


function delete_comment(idcomment) {

	$.get("/ax/functions_comments.php",{idcommentdelete:idcomment},function(data){ 
		
		//alert(data);
		get_news_comment(data);
		
});


	
}


function delete_user_photo(idfoto) {
	$.get("/ax/ax_mod_photo_upload.php",{idfotodel:idfoto},function(data){ 
		$('#fotoiddiv_'+idfoto).hide('slow');
	});
	
}

//####################################################################################################

window.creatie_type = 0;

function creative_form_prepare(type,item_id)
{
	window.creatie_type = type;

	
	if (item_id>0)
	{
		$('#title_block').css('display', 'visible');
		$('#name_block').css('display', 'visible');
		$('#creative_text').css('height', '240px');
		
		$('#item_id').attr('value',item_id);
	
		
		var send_data = {}
		
		send_data['MODE'] = 'creative_post_get_post';
		send_data['creative_type'] = window.creatie_type;
		send_data['item_id'] = item_id;

		
		
		
		JsHttpRequest.query
		(
			'POST /ax/functions.php', send_data,
			function(result, errors)
			{
				if (result["error_message"] != 'ok')
				{
					alert(result["error_message"]);
				}
				else
				{
					/*alert("Спасибо!");
					$.nyroModalRemove();
					document.location.reload();
					*/
					
				
					$('#creative_text').attr('value',result["item_content"]);
					$('#creative_title').attr('value',result["item_title"]);
					$('#creative_user').attr('value',result["item_user_name"]);
					
					
					
				}
			},
			true
		);
		
		
		//$('#creative_text').attr('value','');
		//$('#creative_title').attr('value','');
		//$('#creative_user').attr('value','');
		
	}
	else
	{
	
		if (window.creatie_type == 1)
		{
			$('#title_block').css('display', 'none');
			$('#creative_text').css('height', '290px');
		}
		else
		{
			$('#title_block').css('display', 'block');
			$('#creative_text').css('height', '240px');
		}
	
		$('#creative_user').attr('value','');
		$('#creative_text').attr('value','');
		$('#creative_title').attr('value','');
	}
}


function creative_post()
{
	var send_data = {}

	send_data['MODE'] = 'creative_post';

	send_data['creative_user'] = $('#creative_user').attr('value');
	send_data['creative_text'] = $('#creative_text').attr('value');

	send_data['creative_title'] = $('#creative_title').attr('value');
	send_data['item_id'] = $('#item_id').attr('value');

	send_data['creative_type'] = window.creatie_type;


	JsHttpRequest.query
	(
		'POST /ax/functions.php', send_data,
		function(result, errors)
		{
			if (result["error_message"] != 'ok')
			{
				alert(result["error_message"]);
			}
			else
			{
				alert("Спасибо!");
				$.nyroModalRemove();
				document.location.reload();
			}
		},
		true
	);
}


function creative_set(id, sign, rate_type)
{
	var send_data = {}

	send_data['MODE'] = 'creative_rate';

	send_data['rate_sign'] = sign;
	send_data['rate_id'] = id;
	send_data['rate_type'] = rate_type;
	


	JsHttpRequest.query
	(
		'POST /ax/functions.php', send_data,
		function(result, errors)
		{
			if (result["error_message"] != 'ok')
			{
				alert(result["error_message"]);
			}
			else
			{
				if (rate_type == 'creative')
				{
					$('SPAN#rate_' + id).html(result.res.rating);
				}
				else if (rate_type == 'comment')
				{
					$('SPAN#rate_с_' + id).html(result.res.rating);
				}
				
				alert("Спасибо, Ваш голос учтён!");
			}
		},
		true
	);
}

function creative_comment_add(creative_id)
{
	var send_data = {}

	send_data['MODE'] = 'creative_comment_add';

	send_data['creative_id'] = creative_id;
	send_data['comment_name'] = $('#name').attr('value');
	send_data['comment_text'] = $('#text').attr('value');

	JsHttpRequest.query
	(
		'POST /ax/functions.php', send_data,
		function(result, errors)
		{
			if (result["error_message"] != 'ok')
			{
				alert(result["error_message"]);
			}
			else
			{
				document.location.reload();
				
			}
		},
		true
	);
}


function creative_adm_del(item_id, type)
{
	if (!confirm('Удалить?'))
	{
		return;
	}

	var send_data = {}

	send_data['MODE'] = 'creative_del';

	send_data['item_id'] = item_id;
	send_data['type'] = type;

	JsHttpRequest.query
	(
		'POST /ax/functions.php', send_data,
		function(result, errors)
		{
			if (result["error_message"] != 'ok')
			{
				alert(result["error_message"]);
			}
			else
			{
				document.location.reload();
			}
		},
		true
	);
}


function creative_adm_up(item_id)
{
	var send_data = {}

	send_data['MODE'] = 'creative_up';

	send_data['item_id'] = item_id;

	JsHttpRequest.query
	(
		'POST /ax/functions.php', send_data,
		function(result, errors)
		{
			if (result["error_message"] != 'ok')
			{
				alert(result["error_message"]);
			}
			else
			{
				document.location.reload();
			}
		},
		true
	);
}

/*##################################*/

function rss_renew()
{
	var send_data = {}

	send_data['MODE'] = 'rss_renew';

	JsHttpRequest.query
	(
		'POST /ax/functions.php', send_data,
		function(result, errors)
		{
			if (result["error_message"] != 'ok')
			{
				//alert(result["error_message"]);
			}
			else
			{
				
			}
		},
		true
	);
}

/*##################################*/

function pagination_get_max()
{
	return parseInt($('#pages_total').attr('value'));
}

function pagination_get_current()
{
	return parseInt($('#pagination_select').attr('value'));
}

function pagination_select()
{
	pagination_go(pagination_get_current());
}

function pagination_prev()
{
	var page_dst = pagination_get_current() - 1;

	if (page_dst < 1)
	{
		page_dst = 1;
	}

	pagination_go(page_dst);
}

function pagination_next()
{
	var page_dst = pagination_get_current() + 1;

	if (page_dst > pagination_get_max())
	{
		page_dst = pagination_get_max();
	}

	pagination_go(page_dst);
}

function pagination_go(page_num)
{
	//#####################################

	var nq = '';

	//#####################################

	var q = jQuery.url.attr("query");

	if (q == null)
	{
		q = '&page=0';
	}
	else if ( q.indexOf('&') == -1 && q.length > 0 )
	{
		q = '&' + q;
	}

	//#####################################

	var s = q.split('&');

	for (i=0; i<s.length; i++)
	{
		if (s[i].length)
		{
			if (s[i].substr(0, 5) == 'page=')
			{
				nq = nq += 'page=' + page_num + '&';
			}
			else
			{
				nq = nq += s[i] + '&';
			}
		}
	}

	//#####################################

	document.location = jQuery.url.attr("path") + '?' + nq.substr(0, nq.length - 1);

	//#####################################
}



function byid(id)
{
	return document.getElementById(id);
}

function LayerShow(id)
{
	byid(id).style.display = 'block';
}

function LayerHide(id)
{
	byid(id).style.display = 'none';
}


function currency_show()
{
	byid('currency_cut').style.display = 'block';

	//$('#currency_date').css("height", parseInt(byid('curr_quantity').value) * 48 + 2 + "px");
	$('#currency').css("height", 9 * 48 + 2 + "px");
	
	
	LayerHide('curr_show_link');	
}

/*##################################*/



