// JavaScript Document

$(document).ready(function(){
	paintTagCloud();
	cutomizeArchiveDropDown();
	initSmartDownload();
	initDownloadPopup();
	initSearchFields();
	initSignupFormAnimation();
});

//VlaD BEGIN
//Добавлено для безопасного вывода в консоль firebug
/**
* Вывод информации в консоль, если объект консоли существует
* @param value mixed - выводимое значение
* @param string title - имя выводимого значения
*/
function printLog(value, title)
{
	if(typeof console != 'undefined')
	{
		if(typeof title != 'undefined')
		{
			console.log(title, value);
		}
		else
		{
			console.log(value);
		}
	}
};
//VlaD END

function paintTagCloud(){
	$(".widget_tag_cloud a").each(function(){
		var hue=256-(30-parseInt($(this).css('font-size')))*5;
		$(this).css('color','rgb('+hue+','+hue+','+hue+')');
	});
}

function cutomizeArchiveDropDown(){
	if($(".widget_archive select").length>0){
		$(".widget_archive select").wrap('<div id="WidgetArchive" class="CustomDropDown"><form></form></div>');
		$("#WidgetArchive").fdd2div({
									GenerateHyperlinks:1,
									AnimationSpeed: "fast"
								});
	}
}


function initDownloadPopup(){
	$('a.navlink', $('.DownloadsPopup').parent()).click(function(){
		$(this).css({'position':'relative', 'z-index':'2000'});
		$('.DownloadsPopup .DownloadsPopup_tail', $(this).parent()).css('left', ($(this).position().left+$(this).width()/2-12)+'px');
		$('.DownloadsPopup', $(this).parent()).fadeIn('fast');
	
		return false;
	});
	
	
	$(document).keydown( function(e) { 
		if( e.which == 27) {  // escape
		  $('.DownloadsPopup:visible').fadeOut('fast');
		}
	}); 
	
	$(document).click(function(e){
		if(click_outside(e, '.DownloadsPopup:visible *')){
			$('.DownloadsPopup:visible').fadeOut('fast');
		}
	});
}


function initSmartDownload(){
	var downloadBlock = $('.DownloadsBlock');
	
	
	$('a.CustomDropDown_main_link', downloadBlock).click(function (){
		$('ul.CustomDropDown_ul_list',downloadBlock).slideUp(100);
		$('a.CustomDropDown_main_link',downloadBlock).removeClass('expanded').addClass('collapsed');
		$('ul.CustomDropDown_ul_list',$(this).parent()).stop().slideToggle(100);
		if($(this).hasClass('collapsed')){
			$(this).removeClass('collapsed').addClass('expanded');
		} else {
			$(this).removeClass('expanded').addClass('collapsed');
		}
	});
	
	$('ul.CustomDropDown_ul_list a', downloadBlock).click(function () {
		$('a.CustomDropDown_main_link', $(this).parent().parent().parent())
			.attr('href',$(this).attr('href'))
			.html($(this).html()).each(function(){
				$(this).removeClass('expanded').addClass('collapsed');
			});
		$(this).parent().parent().slideUp(50);
		
		var linkID='download';
		// VlaD костыли BEGIN
		// При переходе по ссылке, например http://cerebrohq.com/en/download/ на страницу загрузки
		// некорректно отрабатывало формирование ссылки на загрузку
		// из-за того, что блоков загрузки с выпадающим меню фактически становилось 2
		// переписать по-человечески
		// то, что добавил, откомментировал как start - end
		
		// start
		var count = $('.CustomDropDown a.CustomDropDown_main_link',downloadBlock).length;
		var deep = 0;
		// end
		$('.CustomDropDown a.CustomDropDown_main_link',downloadBlock).each(function(){
			// start
			if( (2-count+deep)>=0)
			{
			// end
				if($(this).attr('href')){
					linkID+='-'+$(this).attr('href').replace('#','');
				}
			// start
			}
			deep++;
			// end
		});
		// VlaD костыли END
		
		/*
		$('.CustomDropDown a.CustomDropDown_main_link',downloadBlock).each(function(){
			if($(this).attr('href')){
				linkID+='-'+$(this).attr('href').replace('#','');
			}
		});
		*/
		
		$('.CustomButton_downloads', downloadBlock).attr('href',$('#'+linkID).attr('href'));
	});
	
	$('ul.CustomDropDown_ul_list', downloadBlock).each(function(){
		$($('a', $(this)).get(0)).click();
	});
	
	
	
}


function initYoutubeIntro(){
	var youtubeHeight=490;
	$('#youtubePreview').click(function(){
		$('#youtube .content').fadeOut('fast',function(){
			$('#youtube').animate({'height': youtubeHeight+'px'},'fast');
			swfobject.embedSWF(	$('#youtubePreview').attr('href'),
								"youtubePreview",
								"826", youtubeHeight, "8",
								null, null,
								{ 	bgcolor: '#212121',
									allowScriptAccess: "always"},
								{ id: "youtubeIntro" });
			$('#youtube .content').fadeIn(3000);
			
		});
		return false;
	});
}


function initTabs(){
	if($("#Tabs").length>0){
		$("#Tabs").tabs();
	}
}

function initSearchFields(){
	if (!$.browser.safari) {
		$('input[type=search]').blur(function(){
			if($(this).val()=='' || $(this).val()==$(this).attr('placeholder')){
				$(this).val($(this).attr('placeholder'));
				$(this).css('color','#aaa');
			}
		})
		.focus(function(){
			if($(this).val()==$(this).attr('placeholder')){
				$(this).val('');
			}
			$(this).css('color','#111');
		});
		$('input[type=search]').blur();
	}
}

function initRandomTestimonials(){
	var testimonials = $('.TestimonialsBlock li');
	$(testimonials[Math.floor(Math.random() * testimonials.length)]).fadeIn('slow');

}

function initSignupFormAnimation(){
	var signupBox = $('.SignUpBox');
	if(signupBox.length>0){
		
		// Открываем форму, если имеется якорь #openform
		if(location.hash == "#openform")
		{
			$('.SignUpBoxBody', signupBox).show();
			$('.arr a',signupBox).addClass('collapsed');
		}
		else
		{
			$('.SignUpBoxBody', signupBox).hide();
		}
		
		$('.SignUpBoxHeader', signupBox).click(function(e){
			
			if($('.arr a',signupBox).hasClass('collapsed')){
				$('.SignUpBoxBody', signupBox).slideUp(100);
				$('.arr a',signupBox).removeClass('collapsed');
			} else {
				$('.SignUpBoxBody', signupBox).slideDown(100);
				$('.arr a',signupBox).addClass('collapsed');
			}
		});
	}
}

function click_outside(e, obj)
{
	return (!$(e.target).is(obj));
}