  var oldElementFocus = Element.prototype.focus;

  Element.prototype.focus = function () {
    if (this.id != 's4f_messenger_input')
      return oldElementFocus ();
  }

  function htmlspecialchars (string, quote_style, charset, double_encode) {
    var optTemp = 0,
        i = 0,
        noquotes = false;
    if (typeof quote_style === 'undefined' || quote_style === null) {
        quote_style = 2;
    }
    string = string.toString();
    if (double_encode !== false) { // Put this first to avoid double-encoding
        string = string.replace(/&/g, '&amp;');
    }
    string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');
    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE': 1,
        'ENT_HTML_QUOTE_DOUBLE': 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE': 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i = 0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'ENT_IGNORE' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            }
            else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/'/g, '&#039;');
    }
    if (!noquotes) {
        string = string.replace(/"/g, '&quot;');
    }
    return string;
  }

  function declination (number, words) {
    var cases = [2, 0, 1, 1, 1, 2];
    return words [(number % 100 > 4 && number % 100 < 20) ? 2 : cases[(number % 10 < 5) ? number % 10 : 5]];
  }


  document.onkeydown = function (event) {
    if (window.event)
      event = window.event;
    if (event.ctrlKey) {
      var element = null;
      switch (event.keyCode ? event.keyCode : event.which ? event.which : null) {
        case 0x25: // left
          element = document.getElementsByClassName ('ctrlLeftTrigger');
          element = element.length > 0 ? element[0] : null;
          break;
        case 0x27: // right
          element = document.getElementsByClassName ('ctrlRightTrigger');
          element = element.length > 0 ? element[0] : null;
          break;
      }
      if (element && element.href)
        document.location = element.href;
    };
  }

  $(document).ready (function () {
  
    //scrollBarsFix ();
    
    MWindow.dontFixScrollBars = true;
    
    /* Kwicks */
    $('.kwicks').kwicks ({
      min: 60,
      spacing: -20,
      sticky: true,
      duration: 300
    });
    var currentKwick = 0;
    var kwicksCount = $('.kwicks li').size ();
    var kwicksDirectionLtr = true;
    var dontMoveKwicks = false;
    $('.kwicks').hover (function (event, manually) {
      dontMoveKwicks = manually ? false : true;
    }, function () {
      dontMoveKwicks = false;
    });
    setInterval (function () {
      if (!dontMoveKwicks) {
        if (kwicksDirectionLtr) {
          if (currentKwick < kwicksCount - 1) {
            currentKwick++;
          } else {
            kwicksDirectionLtr = false;
            currentKwick--;
          }
        } else {
          if (currentKwick > 0) {
            currentKwick--;
          } else {
            kwicksDirectionLtr = true;
            currentKwick++;
          }
        }
        $('#kwick' + currentKwick).trigger ('mouseover', [true]);
      }
    }, 3000);
    $('.kwicks').fadeIn (100);
    
    /* Clients Trail */
    $('#clientsTrail .floating').clone ().appendTo ('#clientsTrail');
    var ctFloaters = $('#clientsTrail .floating');
    var ctMarginLeft = 0;
    var ctStop = false;
    setInterval (function () {
      if (!ctStop) {
        ctMarginLeft -= 1; // 2
        $(ctFloaters[0]).css ('margin-left', ctMarginLeft + 'px');
        if (ctMarginLeft * -1 >= $(ctFloaters[0]).width ()) {
          ctStop = true;
          $(ctFloaters[0]).css ('margin-left', '0');
          ctMarginLeft = 0;
          ctStop = false;
        }
      }
    }, 40);

    /* Promo Video */
    $('#playTrigger').click (function () {
      $(this).fadeOut (300);
      $('#promoVideo').show ();
    });
    
    /* Services */
    $('.service').hover (function () {
      $(this).find ('.hover').fadeIn (100);
    }, function () {
      $(this).find ('.hover').fadeOut (100);
    });
    /* $('.service .image .hover').each (function () {
      $.preLoadImages ($(this).attr ('data-hover-image'));
    }); */
    
    /* Portfolio Hot List */
    new GalleryBox ({
      containerSelector: '#portfolioHotListWrapper .container',
      floatingBlockSelector: '#portfolioHotListWrapper .floating',
      itemsSelector: '.portfolioItem',
      leftTrigger: '#portfolioHotListWrapper .leftTrigger',
      rightTrigger: '#portfolioHotListWrapper .rightTrigger',
      currentItem: 0
    });
    
    /* Placeholders */
    $('.MFormContainer .labelAndField label').inFieldLabels ();
    
    /* mForm */
    mForm.windowizeForm ('SCallbackForm', 'a[href="/callback/"]', '/callback/', 'Заказать обратный звонок', {
      onload: function () {
        this.find ('.labelAndField label').inFieldLabels ();
      }
    });
    mForm.ajaxifyForm ('SCommentForm', {
      success: function () {
        var form = $('.MFormModel_SCommentForm form');
        var idPrefix = form.attr ('data-id-prefix');
        $([
          '<div class="comment" style="display: none">',
            '<div class="name">' + htmlspecialchars ($('#' + idPrefix + 'SCommentForm_name').val ()) + '</div>',
            '<div class="text">' + htmlspecialchars ($('#' + idPrefix + 'SCommentForm_comment').val ()) + '</div>',
          '</div>'
        ].join ('')).appendTo ('.commentsWrapper').fadeIn ();
        $('.commentsContainer .form, .commentsContainer .noComments').hide ();
      }
    });
    mForm.windowizeForm ('SFeedbackForm', 'a[href="mailto:in@aaccent.ru"]', '/feedback-2/', 'Обратная связь', {
      ajaxifyThisFormOnly: true,
      onload: function () {
        this.find ('.labelAndField label').inFieldLabels ();
      }
    });
    mForm.windowizeForm ('SFeedbackForm', 'a[href="/feedback-2/"]', '/feedback-2/', 'Обратная связь', {
      ajaxifyThisFormOnly: true,
      onload: function () {
        this.find ('.labelAndField label').inFieldLabels ();
      }
    });
    /* mForm.ajaxifyForm ('SCostCalculationForm', {
      success: function () {
        
      }
    }); */
    
    /* Разворачивающийся список услуг в форме расчета стоимости заказа */
    $('.MFormModel_SCostCalculationForm .labelAndField_checkboxes .label').click (function () {
      $('.MFormModel_SCostCalculationForm .labelAndField_checkboxes .field').slideToggle ();
    });
    
    /* redButton IE */
    var redButtonsForIE = function () {
      if (window.ie) {
        $('.redButton .container .c span').live ('click', function () {
          $(this).parent ().parent ().parent ().find ('a, input').trigger ('click');
          return false;
        });
      }
    }
    
    /* Замена .grb кнопкой */
    var redButtonLinkTemplate = $('#sys .redButtonLinkTemplate').html ();
    $('a.grb').each (function () {
      var caption = $(this).text ();
      var href = $(this).attr ('href');
      var newElement = $(redButtonLinkTemplate.replace ('##CAPTION##', caption).replace ('##HREF##', href));
      newElement.addClass ('redButtonAutoWidth');
      $(this).replaceWith (newElement);
    });
    redButtonsForIE ();
    
    /*
     * Ночная скидочка
     */
    if ($('#nightContainer').size ()) {
      var nightOpened = false;
      var nightContentWidth = $('#nightContent').width ();
      var nightOpen = function () {
        $('#nightContainer').animate ({
          left: 0
        });
        nightOpened = true;
      }
      var nightClose = function () {
        $('#nightContainer').animate ({
          left: -nightContentWidth + 'px'
        });
        nightOpened = false;
        $.cookie ('dont_auto_open_night', '1', {
          path: '/',
          expires: 30
        });
      }
      var nightToggle = function () {
        if (nightOpened)
          nightClose ();
        else
          nightOpen ();
      }
      $('#nightTrigger').click (nightToggle);
      if ($.cookie ('dont_auto_open_night') === null) {
        //setTimeout (nightOpen, 10000);
      }
    } else {
    
      /*
       *
       * Онлайн консультант
       *
       */
      window.s4f_messenger_show = function () {
        $('#consContainer').animate ({
          left: 0
        });
        $('#s4f_messenger').show ();
        window.s4f_opened = true;
      }
      window.s4f_messenger_hide = function () {
        $('#consContainer').animate ({
          left: -window.s4f_consContentWidth + 'px'
        });
        $('#s4f_messenger').hide ();
        window.s4f_opened = false;
        $.cookie ('dont_auto_show_s4f', '1', {
          expires: 30,
          path: '/'
        });
        $.cookie ('XMPPClient_left', '', {
          expires: 30,
          path: '/'
        });
      }
      window.s4f_messenger_toggle = function () {
        if (window.s4f_opened)
          s4f_messenger_hide ();
        else
          s4f_messenger_show ();
      }
      window.s4f_messenger_get = function (mess, from) {
        mess = s4f_replace_smiles (mess);
        if (from == null) {
          $('#s4f_messenger_area').append ('<p class="myMessage"><span>Я:</span> ' + mess + '</p>');
          $('#s4f_messenger_input').val ('');
        } else {
          $('#s4f_messenger_area').append ('<p class="opMessage"><span>Консультант:</span> ' + mess + '</p>');
        }
        document.getElementById ('s4f_messenger_area').scrollTop = document.getElementById ('s4f_messenger_area').scrollHeight;
      };
      setTimeout (function () {


        //if ($('#s4f_offline_text').size ()) {
        if (true) {
          // никого нет
        } else {
          // консультант на связи
          $('#s4f_messenger').appendTo ('#consContent').show ();
          $('#consContainer').fadeIn (100);
          $('#s4f_messenger_area').html ('');
          window.s4f_consContentWidth = $('#consContent').width ();
          var consHeight = $('#consTrigger').height ();
          $('#consTrigger').click (window.s4f_messenger_toggle);
          /* CSS */
          $('#s4f_messenger').css ('height', consHeight + 'px')
                             .css ('top', '0')
                             .css ('margin-top', '0')
                             .css ('left', '0')
                             .css ('margin-left', '0');
          $('#s4f_messenger_body').css ('height', '100%');
          $('#s4f_messenger_header').css ('background', 'white')
                                    .css ('cursor', 'default');
          $('#s4f_messenger_header_text').css ('background', 'white')
                                         .css ('height', '22px')
                                         .css ('color', '#333')
                                         .css ('cursor', 'default');
          $('#s4f_messenger_close').hide ();
          $('#s4f_messenger_area').css ('color', '#333')
                                  .css ('border', 'none')
                                  .css ('border-top', '1px solid #aaa')
                                  .css ('border-bottom', '1px solid #aaa')
                                  .css ('height', '100%')
                                  .css ('width', '');
          $('#s4f_messenger_area').parent ().parent ().css ('height', '100%');
          $('#s4f_messenger_body tbody tr:last-child').remove ();
          $('#s4f_messenger_input').css ('border', '')
                                   .css ('width', '291px');
          $('#s4f_messenger_button').css ('width', '100px');
          $('#s4f_messenger_input').parent ().prepend ('<label for="s4f_messenger_input">Впишите ваш вопрос:</label>');
          /* автораскрытие */
          if ($.cookie ('dont_auto_show_s4f') === null) {
            //setTimeout (s4f_messenger_show, 10000);
          }
        }
      }, 1000);
      
    }
    
  });



  var startExpirationTimer = function (dateTime) {
    $(document).ready (function () {
      var target = new Date ();
      target.setFullYear (dateTime.year, dateTime.month - 1, dateTime.date);
      target.setHours (dateTime.hours, dateTime.minutes, dateTime.seconds);
      var timed = function () {
        var now = new Date ();
        var totalRemains = target.getTime () - now.getTime ();
        if (totalRemains > 1) {
          var nSeconds = parseInt (totalRemains / 1000); // необработанных секунд
          var fullHours = parseInt (nSeconds / 3600); // полных часов
          nSeconds -= fullHours * 3600;
          var minutes = parseInt (nSeconds / 60); // минут в оставшемся часе
          nSeconds -= minutes * 60;
          var days = parseInt (fullHours / 24);
          fullHours -= days * 24;

          $('#stockExpiration .timer .d .v').text (days);
          $('#stockExpiration .timer .d .t').text (declination (days, ['день', 'дня', 'дней']));

          $('#stockExpiration .timer .h .v').text (fullHours < 10 ? '0' + fullHours : fullHours);
          $('#stockExpiration .timer .h .t').text (declination (fullHours, ['час', 'часа', 'часов']));
          
          $('#stockExpiration .timer .m .v').text (minutes < 10 ? '0' + minutes : minutes);
          $('#stockExpiration .timer .m .t').text (declination (minutes, ['минута', 'минуты', 'минут']));
          
          $('#stockExpiration .timer .s .v').text (nSeconds < 10 ? '0' + nSeconds : nSeconds);
          $('#stockExpiration .timer .s .t').text (declination (nSeconds, ['секунда', 'секунды', 'секунд']));
        }
      }
      setInterval (timed, 1000);
      $('#stockExpiration .timer').show ();
      timed ();
    });
  }









