$(document).ready(function(){

	// Редактирование комментария
	comment_edit();
	comment_comment();
	DataRating();
		
	// Ajax-статус [загрузка ...]
	$("#loading").bind("ajaxSend", function(){
		$(this).show();
		}).bind("ajaxComplete", function(){   
			$(this).hide();
	});

	//Promo-objects
	$('#next_obj').click(function(){
					$('#promo_content').load('mod/promo-objects.php?show=next'); 
					//return false;    
					});	
	$('#prev_obj').click(function(){
					$('#promo_content').load('mod/promo-objects.php?show=prev'); 
					//return false;    
					});	
	
	// Главное меню
	initMainMenu();
	
	// Язык
	$('#lang_selector a').click(function(){
		var lang = $(this).attr('class');
		
		$.get('/ajax/select_lang.php?lang='+lang,function(result){
			if(result != '0'){
				// получаем html-код меню
				$.get('/ajax/menu_init.php',function(menu_result){
					$('#menu_container').empty();
					$('#menu_container').append(menu_result);
					
					initMainMenu();
				});
			}
		});
		
		return false;
	});
	
	// Голосования
	$(".q_vote").click(function(){						
		q_id = $(this).attr("q_id");	
		 $(this).parent(".q_cont").load("/ajax/vote.php?id="+$(":radio[name=q_check_"+q_id+"]").filter(":checked").val());
		 //$(".q_cont[q_id="+q_id+"]")
	});
	
	//При инициации FancyBox скрываем cloud
	$("a.img").click(function(){
		$('#cloud').css({'visibility':'hidden'});
	});
});

//->
function animateCloud()
{
	var isIE = ($.browser.msie && parseInt($.browser.version.substr(0,1)) < 8);
	$('#cloud').css({'visibility':'visible'});
	if(!isIE){
		$('#cloud').fadeOut(0);
		$('#cloud').fadeIn("slow");
	}
}

//->
function showBanners(menu_id)
{
	switch(menu_id)
	{
	   	case '1':
			$('#ajax_banners').load('/inc/banners.php?section=main');
		break;
		case '4':
			$('#ajax_banners').load('/inc/banners.php?section=6');
		break;
		default:
			$('#ajax_banners').load('/inc/banners.php?section=main');
		break;
	}
}
//->
function initMainMenu()
{
	// init cloud
	var active_element_id = $('#active_menu').size() == 1 ? $('#active_menu').attr('value') : false;
	
	if(active_element_id){
		// count menu elements
		var countElements = $('.element[element_id="'+active_element_id+'"]').parents('.menu_elements').size();
		if(countElements > 0){		
			var elements = $('.element[element_id="'+active_element_id+'"]').parents('.menu_elements').clone();
			
			$('#cloud').empty();
			$('#cloud').append(elements);
			$('#cloud .menu_elements').css('display','block');		
			animateCloud();
			
			$('.element[element_id="'+active_element_id+'"] a').css('color','#bfd72f');
		}
	}
	
	$(".main_menu").click(function()
	{
		var menu_id = $(this).attr('menu_id');
		var count_elements = $(this).find('.element').size(); // children
		
		// Cursor hide & show
		$('.main_cursor').remove();
		$(this).prepend('<div class="main_cursor"></div>');
		$('.main_cursor').show('slow');
		
		if(count_elements > 0){
			// Append Content in cloud
			var elements = $(this).find('.menu_elements').clone();
			$('#cloud').empty();
			$('#cloud').append(elements);
			$('#cloud .menu_elements').css('display','block');		
			animateCloud();
			
			// Elements handler
			/*
			$('#cloud .menu_elements .element:not([out_url="1"])').click(function(){
				var page_link = $(this).attr('page_link');
				
				$('#cloud .menu_elements a').removeClass("selected");
				$(this).find('a').addClass("selected");
				
				$('#doc_area').load('/ajax/page.php?page_link='+page_link,function(){
					// плавная прокрутка к контенту
					//destination = $('#doc_area').offset().top;
					//$("html:not(:animated),body:not(:animated)").animate({scrollTop: destination}, 1100);																		   
				});
				return false;
			});
			*/
			return false;
		}else{
			/*
			$('#cloud').empty();
			$('#cloud').hide();
			var page_link = $(this).attr('page_link');
			$('#doc_area').load('/ajax/page.php?page_link='+page_link,function(){
				// плавная прокрутка к контенту
				destination = $('#doc_area').offset().top;
				$("html:not(:animated),body:not(:animated)").animate({scrollTop: destination}, 1100);																		   
			});
			*/
			return true;
		}
		
		//Появление баннеров по клику на 'who' или 'kids'
		showBanners(menu_id);
	});
}

//->
function DataRating(sent)
{
	// sent - ajax indicator, true - if rated
	
	var rateParentContainer = 'rating_box';
	var rateContainer = 'rating'; 
	
	if(document.getElementById(rateContainer))
	{
		// -> config
		var rateImgCount = 5;
		var rateImgPath = '/images/rateimg/';
		var postFile = '/ajax/rating.php';
		
		var jqEstimation = $('#'+rateContainer+'');
		var estimation = jqEstimation.attr('estimation');
		var module = jqEstimation.attr('module');
		var row = jqEstimation.attr('row');
				
		// images
		rateImg = new Object();
		
		rateImg[1] = new Image(27,12);
		rateImg[1].src = rateImgPath+'1a.gif';
		
		rateImg[2] = new Image(27,12);
		rateImg[2].src = rateImgPath+'1.gif';
		
		rateImg[3] = new Image(27,12);
		rateImg[3].src = rateImgPath+'2a.gif';
		
		rateImg[4] = new Image(27,12);
		rateImg[4].src = rateImgPath+'2.gif';
		// -> end of config
		
		// appending
		for(i=1;i<=rateImgCount;i++)
		{
			var n = i % 2 ? 1 : 3;
			jqEstimation.append('<img src="'+rateImg[n].src+'" estimation="'+i+'" class="rate_step_'+i+'">');
		}
		
		for(i=1;i<=estimation;i++)
		{
			var n = i % 2 ? 2 : 4;
			jqEstimation.find('img[estimation='+i+']').attr('src',rateImg[n].src);
		}

		if(sent !== true)
		{
			// hover
			jqEstimation.find('img').hover(function(){
				
				var cur_estimation = $(this).attr('estimation');
				
				// reset src			
				for(i=1;i<=rateImgCount;i++)
				{
					var n = i % 2 ? 1 : 3;
					jqEstimation.find('img[estimation='+i+']').attr('src',rateImg[n].src);
				}
						
				for(i=1;i<=cur_estimation;i++)
				{
					var n = i % 2 ? 2 : 4;
					jqEstimation.find('img[estimation='+i+']').attr('src',rateImg[n].src);
				}	
				
			},function(){
			
				// reset src
				for(i=1;i<=rateImgCount;i++)
				{
					var n = i % 2 ? 1 : 3;
					jqEstimation.find('img[estimation='+i+']').attr('src',rateImg[n].src);
				}
				
				for(i=1;i<=estimation;i++)
				{
					var n = i % 2 ? 2 : 4;
					jqEstimation.find('img[estimation='+i+']').attr('src',rateImg[n].src);
				}
			
			});
			
			// click - set rating
			jqEstimation.find('img').click(function(){
				
				var selEstimation = $(this).attr('estimation');
				
				// posting
				$.post(postFile,{'estimation':selEstimation,'module':module,'row':row},function(result){
					$('#'+rateParentContainer+'').html(result);	
					DataRating(true);
				});	
				
			});
		}
	}
}

//->
var cc=false;
function comment_edit()
{
	$(".edit_link").click(function(){
		var comment = $(this).next(".content").children(".u_comment");
	
		var id = comment.attr("com_id");
		text = comment.text();
		new_html = '<textarea class="com_text">'+text+'</textarea><div><input type="button" class="com_submit" value="Редагувати" /></div>';	
		comment.html(new_html);
		$(".com_submit").click(function(){	
			var edit = $(this).parent().prev(".com_text");
			edit_text = edit.val();				
			$(".com_text").ajaxSuccess(function(){
				comment_edit();
			});
			$.post("/ajax/edit_comment.php", { 'text': edit_text, 'id': id},
		   		function(result){					
		     			comment.html(result);
			});	
		});
		return false;				
	});
	$(".com_edit_link").click(function(){
		var comment = $(this).next(".content").children(".u_comment");
		var id = comment.attr("com_id");
		text = comment.text();
		new_html = '<textarea class="com_com_text">'+text+'</textarea><div><input type="button" class="com_com_submit" value="Редагувати" /></div>';	
		comment.html(new_html);
		$(".com_com_submit").click(function(){	
			var edit = $(this).parent().prev(".com_com_text");
			edit_text = edit.val();				
			$(".com_com_text").ajaxSuccess(function(){
				comment_edit();
			});
			$.post("/ajax/edit_comment.php", { 'text': edit_text, 'id': id},
		   		function(result){					
		     			comment.html(result);
			});	
		});
		return false;				
	});

}	
function comment_comment()
{
	$(".comment_link").click(function(){
		if(cc==false)
		{
			var comment = $(this).next(".content").children(".u_comment");
			var comment_div = $(this).parent();
			var beforeMe = comment_div.parent().children(".beforeMe");
			var id = comment.attr("com_id");

			new_html = $('<div class="new_comment"><textarea class="newcom_text"></textarea><div align="right"><input type="button" class="newcom_submit" value="Коментувати" /></div></div>');

			new_html.insertAfter(comment_div);
			cc=true;
			$(".newcom_submit").click(function(){	
			
				var edit = $(this).parent().prev(".newcom_text");
				edit_text = edit.val();				
				$(".newcom_text").ajaxSuccess(function(){
					comment_comment();
				});
				new_html.remove();
				cc = false;	
				$.post("/ajax/comment_comment.php", { 'text': edit_text, 'id': id},
	   				function(result){																
	  	   				$(result).insertBefore(beforeMe);										
						comment_edit();
				});			
			});
			return false;				
		}
		return false;
	});
}


function checksearch()
{
	var text = $('INPUT[name=search]').val();
	var speed = 150;
	if(text.length < 5)
	{
		$('.search_error').show().fadeOut(speed).fadeIn(speed).fadeOut(speed).fadeIn(speed);
	}
	else
		location.href = '/search/'+escape(text);
	return false;
}

var trans = [];
for (var i = 0x410; i <= 0x44F; i++)
  trans[i] = i - 0x350; // А-Яа-я
trans[0x401] = 0xA8;    // Ё
trans[0x451] = 0xB8;    // ё
trans[0x407] = 0xAF;    // Ї
trans[0x457] = 0xBF;    // ї
trans[0x406] = 0xB2;    // І
trans[0x456] = 0xB3;    // і

var escapeOrig = window.escape;

window.escape = function(str)
{
  var ret = [];
  for (var i = 0; i < str.length; i++)
  {
    var n = str.charCodeAt(i);
    if (typeof trans[n] != 'undefined')
      n = trans[n];
    if (n <= 0xFF)
      ret.push(n);
  }
  return escapeOrig(String.fromCharCode.apply(null, ret));
}
