function number_format(number, decimals, dec_point, thousands_sep) {
    number = (number+'').replace(',', '').replace(' ', '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
	s = s.join(dec);
	if (s.indexOf(dec_point) != -1) {
		s = rtrim(s,"0");
		s = rtrim(s,dec_point);
	}
    return s;
}

function rtrim ( str, charlist ) {
    charlist = !charlist ? ' \\s\u00A0' : (charlist+'').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\\$1');
    var re = new RegExp('[' + charlist + ']+$', 'g');
    return (str+'').replace(re, '');
}

$(document).ready(function()
{
	$("body").removeClass("noscript");

	//select лучший курс
	changeCurs($("#selcurr1").val());
	$("#selcurr1").change(function() {
		changeCurs($(this).val());
		return false;
	});
	
	/* global replace blocks */
	if($(".forReplaceBlock").length) {
		var colForReplace = $(".forReplace").length;
		for(i=0; i<colForReplace; i++) {
			var forReplaceObj = $(".forReplace").eq(i);
			var forReplace = forReplaceObj.html();

			forReplaceObj.parentsUntil(".forReplaceBlock").find(".forReplaceThere").append("<a href=''>"+forReplace+"</a>");
			$(".forReplaceThere a:first-child").addClass("current");
			$(".forReplaceFrom > div:not(:first-child)").addClass("hide");
		}
		$(".forReplace").remove();
	}

	/*doubleBoxBody tabs*/
	if ($(".doubleBoxBody").length) {
		$(".doubleBoxBody-tabTitle").each(function(){
			if($(this).html()!="") $(this).removeClass("hide");
		});

		$(".doubleBoxBody-tabTitle a").click(function() {
			$(this).addClass("current").siblings().removeClass("current");
			$(this).parent().parent().find(".doubleBoxBody-tabBody-block").eq($(this).index()).removeClass("hide").addClass("visible").siblings().removeClass("visible").addClass("hide");
			return false;
		});
	};

	/* typeOfExchange tabs */
	if($(".typeOfExchange").length) {
		$(".typeOfExchange .typeOfExchange-title .forForm").removeClass("hide");
		$(".typeOfExchange .typeOfExchange-title a").click(function() {
			if(!$(this).hasClass("current")) {
				$(this).addClass("current").siblings().removeClass("current");

				var filterClassName1 = $(".typeOfExchange-title .groupLinks1 a.current span").attr("class");
				var filterClassName2 = $(".typeOfExchange-title .groupLinks2 a.current span").attr("class");

				$(this).parentsUntil(".centerMenuBlockTabs-body-block").find(".typeOfExchange-body table tbody tr").hide();
				$(this).parentsUntil(".centerMenuBlockTabs-body-block").find(".typeOfExchange-body table tbody tr.noHide."+filterClassName1+"."+filterClassName2).fadeIn();
			}

			return false;
		});
	}

	/* typeOfDepartment tabs */
	if($(".typeOfDepartment").length) {
		$(".typeOfDepartment .typeOfExchange-title .forForm").removeClass("hide");
		$(".typeOfDepartment .typeOfExchange-title a").click(function() {
			$(this).addClass("current").siblings().removeClass("current");
			var filterClassName1 = $(".typeOfExchange-title .groupLinks1 a.current span").attr("class");

			$(this).parentsUntil(".centerMenuBlockTabs-body-block").find(".typeOfExchange-body table tbody tr").hide();
			if ( detectIE6() ) {
				$(this).parentsUntil(".centerMenuBlockTabs-body-block").find(".typeOfExchange-body table tbody tr."+filterClassName1).show();
			}
			else {
				$(this).parentsUntil(".centerMenuBlockTabs-body-block").find(".typeOfExchange-body table tbody tr."+filterClassName1).fadeIn();
			}

			return false;
		});
	}

	/* typeOfExchangeCurs tabs */
	if($(".typeOfExchangeCurs").length) {
		$(".typeOfExchangeCurs .typeOfExchange-title .forForm").removeClass("hide");
		$(".typeOfExchangeCurs .typeOfExchange-title a").click(function() {
			if(!$(this).hasClass("current")) {
				$(this).addClass("current").siblings().removeClass("current");
				$(this).parentsUntil(".forReplaceBlock").find(".typeOfExchangeCurs").eq($(this).index()).removeClass("hide").addClass("visible").siblings().removeClass("visible").addClass("hide");
				$(this).parentsUntil(".forReplaceBlock").find(".typeOfExchangeCurs").eq($(this).index()).find(".typeOfExchange-title a").eq($(this).index()).addClass("current").siblings().removeClass("current");
			}

			return false;
		});
	}

	/* centerMenuBlockTabs tabs */
	if($(".centerMenuBlockTabs").length) {
		$(".forCenterMenu .centerMenuTab").click(function() {
			$(this).addClass("active").siblings().removeClass("active");
			$(this).parent().parent().parent().parent().parent().find(".centerMenuBlockTabs-body-block").eq($(this).index()).removeClass("hide").addClass("visible").siblings().removeClass("visible").addClass("hide");
			//setTimeout("differentHeight()",1000);
			differentHeight();
			return false;
		});
	}

	/* doubleBoxBody Title */
	if ($(".courses").length) {
		$(".doubleBox").each(function() {
			if(!$(this).hasClass("open")) $(this).find(".doubleBoxBody").hide();
		});

		$(".doubleBoxTitle").hover(function() {
			if(!$(this).parent().hasClass("top")) {
				$(this).css("background-position","left -34px");
			}
			else {
				$(this).css("background-position","left -36px");
			}
		},
		function() {
			$(this).css("background-position","left top");
		})

		/************* ACCORDEON***********
		$(".doubleBoxTitle").click(function() {
			if($(this).parent().hasClass("open")) {
				$(this).parent().removeClass("open");
				if ( detectIE6() ) {
					$(this).parent().find(".doubleBoxBody").hide().queue(function(next){differentHeight();next();});
				}
				else {
					$(this).parent().find(".doubleBoxBody").slideUp().queue(function(next){differentHeight();next();});
				}
			}
			else {
				$(this).parent().addClass("open").siblings().removeClass("open");
				if ( detectIE6() ) {
					$(this).parent().find(".doubleBoxBody").show().queue(function(next){differentHeight();next();}).parent().siblings().find(".doubleBoxBody").hide().queue(function(next){differentHeight();next();});
				}
				else {
					$(this).parent().find(".doubleBoxBody").slideDown().queue(function(next){differentHeight();next();}).parent().siblings().find(".doubleBoxBody").slideUp().queue(function(next){differentHeight();next();});
				}
			}
			return false;
		});*****************/
		$(".doubleBoxTitle").click(function() {
			if($(this).parent().hasClass("open")) {
				$(this).parent().removeClass("open");
				if ( detectIE6() ) {
					$(this).parent().find(".doubleBoxBody").hide().queue(function(next){differentHeight();next();});
				}
				else {
					$(this).parent().find(".doubleBoxBody").slideUp().queue(function(next){differentHeight();next();});
				}
			}
			else{
				$(this).parent().addClass("open");
				if ( detectIE6() ) {
					$(this).parent().find(".doubleBoxBody").show().queue(function(next){differentHeight();next();});
				}
				else {
					$(this).parent().find(".doubleBoxBody").slideDown().queue(function(next){differentHeight();next();});
				}
			}
			return false;
		});
	};

	/* btn rss */
	if($(".rss").length) {
		$(".rss").mousedown(function(){
			$(this).css("background-position","left -40px");
		})
		.mouseup(function(){
			$(this).css("background-position","left top");
		});
	};

	/* btns */
	if($(".btn1").length) btnFocus($(".btn1"));
	if($(".btn2").length) btnFocus($(".btn2"));
	if($(".btnPromo").length) btnFocus1($(".btnPromo"));
	if($(".btn5").length) btnFocus2($(".btn5"));

	/* forms */
	if($(".forForm").length) {
		$(".forForm").find(":text").focusin(function(){
			$(this).addClass("focus");
		}).focusout(function(){
			$(this).removeClass("focus");
		});

		$(".forForm").find("textarea").focusin(function(){
			$(this).addClass("focus");
		}).focusout(function(){
			$(this).removeClass("focus");
		})
	}

	/* Search */
	if($("#searchinp").length) {
		$("#searchinp").focusin(function(){
			$(this).css("color","#000000").css("border-color","#92b2d2");
		})
		.focusout(function(){
			$(this).css("color","#999999").css("border-color","#d5d5d5");
		})
		.bind('keyup', function(){
			var str = $(this).val();
			if (str.length > 2) {
				$.ajax({
					'global' : false,
					'timeout' : 1000,
					'url' : '/quicksearch.php?'+Math.random(),
					'type' : 'POST',
					'data' : {
						'search' : str
					},
					'async': true,
					'dataType' : 'xml',
					'error' : function(obj, textStatus){
						if (!$("#searchSmart").hasClass('hide'))
							$("#searchSmart").addClass('hide');
					},
					'success': function(data, textStatus) {
						if ($(data).find('root item').length) {
							$("#searchSmart").find('.searchSmartInside').html('');
							$(data).find('root item').each(function(){
								var objMain = $("#searchSmart");
								var obj = objMain.find('.searchSmartInside').eq(0);
								var str = '<a href="'+$(this).find('url').text()+'">';
								if ($(this).find('icon').text() != '') str += '<img class="searchImage" width="35" alt="" src="/uploads/content/icons/'+$(this).find('icon').text()+'" />';
								str += '<span>'+$(this).find('name').text();
								if ($(this).find('text').text() != '') str += '<ins>'+$(this).find('text').text()+'</ins>';
								str += '</span></a>';
								obj.append(str);
							});
							$("#searchSmart").removeClass("hide");
							var widthForLink = $("#searchSmart").find(".searchSmartInside").width();
							$("#searchSmart a").css("width", widthForLink);
						}
						else {
							if (!$("#searchSmart").hasClass('hide'))
								$("#searchSmart").addClass('hide');
						}
					}
				});
			}
			else {
				if (!$("#searchSmart").hasClass('hide'))
					$("#searchSmart").addClass('hide');
			}
		});
	}

	/* Search Results */
	if($("#searchinputbig").length) {
		$("#searchinputbig").focusin(function(){
			$(this).css("color","#000000").css("border-color","#92b2d2");
		})
		.focusout(function(){
			$(this).css("color","#999999").css("border-color","#d5d5d5");
		})
		.css("color","#000000").css("border-color","#92b2d2").focus();
	}

	/* Select City */
	if($(".forCity").length) {
		$(".forCityTitle .activLink").click(function(){
			$(".selectCity").removeClass("hide");
			return false;
		});
		$(".cityClose").click(function(){
			$(".selectCity").addClass("hide");
			return false;
		})
		$(".cityList a").click(function(){
			var newCity = $(this).html();
			$(".forCityTitle h5").html(newCity);
			$(".cityClose").click();
			window.location = $(this).attr('href');
			return false;
//			var needReload = $(this).parent().parent().find("li[class='current']").length ? false : true;
//			$(this).parents(".cityList:first").find("li").removeClass("current");
//			$(this).parent().addClass("current");
//			$(".cityClose").click();
//			if (needReload) window.location = $(this).attr('href');
//			else $.post('/feedback.php'+$(this).attr('href'), {ajax:1});
//			return false;
		})
	}

	/* Height blocks */
	if($(".forNewsAnno").length)
		setEqualHeight($(".forNewsAnno .col1, .forNewsAnno .col2, .forNewsAnno .col3,"))

	/* Slider */
/*	if($(".overflowBlockSlider").length) {
		var scroll_prev = false,
		scroll_next = false;

		$("#foo1").carouFredSel({
			//auto 		: false,
			items		: 7,
			scroll 		: {
				items 		: 1,
				duration	: 1000,
				easing		: "linear",
				pauseOnHover	: true
			},
			prev : {
				onAfter : function() {
					if (scroll_prev) setTimeout(function() {$("#foo1").trigger("prev");}, 10);
				}
			},
			next : {
				onAfter : function() {
					if (scroll_next) setTimeout(function() {$("#foo1").trigger("next");}, 10);
				}
			}
		});
		$("#foo1_prev").hover(
			function() {
				scroll_prev = true;
				$("#foo1").trigger("prev");
			},
			function() {
				scroll_prev = false;
			}
		).click(function() {
			return false;
		});
		$("#foo1_next").hover(
			function() {
				scroll_next = true;
				$("#foo1").trigger("next");
			},
			function() {
				scroll_next = false;
			}
		).click(function() {
			return false;
		});

		// Click
		$(".overflowBlockSlider").find(".promoSlider a").click(function() {
			$(this).addClass("active").siblings().removeClass("active");
			srcObj = $(this).find("img").attr("class");
			hrefObj = $(this).find("img").parent().attr("href");
			if($(".promoBlockBigImg").length)
				$(".promoBlockBigImg").find("img").attr("src",srcObj).parent().attr('href', hrefObj);
			return false;
		});
	}
*/

	/* JCarousel */
	if($('#mycarouseltop').length)
	{
		var colLi= $('#mycarouseltop').find('li').length;
		if($('#change_banner').length && colLi > 1)
			var autoTimer = 15;
		else
			var autoTimer = 0;
		
		$("#mycarouseltop").jcarousel({
			scroll: 1,

			auto: autoTimer,
			wrap: 'circular',
			initCallback: mycarousel_initCallback,
			// This tells jCarousel NOT to autobuild prev/next buttons
			buttonNextHTML: null,
			buttonPrevHTML: null,
			itemVisibleInCallback: {
				onBeforeAnimation: function(objCarusel, objLi, indexLi){

					/*alert(colLi+' '+indexLi);*/
					indexLi = indexLi % colLi;
					/*alert(indexLi);*/
					$('#mycarouseltop').find('.promo-navi a').eq(indexLi-1).css('background-position','0px top').siblings().css('background-position','-20px top');
				}
			}
		});
	};


	if($(".content table").length) {
		$(".content table").each(function() {
			if(!$(this).hasClass("notformated")) {
	/*			objFirstTr = $(".content table tbody tr:first-child").html();
				$(".content table tbody").prepend("<tr class='firstTr'>"+objFirstTr+"</tr>");
				$(".content table tbody tr:first-child td").css("border-bottom","none").html("&nbsp;");*/

				$(this).find("tbody tr:last-child td").css("border-bottom","none");
				$(this).find("tbody tr:first-child").addClass("first-child");

				$(this).find("tbody td").hover(function() {
					if($(this).attr('rowspan') <= 1) {
						//if(!$(this).parent().hasClass("firstTr"))
						//{
							$(this).parent().find("td").each(function() {
								if($(this).attr('rowspan') <= 1)
									$(this).css("cursor","pointer").css("background-color","#f4f4f4");
							});
						//}
					}
				},
				function() {
					$(this).parent().find("td").css("background-color","");
				})
			}

		})

	}

	/* .forNewsAnnounceOpen */
	if($(".forNewsAnnounceOpen").length)
		$(".forNewsAnnounceOpen").find(".newAnnounceOpen:last-child").css("border-bottom","none");

	/* .forLineCards */
	if($(".forLineCards").length)
		$(".forLineCards").find(".lineCards:last-child").css("border-bottom","none");

	/* Site Map */
	if($(".forSiteMap").length) {
		$(".siteMap-title").removeClass("hide");
		$(".shortMap").click(function() {
			$(this).addClass("current").siblings().removeClass("current");
			$(".siteMap-body ul li ul li ul").slideUp();
			return false;
		});
		$(".allMap").click(function() {
			$(this).addClass("current").siblings().removeClass("current");
			$(".siteMap-body ul li ul li ul").slideDown();
			return false;
		});
	}

	/* Checkbox */
	if($(".checkboxForSubscribe").length) {
		var lengthChecbox = $(".checkboxForSubscribe").find(":checkbox").length;

		$(".forCheckBox2").find(":checkbox").click(function() {
			var lengthChecboxCheck = $(".checkboxForSubscribe").find(":checkbox:checked").length;
			if(lengthChecboxCheck < lengthChecbox) $("#subs-all").attr("checked","");
		});

		$("#subs-all").click(function() {
			if($("#subs-all").is(":checked"))
				$(".forCheckBox2").find(":checkbox").attr("checked","checked");
			else
				$(".forCheckBox2").find(":checkbox").attr("checked","");
		});
	}

	/* pagination */
	if($(".forPagination").length) {
		clickBtnPaginLeft($(".paginPrev"));
		clickBtnPaginRight($(".paginNext"));
		$(".paginPrevDisabled").click(function(){return false;}); //new class for IE6
		$(".paginNextDisabled").click(function(){return false;});
	}

	/* questions for section */
	if($(".forQueSection").length) {
		$(".queSection-a").hide();
		$(".queSection-q a").removeClass("open");
		$(".openAll").removeClass("hide");

		$(".queSection-q a").click(function(){
			if ($(this).hasClass("open")) {
				$(this).parent().parent().find(">.queSection-a").hide().removeClass("open").queue(function(next){differentHeight();next();});

				$(this).removeClass("open");
				return false;
			}
			else {
				$(this).parent().parent().find(">.queSection-a").show().addClass("open").queue(function(next){differentHeight();next();});

				$(this).addClass("open");
				return false;
			}
		});

		$(".openAll a").toggle(function(){
			$(this).html("Свернуть все ответы");
			var obj = $(".forQueSection");
			obj.find(".queSection-a .queSection-a").show().addClass("open").parent().find(".queSection-q:eq(0)").find('a').addClass("open");
			obj.find(">.queSection > .queSection-a").show().addClass("open").parent().find(">.queSection-q").find('a').addClass("open");
			//$(this).queue(function(next){differentHeight();next();});
			differentHeight();
		},
		function(){
			$(this).html("Развернуть все ответы");
			var obj = $(".forQueSection");
			obj.find(".queSection-a").hide().removeClass("open").parent().find(".queSection-q:first").find('a').removeClass("open");
			//$(this).queue(function(next){differentHeight();next();});
			differentHeight();
		});
	};

	/* job list */
	if($(".forJobList").length) {
		$(".queSection-a").hide();
		$(".queSection-q a").removeClass("open");

		$(".queSection-q a").toggle(function(){
			$(this).parent().parent().find(">.queSection-a").slideDown().queue(function(next){differentHeight();next();});
			$(this).addClass("open");
		},
		function(){
			$(this).parent().parent().find(">.queSection-a").slideUp().queue(function(next){differentHeight();next();});
			$(this).removeClass("open");
		});
	}

	/* Magazine hover */
	if($(".magazineSmall-popup-content").length) {
		var colMagazinTrumbnail = $(".magazineSmall-img").length;

		for(i=1; i<=colMagazinTrumbnail; i++)
			if (i % 4 == 0)
				$(".magazineSmall").eq(i-1).addClass("fourth");

		$(".magazineSmall-img").hover(function(){
			var topPosition=$(this).offset().top-10;
			var leftPosition=$(this).offset().left-290;
			$(this).find(".magazineSmall-img-hovermask").show();
			$("#altText .magazineSmall-popup-center").html($(this).parent().find('.forMagazineSmall-popup-content').html());
			$("#altText").css({left:leftPosition+"px", top:topPosition+"px"}).show();
		}, function(){
			$("#altText").hide();
			$(this).find(".magazineSmall-img-hovermask").hide();
		});
	}

	/* Hover Img Alpha *
	if($(".promo2-img").length) {
		$(".promo2-img").hover(function(){
			$(this).animate({opacity:0.6},200);
		},
		function(){
			$(this).animate({opacity:1},200);
		});
	}
	*/

	/* Calculator */
	if($(".calcBlockParam").length) {
		$(".calcBlockParam-info .activLinkLine").click(function(){
			var txt = $(this).html();
			$(this).parent().parent().find("input:text").attr("value",txt);
			return false;
		})
	}

	/* Mist */
//		if($(".mist").length) {
//			$(".mist")).each(function(){
//				$(this).height($(this).parent().innerHeight());
//				$(this).width($(this).parent().innerWidth());
//			});
//		}

	jQuery.fn.checkCounter = function(options) {
		var options = jQuery.extend({
			min: 1,
			max: 12,
			width: '30px',
			text: '',
			comments: '',
			errors: {
				min: 'Минимальное значение - {min}',
				max: 'Максимальное значение - {max}',
				notnumber: 'Введенная строка должна быть числом',
				def: 'Ошибка ввода'
			}
		}, options);

		return this.each(function(){
			jQuery(this).data('options', options);

			var str = '<div class="forCounter"><div class="counterBox"></div>';
			if (options.text) str += '<span>'+options.text+'</span>';
			if (options.comments) str += '<p class="calcBlockParam-info">'+options.comments+'</p>';
			str += '</div>';
			jQuery(this).wrap(str).css('width', options.width)
			.after('<div class="counters"><div class="counterUp"></div><div class="counterDown disableCount"></div></div>')
			.attr('maxlength', parseInt(options.max.toString().length)+1)
			.addClass('notBold').addClass('inputCounter');

			jQuery(this).parent().find('.counterUp, .counterDown').each(function(){
				jQuery(this).hover(
					function(){
						if(!jQuery(this).hasClass("disableCount")) jQuery(this).css("background-position","left -22px");
					},
					function(){
						if(!jQuery(this).hasClass("disableCount")) jQuery(this).css("background-position","left -11px");
					}
				);

				jQuery(this).mousedown(function(){
					if(!jQuery(this).hasClass("disableCount")) jQuery(this).css("background-position","left -33px");
				})
				.mouseup(function(){
					if(!jQuery(this).hasClass("disableCount")) jQuery(this).css("background-position","left -22px");
				});
			});

			var counterUp = jQuery(this).parent().find('.counterUp');
			var counterDown = jQuery(this).parent().find('.counterDown');

			counterUp.bind('click', {options : options}, function(event) {
				if(!jQuery(this).hasClass("disableCount")) {
					var elem = jQuery(this).parent().parent().find('input');
					var value = elem.val();
					value = parseInt(value) + 1;

					if (event.data.options.max == 'none' || value <= event.data.options.max) elem.val(value).keyup();
				}
			});

			counterDown.bind('click', {options: options}, function(event) {
				if(!jQuery(this).hasClass("disableCount")) {
					var elem = jQuery(this).parent().parent().find('input');
					var value = elem.val();
					value = parseInt(value) - 1;

					if (event.data.options.min == 'none' || value >= event.data.options.min) elem.val(value).keyup();
				}
			});

			function checkCounter_errorTemplate(input, template, options) {
				var str = '';

				if (template) {
					var insertTemplateBegin = '<a class="activLinkLine" href="" onclick="return false;">';
					var insertTemplateEnd = '</a>';

					str = template.replace(/{min}/i, insertTemplateBegin + options.min + insertTemplateEnd);
					str = str.replace(/{max}/i, insertTemplateBegin + options.max + insertTemplateEnd);

					if (str) {
						input.parent().parent()
						.append('<p class="calcBlockParam-error">'+str+'</p>')
						.find('.calcBlockParam-error a')
						.mousedown(function(){
							jQuery(this).parent().parent().find('input').val(jQuery(this).text()).keyup().focus();return false;
						});
					}
				}
				return str;
			}

			jQuery(this).bind('keyup change', {options : options}, function(event){
				var errorType = 0;
				var value = jQuery(this).val();
				var r = new RegExp("^[\-]{0,1}[1-9]{0,1}[0-9]+$");

				if (!r.test(value)) errorType = 1;

				if (!errorType) {
					value = parseInt(value);
					if (event.data.options.min != 'none' && value < event.data.options.min) errorType = 2;
					if (event.data.options.max != 'none' && value > event.data.options.max) errorType = 3;
				}

				jQuery(this).parent().parent().find('.calcBlockParam-error').remove();
				if (errorType) {
					var errorTemplate = event.data.options.errors.def;

					if (errorType == 1) {
						// введенная строка не число
						jQuery(this).parent().find('.counterDown, .counterUp').addClass('disableCount');
						if (event.data.options.errors.notnumber) errorTemplate = event.data.options.errors.notnumber;
					}
					else if (errorType == 2) {
						// введено число меньше options.min
						jQuery(this).parent().find('.counterDown').addClass('disableCount').parent().find('.counterUp').removeClass('disableCount');
						if (event.data.options.errors.min) errorTemplate = event.data.options.errors.min;
					}
					else if (errorType == 3) {
						// введено число больше options.max
						jQuery(this).parent().find('.counterUp').addClass('disableCount').parent().find('.counterDown').removeClass('disableCount');
						if (event.data.options.errors.max) errorTemplate = event.data.options.errors.max;
					}
					jQuery(this).parent().addClass('error');
					checkCounter_errorTemplate(jQuery(this), errorTemplate, event.data.options);
				}
				else {
					jQuery(this).parent().removeClass('error');

					value = parseInt(value);
					if (value == event.data.options.min)
						jQuery(this).parent().find('.counterDown').addClass('disableCount').parent().find('.counterUp').removeClass('disableCount');
					else if (value == event.data.options.max)
						jQuery(this).parent().find('.counterUp').addClass('disableCount').parent().find('.counterDown').removeClass('disableCount');
					else
						jQuery(this).parent().find('.counterUp, .counterDown').removeClass('disableCount');
				}
			}).keyup();
		});
	};

	/* DropDown Menu */
	if ($(".forDropDownMenu").length) {
		if(printVersion==false) {
			$(".selectForDropDownMenu").hide();
			$(".forDropDownMenu").show();
		}

		$(".dropDownMenu a").click(function(){
			if ($('#calculate_block').length) return true;
			if(!$(this).parent().hasClass("dropMenuCurrent")) {
				var nameLink = $(this).attr("name");
				nameLink = nameLink.replace('town_', '');
//				var htmlLink = $(this).parent().html();
//				var htmlCurrentLink = $(".dropMenuCurrent").html();

				$(this).parentsUntil(".forDropDownMenuBox").find("option").each(function(){
					if($(this).attr("value")==nameLink)
						$(this).attr("selected","selected").siblings().removeAttr("selected");
				});

				//$(".dropMenuCurrent").html(htmlLink);
				//$(this).parent().html(htmlCurrentLink);

				$(this).parentsUntil("form").parent().parent().find("form").submit();
			}
			return false;
		})

		$(".dropMenuCurrent a").mouseover(function(){
			$(this).parent().parent().parent().parent().parent().removeClass("closed").addClass("open");
			$(this).parent().parent().find('div').show();
			var widthDropDownMenu =$(this).parent().parent().innerWidth();
			$(".dropDownMenu").css("width",widthDropDownMenu+20);
			if ( detectIE6() )
				$(".forForm").find("select").css("visibility","hidden");
		});


		$(".dropDownMenu").hover(function(){
		}, function(){
			$(this).parent().addClass("closed");
			$(this).find(".dropDownMenuInside div").each(function(){
				if(!$(this).hasClass("dropMenuCurrent")) $(this).hide();
			});
			if ( detectIE6() )
				$(".forForm").find("select").css("visibility","visible");
		});
	};

	if ($(".content").length) differentHeight();
	if ($(".forNewsAnno").length) differentHeight();

	/* Tooltips */
	if($(".tooltip").length) {
		$(".forTooltip").hover(function(){
			$(this).parent().find(".tooltip").show();
		}, function(){
			$(this).parent().find(".tooltip").hide();
		});
		$(".tooltip").hover(function(){
			$(this).show();
		}, function(){
			$(this).hide();
		})
	};

	if($(".forNewsAnno").length)
	{
		$(".forNewsAnno .forImgBorder").hover(function()
		{
			$(this).parent().addClass("hover");
		}, function()
		{
			$(this).parent().removeClass("hover");
		});
		$(".forNewsAnno .titleNew").hover(function()
		{
			$(this).parent().parent().parent().addClass("hover");
		}, function()
		{
			$(this).parent().parent().parent().removeClass("hover");
		});
	};

     $('.show-hidden-text').each(function(){
          var $text = $('.sh-text .span', $(this));
          var lh = parseInt($(this).css('line-height'));
          var top = lh/2 - 3;
          if (top < 4) top = 4;
          $('.str', $(this)).css('top', top+'px');
     });

     $('.with-hidden-text .hidden-text').slideUp(0);
     $('.with-hidden-text .show-hidden-text .sh-text').click(function(){
          var $div = $(this).parents('.with-hidden-text');
          var $divHT = $div.find('.hidden-text');
          if(!$divHT.is(':animated')){
               if($div.hasClass('opn')){
                    $div.removeClass('opn');
                    $divHT.slideUp(500);
               }
               else {
                    $div.addClass('opn');
                    $divHT.slideDown(500);
               }
          }
     });

});

/* height block */
function setEqualHeight(columns) {
	var tallestcolumn = 0;
	columns.each(function() {
		var currentHeight = $(this).height();
		if(currentHeight > tallestcolumn)
			tallestcolumn  = currentHeight;
	});
	columns.height(tallestcolumn);
}

function detectIE6(){
  var browser = navigator.appName;
  if (browser == "Microsoft Internet Explorer"){
	var b_version = navigator.appVersion;
	var re = /\MSIE\s+(\d\.\d\b)/;
	var res = b_version.match(re);
	if (res[1] <= 6) return true;
  }
  return false;
}

/* buttons focus */
function btnFocus(btn) {
	$(btn).hover(function() {
		if(!$(this).hasClass("disabled"))
		{
			$(this).css("background-position","left -52px");
			$(this).find("input").css("background-position","right -78px").css("color","#129de7");
		}
	},
	function() {
		if(!$(this).hasClass("disabled"))
		{
			$(this).css("background-position","left 0px");
			$(this).find("input").css("background-position","right -26px").css("color","#333333");
		}
	});

	$(btn).mousedown(function() {
		if(!$(this).hasClass("disabled"))
		{
			$(this).css("background-position","left -104px");
			$(this).find("input").css("background-position","right -130px").css("color","#000000");
		}
	}).mouseup(function() {
		if(!$(this).hasClass("disabled"))
		{
			$(this).css("background-position","left 0px");
			$(this).find("input").css("background-position","right -26px").css("color","#333333");
		}
	});
};
function btnFocus1(btn) {
	$(btn).hover(function() {
		if(!$(this).hasClass("disabled"))
		{
			$(this).css("background-position","right -109px");
			$(this).find(":first-child").css("background-position","left -73px");
		}
	},
	function() {
		if(!$(this).hasClass("disabled"))
		{
			$(this).css("background-position","right -36px");
			$(this).find(":first-child").css("background-position","left 0px");
		}
	});

	$(btn).mousedown(function() {
		if(!$(this).hasClass("disabled"))
		{
			$(this).css("background-position","right -183px");
			$(this).find(":first-child").css("background-position","left -147px").css("text-shadow","0 -1px 1px rgba(180,120,6,1)");
		}
	}).mouseup(function() {
		if(!$(this).hasClass("disabled"))
		{
			$(this).css("background-position","right -36px");
			$(this).find(":first-child").css("background-position","left 0px").css("text-shadow","0 -1px 1px rgba(201,133,6,1)");
		}
	});
};
function btnFocus2(btn) {
	$(btn).hover(function() {
		if(!$(this).hasClass("disabled"))
		{
			$(this).css("background-position","left -73px");
			$(this).find(":first-child").css("background-position","right -109px").css("color","#129de7");
		}
	},
	function() {
		if(!$(this).hasClass("disabled"))
		{
			$(this).css("background-position","left 0px");
			$(this).find(":first-child").css("background-position","right -36px").css("color","#333333");
		}
	});

	$(btn).mousedown(function() {
		if(!$(this).hasClass("disabled"))
		{
			$(this).css("background-position","left -147px");
			$(this).find(":first-child").css("background-position","right -183px").css("color","#000001");
		}
	}).mouseup(function() {
		if(!$(this).hasClass("disabled"))
		{
			$(this).css("background-position","left 0px");
			$(this).find(":first-child").css("background-position","right -36px").css("color","#333333");
		}
	});
};

/* pagination */
function clickBtnPaginLeft(btn) {
	if(!btn.hasClass("disabled")) {
		$(btn).mousedown(function(){
			$(this).css("background-position","left -92px");
		}).mouseup(function(){
			$(this).css("background-position","left -62px");
		});
	}
	else {
		$(btn).click(function(){
			return false;
		});
	}
}

function clickBtnPaginRight(btn) {
	if(!btn.hasClass("disabled")) {
		$(btn).mousedown(function(){
			$(this).css("background-position","right -92px");
		}).mouseup(function(){
			$(this).css("background-position","right -62px");
		});
	}
	else {
		$(btn).click(function(){
			return false;
		});
	}
}

/* different Height left and Right Column */
function differentHeight(){
	$(".columnDifferent").remove();
	var columnLeftHeihgt = $(".columnLeft").innerHeight()-14;
	var columnRightHeihgt = $(".columnRight").innerHeight();
	var columnDifferentHeihgt = columnLeftHeihgt - columnRightHeihgt;
	
	//alert(columnLeftHeihgt);
	//$(".content").css("min-height",columnLeftHeihgt-253);
	if($(".content").length)
	{
		if (columnDifferentHeihgt > 0) {
			$(".content").append("<div class='columnDifferent'></div>");
			$(".columnDifferent").css("height",columnDifferentHeihgt);
		}
		else {
			$(".content").append("<div class='columnDifferent'></div>");
		}
	}
	if($(".forNewsAnno").length)
	{
		if (columnDifferentHeihgt > 0) {
			$(".forNewsAnno").after("<div class='columnDifferent'></div>");
			$(".columnDifferent").css("height",columnDifferentHeihgt+5);
		}
		else {
			$(".content").append("<div class='columnDifferent'></div>");
		}
	}
};

var gmap = {
	markers: new Array(),
	map: '',
	town_scope: '',
	town_coord1: '',
	town_coord2: '',
	markerNumber: 0,

	markerAdd: function(obj) {
		this.markers[this.markerNumber] = {
			address: obj.address,
			title: obj.title,
			scope: obj.scope,
			coord1: obj.coord1,
			coord2: obj.coord2,
			obj: '',
			icon: obj.icon,
			infowindow: obj.infowindow
		}
		this.markerNumber++;

		return this.markerNumber-1;
	},

	markerShow: function(num) {
		this.markers[num].obj = new google.maps.Marker({
			position: new google.maps.LatLng(this.markers[num].coord1, this.markers[num].coord2),
			map: this.map,
			draggable: false,
			animation: google.maps.Animation.DROP,
			title: this.markers[num].title
		});

		this.markers[num].obj.setIcon(this.markers[num].icon);

		google.maps.event.addListener(this.markers[num].obj, 'click', function() {
			infowindow = new google.maps.InfoWindow({
				content: gmap.markers[num].infowindow
			});

			infowindow.open(gmap.map, gmap.markers[num].obj);
		});
	},

	init: function(coord1, coord2, scope) {
		this.town_coord1 = coord1;
		this.town_coord2 = coord2;
		this.town_scope = scope;

		if (this.town_scope != '') this.town_scope = parseInt(this.town_scope);
		if (this.town_coord1 != '') this.town_coord1 = parseFloat(this.town_coord1);
		if (this.town_coord2 != '') this.town_coord2 = parseFloat(this.town_coord2);

		if (!this.town_scope || this.town_scope <= 0) this.town_scope = 6;
		if (!this.town_coord1 || this.town_coord1 <= 0) this.town_coord1 = 53.908644;
		if (!this.town_coord2 || this.town_coord2 <= 0) this.town_coord2 = 27.575033;

		var myLatlng = new google.maps.LatLng(this.town_coord1, this.town_coord2);
		var myOptions = {
			zoom: this.town_scope,
			center: myLatlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			panControl: true,
			zoomControl: true,
			mapTypeControl: true,
			scaleControl: true,
			streetViewControl: false
		}

		this.map = new google.maps.Map(document.getElementById("google_map"), myOptions);
		this.map.setCenter(myLatlng);
	},

	markersClear: function() {
		for (var i = 0; i < this.markers.length; i++)
			if (this.markers[i].obj != '') this.markers[i].obj.setMap(null);
	},

	setDefault: function() {
		google.maps.event.trigger(this.map, 'resize');
		var myLatlng = new google.maps.LatLng(this.town_coord1, this.town_coord2);
		this.map.setCenter(myLatlng);
		this.map.setZoom(parseFloat(this.town_scope));
	},

	markersShow: function() {
		for (var i = 0; i < this.markers.length; i++)
			//gmap.markerShow(i);
			setTimeout('gmap.markerShow('+i+')', i * 50);
	},

	showColorbox: function(num) {
		$.colorbox({
			width:'80%',
			innerHeight:'420px',
			inline:true,
			href:'.yaMap',
			current: "image {current} of {total}",
			previous: "назад",
			next: "вперёд",
			close: "",
			title: gmap.markers[num].title+' ('+gmap.markers[num].address+')',
			onComplete:function(){
				google.maps.event.trigger(gmap.map, 'resize');
				gmap.map.setCenter(new google.maps.LatLng(gmap.markers[num].coord1, gmap.markers[num].coord2));
				var scope = gmap.markers[num].scope;
				gmap.map.setZoom(parseFloat(scope));
				gmap.markerShow(num);
			}
		});
	}
};

var smallCalculator = {
	mainobj	: null,
	table	: null,
	input	: null,
	select	: null,
	type	: null, //0 - sell, 1 - buy
	conversion: new Array(),
	courses: new Array(),

	init: function() {
		this.mainobj = $('.formExchange').eq(0).parent().parent().parent();

		this.mainobj.find('.doubleBoxBody-tabTitle').eq(0).find('a').click(function(){
			var numEq = smallCalculator.type==1 ? 0 : 1;
			$(this).parent().next().find('.doubleBoxBody-tabBody-block').eq(numEq).find('.formExchange select').val(smallCalculator.select.val()).parent().find('input').val(smallCalculator.input.val());
			smallCalculator.reinit();

		});
		this.reinit();

		var elem = this.mainobj.find('.doubleBoxBody-tabBody-block .formExchange');
		//elem.find('input, select').val('');

		this.mainobj.find('.formExchange').find('select, input').bind('keyup change', function() {
			smallCalculator.calculate();
		});
	},

	reinit: function() {
		this.type = this.mainobj.find('.doubleBoxBody-tabTitle').find('.current').index();
		var elem = this.mainobj.find('.doubleBoxBody-tabBody-block').eq(this.type);
		this.table = elem.find('.tableExchange').eq(0);
		elem = elem.find('.formExchange').eq(0);
		this.input = elem.find('input').eq(0);
		this.select = elem.find('select').eq(0);
		this.calculate();
	},

	calculate: function() {
		var select = this.select.find(':selected').val();

		var regFloatNumber = new RegExp("^[0-9]+$", 'i');
		this.sum = regFloatNumber.test(this.input.val()) ? parseFloat(this.input.val()) : 0;

		if (this.type == 0) {
			this.setPriceToSell(select, 'byr');
			this.setPriceToSell(select, 'usd');
			this.setPriceToSell(select, 'eur');
			this.setPriceToSell(select, 'rur');
			this.setPriceToSell(select, 'gbp');
			this.setPriceToSell(select, 'uah');
			this.setPriceToSell(select, 'chf');
		}

		if (this.type == 1) {
			this.setPriceToBuy('byr', select);
			this.setPriceToBuy('usd', select);
			this.setPriceToBuy('eur', select);
			this.setPriceToBuy('rur', select);
			this.setPriceToBuy('gbp', select);
			this.setPriceToBuy('uah', select);
			this.setPriceToBuy('chf', select);
		}
	},

	setPriceToSell: function(from, to) {
		var result = -1;
		var i;

		if (from != to) {
			for (i = 0; i <= 7; i++)
				if (this.conversion[i].from == from && this.conversion[i].to == to) {
					result = this.sum * this.conversion[i].sum;
					break;
				}

			if (result == -1) {
				for (i = 0; i <= 6; i++)
					if (this.courses[i].name == from) {
						result = this.sum * this.courses[i].buy;
						break;
					}

				if (result != -1)
					for (i = 0; i <= 6; i++)
						if (this.courses[i].name == to) {
							result = result / this.courses[i].sell;
							break;
						}
			}
		}

		this.setPrice(result, to);
	},

	setPriceToBuy: function(from, to) {
		var result = -1;
		var i;

		if (from != to) {
			for (i = 0; i <= 7; i++) {
				if (this.conversion[i].from == from && this.conversion[i].to == to) {
					result = this.sum / this.conversion[i].sum;
					break;
				}
			}

			if (result == -1) {
				for (i = 0; i <= 6; i++)
					if (this.courses[i].name == to) {
						result = this.sum * this.courses[i].sell;
						break;
					}

				for (i = 0; i <= 6; i++)
					if (this.courses[i].name == from) {
						result = result / this.courses[i].buy;
						break;
					}
			}
		}

		this.setPrice(result, from);
	},

	setPrice: function (price, currency) {
		var price_str = number_format(price.toFixed(2), 2, ',', ' ');
		if (price_str == 0) price_str = '-';
		this.table.find('tbody').find('tr.'+currency).css('display', price == -1 ? 'none' : '').find('td:eq(1)').text(price_str);
	}
}

jQuery.fn.checkInputNumber = function(options) {
	options = jQuery.extend({
		min: 1,
		max: 12,
		text: '',
		comments: '',
		errors: {
			min: 'Минимальное значение - {min}',
			max: 'Максимальное значение - {max}',
			notnumber: 'Введенная строка должна быть числом',
			def: 'Ошибка ввода'
		}
	}, options);

	return this.each(function(){
		var str = '';
		if (options.text) str += '<span>'+options.text+'</span>';
		if (options.comments) str += '<p class="calcBlockParam-info">'+options.comments+'</p>';

		jQuery(this).after(str).data('options', options);

		function checkInputNumber_errorTemplate(input, template, options) {
			var str = '';
			if (template) {
				var insertTemplateBegin = '<a class="activLinkLine" href="" onclick="return false;">';
				var insertTemplateEnd = '</a>';

				var minStr = number_format(options.min, 0, ',', ' ');
				var maxStr = number_format(options.max, 0, ',', ' ');

				str = template.replace(/{min}/i, insertTemplateBegin + minStr + insertTemplateEnd);
				str = str.replace(/{max}/i, insertTemplateBegin + maxStr + insertTemplateEnd);

				if (str) {
					input.parent()
					.append('<p class="calcBlockParam-error">'+str+'</p>')
					.find('.calcBlockParam-error a')
					.mousedown(function(){
						jQuery(this).parent().parent().find('input').val(jQuery(this).text()).keyup();return false;
					});
				}
			}
			return str;
		}

		jQuery(this).bind('keypress', {options : options}, function(event){
			var str = String.fromCharCode(event.charCode);
			var r = new RegExp("^[0-9]+$");
			if (event.charCode == 0 || r.test(str)) return true;
				else return false;
		});

		jQuery(this).bind('keyup click', {options : options}, function(event){
			var errorType = 0;
			var value = jQuery(this).val();
			if (value) value = value.toString().split(' ').join('').replace(/[^0-9]+/gi, '');
			var r = new RegExp("^[\-]{0,1}[1-9]{0,1}[0-9]+$");

			if (value && !r.test(value)) errorType = 1;

			if (!value) value = 0;
				else jQuery(this).val(number_format(value, 0, ',', ' '));

			if (!errorType) {
				value = parseInt(value);
				if (event.data.options.min != 'none' && value < Math.floor(event.data.options.min)) errorType = 2;
				if (event.data.options.max != 'none' && value > Math.floor(event.data.options.max)) errorType = 3;
			}

			jQuery(this).parent().parent().find('.calcBlockParam-error').remove();
			if (errorType) {
				var errorTemplate = event.data.options.errors.def;

				if (errorType == 1) {
					// введенная строка не число
					if (event.data.options.errors.notnumber) errorTemplate = event.data.options.errors.notnumber;
				}
				else if (errorType == 2) {
					// введено число меньше options.min
					if (event.data.options.errors.min) errorTemplate = event.data.options.errors.min;
				}
				else if (errorType == 3) {
					// введено число больше options.max
					if (event.data.options.errors.max) errorTemplate = event.data.options.errors.max;
				}
				jQuery(this).parent().addClass('error');
				checkInputNumber_errorTemplate(jQuery(this), errorTemplate, event.data.options);
			}
			else {
				jQuery(this).parent().removeClass('error');
			}

		});
	});
};

var calc1 = {
	objDuration: null,
	objSum: null,
	objFamilySum: null,
	objFamilyCount: null,
	objCalculateBlock: null,
	objCalculateTable: null,
	percent: 0,
	payPerMonth: 0,
	monthSum: 0,
	sumMin: 0,
	sumMax: 0,
	sumSponsor: 0,
	sumContract: 0,

	init: function() {
		this.objDuration = $('#calc_duration');
		this.objSum = $('#calc_sum');
		this.objFamilySum = $('#calc_familysum');
		this.objFamilyCount = $('#calc_familycount');
		this.objCalculateBlock = $('#calculate_block');
		this.objCalculateTable = $('#calculate_table');

		this.objCalculateBlock.hide();

		$('#calc_duration, #calc_sum, #calc_familycount').keyup(function(){
			var sum = parseInt(calc1.objSum.val().toString().split(' ').join(''));
			var duration = parseInt(calc1.objDuration.val());
			var percent = parseInt(calc1.percent) / 100;
			var payPerMonth = parseInt(calc1.payPerMonth);
			var monthSum = parseInt(calc1.monthSum);
			var familycount = parseInt(calc1.objFamilyCount.val());

			var familysum = ((sum * (12 + duration * percent)) / (12 * duration)) + payPerMonth + (monthSum * familycount);

			if (sum == 0) familysum = 0;

			if (sum < calc1.sumMin) {
				familysum = 0;
			}
			else if (sum > calc1.sumMax) {
				familysum = 0;
			}

			familysum = number_format(familysum, 0, ',', ' ');
			calc1.objFamilySum.val(familysum).parent().removeClass('error');

			calc1.calculate();
		});

		$('#calc_familysum').bind('keyup', function(){
			var familysum = parseInt(calc1.objFamilySum.val().toString().split(' ').join(''));
			var duration = parseInt(calc1.objDuration.val());
			var percent = parseInt(calc1.percent) / 100;
			var payPerMonth = parseInt(calc1.payPerMonth);
			var monthSum = parseInt(calc1.monthSum);
			var familycount = parseInt(calc1.objFamilyCount.val());

			var sum = (12 * duration * ((familysum - monthSum * familycount) - payPerMonth)) / (12 + duration * percent)

			if (sum < calc1.sumMin) sum = 0;
			if (sum > calc1.sumMax) sum = calc1.sumMax;

			sum = number_format(sum, 0, ',', ' ');
			calc1.objSum.val(sum).click();

			calc1.calculate();
		});

		$('#calculate_popup').colorbox({
			width:"70%",
			inline:true,
			href:"#calculate_table",
			previous: "назад",
			next: "вперёд",
			close: "",
			maxHeight: '90%'
		});
	},

	calculate: function(obj) {
		if (this.objSum.parent().hasClass('error') ||
			this.objFamilySum.parent().hasClass('error') ||
			this.objDuration.parent().hasClass('error') ||
			this.objFamilyCount.parent().hasClass('error')) { this.objCalculateBlock.hide(); return false; };

		var sum = parseInt(this.objSum.val().toString().split(' ').join(''));
		var familysum = parseInt(this.objFamilySum.val().toString().split(' ').join(''));
		var duration = parseInt(this.objDuration.val());
		var percent = parseInt(this.percent) / 100;
		var payPerMonth = parseInt(this.payPerMonth);
		var monthSum = parseInt(this.monthSum);
		var familycount = parseInt(this.objFamilyCount.val());

		if (duration > 0 && sum > 0 && familysum > 0 && familycount > 0) {
			var month = 0;
			var calculation = new Array();

			// долг на начало выплат
			var balance = sum;

			// всего выплачено
			var pay_all = 0;

			// всего выплачено по ОД
			var pay_all_od = 0;

			// платеж по ОД
			var payment = null;

			// платеж по %
			var payment_percent = null;

			// платеж по комиссиям
			var payment_ext = null;

			// ежемесячный платеж
			var payment_monthly = null;

			while (month < duration) {
				// следующий период
				month++;

				// остаток долга на начало периода
				balance = sum - pay_all_od;

				// платеж по ОД
				payment = 0;
				if (month <= duration) payment = (sum / duration);

				// платеж по %
				payment_percent = (balance * percent / 12);

				// платеж по комиссиям
				payment_ext = 0;
				if (month <= duration) payment_ext = (payPerMonth);

				// ежемесячный платеж
				payment_monthly = (payment + payment_percent + payment_ext);

				// всего выплачено
				pay_all = (pay_all + payment_monthly);

				// всего выплачено по ОД
				pay_all_od = (pay_all_od + payment);

				// запоминаем строку периода
				calculation[month] = {
					'payment' : payment,
					'payment_percent' : payment_percent,
					'payment_ext' : payment_ext,
					'payment_monthly' : payment_monthly,
					'balance' : balance
				};
			}

			// сумма первоначального платежа по кредиту
			var str = '';
			str = number_format(calculation[1]['payment_monthly'], 0, ',', ' ');
			$('#first_payment').text(str);

			// среднемесячный платеж
			str = number_format(pay_all / duration, 0, ',', ' ');
			$('#sum_average').text(str);

			// Итоговая сумма платежей по кредиту
			str = number_format(pay_all, 0, ',', ' ');
			$('#sum_all').text(str);

			// в том числе проценты и комиссии (если имеются)
			str = number_format(pay_all - sum, 0, ',', ' ');
			$('#sum_ext').text(str);

			// разовая комиссия за оформление договоров поручительства
			str = Math.round(sum / calc1.sumSponsor) * calc1.sumContract;
			str = number_format(str, 0, ',', ' ');
			$('#comission_contract').text(str);

			// разовая комиссия при выдаче наличными через кассу банка
			str = number_format(sum * calc1.percentCash, 0, ',', ' ');
			$('#comission_cash').text(str);

			// разовая комиссия при перечислении на счет продавца
			str = number_format(sum * calc1.percentTransfer, 0, ',', ' ');
			$('#comission_transfer').text(str);

			var tbody = this.objCalculateTable.find('table tbody').empty();

			for (var i = 1; i <= duration; i++) {
				str = '<tr>';

				str += '<td class="td0">' + i + '</td>'
				str += '<td class="td1">' + number_format(calculation[i].payment, 0, ',', ' ') + '</td>'
				str += '<td class="td2">' + number_format(calculation[i].payment_percent, 0, ',', ' ') + '</td>'
				str += '<td class="td3">' + number_format(calculation[i].payment_ext, 0, ',', ' ') + '</td>'
				str += '<td class="td4">' + number_format(calculation[i].payment_monthly, 0, ',', ' ') + '</td>'
				str += '<td class="td5">' + number_format(calculation[i].balance, 0, ',', ' ') + '</td>'

				str += '</tr>';

				tbody.append(str);
			}

			this.objCalculateBlock.show();

		}
	}
}

var calc2 = {
	secondBlock: null,
	objPrice: null,
	objAgeType: null,
	objOwnSum: null,
	objDuration: null,
	objPercent: null,
	objSum: null,
	objFamilySum: null,
	objFamilyCount: null,
	objCalculateBlock: null,
	objCalculateTable: null,
	ages: new Array(),
	price: 0,
	ageType: 0,
	ownSum: 0,
	duration: 0,
	sum: 0,
	familysum: 0,
	familycount: 0,
	percent: 0,
	ownSumComment: '',
	paypermonth: 0,
	monthsum: 0,
	hasErrors: true,
	sumSponsor: 0,
	sumContract: 0,
	percentCash: 0,
	percentTransfer: 0,

	init: function() {
		this.secondBlock = $('#calcSecondBlock');
		this.objPrice = $('#calc_price');
		this.objAgeType = $('#calc_agetype');
		this.objOwnSum = $('#calc_ownsum');
		this.objDuration = $('#calc_duration');
		this.objPercent = $('#calc_percent');
		this.objSum = $('#calc_sum');
		this.objFamilySum = $('#calc_familysum');
		this.objFamilyCount = $('#calc_familycount');
		this.objCalculateBlock = $('#calculate_block');
		this.objCalculateTable = $('#calculate_table');

		this.objCalculateBlock.hide();

		this.objAgeType.val();

		this.objAgeType.bind('change', function(){
			calc2.calculate();
		});

		this.objPrice.bind('keyup', function(){
			calc2.calculate();
		});

		this.objOwnSum.bind('keyup', function(){
			calc2.read();
			var temp = calc2.getCurAgesAndMaxSum();
			var sum = temp.sum;

			var maxSum = calc2.price * sum/100;
			opt = calc2.objSum.data('options');
			opt.max = maxSum;
			calc2.objSum.data('options', opt).keyup();
			calc2.calculateSum();
		});

		this.objDuration.bind('keyup', function(){
			calc2.calculateSum();
		});

		this.objSum.bind('keyup', function(){
			var familysum = 0;
			if (!$(this).parent().hasClass('error')) {
				calc2.read();
				familysum = Math.round((calc2.sum * (12 + calc2.duration * calc2.percent / 100)) / (12 * calc2.duration) + calc2.paypermonth + (calc2.monthsum * calc2.familycount));
			}
			calc2.objFamilySum.val(familysum).keyup();
			calc2.calculateTable();
		});

		this.objFamilyCount.bind('keyup', function(){
			calc2.objSum.keyup();
		});

		$('#calculate_popup').colorbox({
			width:"70%",
			inline:true,
			href:"#calculate_table",
			previous: "назад",
			next: "вперёд",
			close: "",
			maxHeight: '90%'
		});
	},

	read: function () {
		this.price = parseInt(this.objPrice.val().toString().split(' ').join(''));
		this.ageType = parseInt(this.objAgeType.val());
		this.ownSum = parseInt(this.objOwnSum.val().toString().split(' ').join(''));
		this.duration = parseInt(this.objDuration.val());
		this.sum = parseInt(this.objSum.val().toString().split(' ').join(''));
		this.familysum = parseInt(this.objFamilySum.val().toString().split(' ').join(''));
		this.familycount = parseInt(this.objFamilyCount.val().toString().split(' ').join(''));

		var i;
		for (i = 0; i < this.ages.length; i++)
			if (this.ages[i].id == this.ageType) break;

		this.percent = this.getPercent();
		this.hasErrors = this.getErrors();
	},

	getErrors: function() {
		this.hasErrors = true;
		if (!this.objPrice.parent().hasClass('error') &&
			!this.objAgeType.parent().hasClass('error') &&
			!this.objOwnSum.parent().hasClass('error') &&
			!this.objDuration.parent().hasClass('error') ) this.hasErrors = false;
	},

	addAge: function(obj) {
		var def = {
			id: 0,
			age: 0,
			term: 0,
			sum1: 0,
			sum2: 0,
			sum3: 0,
			percent1: 0,
			percent2: 0,
			percent3: 0
		};

		def = $.extend(def, obj);

		var s;
		var p;
		if (def.sum2 < def.sum1) {
			s = def.sum1;
			p = def.percent1;
			def.sum1 = def.sum2;
			def.percent1 = def.percent2;
			def.sum2 = s;
			def.percent2 = p;
		}

		if (def.sum3 < def.sum1) {
			s = def.sum1;
			p = def.percent1;
			def.sum1 = def.sum3;
			def.percent1 = def.percent3;
			def.sum3 = s;
			def.percent3 = p;
		}

		if (def.sum3 < def.sum2) {
			s = def.sum2;
			p = def.percent2;
			def.sum2 = def.sum3;
			def.percent2 = def.percent3;
			def.sum3 = s;
			def.percent3 = p;
		}

		this.ages[this.ages.length] = def;
	},

	setOwnSumComment: function(text) {
		if (text != undefined) {
			this.read();

			this.ownSumComment = text;
			var temp = this.getCurAgesAndMaxSum();
			var sum = 100 - temp.sum;
			var str = this.ownSumComment.replace(/{percent}/gi, sum + '%');

			if (str) {
				if (!this.objOwnSum.parent().find('.calcBlockParam-info').length)
					this.objOwnSum.parent().append('<p class="calcBlockParam-info"></p>');

				this.objOwnSum.parent().find('.calcBlockParam-info').text(str);
			}
		}
	},

	getPercent: function() {
		var i;
		for (i = 0; i < this.ages.length; i++)
			if (this.ages[i].id == this.ageType) break;

		var percent = 0;
		var ownSumPercent = this.ownSum / this.price * 100;
		var sumPercent = 100 - ownSumPercent;

		if (sumPercent <= this.ages[i].sum1) percent = this.ages[i].percent1;
			else if (sumPercent <= this.ages[i].sum2) percent = this.ages[i].percent2;
				else if (sumPercent <= this.ages[i].sum3) percent = this.ages[i].percent3;

		return percent;
	},

	calculateSum: function() {
		this.read();

		var percent = this.getPercent();

		this.objPercent.text(percent + '%');

		if (percent == 0) this.objPercent.parent().parent().parent().hide();
			else this.objPercent.parent().parent().parent().show();

		this.getErrors();

		var sum = 0;
		if (!this.hasErrors ) {
			sum = this.price - this.ownSum;
			if (sum < 0) sum = 0;
		}
		this.objSum.val(sum).keyup();

		this.calculateTable();
	},

	getCurAgesAndMaxSum: function() {
		var i;
		var sum;
		for (i = 0; i < this.ages.length; i++)
			if (this.ages[i].id == this.ageType) break;

		sum = this.ages[i].sum1;

		if (this.ages[i].sum2 > sum && this.ages[i].sum2 > this.ages[i].sum3) {
			sum = this.ages[i].sum2;
		}
		else if (this.ages[i].sum3 > sum && this.ages[i].sum3 > this.ages[i].sum2) {
			sum = this.ages[i].sum3;
		}

		return {sum: sum, i: i}
	},

	calculate: function() {
		this.read();

		var temp = this.getCurAgesAndMaxSum();
		var sum = temp.sum;
		var curAge = this.ages[temp.i];

		var percent = this.getPercent();
		if (percent == 0) this.objPercent.parent().parent().parent().hide();
			else this.objPercent.parent().parent().parent().show();

		sum = 100 - sum;

		var minOwnSum = this.price * (sum/100);
		var opt = this.objOwnSum.data('options');
		opt.min = minOwnSum;
		this.objOwnSum.data('options', opt).keyup();

		opt = this.objDuration.data('options');
		opt.max = curAge.term;
		this.objDuration.data('options', opt).keyup();

		var maxSum = this.price * ((100-sum)/100);
		opt = this.objSum.data('options');
		opt.max = maxSum;
		this.objSum.data('options', opt).keyup();

		var str = this.ownSumComment.replace(/{percent}/gi, sum + '%');

		if (str) {
			if (!this.objOwnSum.parent().find('.calcBlockParam-info').length)
				this.objOwnSum.parent().append('<p class="calcBlockParam-info"></p>');

			this.objOwnSum.parent().find('.calcBlockParam-info').text(str);
		}

		this.calculateSum();
	},

	calculateTable: function() {
		this.read();

		if (this.sum > 0 && this.price > 0 && !this.hasErrors) {
			this.secondBlock.show();
			if (!this.objSum.parent().hasClass('error')) this.objCalculateBlock.show();
				else { this.objCalculateBlock.hide(); return; }
		}
		else {
			this.secondBlock.hide();
			this.objCalculateBlock.hide();
			return;
		}

		var sum = this.sum;
		var percent = this.percent;
		var duration = this.duration;
		var month = 0;
		var calculation = new Array();

		// долг на начало выплат
		var balance = sum;

		// всего выплачено
		var pay_all = 0;

		// всего выплачено по ОД
		var pay_all_od = 0;

		// платеж по ОД
		var payment = null;

		// платеж по %
		var payment_percent = null;

		// платеж по комиссиям
		var payment_ext = null;

		// ежемесячный платеж
		var payment_monthly = null;

		while (month < duration) {
			// следующий период
			month++;

			// остаток долга на начало периода
			balance = sum - pay_all_od;

			// платеж по ОД
			payment = 0;
			if (month <= duration) payment = (sum / duration);

			// платеж по %
			payment_percent = (balance * (percent/100) / 12);

			// платеж по комиссиям
			payment_ext = 0;
			if (month <= duration) payment_ext = this.paypermonth;

			// ежемесячный платеж
			payment_monthly = (payment + payment_percent + payment_ext);

			// всего выплачено
			pay_all = (pay_all + payment_monthly);

			// всего выплачено по ОД
			pay_all_od = (pay_all_od + payment);

			// запоминаем строку периода
			calculation[month] = {
				'payment' : payment,
				'payment_percent' : payment_percent,
				'payment_ext' : payment_ext,
				'payment_monthly' : payment_monthly,
				'balance' : balance
			};
		}

		// сумма первоначального платежа по кредиту
		var str = '';
		str = number_format(calculation[1]['payment_monthly'], 0, ',', ' ');
		$('#first_payment').text(str);

		// среднемесячный платеж
		str = number_format(pay_all / duration, 0, ',', ' ');
		$('#sum_average').text(str);

		// Итоговая сумма платежей по кредиту
		str = number_format(pay_all, 0, ',', ' ');
		$('#sum_all').text(str);

		// в том числе проценты и комиссии (если имеются)
		str = number_format(pay_all - sum, 0, ',', ' ');
		$('#sum_ext').text(str);

		// разовая комиссия за оформление договоров поручительства
		str = Math.round(sum / this.sumSponsor) * this.sumContract;
		if (str > 0) {
			str = number_format(str, 0, ',', ' ');
			$('#comission_contract').text(str).parent().parent().show();
		}
		else $('#comission_contract').text(str).parent().parent().hide();

		// разовая комиссия при выдаче наличными через кассу банка
		str = sum * this.percentCash;
		if (str > 0) {
			str = number_format(str, 0, ',', ' ');
			$('#comission_cash').text(str).parent().parent().show();
		}
		else $('#comission_cash').text(str).parent().parent().hide();

		// разовая комиссия при перечислении на счет продавца
		str = sum * this.percentTransfer;
		if (str > 0) {
			str = number_format(str, 0, ',', ' ');
			$('#comission_transfer').text(str).parent().parent().show();
		}
		else $('#comission_transfer').text(str).parent().parent().hide();

		var tbody = this.objCalculateTable.find('table tbody').empty();

		for (var i = 1; i <= duration; i++) {
			str = '<tr>';

			str += '<td class="td0">' + i + '</td>'
			str += '<td class="td1">' + number_format(calculation[i].payment, 0, ',', ' ') + '</td>'
			str += '<td class="td2">' + number_format(calculation[i].payment_percent, 0, ',', ' ') + '</td>'
			str += '<td class="td3">' + number_format(calculation[i].payment_ext, 0, ',', ' ') + '</td>'
			str += '<td class="td4">' + number_format(calculation[i].payment_monthly, 0, ',', ' ') + '</td>'
			str += '<td class="td5">' + number_format(calculation[i].balance, 0, ',', ' ') + '</td>'

			str += '</tr>';

			tbody.append(str);
		}

		this.objCalculateBlock.show();

	}
}

var calc3 = {
	secondBlock: null,
	objPrice: null,
	objOwnSum: null,
	objDuration: null,
	objPercent: null,
	objSum: null,
	objFamilySum: null,
	objFamilyCount: null,
	objCalculateBlock: null,
	objCalculateTable: null,
	term: new Array(),
	price: 0,
	ownSum: 0,
	duration: 0,
	sum: 0,
	familysum: 0,
	familycount: 0,
	percent: 0,
	ownSumComment: '',
	paypermonth: 0,
	monthsum: 0,
	hasErrors: true,
	sumSponsor: 0,
	sumContract: 0,
	percentCash: 0,
	percentTransfer: 0,

	init: function() {
		this.secondBlock = $('#calcSecondBlock');
		this.objPrice = $('#calc_price');
		this.objOwnSum = $('#calc_ownsum');
		this.objDuration = $('#calc_duration');
		this.objPercent = $('#calc_percent');
		this.objSum = $('#calc_sum');
		this.objFamilySum = $('#calc_familysum');
		this.objFamilyCount = $('#calc_familycount');
		this.objCalculateBlock = $('#calculate_block');
		this.objCalculateTable = $('#calculate_table');

		this.objCalculateBlock.hide();

		this.objPrice.bind('keyup', function(){
			calc3.calculate();
		});

		this.objOwnSum.bind('keyup', function(){
			calc3.read();
			var temp = calc3.getCurAgesAndMaxSum();
			var sum = temp.sum;

			var maxSum = calc3.price * sum/100;
			opt = calc3.objSum.data('options');
			opt.max = maxSum;
			calc3.objSum.data('options', opt).keyup();
			calc3.calculateSum();
		});

		this.objDuration.bind('keyup', function(){
			calc3.calculateSum();
		});

		this.objSum.bind('keyup', function(){
			var familysum = 0;
			if (!$(this).parent().hasClass('error')) {
				calc3.read();
				familysum = Math.round((calc3.sum * (12 + calc3.duration * calc3.percent / 100)) / (12 * calc3.duration) + calc3.paypermonth + (calc3.monthsum * calc3.familycount));
			}
			calc3.objFamilySum.val(familysum).keyup();
			calc3.calculateTable();
		});

		this.objFamilyCount.bind('keyup', function(){
			calc3.objSum.keyup();
		});

		$('#calculate_popup').colorbox({
			width:"70%",
			inline:true,
			href:"#calculate_table",
			previous: "назад",
			next: "вперёд",
			close: "",
			maxHeight: '90%'
		});
	},

	read: function () {
		this.price = parseInt(this.objPrice.val().toString().split(' ').join(''));
		this.ownSum = parseInt(this.objOwnSum.val().toString().split(' ').join(''));
		this.duration = parseInt(this.objDuration.val());
		this.sum = parseInt(this.objSum.val().toString().split(' ').join(''));
		this.familysum = parseInt(this.objFamilySum.val().toString().split(' ').join(''));
		this.familycount = parseInt(this.objFamilyCount.val().toString().split(' ').join(''));

		this.percent = this.getPercent();
		this.hasErrors = this.getErrors();
	},

	getErrors: function() {
		this.hasErrors = true;
		if (!this.objPrice.parent().hasClass('error') &&
			!this.objOwnSum.parent().hasClass('error') &&
			!this.objDuration.parent().hasClass('error') ) this.hasErrors = false;
	},

	addTerm: function(obj) {
		var def = {
			id: 0,
			term: 0,
			sum1: 0,
			sum2: 0,
			sum3: 0,
			percent1: 0,
			percent2: 0,
			percent3: 0
		};

		def = $.extend(def, obj);

		var s;
		var p;
		if (def.sum2 < def.sum1) {
			s = def.sum1;
			p = def.percent1;
			def.sum1 = def.sum2;
			def.percent1 = def.percent2;
			def.sum2 = s;
			def.percent2 = p;
		}

		if (def.sum3 < def.sum1) {
			s = def.sum1;
			p = def.percent1;
			def.sum1 = def.sum3;
			def.percent1 = def.percent3;
			def.sum3 = s;
			def.percent3 = p;
		}

		if (def.sum3 < def.sum2) {
			s = def.sum2;
			p = def.percent2;
			def.sum2 = def.sum3;
			def.percent2 = def.percent3;
			def.sum3 = s;
			def.percent3 = p;
		}

		this.term = def;
	},

	setOwnSumComment: function(text) {
		if (text != undefined) {
			this.read();

			this.ownSumComment = text;
			var temp = this.getCurAgesAndMaxSum();
			var sum = 100 - temp.sum;
			var str = this.ownSumComment.replace(/{percent}/gi, sum + '%');

			if (str) {
				if (!this.objOwnSum.parent().find('.calcBlockParam-info').length)
					this.objOwnSum.parent().append('<p class="calcBlockParam-info"></p>');

				this.objOwnSum.parent().find('.calcBlockParam-info').text(str);
			}
		}
	},

	getPercent: function() {
		var percent = 0;
		var ownSumPercent = this.ownSum / this.price * 100;
		var sumPercent = 100 - ownSumPercent;

		if (sumPercent <= this.term.sum1) percent = this.term.percent1;
			else if (sumPercent <= this.term.sum2) percent = this.term.percent2;
				else if (sumPercent <= this.term.sum3) percent = this.term.percent3;

		return percent;
	},

	calculateSum: function() {
		this.read();

		var percent = this.getPercent();

		this.objPercent.text(percent + '%');

		if (percent == 0) this.objPercent.parent().parent().parent().hide();
			else this.objPercent.parent().parent().parent().show();

		this.getErrors();

		var sum = 0;
		if (!this.hasErrors ) {
			sum = this.price - this.ownSum;
			if (sum < 0) sum = 0;
		}
		this.objSum.val(sum).keyup();

		this.calculateTable();
	},

	getCurAgesAndMaxSum: function() {
		var i;
		var sum;

		sum = this.term.sum1;

		if (this.term.sum2 > sum && this.term.sum2 > this.term.sum3) {
			sum = this.term.sum2;
		}
		else if (this.term.sum3 > sum && this.term.sum3 > this.term.sum2) {
			sum = this.term.sum3;
		}

		return {sum: sum, i: i}
	},

	calculate: function() {
		this.read();

		var temp = this.getCurAgesAndMaxSum();
		var sum = temp.sum;

		var percent = this.getPercent();
		if (percent == 0) this.objPercent.parent().parent().parent().hide();
			else this.objPercent.parent().parent().parent().show();

		sum = 100 - sum;

		var minOwnSum = this.price * (sum/100);
		var opt = this.objOwnSum.data('options');
		opt.min = minOwnSum;
		this.objOwnSum.data('options', opt).keyup();

		opt = this.objDuration.data('options');
		opt.max = this.term.term;
		this.objDuration.data('options', opt).keyup();

		var maxSum = this.price * ((100-sum)/100);
		opt = this.objSum.data('options');
		opt.max = maxSum;
		this.objSum.data('options', opt).keyup();

		var str = this.ownSumComment.replace(/{percent}/gi, sum + '%');

		if (str) {
			if (!this.objOwnSum.parent().find('.calcBlockParam-info').length)
				this.objOwnSum.parent().append('<p class="calcBlockParam-info"></p>');

			this.objOwnSum.parent().find('.calcBlockParam-info').text(str);
		}

		this.calculateSum();
	},

	calculateTable: function() {
		this.read();

		if (this.sum > 0 && this.price > 0 && !this.hasErrors) {
			this.secondBlock.show();
			if (!this.objSum.parent().hasClass('error')) this.objCalculateBlock.show();
				else { this.objCalculateBlock.hide(); return; }
		}
		else {
			this.secondBlock.hide();
			this.objCalculateBlock.hide();
			return;
		}

		var sum = this.sum;
		var percent = this.percent;
		var duration = this.duration;
		var month = 0;
		var calculation = new Array();

		// долг на начало выплат
		var balance = sum;

		// всего выплачено
		var pay_all = 0;

		// всего выплачено по ОД
		var pay_all_od = 0;

		// платеж по ОД
		var payment = null;

		// платеж по %
		var payment_percent = null;

		// платеж по комиссиям
		var payment_ext = null;

		// ежемесячный платеж
		var payment_monthly = null;

		while (month < duration) {
			// следующий период
			month++;

			// остаток долга на начало периода
			balance = sum - pay_all_od;

			// платеж по ОД
			payment = 0;
			if (month <= duration) payment = (sum / duration);

			// платеж по %
			payment_percent = (balance * (percent/100) / 12);

			// платеж по комиссиям
			payment_ext = 0;
			if (month <= duration) payment_ext = this.paypermonth;

			// ежемесячный платеж
			payment_monthly = (payment + payment_percent + payment_ext);

			// всего выплачено
			pay_all = (pay_all + payment_monthly);

			// всего выплачено по ОД
			pay_all_od = (pay_all_od + payment);

			// запоминаем строку периода
			calculation[month] = {
				'payment' : payment,
				'payment_percent' : payment_percent,
				'payment_ext' : payment_ext,
				'payment_monthly' : payment_monthly,
				'balance' : balance
			};
		}

		// сумма первоначального платежа по кредиту
		var str = '';
		str = number_format(calculation[1]['payment_monthly'], 0, ',', ' ');
		$('#first_payment').text(str);

		// среднемесячный платеж
		str = number_format(pay_all / duration, 0, ',', ' ');
		$('#sum_average').text(str);

		// Итоговая сумма платежей по кредиту
		str = number_format(pay_all, 0, ',', ' ');
		$('#sum_all').text(str);

		// в том числе проценты и комиссии (если имеются)
		str = number_format(pay_all - sum, 0, ',', ' ');
		$('#sum_ext').text(str);

		// разовая комиссия за оформление договоров поручительства
		str = Math.round(sum / this.sumSponsor) * this.sumContract;
		if (str > 0) {
			str = number_format(str, 0, ',', ' ');
			$('#comission_contract').text(str).parent().parent().show();
		}
		else $('#comission_contract').text(str).parent().parent().hide();

		// разовая комиссия при выдаче наличными через кассу банка
		str = sum * this.percentCash;
		if (str > 0) {
			str = number_format(str, 0, ',', ' ');
			$('#comission_cash').text(str).parent().parent().show();
		}
		else $('#comission_cash').text(str).parent().parent().hide();

		// разовая комиссия при перечислении на счет продавца
		str = sum * this.percentTransfer;
		if (str > 0) {
			str = number_format(str, 0, ',', ' ');
			$('#comission_transfer').text(str).parent().parent().show();
		}
		else $('#comission_transfer').text(str).parent().parent().hide();

		var tbody = this.objCalculateTable.find('table tbody').empty();

		for (var i = 1; i <= duration; i++) {
			str = '<tr>';

			str += '<td class="td0">' + i + '</td>'
			str += '<td class="td1">' + number_format(calculation[i].payment, 0, ',', ' ') + '</td>'
			str += '<td class="td2">' + number_format(calculation[i].payment_percent, 0, ',', ' ') + '</td>'
			str += '<td class="td3">' + number_format(calculation[i].payment_ext, 0, ',', ' ') + '</td>'
			str += '<td class="td4">' + number_format(calculation[i].payment_monthly, 0, ',', ' ') + '</td>'
			str += '<td class="td5">' + number_format(calculation[i].balance, 0, ',', ' ') + '</td>'

			str += '</tr>';

			tbody.append(str);
		}

		this.objCalculateBlock.show();

	}
};

var calc_depo = {
	objSum: null,
	objSumExt: null,
	objDuration: null,
	objCalculateBlock: null,
	objCalculateTable: null,
	items: new Array(),
	sum: 0,
	sumExt: 0,
	duration: 0,
	hasErrors: false,
	type: 0,
	percent_default: 0,

	init: function(obj) {
		var def = {
			type: 1,
			percent_default: 0
		};

		def = $.extend(def, obj);

		this.type = obj.type;
		this.percent_default = obj.percent_default;

		this.objSum = $('#calc_sum');
		this.objSumExt = $('#calc_sumext');
		this.objDuration = $('#calc_duration');
		this.objCalculateBlock = $('#calculate_block');
		this.objCalculateTable = $('#calculate_table');

		this.objCalculateBlock.hide();

		this.objSum.bind('keyup', function(){
			calc_depo.calculate();
		});

		this.objSumExt.bind('keyup', function(){
			calc_depo.calculate();
		});

		this.objDuration.bind('keyup', function(){
			calc_depo.calculate();
		});

		$('#calculate_popup').colorbox({
			width:"70%",
			inline:true,
			href:"#calculate_table",
			previous: "назад",
			next: "вперёд",
			close: "",
			maxHeight: '90%'
		});

	},

	addItem: function(obj) {
		var def = {
			condition: 0,
			percent: 0
		};

		def = $.extend(def, obj);

		this.items[this.items.length] = def;
	},

	read: function () {
		this.sum = parseInt(this.objSum.val().toString().split(' ').join(''));
		this.sumExt = parseInt(this.objSumExt.val().toString().split(' ').join(''));
		if (isNaN(this.sumExt)) this.sumExt = 0;
		this.duration = parseInt(this.objDuration.val());

		this.percent = 0;
		for (var i = 0; i<this.items.length; i++)
			if (this.duration <= this.items[i].condition) this.percent = this.items[i].percent;

		this.checkErrors();
	},

	checkErrors: function() {
		this.hasErrors = true;
		if (!this.objSum.parent().hasClass('error') &&
			!this.objSumExt.parent().hasClass('error') &&
			!this.objDuration.parent().hasClass('error') &&
			!isNaN(this.sum) &&
			!isNaN(this.sumExt) &&
			!isNaN(this.duration) &&
			this.sum > 0 &&
			this.duration > 0) this.hasErrors = false;

		return this.hasErrors;
	},

	getPercent: function(sum) {
		var percent;

		if (this.type == 1) {
			percent = this.percent;
		}
		else if (this.type == 2) {
			percent = this.percent_default;

			for (var i = 0; i<this.items.length; i++)
				if (sum <= this.items[i].condition) percent = this.items[i].percent;
		}

		return percent;
	},

	calculate: function() {
		this.read();

		if (!this.hasErrors) {

			var sumExt_all = 0;
			var period_end = 0;
			var sum_end = this.sum;
			var calculation = new Array();
			var percent = 0;
			var checkPercent = 0;
			var checkSumEnd = 0;

			for (var i = 1; i <= this.duration; i++) {

				// this.sum - первоначальная сумма вклада на начало периода
				// this.sumExt - сумма пополнения

				// сумма допвзносов
				sumExt_all += this.sumExt;

				// сумма депозита с учетом допвзносов на конец периода
				period_end = this.sum + sumExt_all;

				// процентная ставка для текущего месяца
				percent = this.getPercent(sum_end);

				// сумма депозита с капитализацией на конец периода
				checkSumEnd = (sum_end + this.sumExt) * (1 + (percent/100) / 12);

				if (this.type == 2) {
					checkPercent = this.getPercent(checkSumEnd);
					if (checkPercent != percent) {
						percent = checkPercent;
						checkSumEnd = (sum_end + this.sumExt) * (1 + (percent/100) / 12);
					}
				}

				sum_end = checkSumEnd;

				// запоминаем строку периода
				calculation[i] = {
					'sum' : this.sum,
					'sumExt' : this.sumExt,
					'period_end' : period_end,
					'sum_end' : sum_end,
					'percent' : percent
				};
			}

			// итого сумма возвращаемого депозита
			var str = '';
			str = number_format(calculation[this.duration]['sum_end'], 0, ',', ' ');
			$('#depo_result').text(str);

			// первоначальный взнос
			str = number_format(this.sum, 0, ',', ' ');
			$('#first_payment').text(str);

			// сумма дополнительных взносов
			str = number_format(sumExt_all, 0, ',', ' ');
			$('#sum_ext').text(str);

			// сумма выплаченных процентов
			str = number_format(calculation[this.duration]['sum_end'] - calculation[this.duration]['period_end'], 0, ',', ' ');
			$('#sum_percent_out').text(str);

			var tbody = this.objCalculateTable.find('table tbody').empty();

			for (i = 1; i <= this.duration; i++) {
				str = '<tr>';

				str += '<td class="td0">' + i + '</td>'
				str += '<td class="td1">' + number_format(calculation[i].sum, 0, ',', ' ') + '</td>'
				str += '<td class="td2">' + number_format(calculation[i].sumExt, 0, ',', ' ') + '</td>'
				str += '<td class="td3">' + number_format(calculation[i].period_end, 0, ',', ' ') + '</td>'
				str += '<td class="td4">' + number_format(calculation[i].sum_end, 0, ',', ' ') + '</td>'

				str += '</tr>';

				tbody.append(str);
			}

			this.objCalculateBlock.show();
		}
		else {
			this.objCalculateBlock.hide();
		}
	}
};

/* Carusel */
	/**
 * We use the initCallback callback
 * to assign functionality to the controls
 */
function mycarousel_initCallback(carousel) {
	jQuery('.jcarousel-control a').bind('click', function() {
		carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
		return false;
	});

	jQuery('#mycarousel-next').bind('click', function() {
		carousel.next();
		return false;
	});

	jQuery('#mycarousel-prev').bind('click', function() {
		carousel.prev();
		return false;
	});



	// Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};

function checkOnlineConsultant() {
	$.ajax({
		type: 'GET',
		url: '/scripts/check_online_consultant.php?id=88823',
		async: false,

		success: function(xmlObj) {
			if ($('status', xmlObj).length) {
				if ($('status', xmlObj).text() == 'online'){
					o=window.open;
					o('https://siteheart.com/webconsultation/88823?s=1', 'siteheart_sitewindow_88823', 'width=550,height=400,top=30,left=30,resizable=yes');
					return false;
				} else {
					var faq = $('faq', xmlObj).text();
					window.location = faq;
					return false;
				}
			}
		}
	 });
	 return false;
}

jQuery.fn.addtocopy = function(usercopytxt) {
	var options = {
		htmlcopytxt: '<br>More: <a href="'+window.location.href+'">'+window.location.href+'</a><br>', 
		minlen: 25, 
		addcopyfirst: false
	}
	$.extend(options, usercopytxt);
	var copy_sp = document.createElement('span');
	copy_sp.id = 'ctrlcopy';
	copy_sp.innerHTML = options.htmlcopytxt;
	return this.each(function(){
		$(this).mousedown(function(){
			$('#ctrlcopy').remove();
		});
		$(this).mouseup(function(){
			if(window.getSelection){	//good times
				var slcted=window.getSelection();
				var seltxt=slcted.toString();
				if(!seltxt||seltxt.length<options.minlen) return;
				var nslct = slcted.getRangeAt(0);
				seltxt = nslct.cloneRange();
				seltxt.collapse(options.addcopyfirst);
				seltxt.insertNode(copy_sp);
				if (!options.addcopyfirst) nslct.setEndAfter(copy_sp);
				slcted.removeAllRanges();
				slcted.addRange(nslct);
			} else if(document.selection){	//bad times
				var slcted = document.selection;
				var nslct=slcted.createRange();
				var seltxt=nslct.text;
				if (!seltxt||seltxt.length<options.minlen) return;
				seltxt=nslct.duplicate();
				seltxt.collapse(options.addcopyfirst);
				seltxt.pasteHTML(copy_sp.outerHTML);
				if (!options.addcopyfirst) {
					nslct.setEndPoint("EndToEnd",seltxt);
					nslct.select();
				}
			}
		});
	});
}

function changeCurs(curr) {
	$("#selcurr2 option").hide();
	if (curr == 'usd') {
		$("#selcurr2 option[value='byr']").show();
		$("#selcurr2 option[value='eur']").show();
		$("#selcurr2 option[value='rur']").show();
		$("#selcurr2 option[value='uah']").show();
	} else if (curr == 'eur') {
		$("#selcurr2 option[value='byr']").show();
		$("#selcurr2 option[value='usd']").show();
		$("#selcurr2 option[value='rur']").show();
	} else if (curr == 'rur') {
		$("#selcurr2 option[value='byr']").show();
		$("#selcurr2 option[value='usd']").show();
		$("#selcurr2 option[value='eur']").show();
	} else if (curr == 'uah') {
		$("#selcurr2 option[value='byr']").show();
		$("#selcurr2 option[value='usd']").show();
	} else if (curr == 'gbp') {
		$("#selcurr2 option[value='byr']").show();
	} else if (curr == 'chf') {
		$("#selcurr2 option[value='byr']").show();
	}
	if (!$("#selcurr2 option:selected:visible").length)
		$("#selcurr2 option[value='byr']").attr('selected', 'selected');
}
