function num2str (numeric, many, one, two) { // правильное склонение слов (10 баллов, 1 балл, 2 балла)
	numeric = numeric - (numeric % 1); // отбрасываем дробную часть
	if (numeric % 100 == 1 || (numeric % 100 > 20) && (numeric % 10 == 1)) return one;
	if (numeric % 100 == 2 || (numeric % 100 > 20) && (numeric % 10 == 2)) return two;
	if (numeric % 100 == 3 || (numeric % 100 > 20) && (numeric % 10 == 3)) return two;
	if (numeric % 100 == 4 || (numeric % 100 > 20) && (numeric % 10 == 4)) return two;
	return many;
}

function SetAjaxLoader(id_element) {
	if ($("#ajax_loader")) {
		$("#ajax_loader").remove();
	}
	var ajax_loadercontainer = document.createElement('div');
	ajax_loadercontainer.id = 'ajax_loader';
	ajax_loadercontainer.style.position = 'absolute';
	ajax_loadercontainer.style.zIndex = '9';
	ajax_loadercontainer.style.fontSize = '10pt';
	ajax_loadercontainer.style.fontFamily = 'Verdana';	
	ajax_loadercontainer.innerHTML="<center><img src='http://92.241.191.127/img/loader.gif'><br>подождите...</center>";
	document.body.appendChild(ajax_loadercontainer);
	$("#ajax_loader").css('top',$("#"+id_element).offset().top + ($("#"+id_element).height())/2 - ($("#ajax_loader").height())/2 +'px');
	$("#ajax_loader").css('left',$("#"+id_element).offset().left + ($("#"+id_element).width())/2  - ($("#ajax_loader").width())/2 +'px');
}

function MyMenu (lst) {
	lst.childNodes[1].style.display="block";
	lst.childNodes[1].style.top = lst.offsetHeight;
	lst.style.background = '#FF0066';
	if($.browser.opera){    
		lst.childNodes[1].style.top = lst.offsetHeight -5 + 'px';
	}
}

function HideMyMenu (lst) {
	lst.childNodes[1].style.display="none";
	lst.style.background = '#404040';
}

function RateMarks(all_marks, rating, lst) {
	all_marks = parseInt(all_marks);
	rating = parseInt(rating);
	var marks = new Array();
	marks.push(all_marks);
	marks.push((all_marks + rating)/2);
	marks.push(all_marks - marks[marks.length-1]);
	
	container = document.createElement('span');
		with(container){
				className = 'RateBox';
				style.left = $(lst).offset().left-0+'px';
				if($.browser.msie){    
                            			style.top = $(lst).offset().top + $(lst).height() + 1 + 'px';
                      			}
				else {
					style.top = $(lst).offset().top + $(lst).height() + 2 + 'px';
                        		}
				//innerHTML = 'Голосов: ' + marks[0] + '<br><font color=green>Плюсов: ' + marks[1] + '</font><br><font color=red>Минусов: ' + marks[2] + '</font>';
				innerHTML = '<div style=float:left;>Проголосовало:</div> &nbsp;' + marks[0] + '<br><font color=green><div style=float:left;>Нравится:</div> &nbsp;' + marks[1] + '</font><br><font color=red><div style=float:left;>Не нравится:</div> &nbsp;' + marks[2] + '</font>';
		}
	$(lst).after(container);
	$(lst).next().slideDown('normal');
}


function HideRate(lst){
	$(lst).next().slideUp('normal', function(){ $(this).remove(); });
}

function SwitchRatings (divname, ratid, lst) {
	$.ajax({
		url: "js/switch_files.php",
		data: ({ switch_id: ratid }),
		dataType: 'html',
		beforeSend: function(){
			$('#' + divname).html('');
			
			$(lst).parents('.round_block_2').find("img.progress_img").toggle();
			
			//$(lst).closest("img:first").show();
		},
		success: function(data){
			$('#' + divname).html(data);
			$(lst).siblings("a.pink_active_link").attr('class', 'pink_passive_link');
			$(lst).attr('class', 'pink_active_link');
		},
		error: function(data){
			$('#rating_block').html('error: ' + data.statusText);
		},
		complete: function(){
			$(lst).parents('.round_block_2').find("img.progress_img").toggle();
		}
	});
}

var http_request = false;
function makeRequest(url,func) {
	http_request = false;

	if (window.XMLHttpRequest) { //   ...
		http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
        		http_request.overrideMimeType('text/xml');
				}
        } 
		
	else if (window.ActiveXObject) { //  
    	try {
        http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
        	try {
            	http_request = new ActiveXObject("Microsoft.XMLHTTP");
            	} catch (e) {}
        	}
      	}
		
	if (!http_request) {
    	alert('Unsuccessful query.');
        return false;
        }
		
    http_request.onreadystatechange = function(){ alertContents(func) };
    http_request.open('GET', url, true);
    http_request.send(null);
}

function alertContents(func_name) {
	if (http_request.readyState == 4) {
    	if (http_request.status == 200) {
        	var xmldata = http_request.responseXML;
            //var xmldata = http_request.responseText;
			func_name(xmldata);
          } 
		else{
        	alert('Data does not return.');
			}
		}
}

// --> Голосование за статью
function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie (name) {
	var matches = document.cookie.match(new RegExp("(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"));
	return matches ? decodeURIComponent(matches[1]) : undefined;
}

function SaveCook () {
	var expires = new Date();
	var timeval = expires.getTime();
	expires.setTime(expires.getTime() + 1000 * 86400 * 7); // вычисляем срок хранения cookie
	setCookie('time', timeval, expires); //сохраняем время в cookie
}


function vote (id_vote, type, direct) {
	var exptime = 60000; // 60000 - минута в мс
	var curdate = new Date();
	var comflag = false;
	curdate = curdate.getTime();
	
	var cookdate = getCookie('time');
	
	if (cookdate == undefined) { // если куки "time" не существовал (до первого голоса)...
		setCookie ('time', curdate - exptime, curdate + exptime); //...устанавливаем его со значением -exptime от текущего времени
		cookdate = getCookie('time');
	}
	
	if (type == "com") {
		cookdate = new Date();
		cookdate = cookdate.setTime (cookdate.getTime() - exptime * 2);
		comflag = true;
	}
	
	//if (cookdate != undefined) {
		if (curdate - cookdate < exptime) {
			$.fn.colorbox({html:'<div align="center" style="margin-top: 20px; font-family: Verdana; font-size: 10pt;">Оценивание публикации возможно через: <b>'+ Math.round((exptime-(curdate-cookdate))/1000)+'</b> ' + num2str((exptime-(curdate-cookdate))/1000, "секунд", "секунду", "секунды") + '</div>', width: "500", height: "150"});
		}
		else {
			if (!comflag) { // если не комментарий
				SaveCook();
			}
			var amountArea = document.getElementById('am_'+type+'_'+id_vote).innerHTML = '<span class=\'grey\'>обновление...</span>';
			var url = 'js/vote.php?id_vote='+id_vote+'&type='+type+'&direct='+direct;
			makeRequest(url,rtrn_vote);
		}
	//}
	//else {
	//	alert ('Включите cookie!');
	//}
}

function rtrn_vote(xmldoc){
	var RN = xmldoc.getElementsByTagName('values');
	var id_vote = RN[0].childNodes[0].firstChild.nodeValue;
	var type = RN[0].childNodes[1].firstChild.nodeValue;
	var html = RN[0].childNodes[2].firstChild.nodeValue;	
	
	document.getElementById('am_'+type+'_'+id_vote).innerHTML = html;
}

function AddDelFav(id_n, flag, hideblock) {
	$.ajax({
		url: "js/add_del_fav.php",
		data: ({id_n: id_n, flag: flag}),
		beforeSend: function(){ $('#fav').html('<span class=\'grey\'>подождите...</span>'); },
		success: function(){
			if(flag){
				$('#fav').html('<a href="#" class="pink_box_link" onclick="AddDelFav(' + id_n + ', 0); return false;" title="удалить публикацию из избранного">из избранного</a>');
				$.fn.colorbox({html:'<p id="test" align="center" style="font-family: Verdana; font-size: 10pt;"><b>Публикация добавлена в избранное!</b></p>', transition: "none", width: "450", height: "140"});
			}
			else{
				$('#fav').html('<a href="#" class="pink_line_link"  onclick="AddDelFav(' + id_n + ', 1); return false;" title="добавить публикацию в избранное">в избранное</a>');
				if (hideblock) {
					$('#id_'+id_n).hide();
					$('#fav_count').html(parseInt($('#fav_count').html()) - 1);
				}
				else {
					$.fn.colorbox({html:'<p id="test" align="center" style="font-family: Verdana; font-size: 10pt;"><b>Публикация удалена из избранного!</b></p>', transition: "none", width: "450", height: "140"});
				}
			}
		}
	});
}

function DelModer(id_n){ // устарела
	if (confirm("Вы действительно за удаление?")) {
		$.ajax({
			url: "js/del_moders.php",
			dataType: "json",
			data: ({id_del: id_n}),
			beforeSend: function(){ $('#delcount').html('<span class=\'grey\'>подождите...</span>'); },
			success: function(json){
				$('#delcount').html('<span class=\'black_box\'>За удаление: ' + json.answer.num + '</span>');
			}
		});
	}
	else {
		 return false;
	}
}
// --> end

// --> Опрос
function poll(id_poll,theGroup){
	var answer = 0;
	for (i=0; i<= theGroup.length; i++) {
		if (theGroup[i]) {
			if (theGroup[i].checked) {
				var answer = theGroup[i].value;
				break;
			}
		}
	}
	/* var amountArea = document.getElementById('poll_'+id_poll).innerHTML = '<span class=\'grey\'>обновление...</span>'; */
	var url = 'js/poll.php?id_poll='+id_poll + '&answer=' + answer;
	makeRequest(url,rtrn_poll);
}

function rtrn_poll(xmldoc){
	var RN = xmldoc.getElementsByTagName('values');
	var id_poll = RN[0].childNodes[0].firstChild.nodeValue;
	var html = RN[0].childNodes[1].firstChild.nodeValue;	
	
	document.getElementById('poll_'+id_poll).innerHTML = html;
}
// --> end

// -->  Создание Lookbook - тултипов для картинок
function CreateLookbookTooltip() {
	$('#text_n img').each(function() {
		var pos = 0;
		var iepos = 0;
		if($(this).attr('vspace') > 0) {
			iepos =    0;
			pos = $(this).attr('vspace');
		}
		else {
			if($(this).css('margin-top') != '0px'){
				iepos = pos = 10;
			}
		}
		
		$(this).wrap("<div class='wrapper'></div>");
		
		$(this).after("<div class='tooltipblock' style=\"margin-top: "+ pos +"px;\" onclick='ImageToLookbook(this, $(this).siblings(\"img\").attr(\"src\"));'>В любимые картинки</div><div class='comtip' style=\"margin-top: "+ (pos-9) +"px;\" onclick='ImageToComment(this, $(this).siblings(\"img\").attr(\"src\"));'>В комментарий</div>");
	});
	
	$('div.tooltipblock, div.comtip').each(function(){
			$(this).css('opacity', 0); //прозрачность 100%
			//$(this).css('width', $(this).siblings('img').width());	//ширина тултипа по ширине картинки
			$(this).parent().css('width', $(this).siblings('img').width());	//ширина обёртывающего div (.wrapper) по ширине картинки - для позиционирования тултипа'
			$(this).css('display', 'block');
	});

	$('div.wrapper').hover(
			function(){	//mouse over
					$(this).children('.tooltipblock, .comtip').stop().fadeTo(500, 0.7);	//отображение тултипа
			},
			function(){	//mouse out
					$(this).children('.tooltipblock, .comtip').stop().fadeTo(500, 0);	//скрытие тултипа
			}
	);
}
// --> end

// --> Добавление картинки в Lookbook
function ImageToLookbook (lst, imgsrc) {
	if(imgsrc){
		$.ajax({
			url: 'js/add_del_fav_pic.php',
			cache: false,
			type: 'POST',
			dataType: 'text',
			data: ({ 'img_src': imgsrc, 'flag': 1, 'id_n': imgsrc.substring(imgsrc.lastIndexOf("pic/")+4, imgsrc.lastIndexOf("/")) }),
			beforeSend: function(){
                                                           $(lst).removeAttr("onclick");
                                                           $(lst).html('Подождите...');
                                                           },
			success: function(data){
					if(data == 1) { $(lst).html('Картинка успешно добавлена в любимые'); }
					else{ $(lst).html('Картинка уже есть в любимых'); }
					},
			error: function(data){
					$(lst).html('Картинка успешно добавлена в любимые');
					}
		});
	}
	else{ alert('Ошибка выбора картинки.'); }
}
// --> end

//--> Добавление картинки в комментарй
function ImageToComment(lst, imgsrc){
	$("#selfoto").val('');
	$("#fotocont").remove();
	$('#img_com').attr('value', imgsrc);
	com_foto_src = imgsrc;
	$('div.comtip').html('В комментарий');
	$(lst).html('Картинка прикреплена к комментарию');
	$("#selected_foto").remove();
	$('#fotolink').after("<div id='selected_foto' style='position: relative;'><a href='#' id='foto_com_add' class='red'>Посмотреть прикрепленную картинку</a><div class='comimg'><img src='" + com_foto_src + "'></div></div>").html('Впрочем, без картинки тоже ничего');
	$('#comselect_image').css('opacity', 1).removeAttr('id');
	$(lst).siblings("img").attr('id', 'comselect_image').css('opacity', 0.3);
 }

// --> Удаление картинки из Lookbook
function DelFavImage (id) {
	$.ajax({
		url: "js/add_del_fav_pic.php",
		data: ({id_fav_p: id, 'flag': 0}),
		success: function() {
			$('#id_'+id).hide();
			$('#fav_count').html(parseInt($('#fav_count').html()) - 1);
		}
	});
}
// --> end

// --> Косметичка
function AddCos(addtype){
    $.ajax({
            url: 'js/add_del_fav_cos.php',
            type: "POST",
            data: ({ 'id_cos': id_cos, 'type': addtype, 'flag': 1 }),
            dataType: 'text',
            beforeSend: function(){
                                                        $("#cos_add_button").hide();
                                                        $("#cos_add_button").after('<div id="statustext" class="cos_add_grey">Подождите...</div><div style="height:43px"></div>');
                                                    },
            success: function(data){
                                                        if(data == 1){
                                                            $("#statustext").html('Товар успешно добавлен');
                                                        }
                                                        else{
                                                                    $("#statustext").html('Ошибка добавления');
                                                                }
                                                       },
               error: function(data){
                                                        //alert('Ошибка: '+data.statusText);
                                                        setTimeout('$("#statustext").remove(); $("#cos_add_button").show();', 2000);
                                                }
    });
}

function VoteCos (id_c, mark) {
	$.ajax({
		url: 'js/vote_cos.php',
		type: "POST",
		data: ({ 'id_c': id_c, 'mark': mark }),
		dataType: 'html',
		beforeSend: function(){
			$("#cos_"+id_c).hide().after('<span id="statustext">подождите...</span>');
		},
		success: function(data){
			$("#cos_"+id_c).html(data);
		},
		error: function(data){
			alert('Ошибка: ' + data.statusText + '\n' + data.responseText);
		},
		complete: function(){
			$("#statustext").remove();
			$("#cos_"+id_c).show();
		}
	});
}

function DelMoveCos (lst, id_cos, stype, deltype) {
	$.ajax({
		url: 'js/add_del_fav_cos.php',
		type: "POST",
		data: ({ 'id_cos': id_cos, 'type': stype, 'flag': 0, 'deltype': deltype }),
		success: function() {
		                                            $(lst).parents('tr:first').remove();
		                                            $('#count_num').html($('#count_num').text() - 1);
		                                            
		                                           },
		   error: function(data){
		                                            alert('Ошибка: ' + data.statusText + '\n' + data.responseText);
		                                    }
		});
}

function FastCosMenu () {
	$.ajax({
		url: 'js/cos_fast_menu.php',
		type: "POST",
		data: ({ 'id_pr': $("#cos_category").val() }),
		dataType: 'json',
		success: function(data) {
			$('#cos_brands').empty();
			var i = 1;
			var brands_list = document.getElementById('cos_brands');
			brands_list.options[brands_list.options.length] = new Option('Бренд не выбран', '0');
			
			for(var key in data) {
				brands_list.options[i++] = new Option(data[key].brand_name, data[key].id_b);
			}
		},
		error: function(data){ alert('Ошибка: ' + data.statusText + '\n' + data.responseText); }
	});
}

// фильтрация комментариев по оценке
function ratefilter(rate){
	if(rate != 0){
		$('#comments > div').each(function(){
			if($(this).attr("rate") == rate){	$(this).show();		}
			else{	$(this).hide();	}
		});
	}
	else{	$('#comments > div').show();	}
}

// сортировка комментариев
// choose - аттрибут для сортировки (id - дата, rate - оценка, us - полезность)
function comsort(choose){
	var ind = [];
	$('#comments > div').each(function(){	ind.push([$(this).attr("id"), $(this).attr(choose)]);	});
	
	ind.sort(function(a, b){
					a = a[1];
					b = b[1];
					if(choose == 'id')	return a - b;		// порядок сортировки по дате - от меньшего к большему
					return b - a;
				});

	for(var i in ind){	$("#comments").append($('#comments > div[id='+ ind[i][0] +']'));	}
}
// --> end

// --> To Top
function body_scroll(){
	if($(this).scrollTop() >= 4500){
		$('#toTop').fadeIn();
	}
	else{
		$('#toTop').fadeOut();
	}
}

function create_totop(){
	var totopdiv = document.createElement('div');
	totopdiv.setAttribute('id', 'toTop');
	totopdiv.onclick = totop_click;
	totopdiv.innerHTML = '<img src="http://92.241.191.127/img/to_top.gif" class="toToPic">Наверх';
	document.body.appendChild(totopdiv);
}

function totop_click(){
	$('body,html').animate({scrollTop:0}, 800);
}
// --> end

//  --> Сортировка лидеров конкурса
function konkurs_sorting(){
	//var start = new Date().getTime();
	var ind = [];
	temp_com = $('#comments').html();
	
	var coms = $('#comments > div');
	var c = coms.length;
	for(var i = 0; i < c; i++){
		if($(coms[i]).attr("parentid") == 0){
			ind.push([$(coms[i]).attr("id"), $(coms[i]).find("span.green_box").html()]);
		}
	}
	
	ind.sort(function(a, b){
					a = a[1];
					b = b[1];
					return b - a;
				});
				
	var sort_cont = '';
	for(var i in ind){
		sort_cont += $('<div>').append($('#'+ ind[i][0]).clone()).remove().html();
		//$("#comments").append($('#comments > div[id='+ ind[i][0] +']'));
	}
	$("#comments").html(sort_cont);
	$('.word_answer').hide();
	$('.add_comment').hide();
	//console.log(new Date().getTime() - start);
	return ind.length;
}
