document.documentElement.id = "js";

//возвращает cookie если есть или undefined
function getCookie(name) {
	var matches = document.cookie.match(new RegExp(
	  "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
	))
	return matches ? decodeURIComponent(matches[1]) : undefined 
}

// уcтанавливает cookie
function setCookie(name, value, props) {
	props = props || {}
	var exp = props.expires
	if (typeof exp == "number" && exp) {
		var d = new Date()
		d.setTime(d.getTime() + exp*1000)
		exp = props.expires = d
	}
	if(exp && exp.toUTCString) { props.expires = exp.toUTCString() }

	value = encodeURIComponent(value)
	var updatedCookie = name + "=" + value
	for(var propName in props){
		updatedCookie += "; " + propName
		var propValue = props[propName]
		if(propValue !== true){ updatedCookie += "=" + propValue }
	}
	document.cookie = updatedCookie

}

// удаляет cookie
function deleteCookie(name) {
	setCookie(name, null, { expires: -1 })
}


// показ тултипа
function showTooltip() {
	// hack. клик по ссылке, у которой вызывается тултип.
	var href = $('.js-tooltip-init').attr('href');
	$('.js-tooltip-init').bind('click', function() {
		location.href = $(this).attr('rel');
	});
	
	if (typeof $.fn.tooltip !== undefined) {
		$('.js-tooltip-init').removeAttr('href');
		$('.js-tooltip-init').tooltip({
			tip: '.b-personal-item-info',
			relative: true,
			position: 'center right',
			offset: [-45, -50]
		});
	}
}

function hider() {
	$('.js-hider-head').click(function() {
		if (!$(this).hasClass('js-hider-selected')) {
			$(this).addClass('js-hider-selected');
			$(this).next('.js-hider-body').slideToggle('slow');
		} else {
			$(this).removeClass('js-hider-selected');
			$(this).next('.js-hider-body').slideToggle('slow');
		};
		return false;
	});
}

function giant_enemy_tab(tab_dl_id) {
	$('#' + tab_dl_id + ' dt.b-tabs__tab-title').click(function(){
		$('#' + tab_dl_id + ' dt.b-tabs__tab-title').removeClass('selected');
		$('#' + tab_dl_id + ' dd.b-tabs__tab-content').removeClass('selected');
		$(this).addClass('selected');
		$(this).next('dd.b-tabs__tab-content').addClass('selected');
	});
}









function shop_footer_scrollbar(sContainerElementId, columnsPerPage) {

	$('#' + sContainerElementId).bind('shop_footer_scrollbar_show', function(){
		update();
	});

	//scrollpane parts
	var scrollPane = $('#' + sContainerElementId + ' .b-slider-box');
	var scrollContent = $('#' + sContainerElementId + ' .b-slider-list');
	var iElementsCount = $('#' + sContainerElementId + ' .b-slider-list-item').size();
	var index = 0;

	if (iElementsCount <= columnsPerPage) {
		$('#' + sContainerElementId + ' .b-slider__step-navi_left').hide();
		$('#' + sContainerElementId + ' .b-slider__step-navi_right').hide();
		$('#' + sContainerElementId + ' .b-slider-list-item').width( scrollPane.width() / columnsPerPage );
		return;
	} else {
		$('#' + sContainerElementId + ' .b-slider__step-navi_left').show();
		$('#' + sContainerElementId + ' .b-slider__step-navi_right').show();
	}
	
	function update() {
		
		//scrollContent.css('left',(-1 * index * scrollPane.width() / columnsPerPage) + 'px');
		
		scrollContent.animate({
			left: (-1 * index * scrollPane.width() / columnsPerPage)
		}, 400, function() {
			// Animation complete.
		});

		// $('#' + sContainerElementId + ' .b-slider-list-item').animate({
			// width: scrollPane.width() / columnsPerPage
		// }, 1000, function() {
			// // Animation complete.
		// });
		
		$('#' + sContainerElementId + ' .b-slider-list-item').width(Math.floor(scrollPane.width() / columnsPerPage - 3));
	}
	
	$('#' + sContainerElementId + ' .b-slider__step-navi_left').click(function(){
		if (index > 0) {
			index--;
			update();
		}
	});
	$('#' + sContainerElementId + ' .b-slider__step-navi_right').click(function(){
		if (iElementsCount - index > columnsPerPage) {
			index++;
			update();
		}
	});

	$( window ).resize(function() {
		update();
	});
	//init scrollbar size
	setTimeout( update, 10 );//safari wants a timeout
}

function scrollbar( sContainerElementId ) {
	//scrollpane parts
	var scrollPane = $( '#' + sContainerElementId + ' .scroll-pane' ),
		scrollContent = $( '#' + sContainerElementId + ' .scroll-content' );
	
	if ($('#' + sContainerElementId + ' .b-slider-list-item').size() <= 5) {
		$('#' + sContainerElementId + ' .b-slider-control').addClass('b-none');
		return;
	}
	
	$('#' + sContainerElementId + ' .b-slider-list-item').width( $('#' + sContainerElementId + ' .b-slider-box').width() / 5 );
	
	scrollContent.width( 
		$('#' + sContainerElementId + ' .b-slider-list-item').size() * 
		$('#' + sContainerElementId + ' .b-slider-list-item').width()
		);
	//build slider
	var scrollbar = $( '#' + sContainerElementId + ' .scroll-bar' ).slider({
		slide: function( event, ui ) {
			if ( scrollContent.width() > scrollPane.width() ) {
				scrollContent.css( "margin-left", Math.round(
					ui.value / 100 * ( scrollPane.width() - scrollContent.width() )
				) + "px" );
			} else {
				scrollContent.css( "margin-left", 0 );
			}
		},
		stop:  function( event, ui ) {
			scrollbar.width( "100%" );
		}
	});
	
	//append icon to handle
	var handleHelper = scrollbar.find( ".ui-slider-handle" )
	.mousedown(function() {
		scrollbar.width( handleHelper.width() );
	})
	.mouseup(function() {
		scrollbar.width( "100%" );
	})
	.wrap( "<div class='ui-handle-helper-parent'></div>" ).parent();
	
	//change overflow to hidden now that slider handles the scrolling
	scrollPane.css( "overflow", "hidden" );
	
	//size scrollbar and handle proportionally to scroll distance
	function sizeScrollbar() {
		var remainder = scrollContent.width() - scrollPane.width();
		var proportion = remainder / scrollContent.width();
		var handleSize = scrollPane.width() - ( proportion * scrollPane.width() );
		scrollbar.find( ".ui-slider-handle" ).css({
			width: handleSize,
			"margin-left": -handleSize / 2 - 4
		});
		handleHelper.width( "" ).width( scrollbar.width() - handleSize );
		$('#debug').text( scrollPane.width() );
		$('#' + sContainerElementId + ' .ui-handle-helper-parent').width( "" ).width( scrollPane.width() -handleSize - 10 );
		$('#debug').text( $('.ui-handle-helper-parent').width() );
	}
	
	//reset slider value based on scroll content position
	function resetValue() {
		var remainder = scrollPane.width() - scrollContent.width();
		var leftVal = scrollContent.css( "margin-left" ) === "auto" ? 0 :
			parseInt( scrollContent.css( "margin-left" ) );
		var percentage = Math.round( leftVal / remainder * 100 );
		scrollbar.slider( "value", percentage );
	}
	
	//if the slider is 100% and window gets larger, reveal content
	function reflowContent() {
			var showing = scrollContent.width() + parseInt( scrollContent.css( "margin-left" ), 10 );
			var gap = scrollPane.width() - showing;
			if ( gap > 0 ) {
				scrollContent.css( "margin-left", parseInt( scrollContent.css( "margin-left" ), 10 ) + gap );
			}
	}
	
	//change handle position on window resize
	$( window ).resize(function() {
		$('#' + sContainerElementId + ' .b-slider-list-item').width( $('#' + sContainerElementId + ' .b-slider-box').width() / 5 );
	
		scrollContent.width( 
			$('#' + sContainerElementId + ' .b-slider-list-item').size() * 
			$('#' + sContainerElementId + ' .b-slider-list-item').width()
		);
		resetValue();
		sizeScrollbar();
		reflowContent();
	});
	$('#' + sContainerElementId + ' .scroll-bar .ui-slider-handle').addClass('b-billet b-billet_slider-scroll-toddler').append(
		'	<span class="b-billet__in"></span>'
	);
	//init scrollbar size
	setTimeout( sizeScrollbar, 10 );//safari wants a timeout
}


/**
 * class CMediaQueries. 
 * Js-аналог Media Queries для IE. 
 * Не требует подключения сторонних библиотек.
 * 
 * @author	Tikhomirov Yaroslav <Yaroslav.Tihomirov@softline.ru>
 * @example 
 * 			Пример использования (используются функции jQuery):
 * 			var aWidth = [980, 1024, 1280, 1600],
 * 				sMask = 'm-page-width_',
 * 				oMediaQueries = new CMediaQueries(aWidth, sMask); // передаем массив разрешений и маску названия класса
 * 			if ($.browser.msie) {
 * 				$(window).bind('load resize', function() {
 * 					// добавляем новый класс
 * 					// oMediaQueries.getClassNameByWidth() вернет названия класса, которое необходимо добавить к body
 * 					// Ширина окна браузера высчитывается внутри класса.
 * 					$('body').addClass(oMediaQueries.getClassNameByWidth());
 * 				});
 * 			}
 * @since	28.03.2011
 */
function CMediaQueries(aWidth, sMask) {
	/**
	 * Массив допустимых разрешений
	 */
	this.aBodyWidth = aWidth ? aWidth : [];
	
	/**
	 * Маска названия класса
	 */
	this.sMask = sMask ? sMask : '';
	
	/**
	 * Вычисляет минимальное значение величины допустимого разрешения
	 * @returns {Number} МИнимум из this.aBodyWidth
	 */
	this.getMin = function() {
		var iMin = this.aBodyWidth[0];
		
		for (var iKey = 1, iLen = this.aBodyWidth.length; iKey < iLen; iKey++) {
			if (this.aBodyWidth[iKey] < iMin) {
				iMin = this.aBodyWidth[iKey];
			}
		}
		
		return iMin;
	};
	
	/**
	 * Вычисляет максимальное значение величины допустимого разрешения
	 * @returns {Number} Максимум из this.aBodyWidth
	 */
	this.getMax = function() {
		var iMax = this.aBodyWidth[0];
		
		for (var iKey = 1, iLen = this.aBodyWidth.length; iKey < iLen; iKey++) {
			if (this.aBodyWidth[iKey] > iMax) {
				iMax = this.aBodyWidth[iKey];
			}
		}
		
		return iMax;
	};
	
	/**
	 * Вычисляет класс, который необходимо установить body.
	 */
	this.getClassNameByWidth = function() {
		var iMax = this.getMax(),
			iMin = this.getMin(),
			sClassName = '',
			iWindowWidth = getWindowWidth();
		
		if (iWindowWidth > iMax) {
			sClassName = this.sMask + iMax.toString();
		} else if (iWindowWidth <= iMin) {
			sClassName = this.sMask + iMin.toString();
		} else {
			this.aBodyWidth.sort(sortNumber);
			for (var i = 0, iLen = this.aBodyWidth.length; i < iLen; i++) {
				if (this.aBodyWidth[i - 1] != undefined) {
					if (iWindowWidth <= this.aBodyWidth[i] && iWindowWidth > this.aBodyWidth[i - 1]) {
						sClassName = this.sMask + this.aBodyWidth[i].toString();
						break;
					}
				}
			}
		}
		
		return sClassName == '' ? null : sClassName;
	};
	
	/**
	 * Вспомогательная функция для sort: сортировка чисел по возрастанию
	 * @param a 
	 * @param b
	 * @returns {Number}
	 */
	function sortNumber(a, b) {
		return a - b;
	}
	
	/**
	 * Кроссбпаузерно вычисляет ширину окна браузера
	 * @returns {Number} Ширина окна браузера
	 */
	function getWindowWidth() {
		return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientWidth : document.body.clientWidth;
	}
} // class CMediaQueries


/* cufon > */
if (typeof window['Cufon'] == 'function') {
	Cufon.replace('.sScript', { fontFamily: 'Segoe Script' });
	Cufon.replace('.sPrint', { fontFamily: 'Segoe Print' });
}
/* cufon < */


/**
 * Действия после загрузки DOM (jQuery(document).ready())
 */
$(function() {
	/*raphael > */
	if ( $("#status_canvas").html() != null ) {
		var R = Raphael("status_canvas", 250, 25),
			fill_point = "0,0,"+$("#status_canvas").attr("rel")+",25",
			attr = {
				fill: "#d6d6d6",
				"stroke-width": 0,
				"stroke-linejoin": "round"
			},
			attr_fill = {
				fill: "#bc0a0a",
				"stroke-width": 0,
				"stroke-linejoin": "round",
				"clip-rect": fill_point
			},
			figure = {},
			figure_fill = {};
		
		/*figure = R.path("M 0 3 C 84,1 196,1 250,3 L 250 23 C 186,25 62,21 0,23 L 0 3").attr(attr)*/
		console.log(fill_point);
		figure = R.rect(0, 0, 250, 25).attr(attr);
		figure_fill = R.rect(0, 0, 250, 25).attr(attr_fill);
	}
	/*raphael < */
	
	
	var iElHeightHalf = Math.ceil($('.b-online-consult').height() / 2),
		iTop = Math.ceil($(window).height() / 2) - iElHeightHalf;

	$('.b-online-consult').css({marginTop: iTop + 'px'});

	var iBorder = $(document).height() - 550;
	
	if ($('#scroll-gallery-track-nexb-link b-i b-i_48 b-i_48-1t').length > 0) {
		iBorder = $(document).height() - 610;
	}


	// скролинг кнопки он-лайн консультанта
	$(window).scroll(function(){
		var iNewTop = $(window).scrollTop() + iTop;
		
		if (iNewTop <= iBorder) {
			$('.b-online-consult').css({marginTop: iNewTop + 'px'});
		} else {
			$('.b-online-consult').css({marginTop: iBorder + 'px'});
		}
	});
	
	// иммитация тени для текста банера для браузеров не поддерживающих CSS3
	if ($('.b-wide-banner-text').length) {
		$('.b-wide-banner-text').after(
			'<span class="b-wide-banner-text b-wide-banner-text_ie-shadow"><strong class="b-wide-banner-text__heading">AFLEX DISTRIBUTION&nbsp;&mdash; </strong>официальный представитель мировых разработчиков программного&nbsp;обеспечения</span>'
		);
	}
	
	if ( $(".js-hider").html() !=null ) {
		hider();
	}
	if ( $(".b-personal-item-info").html() != null ) {
		showTooltip();
	}
	
	//кнопка запуска онлайн консультанта
	$('.webim_button').click(function(){

		if(navigator.userAgent.toLowerCase().indexOf('opera') != -1 && window.event.preventDefault){ 
			window.event.preventDefault();
		}

		this.newWindow = window.open('http://aflex.ru/webim/client.php?locale=ru&url='+escape(document.location.href)+'&referrer='+escape(document.referrer), 'webim', 'toolbar=0,scrollbars=0,location=0,status=1,menubar=0,width=640,height=480,resizable=1');
		this.newWindow.focus();
		this.newWindow.opener=window;
		return false;		

	});	
	

	$('.stylish_select').each(function(){
		$(this).sSelect();
	});

//	var aWidth = [980, 1024, 1280, 1600],
//		sMask = 'm-page-width_',
//		oClassRegExp = /m-page-width_[0-9]+/,
//		oMediaQueries = new CMediaQueries(aWidth, sMask);
//	
//	// для IE добавляем класс к body
//	if ($.browser.msie) {
//		$(window).bind('load resize', function() {
//			var sBodyCurClass = $('body').attr('class'),
//			aMatches = [];
//			
//			// Проверяем нет ли у body класса типа {mask}[0-9]+
//			// если есть, то удаляем его
//			if ((aMatches = sBodyCurClass.match(oClassRegExp)) != null) {
//				$('body').removeClass(aMatches[0]);
//			}
//			
//			// добавляем новый класс
//			$('body').addClass(oMediaQueries.getClassNameByWidth());
//		});
//	}

});

