var SITEDATA=new Array();

//Function that starts after page downloading
$(document).ready(function () {
	$("a[rel^='prettyPhoto']").prettyPhoto({theme:'facebook'});
	Cufon.replace(".Myriad_Pro");
	$('form.niceform, form, form.fg_formDiv').jqTransform({imgPath:'jqtransformplugin/img/'}); 	
});


/* ------------------------ Login and registration -------------------------- */

//Show form of password reminder
function showReminder()
{
	$("#loginDiv").fadeOut(200, function(){ $("#passwordReminder").fadeIn(200); });	
}

//Show form of loginer
function showLoginer()
{
	$("#passwordReminder").fadeOut(200, function(){ $("#loginDiv").fadeIn(200); });
}

//Synchronize email between forms of loginer and password reminder
function syncronizeEmails()
{
	$("#reminderEmail").attr("value", $("#loginerEmail").attr("value")); 
}

function showLoader()
{
	topPosition=Math.floor(parseInt($(document).scrollTop())+parseInt($(window).height())/2)-12;
	$("#ajaxLoader").css("top", topPosition+"px");
	$("#ajaxLoader").show();			
}

function hideLoader()
{
	$("#ajaxLoader").hide();			
}


function logout()
{
	showLoader()
	$.ajax({
	  url: base_url+'logout/',
	  success: function(){
		hideLoader();
		document.location.href=document.location.href;
	  }
	});	
}

// ------------------------------------------------ Вакансии -----------------------------------------
//Функция фильтрует вакансии по городам и по профессиям
function jobsFilter()
{
	selectedCity=parseInt($('#jobsFilterCity').val());
	selectedPost=parseInt($('#jobsFilterPost').val());
	
	$('.jobsBlock').each(function(){
		showMe=false;
		
		cityCheck=false;
		postCheck=false;
		
		cid=$(this).attr("id");
		currentPost=parseInt($('#'+cid+' input[name="post"]').attr("value"));
		currentCity=parseInt($('#'+cid+' input[name="city"]').attr("value"));
		
		
		
		//Проверяем город
		if(selectedCity==0)
		{
			cityCheck=true;
		}
		else if(selectedCity==currentCity)
		{
			cityCheck=true;
		}
		else
		{
			cityCheck=false;
		}
		
		//Проверяем должность
		if(selectedPost==0)
		{
			postCheck=true;
		}
		else if(selectedPost==currentPost)
		{
			postCheck=true;
		}
		else
		{
			postCheck=false;
		}
				
		
		//Проверяем какой тип анимации нужен для этого блока
		if(postCheck && cityCheck)
		{
			showMe=true;
		}
		else
		{
			showMe=false;	
		}
		
		
		//Показываем или скрываем текущий блок
		currentDisplay=$('#'+cid).css("display");
		if(showMe)
		{
			//alert(currentDisplay);
			if(currentDisplay=="none")
			{
				$('#'+cid).fadeIn(500);
			}
		}
		else
		{
			if(currentDisplay!="none")
			{
				$('#'+cid).fadeOut(500);
			}
		}
		
	});
	
	
	//Скрытие не существующих в данном городе должностей из выпадающего списка должностей.
	//selectedCity
	//selectedPost
	var activePosts=new Array();
	i=0;
	$(".jobsBlock").each(function(){
		id=$(this).attr("id");
		c_city=parseInt($("#"+id+" input[name='city']").attr("value"));	
		if(c_city==selectedCity || selectedCity==0)
		{
			c_post=parseInt($("#"+id+" input[name='post']").attr("value"));	
			activePosts[i]=c_post;	
			i++;						
		}
	});	
	
	$("#jobsFilterPost option").each(function(){
		id=$(this).attr("id");
		val=parseInt($("#"+id).attr("value"));
		if(contains(activePosts, val))
		{
			$("#"+id).show();
		}
		else
		{
			$("#"+id).hide();
		}	
	});	
	
	
	$("#jobsFilterPost option").each(function(){
		id=$(this).attr("id");
		if($("#"+id).css("display")=="block")
		{
			//$("#"+id).attr("selected","selected")
		}		
	});	
	
}

		
function contains(a, obj){
  for(var i = 0; i < a.length; i++) {
    if(a[i] === obj){
      return true;
    }
  }
  return false;
}


// ------------------------------------------------ Акции -----------------------------------------
//Функция фильтрует акции по категории
function actionsFilter()
{
	currentType=parseInt($("#actionsList").val());
	$(".actions_visible").animate({opacity: "0"}, 500, function(){
		$(".actions_visible").hide();
		$("#actionsBlock"+currentType).css("opacity","0").show();
		$("#actionsBlock"+currentType).animate({opacity: "1"}, 500);
		$(".actions_visible").attr("class", "actions_hidden");
		$("#actionsBlock"+currentType).attr("class", "actions_visible");
	});
}


//---------------------------------------- MAPS ---------------------------------------------------
var activeDistrict=-1;

$(document).ready(function(){
	if(!$.browser.msie)
	{
		$('.cosmo_district_map').css('opacity','0');	
		$('.cosmo_address_detailed').css('opacity','0');
	}
});

//Функция срабатывающая при наведении на область с номером num
function switchDistrict(num, state)
{
	if(state=='show')
	{
		if(activeDistrict!=num)
		{
			$('#map_'+num).show();
			if(!$.browser.msie)
			{
				$('#map_'+num).stop().animate({opacity:'1'},200);
			}
		}
		
		//$("#kyivmap").css("z-index","1000");
		
		//Скрываем названия областей
		$('.cosmo_district_name[id!=cosmo_district_name_'+num+']').stop().animate({opacity: '0.2'}, 400);
	}
	else
	{
		
		if(activeDistrict!=num)
		{
			if($.browser.msie)
			{
				$('#map_'+num).hide();
			}
			else
			{
				$('#map_'+num).stop().animate({opacity:'0'},200);
			}
		}
		
		//$("#kyivmap").css("z-index","10000");
		
		//Проявляем названия областей
		$('.cosmo_district_name').stop().animate({opacity: '1'}, 400);
		
	}
}




//Функция срабатывающая при клике на область
function selectDistrict(num)
{
	//убираем старую подсвеченную область
	if(activeDistrict!=num)
	{
		if(activeDistrict>0)
		{
			if($.browser.msie)
			{
				$('#map_'+activeDistrict).hide();
			}
			else
			{
				$('#map_'+activeDistrict).stop().animate({opacity:'0'},400);
			}			
		}		
	}
	
	//показываем окно со списком объектов этой области
	cid=$('#cosmo_address_detailed'+activeDistrict).attr("id");
	if($.browser.msie)
	{
		if(activeDistrict>0)
		{			
			$('#'+cid).hide();				
		}
		$('#cosmo_address_detailed'+num).show();
	}
	else
	{
		if(activeDistrict>0)
		{			
			$('#'+cid).animate({opacity: '0'}, 400, function(){
				$('#'+cid).hide();
			});	
		}
		$('#cosmo_address_detailed'+num).show();
		$('#cosmo_address_detailed'+num).animate({opacity: '1'}, 400);
	}
	
	//прокручиваем список с адресами до нужной области
	i=0;
	$('#cosmo_address_districtname'+num).each(function(){
		i++;		
	});
	
	if(i)
	{
		tmpOffset=$('.map_adres').offset();
		offset=$('#cosmo_address_districtname'+num).offset();
		neededOffset=offset.top-tmpOffset.top+$('.map_adres').scrollTop();
		$('.map_adres').animate({scrollTop: neededOffset+'px'}, 500);
	}
	else
	{
		$('.map_adres').animate({scrollTop: '0px'}, 500);
	}
	
	activeDistrict=num;
}

//Функция открывающая PrettyPhoto окно с картой Google
function showGoogleMap(id, address)
{
	$.prettyPhoto.open(base_url+url_language+'googlemap/'+id+'/?iframe=true&width=600&height=400');
}


/* ---------------------------- КОНСУЛЬТАЦИИ ЭКСПЕРТОВ ---------------------------------- */

var quizCat=0;
var quizExpert=0;

//Функция вызываемая при изменении параметров фильтра 
function quizFilter(category, ex)
{
	quizExpert=$('#quiz_expert').val();
	if(!ex)
	{
		quizCat=category;
	}
	url=base_url+url_language+'consultations/0o'+quizCat+'o'+quizExpert+'o0/';
	document.location=url;
}

//Функция добавляющая комментарий или вопрос
function cosmoAddMaterial(contentId, type)
{
	content=$("#"+contentId).val();
	additionalParameters='';
	if(type==1)
	{
		additionalParameters="&exp="+$("#quiz_askexpert").val();
		$('input[type="radio"][name="askcategory"]').each(function(){
			ch=$(this).attr("checked")
			if(ch)
			{
				val=$(this).attr("value");
				additionalParameters+="&cat="+val;	
			}
		});
	}
	else if(type==2)
	{
		additionalParameters="&quizid="+$('input[type="hidden"][name="quizid"]').val();;	
	}
	
	showLoader();
	$.ajax({
	   type: "POST",
	   url: base_url+'ajax/quiz/',
	   data: "type="+type+additionalParameters+"&content="+content,
	   success: function(msg){
		  result=eval('('+msg+')');
		  
		  hideLoader();
	  	  messageClassName='regAlert';
		  if(result['error'])
		  {
			  messageClassName='regError';
		  }
		  
		  mes=result['message'];
		  
		  if(mes.length)
		  {
		  	$('#cosmoErrorContainer').html('<div class="'+messageClassName+'">'+mes+'</div>');
		  }
		  
		  $("#"+contentId).val("");
	   }
	});
}




//Функция добавляющая комментарий или вопрос
function cosmoAddBlogMaterial(contentId, type)
{
	content=$("#"+contentId).val();
	additionalParameters='';
	additionalParameters="&exp="+$("#quiz_askexpert").val();
	additionalParameters="&quizid="+$('input[type="hidden"][name="quizid"]').val();	
	
	showLoader();
	$.ajax({
	   type: "POST",
	   url: base_url+'ajax/blog/',
	   data: "type="+type+additionalParameters+"&content="+content,
	   success: function(msg){
		  result=eval('('+msg+')');
		  
		  hideLoader();
	  	  messageClassName='regAlert';
		  if(result['error'])
		  {
			  messageClassName='regError';
		  }
		  
		  mes=result['message'];
		  
		  if(mes.length)
		  {
		  	$('#cosmoErrorContainer').html('<div class="'+messageClassName+'">'+mes+'</div>');
		  }
		  
		  $("#"+contentId).val("");
	   }
	});
}



//---------------------------------- МОЁ ЗЕРКАЛО ---------------------------------------------------- //
function cosmoShowDetailedForm()
{
	$('#cosmo_detailedBg').css('opacity','0').css('height',(parseInt($('.main').height())+30)+'px');
	$('#cosmo_detailedBg').show();
	$('#cosmo_detailedBg').stop().animate({opacity: '0.8'},500);
	$('#cosmo_detailedForm').css('margin-top', -(parseInt($('#cosmo_detailedForm').height())+400)+'px').show();
	$('#cosmo_detailedForm').animate({marginTop: '0px'},300);
}


function cosmoHideDetailedForm()
{
	$('#cosmo_detailedBg').stop().animate({opacity: '0'},500, function()
	{  
		$('#cosmo_detailedBg').hide();
	});
	
	$('#cosmo_detailedForm').animate({marginTop: -(parseInt($('#cosmo_detailedForm').height())+400)+'px'},300, function()
	{
		$('#cosmo_detailedForm').hide();	
	});
}


function cosmoProfileFormCheck(formId)
{
	if(formId=='cosmo_profileInfo2')
	{
		psw=$('#'+formId+' input[name="passwordopen"]').val();
		if(psw.length>=5)
		{
			$('#'+formId).submit();
		}
		else
		{
			alert('Пароль повинен бути довшим за 5 символів');
		}
	}
	else
	{
		$('#'+formId).submit();	
	}
}


function cosmoShowLayer(id)
{
	if(id=='cosmo_allquestions')
	{
		w=850;	
	}
	else
	{
		w=800;	
	}
	
	//$('html, body').animate({scrollTop: 0},600);
	//scrollTop=
	
	//topPosition=Math.floor(parseInt($(document).scrollTop())+parseInt($(window).height())/2)-12;
	
	$('#cosmo_layerContent').html($('#'+id).html());
	$('#cosmo_layerBg').css('opacity','0').css('height',(parseInt($('.main').height())+50)+'px');
	$('#cosmo_layerBg').show();
	$('#cosmo_layerBg').stop().animate({opacity: '0.8'},500);
	$('#topframe').css('width',w+'px').show();
	$('#topframe').css('margin-top', -(parseInt($('#topframe').height())+400)+'px').show();
	$('#topframe').animate({marginTop: (parseInt($(document).scrollTop())-280+parseInt($(window).height())/2)-Math.floor(parseInt($('#topframe').height())/2)+'px'},300);
}


function cosmoHideLayer()
{
	$('#cosmo_layerBg').stop().animate({opacity: '0'},500, function()
	{  
		$('#cosmo_layerBg').hide();
	});
	
	$('#topframe').animate({marginTop: -(parseInt($('#topframe').height())+400)+'px'},300, function()
	{
		$('#topframe').hide();	
	});
}

/* ----------------------------------- Акции ----------------------------- */
function actionsTakePart(uid, aid)
{
	showLoader();
	$.ajax({
	   type: "POST",
	   url: base_url+'ajax/action/',
	   data: "aid="+aid+"&uid="+uid+"&act=0",
	   success: function(msg){
		  	hideLoader();	
		  	$('#actUntake').show();
			$('#actTake').hide();  	
			//alert(msg); 
	   }
	});	
}

function actionsUntakePart(uid, aid)
{
	showLoader();
	$.ajax({
	   type: "POST",
	   url: base_url+'ajax/action/',
	   data: "aid="+aid+"&uid="+uid+"&act=1",
	   success: function(msg){
		  	hideLoader();	
			$('#actUntake').hide();
			$('#actTake').show();
			//alert(msg); 	 
	   }
	});		
}

function actionsUntakePart2(uid, aid)
{
	showLoader();
	$.ajax({
	   type: "POST",
	   url: base_url+'ajax/action/',
	   data: "aid="+aid+"&uid="+uid+"&act=1",
	   success: function(msg){
		  	hideLoader();	
			$(".actrow"+aid).fadeOut(400);
			//alert(msg); 	 
	   }
	});		
}
