Main = function() {
	this.init_DOM();
}

Main.prototype = {
	init_DOM: function() {
		this.jPage = $('#layout');
		this.jLink = $('#popup_link, .popup_link');
		this.jLinkBank = $('#popup_link_2');
		this.jFade = $('#fade');
		this.jPopup = $('#popup');
		this.jPhone = this.jPopup.find('.content .phone');
		this.jClose = $('#popup .close, .submit input, #fade');


		this.phoneCont = $('#phone_container');

		this.bOpened = false;

		this.init();
	},

	init: function() {
		if($.browser.msie && $.browser.version == 6) {
			this.jFade.prepend('<iframe></iframe>');
		}

		this.popup();
		this.ruble_fix();

		var oThis = this;

		$(window).resize(
			function(){
				if(oThis.bOpened){
					oThis.updateFontSize();
				}
			}
		);
	},

	popup: function() {
		var oThis = this;
		this.step = 50/20/100;

		this.jLink.click(function() {
			oThis.jFade.removeClass('not_display');
			oThis.jPopup.removeClass('not_display');

			oThis.bOpened = true;
			oThis.updateFontSize();

			if(!$.browser.msie) {
				oThis.jPopup.animate({opacity: 1}, function() {
					if(oThis.jFade[0].offsetHeight < oThis.jPopup[0].offsetHeight + oThis.jPopup[0].offsetTop) {
						oThis.jFade[0].style.height = oThis.jPopup[0].offsetHeight + oThis.jPopup[0].offsetTop + 'px';
					}
				});
				oThis.jFade.stop().animate({opacity: 0.5});
			}

			oThis.close();
		});
	},

	close: function() {
		var oThis = this;

		this.jClose.click(function() {
			if($.browser.msie) {
				oThis.jPopup.addClass('not_display');
				oThis.jFade.addClass('not_display');
			}
			else {
				oThis.jPopup.stop().animate({opacity: 0}, function() {
					$(this).addClass('not_display');
				});
				oThis.jFade.stop().animate({opacity: 0}, function() {
					$(this).addClass('not_display');
				});
			}
		});
	},

	updateFontSize : function(){
		var iFontSize = Math.round(this.jPage.width() / 35) + "px";
		this.jPhone.css("fontSize", iFontSize);

		if($.browser.mozilla){
			/*
				Firefox при изменении размера шрифта криво перерисовывает телефон
				(одни цифры ничанают наезжать на другие) - лечим передёргиванием.
			*/
			this.mozillaFix();
		}
	},

	mozillaFix : function(){
		var that = this;
		this.jPhone.hide();
		setTimeout(
			function(){
				that.jPhone.show();
			},
			1
		);
	},

	ruble_fix: function() {
		var jBody = $('body');

		if($.browser.safari) {
			jBody.addClass('safari');
		}
	},

	phoneChanger : function(){
		var oThat = this;

		this.phoneLinks.click(
			function(){
				var currentLink = $(this);
				if (currentLink.hasClass("pseudo_link")){
					oThat.phoneLinks.filter(".selected").removeClass("selected").addClass("pseudo_link");
					currentLink.addClass("selected").removeClass("pseudo_link")
					oThat.jLinkBank.text(currentLink.text()).append("<span class='icon'/>");
					oThat.phoneCont.text(currentLink.next("span").text());
					oThat.jClose.click();
				}
			}
		);
	}
}

function fixIeBug() {
	$(".pseudo_link, .with_hover, .close").hover(
		function(){
			$(this).addClass("hover");
		},
		function(){
			$(this).removeClass("hover");
		}
	);
}

var slidingBlocks = {

	/**
	 * Функция инициализации
	 */
	init : function(){
		var that = this;

		this.products_switcher = $(".product_chooser strong");

		this.products_groups = $("#bank_products .group");
		this.products_all = $("#bank_products .product");
		this.products = $("#bank_products .current_account_group .product");
		this.products_item = $(".item", this.products);
		this.products_content = $(".content", this.products);
		this.layoutWidth = $("#layout").width();
		this.currentOffset = 0;

		this.arrowRight = $("#bank_products .right_arrow");
		this.arrowLeft = $("#bank_products .left_arrow");

		this.productsWidth = 0;

		this.products_container = $("#bank_products .wrap_products");

		this.switcher = $("#bank_products .group .item");
		this.startPageX = 0;
		this.startOffsetLeft = 0;
		this.isBusy = false;
		this.isDrag = false;

		this.measurer();

		setTimeout(
			function(){
				that.products_container.animate(
					{
						left: 100
					}, 500,
					function(){
						that.products_container.css("left","100px");
					}
				);
			}, 300
		);

		jCommon.measurer.bind(
			function(){
				that.recalculate(that);
			}
		);
		this.attachEvents();
	},

	measurer : function(){
		el = $('<div id="measurer"></div>').css({
			height: '1em',
			left: 0,
			lineHeight: '1em',
			margin: 0,
			position: 'absolute',
			padding: 0,
			top: '-1em',
			visibility: 'hidden',
			width: '100%'
		}).appendTo('body');

		this.measurerHeight = el.height();
	},

	attachEvents : function(){
		var that = this;

		this.products_switcher.click(
			function(){
				if($(this).hasClass("pseudo_link")){
					that.products_switcher.parent().removeClass("selected");
					that.products_switcher.addClass("pseudo_link");
					$(this).removeClass("pseudo_link").parent().addClass("selected");

					that.newBlocks($(this).parent().attr("class"));
				}
			}
		);

		this.arrowRight.click(
			function(){
				if(!that.isDrag && !that.isBusy){
					that.isBusy = true;
					var current_prod = that.products_groups.filter(":visible").find(".selected");
					var current_number = current_prod.prevAll('.product').length + 1
					//var direction = $(this).parents(".product").hasClass("next") ? true : false;
					//that.container_width = that.products_container.width();
					/*if (direction){
						var pixelValue = ((current_number-1) == 0) ? "0" : "-" + (that.container_width * 10 * (current_number-1) - that.container_width * 1.85) / 100;
					}
					else{
						var pixelValue = ((current_number+1) == 0) ? "0" : "-" + (that.container_width * 10 * (current_number+1) - that.container_width * 1.85) / 100;
					}*/
					//that.products_container.css("left", pixelValue+"px");
					that.animateBlocks(current_number, true);
				}
				return false;
			}
		);

		this.arrowLeft.click(
			function(){
				if(!that.isDrag && !that.isBusy){
					that.isBusy = true;
					var current_prod = that.products_groups.filter(":visible").find(".selected");
					var current_number = current_prod.prevAll('.product').length + 1;
					that.animateBlocks(current_number, false);
				}
				return false;
			}
		);

		this.products_container.mousedown(
			function(e){
				that.startDrag(e);
			}
		);

		this.products_all.find("img").mousedown(
			function(e){
				e.preventDefault();
			}
		);

		this.products_all.find("img").mousemove(
			function(e){
				e.preventDefault();
			}
		);

		$(document).mouseup(
			function(){
				if(that.isDrag){
					that.isDrag = false;
				}
			}
		);

		$(document).mousemove(
			function(e){
				if(that.isDrag){
					var delta = e.pageX - that.startPageX;
					that.move(that.startOffsetLeft + delta);

					return false;
				}
			}
		);
	},

	recalculate : function(obj){
		obj.layoutWidth = $("#layout").width();
		obj.measurerHeight = el.height();
	},

	startDrag : function(e){
		if(!this.isDrag && e.which === 1){
			this.isDrag = true;
			this.startPageX = e.pageX;

			this.startOffsetLeft = parseInt(this.products_container.css("left"));

			var prod = this.products_container.find(".product:visible");
			var width = 0;
			prod.each(
				function(){
					width += $(this).width();
				}
			);
			this.productsWidth = width;

			return false;
		}
	},

	move : function(left){
		if(left <= 100 && (left >= -(this.productsWidth - this.layoutWidth + 50))){
			this.products_container.css("left", left);
		}
	},

	newBlocks : function(className){
		var that = this;

		var groupName = "." + className.split(/\s/)[0] + "_group";
		this.arrowLeft.hide();
		this.arrowRight.show();
		this.products.removeClass("next").removeClass("prev").addClass("selected");
		this.products_container.animate(
			{
				left: "100%"
			}, 500,
			function(){
				that.products_groups.hide();

				that.products.removeClass("selected").eq(0).addClass("selected");
				that.products.eq(1).addClass("next");
				that.products_groups.filter(groupName).show();
				that.products = $("#bank_products " + groupName + " .product");

				that.products_item = $(".item", that.products);
				that.products_content = $(".content", that.products);

				that.products_container.animate(
					{
						left: "100px"
					}, 500
				);
			}
		);
	},

	/**
	 *
	 * @param {} i Номер нажатого элемента
	 * @param {} dir Направление. True - next, false - previous
	 */
	animateBlocks : function(prod, dir){
		var that = this;

		if(dir){
			var offsetValue = (prod == 1) ? 42 * that.measurerHeight : Number(42 + (prod-1)*52) * that.measurerHeight;
		}
		else{
			var offsetValue = (prod == 2) ? -100 : Number(42 + (prod-3)*52) * that.measurerHeight;
		}

		if(dir){
			jTweener.addTween(
				that.products_container,
				{
					left: -Number(offsetValue),
					delay: 0,
					time: 1,
					onComplete: function(){
									if(that.products_groups.filter(":visible").find(".product")[prod + 1]){
										that.products_all.removeClass("selected");
										that.products_groups.filter(":visible").find(".product").eq(prod).addClass("selected");
										that.arrowLeft.show();
									}
									else{
										that.products_all.removeClass("selected");
										that.products_groups.filter(":visible").find(".product").eq(prod).addClass("selected");
										that.arrowRight.hide();
									}
									that.currentOffset = offsetValue;
									that.isBusy = false;
								}
				}
			);
		}
		else{
			jTweener.addTween(
				that.products_container,
				{
					left: -Number(offsetValue),
					delay: 0,
					time: 1,
					onComplete: function(){
									if(that.products_groups.filter(":visible").find(".product")[prod - 3]){
										that.products_all.removeClass("selected");
										that.products_groups.filter(":visible").find(".product").eq(prod - 2).addClass("selected");
										that.arrowRight.show();
									}
									else{
										that.products_all.removeClass("selected");
										that.products_groups.filter(":visible").find(".product").eq(prod - 2).addClass("selected");
										that.arrowLeft.hide();
									}
									that.currentOffset = offsetValue;
									that.isBusy = false;
								}
				}
			);
		}
	}

};

var slidingMenu = {

	/**
	 * Функция инициализации
	 */
	init : function(){
		var that = this;

		this.menuItemsLink = $("#side_navigation .pseudo_link");
		this.menuItems = $("#side_navigation .pseudo_link + .navigation");
		this.selectedItem = $("#side_navigation ul li.selected > .pseudo_link").parent().prevAll('li').find('.pseudo_link').length;;
		this.isBusy = false;

		this.attachEvents();
	},

	attachEvents : function(){
		var that = this;

		this.menuItemsLink.click(
			function(){
					var currentItem = $(this).parent().prevAll('li').find('.pseudo_link').length;
					if (currentItem == that.selectedItem){
						that.menuItems.eq(that.selectedItem).slideToggle(150);
					}
					else{
						that.menuItems.eq(that.selectedItem).slideUp(150);
						that.menuItems.eq(currentItem).slideDown(150);
						that.selectedItem = currentItem;
					}
			}
		);

	}

};

var cardSwitcher = {

	/**
	 * Функция инициализации
	 */
	init : function(){
		var that = this;

		this.cardLinks = $(".switcher li");
		this.cardLinksPseudo = $(".switcher li span");
		this.cardBlocks = $(".card_block");
		this.selectedItem = 0;

		this.attachEvents();
	},

	attachEvents : function(){
		var that = this;

		this.cardLinks.click(
			function(){
				var currentNum = $(this).prevAll("li").length;

				that.cardLinks.eq(that.selectedItem).removeClass("selected");
				that.cardLinksPseudo.eq(that.selectedItem).addClass("pseudo_link");

				that.cardLinks.eq(currentNum).addClass("selected");
				that.cardLinksPseudo.eq(currentNum).removeClass("pseudo_link");

				that.cardBlocks.eq(that.selectedItem).addClass("hidden");
				that.cardBlocks.eq(currentNum).removeClass("hidden");

				that.selectedItem = currentNum;
			}
		);

	}

}

function Blocks (link, blocks) {
	this.link = $(link);
	this.blocks = $(blocks);

	this.init_block();
}

Blocks.prototype = {
	init_block: function() {
		this.init();
	},

	init: function() {
		var that = this;

		this.link.click(
			function(e){
				e.stopPropagation();
				$(this).next().slideToggle(150);
			}
		);
	}

}
var slidingRight = {

	/**
	 * Функция инициализации
	 */
	init : function(){
		var that = this;

		this.banBlock = $("#sliding_banner");
		this.banWidth = this.banBlock.width() + 1.5*15;

		this.banBlock.animate(
			{
				right: - this.banWidth
			}, 2000,
			function(){
				that.banBlock.css("right","-14.5em");
			}
		);

	}

}

$(function() {
	new Main();
	if (jCommon.browser.msie && 6 >= parseInt(jCommon.browser.version)) {
		fixIeBug();
	}
	slidingBlocks.init();
	slidingMenu.init();
	cardSwitcher.init();
	slidingRight.init();

	$("form .pseudo label").click(
		function(){
			var par = $(this).parent().parent().removeClass("selected").removeClass("initial_selected");
			par.siblings().removeClass("selected").removeClass("initial_selected");
			$(this).parent().parent().toggleClass("selected");
		}
	);

	$("*:header[.pseudo_link] + .hidden, .pseudo_link + .hidden", "#main_content").prev().click(function() {
		if($.browser.msie){
			$(this).next().toggle()
			$("#layout").width($("#layout").width());
			$("#layout").removeAttr("style");
		}
		else{
			$(this).next().slideToggle(150);
		}
	});

	  selectedvideo = getParameterByName('vid');
    if(window.selectedvideo){
	     if($.browser.msie){
			     $("#"+selectedvideo).prev().next().toggle();
			     $("#layout").width($("#layout").width());
			     $("#layout").removeAttr("style");
		    }
		    else{
			     $("#"+selectedvideo).prev().next().slideToggle(150);
		    }
    };

});


Main.popup_box = {
	append: function(params){
		return new this.item(params);
	},

	item: function(params){
		this.init(params);
	}
};

Main.popup_box.item.prototype = {
	init: function(params){
		this.element = params && params.element ? params.element : this.create(params);
		this.element.hide();
		var t = this;
		this.element.find('.close').click(function(){t.close();});
	},

	create: function(params){
		return $('<div class="popup_box"><div class="corner lt"></div><div class="corner rt"></div><div class="shadow right iesizing-scale"></div><div class="icon close"></div><div class="content"></div><div class="shadow left iesizing-scale"></div><div class="corner lb"></div><div class="corner rb"></div></div>').appendTo('#header');
	},

	open: function(){
		this.element.show();
		if(!$.browser.msie) {
			this.element.css({opacity: 0});
			this.element.animate({opacity: 1}, 300);
		}
	},

	close: function(){
		if(!$.browser.msie) {
			this.element.animate({opacity: 0}, 200);
		}
		this.element.hide();
	}
};


function getParameterByName( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
};


