var switcher = function(){
	this.init();
}

switcher.prototype = {
	init: function(){
		var that = this;
		this.is_init = false;
		this.tabs_items = $('#tabs li');
		this.current_item = this.tabs_items.filter('.selected');
		this.tabs_links = this.tabs_items.find('.pseudo_link');


		this.main_content = $('#content');
		this.clouds = $('#clouds');
		this.current_clouds = this.clouds.find('.current_cloud');
		this.content_wrapper = this.main_content.find('.content_wrapper');
		this.current_content = this.main_content.find('.current_content');

		this.start = this.main_content.find('.start');
		this.open_news = this.main_content.find('.open_news');

		this.smart_links = this.main_content.find('.smart_pseudo');

		this.is_animate = false;

		that.initClickLink = false;
		$('#header .start').click(function(){
			if(!that.initClickLink){
			that.initClickLink = true;
			$("html:not(:animated),body:not(:animated)").animate({'scrollTop':that.start.offset().top},300,function(){
				that.start.click();
			});
			}else{
				that.start.click();
			}
		});

		this.switch_tabs();
	},

	switch_tabs: function(){
		var that = this;

		this.start.click(function(){
			var current = that.current_item.next();
			if(current.length > 0)
				current.find('.pseudo_link').click();
			else
				that.tabs_links.eq(0).click();
		});

		this.smart_links.click(function(){
			var current = that.current_item.next();
			var next = current.next();
			if(current.length > 0){
				current.find('.pseudo_link').click();
				$(this).find('ins').html(next.find('.pseudo_link').html())
				if(next.length == 0)
					$(this).find('ins').html(that.tabs_links.eq(0).html())
			}
			else
			{
			  that.tabs_links.eq(0).click();
				$(this).find('ins').html(that.tabs_links.eq(1).html())
			}
		});

		this.open_news.click(function(){
			that.tabs_links.eq(3).click();
		});

		this.open_news.hover(function(){$(this).addClass('hover')},function(){$(this).removeClass('hover')})

		this.tabs_links.click(function(){
			var
				me = $(this),
				parent = me.parents('li');

			if( !parent.hasClass('selected') && !that.is_animate ){
				that.current_item.removeClass('selected');
				that.current_item = parent.addClass('selected');

				if(!that.is_init)	
					setTimeout(function(){that.switch_content(me.attr('class').split(' ')[0].split('link_')[1]);that.is_init=true;},1000);
				else
					that.switch_content(me.attr('class').split(' ')[0].split('link_')[1]);
			}

			var next = $(this).parent().next().find('span');
			if(next.length > 0){
				that.smart_links.find('ins').html(next.text());
			}else{
				that.smart_links.find('ins').html(that.tabs_links.eq(0).text());
			}



			if(that.current_item.find('.pseudo_link').hasClass('link_04')){
				that.open_news.addClass('disable');
			}
			else{
				that.open_news.removeClass('disable');
			}
		});
	},

	switch_content: function( content_id ){
		var that = this;

        $('#home_page .top_blend, #home_page .bottom_blend').css('z-index','10');

		this.new_content = this.main_content.find('.content_' + content_id);
		this.new_clouds = this.clouds.find('.clouds_' + content_id);

    changeClouds(content_id);

		this.content_wrapper.css({'overflow': 'hidden'});
		this.content_wrapper.animate({'height':this.new_content[0].offsetHeight},300);
		this.current_content.before(this.new_content);

		this.is_animate = true;

		this.new_content.css({'margin-top': -(this.new_content[0].offsetHeight) , 'margin-bottom': 0, 'z-index': 10}).removeClass('hidden').animate({'margin-top': 0}, 500, function(){
			that.switch_classes();
		});

		var hh = $('#layout').height();
		if($('#layout').height() < this.new_content[0].offsetHeight)
			hh = this.new_content[0].offsetHeight;

		this.current_clouds.animate({'top': hh}, 500,function(){
			that.content_wrapper.removeAttr('style');
            $('#home_page .top_blend, #home_page .bottom_blend').css('z-index','1');
		});
		this.new_clouds.css({'top': -(this.new_content[0].offsetHeight + this.new_content.offset().top*2)}).removeClass('hidden').animate({'top': 0}, 500);
    },

	switch_classes: function(){
		this.current_content.removeClass('current_content').addClass('hidden').removeAttr('style');
		this.current_content = this.new_content.addClass('current_content').removeAttr('style');

		//this.content_wrapper.removeAttr('style');
		this.current_clouds.removeClass('current_cloud').addClass('hidden').removeAttr('style');
		this.current_clouds = this.new_clouds.addClass('current_cloud').removeAttr('style');

		this.is_animate = false;
	}





}

$(function(){
	new switcher();
});



$(document).ready(function(){
  $('#r_passport_number .field .valid_message').css('left',eval($(window).width()/3.5));
		var userAgent = navigator.userAgent.toLowerCase();
		jQuery.browser = {
			version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
			chrome: /chrome/.test( userAgent ),
			safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ),
			opera: /opera/.test( userAgent ),
			msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
			mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
		};
		
if(jQuery.browser.msie && jQuery.browser.version.substr(0,1) == '6'){
  DD_belatedPNG.fix('.unitPng, #page_body, #after_content, .bottom, .head, .hrt, .td_wzrw, .shadow, .corner, .head_feedback, .content_feedback, #enroll_container, #homepage .content_wrapper');
};



/* врашаем при загрузке. пришлось в шаблоне сделать выбранным по умолчанию второй блок, а при загрузке кликать на первый */
	$('#home_page #page_body #content .inner #tabs li span.link_01').click();
	


	$(".mific .pseudo").hover(
  function () {
    $('.mific').attr('style','color:#BE0026;');
  },
  function () {
    $('.mific').attr('style','color:black');
  }
);



});

/* далее прикручиваем рандомайзер облаков */

function changeClouds(contentid){
	var clouds_amount = 6;	/*for each page*/
	cloud_numbers = getRandomClouds(clouds_amount,9);
	cloud_positions = getRandomClouds(clouds_amount,9)

 /* Простите меня пожалуйста за множество однобуквенных переменных — они все либо счетчики, либо флажки.
 z считает сколько облаков уже обработано. если 3 уже есть, то переходит с левой на правую сторону
 w - считает сколько облаков уже не выведено (для того, чтобы каждый раз слева и справа выводилось разное количество облаков)
 e - коэффициент, насколько можно увеличить разницу по высоте между облаками. он там потом еще умножается на другой коэффициент, который можно менять (подбирались на глаз). без него они чаще слипались. добавило рандомности.
 r - маркер, чтобы если в промежуток между меню и плашкой с контентом не попадает ни одного облака, принудительно последнее обработанное пихать туда.
Времени оптимизировать как-то уже нет, хотя можно было бы заняться.
Пинайте в почту, если что. asar@design.ru gorpacrate@gmail.com :)
 */
 var z = 0;
 var prev_pos_top = 0;
 var prev_pos_left = 0;
 var prev_pos_right = 0;
 var pos_top;
 var resulting_pos_top;
 var resulting_pos_left;
 var resulting_pos_right;
 var w = 0;
 var e;
 var last_used;
 var last_stylestr;
 var r = 0;
 var changed_pos_right;

 $('.clouds_'+contentid+' div' ).each(function(){
		$(this).removeClass();

 		changed_pos_right = '';

		$(this).addClass('cloud_0'+cloud_numbers[z]);

		pos_top = $.randomBetween(330,1050);
		if(prev_pos_top !== 0){
			if(z > 2){
				e = eval(5-z);}else{e = eval(z);
			};
 	  	while(eval(prev_pos_top - pos_top) < eval(140*e) && eval(prev_pos_top - pos_top) > -eval(150*e)){
        pos_top = $.randomBetween(330,1050);
			}
		}
      if(z > 2 && z < 6 && pos_top > 300 && pos_top < 510){
    		pos_top = $.randomBetween(570,1050);

			}

		resulting_pos_top = pos_top+'px !important';

		if(z < 3){
/*  	 pos_left = $.randomBetween(23,62);  */
 			 pos_left = eval($.randomBetween(300,400)/100);

			if(prev_pos_left !== 0){
          pos_left = eval($.randomBetween(900,1500)/100);
			}

		  resulting_pos_left = pos_left+'% !important';

		  if( w <= 1 && $.randomBetween(0,1) == 0){
       	var stylestr = 'display:none;';
				w = eval(+w+1);
 			}else{
				var stylestr = 'top:'+resulting_pos_top+';left:'+resulting_pos_left+';right:auto;margin-left:-5% !important;display:block;';
        prev_pos_left = pos_left;
        		prev_pos_top = pos_top;
			}


		}else{
	/*			pos_right = $.randomBetween(23,60);*/

			pos_right = eval($.randomBetween(300,400)/100);

			if(prev_pos_right !== 0){
		  	pos_right = eval($.randomBetween(900,1500)/100);
			}
			resulting_pos_right = pos_right+'% !important';


    	if( w <= 1 && $.randomBetween(0,1) == 0){
				var stylestr = 'display:none;';
				w = eval(+w+1);
			}else{
				var stylestr = 'top:'+resulting_pos_top+';right:'+resulting_pos_right+';left:auto;margin-right:-5% !important;display:block;';
      	prev_pos_right = pos_right;
        prev_pos_top = pos_top;
			}



		}

		//console.log('z='+z+', pos_top='+pos_top+', changed_pos_right='+changed_pos_right);





    if(pos_top > 400){
			if($(this).css('display') !== 'none'){
				last_used = $(this);
				if(z<3){
					last_stylestr = 'top:400px;left:'+resulting_pos_left+';right:auto;margin-left:-5% !important;display:block;';
				}else{
	  			last_stylestr = 'top:370px;left:14%;right:auto;margin-left:-5% !important;display:block;';
				}

			}
		}else{
    			r = 1;
		}

		$(this).attr('style',stylestr);
		if(z==2){prev_pos_top = 0;}


		z = eval(+z+1);


 });

	if(r==0){

    last_used.attr('style',last_stylestr);
	}


}

/* возвращает нужное количество (amount) уникальных рандомно взятых облаков из общего количества доступных облаков */
function getRandomClouds(amount,total_amount){
	var cloud_numbers = new Array();
  var i=0;
	for (i=0;i<=eval(amount - 1);i++){
	  var tryunique = false;
	  while(!(tryunique)){
			var curr=$.randomBetween(1, total_amount);
			tryunique = try_unique(cloud_numbers, curr);
		}
    cloud_numbers[i] = curr;
	}
	return cloud_numbers;
};

function try_unique(cloudnumbers, current){
	var x;
	var y = true; /* пропускаем по умолчанию */
	for (x in cloudnumbers){
		if(current == cloudnumbers[x]){ y = false; }
	}
	return y;
};

jQuery.extend({
	random: function(X) {
	    return Math.floor(X * (Math.random() % 1));
	},
	randomBetween: function(MinV, MaxV) {
	  return MinV + jQuery.random(MaxV - MinV + 1);
	}
});






