String.prototype.trim = function() {
a = this.replace(/^\s+/, '');
return a.replace(/\s+$/, '');
};

function winop(){
    windop = window.open("popup.html","Лучшее от Polemika.com.ua","height=400,width=600,top=0");
}

//мигает на поле с ошибкой
function init_toggle(container_id) {
   var fld = $(container_id);
   
   //преобразование rgb -> #xxyyzz
   var color = [];
   fld.getStyle('background-color').scan(/\d+/, function(match) {color.push(parseInt(match[0]))});
   var tmp = '#' + color.invoke('toColorPart').join(''); //->'#800a10'
   
   var red_alert = new fx.Flash(container_id, {color_from: tmp, color_to:"#7f0000", count:2, duration:100});
   red_alert.toggle();
}

function preRebuildpage(){

    var stretchers = $A(document.getElementsByClassName('pr_ch'));

    if(Get_Cookie('polemika_weather_pref')){

        var _pref_settings = Get_Cookie('polemika_weather_pref');
        var array_pref_settings = _pref_settings.split(',');

        var _a = new Array();

        _counter = 0;
        array_pref_settings.each(function(array_pref_setting,iterator) {

            if(iterator%2 == 1){

                _a.push(Array(array_pref_settings[iterator-1], array_pref_setting));
                    
                if(array_pref_setting == 'true'){
                    stretchers[_counter].checked = 'checked';
                } else {
                    stretchers[_counter].checked = '';
                }

                _counter++;
            }
        });

        rebuildStructurePage(_a);

    } else { 
        stretchers.each(function(stretcher) { stretcher.checked = 'checked'; });
    }
}

function setNewPreferences(){

    // 1. set new coocke.
    var stretchers = $A(document.getElementsByClassName('pr_ch'));
    var pr_values = '';

    var _vidgets_name = new Array('hot_top_news', 'politica_news', 'ekonomika_news', 'video_news', 'rotator_news', 'obshestwo_news', 'vspomnit_news');
    var _a = new Array();

    stretchers.each(function(stretcher, index) {
        _a.push(Array(_vidgets_name[index], stretcher.checked));
    });

    pr_values = _a.join(',');

    Set_Cookie('polemika_weather_pref', pr_values, 7, '/', '', '' );

    // 2. reformat page.
    rebuildStructurePage(_a);

    document.getElementById('pref_win').className='preferences_window_closed';
}

function rebuildStructurePage(_array){

    _array.each(function(element) {
        
        if(element[1] == 'true' || element[1] == true){ 
            _style = "block"; 
            if(element[0] == 'hot_top_news'){ $("hot_categories_categories").className = "hot_categories"; }
        } else { 
            if(element[0] == 'hot_top_news'){ $("hot_categories_categories").className = "hot_categories_off"; }
            _style = "none"; 
        }

        Element.setStyle(element[0], 'display:'+_style);
    });
}

function makeAnswer(parent_id){
    $('cid').innerHTML = parent_id;

    var myElement = $('comments_make_block');
    var myScrollEffect = new fx.Scroll;
    myScrollEffect.scrollTo(myElement);
    
    $('comment_body').focus();
}

/**
 * Инициализация поиска
**/
function search_init(siteurl){
    var str = $('search_key').value;
    
    if(typeof str == "string") {
      str = str.replace(/^\s+|\s+$/g, '');
    } else {
      str = '';
    }
    
    if(str == '' || str == 'Поиск') {
      alert("Необходимо задать строку для поиска!");
      $('search_key').focus();
      return;
    }
    
    $("main_form").action=siteurl+"?action=search&search_str="+str;
    $("main_form").submit();
}


function messageSend(nid, cid){

    var comment_body = $('comment_body');
    var editname = $('commentor_name');
    var captchanumbers = $('captchanumbers');

    if( comment_body.value != '' && 
        captchanumbers.value != '' && 
        editname.value != '' && 
        !comment_body.value.blank())
    {

        xajax_addComment(
                            comment_body.value, 
                            $('nid').innerHTML, 
                            editname.value, 
                            captchanumbers.value,
                            $('cid').innerHTML
                        );
        return;

    } else {

        alert('Поля \'Имя\', \'Текст сообщения\' и \'Код\' являются обязательными.');

        if(comment_body.value == ''){comment_body.focus();}
        if(editname.value == ''){editname.focus();}
        if(captchanumbers.value == ''){captchanumbers.focus();}
        
        return;
    }
    
}

function commentsInit(){
    var rated = Get_Cookie('CommentsRated');
    if(rated && rated.length > 0) {
        rated.evalJSON().each(function(el) {
            var el = $('rate_' + el +'_id');
            if(el) {
                el.hide();
            }
        });
    }
}

function setRate(id){
    var rated = Get_Cookie('CommentsRated');
    if(rated && rated.length > 0) {
      rated = rated.evalJSON();  
      rated.push(id);
    } else {
      rated = [id];
    }
    Set_Cookie('CommentsRated', rated.toJSON(), 7, '/', '', '');
    xajax_setCommentRating(id);
    commentsInit();
}

/*

<script type="text/javascript">

    // remember, these are the possible parameters for Set_Cookie:
    // name, value, expires, path, domain, secure
    Set_Cookie( 'test', 'it works', '', '/', '', '' );
    if ( Get_Cookie( 'test' ) ) alert( Get_Cookie('test'));

    // and these are the parameters for Delete_Cookie:
    // name, path, domain
    // make sure you use the same parameters in Set and Delete Cookie.
    Delete_Cookie('test', '/', '');
    ( Get_Cookie( 'test' ) ) ? alert( Get_Cookie('test')) :
    alert( 'it is gone');

</script>

*/

function Set_Cookie( name, value, expires, path, domain, secure ){

    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires ){
        expires = expires * 1000 * 60 * 60 * 24;
    }

    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}


function Get_Cookie( check_name ) {

    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for ( i = 0; i < a_all_cookies.length; i++ )
    {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split( '=' );


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if ( cookie_name == check_name )
        {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if ( a_temp_cookie.length > 1 )
            {
                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if ( !b_cookie_found )
    {
        return null;
    }
}


var _siteurl = null;

function get_siteurl() {
  _siteurl = window.location.protocol.toString() + '//'+ window.location.host.toString() + window.location.pathname.toString();
  var re = new RegExp(/\/news-\d*\.html/i);
  _siteurl = _siteurl.replace(re, "");
  re = new RegExp(/\/$/i);
  _siteurl = _siteurl.replace(re, "");
  return _siteurl;
}

//var xajaxRequestUri = get_siteurl() + '/';

//http://habrahabr.ru/blogs/javascript/14481/
onReady = (function(ie){
 var d = document;
 return ie ? function(c){
   var n = d.firstChild,
    f = function(){
     try{
      c(n.doScroll('left'))
     }catch(e){
      setTimeout(f, 10)
     }
    }; f()
  } : 
  /webkit|safari|khtml/i.test(navigator.userAgent) ? function(c){
   var f = function(){
     /loaded|complete/.test(d.readyState) ? c() : setTimeout(f, 10)
    }; f()
  } : 
  function(c){
   d.addEventListener("DOMContentLoaded", c, false);
  }
})(/*@cc_on 1@*/);

Object.extend(Event, {
    onReady : function(f) {
        onReady(f);
    }
});

String.prototype.trim = function () {
    var str = this;
    str = str.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
            if (/\S/.test(str.charAt(i))) {
                    str = str.substring(0, i + 1);
                    break;
            }
    }
    return str;
}

/**
 * Функции работы с cookies
**/
function ex_setCookie(c_name,value,expiredays) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function ex_getCookie(c_name) {
    if (document.cookie.length>0)
      {
      c_start=document.cookie.indexOf(c_name + "=");
      if (c_start!=-1)
        { 
        c_start=c_start + c_name.length+1; 
        c_end=document.cookie.indexOf(";",c_start);
        if (c_end==-1) c_end=document.cookie.length;
        return unescape(document.cookie.substring(c_start,c_end));
        } 
      }
    return "";
}


/**
 * Процедуры обслуживания изменения размера шрифта при прочтении новости
**/
function ReSize(step)
{
    if(step == null || typeof step != "string" || step.trim().length == 0) {step = '1'}
    $('article').className='article_text fontsize'+step;

    $$('.art_fontsize a').each(function(el) {el.className = "fontsize_link"; });
    $('size' + step).className = "fontsize_current";

    ex_setCookie('Polemika/articleSize', step);
}

/*@cc_on
   @if (@_jscript_version >= 5.7)
      Event.onReady(function() { IE7_TargetFix(); }  );
   @end
@*/

/**
 * Решает проблему target="_blank" под IE7
**/
function IE7_TargetFix() {
  $$("td.latest_news a, #printpagehref").each(function(el) {
     el.target = "";
     Event.stopObserving(el, 'click');
     Event.observe(el, 'click', function(e) {
        window.location = this.href;
        
        // We've handled this event. Don't let anybody else see it.
        if (e.stopPropagation) e.stopPropagation(); // DOM Level 2
        else e.cancelBubble = true;
    
        // Now prevent any default action.
        if (e.preventDefault) e.preventDefault(); // DOM Level 2
        else e.returnValue = false;               // IE
     });
  });
}

/**
 * Процедуры для обслуживания модуля голосования
**/

function Polls (dataset, options) {
   this.dataset = dataset;
   this.options = options;
}

Polls.prototype.reload = function(res) {
    if(typeof res == "string") {
        res = res.evalJSON();
    }
    if(res != undefined) {
        if(res.result == 0) {
            this.dataset = res.dataset;
            this.options = res.options;
            return this.gen_voting_result();
        }
    }
    return '';
}

Polls.prototype.get_vote_rate = function (vote_id, total) {
   var rate = 0;
   if(total == 0) {
      return 0;
   }
   for(var i=0; i < this.dataset.myFirstDataset.length; i++) {
      if(this.dataset.myFirstDataset[i][0] == vote_id) {
         rate = Math.round(this.dataset.myFirstDataset[i][1]*100/total);
         break;
      }
   }
   return rate;
}

Polls.prototype.get_votes = function (vote_id) {
   var votes = 0;
   for(var i=0; i < this.dataset.myFirstDataset.length; i++) {
      if(this.dataset.myFirstDataset[i][0] == vote_id) {
         votes = this.dataset.myFirstDataset[i][1];
         break;
      }
   }
   return votes;
}

Polls.prototype.get_max_vote_id = function () {
   var vote_id = 0;
   var max_vote = -1;
   for(var i=0; i < this.dataset.myFirstDataset.length; i++) {
      if(this.dataset.myFirstDataset[i][1] >= max_vote) {
         max_vote = this.dataset.myFirstDataset[i][1];
         vote_id = this.dataset.myFirstDataset[i][0];
      }
   }
   return vote_id;
}

Polls.prototype.gen_voting_result = function () {
   var _html = "";
   var total = 0;
   var max_vote_id = this.get_max_vote_id();
   
   _html = '<div class="vote_results">';
   
   //подсчет общего кол-ва голосов
   for(var i=0; i < this.dataset.myFirstDataset.length; i++) {
      total += this.dataset.myFirstDataset[i][1];
   }

   //расчет рэйтов
   for(var i=0; i < this.options.xTicks.length; i++) {
      var rate = this.get_vote_rate(this.options.xTicks[i].v, total);
      _html += '<div class="vr_item">';
      _tmp = "";
      /*
      if(this.options.xTicks[i].v == max_vote_id) {
        _tmp = "<div class=\"bar_container v_top\">";
      } else { 
        _tmp = "<div class=\"bar_container\">";
      }*/
      _html += _tmp + '<div class="vr_bar" style="width:' + rate + '%"><b></b></div>';
      _html += '<div class="vr_percent"> ' + rate + "%, " + this.get_votes(this.options.xTicks[i].v) + " голосов</div>";
      _html += '<div class="vr_answer">' + this.options.xTicks[i].label + '</div>';
      _html += "</div>";
   }
   _html += '<div class="vr_total">Всего проголосовало: ' + total + '</div>';
   _html += '</div>';
   return _html;
}

/**
 * Процедуры для scroll-ленты
**/
var topspace        = 0;        // TOP SPACING FIRST TIME SCROLLING
var frameheight     = 1050;     // IF YOU RESIZE THE WINDOW EDIT THIS HEIGHT TO MATCH
var div_id          = "NewsDiv";
var direction       = 0;        // 0 - вниз, 1 - вверх
var startdelay      = 1;
var offset          = 0;
var playTape    = 0;
var scrollspeed =    0;
var current;

current = scrollspeed;

function recolor_background() {
    $$('.latest_news').each(function(el) {
        Event.observe(el, 'mouseover', set_background);
        Event.observe(el, 'mouseout', clear_background);
    });
}

function set_background() {
    Element.setStyle(this, "background-color: #faf3e0;");
}

function clear_background() {
    Element.setStyle(this, "background-color: #ffc78f;");
}

function playNewsTape() {
    var button;
    if(playTape == 0){
        scrollspeed = current = playTape = 1;
        button = 'pause.gif'
    } else { 
        scrollspeed = current = playTape = 0;
        button = 'play.gif'
    }
    $('news_tape1').innerHTML = '<a href="javascript:void(0);" onclick="playNewsTape();"><img src="images/'+button+'" height="12" width="12" alt="Старт/стоп прокрутки ленты новостей"/></a>';
    $('news_tape2').innerHTML = '<a href="javascript:void(0);" onclick="playNewsTape();"><img src="images/'+button+'" height="12" width="12" alt="Старт/стоп прокрутки ленты новостей"/></a>';
}

function scroller_start(){
    dataobj=document.all? document.all.NewsDiv : document.getElementById("NewsDiv")
    dataobj.style.top=topspace
    setTimeout("scroll_news()", 1)
    recolor_background();
}

function scroll_news(){
    // down
    if( direction == 0 && ($(div_id).getHeight() - Math.abs(offset) - frameheight) < 0) {
        direction = 1;
        setTimeout("scroll_news()", 1000);
        return;
    }

    // up
    if( direction == 1 && (offset + topspace) > 0) {
        direction = 0;
        setTimeout("scroll_news()", 1000);
        return;
    }

    offset = offset + scrollspeed * (direction > 0 ? 1: -1);
    Element.setStyle($(div_id), "margin-top: " + offset + "px");
    setTimeout("scroll_news()", 100);
}


/**
 * Классы индикаторов
*/
var FakeLoader = Class.create();
FakeLoader.prototype = {
  initialize: function() {
  },
  show: function() {
  },
  hide: function() {
  }
};


/**
 * Классы индикаторов
*/
var Loader = Class.create();
Loader.prototype = {
  initialize: function(container_id, className) {
    var el = $(container_id);
    this.el = null;
    if(!Object.isUndefined(el)) {
        this.el = el;
    }
    this.className = className;
  },
  show: function() {
    if(!Object.isUndefined(this.el)) {
        this.el.addClassName(this.className);
    }
  },
  hide: function() {
    if(!Object.isUndefined(this.el) && this.el.hasClassName(this.className)) {
        this.el.removeClassName(this.className);
    }
  }
};

//full screen loader
var FSLoader = Class.create();
FSLoader.prototype = {
  initialize: function() {
  },
  show: function() {
       var el = $('loader');
       if(Prototype.Browser.IE) {
          var xy = Element.cumulativeOffset($('footer_id'));
          $('loader_shadow').setStyle({'height': xy[1] + 76 + 'px'});
       }
       el.show();
  },
  hide: function() {
        $('loader').hide();
  }
};


var Tools = {
    isDebugMode: function () {
        return false;
    },
    processException: function (req, exception) {
        //IE hack outerHTML with null
        if(exception.number == -2146823281) {
            return true;
        }
        var msg = '';
        if(Tools.isDebugMode()) {
            msg = "\n\nResponse object:\n" + (typeof req == "object" && req != null
                    ? Object.toJSON(req)
                    : req
            );
        }
        //alert("The request had a fatal exception thrown.\n\nMessage:\n" + exception.message + msg);
        alert("The request had a fatal exception thrown.\n\nMessage:\n" + Object.toJSON(exception) + msg);
        return true;
    }
} 

/**
 * Загрузка данных ошибок в элементы документа
 * @param form {string} Какой action вызвать
 * @param values {string}
 */
function populate_errors(errors) {
    for(var obj in errors){
        var el = $(obj + '_error');
        if(el != null) {
            try {
                el.innerHTML = errors[obj];
            } catch (exc) {}
        }
    }
}

/**
 * Загрузка данных в элементы формы
 * @param form {string} Какой action вызвать
 * @param values {string}
 */
function populate_values(form_id, values) {
    var form = $(form_id);
    for(var obj in values) {
        var input = form[obj];
        if(input != null) {
            try {
                Form.Element.setValue(input, values[obj]);
            } catch (exc) {}
        }
    }
}

/**
 * Реализует обработку
 * @param container {integer}
 * @param callback {function}
 */
function keydown_ex(container, callback, callback1) {
    Element.childElements($(container)).each(function(el) {
        if(Element.childElements(el).size() > 0) {
            keydown_ex(el, callback, callback1);
        } else {
            if(el.match('input')) {
               Element.observe(el, 'keypress',
                function(event) {
                    if (event.keyCode == Event.KEY_RETURN) {
                        callback();
                    } else if(event.keyCode == Event.KEY_ESC && callback1 != undefined) {
                        callback1();
                    }
               }); 
            }
        }
    });
}

/**
 * Реализует AJAX-запрос
 * @param action {string} Какой action вызвать
 * @param message {string}
 */
function ajax_request(action, params, message, callback, loader) {
    if (message == null || confirm(message)) {
        if(Object.isUndefined(loader)) {
            loader = new FSLoader();
        }
        loader.show();
        new Ajax.Request(action, {
            contentType: 'application/x-www-form-urlencoded',
            method: 'post',
            parameters: params,
            onComplete: function(transport) {
                if (200 == transport.status) {
                    if(callback != null) {
                        callback(transport.responseText);
                    }
                } else {
                    if(callback != null) {
                        callback(null);
                    }
                }
                loader.hide();
                return true;
            },
            onException: function(req, exception) {
                loader.hide();
                return Tools.processException(req, exception);
            }
        });
    }
}

/**
* Inline text Alt class
* Note: 
*/
var InlineAlt = Class.create({
    initialize: function(el) {
        this.el = $(el);
        Element.observe(this.el, 'focus', this.updateAlt.bind(this, 'focus'));
        Element.observe(this.el, 'blur', this.updateAlt.bind(this, 'blur'));
        this.setAlt(false, this.el.getValue());
    },
    setAlt: function(disabled, alt) {
        this.alt = alt;
        this.el.setAttribute('title', alt);
        this.el.setAttribute('alt', alt);
        this.el.value = this.alt;
        if(disabled) {
            this.el.disable();
        } else {
            this.el.enable();
        }
        this.disabled = disabled;
    },
    updateAlt: function(type) {
        var value = this.el.getValue();
        if(value == this.alt && type == "focus" && !this.disabled) {
            this.el.value = '';
        }
        if(value.trim() == '' && type == "blur") {
            this.el.value = this.alt;
        }
    },
    value_ex: function() {
        if(this.el.value == this.alt) {
            return '';
        }
        return this.el.value;
    }
});

//проверка текстовых полей
function validateText(value, required, regexp, msg, limits) {
    var error = "";
    if (required && value == "") {
        error = msg.incorrectEmpty;
    } else if (regexp != undefined && !regexp.test(value)) {
        error = msg.incorrectChars;
    } else if(Object.isArray(limits) && limits.size() == 2 && value != "") {
        if ((value.length < limits[0]) || (value.length > limits[1])) {
            error = msg.incorrectLen;
        }
    }
    return error;
}

function parseDate(string) {
  var regexp = '([0-9]{1,2})\.(([0-9]{1,2})\.(([0-9]{4})( ([0-9]{1,2}):([0-9]{2})? *)?)?)?';
  var d = string.match(new RegExp(regexp, "i"));
  if (d==null) return Date.parse(string); // at least give javascript a crack at it.
  var offset = 0;
  var date = new Date(d[5], 0, 1);
  if (d[3]) { date.setMonth(d[3] - 1); }
  if (d[5]) { date.setDate(d[1]); }
  if (d[7]) {
    date.setHours(parseInt(d[7], 10));    
  }
  if (d[8]) { date.setMinutes(d[8]); }
  if (d[10]) { date.setSeconds(d[10]); }
  return date;
}

//проверка даты
function validateDate(value, msg) {
    var error = "";
    var res = parseDate(value);
    if (res == null || isNaN(res)){
        error = msg.incorrectDate;
    }
    return error;
}

//класс календаря
var myCal = [];
var calInit = {days: ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье'], months: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь']};

//перерисовать период
function redraw_period(el_id, el_container_id) {
    var html = '';
    if(el_id != null && myCal && myCal[el_id]) {
        var tmp = myCal[el_id].getDate();
        html += tmp.getDate() + ' ' + calInit.months[tmp.getMonth()];
    }
    var el = $(el_container_id);
    if(el) {
        el.innerHTML = html;
    }
}

var CalendarEx = new Class.create({
    //конструктор
    initialize: function(container_id, init_date, init, change_callback) {
        this.id = myCal.push(this) - 1;
        //alert(this.id + ' ' + container_id);
        this.container_id = container_id;
        this.days_lang = init.days;
        this.months_lang = init.months;
        this.change_callback = change_callback;
        if(init_date) {
            this.month = init_date.getMonth();
            this.year  = init_date.getYear();
            this.setDay(init_date.getDate());
        } else {
            this.setToday();
        }
    },
    
    //возвращает выбранную дату на календаре
    getDate: function() {
        return new Date(this.focusYear, this.focusMonth, this.focusDay);
    },

    //устанавливает дату, выбранную на календаре    
    setDay: function(day) {
        this.focusDay = day;
        this.focusMonth = this.month;
        if (this.year < 2000)    // Y2K Fix, Isaac Powell
            this.year = this.year + 1900; // http://onyx.idbsu.edu/~ipowell
        this.focusYear = this.year;
        if(this.change_callback && typeof this.change_callback == "function") {
            this.change_callback(this.id);
        }
        this.displayCalendar();
    },
    
    setToday: function () {
        var now   = new Date();
        this.month = now.getMonth();
            this.year  = now.getYear();
        this.setDay(now.getDate());
    },

    setPreviousMonth: function () {
        this.day   = 0;
        if (this.month == 0) {
            this.month = 11;
            if (this.year > 1000) {
                this.year--;
            }
        } else { this.month--; }
        this.displayCalendar();
    },

    setNextMonth: function () {
        this.day   = 0;
        if (this.month == 11) {
            this.month = 0;
            this.year++;
        } else { this.month++; }
        this.displayCalendar();
    },

    displayCalendar: function () {
        el = $(this.container_id);
        if(el) {
            var html = this.render();
            el.innerHTML = html;
        }
        return;
    },
        
    getDaysInMonth: function (month, year)  {
        var days;
        if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)  days=31;
        else if (month==4 || month==6 || month==9 || month==11) days=30;
        else if (month==2)  {
            if (this.isLeapYear(year)) { days=29; }
                else { days = 28; }
        }
        return (days);
    },

    isLeapYear: function  (Year) {
        if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0)) {
        return (true);
        } else { return (false); }
    },
    
    getDay: function(day) {
        if(day > 0) {
            day -=1;
        } else {
            day = 6;
        }
        return day;
    },
    
    //рендерит календарь
    render: function () {
        var html = '<a class="cal_back" href="javascript:void(0);" onclick="myCal['+ this.id +'].setPreviousMonth();"></a>' +
        '<div class="cal_date">' + this.months_lang[this.month] + ', '+ this.year + '</div>' +
        '<a class="cal_fwd" href="javascript:void(0);" onclick="myCal['+ this.id +'].setNextMonth();"></a>';
        html += '<div class="cal_weekdays">';
        for(i=0;i<7;i++) {
            html += '<b title="' + this.days_lang[i] + '">' + this.days_lang[i].substr(0, 1) + '</b>';
        }
        html += '</div>';
        html += '<div class="cal_days">';
        
        var i = 0;
        var days = this.getDaysInMonth(this.month+1, this.year);
        var firstOfMonth = new Date (this.year, this.month, 1);
        var startingPos = this.getDay(firstOfMonth.getDay());
        days += startingPos;
        for (i = 0; i < startingPos; i++) {
            html += '<a></a>';
        }
        for (i = startingPos; i < days; i++) {
            var cl = "";
            if(this.focusDay == (i-startingPos+1) && this.month == this.focusMonth && this.year == this.focusYear) {
                var cl = "current_day";
            }
            var tmp_day = (i-startingPos+1);
            html += '<a id="day_' + tmp_day + '" onclick="myCal['+ this.id +'].setDay('+tmp_day+');" href="javascript:void(0);"'+ (cl != "" ? ' class="' + cl + '"': '')+'>' + tmp_day + '</a>';
        }
        if(days > 35) {
            for (i=days; i<42; i++)  {
                html += '<a></a>';
            }
        }
        html += '</div>';
        return html;
    }
});

/* Закрытие закладки в браузере */
function closeTab() {
    if(Prototype.Browser.Gecko) {
        //netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
        window.open('','_self');
        //window.open('','_parent','');
    } else if (Prototype.Browser.MobileSafari || Prototype.Browser.WebKit) {
        var objWindow = window.open(location.href, "_self");
        objWindow.close();
        return;
    }
    window.close();        
}

/* */
function toggleClassEx(element, className1, className2) {
    element.toggleClassName(className1);
    element.toggleClassName(className2);
    
}

function validateUsername(value) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores
    if (value == "") {
        error = "Имя пользователя задано неверно";
    } else if ((value.length < 2) || (value.length > 32)) {
        error = "Некорректная длина имени пользователя";
    } else if (illegalChars.test(value)) {
        error = "В имени пользователя используются недопустимые символы";
    /*
    } else {
        fld.style.background = 'White';
    */
    } 
    return error;
}

/**
* Inline text Alt class
* Note: 
*/
var InlineAlt = Class.create({
    initialize: function(el) {
        this.el = $(el);
        Element.observe(this.el, 'focus', this.updateAlt.bind(this, 'focus'));
        Element.observe(this.el, 'blur', this.updateAlt.bind(this, 'blur'));
    },
    setAlt: function(disabled, alt) {
        this.alt = alt;
        this.el.setAttribute('title', alt);
        this.el.setAttribute('alt', alt);
        this.el.value = this.alt;
        if(disabled) {
            this.el.disable();
        } else {
            this.el.enable();
        }
        this.disabled = disabled;
    },
    updateAlt: function(type) {
        var value = this.el.getValue();
        if(value == this.alt && type == "focus" && !this.disabled) {
            this.el.value = '';
        }
        if(value == '' && type == "blur") {
            this.el.value = this.alt;
        }
    },
    value_ex: function() {
        if(this.el.value == this.alt) {
            return '';
        }
        return this.el.value;
    }
});

// Реализует AJAX-запрос на обновление каптчи
function renew_captcha(captcha_img, captcha_id, loader) {
    if(loader == null) {
        loader = new FakeLoader();
    }
    ajax_request('/content/captcha', {}, null,
        function(res) {
            if(res && typeof res == "string") {
                res = eval('(' + res + ')');
                $(captcha_img).innerHTML = res.captcha;
                $(captcha_id).value = res.captcha_id;
            }
        },
        loader
    );
}

//преобразование строки в вещественное число
function _floatval(num) {
    var f = 0.0;
    try {
        f = parseFloat(num);
    } catch(e) {}
    if(isNaN(f)) {
      f = 0.0;
    }
    return f;
}

//округление до rlength знакак после запятой
function _round(rnum, rlength) {
  return Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
}

//расчет суммы после конвертации
function calc_amount(in_amount, currency_in, currency_out, rlength) {
    if(!rlength) {
      rlength=4;
    }
    var in_rate = rates.find(function(n) { return n.id == currency_in; } );
    var out_rate = rates.find(function(n) { return n.id == currency_out; } );
    var commission = in_rate.commissions.find(function(n) { return n.out_currency_id == currency_out; });
    if(commission && 'commission' in commission) {
        in_rate['buy_rate'] *= _floatval(in_rate['buy_rate']) * (1.0 - _floatval(commission.commission / 100));
    }
    if (typeof(console) != undefined) {
        console.log(in_rate['buy_rate']);
    }
    var tmp = _floatval(in_amount) * _floatval(in_rate['buy_rate']) / _floatval(out_rate['sale_rate']);
    if(currency_in == currency_out) {
       tmp = tmp * 0.99; 
    }
    return _round(tmp, rlength);
}

//генерация списка
function gen_selHTML(el, rows, title) {
    var html = '';
    if(title != undefined) {
        html = html + '<option disabled selected>' + title +'</option>';
    }
    rows.each(function(c) {if(c != undefined) { html = html + '<option value="' + c['id'] +'">' + c['name'] +'</option>'; }});
    if(Prototype.Browser.IE) {
        setSelOuterHTML(el, html);
    } else {
        el.innerHTML = html;
    }
}

function clearSel(el) {
    if(Prototype.Browser.IE) {
        setSelOuterHTML(el, '');
    } else {
        el.innerHTML = '';        
    }
}

function setSelOuterHTML(el, options) {
    //http://support.microsoft.com/default.aspx?scid=kb;en-us;276228
    var change = el.getAttribute('onchange');
    if(change != null) {
        change = change.toString();
        if(change.indexOf('{') > 0 ) {
            var regex = /\{[\n\r]*(.*)[\n\r]*\}.*/mg;
            var match = regex.exec(change);
            change = match[1];
        }
    }
    var _class = el.classNames();
    var html = '<select id="' + el.id + '" '+ (_class != null ? 'class="' + _class +'"': '') + ' name="' + el.getAttribute('name')+'" '+
    (change != null ? 'onchange="' + change +'"': '') + '>' + options + '</select>';
    el.outerHTML = html;
}    

/**
 * Сброс параметров фильтра
 * @param form_id {string} Идентификатор формы фильтра
 */
function reset_filter(form_id) {
    var form = $(form_id);
    for(var obj in values) {
        var input = form[obj];
        if(input != null) {
            try {
                Form.Element.setValue(input, "");
            } catch (exc) {}
        }
    }
}

Array.prototype.in_array = function(p_val) {
    for(var i = 0, l = this.length; i < l; i++) {
        if(this[i] == p_val) {
            return true;
        }
    }
    return false;
}

function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (typeof value.length === 'number' &&
                    !(value.propertyIsEnumerable('length')) &&
                    typeof value.splice === 'function') {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}

function isEmpty(o) {
    var i, v;
    if (typeOf(o) === 'object') {
        for (i in o) {
            v = o[i];
            if (v !== undefined && typeOf(v) !== 'function') {
                return false;
            }
        }
    }
    return true;
}
