
var Community = Class.create({
  initialize: function()
  {
  var userAgent = navigator.userAgent.toLowerCase();
  this.browser =  {
    version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
    safari: /webkit/.test(userAgent),
    opera: /opera/.test(userAgent),
    msie: /msie/.test(userAgent) && !/opera/.test(userAgent),
    mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)
      };
  //alert(userAgent+" "+$H(this.browser).toJSON());
  this.init = new Community.Initializer(this);
  this.geometry = null;
  var t_this = this;
  this.init.add(function() { t_this.geometry = new Community.Geometry(); });
  window.onerror = this.onerror.bind(this);
  this.prop = {};
  this.url = {};
  this.image = {};
  this.sound = {};
  this.is_sound_loaded = false;
  this.acc_title = new Hash();
  this.wr_acc_title = new Hash();
  this.acc_title_user =
        $H({"all":"все","friend":"друзья",
           "good":"хорошие друзья","self":"только владелец"
          });
  this.wr_acc_title_user =
        $H({"community":"участники сообщества","friend":"друзья",
            "good":"хорошие друзья","self":"только владелец"
          });
  this.acc_title_group =
         $H({"all":"все","friend":"участники группы",
             "good":"модераторы группы","self":"только владелец"
           });
  this.wr_acc_title_group =
         $H({"community":"участники сообщества",
             "friend":"участники группы","good":"модераторы группы",
             "self":"только владелец"
           });
  this.acc_order = $H({"all":0,"community":2,"friend":3,"good":4,"self":5});
  this.re_email = new RegExp('^[a-z0-9\._\-]+\@[a-z0-9][a-z0-9_\-]*(\.[a-z0-9_\-]+)*\.([a-z]{2,10})$','i');
  this.re_url = new RegExp('^(http://)?(www\.)?[a-z0-9][a-z0-9_\-]*(\.[a-z0-9_\-]+)*\.([a-z]{2,10})$','i');
  this.re_phone = new RegExp(/^[+]?[\d\- ]*(\(\d+\))?[\d\- ]+$/);
  this.re_date = new RegExp(/^(\d{2})-(\d{2})-(\d{4})$/);
  this.re_time = new RegExp(/^(\d{2}):(\d{2}):(\d{2})$/);
  this.re_mysqldatetime = new RegExp(/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})$/);
  this.re_num = new RegExp(/^[+\-]?\d+$/);
  this.re_fnum = new RegExp(/^[+\-]?\d*\.?\d+$/);
  this.user_title.id = 0;
  },

  set_props: function(props)
  {
  for (var prop in props)
  {
    this.prop[prop] = props[prop];
  }
  if (this.prop.current_user_id == "0")
  {
    this.acc_title = this.acc_title_group;
    this.wr_acc_title = this.wr_acc_title_group;
  }
  else
  {
    this.acc_title = this.acc_title_user;
    this.wr_acc_title = this.wr_acc_title_user;
  }
  },

  set_urls: function(urls)
  {
  for (var url in urls)
  {
    this.url[url] = urls[url];
  }
  },

  set_images: function(images)
  {
  for (var image in images)
  {
    this.image[image] = images[image];
  }
  },

  ajax_failure: function(message)
  {
  throw new Error("Ошибка передачи ajax-запроса: "+message);
  },

  user_title_big: function(title)
  {
  if (!title) return "";
  var vis_title = title.replace("$","");
  if (!vis_title) return "";
  var id = this.user_title.id++;
  var value = '';

  if (title == vis_title) {
    value += '<table class="mb5 av"><tr>';
    value += '<td class="pb5"><a class="info" href="'+this.url.info+'?where='+title+'">';
    value += '<img class="avatar" src="'+community.url.avatar_src+'?id='+title+'&size=3&default=1'; //avatar
    value += '" alt="Информация" title="Информация" />';
    value += '</a></td></tr>';
    value += '<tr><td><a class="nou mr5" id="Community_user_title_'+id+'"';
    value += ' href="'+this.url.blog+'?where='+title+'">'+vis_title+'</a>';
  } else {
    value += '<a class="info" href="'+this.url.info+'?where='+title+'">';
    value += '<img width="11" height="11" src="/i/comm/skin' + community.prop.skin + '/icon_g.gif' ; //this.image.group;
    value += '" alt="Информация" title="Информация" />';
    value += '</a><a class="nou" id="Community_user_title_'+id+'"';
    value += ' href="'+this.url.blog+'?where='+title+'">'+vis_title+'</a>';
  }

  var t_this = this;
  this.init.add(function()
      {
        new Community.Popup('Community_user_title_'+id,
          '',
          { content_provider: Community.User.all.get(title) ? Community.User.all.get(title) : new Community.User(title) }
          );
      });
  return value;
  },

  user_title: function(title,options)
  {
  if (!title) return "";
  if (!options) options = {};
  var vis_title = title.replace("$","");
  var avsize = options.avsize || 2;
  var link = options.link || this.url.blog+'?where='+title;
  if (!vis_title) return "";
  var id = this.user_title.id++;
  var value = '';
  
  if (options.avatar && (title == vis_title)) {
    value += '<table class="mb5 av"><tr>';
    value += '<td><a class="info" href="'+this.url.info+'?where='+title+'">';
    value += '<img class="avatar" src="'+community.url.avatar_src+'?id='+title+'&size='+avsize+'&default=1'; //avatar
    value += '" alt="Информация" title="Информация" />';
    value += '</a></td>';
    value += '<td><a class="nou" id="Community_user_title_'+id+'"';
    value += ' href="'+this.url.blog+'?where='+title+'">'+vis_title+'</a>';
    value += '</td>';
  } else {
    value += '<a class="info" href="'+this.url.info+'?where='+title+'">';
    if (title == vis_title) {
      value += '<img width="11" height="11" src="/i/comm/skin' + community.prop.skin + '/icon_info.gif'; //this.image.info;
    } else {
      value += '<img width="11" height="11" src="/i/comm/skin' + community.prop.skin + '/icon_g.gif' ; //this.image.group;
    }
    value += '" alt="Информация" title="Информация" />';
    value += '</a><a class="nou" id="Community_user_title_'+id+'"';
    value += ' href="'+link+'">'+vis_title+'</a>';
  }

  if (!options.nopopup)
  {
    var t_this = this;
    this.init.add(function()
      {
        new Community.Popup('Community_user_title_'+id,
          options.popup_content ? options.popup_content : '',
          { content_provider: Community.User.all.get(title) ? Community.User.all.get(title) : new Community.User(title) }
          );
      });
  }
  return value;
  },

  user_title_plain: function(title)
  {
  if (!title) return "";
  return title.replace("$","");
  },

  user_title_list: function(title)
  {
  var title_array = title.split(",");
  var t_this = this;
  title_array = title_array.map(function(value) { return t_this.user_title(value); });
  return title_array.join(",");
  },

  current_date: function()
  {
  var date = new Date();
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  if (month < 10) month = "0"+month;
  if (day < 10) day = "0"+day;
  return day+"-"+month+"-"+year;
  },

  is_leap_year: function(year)
  {
  if (year % 4 == 0 && ((year % 100 != 0) || (year % 400 == 0))) return true;
  return false;
  },

  is_valid_date: function(date)
  {
  var date_array = this.re_date.exec(date);
  if (!date_array) return false;
  if (date_array.length != 4) return false;
  date_array.splice(0,1);
  if (date_array[2] < 1910 || date_array[2] > 2036) return false;
  if (date_array[1] < 1 || date_array[1] > 12) return false;
  if (date_array[0] < 1) return false;
  if (date_array[2] == 1 && date_array[0] > 31) return false;
  if (date_array[2] == 2 && this.is_leap_year(date_array[2]) && date_array[0] > 29) return false;
  if (date_array[2] == 2 && !this.is_leap_year(date_array[2]) && date_array[0] > 28) return false;
  if (date_array[2] == 3 && date_array[0] > 31) return false;
  if (date_array[2] == 4 && date_array[0] > 30) return false;
  if (date_array[2] == 5 && date_array[0] > 31) return false;
  if (date_array[2] == 6 && date_array[0] > 30) return false;
  if (date_array[2] == 7 && date_array[0] > 31) return false;
  if (date_array[2] == 8 && date_array[0] > 31) return false;
  if (date_array[2] == 9 && date_array[0] > 30) return false;
  if (date_array[2] == 10 && date_array[0] > 31) return false;
  if (date_array[2] == 11 && date_array[0] > 30) return false;
  if (date_array[2] == 12 && date_array[0] > 31) return false;
  return true;
  },

  is_valid_time: function(time)
  {
  var time_array = this.re_time.exec(time);
  if (!time_array) return false;
  if (time_array.length != 4) return false;
  time_array.splice(0,1);
  if (time_array[0] > 23 || time_array[0] < 0) return false;
  if (time_array[1] > 59 || time_array[0] < 0) return false;
  if (time_array[2] > 59 || time_array[0] < 0) return false;
  return true;
  },

  filter_body: function(string)
  {
   if (!string) return "";
   return string.escapeHTML()
          .gsub("\"","&quot;")
          .gsub("\'","&#39;")
          .gsub("\\\\","&#92;")
          .gsub("\t","&nbsp;&nbsp;&nbsp;")
          .gsub(/\r?\n/,"<br />");
  },

  filter_body_textarea: function(string)
  {
   if (!string) return "";
   return this.filter_body(string).gsub("<br />","&#10;");
  },

  unfilter_body: function(string)
  {
   if (!string) return "";
   return string.gsub("<br />","\n")
                .gsub("&nbsp;"," ")
                .gsub("&#92;","\\")
                .gsub("&#39;","\'")
                .gsub("&quot;","\"")
                .unescapeHTML();
  },

  update_wr_acc_select: function(rd_id,wr_id)
  {
  var rd_acc = $F(rd_id);
  var wr_acc = $F(wr_id);
  var value;
  var t_this = this;
  if ($(wr_id).selectObj) $(wr_id).selectObj.remove();
  this.wr_acc_title.each(function(pair)
        {
    if (t_this.acc_order.get(pair.key) < t_this.acc_order.get(rd_acc)) return;
    value += '<option value="'+pair.key+'"';
    if (pair.key == wr_acc) value=value+" selected";
    value += '>'+pair.value+'</option>';
        }
       );
  $(wr_id).update(value);
  makeSelectBox("#"+wr_id);
  },

  update_wr_acc_select2: function(rd_id,wr_id)
  {
  var rd_acc = $F(rd_id);
  var wr_acc = $F(wr_id);
  var value;
  var t_this = this;
  if ($(wr_id).selectObj) $(wr_id).selectObj.remove();
  value += '<option value="-1"';
  if (wr_acc == -1) value=value+" selected";
  value += '>--без изменений--</option>';
  this.wr_acc_title.each(function(pair)
        {
    if (t_this.acc_order.get(pair.key) < t_this.acc_order.get(rd_acc)) return;
    value += '<option value="'+pair.key+'"';
    if (pair.key == wr_acc) value=value+" selected";
    value += '>'+pair.value+'</option>';
        }
       );
  $(wr_id).update(value);
  makeSelectBox("#"+wr_id);
  },

  hide: function(element)
  {
  $(element).setStyle({'display':'none'});
  },

  show: function(element)
  {
  $(element).setStyle({'display':'block'});
  },

  onerror: function(message,url,strnum)
  {
  this.debug("Ошибка JavaScript в файле "+url+" в строке "+strnum+": "+message);
  },

  debug: function(string)
  {
  var debug_element = $("Community_Debug");
  if (debug_element)
  {
    new Insertion.Bottom(debug_element,string+'<br />');
    debug_element.show();
  }
  if(typeof console != 'undefined' && community.browser.mozilla) {
	console.log.apply('', arguments);
  }  
  //else alert(string);
  },

  //This function is used in survey_answer module
  $RF: function(el)
  {
  el = $(el);
  if (!el) return null;
  if (el.disabled) return null;
  var val;
  if(el.type && el.type.toLowerCase() == 'radio')
  {
    var checked = $(el.form).getInputs('radio',el.name).find(function(re) {return re.checked;});
    val = checked ? checked.value : null;
    if (val == "0") val = null;
    return val;
  }
  if (el.type && el.type.toLowerCase() == 'checkbox') 
  {
    if (!el.name) return (el.checked ? "1" : "0");
    var checked = $(el.form).getInputs('checkbox',el.name);
    val = checked.inject(new Array,function(acc,value)
            {
              if (value.checked) acc.push(value.value);
              return acc;
            }
            );
    return (val.length > 0) ? val.join(",") : null;
  }
  if (el.tagName.toLowerCase() == 'select' && el.value == "0") return null;
  val = $F(el);
  if (el.multiple) { return (val.length > 0) ? val.join(",") : null; }
  if (val == "") return null;
  return val;
  },

  convert_smiles: function(message,max_smiles)
  {
	var j = 0;
    if (!max_smiles) max_smiles = 100;
    for (var i=0; i<game_linker.smiles.length; i++)
    {
      while(message.indexOf(':'+game_linker.smiles[i]+':') >= 0)
      {
        message = message.replace(':'+game_linker.smiles[i]+':','<img src="'+game_linker.smiles_url()+game_linker.smiles[i]+'.gif" width="'+game_linker.smiles_x[i]+'" height="'+game_linker.smiles_y[i]+'" />');
        if (++j >= max_smiles) break;
      }
      if (j >= max_smiles) break;
    }
    return message;
  },

  get_smile_img: function(smile)
  {
    for (var i=0;i<game_linker.smiles.length;i++)
    {
      if (game_linker.smiles[i] == smile)
      {
        return '<img src="'+game_linker.smiles_url()+game_linker.smiles[i]+'.gif" width="'+game_linker.smiles_x[i]+'" height="'+game_linker.smiles_y[i]+'" />';
      }
    }
    return '';
  },

  cut_body: function(text,maxlength) {
    var pattern = new RegExp('<[^>]+>','g');
    var tag_pattern = new RegExp('^<(span|p|a|em|strong|object|embed|param)[^a-zA-Z]');
    var imgtag_pattern = new RegExp('^<(img)[^a-zA-Z]');

    var closetag_pattern = new RegExp('^</(span|p|a|em|strong)[^a-zA-Z]');
    var opened_tags = new Array();

    var index = 0;
    var count = 0;
    var result = '';
    var cutted = false;
    var tag = pattern.exec(text);
    while (tag)
    {
      //if (count >= maxlength) { cutted = true; break; }
      tag = String(tag);

      //Adding text
      var text_chunk = text.substring(index,pattern.lastIndex-tag.length);
      var final_text_chunk = this._get_next_text_chunk(count,text_chunk,maxlength);
      //alert(tag+' '+index+' '+text_chunk+' '+final_text_chunk);
      count += final_text_chunk.length;
      result += final_text_chunk;
      if (text_chunk.length != final_text_chunk.length) { cutted = true; break; }

      //Adding tag
      result += tag;
      var tag_pattern_match = tag_pattern.exec(tag);
      if (tag_pattern_match) opened_tags.push(tag_pattern_match[1]);
      else
      {
        var closetag_pattern_match = closetag_pattern.exec(tag);
        if (closetag_pattern_match && closetag_pattern_match[1] == opened_tags[opened_tags.length-1])
        {
          opened_tags.pop();
        }
      }
      index += text_chunk.length+tag.length;

      if (imgtag_pattern.test(tag)) count += 50;
      //Search next
      tag = pattern.exec(text);
    }
    if (!cutted)
    {
      //Adding last text
      var text_chunk = text.substring(index);
      var final_text_chunk = this._get_next_text_chunk(count,text_chunk,maxlength);
      count += final_text_chunk.length;
      result += final_text_chunk;
      if (text_chunk.length != final_text_chunk.length) cutted = true;
    }

    if (result.length < text.length)
    {
      result += '...';
    }

    if (cutted)
    {
      for (var i=opened_tags.length-1;i>=0;i--)
      {
        result += '</'+opened_tags[i]+'>';
      }
    }

    //alert(result);
    return result;
  },


  _get_next_text_chunk: function(count,text_chunk,maxlength)
  {
    var space_pattern = new RegExp('\\s');

    if (count >= maxlength) return '';

    if (count+text_chunk.length > maxlength)
    {
      var last_index = maxlength-count;
      var final_text_chunk = text_chunk.substring(0,last_index);
      while (last_index < text_chunk.length && !space_pattern.test(text_chunk.charAt(last_index)))
      {
        final_text_chunk += text_chunk.charAt(last_index);
        last_index++;
      }
      return final_text_chunk;
    }
    return text_chunk
  },

  show_cut: function(a_element)
  {
    a_element.style.display = 'none';
    a_element.nextSibling.style.display = '';
  },

  show_pages: function(page,pages,options)
  {
    document.write(community.show_pages_text(page,pages,options));
  },

  show_pages_text: function(page,pages,options)
  {
    var value = '';
    var f = 0;
    page = Number(page);
    pages = Number(pages);
	if (pages <= 1) return value;
    if (!options) options = {};
	var show = options.show || 4;
	value += '<ul class="pager">';
	if (options.tworows) value += 'Страницы:<br />';
	else value += '<li class="next">Страницы:</li>';
    if (!page) page = 0;
    var page_label = options.page_label || 'page';
    if (page > 0)
    {
     value += '<li class="next"><a href="#" onclick="community.go_to_page('+(page-1)+');return false;">';
     value += '&lt;&lt;</a></li>';
    }
    for (var i=0;i<pages;i++)
    {
      if ((i > 0) && (i < page-show))
      {
        if (f < 1) { value += '<li>...</li>'; f = 1; }
        continue;
      }
      if ((i < pages-1) && (i > page+show))
      {
        if (f < 2) { value += '<li>...</li>'; f = 2; }
        continue;
      }
      if (i!=page)
      {
        value += '<li><a href="#" onclick="community.go_to_page('+i+');return false;">';
        value += (i+1)+'</a></li>';
      }
      else
      {
        value += '<li class="current"><a href="#" onclick="return false;">'+(i+1)+'</a></li>';
      }
    }
    if (page < pages-1)
    {
      value += '<li class="next"><a href="#" onclick="community.go_to_page('+(page+1)+');return false;">';
      value += '&gt;&gt;</a></li>';
    }
    value += '</ul><div class="clear"></div>';
    return value;
  },

  go_to_page: function(page)
  {
    var location = document.location.href;
    if (location.indexOf("page=") == -1) location += "&page="+page;
    else location = location.replace(/page=\d+/,"page="+page);
    if (new RegExp(/[\?&]check=([^&]*)/).test(location))
    {
       location = location.replace(/([\?&])cmd=([^&]*)/,'&');
       location = location.replace(/([\?&])check=([^&]*)/,'&');
       location = location.replace(/&{2,}/g,'&');
       location = location.replace(/\?&/,'?');
       location = location.replace(/[\?&]$/,'');
    }
    if (new RegExp(/^([^?]+)&/).test(location))
    {
       location = location.replace(/&/,'?');
    }
    document.location.href=location;
  },

  editor_fonts: [ "", "andale mono,times;", "arial,helvetica,sans-serif", "arial black,avant garde",
                  "book antiqua,palatino", "comic sans ms,sans-serif", "courier new,courier",
                  "georgia,palatino", "helvetica", "impact,chicago", "symbol",
                  "tahoma,arial,helvetica,sans-serif", "terminal,monaco", "times new roman,times",
                  "trebuchet ms,geneva", "verdana,geneva"
                ],

  editor_fonts_names: [ "", "Andale Mono", "Arial", "Arial Black", "Book Antiqua", "Comic Sans MS", "Courier New",
                        "Georgia", "Helvetica", "Impact", "Symbol", "Tahoma", "Terminal", "Times New Roman",
                        "Trebuchet MS", "Verdana"
                      ],

  editor_fontsizes: [ "", "9px", "11px", "13px", "15px", "17px", "19px", "21px" ],
  editor_fontsizes_names: [ "", "1 (9px)", "2 (11px)", "3 (13px)", "4 (15px)", "5 (17px)", "6 (19 px)", "7 (21px)" ],

  moods: [ { string: "раздосадованное", smile: "mad" }, { string: "грустное", smile: "cry" },
           { string: "мечтательное", smile: "ponder" }, { string: "радостное", smile: "yahoo" },
           { string: "задумчивое", smile: "shuffle" }, { string: "творческое", smile: "writer" },
           { string: "шокированное", smile: "wow" }

//           { string: "ангельское", smile: ":angel:" }, { string: "взбешенное", smile: ":badevil:" },
//           { string: "циничное", smile: ":badtease:" }, { string: "нормальное", smile: ":ok:" },
//           { string: "несчастное", smile: ":plak:" }, { string: "злое", smile: ":evil:" },
//           { string: "грустное", smile: ":cry:" }, { string: "мечтательное", smile: ":ponder:" },
//           { string: "сумасшедшее", smile: ":kz:" }, { string: "игривое", smile: ":gy:" },
//           { string: "насмешливое", smile: ":haha:" }, { string: "веселое", smile: ":laught:" },
//           { string: "влюбленное", smile: ":boylove:" }, { string: "радостное", smile: ":yahoo:" },
//           { string: "испуганное", smile: ":strah:" }, { string: "беззаботное", smile: ":tooth:" },
//           { string: "сонное", smile: ":sleep:" }, { string: "скучное", smile: ":yawn:" },
//           { string: "смущенное", smile: ":confused:" }, { string: "счастливое", smile: ":ura:" },
//           { string: "задумчивое", smile: ":shuffle:" }, { string: "творческое", smile: ":writer:" },
//           { string: "боевое", smile: ":horseman:" }, { string: "шокированное", smile: ":wow:" },
//           { string: "раздосадованное", smile: ":mad:" }
  ],

  get_mood_by_smile: function(smile)
  {
    for (var i=0;i<community.moods.length;i++)
    {
      if (community.moods[i].smile == smile) return community.moods[i];
    }
    return null;
  },

  soundloaded: function()
  {
    this.is_sound_loaded = true;
    if (!Number(this.prop.sounds)) return;
    this.sound.letter = soundManager.createSound({
     id: 'letter_sound',
     url: '/audio/message.mp3',
     volume: 100,
     autoPlay: false
    });
    var t_this = this;
    this.init.add_unload(function()
      {
        t_this.sound.letter.destruct(); t_this.sound.letter = null;
      });
  },

  word_end: function(num)
  {
    if (num > 10 && num < 20) return "ов";
    if ((num % 10) == 0) return "ов";
    if ((num % 10) == 1) return "";
    else if ((num % 10) < 5) return "а";
    else return "ов";
  },

  word_end2: function(num)
  {
    if (num > 10 && num < 20) return "ей";
    if ((num % 10) == 0) return "ей";
    if ((num % 10) == 1) return "ень";
    else if ((num % 10) < 5) return "я";
    else return "ей";
  },

  translit: function(text)
  {
    var pattern = new RegExp('<[^>]+>','g');
    var result = '';
    var index = 0;
    var tag = pattern.exec(text);
    while(tag)
    {
      tag = String(tag);

      var text_chunk = text.substring(index,pattern.lastIndex-tag.length);
      index += text_chunk.length+tag.length;

      result += community.translit_convert_string(text_chunk);
      result += tag;

      tag = pattern.exec(text);
    }
    var text_chunk = text.substring(index);
    result += community.translit_convert_string(text_chunk);
    return result;
  },

  translit_convert_string: function(string)
  {
    var string_array = string.split(' ');
    for (var i=0;i<string_array.length;i++)
    {
      if (string_array[i].indexOf("http://") < 0 && string_array[i].indexOf("@") < 0 &&
          string_array[i].indexOf("www.") < 0 &&
          !(string_array[i].charAt(0)==":" && string_array[i].charAt(string_array[i].length-1)==":")) 
      {
        string_array[i] = community.translit_convert_word(string_array[i]);
      }
    }
    return string_array.join(' ');
  },

  translit_convert_word: function(word)
  {
    var en_ru = [["shh","SHH","sh","SH","ch","CH","jo","JO","zh","ZH","je","JE","ju","JU","ja","JA","sx","SX","j/o","J/O","j/e","J/E","a","A","b","B","v","V","g","G","d","D","e","E","z","Z","i","I","j","J","k","K","l","L","m","M","n","N","o","O","p","P","r","R","s","S","t","T","u","U","f","F","x","X","h","H","c","C","w","W","##","#","y","Y","''","'"],["щ","Щ","ш","Ш","ч","Ч","ё","Ё","ж","Ж","э","Э","ю","Ю","я","Я","сх","сх","йо","ЙО","йе","йе","а","А","б","Б","в","В","г","Г","д","Д","е","Е","з","З","и","И","й","Й","к","К","л","Л","м","М","н","Н","о","О","п","П","р","Р","с","С","т","Т","у","У","ф","Ф","х","Х","х","Х","ц","Ц","щ","Щ","Ъ","ъ","ы","Ы","Ь","ь"]];

    for (var i=0;i<en_ru[0].length;++i) 
    {
      while(word.indexOf(en_ru[0][i])>=0) word = word.replace(en_ru[0][i],en_ru[1][i]);
    }
    return word;
  },

  cmp_times: function(time1,time2)
  {
    var time1_array = this.re_mysqldatetime.exec(time1);
    if (!time1_array) return 0;
    if (time1_array.length != 7) return false;
    time1_array.splice(0,1);
    var time2_array = this.re_mysqldatetime.exec(time2);
    if (!time2_array) return 0;
    if (time2_array.length != 7) return false;
    time2_array.splice(0,1);
    var time1_num = Number(time1_array.join(""));
    var time2_num = Number(time2_array.join(""));
    if (time1_num > time2_num) return 1;
    if (time1_num < time2_num) return -1;
    return 0;
  },

  submit_form: function(params,action)
  {
    var form = document.createElement('form');
    form.setAttribute("method","POST");
    if (action) form.setAttribute("action",action);
    for (var name in params)
    {
      var element = document.createElement("input");
      element.setAttribute("type","hidden");
      element.setAttribute("name",name);
      element.setAttribute("value",params[name]);
      form.appendChild(element);
    }
    document.body.appendChild(form);
    form.submit();
  }

});

//--------------------------------------------------------------------------------------------------

//This class is based on jQuery 1.3.1 ready function
Community.Initializer = Class.create({
  initialize: function(community)
  {
  this.community = community;
  this.done = 0;
  this.functions = new Array();
  this.functions_unload = new Array();
  var t_this = this;
  if (document.addEventListener)
  { //Mozilla,Opera,Safari etc...
    document.addEventListener("DOMContentLoaded", function(){
      document.removeEventListener("DOMContentLoaded",arguments.callee,false);
      t_this.init();
    },false);
  }
  else if (document.attachEvent) 
  { //IE
    document.attachEvent("onreadystatechange", function(){
      if (document.readyState == "complete")
      {
        document.detachEvent("onreadystatechange",arguments.callee);
        t_this.init();
      }
    });
    if (document.documentElement.doScroll && (typeof window.frameElement === "undefined"))
    {
      (function(){
        if (t_this.done) return;
        try { document.documentElement.doScroll("left"); }
        catch(error) {
          setTimeout(arguments.callee,0);
          return;
        }
        t_this.init();
      })();
    }
  }
  window.onload = this.init.bind(this); //fallback
  window.onunload = this.uninit.bind(this);
  },

  add: function(fun)
  {
  if (this.done) setTimeout(fun,10);
  else this.functions.push(fun);
  },

  add_unload: function(fun)
  {
  this.functions_unload.push(fun);
  },

  init: function()
  {
  if (this.done) return;
  this.done = 1;
  window.onload = null;
  this.functions.each(function(fun) { fun(); });
  },

  uninit: function()
  {
  window.onunload = null;
  this.functions_unload.each(function(fun) { fun(); });
  }

});

//-------------------------------------------------------------------------------

Community.BindInputWithButton = Class.create({
  initialize: function(input,button)
  {
  this.input = $(input);
  this.button = $(button);
  var t_this = this;
  this.bind = function(event)
    {
      if (event.keyCode==13)
      {
        if (document.createEvent)
        {
          var evObj = document.createEvent('MouseEvents');
          evObj.initEvent( 'click', true, true);
          if (t_this.button) t_this.button.dispatchEvent(evObj);
        }
        else
        {
          if (t_this.button) t_this.button.fireEvent('onclick');
        }
      }
      return true;
    };
  this.input.observe("keydown",this.bind);
  community.init.add_unload(this.clean.bind(this));
  },

  stop: function()
  {
  if (this.input) this.input.stopObserving("keydown",this.bind);
  },

  clean: function()
  {
  this.stop();
  this.input = null;
  this.button = null;
  }

});

//--------------------------------------------------------------------------------------

//Attention: If you use callback in options, this class will not work as expected if you use more than
//1 elements in the first massive! (That's a known bug for now)
Community.Pages = Class.create({
  initialize: function(elements,curpage,maxpage,url,where,options)
  {
  if (!options) options={};
  this.id = Community.Pages.id++;
  this.curpage = Number(curpage);
  this.maxpage = Number(maxpage);
  this.url = url;
  this.where = where;
  this.add_params = options.add_params || "";
  this.callback = options.callback || null;
  this.page_label = options.page_label || "page";
  this.nowhere = options.nowhere || false;
  this.elements = $A(elements);
  if (this.maxpage <= 1)
  {
    this.elements.invoke('update','');
    return;
  }
  var f = 0;

  var value = '<ul class="pager"><li class="next">Страницы:</li>';
  if (!this.curpage) this.curpage = 0;
  if (this.curpage > 0)
  {
    value += '<li class="next"><a';
    if (this.callback) value += ' href="#" id="'+this.previous_id()+'" onclick="return false;"';
    else value += ' href="'+this.url+'?';
    if (!this.nowhere) value += 'where='+this.where+'&';
    value += this.page_label+'='+(this.curpage-1)+(this.add_params ? ('&'+this.add_params) : "")+'"';
    value += '>&lt;&lt;</a></li>';
  }

  for (var i=0;i<this.maxpage;i++)
  {
    if ((i > 0) && (i < this.curpage-4))
    {
      if (f < 1) { value += '<li>...</li>'; f = 1; }
      continue;
    }
    if ((i < this.maxpage-1) && (i > this.curpage+4))
    {
      if (f < 2) { value += '<li>...</li>'; f = 2; }
      continue;
    }
    if (i!=this.curpage)
    {
      value += '<li><a';
      if (this.callback) value += ' href="#" id="'+this.page_id(i)+'" onclick="return false;"';
      else value += ' href="'+this.url+'?';
      if (!this.nowhere) value += 'where='+this.where+'&';
      value += this.page_label+'='+i+(this.add_params ? ('&'+this.add_params) : "")+'"';
      value += '>'+(i+1)+'</a></li>';
    }
    else
    {
      value += '<li class="current"><a href="#" onclick="return false;">'+(i+1)+'</a></li>';
    }
  }
  if (this.curpage < this.maxpage-1)
  {
    value += '<li class="next"><a';
    if (this.callback) value += ' href="#" id="'+this.next_id()+'" onclick="return false;"';
    else value += ' href="'+this.url+'?';
    if (!this.nowhere) value += 'where='+this.where+'&';
    value += this.page_label+'='+(this.curpage+1)+(this.add_params ? ('&'+this.add_params) : "")+'"';
    value += '>&gt;&gt;</a></li>';
  }
  value += "</ul><div class='clear'><!-- --></div>";

  if (this.callback && this.elements.length > 1)
  {
    throw new Error("Невозможно создать динамический элемент Pages для более чем одного контейнера");
  }
  this.elements.invoke('update',value);

  if (this.callback)
  {
    var t_this = this;
    if (this.curpage > 0)
    {
      $(this.previous_id()).observe("click",function(event)
      {
        t_this.callback(t_this.curpage - 1);
      });
    }
    if (this.curpage < this.maxpage-1)
    {
      $(this.next_id()).observe("click",function(event)
      {
        t_this.callback(t_this.curpage + 1);
      });
    }
    $R(0,this.maxpage-1).each(function(page,index)
    {
      if ($(t_this.page_id(index)))
      {
        $(t_this.page_id(index)).observe("click",function(event)
        {
          t_this.callback(index);
        });
      }
    });
    community.init.add_unload(this.clean.bind(this));
  }
  },

  clean: function()
  {
  if (this.callback)
  {
    this.stop();
    this.callback = null;
  }
  this.elements = null;

  },

  stop: function()
  {
  if (this.callback)
  {
    var t_this = this;
    var previous_element = $(this.previous_id());
    if (this.curpage > 0 && previous_element) previous_element.stopObserving("click");
    var next_element = $(this.next_id());
    if (this.curpage < this.maxpage-1 && next_element) next_element.stopObserving("click");
    $R(0,this.maxpage-1).each(function(page,index)
    {
      var page_element = $(t_this.page_id(index));
      if (index!=t_this.curpage && page_element)
      {
        page_element.stopObserving("click");
      }
    });
  }
  },

  previous_id: function() { return "Community_Pages_Previous_"+this.id; },
  next_id: function() { return "Community_Pages_Next_"+this.id; },
  page_id: function(index) { return "Community_Pages_Page_"+index+"_"+this.id; }

});

Community.Pages.id = 0;
//--------------------------------------------------------------------------------------

Community.Hint = Class.create({
  initialize: function(element,hint_text)
  {
  this.id = Community.Hint.id++;
  this.element = $(element);
  this.hint_text = hint_text || "";
  if (!this.element) throw new Error("Отсутствует элемент, для которого нужно показывать подсказку (hint)!");
  this.hint_element = new Element('div',{'class':'hint'}).
        setStyle({'display':'none'}).
        update(this.html());
  document.body.appendChild(this.hint_element);
  var dimensions = this.hint_element.getDimensions();
  this.hint_height = dimensions.height;
  this.hint_width = dimensions.width;
  this.element.observe("mouseout",this.handleMouseOut.bindAsEventListener(this));
  this.element.observe("mouseover",this.handleMouseOver.bindAsEventListener(this));
  community.init.add_unload(this.clean.bind(this));
  },

  clean: function()
  {
  this.stop();
  this.element = null;
  this.hint_element = null;
  },

  stop: function()
  {
  if (this.element)
  {
    this.element.stopObserving("mousemove");
    this.element.stopObserving("mouseover");
    this.element.stopObserving("mouseout");
  }
  },

  html: function()
  {
  var value='<table cellpadding="1" cellspacing="0"><tbody>';
  value=value+'<tr><td align="left" nowrap="nowrap"><small>'+this.hint_text+'</small></td></tr>';
  value=value+'</tbody></table>';
  return value;
  },

  handleMouseOver: function(event)
  {
  this.set_pos(event);
  this.hint_element.setStyle({'display':'block'});
  this.element.observe("mousemove",this.handleMouseMove.bindAsEventListener(this));
  },

  handleMouseOut: function(event)
  {
  this.hint_element.setStyle({'display':'none'});
  this.element.stopObserving("mousemove");
  },

  handleMouseMove: function(event)
  {
  if (this.hint_element.getStyle('display') == 'block') this.set_pos(event);
  else this.element.stopObserving("mousemove");
  },

  set_pos: function(event)
  {
  var event_x = event.pointerX();
  var event_y = event.pointerY();
  var dimensions = $(document.body).getDimensions();
  var body_height = community.geometry.client_height();
  var body_width = community.geometry.client_width();
  var x,y;
  if (event_x+this.hint_width+10 >= body_width) x = event_x-this.hint_width-10;
  else x = event_x+10;
  if (event_y+this.hint_height+20 >= body_height) y = event_y-this.hint_height-20;
  else y = event_y+20;
  this.hint_element.setStyle({left:x+"px",top:y+"px"});
  }
});

Community.Hint.id = 0;

//--------------------------------------------------------------------------------------

Community.Window = Class.create({
  initialize: function(options)
  {
  if (!options) options = {};
  this.id = Community.Window.id++;
  this.title = options.title || '(Без заголовка)';
  this.content = options.content || '';
  this.width = options.width || 0;
  this.height = options.height || 0;
  this.top = options.top || 100;
  this.left = options.left || 150;
  this.ok_button = options.ok_button ? true : false;
  this.on_ok = options.on_ok || null;
  this.on_close = options.on_close || null;
  this.on_before_close = options.on_before_close || null;
  this.ok_button_text = options.ok_button_text || "Ок";
  if (options.buttons) this.buttons = $A(options.buttons);
  else this.buttons = new Array();
  if (options.container)
  {
    this.container = $(options.container);
    if (!this.container) throw new Error("Отсутствует контейнер для окна!");
    this.window_element = new Element('div').setStyle({'display':'none'});
    if (this.width) this.window_element.setStyle({width:this.width+"px"});
    if (this.height) this.window_element.setStyle({height:this.height+"px"});
    this.container.appendChild(this.window_element);
  }
  else
  {
    this.window_element = new Element('div',{'class':'window'}).setStyle({'display':'none'});
    if (this.width) this.window_element.setStyle({width:this.width+"px"});
    if (this.height) this.window_element.setStyle({height:this.height+"px"});
    document.body.appendChild(this.window_element);
  }
  this.display();
  community.init.add_unload(this.clean.bind(this));
  },

  clean: function()
  {
  this.clear();
  this.window_element = null;
  this.container = null;
  },

  window_close_id: function() { return "Community_Window_Close_"+this.id; },
  window_rolldown_id: function() { return "Community_Window_Rolldown_"+this.id; },
  window_content_id: function() { return "Community_Window_Content_"+this.id; },
  window_ok_id: function() { return "Community_Window_Ok_"+this.id; },
  window_header_id: function() { return "Community_Window_Header_"+this.id; },
  window_button_id: function(index) { return "Community_Window_Button_"+index+"_"+this.id; },
  window_content_id: function() { return "Community_Window_Content_"+this.id; },

  display: function()
  {
  this.window_element.update(this.html());
  $(this.window_close_id()).observe("click",this.close.bindAsEventListener(this));
  $(this.window_rolldown_id()).observe("click",this.rolldown.bindAsEventListener(this));
  if (this.ok_button && this.on_ok)
  {
    $(this.window_ok_id()).observe("click",this.on_ok);
  }
  var t_this = this;
  this.buttons.each(function(button,index)
    {
      if (button.callback) $(t_this.window_button_id(index)).observe("click",button.callback);
    });
  if (!this.container)
  {
    this.dragger = new Community.Dragger(this.window_header_id(),{on_drag:this.drag.bind(this)});
  }
  },

  html: function()
  {
  var value = '';
  //if (!this.container && community.browser.msie && community.browser.version < 7)
  //{
    //value += '<iframe class="iframe_window"></iframe>';
  //}
  value += '<table';
  if (this.width) value += ' style="width:'+this.width+'px;"';
  value += '>';
  value += '<tr><td style="text-align:left;" id="'+this.window_header_id()+'"><div class="fr">';
  value += '<img style="margin:10px 10px 0 0;" id="'+this.window_rolldown_id()+'" src="/i/comm/skin' + community.prop.skin + '/window_fold.gif" alt="Свернуть" title="Свернуть" />';
  value += '<img style="margin:10px 10px 0 0;" id="'+this.window_close_id()+'" src="/i/comm/skin' + community.prop.skin + '/icon_delete.gif" alt="Закрыть" title="Закрыть" />';
  value += '</div><h3 class="m0" style="padding:8px 10px 6px 10px;cursor: move;">'+this.title+'</h3></td>';
  
  value += '</tr><tr><td colspan="3">'; //community.image.close
  value += '<table class="innerwindow" id="'+this.window_content_id()+'"><tbody><tr><td id="'+this.window_content_id()+'">';
  value += this.content;
  value += '</td></tr>';
  var numbuttons = this.buttons.length + (this.ok_button ? 1 : 0);
  if (numbuttons)
  {
    value += '<tr><td colspan="'+numbuttons+'"><div class="oh pb20 mt5">';
    if (this.ok_button) value += '<input class="button mr5" type="button" value="'+this.ok_button_text+'" id="'+this.window_ok_id()+'" style="cursor: pointer"></input>';
    var t_this = this;
    this.buttons.each(function(button,index)
      {
        //if (t_this.ok_button || index>0) value += '&nbsp;';
        value += '<input class="button mr10" type="button" value="'+button.text+'" id="'+t_this.window_button_id(index)+'" style="cursor: pointer" />';
      });
    value += '</div></td></tr>';
  }
  value += '</tbody></table></td></tr></table>';

  return value;
  },

  update_title: function(title)
  {
  this.stop_observing();
  this.title = title || "(Без заголовка)";
  this.display();
  return this;
  },

  update: function(content)
  {
  this.stop_observing();
  this.content = content || "";
  this.display();
  return this;
  },

  show: function()
  {
  if (!this.container)
  {
    this.window_element.setStyle({
      top:(this.top+community.geometry.client_scroll_y())+"px",
      left:(this.left+community.geometry.client_scroll_x())+"px",
      'display':'block'
              });
  }
  else this.window_element.setStyle({'display':'block'});
  return this;
  },

  hide: function()
  {
  if (!this.container && this.window_element) this.window_element.setStyle({'display':'none'});
  else if (this.window_element) this.window_element.setStyle({'display':'none'});
  return this;
  },

  close: function(event)
  {
  if (this.on_before_close && typeof this.on_before_close == "function")
  {
    if (!this.on_before_close()) return;
  }
  this.hide();
  if (this.on_close && typeof this.on_close == "function") this.on_close();
  },

  rolldown: function(event)
  {
  $(this.window_content_id()).toggle();
  var rolldown_image = $(this.window_rolldown_id());
  if (rolldown_image.readAttribute("alt") == "Свернуть")
  {
    rolldown_image.writeAttribute({"alt":"Развернуть","title":"Развернуть","src":"/i/comm/skin" + community.prop.skin + "/window_fold_up.gif"});
  }
  else
  {
    rolldown_image.writeAttribute({"alt":"Свернуть","title":"Свернуть","src":"/i/comm/skin" + community.prop.skin + "/window_fold.gif"});
  }
  },

  clear: function()
  {
  this.hide();
  this.stop_observing();
  if (this.window_element) this.window_element.update("");
  },

  stop_observing: function() { 
  var close_element = $(this.window_close_id());
  if (close_element) close_element.stopObserving("click");
  var rolldown_element = $(this.window_rolldown_id());
  if (rolldown_element) rolldown_element.stopObserving("click");
  var ok_element = $(this.window_ok_id());
  if (ok_element) ok_element.stopObserving("click");
  var t_this = this;
  this.buttons.each(function(button,index)
    {
      var button_element = $(t_this.window_button_id(index));
      if (button_element)
      {
        button_element.stopObserving("click");
      }
    });
  if (this.dragger) { this.dragger.clean(); this.dragger = null; }
  },

  ok_button_element: function()
  {
  return $(this.window_ok_id());
  },


  drag: function(event)
  {
  this.window_element.setStyle({left:(event.pointerX() - this.dragger.drag_delta_x) + "px",
              top:(event.pointerY() - this.dragger.drag_delta_y) + "px"
            });
  },

  get_content_element: function()
  {
    return $(this.window_content_id());
  }

});

Community.Window.id = 0;

//--------------------------------------------------------------------------------------

Community.Popup = Class.create({
  initialize: function(element,content,options)
  {
  this.id = Community.Popup.id++;
  if (!options) options = {};
  this.element = $(element);
  this.content = content || "";
  if (!this.element) throw new Error("Отсутствует элемент, для которого нужно показывать всплывающее окно!");
  this.show_timeout = options.show_timeout || 2;
  this.element_pe = null;
  this.element_event_x = 0;
  this.element_event_y = 0;
  this.content_provider = options.content_provider || null;
  if (!Community.Popup.element)
  {
   Community.Popup.element = new Element('div',{'class':'popup'}).
           setStyle({'display':'none'}).
           update(this.html());
   document.body.appendChild(Community.Popup.element);
  }
  this.popup_element = Community.Popup.element;
  if (community.browser.opera) {
	this.element.observe("mouseout",this.element_mouseout.bindAsEventListener(this));
	this.element.observe("mouseover",this.element_mouseover.bindAsEventListener(this));
	this.element.observe("mousemove",this.element_mousemove.bindAsEventListener(this));
  }
  else {
	this.element.observe("contextmenu",this.element_contextmenu.bindAsEventListener(this));
  }

  community.init.add_unload(this.clean.bind(this));
  },

  clean: function()
  {
  this.stop();
  this.element = null;
  this.popup_element = null;
  this.element_pe = null;
  if (this.element_pe) this.element_pe.stop();
  },

  stop: function()
  {
   if (this.element)
   {
    this.element.stopObserving("mouseout");
    this.element.stopObserving("mouseover");
    this.element.stopObserving("mousemove");
   }
   this.stop_popup();
  },

  stop_popup: function()
  {
   if (this.popup_element)
   {
    document.stopObserving("click");
    document.stopObserving("contextmenu");
    this.popup_element.cur_element = null;
   }
  },

  html: function()
  {
  var value='<div class="popup_inner" id="Community_Popup_Element">';
  //if (!this.container && community.browser.msie && community.browser.version < 7)
  //{
    //value += '<iframe class="iframe_window"></iframe>';
  //}
  value += '</div>';
  return value;
  },

  element_contextmenu: function(event)
  {
    if (this.element_pe) this.element_pe.stop();
    this.element_event_x = event.pointerX();
    this.element_event_y = event.pointerY();
    if (this.popup_element.cur_element != this)
    {
      this.element_pe = new PeriodicalExecuter(this.show_popup.bind(this),0);
    }
    event.stop();
  },

  element_mouseover: function(event)
  {
  if (this.element_pe) this.element_pe.stop();
  this.element_event_x = event.pointerX();
  this.element_event_y = event.pointerY();
  if (this.popup_element.cur_element != this)
  {
    this.element_pe = new PeriodicalExecuter(this.show_popup.bind(this),this.show_timeout);
  }
  },

  element_mousemove: function(event)
  {
  this.element_event_x = event.pointerX();
  this.element_event_y = event.pointerY();
  },

  element_mouseout: function(event)
  {
  if (this.element_pe) this.element_pe.stop();
  },

  show_popup: function(pe)
  {
   var content = this.content ? this.content : this.content_provider.get_content();
   if (content == '')
   {
     if (this.element_pe) this.element_pe.stop();
     this.element_pe = new PeriodicalExecuter(this.show_popup.bind(this),0.1);
     return;
   }
   var old_element = this.popup_element.cur_element;
   if (old_element)
   {
     if (old_element.element_pe) old_element.element_pe.stop();
     old_element.stop_popup();
   }
   else this.stop_popup();
   $("Community_Popup_Element").update(content);
   var dimensions = this.popup_element.getDimensions();
   this.popup_height = dimensions.height;
   this.popup_width = dimensions.width;
   this.set_pos();

   this.popup_element.cur_element = this;
   this.popup_element.setStyle({'display':'block'});
   document.observe("click",this.hide_popup.bind(this));
   document.observe("contextmenu",this.hide_popup.bind(this));
  },

  hide_popup: function(pe)
  {
  this.popup_element.setStyle({'display':'none'});
  this.stop_popup();
  },

  set_pos: function()
  {
  var dimensions = $(document.body).getDimensions();
  var body_height = community.geometry.client_height();
  var body_width = community.geometry.client_width();
  var x,y;
  if (this.element_event_x+this.popup_width+10 >= body_width) x = this.element_event_x-this.popup_width-10;
  else x = this.element_event_x+10;
  if (this.element_event_y+this.popup_height+20 >= body_height) y = this.element_event_y-this.popup_height-20;
  else y = this.element_event_y+20;
  this.popup_element.setStyle({left:x+"px",top:y+"px",position:"absolute"});
  }
});

Community.Popup.id = 0;

//--------------------------------------------------------------------------------------

Community.Geometry = Class.create({
  initialize: function()
  {
  if (window.screenLeft) //IE
  {
    this.window_x = function() { return window.screenLeft; }
    this.window_y = function() { return window.screenTop; }
  }
  else if (window.screenX) //Firefox
  {
    this.window_x = function() { return window.screenX; }
    this.window_y = function() { return window.screenY; }
  }
  
  if (window.innerWidth) //Firefox
  {
    this.client_width = function() { return window.innerWidth; }
    this.client_height = function() { return window.innerHeight; }
    this.client_scroll_x = function() { return window.pageXOffset; }
    this.client_scroll_y = function() { return window.pageYOffset; }
  }
  else if (document.documentElement && document.documentElement.clientWidth)
  {
    this.client_width = function() { return document.documentElement.clientWidth; }
    this.client_height = function() { return document.documentElement.clientHeight; }
    this.client_scroll_x = function() { return document.documentElement.scrollLeft; }
    this.client_scroll_y = function() { return document.documentElement.scrollTop; }
  }
  else if (document.body.clientWidth)
  {
    this.client_width = function() { return document.body.clientWidth; }
    this.client_height = function() { return document.body.clientHeight; }
    this.client_scroll_x = function() { return document.body.scrollLeft; }
    this.client_scroll_y = function() { return document.body.scrollTop; }
  }

  if (document.documentElement && document.documentElement.scrollWidth)
  {
    this.document_width = function() { return document.documentElement.scrollWidth; }
    this.document_height = function() { return document.documentElement.scrollHeight; }

  }
  else if (document.body.scrollWidth)
  {
    this.document_width = function() { return document.body.scrollWidth; }
    this.document_height = function() { return document.body.scrollHeight; }
  }
  },

  window_x: function() { return 0; },
  window_y: function() { return 0; },
  client_width: function() { return 0; },
  client_height: function() { return 0; },
  client_scroll_x: function() { return 0; },
  client_scroll_y: function() { return 0; },
  document_width: function() { return 0; },
  document_height: function() { return 0; }
});

//---------------------------------------------------------------------------------------

Community.Survey = Class.create({
  initialize: function(survey)
  {
  if (survey == null)
  {
    this.survey = new Hash;
    this.survey.set("deleted_groups",new Array());
    this.survey.set("deleted_issues",new Array());
    return;
  }
  this.survey = $H(survey);
  this.survey.set("groups",$A(this.survey.get("groups")));
  var t_this = this;
  this.survey.get("groups").each(function(group,group_index)
    {
     t_this.survey.get("groups")[group_index] = $H(group);
     t_this.group_set(group_index,"issues",$A(t_this.group_get(group_index,"issues")));
     t_this.group_get(group_index,"issues").each(function(issue,issue_index)
      {
       t_this.group_get(group_index,"issues")[issue_index] = $H(issue);
      });
    });
  this.survey.set("deleted_groups",new Array());
  this.survey.set("deleted_issues",new Array());
  },

  get: function(field)
  {
  return this.survey.get(field);
  },

  set: function(field,value)
  {
  this.survey.set(field,value);
  },

  update: function(object)
  {
  this.survey.update(object);
  },

  group_get: function(group_index,field)
  {
  return this.survey.get("groups")[group_index].get(field);
  },

  issue_get: function(group_index,issue_index,field)
  {
  return this.survey.get("groups")[group_index].get("issues")[issue_index].get(field);
  },

  group_set: function(group_index,field,value)
  {
  this.survey.get("groups")[group_index].set(field,value);
  },

  issue_set: function(group_index,issue_index,field,value)
  {
  this.survey.get("groups")[group_index].get("issues")[issue_index].set(field,value);
  }
});

//------------------------------------------------------------

Community.User = Class.create({
  initialize: function(title)
  {
    this.title = title;
    this.info = null;
    this.request = false;
    Community.User.all.set(title,this);
  },

  get_content: function()
  {
	if (this.info) return this.html();
    if (this.request) return '';
    new Ajax.Request(community.url.info_ajax,
     {
       parameters: {'cmd':'get_info', 'id':this.title },
       onSuccess: this.get_content_success.bind(this),
       onFailure: community.ajax_failure.bind(community)
     });
    this.request = true;
    return '';
  },

  get_content_success: function(transport)
  {
    var response = transport.responseText.split(" ");
    if (response[0] != "OK") throw new Error("Ошибка получения информации о пользователе: "+transport.responseText);

    response.splice(0,1);
    this.info = response.join(" ").evalJSON(true);
  },

  html: function()
  {
    var title = this.title;
    var id = this.info.id;
    if (!title) return '';
    var vis_title = title.replace('$','');
    if (!vis_title) return '';
    var value='';
    if (vis_title != title) value += '<p><strong>'+vis_title+'</strong>';
    else value += '<p><img class="avatar" src="'+community.url.avatar_src+'?id='+title+'&size=3" /></p><p> <strong>'+vis_title+'</strong>';
    if (Number(this.info.online)) value += ' <strong>(онлайн)</strong>';
    if (title == vis_title && this.info.anketa)
    {
      if (this.info.anketa.sex == "2")
      {
        value += ' <a href="'+game_linker.user_info_link(this.info.login)+'" target="_blank"><img align="absmiddle" src="'+game_linker.user_info_icon_female()+'" width="'+game_linker.user_info_icon_width()+'" height="'+game_linker.user_info_icon_height()+'" alt="Информация о персонаже"></a>';
      }
      else if (this.info.anketa.sex == "1")
      {
        value += ' <a href="'+game_linker.user_info_link(this.info.login)+'" target="_blank"><img align="absmiddle" src="'+game_linker.user_info_icon_male()+'" width="'+game_linker.user_info_icon_width()+'" height="'+game_linker.user_info_icon_height()+'" alt="Информация о персонаже"></a>';
      }
      else
      {
        value += ' <a href="'+game_linker.user_info_link(this.info.login)+'" target="_blank"><img align="absmiddle" src="'+game_linker.user_info_icon()+'" width="'+game_linker.user_info_icon_width()+'" height="'+game_linker.user_info_icon_height()+'" alt="Информация о персонаже"></a>';
      }
    }
    value += '</p><ul style="margin-top:10px;">';
    value += '<li><a href="'+community.url.info+'?where='+id+'">Информация</a></li>';
    value += '<li><a href="'+community.url.blog+'?where='+id+'">Блог</a></li>';
    value += '<li><a href="'+community.url.albums+'?where='+id+'">Фото</a></li>';
    value += '<li><a href="'+community.url.audioalbums+'?where='+id+'">Аудио</a></li>';
    if (title == vis_title)
    {
      value += '<li><a href="'+community.url.friends+'?where='+id+'">Друзья</a></li>';
      value += '<li><a href="'+community.url.groups+'?where='+id+'">Группы</a></li>';
    }
    else
    {
      value += '<li><a href="'+community.url.group_members+'?where='+id+'">Состав</a></li>';
    }
    if (title == vis_title)
    {
      value += '<li><a href="'+community.url.tags+'?where='+id+'">Метки</a></li>';
      value += '<li><a href="'+community.url.favorites+'?where='+id+'">Избранное</a></li>';
      if (title != community.prop.user_title && Number(community.prop.user_id))
      {
        value += '<li><a href="'+community.url.send_gift+'?user='+title+'">Послать подарок</a></li>';
        value += '<li><a href="'+community.url.letters+'?writeto='+title+'">Написать письмо</a></li>';
        value += '<li><a href="'+community.url.letters_chat+'?contact='+title+'">Переписка</a></li>';
      }
      //value += '<li><a href="'+community.url.article_sets+'?where='+id+'">Подборки</a></li>';
    }
    var relation_abilities = this.info.relation_abilities;
    if (relation_abilities && relation_abilities.length > 0)
    {
      value += '<li>Сделать: <ul style="margin-left:10px;">';
      for (var i=0;i<relation_abilities.length;i++)
      {
        var ability = relation_abilities[i];
        value += '<li><a href="'+community.url.friends+'?cmd=relation&where='+id+'&level='+ability.level+'&check='+community.prop.check+'">';
        value += ability.level_title_tv+'</a>';
        if (ability.confirm) value += ' (*)';
        value += '</li>';
      }
      value += '</ul></li>';
    }
    var revert_relation_abilities = this.info.revert_relation_abilities;
    if (revert_relation_abilities && revert_relation_abilities.length > 0)
    {
      value += '<li>Стать: <ul style="margin-left:10px;">';
      for (var i=0;i<revert_relation_abilities.length;i++)
      {
        var ability = revert_relation_abilities[i];
        value += '<li><a href="';
        if (title == vis_title) value += community.url.friends;
        else value += community.url.group_members;
        value += '?cmd=relation_r&where='+id+'&level='+ability.level+'&check='+community.prop.check+'">';
        value += ability.level_title_tv+'</a>';
        if (ability.confirm) value += ' (*)';
        value += '</li>';
      }
      value += '</ul></li>';
    }
    value += '</ul>';
    return value;
  }
});

Community.User.all = new Hash();

//------------------------------------------------------------

Community.ArticleTypeList = Class.create({
  initialize: function(element,options)
  {
  this.id = Community.ArticleTypeList.id++;
  if (!options) options = {};
  this.element = $(element);
  if (!this.element) throw new Error("Отсутствует контейнер для списка типов записей!");
  this.types = new Array();
  this.display();
  community.init.add_unload(this.clean.bind(this));
  },

  clean: function()
  {
  this.element = null;
  },

  type_checkbox_id: function(id) { return "Community_ArticleTypeList_Type_CheckBox_"+id+"_"+this.id; },

  display: function()
  {
  this.element.update(this.html());
  },

  html: function()
  {
  var value='Тип объекта: <br />';
  value += '<input type="checkbox" id="'+this.type_checkbox_id("1")+'">записи</input><br />';
  value += '<input type="checkbox" id="'+this.type_checkbox_id("2")+'">альбомы</input><br />';
  value += '<input type="checkbox" id="'+this.type_checkbox_id("3")+'">фотографии</input><br />';
  return value;
  },

  get_types: function()
  {
  var result = new Array();
  if ($F(this.type_checkbox_id("1"))) result.push("1");
  if ($F(this.type_checkbox_id("2"))) result.push("2");
  if ($F(this.type_checkbox_id("3"))) result.push("3");
  return result.join(",");
  }

});

Community.ArticleTypeList.id = 0;

//------------------------------------------------------------

Community.DropDownMenu = Class.create({
  initialize: function(element,provider,options)
  {
    options = options || {};
    this.element = $(element);
    if (!this.element) { alert("Не найден контейнер для выпадающего меню!"); return; }
    this.provider = provider;
    if (!this.provider) { alert("Не указан провайдер контента для выпадающего меню!"); return; }

    this.can_hide = true;
    this.displayed = false;
    this.need_hide_time = 0;
    this.need_show_time = 0;
    this.show_interval = 500;
    this.hide_interval = 2000;
    this.timer = null;

    this.element.observe("mouseover",this.onElementMouseOver.bindAsEventListener(this));
    this.element.observe("mouseout",this.onElementMouseOut.bindAsEventListener(this));

    document.observe("click",this.hide_menu.bind(this));
    community.init.add_unload(this.clean.bind(this));
  },

  clean: function()
  {
    this.element.stopObserving("mouseover");
    this.element.stopObserving("mouseout");
    document.stopObserving("click");
    if (this.timer) { this.timer.stop(); this.timer = null; }
    if (this.displayed)
    {
      Community.DropDownMenu.owner = null;
      if (Community.DropDownMenu.element)
      {
        Community.DropDownMenu.element.stopObserving("mouseover");
        Community.DropDownMenu.element.stopObserving("mouseout");
        Community.DropDownMenu.element.hide();
      }
    }
  },

  onElementMouseOver: function(event)
  {
    if (!this.can_hide) return;
    this.need_show_time = (new Date()).getTime();
    this.can_hide = false;
    this.need_show();
  },

  onElementMouseOut: function(event)
  {
    if (this.can_hide) return;
    this.need_hide_time = (new Date()).getTime();
    this.can_hide = true;
    this.need_hide();
  },

  onMenuMouseOver: function(event)
  {
    this.can_hide = false;
  },

  onMenuMouseOut: function(event)
  {
    if (this.can_hide) return;
    this.need_hide_time = (new Date()).getTime();
    this.can_hide = true;
    this.need_hide();
  },

  need_show: function()
  {
    if (this.timer) { this.timer.stop(); this.timer = null; }
    if (this.displayed) return;
    var t_this = this;
    var cur_time = new Date();
    if (cur_time.getTime() - this.need_show_time >= this.show_interval)
    {
      if (!this.can_hide) this.show_menu();
    }
    else
    {
      this.timer = new PeriodicalExecuter(this.need_show.bind(this),
          (this.show_interval-(cur_time.getTime() - this.need_show_time))/1000);
    }
  },

  need_hide: function()
  {
    if (this.timer) { this.timer.stop(); this.timer = null; }
    if (!this.displayed) return;
    var t_this = this;
    var cur_time = new Date();
    if (cur_time.getTime() - this.need_hide_time >= this.hide_interval)
    {
      if (this.can_hide) this.hide_menu();
    }
    else
    {
      this.timer = new PeriodicalExecuter(function() { t_this.need_hide(); },
          (t_this.hide_interval - (cur_time.getTime() - t_this.need_hide_time))/1000);
    }
  },

  show_menu: function()
  {
    if (this.displayed) return;
    if (!Community.DropDownMenu.element)
    {
      Community.DropDownMenu.element = new Element('div',{'class':'popup'}).setStyle({'display':'none'});
      document.body.appendChild(Community.DropDownMenu.element);
    }
    if (Community.DropDownMenu.owner)
    {
      Community.DropDownMenu.owner.can_hide = true;
      Community.DropDownMenu.owner.displayed = false;
      Community.DropDownMenu.element.hide();
    }
    Community.DropDownMenu.owner = this;
    var content = this.provider.get_content(this);
    if (!content) content = "Идет загрузка...";

    var offset = this.element.cumulativeOffset();
    Community.DropDownMenu.element.update(this.html(content))
      .setStyle({left:offset[0]+"px",top:(offset[1]+this.element.getHeight())+"px"})
      .show();
    this.displayed = true;
    var t_this = this;
    Community.DropDownMenu.element.observe("mouseover",this.onMenuMouseOver.bindAsEventListener(this));
    Community.DropDownMenu.element.observe("mouseout",this.onMenuMouseOut.bindAsEventListener(this));
  },

  hide_menu: function(event)
  {
    if (this.displayed && this.can_hide && Community.DropDownMenu.element)
    {
      Community.DropDownMenu.element.stopObserving("mouseover");
      Community.DropDownMenu.element.stopObserving("mouseout");
      Community.DropDownMenu.element.hide();
      Community.DropDownMenu.owner = null;
      this.displayed = false;
    }
  },

  update_content: function(content)
  {
    if (this.displayed) Community.DropDownMenu.element.update(this.html(content));
  },

  html: function(content)
  {
    var value = '<div class="popup_inner">'+content+'</div>';
    return value;
  }

});

Community.DropDownMenu.element = null;
Community.DropDownMenu.owner = null;

Community.DropDownMenu.ContentProvider = new Object();

//-------------------------------------------------

Community.DropDownMenu.ContentProvider.List = Class.create({
  initialize: function(list,options)
  {
    options = options || {};
    this.list = $A(list);
  },

  get_content: function(menu)
  {
    return this.html();
  },

  html: function()
  {
    value = '<ul>';
    for (var i=0;i<this.list.length;i++)
    {
      if (this.list[i].delimiter) value += '<li>&nbsp;</li>';
      else value += '<li><a href="'+this.list[i].url+'">'+this.list[i].name+'</a></li>';
    }
    value += '</ul>';
    return value;
  }

});

Community.DropDownMenu.ContentProvider.Groups = Class.create({
  initialize: function(options)
  {
    options = options || {};
    this.loaded = false;
    this.request = false;
    this.groups = null;
    this.menu = null;
  },


  get_content: function(menu)
  {
    if (this.loaded) return this.html();
    if (this.request) return "";
    this.menu = menu;
    new Ajax.Request(community.url.info_ajax,
     {
       parameters: {'cmd':'get_groups'},
       onSuccess: this.get_groups_success.bind(this),
       onFailure: function (transport) { t_this.request = false; }
     });
   this.request = true;
   return "";
  },

  get_groups_success: function(transport)
  {
    this.request = false;
    var response = transport.responseText.split(" ");
    if (response[0] != "OK") throw new Error("Ошибка получения групп пользователя: "+transport.responseText);
    response.splice(0,1);
    this.groups = response.join(" ").evalJSON(true);
    this.loaded = true;
    this.menu.update_content(this.html());
  },

  html: function()
  {
	if (this.groups.length == 0) return "";
    value = '<ul>';
    for (var i=0;i<this.groups.length;i++)
    {
      value += '<li>'+community.user_title(this.groups[i].title,{nopopup:1})+'</li>';
    }
    value += '</ul>';
    return value;
  }
});

Community.DropDownMenu.id = 0;

//------------------------------------------------------------
Community.Dragger = Class.create({
  initialize: function(element,options)
  {
    options = options || {};
    this.id = Community.Dragger.id++;
    this.element = $(element);
    this.on_start_drag = options.on_start_drag || null;
    this.on_drag = options.on_drag || null;
    this.on_stop_drag = options.on_stop_drag || null;
    if (!this.element) throw new Error("Отсутствует перетаскиваемый элемент!");
    this.element.observe("mousedown",this.start_drag.bindAsEventListener(this));
    community.init.add_unload(this.clean.bind(this));
  },

  clean: function()
  {
    this.element.stopObserving("mousedown");
  },

  start_drag: function(event)
  {
    var orig_offset = this.element.cumulativeOffset();
    this.drag_delta_x = event.pointerX() - orig_offset.left;
    this.drag_delta_y = event.pointerY() - orig_offset.top;
    if (document.addEventListener)
    {
      this.drag_wrapper = this.drag.bindAsEventListener(this);
      this.stop_drag_wrapper = this.stop_drag.bindAsEventListener(this);
      document.addEventListener("mousemove",this.drag_wrapper,true);
      document.addEventListener("mouseup",this.stop_drag_wrapper,true);
    }
    else
    {
      this.element.observe("mousemove",this.drag.bindAsEventListener(this));
      this.element.observe("mouseup",this.stop_drag.bindAsEventListener(this));
      if (this.element.setCapture)
      {
        if (this.element.setCapture) this.element.setCapture();
        this.element.observe("losecapture",this.stop_drag.bindAsEventListener(this));
      }
      else
      {
        this.element.observe("mouseout",this.stop_drag.bindAsEventListener(this));
      }
    }
    if (this.on_start_drag) this.on_start_drag(event);
    event.stop();
  },

  drag: function(event)
  {
    if (this.on_drag) this.on_drag(event);
    if (document.addEventListener) event.stopPropagation();
    else event.stop();
  },

  stop_drag: function(event)
  {
    if (this.on_stop_drag) this.on_stop_drag(event);
    if (document.addEventListener)
    {
      document.removeEventListener("mousemove",this.drag_wrapper,true);
      document.removeEventListener("mouseup",this.stop_drag_wrapper,true);
      event.stopPropagation();
    }
    else
    {
      this.element.stopObserving("mousemove");
      this.element.stopObserving("mouseup");
      if (this.element.releaseCapture)
      {
        this.element.stopObserving("losecapture");
        this.element.releaseCapture();
      }
      else
      {
        this.element.stopObserving("mouseout");
      }
      event.stop();
    }
  }
});
//------------------------------------------------------------
var community = new Community();

var debug = community.debug;

soundManager.debugMode = false;
soundManager.flashVersion = 9;
soundManager.url = '/f/sound/';

soundManager.onload = community.soundloaded.bind(community);
soundManager.onerror = function() {
  // Something went wrong during init - in this example, we *assume* flashblock etc.
  soundManager.flashLoadTimeout = 0; // When restarting, wait indefinitely for flash
  soundManager.onerror = {}; // Prevent an infinite loop, in case it's not flashblock
  soundManager.reboot(); // and, go!
};
