// Глобальные переменные
var allW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var allH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var isMobile = (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) ? true : false;
// Мобильное меню
$(function(){
$("#back-top").hide();
$(window).scroll(function (){
if ($(this).scrollTop() > 600){
$("#back-top").fadeIn();
} else {
$("#back-top").fadeOut();
}
});
$("#back-top").click(function (){
$("body,html").animate({
scrollTop:0
}, 800);
return false;
});
// Скрываем/показываем кнопку "Назад"
var urlArr = window.location.href.split('/');
if (urlArr.length > 3 && urlArr[3] != '#' && urlArr[3] != '') $('#back').css({'display':'block'});
// Скрываем/показываем панель меню вверху
var lastScrollTop = 0, delta = 5;
$(window).scroll(function(event){
var st = $(this).scrollTop();
// Отключаем/включаем фикс. фона
if (st > allH+30) {
$('#main-slider, #main-slider1').removeClass('back');
} else {
$('#main-slider, #main-slider1').addClass('back');
}
if (Math.abs(lastScrollTop - st) <= delta) return;
if (st >= lastScrollTop && st >= 200 && !$("#mobile-menu").hasClass('slideOutUp')){
// Скролл вниз
$("#mobile-menu").addClass('slideOutUp').removeClass('slideInDown').hover();
}
if (st < lastScrollTop && !$("#mobile-menu").hasClass('slideInDown')) {
// Скролл вверх
$("#mobile-menu").addClass('slideInDown').removeClass('slideOutUp');
}
lastScrollTop = st;
});
// Отображение/скрытие панели меню
$('#menu').on('click', function() {
if ($('#mobile-view').hasClass('slideInRight')) return;
$('#mobile-view').css({'display':'block'}).addClass('slideInRight').removeClass('slideOutRight');
});
$('#menu-close').on('click', function() {
$('#mobile-view').addClass('slideOutRight').removeClass('slideInRight').css({'display':'none'});
});
// Разворачиваем/сворачиваем доп. меню
$('.mobile-main').on('click', function() {
if ($(this).attr('href') != '' && $(this).attr('href') != '#') return;
if ($(this).next('.mobile-menu-sub').css('display') == 'block') {
$(this).next('.mobile-menu-sub').css({'display':'none'});
$(this).children('img').attr('src', '/img/mob_icon/down.png');
return;
}
$('.mobile-menu-sub').css({'display':'none'});
$('.mobile-main').children('img').attr('src', '/img/mob_icon/down.png');
if ($(this).next().hasClass('mobile-menu-sub')) {
$(this).children('img').attr('src', '/img/mob_icon/up.png');
$(this).next('.mobile-menu-sub').css({'display':'block'});
}
});
});
// Мобильное меню - Конец
// Форма обратной связи popup_banner_exit
function callBackForm() {
if ($('.popup').find('#callBackForm').length === 0) {
popup ('form', '', 'callBackForm', false, false);
}
}
// При готовности DOM
$(function() {
preloader();
// Dadata
$("#company_name").suggestions({
token: "57fd8b411cc7c7dd59f4007427b10047946db3d3",
type: "PARTY",
/* Вызывается, когда пользователь выбирает одну из подсказок */
onSelect: function(suggestion) {
console.log(suggestion.data.inn);
if (typeof suggestion != 'undefined' && typeof suggestion.data != 'undefined' && typeof suggestion.data.inn != 'undefined') {
$('#inn').val(suggestion.data.inn);
}
}
});
// Пролистывания слайдера
$('.button-prev').on('click', function() {
$(this).parents('section').find('.swiper-button-prev').trigger('click');
});
$('.button-next').on('click', function() {
$(this).parents('section').find('.swiper-button-next').trigger('click');
});
// Равномерное размещение плиток каталога в зависимости от разрешения экрана
//if (!isMobile) {
var fullWidthShopList = $('#shop-list').width();
if (typeof $('.gal')[0] != 'undefined') {
console.log(allW / allH);
var fullWidthShopItem = $('.gal')[0].offsetWidth;
if (fullWidthShopItem != 0) {
console.log(fullWidthShopList, fullWidthShopItem);
var newShopItem = Math.round(fullWidthShopList / fullWidthShopItem);
var newWidthShopItem = Math.floor(fullWidthShopList / newShopItem) - 10;
$('.gal').attr('style', 'margin-right: 10px; width: '+newWidthShopItem+'px !important;');
}
}
//}
/*
$('.gal').each(function(index, element) {
console.log($(element).width());
});
*/
// Закрываем popup по нажатию Esc
$('body').on('keyup', function(e) {
if (e.which === 27) {
if ($('body').find('.popup').length > 0) {
$('.close').trigger('click');
}
}
});
// Механизм показа информации при выходе курсора мыши за пределы раб. области браузера и по истечению времени пребывания на странице
// Счетчик показа баннера
/*
var bannerTimerCounter = 0;
if (typeof sessionStorage['bannerView'] == 'undefined') {
var bannerTimer = setInterval(function() {
if (bannerTimerCounter >= 0) {
if (typeof sessionStorage['bannerView'] == 'undefined') popupBanner();
sessionStorage['bannerView'] = false;
}
if (bannerTimerCounter >= 10) {
clearInterval(bannerTimer);
delayClosePopup(500);
}
bannerTimerCounter++;
}, 1000);
}
// Считываем координаты мыши
var oldYMouse = 0;
window.onmousemove = function(event){
if (event.clientY < oldYMouse && event.clientY <= 5 && typeof sessionStorage['bannerViewExit'] == 'undefined') {
clearInterval(bannerTimer);
sessionStorage['bannerViewExit'] = false;
if (window.location.pathname != '/test1') popupBannerExit();
}
oldYMouse = event.clientY;
};
function popupBanner() {
if ($('.popup').find('#popup_banner').length === 0) {
popup ('form', '', 'popup_banner', false, false);
}
}
function popupBannerExit() {
if ($('.popup').find('#popup_banner').length === 0) {
popup ('form', '', 'popup_banner_exit', false, false);
}
}
*/
// Механизм показа информации при выходе курсора мыши за пределы раб. области браузера и по истечению времени пребывания на странице - Конец
// "Ручное" автоперелистование слайдера в связи с рассинхронизацией подсветки заголовков
$('body').on('mouseover', '.swiper-pagination-bullet', function() {
$(this).trigger('click');
clearInterval(slideInt);
});
var slideInt = setInterval(function() {
var cur = $('.swiper-pagination1').children('.swiper-pagination-bullet-active');
if (cur) if (cur.next().length > 0) cur.next().trigger('click'); else $('.swiper-pagination1').children('.swiper-pagination-bullet').first().trigger('click');
}, 5000);
// Если есть указатель на скролл, то выполняем
if (sessionStorage.getItem('scrTo')) {
scr(sessionStorage.getItem('scrTo'));
sessionStorage.removeItem('scrTo');
}
// Подготавливаем бегущую строку
$('.marquee-tips').children('span').first().clone().appendTo('.marquee-tips');
// Если есть новости, отзывы, то делаем превью
if ($('.news').length) {
$('.news').each(function(index, element) {
var hBody = $(element).children('.news-body').height();
var hBody1 = $(element).children('.news-body').children('.news-content').height();
var hBodyW = hBody1 - hBody;
if (hBodyW > 50) {
$(element).find('.news-line').css({'display':'block'});
$(element).addClass('news-hover');
}
});
}
$('.news-hover').on('mouseover', function() {
$(this).children('.c-green').css({'text-decoration':'underline'});
});
$('.news-hover').on('mouseout', function() {
$(this).children('.c-green').css({'text-decoration':'none'});
});
$('.news-hover').on('click', function() {
$('.news-hover').find('.news-body').css({'height':'6.8em'});
$('.news-hover').find('.news-line').css({'display':'block'});
$(this).children('.news-body').css({'height':'unset'});
$(this).find('.news-line').css({'display':'none'});
});
// Блок меню на странице
if ($('#sub-menu-page').length) {
$('#main-content').find('.block').first().append($('#sub-menu-page'));
} else {
$('#main-content').find('.block').first().children('.w33').addClass('w1').removeClass('w33');
}
// Если меню больше по высоте то ограничиваем высоту по размеру блока слева и включаем скролл слоя
var h = $('#sub-menu-page').height() - $('.w33').first().height();
if (h > 30) $('#sub-menu-page').height($('.w33').first().height() - 30).addClass('scroll-menu');
$('#sub-menu-page').lionbars({ autohide: false });
// Слайдеры на страницах
if ($('.swiper-container-page')) {
$('.swiper-container-page').each(function(){
new Swiper($(this), {
pagination: $(this).find('.swiper-pagination'),
paginationClickable: $(this).find('.swiper-pagination'),
nextButton: $(this).find('.swiper-button-next'),
prevButton: $(this).find('.swiper-button-prev'),
slidesPerView: 'auto',
paginationClickable: true,
spaceBetween: 10
});
});
}
// Формы
// Отображение дополнительного контента связанного с радио, или чекбоксом
/*
$('form').on('change', ':checkbox, :radio', function() {
var content = $(this).parent().siblings('.dop-content');
if ( $(this).hasClass('dop-view') ) {
content.slideDown(300);
}
if ( $(this).hasClass('dop-hide') ) {
content.slideUp(300);
}
});
// Получить имена выбранных файлов
$('form').on('change', 'input[type="file"]', function(){
var upload = document.getElementById( $(this).attr('id') );
function getFileNames() {
return Array.prototype.map.call(upload.files, function(file) {
return ' '+file.name;
});
}
$(this).prev('.label-file').children('div').html( getFileNames() );
});
*/
// Формы - Конец
//---- Формы
// Отображение дополнительного контента связанного с радио, или чекбоксом
$('form').on('change', ':checkbox', function() {
if ( $(this).hasClass('d') ) {
if ($(this).is(':checked')) {
$('.dop').slideDown(300);
} else {
$('.dop').slideUp(300);
}
}
resize();
});
// Глобальная переменная куда будут располагаться данные файлов.
var files = '';
// Получить выбранные файлы
$('form').on('change', 'input[type="file"]' , function(){
var upload = document.getElementById( $(this).attr('id') );
files = this.files;
function getFileNames() {
return Array.prototype.map.call(upload.files, function(file) {
return ' '+file.name;
});
}
$(this).prev('.label-file').children('div').html( getFileNames() );
});
// Проверка и отправка данных формы
$('form').validationEngine('attach', {
promptPosition : 'bottomLeft',
onValidationComplete: function(form, status){
if (status === true) {
// id формы для обработки
var formIdOrigin = $(form).attr('id');
// Здесь у нас один обработчик
var formId = 'callback_order';
//var formId = $(form).attr('id');
// Устанавливаем куки для проверки форм
setCookie('sendForm', 'true');
var datas = $(form).serializeArray();
dataSend (formId, datas, files, formIdOrigin);
}
}
});
// Функция отправки данных и файлов
function dataSend (url, datas, files, formIdOrigin) {
// Отображаем прелоадер
preloader('show');
// Создадим данные формы и добавим в них данные файлов из files
var data = new FormData();
$.each( files, function( key, value ){
data.append( key, value );
});
// Создадим данные формы и добавим в них данные из других полей ввода
$.each( datas, function(key, value){
data.append( value.name, value.value );
});
// Отправляем запрос
$.ajax({
url: '/components/'+url+'.php?sharkey='+sharkey,
type: 'POST',
data: data,
cache: false,
async: false,
processData: false,
contentType: false,
success: function (respond, textStatus, jqXHR) {
var respondJson = {};
try {
respondJson = JSON.parse(respond);
} catch (e) {}
if (typeof respondJson.status != 'undefined' && respondJson.status == 'error') {
popup ('bad', 'Ошибка!', respondJson.message, true);
} else {
delayClosePopup (500);
setTimeout(function() {
popup ('good', 'Ваше сообщение отправлено.', 'Спасибо за обращение!', true);
}, 500);
}
delayClosePopup (3000);
delayReload (3000);
return;
},
error: function (jqxhr, status, errorMsg) {
switch (jqxhr.status) {
case 412:
popup ('bad', 'Ошибка!', 'Неверный ключ антиспама.', true);
break;
case 403:
popup ('good', '', 'Сообщение уже отправлено и будет обработано в ближайшее время.', true);
break;
default:
popup ('bad', '', 'Извините, но сервер не отвечает!
Вы можете связаться с нами по телефону, указанному на сайте.', true);
}
return;
},
complete: function () {
preloader();
}
});
}
//---- Формы - Конец
// Главное меню
$('.imenu').first().hover( function () {
$('.mainmenu').toggleClass('mainmenubefore');
});
$('.imenu').last().hover( function () {
$('.mainmenu').toggleClass('mainmenuafter');
});
// Клик на кнопке скролла вниз
$('#down').on('click', function(e){
$('html,body').stop().animate({ scrollTop: $('#main-content').offset().top - 100 }, 1000);
e.preventDefault();
});
// Действия ссылки
var uri = sessionStorage['termart'];
$('body').on('click', '[data-href]', function(e) {
e.preventDefault();
var url = $(this).attr('data-href');
sessionStorage.setItem('termart', url);
var uri = window.location;
uri.href = uri.protocol+'//'+uri.hostname+'/'+url;
});
resize();
uncheckAll();
});
// Действия при события загрузки, изменения размера и ориентации страницы
$(window).on('load resize orientationchange', function() {
resize();
});
// Действия при события прокрутки
$(window).on('scroll', function() {
if ( $(window).scrollTop() >= 190 ) {
$('.mainmenu').addClass('mainmenufix');
$('.menuline').hide();
if ($('.mainmenu-wrap').length === 0) $('.mmw').wrap("
");
$('.mainmenudop').css({'margin-top':$('.mainmenu').height()});
} else {
$('.mainmenu').removeClass('mainmenufix');
$('.menuline').show();
$('.mmw').unwrap('.mainmenu-wrap');
$('.mainmenudop').css({'margin-top':'0em'});
}
});
// Главное меню
var self;
$(document).on('mouseenter', '.imenu', function () {
var t = $(this).attr('rel');
if (t != self) $('.imenudop').hide(250);
self = t;
$('.imenudop[rel="'+t+'"]').show();
$('.mainmenudop').slideDown(250).css({'left': $(this).offset().left });
var width = [];
$('.imenudop[rel="'+t+'"]').children('li').each(function(indx, element){
width.push($(element).outerWidth());
});
var widthM = getMax(width);
// Делаем в 2 ряда первое меню
var twoCol = 1;
if (t == '1311866884') twoCol = 2;
$('.imenudop[rel="'+t+'"]').outerWidth(widthM*twoCol+20);
$('.mainmenudop').outerWidth(widthM*twoCol+20);
$('.imenudop[rel="'+t+'"]').children('li').each(function(indx, element){
$(element).outerWidth(widthM);
});
timerMenu();
});
var tObj = true;
var timerMenu = function() {
var menuTimer = setInterval(function() {
$(document).on('mouseenter', '.imenu, .mainmenudop', function () {
tObj = true;
});
$(document).on('mouseleave', '.imenu, .mainmenudop', function () {
tObj = false;
});
if (!tObj) {
$('.mainmenudop').slideUp(250);
$('.imenudop').hide(250);
clearInterval(menuTimer);
}
}, 500);
}
// Проверка
setInterval(function() {
if ($('.imenudop:hover').length === 0 && $('.imenu:hover').length === 0) {
$('.mainmenudop').slideUp(250);
$('.imenudop').hide(250);
}
}, 1000);
// Действия ссылки
var uri = sessionStorage['siteURL'];
$('body').on('click', '[data-href]', function(e) {
e.preventDefault();
var url = $(this).attr('data-href');
sessionStorage.setItem('siteURL', url);
var uri = window.location;
uri.href = uri.protocol+'//'+uri.hostname+'/'+url;
});
// Скролл до объекта
function scr(obj) {
$('html, body').animate({ scrollTop: $('#'+obj).offset().top - 90 }, 250, 'swing');
}
// Функции для работы с куки
function setCookie(name, value) {
document.cookie = name + '=' + value+'; path=/;';
}
function getCookie(name) {
var r = document.cookie.match("(^|;) ?" + name + "=([^;]*)(;|$)");
if (r) return r[2];
else return "";
}
function deleteCookie(name) {
var date = new Date(); // Берём текущую дату
date.setTime(date.getTime() - 100); // Возвращаемся в "прошлое"
document.cookie = name + "=; path=/; expires=" + date.toGMTString(); // Устанавливаем cookie пустое значение и срок действия до прошедшего уже времени
}
// Функции для работы с куки - Конец
// Макс. и Мин. значения в массиве
function getMax(numArray) {
return Math.max.apply(null, numArray);
}
function getMin(numArray) {
return Math.min.apply(null, numArray);
}
function resize () {
if (allH < 700) allH = 700;
$('#main-slider').height(allH);
$('#main-slider').width(allW);
$('.swiper-container').width(allW);
// Браузер
if ( navigator.userAgent.indexOf('Chrome') !== -1) {
var ml = $('.mainmenu').width()+46;
$('.menuline').width(ml);
}
}
// Снимает все checkbox
function uncheckAll() {
var w = document.getElementsByTagName('input');
for(var i = 0; i < w.length; i++){
if(w[i].type=='checkbox'){
w[i].checked = false;
}
}
}
// Вывод на печать
function toPrint(obj) {
var objPrint = $(obj).parent().parent().clone();
var newWin = window.open('/print.html', 'Вывод на печать', 'width=1200,height=600,resizable=yes,scrollbars=yes,status=no,toolbar=no,location=no,menubar=no');
newWin.onload = function() {
var div = newWin.document.createElement('div');
body = newWin.document.body;
div.innerHTML = objPrint[0].innerHTML;
body.insertBefore(div, body.firstChild);
$(body).find('.print').remove();
$(body).children('div').css({'margin':'5em'});
$(body).children('div').prepend('
Результаты тестирования
');
setTimeout(function() {
newWin.print();
}, 500);
}
}
// Округляем
var rounded = function(number, r){
return +number.toFixed(r);
}
//---- Popup-окна
function popup (type, head, message, other) {
//$('html').css({'overflow-y':'hidden'});
//var pos = $('html,body').scrollTop()+30;
$('body').append('');
var thisH = $('.popup .wind .head').last();
var thisC = $('.popup .wind .cont').last();
switch (type) {
case 'good':
thisH.addClass('good').append(head);
thisC.append(message);
break;
case 'bad':
thisH.addClass('bad').append(head);
thisC.append(message);
break;
case 'atten':
thisH.addClass('atten').append(head);
thisC.append(message);
break;
case 'form-simple':
thisH.addClass('form-simple').append(head);
thisC.append($('#'+message));
break;
case 'form':
thisH.addClass('form').append(head);
thisC.append($('#'+message));
if (other) {
thisC.append( $('#'+other) );
$('#'+other).find('input[name="type"]').val(head);
}
setTimeout(function () {
if (typeof (swipe) != 'undefined') swipe();
}, 500);
break;
default:
thisH.append(head);
thisC.append(message);
}
}
function delayClosePopup (time) {
setTimeout(function() { $('.popup').trigger('click'); }, time);
}
function delayReload (time) {
setTimeout(function() { window.location.reload(); }, time);
}
$(document).on('click', '.popup, .close', function(e) {
var obj = e.target.className;
if ( (obj !== 'close' && obj !== 'popup') ) return;
$('html').css({'overflow-y':'scroll'});
var t = $(this);
t.children('.wind').removeClass('zoomIn').addClass('zoomOut');
t.fadeOut('slow', function() { t.remove(); });
// Если popup больше одного только удаляем верхний, если 1, то переносим контент (это значит, что есть контент, который надо переносить)
if ($('.popup').find('article').length >= 1 && $('.popup').length === 1) $('#_wrap').append( $('.popup').find('article') );
});
// Если изображение
$(document).on('click', '.img', function() {
if( !$('img').is('#popupImg') ) {
var newSrc = $(this).attr('src').split('/');
newSrc[newSrc.length-1] = 'large/'+newSrc[newSrc.length-1];
var i = new Image();
i.src = newSrc.join('/');
i.onload = function() {
var width = i.width;
var height = i.height;
// Масштабируем изображение, исходя из разрешения меньшей стороны экрана
var w = 0;
var margin = 4;
if (allW > allH) {
var k = width / height;
var newH = allH - (allH / margin);
w = 'width="'+newH * k +'" height="'+newH+'"';
} else {
var k = height / width;
var newM = allW - (allW/ margin);
w = 'width="'+newM+'" height="'+newM * k+'"';
}
popup ('', '', '');
setTimeout(function () {
$('.wind').animate({ width: Number($('#popupImg').attr('width')) + 45 }, 100, 'swing');
}, 500);
}
}
});
//---- Popup-окна - Конец
// Preloader
function preloader (action) {
if (action === 'show') {
$('body').append('
Подождите...
');
} else {
var obj = $('.preloader');
obj.fadeOut('slow', function() { obj.remove(); });
}
}
// Preloader - Конец
// Изменение внешнего вида scrollbars
(function( $ ) {
$.fn.hasScrollBar = function() {
return this.get(0).scrollHeight > this.height();
};
$.fn.lionbars = function(options) {
options = options || {};
autohide = options.autohide;
// Flags
var timeout,
HDragging=false,
VDragging=false,
activeScroll=0,
activeWrap=0,
eventX,
eventY,
mouseX,
mouseY,
currentRatio,
initPos,
scrollValue,
hideTimeoutSet=false,
vEventFired = false,
hEventFired = false;
// Initialization
var elements = $(this),
id = 0,
vScrollWidth=0, hScrollWidth=0,
addHScroll=false, addVScroll=false,
paddingTop=0, paddingLeft=0, paddingBottom=0, paddingRight=0,
borderTop=0, borderRight=0, borderBottom=0, borderLeft=0,
scrollHeight=0, scrollWidth=0, offsetWidth=0, offsetHeight=0, clientWidth=0, clientHeight=0,
vRatio=0, hRatio=0,
vSliderHeight=0, hSliderHeight=0,
vLbHeight=0, hLbHeight=0;
// Main Loop
mainLoop();
function mainLoop() {
for (var i=0; elements[i] !== undefined; i++) {
if (needScrollbars(elements[i]) && !$(elements[i]).hasClass('nolionbars')) {
// add the element to the main array
target = elements[i];
// get some values before the element is wrapped
getDimentions(target);
// wrap the element
wrap(target, addVScroll, addHScroll);
// hide the default scrollbar
hideScrollbars(target, addVScroll, addHScroll);
// Calculate the size of the scrollbars
reduceScrollbarsWidthHeight(target);
setSlidersHeight(target);
// Set variables needed to calculate scroll speed, etc.
setScrollRatios(target);
// Set events
setEvents(target);
// prepare for next element
resetVars();
}
}
}
// Set document events
$(document).mousemove(function(e) {
if (VDragging) {
mouseY = e.pageY;
activeWrap.scrollTop((initPos + mouseY - eventY) * Math.abs(currentRatio));
}
if (HDragging) {
mouseX = e.pageX;
activeWrap.scrollLeft((initPos + mouseX - eventX) * Math.abs(currentRatio));
}
});
$(document).mouseup(function(e) {
if (VDragging) {
VDragging = false;
}
if (HDragging) {
HDragging = false;
}
});
// Core functions
function setEvents(elem) {
var el = $(elem);
if (addVScroll || addHScroll) {
el.find('.lb-wrap').scroll(function(e) {
el.find('.lb-v-scrollbar-slider').css({ "top" : -$(this).scrollTop()/el.attr('vratio') });
el.find('.lb-h-scrollbar-slider').css({ "left" : -$(this).scrollLeft()/el.attr('hratio') });
if (el.find('.lb-v-scrollbar').height() == (parseInt(el.find('.lb-v-scrollbar-slider').css('top')) + el.find('.lb-v-scrollbar-slider').height())
&& typeof(options.reachedBottom) == 'function'
&& !vEventFired
) {
vEventFired = true;
var self = $(this);
options.reachedBottom.apply($(this).children('.lb-content'), [function () {
getDimentions($(self).parent(), {
height: $(self).children('.lb-content').get(0).scrollHeight,
width: $(self).children('.lb-content').get(0).scrollWidth
});
// Calculate the size of the scrollbars
reduceScrollbarsWidthHeight($(self).parent());
setSlidersHeight($(self).parent());
// Set variables needed to calculate scroll speed, etc.
setScrollRatios($(self).parent());
// prepare for next element
resetVars();
vEventFired = false;
}]);
}
if (el.find('.lb-h-scrollbar').width() == (parseInt(el.find('.lb-h-scrollbar-slider').css('left')) + el.find('.lb-h-scrollbar-slider').width())
&& typeof(options.reachedRight) == 'function'
&& !hEventFired
) {
hEventFired = true;
var self = $(this);
options.reachedRight.apply($(this).children('.lb-content'), [function () {
getDimentions($(self).parent(), {
height: $(self).children('.lb-content').get(0).scrollHeight,
width: $(self).children('.lb-content').get(0).scrollWidth
});
// Calculate the size of the scrollbars
reduceScrollbarsWidthHeight($(self).parent());
setSlidersHeight($(self).parent());
// Set variables needed to calculate scroll speed, etc.
setScrollRatios($(self).parent());
// prepare for next element
resetVars();
hEventFired = false;
}]);
}
if (autohide) {
el.find('.lb-v-scrollbar, .lb-h-scrollbar').fadeIn(150);
clearTimeout(timeout);
timeout = setTimeout(function() {
el.find('.lb-v-scrollbar, .lb-h-scrollbar').fadeOut(150);
}, 2000);
}
});
}
if (addVScroll) {
el.find('.lb-v-scrollbar-slider').mousedown(function(e) {
eventY = e.pageY;
VDragging = true;
activeScroll = $(this);
activeWrap = el.find('.lb-wrap');
currentRatio = activeWrap.parent().attr('vratio');
initPos = activeScroll.position().top;
return false;
});
el.find('.lb-v-scrollbar').mousedown(function(e) {
if (!$(e.target).hasClass('lb-v-scrollbar-slider')) {
el.find('.lb-wrap').scrollTop((e.pageY - $(this).offset().top) * Math.abs(el.attr('vratio')) - $(this).find('.lb-v-scrollbar-slider').height()/2);
}
return false;
});
}
if (addHScroll) {
el.find('.lb-h-scrollbar-slider').mousedown(function(e) {
eventX = e.pageX;
HDragging = true;
activeScroll = $(this);
activeWrap = el.find('.lb-wrap');
currentRatio = activeWrap.parent().attr('hratio');
initPos = activeScroll.position().left;
return false;
});
el.find('.lb-h-scrollbar').mousedown(function(e) {
if (!$(e.target).hasClass('lb-h-scrollbar-slider')) {
el.find('.lb-wrap').scrollLeft((e.pageX - $(this).offset().left) * Math.abs(el.attr('hratio')) - $(this).find('.lb-h-scrollbar-slider').width()/2);
}
return false;
});
}
if ((addVScroll || addHScroll) && autohide) {
el.find('.lb-v-scrollbar, .lb-h-scrollbar').hide();
el.hover(function() {
}, function() {
el.find('.lb-v-scrollbar, .lb-h-scrollbar').fadeOut(150);
});
}
}
function setScrollRatios(elem) {
vRatio = (offsetHeight - $(elem).find('.lb-wrap').get(0).scrollHeight - borderTop - borderBottom)/(vLbHeight - vSliderHeight);
hRatio = (offsetWidth - $(elem).find('.lb-wrap').get(0).scrollWidth - borderLeft - borderRight)/(hLbHeight - hSliderHeight);
var el = $(elem);
el.attr('vratio', vRatio);
el.attr('hratio', hRatio);
}
function setSlidersHeight(elem) {
var el = $(elem);
var hmin, hmax, gap;
if (el.find('.lb-v-scrollbar').length != 0) {
hmin = 20;
gap = offsetHeight - el.find('.lb-v-scrollbar').height();
hmax = offsetHeight - gap - hmin;
vSliderHeight = Math.round((offsetHeight*hmax)/scrollHeight);
vSliderHeight = (vSliderHeight < hmin) ? hmin : vSliderHeight;
}
if (el.find('.lb-h-scrollbar').length != 0) {
hmin = 20;
gap = offsetWidth - el.find('.lb-h-scrollbar').width();
hmax = offsetWidth - gap - hmin;
hSliderHeight = Math.round((offsetWidth*hmax)/scrollWidth);
hSliderHeight = (hSliderHeight < hmin) ? hmin : hSliderHeight;
}
el.find('.lb-v-scrollbar-slider').css({ "height" : vSliderHeight });
el.find('.lb-h-scrollbar-slider').css({ "width" : hSliderHeight });
}
function resetVars() {
vScrollWidth = 0;
hScrollWidth = 0;
addHScroll=false;
addVScroll=false;
paddingTop = 0;
paddingLeft = 0;
paddingBottom = 0;
paddingRight = 0;
borderTop = 0;
borderLeft = 0;
borderBottom = 0;
borderRight = 0;
scrollHeight = 0;
scrollWidth = 0;
offsetWidth = 0;
offsetHeight = 0;
clientWidth = 0;
clientHeight = 0;
// vRatio = 0;
// hRatio = 0;
vSliderHeight = 0;
hSliderHeight = 0;
vLbHeight = 0;
hLbHeight = 0;
}
function reduceScrollbarsWidthHeight(elem) {
var el = $(elem);
if (addVScroll && addHScroll) {
vLbHeight = el.height()-12;
hLbHeight = el.width()-12;
el.find('.lb-v-scrollbar').css({ "height" : vLbHeight });
el.find('.lb-h-scrollbar').css({ "width" : hLbHeight });
} else {
vLbHeight = el.height()-4;
hLbHeight = el.width()-4;
el.find('.lb-v-scrollbar').css({ "height" : vLbHeight });
el.find('.lb-h-scrollbar').css({ "width" : hLbHeight });
}
}
function hideScrollbars(elem, vscroll, hscroll) {
var el = $(elem);
if (vscroll || hscroll) {
el.css({ "overflow" : 'hidden' });
movePadding(el, el.find('.lb-wrap'));
resizeMainBox(el);
resizeInnerWrap(el, el.find('.lb-wrap'));
}
}
function resizeMainBox(elem) {
var el = $(elem);
el.css({ "width" : el.width() + paddingLeft + paddingRight, "height" : el.height() + paddingTop + paddingBottom });
}
function movePadding(from, to) {
var fromEl = $(from);
var toEl = $(to);
fromEl.css({ "padding" : 0 });
toEl.css({
"padding-top" : paddingTop+'px',
"padding-left" : paddingLeft+'px',
"padding-bottom" : paddingBottom+'px',
"padding-right" : paddingRight+'px'
});
}
function resizeInnerWrap(main, child) {
var mainEl = $(main);
var childEl = $(child);
mainEl.css({ "position" : 'relative' });
childEl.css({
"width" : mainEl.width()+vScrollWidth - paddingLeft - paddingRight,
"height" : mainEl.height()+hScrollWidth - paddingTop - paddingBottom
});
}
function setVScrollbarWidth(elem) {
var el = $(elem);
el.css({ "overflow" : 'auto' });
vScrollWidth = offsetWidth - clientWidth - borderLeft - borderRight;
el.css({ "overflow" : 'hidden' });
}
function setHScrollbarWidth(elem) {
var el = $(elem);
el.css({ "overflow" : 'auto' });
hScrollWidth = offsetHeight - clientHeight - borderTop - borderBottom;
el.css({ "overflow" : 'hidden' });
}
function wrap(elem, vscroll, hscroll) {
var el = $(elem);
var elemId = el.attr('id');
var wrap = 0;
if (elemId !== undefined) {
el.wrapInner('');
wrap = $('#lb-wrap-'+id+'-'+elemId);
} else {
el.wrapInner('');
wrap = $('#lb-wrap-'+id);
}
wrap.wrapInner('');
if (vscroll) {
el.prepend('');
el.find('.lb-v-scrollbar').append('');
}
if (hscroll) {
el.prepend('');
el.find('.lb-h-scrollbar').append('');
}
// preparation for the next element
id = id + 1;
}
function needScrollbars(elem) {
var el = $(elem);
addVScroll = false;
addHScroll = false;
getPadding(el);
getBorders(el);
el.css({ "overflow" : 'hidden' });
// check for vertical scrollbars
if (el.get(0).scrollHeight > el.get(0).clientHeight) {
addVScroll = true;
// setVScrollbarWidth(el);
}
// check for horizontal scrollbars
if (el.get(0).scrollWidth > el.get(0).clientWidth) {
addHScroll = true;
// setHScrollbarWidth(el);
}
el.css({ "overflow" : 'auto' });
if (addVScroll || addHScroll) {
return true;
}
}
function getPadding(elem) {
var el = $(elem);
paddingTop = parseInt(el.css('padding-top').replace('px', ''));
paddingLeft = parseInt(el.css('padding-left').replace('px', ''));
paddingBottom = parseInt(el.css('padding-bottom').replace('px', ''));
paddingRight = parseInt(el.css('padding-right').replace('px', ''));
}
function getBorders(elem) {
var el = $(elem);
borderTop = parseInt(el.css('border-top-width').replace('px', ''));
borderRight = parseInt(el.css('border-right-width').replace('px', ''));
borderBottom = parseInt(el.css('border-bottom-width').replace('px', ''));
borderLeft = parseInt(el.css('border-left-width').replace('px', ''));
}
function getDimentions(elem, scroll) {
var el = $(elem).get(0);
scrollHeight = (typeof(scroll) != 'undefined') ? scroll.height : el.scrollHeight;
scrollWidth = (typeof(scroll) != 'undefined') ? scroll.width : el.scrollWidth;
clientHeight = el.clientHeight;
clientWidth = el.clientWidth;
offsetHeight = el.offsetHeight;
offsetWidth = el.offsetWidth;
setVScrollbarWidth($(elem));
setHScrollbarWidth($(elem));
}
return this.each(function() {
//var $this = $(this);
});
};
})( jQuery );