function str_replace ( search, replace, subject ) {
	if(!(replace instanceof Array)){
		replace=new Array(replace);
		if(search instanceof Array){
			while(search.length>replace.length){
				replace[replace.length]=replace[0];
			}
		}
	}

	if(!(search instanceof Array))search=new Array(search);

	while(search.length>replace.length){
		replace[replace.length]='';
	}

	if(subject instanceof Array){
		for(k in subject){
			subject[k]=str_replace(search,replace,subject[k]);
		}
		return subject;
	}

	for(var k=0; k<search.length; k++){
		var i = subject.indexOf(search[k]);
		while(i>-1){
			subject = subject.replace(search[k], replace[k]);
			i = subject.indexOf(search[k],i);
		}
	}
	return subject;
}

function infotab(group) {
	k=49;
	r=0;
	group.each( function() {
		$(this).css("z-index", k);
		$(this).css("right", r);
		k=k-1;
		r=r+10;
	});
}

/*function favourite_elem(group) {
	k=99;
	group.each( function() {
		$(this).css("z-index", k);
		k=k-1;
	});
}*/

function equalHeight(group) {
    tallest = 0;
    group.each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
        tallest = thisHeight;
        }
    });
    group.height(tallest);
}
$(document).ready(function() {
	$(".news .elem:last").addClass("last");//Убрать бэкграунд в новостях

	//favourite_elem($(".favourite .elem"));

	//infotab($(".tabs .elem"));
	$(".tabs .elem:first").addClass("first");
	$(".tabs .elem").not(".selected").hover(
		function () {
			$(this).addClass("hover");
		},
		function () {
			$(this).removeClass("hover");
		}
    );//оформление info

	$(".prev").hover(
	 function () {
		$(this).addClass("prev-h");
      },
      function () {
		$(this).removeClass("prev-h");
	  }
    );//Подсветка стрелочек

	$(".next").hover(
	 function () {
		$(this).addClass("next-h");
      },
      function () {
		$(this).removeClass("next-h");
	  }
    );//Подсветка стрелочек

	$(".forum .elem:last").addClass("last-elem");//Убрать бэкграунд в новотях с форума
	$(".resurs").hover(
      function () {
        $(this).children(".mm-menu").fadeIn(300);
      },
      function () {
        $(this).children(".mm-menu").fadeOut(10);
      }
    );//Всплывающие мм ресурсы


	$(".text-inn table tr:nth-child(even)").addClass("second");
	$(".text-inn table td:last-child").addClass("last-td");
	$(".text-inn table:not('.no-header') tr:first-child").addClass("table-head");//Для оформления таблиц

	standvalue($("#search"), "Поиск");//исходное значение полей
	standvalue($("#h-login"), "Логин");//исходное значение полей
	standvalue($("#h-pass"), "Пароль");//исходное значение полей
	standvalue($("#login-input"), "Введите логин");//исходное значение полей
	standvalue($("#name-input"), "Введите ваше имя");//исходное значение полей
	standvalue($("#surname-input"), "Введите вашу фамилию");//исходное значение полей
	standvalue($("#email-input"), "Введите ваш адрес электронной почты");//исходное значение полей
	standvalue($("#name"), "Изменить имя");//исходное значение полей
	standvalue($("#lastname"), "Изменить фамилию");//исходное значение полей
	standvalue($("#phone"), "Изменить телефон");//исходное значение полей
	standvalue($("#ops"), "");//исходное значение полей
	standvalue($("#nps"), "");//исходное значение полей
	standvalue($("#rnps"), "");//исходное значение полей

	$(".file-input").filestyle({
		image: "/vs/common/img/input.jpg",
		imageheight : 24,
		imagewidth : 71,
		width : 193
	});//Оформление инпутов

	$(".file-input-b").filestyle({
		image: "/vs/common/img/input.jpg",
		imageheight : 24,
		imagewidth : 71,
		width : 290
	});//Оформление инпутов

	/*$(".favourite .elem").each( function() {
		for (i=2 ; i <= $(".favourite .elem").length ; i=i+3) {
			$(".favourite .elem:eq("+i+")").addClass("fav3");
		}
	});*/ //Для правильного отображения комментов

	$('.page-num').selectstyle(); //Для задания селекта

	$(".lost-table tr td:nth-child(even)").addClass("second");//Оформление таблиц
	$('.search-s select').selectstyle(); //Для задания селекта


	$('.search-d').DatePicker({
		format:'d/m/Y',
		date: $('.search-d').val(),
		current: $('.search-d').val(),
		starts: 1,
		calendars: 1,
		position: 'r',
		onBeforeShow: function(){
			$('.search-d').DatePickerSetDate($('.search-d').val(), true);
		},
		onChange: function(formated, dates){
			$('.search-d').val(formated);
		}
	});//Календарь
	$('.search-d1').DatePicker({
		format:'d/m/Y',
		date: $('.search-d1').val(),
		current: $('.search-d1').val(),
		starts: 1,
		calendars: 1,
		position: 'r',
		onBeforeShow: function(){
			$('.search-d1').DatePickerSetDate($('.search-d1').val(), true);
		},
		onChange: function(formated, dates){
			$('.search-d1').val(formated);
		}
	});//Календарь
	$('.news-date-calend').DatePicker({
		format:'m/Y',
		date: $('.news-date-calend').val(),
		current: $('.news-date-calend').val(),
		starts: 1,
		calendars: 1,
		view: 'days',
		position: 'r',
		onBeforeShow: function(){
			$('.news-date-calend').DatePickerSetDate($('.news-date-calend').val(), true);
		},
		onChange: function(formated, dates){
			$('.news-date-calend').val(formated);
		}
	});//Календарь


	$(".lost-table-text .slider-inn").each(function() {
		if ($(this).height() <= 105)
			{
				$(this).parent().parent().children(".slide-b").hide();
				$(this).parent().css({"height" : "auto" } );
			/*
				this.css({
			top			: -this.outerHeight(),
			marginLeft	: -this.outerWidth()/2,
			position	: 'fixed',
			left		: '50%'
		});
		*/
			}
    });
	$(".lost-table-text .slide-b a").toggle(
		function () {
			k = $(this).parent().parent().children(".slider").children(".slider-inn").height();
			$(this).parent().parent().children(".slider").animate({ height: k}, 300 );
			$(this).text("Свернуть");
		},
		function () {
			$(this).parent().parent().children(".slider").animate({ height: "105px"}, 300 );
			$(this).text("Далее");
		}
    );//Раскрывающееся меню на потерявшихся животных

	$('.delete-ann').click(function (e) {
		e.preventDefault();
		arg=(this.id).split('_');
		id=arg[1];
		$("#del_id").attr("value",id);
		$('#basic-modal-content').modal();
	});//Меню удаления обьявления

	$(".en-ann input").each(function () {
        if ($(this).attr('checked')){
			$(this).parent().parent().parent().addClass("enable");
			$(this).parent().parent().parent().removeClass("disable");
			$(this).parent().children("span").text("активно");


		}
		else {

			$(this).parent().parent().parent().addClass("disable");
			$(this).parent().parent().parent().removeClass("enable");
			$(this).parent().children("span").text("не активно");

		}
    });
	$(".en-ann input").click(function () {
        if ($(this).attr('checked')){



				$(this).parent().parent().parent().addClass("enable");
			$(this).parent().parent().parent().removeClass("disable");
			$(this).parent().children("span").text("активно");
		}
		else {

		$(this).parent().parent().parent().addClass("disable");
			$(this).parent().parent().parent().removeClass("enable");
			$(this).parent().children("span").text("не активно");

		}
    });// Сделать меню не активным

	$(".mydata-table tr:last").addClass("last");//Оформление таблицы в моих данных
	$(".priut table tr:last").addClass("last");//Оформление таблицы в моих данных

});



var board=0;

	function showMainTab(t)
	{
		board=t;
		showMainAnimal(0);
		$(".tabs table.elem").each(function()
		{
			tabs=$(this).attr("id").split('-');
			tab=tabs[1];
		if (tab!=t)
		{
			$(this).removeClass("selected");
			$("#tab-"+tab+" td.right-c").html("<a href='javascript:void(0);' onclick='showMainTab("+tab+"); return false;'>"+$(this).text()+"</a>");
		}
		else
		{
			$(this).addClass("selected");
			$("#tab-"+tab+" td.right-c").html("<span>"+$(this).text()+"</span>");
		}
		})
	}

	function showMainAnimal(a)
	{
		$.ajax({
   			type: "POST",
   			url: "/mainboard/",
   			dataType : "html",
   			cache: false,
   			data: "board="+board+"&animal="+a+"",
   			async: false,
   			beforeSend: function(){
   			   $(".carousel").html("<img src=\"/vs/common/img/loadingAnimation.gif\" />");
 			},
 			success: function(html){
    			$(".carousel").html(html);
    			 $(".carousel").css("width","620px");
               	if ($('.carousel ul').length)
               	{
	               $(".carousel").jCarouselLite({
						btnNext: ".next",
						btnPrev: ".prev",
						visible: 3
					});
				}
            	$(".tag ul li").each(function()
				{
					anims=$(this).attr("id").split('-');
					anim=anims[1];

					if (anim!=a)
					{
						$("#anim-"+anim).html("<a href='javascript:void(0);' onclick='showMainAnimal("+anim+"); return false;'>"+$(this).text()+"</a>")
					}
					else
					{
						$("#anim-"+anim).html("<span>"+$(this).text()+"</span>")
					}
				})


 			}
 		})
	}


$(window).load(function () {
	if (window.location.pathname=="/")
	{
	showMainTab(2706);
    }


	$('.up-img').lightBox({
		overlayBgColor: '#000',
		overlayOpacity:	0.5,
		containerBorderSize:	2,
		imageLoading: '/vs/common/img/lightbox/lightbox-ico-loading.gif',
		imageBtnClose: '/vs/common/img/lightbox/lightbox-btn-close.gif',
		imageBtnPrev: '/vs/common/img/lightbox/lightbox-btn-prev.gif',
		imageBtnNext: '/vs/common/img/lightbox/lightbox-btn-next.gif',
		imageBlank:	'/vs/common/img/lightbox/lightbox-blank.gif',
		txtImage: 'Фотография',
		txtOf: 'из'
	});//Картинки всплывающие


	$("a[rel=example_group]").fancybox({
				'cyclic'				:	true,
				'transitionIn'		: 'fade',
				'transitionOut'		: 'fade',
				'titlePosition' 	: 'over',
				'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
					return ''+ (title.length ? ' &nbsp; ' + title : '' ) + '';
				}
	});



	/*equalHeight($(".eq .elem"));*/
	function trimpx(n){
		return str_replace('px','',n);
	}
	$(".comment").each(function (n,k){
		nw = k.offsetWidth;
		//lm=0;while(k.offsetHeight>230 && lm<20) {$(k).css('width',(k.offsetWidth+4)+'px'); lm++;}
		$(k).css('margin-left', (nw-k.offsetWidth)/2).css('margin-top', -1*(k.offsetHeight)+'px').css('display','none').css('visibility', 'visible');
	})
	$(".favourite .elem-img").hover(
      function () {
		//mtr = $(this).parent().css("z-index");
		$(this).parent().css('z-index','9999');
        $(this).children().children().children().children(".comment").fadeIn(300);
      },
      function () {
		$(this).parent().css('z-index',10);
        $(this).children().children().children().children(".comment").fadeOut(300);
      }
    );//Для комментариев

	$(".ani-shelter-c .slide-in").toggle(
		function () {
			//k = $(this).parent().children(".slide-photo").height();
			$(this).parent().children(".slide-photo").show("slow");
			$(this).addClass("open-n");
			$(this).removeClass("close-n");
			//$(this).text("Свернуть");
		},
		function () {
			//$(this).parent().parent().children(".slider").animate({ height: "105px"}, 300 );
			//$(this).text("Далее");
			$(this).parent().children(".slide-photo").hide("slow");
			$(this).removeClass("open-n");
			$(this).addClass("close-n");
		}
    );//Раскрывающееся меню на животных муниципального приюта


	//$(".best-photo .right img").wrap("<div class='best-photo-cont-new'><table style='background:#000d25; width:85px; height:85px;'><tr><td align='center'></td></tr></table></div>");
	//$(".best-photo .right img").show();
/*
	$(".lost .lost-img img").each( function() {
		if ($(this).height() > 105)
		{
			h = $(this).height();
			$(this).height(105);
			w = $(this).width();
			$(this).width( Math.round(w * 105 / h));
		}
		if ($(this).width() > 105)
		{
			w = $(this).width();
			$(this).width(105);
			h = $(this).height();
			$(this).height( Math.round(h * 105 / w));
		}
	}); //Для задания размера фоток

	$(".slide-photo .lost-img").each( function() {
		if ($(this).height() > 109)
		{
		$(this).addClass("sdfsdfsdf");
		}
	}); //Для задания размера фоток
*/

});

function votePet(id)
			{
				$.ajax({
		    		url: "/pets/votepet/",
		    		data: "action=vote&id="+id+"",
		    		dataType : "json",
		    		type: "POST",
		    		async: false,
		   			cache: false,
		   			timeout: 5000,
		   			error: function() {$(".delete").enable(true);alert('Сервер не ответил, попробуйте ещё раз!');},
		   			beforeSend: function()
		   			{
		   				$(".delete").enable(false);

		   			},
		    		success: function (data, textStatus)
		    		{
		    			$("#voice_"+data['id']+"").html("<p>Ваш голос учтен</p>");
		    			$("#vote_"+data['id']+"").html(data['vote']);

		    			if ($("#votebtn_"+data['id']+"").length)
		    			{
		    			$("#votebtn_"+data['id']+"").html(data['vote']);
		    			}

		    			if ($("#voicebtn_"+data['id']+"").length)
		    			{
		    			$("#voicebtn_"+data['id']+"").html("Ваш голос учтен");
		    			}

		    			if (data['res']=='true')
		    			{
		    			$("#result").html('<div id="basic-modal-content"><table style="z-index:10000;" class="basic-modal-content-table"><tr class="top-t"><td class="border-m" colspan="3">&nbsp;</td></tr><tr class="middle-t"><td class="border-m">&nbsp;</td><td class="text-m"><div class="text-m-c"><table width="300px" height="200px"><tr><td align="center"><h2 align="center">Ваш голос учтен</h2></td></tr></table></div></td><td class="border-m">&nbsp;</td></tr><tr class="bottom-t"><td class="border-m" colspan="3">&nbsp;</td></tr></table></div>');
         				}
         				else
         				{         				$("#result").html('<div id="basic-modal-content"><table style="z-index:10000;" class="basic-modal-content-table"><tr class="top-t"><td class="border-m" colspan="3">&nbsp;</td></tr><tr class="middle-t"><td class="border-m">&nbsp;</td><td class="text-m"><div class="text-m-c"><table width="300px" height="200px"><tr><td align="center"><h2 align="center">Вы уже голосовали за это фото</h2></td></tr></table></div></td><td class="border-m">&nbsp;</td></tr><tr class="bottom-t"><td class="border-m" colspan="3">&nbsp;</td></tr></table></div>');         				}

         				$('#basic-modal-content').modal();
         				$.cookie("votepet["+data['id']+"]","true",{path: "/"});
         				//setTimeout("window.location.href=window.location.href",1000);

		    		}
				});
			}
