$(document).ready(function()
{
 // code
 equal_height_blocks('anons');
 equal_height_blocks('news');
 equal_height_blocks('catalogue');
 // end code
}
);

function equal_height_blocks(alias)
{
 var flag = true;
 var i = 1;
 var j = 2;
 while(flag)
 {
  if ($("#"+alias+i).get(0) && $("#"+alias+j).get(0))	
  {
   var height = Math.max($("#"+alias+i).height(),$("#"+alias+j).height(),130);
   $("#"+alias+i).css(
   {
    height: height+"px"
   }
   );	
   $("#"+alias+j).css(
   {
    height: height+"px"
   }
   );
   i = i + 2;
   j = j + 2;	
  }
  else
  {
   flag = false;	
  }
 }
}

function nicedit_hack()
{
 $("#ajaxfilemanager").get(0).value = tinyMCE.get('ajaxfilemanager').getContent(); 
}

function nicedit_anons_hack()
{
 $("#anons").get(0).value = tinyMCE.get('anons').getContent(); 
}

function nicedit_vakancy_hack()
{
 $("#requirements").get(0).value = tinyMCE.get('requirements').getContent(); 
 $("#conditions").get(0).value = tinyMCE.get('conditions').getContent();
 $("#charge").get(0).value = tinyMCE.get('charge').getContent(); 
}

function nicedit_answer_hack()
{
 $("#ajaxfilemanager").get(0).value = tinyMCE.get('ajaxfilemanager').getContent();
 $("#answer").get(0).value = tinyMCE.get('answer').getContent();	
}

function textareanicedithack(alias)
{
 $("#"+alias).css(
 {
  width: $("#"+alias).width()+"px"
 }
 );		
}

function loadform(alias)
{
 $('#'+alias).ajaxForm(
 { 
  dataType:  'json', 
  success:   processJsonForm
 }
 );	
}

function processJsonForm(data)
{
 $("#inputresult").html("<div class=\"error\"><div class=\"errorpad\">"+data.text+"</div></div>");	
 if(data.done==1) 
 {
  $("#submit_data").attr("disabled","disabled");
  // ставим задержку, чтобы пользователь мог прочитать надпись
  setTimeout(function(){window.location = data.link;}, 2000);
 }
 else
 {
  $("#submit_data").attr("disabled","");	
 }
 $("#formajaxloader").empty();
}

function loadindicator()
{
 $("#formajaxloader").html("<div style=\"position:absolute;top:5px;left:50%;width:16px;height:16px\"><img src=\"/i/ajax/orange.gif\" width=\"16\" height=\"16\" alt=\"\" /></div>");
}

function show_login_form()
{
 $("#loginblock").hide();
 $("#loginblock").load("/userlogin/",
 {
  show_login_block: true
 }
 );
 $("#loginblock").show();
}

/*
* Функция, проверяет наличие вводимого пользователем логина на уникальность (при регистрации)
*/
function unique_login()
{
 $.getJSON(
 '/registration',
 {
  login:$("#login").get(0).value,
  check_login: true
 },
 getloginunique
 );
}

function getloginunique(obj)
{
 $("#checklogin").empty();
 if(obj.param==1)
 {
  $("#submit_data").attr("disabled","");
  $("#checklogin").append("<span style=\"color:green\">ок</span>");
 }
 else
 {
  $("#submit_data").attr("disabled","disabled");
  $("#checklogin").append("<span style=\"color:red\">логин не уникален</span>");
 }
}

/* 
* функция сравнивает пароли в полях пароль и повторите пароль
*/

function passwords_compare()
{
 if ($("#password").get(0).value && $("#password_r").get(0).value)
 {
  if ($("#password").get(0).value == $("#password_r").get(0).value)
  {
   var pass = $("#password").get(0).value;
   if (pass.length<5)
   {
   	$("#submit_data").attr("disabled","disabled");
    $("#checkpassword").html("<span style=\"color:red\">пароль должен быть не менее 5ти символов</span>");
   }
   else
   {
   	$("#submit_data").attr("disabled","");
    $("#checkpassword").html("<span style=\"color:green\">ок</span>");  	
   }
  }
  else
  {
   $("#submit_data").attr("disabled","disabled");
   $("#checkpassword").html("<span style=\"color:red\">пароли не совпадают</span>"); 	
  }
 }
}


/*
* функции для напоминания пароля
*/
function remind_password()
{
 $("#loginblock").animate({height: "hide"}, 300);
 $("#loginblock").load("/userlogin/",
 {
  remind_password: true
 }
 );
 $("#loginblock").animate({height: "show"}, 300);
}

function send_new_password()
{
 $("#ajaxloader").html("<div style=\"position:absolute;top:70px;left:215px;width:16px;height:16px\"><img src=\"/i/ajax/black.gif\" width=\"16\" height=\"16\" alt=\"\" /></div>");
 $.getJSON(
 '/userlogin',
 {
  login:$("#login_for_remind").get(0).value,
  email_password: true
 },
 getremainpassword
 );
}

function getremainpassword(obj)
{
 alert(obj.note);
 if (obj.send==1) $("#loginblock").hide();
}

/*
* Функция, проверяет совпадает ли пароль полльзователя и то что, он вводит в поле "старый пароль" при изменении пароля
*/
function oldpassword_enter()
{
 $("#oldpassword_result").empty();
 $("#oldpassword_result").append("<img src=\"/i/circle-loader.gif\" alt=\"\" width=\"16\" height=\"16\" />");
 $("#oldpassword_result").load("/users/",
 {
  oldpassword:$("#oldpassword").get(0).value,
  check_oldpassword: true
 }
 );
}

function pick_parent(title,id)
{
 $("#picked_parent").empty();
 $("#picked_parent").append(title);
 $("#parent_id").attr("value",id);
}

/**
 *
 * @access public
 * @return void
 **/
function getLogin()
{
 $("#login_result").empty();
 $("#ajaxloader").html("<div style=\"position:absolute;top:65px;left:155px;width:16px;height:16px\"><img src=\"/i/ajax/black.gif\" width=\"16\" height=\"16\" alt=\"\" /></div>");
 $.getJSON(
 '/userlogin',
 {
  login:$("#trylogin").get(0).value,
  password:$("#trypassword").get(0).value,
  remember: $("#remember").get(0).checked ? "Y":"N",
  submit_login: true
 },
 function(obj)
 {
  $("#log_information").empty();
  $("#ajaxloader").empty();
  $("#log_information").append(obj.userstring);
  if(obj.reload==1) 
  {
   document.location.href= document.location.href; 
  } 
  else
  {
   $("#login_result").html("<div style=\"position:absolute;top:-17px;left:75px;color:#f00;width:200px;font-size:11px;font-weight:bold;z-index:100\">Вы ввели неправильные данные!</div>");
  }
 }
 );
}

function getLogout()
{
 var html = $("#log_information").html();	
 $("#log_information").html(html + "<div style=\"position:absolute;top:19px;left:120px;width:16px;height:16px\"><img src=\"/i/ajax/orange.gif\" width=\"16\" height=\"16\" alt=\"\" /></div>");
 $.getJSON(
 "/userlogin/",
 {
  submit_logout: true
 },
 function(obj)
 {
  $.cookie("id_user_cookie", null);
  $.cookie("password_cookie", null);
  document.location.href=document.location.href;	
 }
 );
}

function send_message(id,type)
{
 $("#message_box").empty();
 $("#message_box").get(0).style.display = 'block';
 $("#message_box").append("<img src=\"/i/ajaxarrows.gif\" alt=\"\" width=\"16\" height=\"16\" />");
 $("#message_box").load("/users/",
 {
  id: id,
  type: type,
  show_message_form: true
 }
 );
}

function send_message_action(id)
{
 $("#send_info").append("<img src=\"/i/ajaxarrows.gif\" alt=\"\" width=\"16\" height=\"16\" />");
 $("#send_info").load("/users/",
 {
  title:$("#msgtitle").get(0).value,
  text:$("#msgtext").get(0).value,
  to: id,
  send_message: true
 }
 );
}

function selectallmsg()
{
 $("div#messagelist input:checkbox").attr("checked",  $("#allmsg").get(0).checked ? "checked" : "");
}

function show_submenu(id,type)
{
 $("#submenu_"+type+id).animate({height: $("#submenu_"+type+id).get(0)&&$("#submenu_"+type+id).get(0).style.display=='none' ? "show" : "hide"}, 400);
}

/*
* Добавляем фотоальбом
*
*/
function create_album()
{
 $.getJSON(
 '/ajax',
 {
  title:$("#albumtitle").get(0).value,
  parent_id:$("#parent_id").get(0).value,
  add_album: true
 },
 function(obj)
 {
  $('#newalbum').hide();
  if(obj.done==1) 
  {
   $("#album").html(obj.select);
   $("#album > option[@value="+obj.selected+"]").attr("selected", "selected");        
  }
 }
 );
}

/* 
* функция подгружает в другой селект - древовидное меню, в зависимости от выбранного типа публикации
*
*/
function load_tree()
{
 $("#tree").html("<img src=\"/i/indicator.gif\" alt=\"\" width=\"16\" height=\"16\" />");
 $.getJSON(
 '/ajax',
 {
  table:$("#table").get(0).value,
  parent:$("#parent_id").get(0).value,
  show_tree: true
 },
 tree_show
 );
}

function tree_show(obj)
{
 $("#tree").html(obj.menu);         
}


function load_branch(id)
{
 $("#branch").html("<img src=\"/i/indicator.gif\" alt=\"\" width=\"16\" height=\"16\" />");
 $.getJSON(
 '/ajax',
 {
  table: $("#old_table").get(0).value,
  parent: $("#parent_id").get(0).value,
  id: id,
  show_branch: true
 },
 branch_show
 );
}

function branch_show(obj)
{
 $("#branch").html(obj.menu);         
}

function promote_to(where,id)
{
 $("#branch").html("<img src=\"/i/indicator.gif\" alt=\"\" width=\"16\" height=\"16\" />");
 $.getJSON(
 '/ajax',
 {
  where: where,
  id: id,
  table: $("#old_table").get(0).value,
  parent: $("#parent_id").get(0).value,
  sort_branch: true
 },
 branch_show
 );        
}

function redraw_calendar(direction,table,script)
{
 $("#calendar_snake").append("<img src=\"/i/ajax/black.gif\" alt=\"\" width=\"16\" height=\"16\" />");
 $("#calendar").load("/calendar/",
 {
  direction: direction,
  table: table,
  script: script
 }
 );
}

/* work with docs */
function pre_public_document(table,id,status,field)
{
 var div = field=='available' ? "ajaxloader":"ajaxloader_main";	
 $("#"+div).html("<div style=\"position:absolute;top:-9px;left:240px;border:1px solid #902002;padding:5px;text-align: center\"><input type=\"checkbox\" id=\"paid\" checked=\"checked\" /> - платная заявка<br/><input type=\"button\" value=\"Ок\" onclick=\"public_document('"+table+"','"+id+"','"+status+"','"+field+"')\" class=\"submit\" /></div>");	
}

function public_document(table,id,status,field)
{	
 var div = field=='available' ? "ajaxloader":"ajaxloader_main";
 var button = field=='available' ? "public":"main_public";
 var paid = $("#paid").get(0) && $("#paid").get(0).checked ? 1:0;
 $("#"+button).attr("disabled","disabled");
 $("#"+div).html("<div style=\"position:absolute;top:10px;left:240px;width:16px;height:16px\"><img src=\"/i/ajax/black.gif\" width=\"16\" height=\"16\" alt=\"\" /></div>");
 $.getJSON(
 '/ajax',
 {
  table: table,
  id: id,
  status: status,
  field: field,
  paid: paid,
  public_document: true
 },
 function(obj)
 {
  $("#"+obj.div).empty();
  $("#"+obj.div).html("<div style=\"position:absolute;top:10px;left:240px;\">"+obj.text+"</div>");
 }
 );
}

/* отправляем */
function send_order(table,id,type)
{
 $("#ajaxloader_"+type+"_order").html("<div style=\"position:absolute;top:10px;left:240px;width:16px;height:16px\"><img src=\"/i/ajax/black.gif\" width=\"16\" height=\"16\" alt=\"\" /></div>");
 $("#send_"+type).attr("disabled","disabled");
 $.getJSON(
 '/ajax',
 {
  type: type,	
  table: table,
  id: id,
  send_order: true
 },
 function(obj)
 {
  $("#ajaxloader_"+obj.type+"_order").empty();
  $("#ajaxloader_"+obj.type+"_order").html("<div style=\"position:absolute;top:3px;left:240px;\">"+obj.text+"</div>");
 }
 );
}

/* пытаемся оплатить портфолио */
function pay_portfolio(type)
{
 $("#ajaxloader_"+type).html("<div style=\"position:absolute;top:-13px;left:240px;width:16px;height:16px\"><img src=\"/i/ajax/black.gif\" width=\"16\" height=\"16\" alt=\"\" /></div>");
 $("#send_"+type).attr("disabled","disabled");
 $.getJSON(
 '/ajax',
 {
  type: type,
  pay_portfolio: true
 },
 function(obj)
 {
  $("#ajaxloader_"+obj.type).empty();
  $("#ajaxloader_"+obj.type).html("<div style=\"position:absolute;top:-15px;left:240px;width:200px\">"+obj.html+"</div>");
  if (obj.success==0) $("#send_"+type).attr("disabled",""); 
  else setTimeout(function(){document.location.href= document.location.href;}, 2000);
 }
 );	
}


/* функция для отображения фотографии в альбоме, при клике на превью со списка */
function show_photo(id,number)
{
 var top = $("#cell"+number).offset().top;
 top = top - 328;
 top = top < 100 ? 100:top;
 $("#photobox").css(
 {
  top: top+"px"
 }
 );
 $("#photobox").show();
 $.getJSON(
 '/albums',
 {
  id: id,
  show_photo: true
 },
 function(obj)
 {
  $("#photobox").html(obj.response);
 }
 );	
}

/* Сворачиваем и разворачиваем пользовательское меню */
function user_menu_show()
{
 $("#user_menu").show();
 $("#show_user_menu").html("<span class=\"show_user_menu hand\" onclick=\"user_menu_hide()\">Скрыть меню</span>");	
}

function user_menu_hide()
{
 $("#user_menu").hide();
 $("#show_user_menu").html("<span class=\"show_user_menu hand\" onclick=\"user_menu_show()\">Отобразить пользовательское меню</span>");	
}

/* считаем клики по баннерам */
function CountClick(id,link)
{
 $.getJSON(
 '/ajax',
 {
  id: id,
  link: link,
  count_clicks: true
 },
 function(obj)
 {
  //window.location = obj.result;
  window.open(obj.result);
 }
 );	
}

/* подписываемся на рассылку, отправляем форму другу */
function sign_delivery()
{
 $("#tofriend").html("<div style=\"position:absolute;top:17px;right:130px;width:16px;height:16px\"><img src=\"/i/ajax/orange.gif\" width=\"16\" height=\"16\" alt=\"\" /></div>");
 $.getJSON(
 '/ajax',
 {
  sign_delivery: true
 },
 function(obj)
 {
  if (obj.user)
  {	
   alert("Спасибо! Вы подписаны на расслку сайта event-forum.ru");
  } 
  else alert("Вы должны войти на сайт, прежде чем мы сможем занести Вас в список получателей рассылки");
  $("#tofriend").empty();
 }
 );		
}

function send_to_friend_form(section,id)
{
 $("#tofriend").html("<div style=\"position:absolute;top:17px;right:130px;width:16px;height:16px\"><img src=\"/i/ajax/orange.gif\" width=\"16\" height=\"16\" alt=\"\" /></div>");
 $.getJSON(
 '/ajax',
 {
  section: section,
  id: id,	
  draw_friend_form: true
 },
 function(obj)
 {
  $("#tofriend").html(obj.html);
 }
 );		
}

function send_to_friend(section,id)
{
 var email = $("#friend").get(0).value;
 $("#tofriend").html("<div style=\"position:absolute;top:17px;right:130px;width:16px;height:16px\"><img src=\"/i/ajax/orange.gif\" width=\"16\" height=\"16\" alt=\"\" /></div>");
 $.getJSON(
 '/ajax',
 {
  section: section,
  id: id,	
  email: email,
  send_to_friend: true
 },
 function(obj)
 {
  $("#tofriend").html("<div style=\"position:absolute;top:21px;right:130px;\">"+obj.html+"</div>");
 }
 );		
}

/* блок функция для голосовалки */

function loadpollform(alias)
{
 $('#'+alias).ajaxForm(
 { 
  dataType:  'json', 
  success:   processPollForm
 }
 );	
}

function processPollForm(data)
{
 $("#pollresult").html("<p class=\"note\">"+data.text+"</p>");	
 $("#submit_poll").attr("disabled","disabled");
 $("#pollajaxloader").empty();
 if(data.done==1) setTimeout(function(){document.location.href= document.location.href;}, 2000);
}

function pollindicator()
{
 $("#pollajaxloader").html("<div style=\"position:absolute;top:5px;left:50%;width:16px;height:16px\"><img src=\"/i/ajax/orange.gif\" width=\"16\" height=\"16\" alt=\"\" /></div>");
}

function check_delivery()
{
 	
}

function fill_cat_element(id)
{
 $("ul#catsort li").css({background:"none"});
 $("#el"+id).css(
 {
  background: "red"	
 }
 );
 $("#movedid").attr("value",id);
}

function change_sort(table,id)
{
 var sort = $("#sort"+id).get(0).value;
 $.getJSON(
 '/ajax',
 {
  table: table,
  id: id,	
  sort: sort,
  change_sort: true
 },
 function(obj)
 {
  $("#result"+id).html(obj.done==1 ? "<strong>ок</strong>":"fail")	
 }
 );		
}