jQuery(document).ready(function(){
	 $('.spheres_item').mouseover(function(){
	 	  $('#spheres_img').attr('src', '/i/spheres_'+$(this).attr('id')+'.png');
	 }).mouseout(function(){
	 	  $('#spheres_img').attr('src', '/i/spheres_grayscale.png');
	 });


	$('.placeholder_search').focus(function() {
		if($(this).val() == 'поиск') { $(this).val(""); }
	}).blur(function() {
		if($(this).val() == "") { $(this).val('поиск'); }
	});
	

	/* Галерея */
	if($(".highslide-gallery").length) {
		hs.graphicsDir = '/libs/highslide/graphics/';
		hs.align = 'center';
		hs.transitions = ['expand', 'crossfade'];
		hs.fadeInOut = true;
		hs.dimmingOpacity = 0.8;
		hs.outlineType = 'rounded-white';
		hs.marginBottom = 175; // make room for the thumbstrip and the controls
		hs.numberPosition = 'caption';
		hs.zIndexCounter = 5500;
		hs.lang = {
				cssDirection: 'ltr',
				loadingText : 'Загрузка...',
				loadingTitle : 'Кликните для отмены',
				focusTitle : 'Кликните, чтобы перенести на передний план',
				fullExpandTitle : 'Расширить до настоящего размера (f)',
				creditsText : '',
				creditsTitle : '',
				previousText : '',
				nextText : '', 
				moveText : 'Двигать',
				closeText : '', 
				closeTitle : 'Закрыть (esc)', 
				resizeTitle : 'Изменить размер',
				playText : 'Слайд-шоу',
				playTitle : 'Запустить слайд-шоу (spacebar)',
				pauseText : 'Пауза',
				pauseTitle : 'Приостановить слайд-шоу (spacebar)',
				previousTitle : 'Предыдущее изображение (arrow left)',
				nextTitle : 'Следующее изображение (arrow right)',
				moveTitle : 'Двигать',
				fullExpandText : 'Показать масштаб 1:1',
				number: 'Фотография %1 из %2',
				restoreTitle : 'Кликните, чтобы закрыть изображение, кликните и тащите, чтобы двигать. Используйте клавиши стрелок для перемещения вперёд и назад.'
			};
		
		// Add the slideshow providing the controlbar and the thumbstrip
		hs.addSlideshow({
			interval: 5000,
			repeat: false,
			useControls: true,
			overlayOptions: {
				className: 'text-controls',
				position: 'bottom center',
				relativeTo: 'viewport',
				offsetY: -100
			},
			thumbstrip: {
				position: 'bottom center',
				mode: 'horizontal',
				relativeTo: 'viewport'
			}
		});

	}
	
	/* Фото одиночное */
	if($(".highslide-photo").length) {
		hs.graphicsDir = '/libs/highslide/graphics/';
		hs.align = 'center';
		hs.transitions = ['expand', 'crossfade'];
		hs.fadeInOut = true;
		hs.dimmingOpacity = 0.8;
		hs.outlineType = 'rounded-white';
		hs.zIndexCounter = 5500;
		hs.lang = {
				cssDirection: 'ltr',
				loadingText : 'Загрузка...',
				loadingTitle : 'Кликните для отмены',
				focusTitle : 'Кликните, чтобы перенести на передний план',
				fullExpandTitle : 'Расширить до настоящего размера (f)',
				creditsText : '',
				creditsTitle : '',
				previousText : '',
				nextText : '', 
				moveText : 'Двигать',
				closeText : '', 
				closeTitle : 'Закрыть (esc)', 
				resizeTitle : 'Изменить размер',
				playText : 'Слайд-шоу',
				playTitle : 'Запустить слайд-шоу (spacebar)',
				pauseText : 'Пауза',
				pauseTitle : 'Приостановить слайд-шоу (spacebar)',
				previousTitle : 'Предыдущее изображение (arrow left)',
				nextTitle : 'Следующее изображение (arrow right)',
				moveTitle : 'Двигать',
				fullExpandText : 'Показать масштаб 1:1',
				number: 'Фотография %1 из %2',
				restoreTitle : 'Кликните, чтобы закрыть изображение, кликните и тащите, чтобы двигать. Используйте клавиши стрелок для перемещения вперёд и назад.'
			};
	}
	
	
	/* Доска почета */
	if($(".highslide-honors").length) {
		hs.graphicsDir = '/libs/highslide/graphics/';
		hs.wrapperClassName = 'draggable-header';
		hs.outlineType = 'rounded-white';
		hs.zIndexCounter = 5500;
		hs.minWidth = 700;
		hs.marginBottom = 100;
		hs.showCredits = false;
		hs.align = 'center';
		hs.padToMinWidth = true;
		hs.dimmingOpacity = 0.5;
		
		hs.lang = {
				loadingText : 'Загрузка...',
				loadingTitle : 'Кликните для отмены',
				moveText : 'Двигать',
				closeText : 'Закрыть', 
				closeTitle : 'Закрыть (esc)', 
				resizeTitle : 'Изменить размер',
				moveTitle : 'Двигать'
		};
	}
	
	/* Калькулятор ж/д тарифов */
	if($(".highslide-metall-calc").length) {
		hs.graphicsDir = '/libs/highslide/graphics/';
		hs.wrapperClassName = 'draggable-header';
		hs.outlineType = 'rounded-white';
		hs.zIndexCounter = 5500;
		hs.minWidth = 700;
		hs.marginBottom = 100;
		hs.showCredits = false;
		hs.align = 'center';
		hs.padToMinWidth = true;
		hs.dimmingOpacity = 0.5;
		
		hs.lang = {
				loadingText : 'Загрузка...',
				loadingTitle : 'Кликните для отмены',
				moveText : 'Двигать',
				closeText : 'Закрыть', 
				closeTitle : 'Закрыть (esc)', 
				resizeTitle : 'Изменить размер',
				moveTitle : 'Двигать'
		};
	}
	
	
	save_screen_params();
});

function intval(mixed_var) {
	var type = typeof(mixed_var);
	
	if (type === 'string') {
		tmp = parseInt(mixed_var);
		return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp;
	} else if (type === 'number' && isFinite(mixed_var)) {
		return Math.floor(mixed_var);
	} else {
		return 0;
	}
}

function floatval (mixed_var) {
    return (parseFloat(mixed_var) || 0);
}

function number_format (number, decimals, dec_point, thousands_sep) {
	number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
	var n = !isFinite(+number) ? 0 : +number,
	prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
	sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
	dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
	s = '',
	toFixedFix = function (n, prec) {
		var k = Math.pow(10, prec);
		return '' + Math.round(n * k) / k;
	};
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    
	s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
	if (s[0].length > 3) {
		s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
	}
	if ((s[1] || '').length < prec) {
		s[1] = s[1] || '';
		s[1] += new Array(prec - s[1].length + 1).join('0');
	}
	return s.join(dec);
}

/* сохранение параметров экрана*/
function save_screen_params(){
	if(window.innerWidth){
		width = window.innerWidth;
		height = window.innerHeight;
	} else if(document.documentElement && document.documentElement.clientWidth){
		width = document.documentElement.clientWidth;
		height = document.documentElement.clientHeight;
	} else if(document.body && document.body.clientWidth){
		width = document.body.clientWidth;
		height = document.body.clientHeight;
	}
	
	setCookie("screen_width", width, false, '/');
	setCookie("screen_height", height, false, '/');
}

function setCookie(name, value, expires, path, domain, secure) {
	if (!name || !value) return false;
	var str = name + '=' + encodeURIComponent(value);
	
	if (expires) str += '; expires=' + expires.toGMTString();
	if (path)    str += '; path=' + path;
	if (domain)  str += '; domain=' + domain;
	if (secure)  str += '; secure';
	
	document.cookie = str;
	return true;
}

function getCookie(name) {
	var pattern = "(?:; )?" + name + "=([^;]*);?";
	var regexp  = new RegExp(pattern);
	
	if (regexp.test(document.cookie))
	return decodeURIComponent(RegExp["$1"]);
	
	return false;
}


/**
 * Добавление товара в корзину
 */
function add_to_basket(uri, id, city, color) {
	$.ajax({
		type: "GET",
		dataType: "json",
		data: {'good': id, 'city': city, 'ajax': 1},
		url: uri +"/add",
		
		beforeSend : function(){
			$("#good"+id).hide();
			$("#good"+id).after('<div>'+$('#img_loader_'+color).html()+'</div>');
		},
		success: function(data){
			if (data.request == true) {
				$('#price').text(data.total);
				$('#unit').text(data.total_unit);
				
				$("#good"+id+" + div").html('<b>Товар в корзине</b>');
			} else {
				$("#good"+id+" + div").html('<span style="color:red;">ошибка</span>');
				setTimeout(function(){ 
					$("#good"+id+" + div").remove();
					$("#good"+id).fadeIn(250);
				}, 2000);
			}
		},
		error : function(data, error){
			$("#good"+id+" + div").html('<span style="color:red;">ошибка</span>');
			setTimeout(function(){ 
				$("#good"+id+" + div").remove();
				$("#good"+id).fadeIn(250);
			}, 2000);
		}
	});
}

/**
 * Удаление товара из корзину
 */
function del_from_basket(uri, id, color) {
	$.ajax({
		type: "GET",
		dataType: "json",
		data: {'order': id, 'ajax': 1},
		url: uri +"/delete",
		
		beforeSend : function(){
			$("#order"+id).hide();
			$("#order"+id).after('<div>'+$('#img_loader_'+color).html()+'</div>');
		},
		success: function(data){
			if (data.request == true) {
				$("#order"+id).parent().parent().hide(500).remove();
				$("#total").text(data.total);
			} else {
				$("#order"+id+" + div").html('<span style="color:red;">ошибка</span>');
				setTimeout(function(){ 
					$("#order"+id+" + div").remove();
					$("#order"+id).fadeIn(250);
				}, 2000);
			}
		},
		error : function(data, error){
			$("#order"+id+" + div").html('<span style="color:red;">ошибка</span>');
			setTimeout(function(){ 
				$("#order"+id+" + div").remove();
				$("#order"+id).fadeIn(250);
			}, 2000);
		}
	});
}
