var friendBox;

function addToFriend(id) {
  return addToFriends(id);
}

function addToFriends(id, obj) {
  if (friendBox == undefined) {
    friendBox = new MessageBox({title: add_box_title, width: 400});
    if (!window.Dropdown) {
      attachScript('uiControls', 'js/lib/ui_controls.js');
      addCss('css/ui_controls.css');
    }
  }
  var url, act;
  url = 'friends_ajax.php';
  act = 'request_form';

  friendBox.removeButtons();
  friendBox.addButton({label: friends_cancel, style: 'button_no', onClick: function(){friendBox.hide();}});
  friendBox.addButton({label: Add_to_friends, onClick: function(){
    var form = ge('addFriendForm');
    if (!form) return;
    var params = serializeForm(form);
    Ajax.postWithCaptcha(url, params, {onSuccess: function(ajax, responseText){
      try {
        var response = eval('(' + responseText + ')');
        responseText = response.result || response.error || response.text;
      } catch (e) {}
      friendBox.content(responseText).removeButtons();
      friendBox.addButton({label: box_close, onClick: function(){friendBox.hide();}});
      friendBox.show();
      hide(obj);
      setTimeout("friendBox.hide(600)", 1200);
    }});
  }});
  friendBox.content('<div class="box_loader"></div>').show();
  Ajax.postWithCaptcha(url, {act: act, fid: id}, {json: 1, onSuccess: function(ajaxObj, response) {
    if (response.error) {
      friendBox.removeButtons().addButton({label: box_close, onClick: function(){friendBox.hide();}});
    }
    friendBox.content(response.text).show();
    if (response.script) {
      var script = response.script.replace(/^[\s\\n]+/g, '');
      eval(script);
    }
  }});
  return false;
}

var friendDeleteBox;
function removeFriend(fid, obj, hash) {
  if (friendDeleteBox == undefined) {
    friendDeleteBox = new MessageBox({title: friends_remove_from_list_title});
  }
  friendDeleteBox.removeButtons();
  friendDeleteBox.addButton({
    onClick: function(){friendDeleteBox.hide(200)},
    style:'button_no',
    label: friends_cancel
  }).addButton({
    onClick: function(){
     Ajax.Post({
       url: 'friends_ajax.php',
       query: {fid: fid, act: 'decline_friend', hash: hash},
       onDone: function(ajaxObj, responseText) {
        hide(obj);
       }
     });
     friendDeleteBox.hide(200);
    },
    label: friend_friend_remove
  });
  friendDeleteBox.loadContent("friends_ajax.php",{'act':'remove_box','fid':fid}).show();
  return false;
}

function showRateBox() {
  addCss('css/privacy.css');
  addCss('css/wiki.css');
  if (rateBox == undefined) {
    rateBox = new MessageBox(
     {title: getLang('global_rating_box_header'), bodyStyle: 'padding:0px', width: '480px', progress: 'rateProgress'}
    );
  }
  rateBox.removeButtons();
  rateBox.addButton({
    onClick: function() { rateBox.hide(200); },
    label: box_close
  });
  rateBox.loadContent("rate.php", {'act':'a_get_rate'}, true).show();
  return false;
}

var voteBox;
function showVoteBox() {
  addCss('css/privacy.css');
  if (voteBox == undefined) {
    voteBox = new MessageBox(
     {title: getLang('rate_voting'), bodyStyle: 'padding:0px', width: '480px', progress: 'voteProgress'}
    );
  }
  voteBox.removeButtons();
  voteBox.addButton({
    style: 'button_no',
    onClick: function() { voteBox.hide(200); },
    label: global_cancel
  });
  voteBox.loadContent("rate.php", {'act':'a_get_vote_box', 'id': ge('mid').value}, true).show();
  return false;
}

var giftBox, giftBoxTitle;
function showGiftBox(title) {
  giftBoxTitle = title;
  if (!giftBox) {
    addCss('css/gifts.css');
    addCss('css/privacy.css');
    if (!window.Dropdown) {
      attachScript('uiControls', 'js/lib/ui_controls.js');
      addCss('css/ui_controls.css');
    }
    giftBox = new MessageBox({title: title, bodyStyle: 'padding:0px', width: '654px', progress:'gifts_progress'});
  }
  giftBox.removeButtons();
  giftBox.addButton({
    onClick: function() { giftBox.hide(200); },
    label: box_close
  });
  giftBox.loadContent("gifts.php", {'act':'a_get_gift_box', 'id': ge('mid').value}, true).show();
  return false;
}

var giftSendBox, selectedGift, giftPrice;
function showGift(num, obj, price, bonus) {
  giftSendBox.show();
  selectedGift = num;
  giftPrice = price;
  if (price <= window.userBalance) {
    hide('gift_error', 'g_money_to_votes');
  } else if (price <= window.userBalance + Math.floor(window.userMoney / window.config_vote_cost)) {
    hide('gift_error');
    var v = langNumeric(price - window.userBalance, window.lang_n_votes);
    var m = langNumeric(parseInt((price - window.userBalance) * window.config_vote_cost / 10) / 100, lang_money_amount);
    ge('g_money_to_votes_text').innerHTML = window.lang_money_to_votes.replace('{money}', '<b>' + m + '</b>').replace('{votes}', '<b>' + v + '</b>');
    show('g_money_to_votes');
  } else {
    hide('g_money_to_votes');
    show('gift_error');
  }
  ge('gift_loader').innerHTML = '<img src="' + base_domain + 'images/gifts/256/' + num +'.jpg" />';
  return false;
}

function doSendGift(num) {
  if (isVisible('send_progress')) return;
  hide('gift_msg_link');
  show('send_progress');
  var onComplete = function(ajaxObj, responseText) {
    hide('send_progress');
    show('gift_msg_link');
    if (ajaxObj.status == 400) {
      hide('g_money_to_votes');
      show('gift_error');
      ge('gift_error').innerHTML = responseText;
      animate(ge('gift_error').firstChild, {backgroundColor: '#F9F6E7', borderColor: '#D4BC4C'}, 5000);
    } else {
      var result = eval('(' + responseText + ')');
      window.userBalance = intval(result.balance);
      if (window.userBalance) {
        show('left_balance_box');
        ge('left_balance_box').innerHTML = result.balance_html;
      } else {
        hide('left_balance_box');
      }
      window.userMoney = intval(result.money);
      if (window.userMoney) {
        show('left_money_box');
        ge('left_money_box').innerHTML = result.money_html;
      } else {
        hide('left_money_box');
      }
      var profileBlock = ge('profile_gifts');
      if (profileBlock) profileBlock.innerHTML = result.profile_html;
      showGiftResult(result.result);
    }
  };
  Ajax.Send("gifts.php", {act:'do_send', to_users: ge('mid').value, giftType: ge('giftType').value, giftNumber: selectedGift, giftText: ge('gift_text').value, hash: giftHash}, {onSuccess: onComplete, onFail: onComplete});
  return false;
}

var giftResultBox;
function showGiftResult(text) {
  if (!giftResultBox) {
    giftResultBox = new MessageBox({title: giftBoxTitle, width: '444px'});
    giftResultBox.addButton({label: box_close, onClick: giftResultBox.hide});
  }
  giftResultBox.content(text).show();
  setTimeout(function(){giftResultBox.hide(400);}, 1200);
}

var curGiftFilter = 0;
function giftsFilter(filter) {
  ge('giftTab'+curGiftFilter).className = 't_filter_off';
  ge('giftTab'+filter).className = 't_filter_selected';
  curGiftFilter = filter;
  show('gifts_progress');
  Ajax.Send('gifts.php', {act: 'a_get_gifts', filter: filter}, function(ajaxObj, responseText) {
    var parent = ge('selectGift');
    parent.innerHTML = responseText;
    parent.parentNode.scrollTop = 0;
    hide('gifts_progress');
  });
}

var beFanBox;
function beFan(mid) {
  beFanBox = new MessageBox(
   {title: profile_become_a_fan}
  );
  beFanBox.removeButtons();
  beFanBox.addButton({
    onClick: function(){beFanBox.hide(200)},
    label:box_close
  });
  beFanBox.loadContent("rate.php", {'act':'a_be_fan', 'mid': mid}, true).show();
  return false;
}

function notFan(mid) {
  beFanBox = new MessageBox({title: profile_not_a_fan});
  beFanBox.loadContent("rate.php", {'act':'a_not_fan', 'mid': mid}, true).show();
  return false;
}

// EX ACTIVITY.JS

activity_editor = {

  active:             false,  // Is Editor Visible
  menu_active:        false,  // Is Suggestion Menu Visible
  activity_text:        '',

  activity_blur:        false,
  activity_reblur:      false,

  //
  // Functions to transition between modes
  //

  setup: function(initial_activity) {
    this.activity_text = initial_activity;
  },

  reset: function() {
    ge('edit_activity_text').value='';
    return false;
  },

  show: function() {
    if (!this.active) {
    historyAjaxHide();
      hide('profile_activity');
      hide('profile_empty_activity');
      this.hide_menu();
      show('activity_editor');
      if (ge('activity_text').firstChild) {
        this.activity_text = ge('activity_text').firstChild.nodeValue;
      }
      ge('edit_activity_text').value = this.activity_text;
      ge('edit_activity_text').focus();
      ge('edit_activity_text').select();
      this.activity_blur = true;
    setTimeout(function() { activity_editor.active = true; }, 200);
      // this.active = true;
    } else {
      ge('edit_activity_text').focus();
    }
    return false;
  },

  hide: function() {
    if (!this.active) {
      return;
    }
  setTimeout(function() { activity_editor.active = false; }, 200);
    // this.active = false;
    this.activity_blur = false;
    hide('activity_editor');
    show((this.activity_text != '') ? 'profile_activity' : 'profile_empty_activity');
  //if (this.activity_text != '') {
  //  show('profile_activity');
  //}
    return false;
  },

  toggle_menu: function(event) {
   if (browser.safari || browser.msie || browser.opera) {
     this.activity_reblur = true;
    }
    if (this.menu_active) {
      return this.hide_menu();
    } else {
      return this.show_menu();
    }
  },

  show_menu: function(event) {
    this.menu_active = true;
    ge('edit_activity_toggle').style.backgroundColor='#E1E8ED';
    ge('edit_activity_toggle').style.borderLeftColor='#D2DBE0';
    ge('edit_activity_select').style.display='block';
    return false;
  },

  hide_menu: function() {
    this.menu_active = false;
    ge('edit_activity_toggle').style.backgroundColor='#FFF';
    ge('edit_activity_toggle').style.borderLeftColor='#FFF';
    hide('edit_activity_select');
    return false;
  },

  activity_select: function(elem) {
    if (browser.safari || browser.msie || browser.opera) {
      this.activity_reblur = true;
    }
    this.hide_menu();
    ge('edit_activity_text').value = elem.innerHTML;
    ge('edit_activity_text').focus();
    ge('edit_activity_text').select();
  return false;
  },

  menu_over: function(elem) {
  },

  menu_out: function(elem) {
  },

  blur: function(real_blur) {
    if (browser.opera && !real_blur) {
    setTimeout(function() { activity_editor.blur(1); }, 100);
    return false;
  }
    if (this.activity_reblur) {
      ge('edit_activity_text').focus();
      this.activity_reblur = false;
      return false;
    }
    if (this.activity_blur) {
      if (ge('edit_activity_text').value != this.activity_text) {
        this.submit_activity_set(ge('edit_activity_text').value);
      } else {
        this.hide();
      }
    }
    return true;
  },

  //
  // Ajax
  //

  activity_set: function(activity) {
    this.activity_text = activity || '';
    this.reset();
    this.hide();
    if (activity != null && activity != '') {
      ge('activity_text').innerHTML = this.activity_text;
      ge('activity_time_link').innerHTML = activity_update_just_now;
    } else {
      ge('activity_text').innerHTML = activity_cant_update;
    }
  },

  submit_activity_set: function(activity) {
    if (activity == null || activity == '') return;
    var selectInput = function() { ge('edit_activity_text').focus(); };
    var unsetBg = function() { hide('activity_progress'); show('activity_links'); };
    var onDone = function(ajax, response) {unsetBg(); activity_editor.activity_set(response); };
    var onFail = function(ajax) { unsetBg(); activity_editor.activity_set(null); };

    var options = {onSuccess: onDone, onFail: onFail, onCaptchaShow: unsetBg, onCaptchaHide: selectInput};
//    ge('edit_activity_text').style.backgroundImage='url('+base_domain+'images/progress_candy_hor.gif)';
    hide('activity_links');
    show('activity_progress');
    Ajax.postWithCaptcha('/profile.php', {'setactivity':activity, 'activityhash': ge('activityhash').value}, options);
    return false;
  },

  activity_cleared: function() {
    this.activity_text = '';
    ge('activity_text').innerHTML = '';
    this.hide();
    ge('activity_blank_nag').innerHTML=activity_deleted;
    setTimeout(function(){
    // hide('activity_blank_nag');
        ge('activity_blank_nag').innerHTML = activity_change_status;
    }.bind(this), 2500);
  },

  submit_activity_clear: function() {
    this.activity_blur = false;
    ajax = new Ajax();
    ajax.onDone = function(ajaxObj, response) { show('activity_links'); hide('activity_progress'); this.activity_cleared(); }.bind(this);
    ajax.onFail = function(ajaxObj) { show('activity_links'); hide('activity_progress'); this.activity_cleared(); }.bind(this); // fingers crossed
    hide('activity_links');
    show('activity_progress');
    ajax.post('/profile.php', {'clearactivity':'1', 'activityhash': ge('activityhash').value});
    return false;
  },

  //
  // User Interaction
  //

  handle_key_press: function(event) {
    event = event || window.event;
    key_code = event.keyCode || event.which;

    if (key_code == this.KEYS.RETURN) {
      if (ge('edit_activity_text').value != '')
      this.submit_activity_set(ge('edit_activity_text').value);
      return false;
    }
    if (key_code == this.KEYS.ESC) {
      this.hide();
      return false;
    }
    return true;
  },

  KEYS: {BACKSPACE:8,TAB:9,RETURN:13,ESC:27,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46}
}

var historyShown = false;

function getActivityHistory(user_id) {
  ajax = new Ajax();
  ajax.onDone = onGotHistory;
  ajax.onFail = historyAjaxHide;
  historyAjaxProgress();
  ajax.post('/profile.php', {'activityhistory':'1', 'id': user_id});
}

function onGotHistory(ajaxObj, response) {
  historyAjaxShow();
  ge('historyContainer').innerHTML = response;
}

function deleteHistoryItem(item_id) {
  ajax = new Ajax();
  ajax.onDone = onGotHistory;
  ajax.onFail = historyAjaxHide;
  historyAjaxProgress(1);
  ajax.post('/profile.php', {'deletehistoryitem':'1', 'iid': item_id, 'activityhash': ge('activityhash').value});
}

function historyAjaxProgress(onlyshowprogress) {
  if (!onlyshowprogress) {
    hide('historyContainer');
    hide('historyHeader');
  }
  show('historyProgress');
  show('history');
}

function historyAjaxShow() {
  historyShown = true;
  show('history');
  hide('historyProgress');
  show('historyHeader');
  show('historyContainer');
}

function historyAjaxHide() {
  historyShown = false;
  hide('history');
  hide('historyProgress');
  hide('historyHeader');
  hide('historyContainer');
}

// Profile tabs
var tab_masks = {
  'friendsCommon': 0x1,
  'friends'      : 0x2,
  'friendsOnline': 0x4,
  'albums'       : 0x8,
  'videos'       : 0x10,
  'questions'    : 0x20,
  'matches'      : 0x40,
  'notes'        : 0x80,
  'groups'       : 0x100,
  'apps'         : 0x200,
  'personal'     : 0x400,
  'education'    : 0x800,
  'career'       : 0x1000,
  'places'       : 0x2000,
  'military'     : 0x4000,
  'opinions'     : 0x8000,
  'audios'       : 0x10000,
  'wall'         : 0x20000,
  'gifts'        : 0x40000,
  'optional'     : 0x80000,
  'fans'         : 0x100000,
  'idols'        : 0x200000
}

function collapseBox(id, container, dopen, dclose) {
  var box = ge(id);
  if (!box) return;

  var masks = tab_masks;
  var cookie_key = 'closed_tabs';

  var c = geByClass("c", box)[0];
  if (!c) return;
  var newClass = container.parentNode.className == "bOpen" ? "bShut" : "bOpen";
  if (slideToggle(c, 300, function() {
    if (!masks[id]) return;
    var closed_tabs = parseInt(getCookie('remix' + cookie_key));
    if (isVisible(c)) {
      closed_tabs = isNaN(closed_tabs) ? 0 : closed_tabs & ~masks[id];
    } else {
      closed_tabs = isNaN(closed_tabs) ? masks[id] : closed_tabs | masks[id];
    }
    setCookie('remix' + cookie_key, closed_tabs, 360);
  })) {
    container.parentNode.className = newClass;
  }

  return false;
}


function quickReply(id, dopen, dclose, foca){
  var box = ge(id);
  if (!box) return;
  var c = geByClass("r", box)[0];
  if (!c) return;
  if (!isVisible(c))
    slideDown(c, 200, function(){ ge("reply_field").focus(); });
  else
    slideUp(c, 200);
}

// EX FAVE.JS

function addFave() {
  ajax = new Ajax();
  ge('faveProgress').innerHTML = "<IMG SRC='images/upload.gif'>";
  ajax.onDone = function(ajaxObj, response) {
    ge('addToFaves').innerHTML = response;
  }
  ajax.onFail = function(ajaxObj) {
  }
  ajax.post('/fave.php', {'act':'addPerson', 'mid': ge('mid').value, hash: ge('faveHash').value});
}

function deleteFave() {
  ajax = new Ajax();
  ge('faveProgress').innerHTML = "<IMG SRC='images/upload.gif'>";
  ajax.onDone = function(ajaxObj, response) {
    ge('addToFaves').innerHTML = response;
  }
  ajax.onFail = function(ajaxObj) {
  }
  ajax.post('/fave.php', {'act':'deletePerson', 'mid': ge('mid').value, hash: ge('faveHash').value});
}

/* Make Photo From Camera */
var cameraBox = null;
function makeCameraPhoto() {
  if (cameraBox) {
    hideEditPhotoMenu(true);
    cameraBox.show();
    setTimeout(function() { if (ge('flash_camera')) ge('flash_camera').style.visibility = 'visible'; }, 50);
    return;
  }
  cameraBox = new MessageBox({ title: '', width: 299, type: 'POPUP', hideOnClick: false, bodyStyle: 'height: 471px; padding: 0px' });
  cameraBox.removeButtons();
  cameraBox.content('<div id="camera_photo" style="text-align: center; visibility: hidden;"><div style="padding: 160px 0px 30px 0px;">' + profile_install_flash_text + '</div><div class="button_yes" style="width: 180px; margin: auto;"><div id="installFlash" style="padding: 8px 10px; font-size: 12px">' + profile_install_flash_player + '</div></div><div><br/><a href="javascript:hideCameraBox();">Закрыть окно</a></div></div>');
  var so = new SWFObject('swf/CaptureImg.swf?3', 'flash_camera', 300, 471, '9');
  so.addParam('allowNetworking', true);
  so.addVariable('s_save', box_save);
  so.addVariable('s_close', box_close);
  so.addVariable('s_cancel', box_cancel);
  so.addVariable('s_noCamera', profile_no_camera);
  so.addVariable('s_noAccess', profile_no_camera_access);
  so.addVariable('s_setAccess', profile_set_camera_access);
  so.addVariable('s_title', profile_capture_image_title);
  so.addVariable('s_capture', profile_capture_image);
  so.addVariable('s_videoMode', profile_to_video_mode);

  cameraBox.show();
  var installFlash = ge('installFlash');
  if (installFlash) {
    createButton(installFlash, function(){
      location.href = 'http://get.adobe.com/flashplayer/';
    }, 'button');
  }
  Ajax.Post({
    url: 'profileEdit.php',
    query: {page: 'load_new_photo', upload_url: '1'},
    onDone: function(ajaxObj, responseText) {
      so.addVariable('upload_url', encodeURIComponent(responseText));
      var result = so.write('camera_photo');
      if (!result) {
        ge('camera_photo').style.visibility = 'visible';
      } else {
        ge('camera_photo').style.visibility = 'visible';
        setTimeout(function() { if (ge('flash_camera')) ge('flash_camera').style.visibility = 'visible'; }, 50);
      }
    }
  });
}
function hideCameraBox() {
  cameraBox.hide();
}
function changeCameraPhoto(serverData) {
  hideCameraBox();
  try {
    var data = eval("(" + serverData + ")");
    if (data.server && data.photo) {
      var query = {server: data.server, hash: data.hash, photo: data.photo, mid: data.mid, message_code: data.message_code, func: 1, callback: 1};
      Ajax.Send('profileEdit.php?page=done_photo', query, function(ajaxObj, responseText){
        location.reload();
        /*try {
          var script = document.createElement('SCRIPT');
          var head = document.getElementsByTagName('HEAD')[0];
          script.innerHTML = responseText;
          head.appendChild(script);
        } catch (e) {}*/
      });
    } else {
    }
  } catch (error) {
  }
}
/* Menu Edit Photo */
function showEditPhotoMenu(elem) {
  clearTimeout(window.pmTimer);
  var xy = getXY(elem), menu_cont = ge('menu_edit_photo_cont'), elems = menu_cont.getElementsByTagName('*');
  if (!browser.msie) setStyle(menu_cont, 'opacity', 1);
  if (window.pmTimer == undefined) {
    each(elems, function(i, obj) { addEvent(obj, 'mouseover', function() { clearTimeout(window.pmTimer); }); });
  }
  menu_cont.style.left = xy[0] - 5 + 'px';
  menu_cont.style.top = xy[1] - 1 + 'px';
  show(menu_cont);
}
function hideEditPhotoMenu(noFade) {
  if (noFade) {
    hide('menu_edit_photo_cont');
  } else {
    window.pmTimer = setTimeout(function() {
      if (browser.msie) {
        hide('menu_edit_photo_cont');
      } else {
        fadeTo('menu_edit_photo_cont', 200, 0, function() { hide('menu_edit_photo_cont'); });
      }
    }, 500);
  }
}
(function () {
 var deleteBox, photoEditBox, photoSquareBox, cropSuccessBox;
 var onDeleteConfirm = function(hash) {
  var url = 'profileEdit.php?page=delete_photo&hash=' + hash;
  location.href = url;
 }

 window.deletePhoto = function(hash) {
  hideEditPhotoMenu(true);
  if (!deleteBox)
    deleteBox = AlertBox(global_warning, profile_really_delete_photo, function(){onDeleteConfirm(hash);}, { boxType: 'CONFIRM' });
  deleteBox.show();
 }

 window.loadNewPhoto = function() {
  hideEditPhotoMenu(true);
  if (!photoEditBox) {
    var box = new MessageBox({ title: profileEdit_photo_upload_photo, progress: 'load_new_photo_progress' });
    box.removeButtons();
    box.addButton({ label: box_cancel, onClick: function() { box.hide(); }, style: 'button_no' });
    box.addButton({ label: profile_load, onClick: function() {
      if (ge('photo').value != '') {
        show('load_new_photo_progress');
        ge('transport_iframe').innerHTML = '<iframe name="transport"></iframe>';
        ge('editPhoto').submit();
      }
    }});
    var boxHeight = 188;
    boxHeight += browser.mozilla ? -1 : browser.chrome ? 1 : browser.opera ? -4 : browser.safari ? 1 : browser.msie8 ? -5 : -7;
    box.loadContent('profileEdit.php?page=load_new_photo', null, true, 'height: ' + boxHeight + 'px;');
    photoEditBox = box;
  }
  hide('load_new_photo_progress');
  if (ge('messageWrap')) hide('messageWrap');
  if (ge('transport_iframe')) ge('transport_iframe').innerHTML = '<iframe name="transport"></iframe>';
  if (ge('photo')) ge('photo').value = '';
  if (photoEditBox) photoEditBox.show();
 }
 window.editSquarePhoto = function() {
  hideEditPhotoMenu(true);
  if (!photoSquareBox) {
    cropSuccessBox = AlertBox(profile_inf, '<div id="message_crop" style="margin: 0px;">' + profileEdit_small_photo_saved + '</div>');
    if (browser.msie6) {
      setTimeout(function(){
       addCss('css/crop.css');
      }, 0);
    } else {
      addCss('css/crop.css');
    }
    var profilePhoto = ge('profilePhoto').getElementsByTagName('IMG')[0], h = 200;
    if (profilePhoto.offsetHeight > 300) {
      h = 300;
    } else if (profilePhoto.offsetHeight > 200) {
      h = profilePhoto.offsetHeight;
    }
    var box = new MessageBox({ title: profile_edit_small, progress: 'load_edit_progress', width: 420, bodyStyle: 'height: ' + h + 'px' });
    box.removeButtons();
    box.addButton({ label: box_cancel, onClick: function() { box.hide(); }, style: 'button_no' });
    box.addButton({ label: box_save, onClick: function() {
      if (window.crop != window.rCrop) {
        show('load_edit_progress');
        ge('transport_iframe').innerHTML = '<iframe name="transport"></iframe>';
        ge('cropPhoto').submit();
      } else {
        box.hide();
      }
    }});
    if (ge('message_crop')) {
      hide('message_crop');
    }
    box.show();
    box.loadContent('profileEdit.php?page=edit_square_photo', null, true, 'height: ' + h + 'px');
    photoSquareBox = box;
  } else {
    if (ge('message_crop')) {
      hide('message_crop');
    }
    photoSquareBox.show();
  }
 }
})();

var fansBox;
function profileFans(mid, tab, edit, tabbed, titles) {
  var curTab = tab ? 'idols' : 'fans';
  if (!fansBox) {
    if(tabbed) {
      fansBox = new TabbedBox(curTab, [['idols', getLang('profile_idols'), titles[0]], ['fans', getLang('profile_fans'), titles[1]]], {
        title: getLang('profile_fans'),
        width: 478,
        tabStyle: 'height:310px',
        onTab: function(tab, loaded) {
          if(!loaded) {
            fansBox.tabLoadContent(tab, '/profile.php', {act:tab=='idols' ? 'a_get_idols' : 'a_get_fans', mid: mid, offset: 0}, true, 'height:310px;');
            return false;
          }
          if(edit){
            ge('fans_link').innerHTML = '<a href="/fans.php?id='+mid+'&act='+tab+'">'+getLang('Edit')+'</a>'
          }
        }
      });
    } else {
      fansBox = new MessageBox({
        title: getLang('profile_fans'),
        width: 478,
        bodyStyle:'padding:0;height:310px;'
      });
    }
    fansBox.addButton({
      label: getLang('box_close'),
      onClick: function() {fansBox.hide(200);}
    });
    if(edit){
      fansBox.addControlsText('<span id="fans_link"><a href="/fans.php?id='+mid+'&act='+curTab+'">'+getLang('Edit')+'</a></span>');
    }
  }
  if(tabbed) {
    fansBox.loadTab(curTab).show();
  } else {
    fansBox.loadContent('/profile.php', {act:curTab=='idols' ? 'a_get_idols' : 'a_get_fans', mid: mid, offset: 0}, true, 'height:310px;').show();
  }
}
function getFansPage(mid, offset) {
  Ajax.Send('/profile.php?act=a_get_fans', {mid: mid, offset: offset}, function(o, t) {
    var res = eval('('+t+')');
    isFunction(fansBox.tabContent) ? fansBox.tabContent('fans', res.html) : fansBox.content(res.html);
    hide('loadfans');
  });
  show('loadfans');
  return false;
}

function getIdolsPage(mid, offset) {
  Ajax.Send('/profile.php?act=a_get_idols', {mid: mid, offset: offset, more:1}, function(o, t) {
    var res = eval('('+t+')');
    ge('box_idols').innerHTML += res.html;
    ge('more_idols').innerHTML = res.more;
  });
  ge('more_idols').innerHTML = '<img src="/images/upload.gif"/>';
  return false;
}

function acceptRelation(mid, hash) {
  Ajax.Send('/profile.php', {act:'a_accept_relation', mid: mid, hash:hash}, function(o, t) {
    ge('relations').innerHTML = t;
  });
  return false;
}

function declineRelation(mid, hash) {
  Ajax.Send('/profile.php', {act:'a_decline_relation', mid: mid, hash:hash}, function(o, t) {
    ge('relations').innerHTML = t;
  });
  return false;
}

function postWall(to_id, hash, top_id) {
  if (posting_on_wall) {
    return;
  }
  top_id = top_id || '';
  var el = ge('reply_field'+top_id);
  var txt = isFunction(el.getValue) ? el.getValue() : el.value;
  if (!trim(txt).length) {
    el.focus();
    return;
  }
  posting_on_wall = true;
  hide('msg', 'msg_graffiti','msg_photo', 'msg_video', 'msg_audio');
  show('progr2');
  var type = ge('wall_type') ? ge('wall_type').value : 0;
  setTimeout(function(){ge("progr2").src = base_domain+'images/upload.gif'}, 200);
  var params = {act: 'a_post_wall', hash: decodehash(hash), message: txt, to_id: to_id, reply_to:(ge('reply_to'+top_id)||{}).value, top_id: top_id, type: type, old:window.old_wall};
  var callback = function(o, t) {
    var res = eval('('+t+')');
    posting_on_wall = false;
    el.value = '';
    el.phevents = 0;
    hideReplyBox(top_id);
    /*show('msg');*/
    hide('progr2');
    if (window.old_wall) hide('r');
    if (type == 1 && top_id) {
      ge('replies'+top_id).innerHTML = res.html;
      placeholderSetup(el);
    } else {
      ge('fBox2').innerHTML = res.html;
      setupReply();
      if (!top_id) placeholderSetup(el);
    }
  }
  var stop = function(obj, text) {
    hide('progr2');
    ge('reply_field'+top_id).focus();
    posting_on_wall = false;
  }
  var options = {onSuccess: callback, onFail: stop, onCaptchaShow: stop, onCaptchaHide: stop};
  Ajax.Send('wall.php', params, options);
}


function showReplies(to_id, msg_id) {
  Ajax.Send('wall.php', {act:'a_get_replies', msg_id:msg_id, to_id:to_id, old:old_wall}, function(o,t) {
    ge('replies'+msg_id).innerHTML = t;
  });
}

function switchWall(to_id, type) {
  ge('wall_type').value = type;
  Ajax.Send('wall.php', {act:'a_get_wall', type:type, to_id:to_id}, function(o,t) {
    var res = eval('('+t+')');
    ge('fBox2').innerHTML = res.html;
    ge('wall_right_options').innerHTML = res.options;
    setupReply();
  });
}

function replyTo(reply_id, msg_id, to_href, to_name, top_id) {
  top_id = top_id || '';
  ge('reply_to'+top_id).value = msg_id;
  if (!top_id) {
    ge('reply_to_name').innerHTML = '<a href="'+to_href+'">'+to_name+'</a>';
    if (!isVisible('reply_to_title')) slideDown('reply_to_title', 50);
  }
  show('reply_field'+top_id);
  ge('reply_field'+top_id).focus();
}

var hideReplyTO = {};

function showReplyBox(top_id) {
  top_id = top_id || '';
  var el = ge('reply_field'+top_id);
  clearTimeout(hideReplyTO[top_id]);
  if (!el.show) {
    tween = new Fx.Base(el, {duration:50}, null);
    tween.start({height:getSize(el)[1]}, {height:top_id?50:80});
    if (!isVisible('post_submit'+top_id)) slideDown('post_submit'+top_id, 50);
    el.show = true;
  }
  return false;
}

function hideReplyBox(top_id) {
  top_id = top_id || '';
  var el = ge('reply_field'+top_id);
  if (el.show) {
    hideReplyTO[top_id] = setTimeout(function() {
      if (!el.down) {
        animate('reply_field'+top_id, {height:14}, 50);
        slideUp('post_submit'+top_id, 50);
        ge('reply_to'+top_id).value = top_id || 0;
        if (!top_id) {
          if (isVisible('reply_to_title')) slideUp('reply_to_title', 50, function(){ge('reply_to_name').innerHTML = '';});
        }
      }
      el.show = false;
    }, 150);
  }
  return true;
}

function setupReply() {
  each(geByClass('reply_message'), function(i,v) {
    debugLog([v.id, v.value]);
    placeholderSetup(v);
  });
}

onDomReady(setupReply);