(function () {

  function style(el, style) {

    var mrg = el.getStyle(style);

    return mrg == 'auto' ? 0 : mrg.toInt()
  }

  var Carousel = this.Carousel = new Class({

    Implements: [Options, Events],
    options: {

      mode: 'horizontal',
      scroll: 7,
      distance: 1,
      circular: true,
      animation: 'Move',
      fx: {
        link: 'cancel',
        transition: 'sine:in:out',
        duration: 500
      }
    },
    plugins: {},
    initialize: function (options) {

      this.addEvent('change', function (current) {

        this.current = current

      }.bind(this)).setOptions(options);

      ['previous', 'next'].each(function (val) {

        if($(this.options[val])) $(this.options[val]).addEvent('click', function (e) {

          e.stop();

          this[val]()

        }.bind(this))

      }, this);

      this.elements = $(options.container).getChildren(options.selector);

      this.current = 0;
      this.anim = new this.plugins[this.options.animation](this);

      this.move(this.options.current || 0);
    },

    isVisible: function (index) {

      if($type($(index)) == 'element') index = this.elements.indexOf($(index));

      var length = this.elements.length,
      current = this.current,
      scroll = this.options.scroll;

      if(current <= index && index < current + scroll) return true;

      if(this.options.circular) for(var i = 1; i < scroll; i++) {

        if((i + current)  % length == index) return true;
      }

      return false
    },

    first: function () {

      return this.current
    },

    previous: function (direction) {

      return this.move(this.current - this.options.distance, direction)
    },

    next: function (direction) {

      return this.move(this.current + this.options.distance, direction)
    },

    move: function (index, direction) {

      var elements = this.elements,
      current = this.current,
      length = elements.length,
      scroll = this.options.scroll;

      if($type($(index)) == 'element') index = elements.indexOf($(index));

      //if(this.isVisible(index)) return this;

      if(!this.options.circular) {

        if(index > length - scroll) index = length - scroll
      }

      else {

        if(index < 0) index += length
        index %= Math.max(length, 1);
      }

      if(index < 0 || length <= scroll || index >= length) return this;

      if(direction == undefined) {

        //detect direction. inspired by moostack
        var forward = current < index ? index - current : elements.length - current + index,
        backward = current > index ? current - index : current + elements.length - index;

        direction = Math.abs(forward) <= Math.abs(backward) ? 1 : -1

      }
      this.anim.move(this, index, direction);

      return this
    }
  });

  Carousel.prototype.plugins.Move = new Class({

    initialize: function (carousel) {

      var up = this.up = carousel.options.mode == 'vertical',
      options = this.options = carousel.options,
      elements = this.elements = carousel.elements.map(function (el) {

        return el.setStyles({
          display: 'block',
          position: 'absolute'
        })

      }),
      parent = elements[0].getParent(),
      pos = parent.setStyles({
        height: parent.offsetHeight,
        position: 'relative',
        overflow: 'hidden'
      }).getStyle('padding' + (this.up ? 'Top' : 'Left'));

      this.property = 'offset' + (up ? 'Top' : 'Left');
      this.margin = 'margin' + (up ? 'Top' : 'Left');

      this.reorder(0, 1).fx = new Fx.Elements(elements, options.fx)
    },

    reorder: function (offset, direction) {

      var options = this.options,
      panels = this.elements,
      ini = pos = style(panels[0].getParent(), 'padding' + (this.up ? 'Top' : 'Left')),
      i,
      index,
      length = panels.length,
      horizontal = options.mode == 'horizontal',
      side = horizontal ? 'offsetWidth' : 'offsetHeight';

      //rtl
      if(direction == -1) {
        for(i = length; i > options.scroll - 1; i--) {

          index = (i + offset + length) % length;
          panel = panels[index];

          if (horizontal) panel.setStyle('left', pos);
          else panel.setStyles({
            left: 0,
            top: pos
          });
          pos -= (panel[side] + style(panel, this.margin));
        }

        pos = ini + panel[side] + style(panel, this.margin);

        for(i = 1; i < options.scroll; i++) {

          index = (i + offset + length) % length;

          panel = panels[index];

          if(horizontal) panel.setStyle('left', pos);
          else panel.setStyles({
            left: 0,
            top: pos
          });
          pos += panel[side] + style(panel, this.margin);
        }

      //ltr
      } else if(direction == 1) for(i = 0; i < length; i++) {
        index = (i + offset + length) % length;
        panel = panels[index];

        if(horizontal) panel.setStyle('left', pos);
        else panel.setStyles({
          left: 0,
          top: pos
        });
        pos += panel[side] + style(panel, this.margin);
      }

      return this
    },

    move: function (carousel, current, direction) {

      var obj = {},
      up = this.up,
      property = this.property,
      offset;
      if(this.options.circular) this.reorder(carousel.current, direction);

      offset = carousel.elements[current][property];

      carousel.elements.each(function (el, index) {

        obj[index] = up ? {
          top: el[property] - offset
        } : {
          left: el[property] - offset
        }
      });

      this.fx.start(obj).chain(function () {
        carousel.fireEvent('change', current)
      })
    }
  })
})();






/**********************__________________________________________________****************************************************************************/

var ImageCarousel = new Class({
  Implements: [Options],
  options: {
    element: 'slider',
    showDuration: 10000,
    fadeDuration: 1500,
    autoPlay: true,
    height: 385,
    width: 1000,
    data: [],
    nav_type: 'list',
    animatetext: 0,
    showtext:1
  },
  slide: [],
  number: [],

  initialize: function(options) {
    this.setOptions(options);
    this.options.element = $(this.options.element).grab(
      this.panel = new Element('div', {
        'class': 'nav'
      })
      );
    this.dim = this.options.element.getSize();

    this.createSlide(this.options.data);
    this.loadImage(0, true);
    if (this.options.autoPlay) this.play();
  },

  play: function() {
    this.player = this.nextSlide.periodical(this.options.showDuration, this);
    return this;
  },

  stop: function() {
    $clear(this.player);
    return this;
  },

  createSlide: function(data) {
    this.options.data = data;
    this.options.data.each(function(f, j) {
      if ($defined(f)) {
        var img =  new Element('img', {
          styles: {
            height: this.options.height+"px",
            width: this.options.width+"px"
          },
          src: f.image,
          events: {
            click: function() {
              if(this.options.nav_type == 'click'){
                this.nextSlide();
              }
            }.bind(this)
          }
        })
        if(this.options.showtext == 1){
          var txt = new Element('div').set({
            'html': f.text,
            'class': 'text'
          });
        }
        else{
          var txt = ""
        }
        var slide = {
          element: new Element('div',{
            styles: {
              opacity: 0
            }
          }).set('class','slide').adopt(txt, img)
        };

        this.options.element.grab(slide.element);
        slide.element.set('tween', {
          duration: this.options.fadeDuration,
          link:'cancel'
        })
        this.slide.push(slide);
      }

    }.bind(this));
    this.addNumbers();
    return this;
  },



  loadImage: function(i, isfirst, isauto) {
    this.currentImage = i;
    this.slide.each(function(s, j) {
      this.number[j].removeClass('active');
      if(this.options.animatetext == 1){
        var textCont = s.element.getElement('div.text img')
      }
      if (i == j) { // show this slide
        if(this.options.animatetext == 1){
          if(isfirst == true){
            textCont && textCont.setStyle('opacity','0');
            s.element.fade(1);
          }else{
            (function(){
              textCont && textCont.setStyles({
                'opacity':'0',
                'display':'block'
              })
              s.element.fade(1);
            }).delay(1500, this);
          }
          (function(){
            textCont && textCont.set('morph', {
              duration: 1600,
              link:'cancel'
            });
            textCont && textCont.morph({
              'opacity': 1
            });
          }).delay(3000, this);
        }else{
          s.element.fade(1)
        }
        this.number[j].addClass('active');
      } else { // else hide it
        s.element.fade(0);
        if(this.options.animatetext == 1){
          if(Browser.Engine.trident && Browser.Engine.version < 9){
            if(isauto != true){
              textCont && textCont.setStyle('display','none')
            }
          }else{
            textCont && textCont.set('morph', {
              duration: 1000,
              link:'cancel'
            });
            textCont && textCont.morph({
              'opacity': 0
            });
          }
        }
      }
    }.bind(this));
  },

  addNumbers: function() {
    this.slide.each(function(s, i) {
      var n;
      this.panel.grab(
        n = new Element('a', {
          'class': 'item',
          events: {
            click: function() {
              this.loadImage(i);
              this.stop().play();
              return false;
            }.bind(this)
          }
        })//.grab(new Element('span', { text: (i+1) }))
        );
      this.number.push(n);

    }.bind(this));
  },


  nextSlide: function() {
    var t = this.currentImage + 1;
    if (t > this.slide.length - 1) t = 0;
    this.loadImage(t, false, true);
    return this;
  }

});


var number_format = function (_number, _cfg) {
  var obj_merge = function(obj_first, obj_second) {
    var obj_return = {};
    for (key in obj_first) {
      if (typeof obj_second[key] !== 'undefined')
        obj_return[key] = obj_second[key];
      else
        obj_return[key] = obj_first[key];
    }
    return obj_return;
  }

  var thousands_sep = function(_num, _sep) {
    if (_num.length <= 3)
      return _num;
    var _count = _num.length;
    var _num_parser = '';
    var _count_digits = 0;
    for (var _p = (_count - 1); _p >= 0; _p--) {
      var _num_digit = _num.substr(_p, 1);
      if (_count_digits % 3 == 0 && _count_digits != 0 && !isNaN(parseFloat(_num_digit)))
        _num_parser = _sep + _num_parser;
      _num_parser = _num_digit + _num_parser;
      _count_digits++;
    }
    return _num_parser;
  }

  if (typeof _number !== 'number') {
    _number = parseFloat(_number);
    if (isNaN(_number))
      return false;
  }

  var _cfg_default = {
    before: '',
    after: '',
    decimals: 2,
    dec_point: ',',
    thousands_sep: ' '
  };

  if (_cfg && typeof _cfg === 'object') {
    _cfg = obj_merge(_cfg_default, _cfg);
  } else
    _cfg = _cfg_default;
  _number = _number.toFixed(_cfg.decimals);
  if(_number.indexOf('.') != -1) {
    var _number_arr = _number.split('.');
    var _number = thousands_sep(_number_arr[0], _cfg.thousands_sep) + _cfg.dec_point + _number_arr[1];
  } else
    var _number = thousands_sep(_number, _cfg.thousands_sep);

  return _cfg.before + _number + _cfg.after;
}

var Calculator = new Class({

  initialize: function () {
    var __this__ = this;

    this.fields = new Hash({
      program: $$('#calculator select[name="program"]')[0],
      url: $('calculator-url'),
      description: $('calculator-description'),
      option: $$('#calculator select[name="option"]')[0],
      term: $$('#calculator select[name="term"]')[0],
      sex: $$('#calculator select[name="sex"]')[0],
      age: $$('#calculator select[name="age"]')[0],
      sum: $$('#calculator input[name="sum"]')[0],
      calculate: $$('#calculator button[name="calculate"]')[0]
    });

    this.results = new Hash({
      result: $('calculator-result'),
      fee: $('calculator-fee'),
      reach: $('calculator-reach'),
      death: $('calculator-death'),
      accident: $('calculator-accident'),
      crash: $('calculator-crash'),
      traum: $('calculator-traum'),
      child_invalid: $('calculator-child-invalid'),
      child_death: $('calculator-child-death'),
      child_accident: $('calculator-child-accident'),
      child_invalid1: $('calculator-child-invalid1'),
      child_death1: $('calculator-child-death1'),
	  death2: $('calculator-death2')
    });
    this.programs = new Array();
    this.values = new Array();



    var fieldEnable = function (element) {
      element.removeProperty('disabled');
	  element.getParents('div.element')[0].removeClass('disabled')
    }

    var fieldDisable = function (element) {
      element.setProperty('disabled', 'disabled');
	  element.getParents('div.element')[0].addClass('disabled')
    }

    var fieldShow = function (element) {
      element.getParent('dd').removeClass('x-hide').getPrevious('dt').removeClass('x-hide');
    }

    var fieldHide = function (element) {
      element.getParent('dd').addClass('x-hide').getPrevious('dt').addClass('x-hide');
    }

    // function to fill aimed select with data's options
    var fillSelect = function (type, element, array) {
      fieldDisable(element);

	  element.getPrevious('span').set('html',' ')

      if (type == 'program') {
        __this__.programs = new Array();
      }
      if (type == 'option') {
        __this__.values = new Array();
      }

      element.getElements('option').dispose();
      new Element('option').inject(element);
      array.each(function (i) {
        new Element('option', {
          value: i.id,
          text: i.name,
          selected: array.length == 1
        }).inject(element);

        if (type == 'program') {
          __this__.programs[i.id] = i;
        }
        if (type == 'option') {
          __this__.values[i.id] = i.value;
        }
      });

      if (array.length > 0) {

        fieldEnable(element);
		if(array.length == 1){
			fieldDisable(element);
		}
		element.getPrevious('span').set('html', element.getSelected().get('html'))
      //        fieldShow(element);
      //      } else if (array.length == 1) {
      //        fieldHide(element);
      }
	  $('loader').setStyle('display','none')
      return element;
    }

    // Request.JSON
    var requestAndFill = function (type, parent, field, url) {
      __this__.results.result.addClass('x-hide');
	  $('loader').setStyle('display','block')
      if (!parent || parent.value != '') {
        new Request.JSON({
          url: url,
          onSuccess: function(response) {
            // get data tree and fields
            var data = response;

            fillSelect(type, field, data);

            //ignite fill next
            field.fireEvent('change');
          }
        }).send();
      } else {
        fillSelect(type, field, new Array());
		$('loader').setStyle('display','none')
        //ignite fill next
        field.fireEvent('change');
      }
    }

    // add program change handlers
    __this__.fields.program.addEvent('change', function () {
      requestAndFill('sex', __this__.fields.program, __this__.fields.sex,
        '?sexes=1&program=' + __this__.fields.program.value);

      var program = __this__.programs[__this__.fields.program.value];
      if (program && (program.description || program.url)) {
        if (program.description) {
          __this__.fields.description.set('html', program.description);
        }
        if (program.url) {
          __this__.fields.url.set('href', program.url).removeClass('x-hide');
        } else {
          __this__.fields.url.set('href', '#').addClass('x-hide');
        }
        fieldShow(__this__.fields.description);
      } else {
        __this__.fields.description.set('html', '');
        __this__.fields.url.set('href', '#').addClass('x-hide');
        fieldHide(__this__.fields.description);
      }

      if (program && program.code == 'junior') {
        __this__.fields.sex.getParent('dd').getPrevious('dt').
        getFirst('span').addClass('x-hide').getNext('span').removeClass('x-hide');
        __this__.fields.age.getParent('dd').getPrevious('dt').
        getFirst('span').addClass('x-hide').getNext('span').removeClass('x-hide');
      } else {
        __this__.fields.sex.getParent('dd').getPrevious('dt').
        getFirst('span').removeClass('x-hide').getNext('span').addClass('x-hide');
        __this__.fields.age.getParent('dd').getPrevious('dt').
        getFirst('span').removeClass('x-hide').getNext('span').addClass('x-hide');
      }
    });

    // add sex change handlers
    __this__.fields.sex.addEvent('change', function () {
      requestAndFill('age', __this__.fields.sex, __this__.fields.age,
        '?ages=1&program=' + __this__.fields.program.value
        + '&sex=' + __this__.fields.sex.value);
    });

    // add age change handlers
    __this__.fields.age.addEvent('change', function () {
      requestAndFill('term', __this__.fields.age, __this__.fields.term,
        '?terms=1&program=' + __this__.fields.program.value
        + '&sex=' + __this__.fields.sex.value
        + '&age=' + __this__.fields.age.value);
    });

    // add term change handlers
    __this__.fields.term.addEvent('change', function () {
      requestAndFill('option', __this__.fields.term, __this__.fields.option,
        '?options=1&program=' + __this__.fields.program.value
        + '&sex=' + __this__.fields.sex.value
        + '&age=' + __this__.fields.age.value
        + '&term=' + __this__.fields.term.value);
    });

    // add option change handlers
    __this__.fields.option.addEvent('change', function () {
      __this__.results.result.addClass('x-hide');

      if (__this__.fields.option.value != '') {
        fieldEnable(__this__.fields.sum);
      } else {
        fieldDisable(__this__.fields.sum);
      }

      __this__.fields.sum.value = '';

      __this__.fields.sum.fireEvent('keyup');
    });

    // add sum change handlers
    __this__.fields.sum.addEvent('keyup', function () {
      __this__.results.result.addClass('x-hide');

      var sum = __this__.fields.sum.value.toFloat();
      var tariff = __this__.values[__this__.fields.option.value];

      if (sum && tariff) {
        fieldShow(__this__.fields.calculate);
      } else {
        fieldHide(__this__.fields.calculate);
      }
    });

    // add calculate change handlers
    __this__.fields.calculate.addEvent('click', function () {
      var sum = __this__.fields.sum.value.toFloat();
      var tariff = __this__.values[__this__.fields.option.value];
      var program = __this__.programs[__this__.fields.program.value];

      if (program && sum && tariff) {
        var fee = sum * tariff;

        __this__.results.fee.set('text', number_format(fee));
        __this__.results.reach.set('text', number_format(sum));

        if (program.code == 'junior') {
          fieldHide(__this__.results.accident);
          fieldHide(__this__.results.crash);
          fieldHide(__this__.results.traum);
          fieldHide(__this__.results.death2);

          fieldShow(__this__.results.child_death);
          fieldShow(__this__.results.child_accident);
          fieldShow(__this__.results.child_invalid1);
          fieldShow(__this__.results.child_death1);

          __this__.results.death.set('text', '').
          getNext('span').addClass('x-hide').
          getNext('span').removeClass('x-hide');

          __this__.results.child_invalid.set('text', number_format(sum));
          __this__.results.child_death.set('text', number_format(sum * 0.25));
          __this__.results.child_accident.set('text', number_format(sum * 0.5));
          __this__.results.child_death1.set('text', number_format(sum));

        } else if (program.code == 'trust') {
          fieldHide(__this__.results.accident);
          fieldHide(__this__.results.crash);
		  fieldHide(__this__.results.death2);

          fieldShow(__this__.results.traum);

          fieldHide(__this__.results.child_invalid);
          fieldHide(__this__.results.child_death);
          fieldHide(__this__.results.child_accident);
          fieldHide(__this__.results.child_invalid1);
          fieldHide(__this__.results.child_death1);

          __this__.results.death.set('text', '').
          getNext('span').addClass('x-hide').
          getNext('span').removeClass('x-hide');

        } else {
          fieldShow(__this__.results.accident);
          fieldShow(__this__.results.crash);
		  fieldHide(__this__.results.death2);

          fieldHide(__this__.results.traum);
          fieldHide(__this__.results.child_invalid);
          fieldHide(__this__.results.child_death);
          fieldHide(__this__.results.child_accident);
          fieldHide(__this__.results.child_invalid1);
          fieldHide(__this__.results.child_death1);

          if (program.code == 'life') {
            __this__.results.death.set('text', number_format(sum)).
            getNext('span').addClass('x-hide').
            getNext('span').addClass('x-hide');
            __this__.results.accident.set('text', number_format(sum * 2)).
            getNext('span').addClass('x-hide');
            __this__.results.crash.set('text', number_format(sum * 3)).
            getNext('span').addClass('x-hide');

          } else if (program.code == 'capital') {
            __this__.results.death.set('text', '').
            getNext('span').removeClass('x-hide').
            getNext('span').addClass('x-hide');
            __this__.results.accident.set('text', number_format(sum)).
            getNext('span').removeClass('x-hide');
            __this__.results.crash.set('text', number_format(sum * 2)).
            getNext('span').removeClass('x-hide');


			fieldShow(__this__.results.death2);


          } else if (program.code == 'active') {
            __this__.results.death.set('text', number_format(sum * 0.5)).
            getNext('span').addClass('x-hide').
            getNext('span').addClass('x-hide');
            __this__.results.accident.set('text', number_format(sum)).
            getNext('span').addClass('x-hide');
            __this__.results.crash.set('text', number_format(sum * 2)).
            getNext('span').addClass('x-hide');
          }
        }

        __this__.results.result.removeClass('x-hide');
      } else {
        __this__.results.result.addClass('x-hide');
      }
    });

    // fill programs
    requestAndFill('program', null, __this__.fields.program, '?programs=1');

  }

});


var Payment = new Class({

  initialize: function () {
    var __this__ = this;

    this.fields = new Hash({
      series: $('payment_contract_series'),
      number: $('payment_contract_number'),
      currency: $('payment_currency'),
      sum: $('payment_sum'),
      sum_uah: $('payment_sum_uah')
    });

    var calculateSum = function () {
      var currency = __this__.fields.currency.value;
      var rate = currency_rates[currency];

      var sum = __this__.fields.sum.value;
      sum = sum.replace(',', '.');
      sum = sum.replace(/[^\d\.]/g, '');

      if (sum != __this__.fields.sum.value) {
        __this__.fields.sum.value = sum;
      }

      sum = sum.toFloat();
      if (sum > 0) {
        sum_uah = number_format(Math.ceil(sum * rate * 100) / 100, {decimals: 2, dec_point: '.', thousands_sep: ''});
      } else {
        sum_uah = '';
      }
      __this__.fields.sum_uah.value = sum_uah;
    }

    var correctNumber = function (showError) {
      var series = __this__.fields.series.value;

      var length = 15;
      var set = 'chars';
      switch (series) {
        case 'АВ': case 'AD': case 'JU': case 'КЗ':
        case 'ТА': case 'ТД': case 'ТМ': case 'ТТ': {
          length = 7; set = 'digits'; break;
        }
        case 'РП': case 'ДП': case 'ПП': {
          length = 8; break;
        }
        case 'ТБ': case 'ТО': {
          length = 10; break;
        }
      }

      var number = __this__.fields.number.value;
      if (set == 'chars') {
        number = number.replace(/\s/g, '');
      } else if (set == 'digits') {
        number = number.replace(/\D/g, '');
      }

      number = number.substr(0, length);

      if (number != __this__.fields.number.value) {
        __this__.fields.number.value = number;
      }

      var isCorrect = (series == '') || (number.length == length);

      if (!isCorrect && showError) {
        $('payment-contract-error').show();
        $('payment-contract-length').set('html', length);
        if (set == 'chars') {
          $('payment-contract-digits').hide();
          $('payment-contract-chars').show();
        } else {
          $('payment-contract-digits').show();
          $('payment-contract-chars').hide();
        }
      } else {
        $('payment-contract-error').hide();
      }

      return isCorrect;
    }

    // add series change handlers
    __this__.fields.series.addEvent('change', function () {
      correctNumber(true);
    });

    // add number change handlers
    __this__.fields.number.addEvent('keyup', function () {
      correctNumber(true);
    });

    // add currency change handlers
    __this__.fields.currency.addEvent('change', function () {
      calculateSum();
    });

    // add sum change handlers
    __this__.fields.sum.addEvent('keyup', function () {
      calculateSum();
    });

    // add sum change handlers
    __this__.fields.sum.addEvent('change', function () {
      calculateSum();
    });

    // add sum change handlers
    __this__.fields.sum.addEvent('blur', function () {
      calculateSum();
    });

    // add form submit handlers
    __this__.fields.sum.getParent('form').addEvent('submit', function (event) {
      if (!correctNumber(true)) {
        event.preventDefault();
      }
    });

    calculateSum();
    correctNumber(false);

  }

});


window.addEvent('domready', function() {

  // calculator
  try {
    new Calculator();
  } catch(e){}

  // payment form
  try {
    new Payment();
  } catch(e){}


  new Exm();
  try {
    new Carousel({
      container: 'carousel_content',
      previous:  $$('.carousel a.prev').shift(),
      next:  $$('.carousel a.next').pop(),
      fx: {
        duration:  120
      }
    });
  }catch(e){}
  // release accordeons
  try {
    $$('dl.sys-accordeon').each(function(i){
      i.getElements('dt').addEvents({
        'mouseover': function(){
          this.addClass('hover');
          return false;
        },
        'mouseout': function(){
          this.removeClass('hover');
          return false;
        },
        'click': function(){
          if (this.getNext().get('tag')=='dd') {
            if (this.getNext().hasClass('open')) {
              this.getNext().removeClass('open');
            } else {
              this.getParent('dl').getElements('dd.open').removeClass('open');
              this.getNext().addClass('open');
            }
          }
          return false;
        }
      });
    });
  } catch(e){}

  try {
    $$('.sidebar').each(function(i){
      i.getElements('div.li').addEvents({
        'click': function(){
          if (this.getNext().hasClass('x-1')) {

            if(this.hasClass('cur')){
              this.getNext().toggleClass('open');
            }else{
              i.getElements('div.li').removeClass('cur');
              $$('.sidebar .x-1').removeClass('open');
              this.getNext().addClass('open');
            }
            this.addClass('cur')
          }

        }
      });
    });
  } catch(e){}



  // releases TAB for Page View
  try {
    $$('a[rel|="x-view"], li[rel|="x-tab"]').addEvent('click', function() {
      $$('a[rel|="x-view"], li[rel|="x-tab"]').removeClass('this').addClass('not_active');
      this.addClass('this').removeClass('not_active');
      $$('div[id|="x-view"], table[id|="x-tab"]').addClass('hidden');
      $(this.get('rel')).removeClass('hidden');
      return false;
    });
  } catch(e){}

  try{
    var slider = new ImageCarousel({
      element: 'slider',
      nav_type: 'list',
      animatetext: 1,
      showtext:1,
      data: slidshowdata
    }), indicators = new ImageCarousel({
      element: 'indicators',
      height: 152,
      width: 279,
      fadeDuration:300,
      autoPlay: false,
      nav_type:  'click',
      animatetext: 0,
      showtext:0,
      data: indicatordata
    });
  }catch(e){}


  /*Виджет опрос*/
  try{
    // при клике на один из пунктов (выбор ответа) активируем кнопку сабмита
    $$('#poll-content input').addEvent('change', function(event) {
      $$('#poll-content button').removeProperty('disabled');
      return true;
    });
    // сабмит формы
    $$('#poll-content button').addEvent('click', function() {
      // для удобства берем в переменную форму
      var form = this.getParent('form');

      // конструируем и шлем Аякс-запрос
      new Request({
        url: form.get('action'),
        method: 'post',
        data: form.toQueryString(),
        onSuccess: function(result) {
          // если все ок, чистим содержимое всего дива модуля и
          // заменяем его кодом из АЯКС-ответа

          // WARNING!
          // аякс-ответ надо отдавать без внешнего оберточного дива модуля
          $('poll-content').empty().set('html', result);
          return this;
        },
        onFailure: function(xhr) {
          // если неок, просим прощения
          $$('#poll-content div').removeClass('hidden');

          // и активируем инпуты
          form.getElements('input, button').each(function(o){
            return o.removeProperty('disabled');
          });
          return this;
        }
      }).send();

      $$('#poll-content div').addClass('hidden');

      // пока обрабатывается запрос, дисейблим инпуты, чтобы ебучий юзер не проголосовал еще раз
      form.getElements('input, button').each(function(o){
        return o.set('disabled', 'disabled');
      });

      // на всякий случай запрещаем обычный сабмит формы
      return false;
    });
  }catch(e){}

  try {
    $$('.toggler .toggler_title').addEvent('click', function(){
      this.getParent('div').toggleClass('open');
      return false;
    });
  }catch(e){}

  // milkbox init
  try {
    new Milkbox({
      overlayOpacity: 0.8
    });
  } catch(e){}

  // subscribe form buttons fix
  try {
	  var buttonElements = $$('#article_subscribe button[type="submit"]');
	  buttonElements.each(function(e){
		  e.addEvent('click' , function(){
			  $('article_subscribe_mode').set('value', e.get('val'))
			  this.getParent('form').submit();
		  });
	  });
  } catch(e){}




});
