var navwidth = 0;
var galleryview = 1; // По умолчанию стоит первый вид отображения
var openmenu = 0; // Флаг открытого меню
var globalProductID = 0; //Идентификатор продукта, открытого на экране
var globalProductIDHref = ''; //Ссылка, куда стоит перейти по нажатию кнопки Enter
var startSlider = 0; //Начальная позиция слайдера
$(document).ready(function(){
	
	/*Устанавливаем нужный фон*/
	setBG();
	/*Устанавливаем нужный фон*/
	
	
	if(jQuery.browser.msie) {
		navwidth = navwidth - document.body.clientWidth + 36;
	} else {
		navwidth = navwidth - window.innerWidth + 36;
	}
	
	
	$("#navbar").slider({
			orientation: "gorizontal",
			range: "min",
			min: 0,
			max: navwidth,
			value: startSlider,
			slide: function(event, ui) {
				$("#gallery-short").css('margin-left', -1 * ui.value);
			}
	});
	if (typeof searchScroll == 'function') {
		searchScroll();
	}
	
	
	$('#m2, #m4, #m5').hover(function(){
		$('#m-coll-1,#m-coll-2, #m-coll-3').css('display', 'none');
	});
	$('#m1').hover(function(){
		$('#m-coll-2, #m-coll-3').css('display', 'none');
		$('#m-coll-1').css('display', 'block');
	});
	$('#m3').hover(function(){
		$('#m-coll-1, #m-coll-3').css('display', 'none');
		$('#m-coll-2').css('display', 'block');
	});
	$('#m6').hover(function(){
		$('#m-coll-1, #m-coll-2').css('display', 'none');
		$('#m-coll-3').css('display', 'block');
	});
	$('#w1').hover(function(){
		$('#w-coll-2, #w-coll-3').css('display', 'none');
		$('#w-coll-1').css('display', 'block');
	});
	$('#w2').hover(function(){
		$('#w-coll-1, #w-coll-3').css('display', 'none');
		$('#w-coll-2').css('display', 'block');
	});
	$('#w3').hover(function(){
		$('#w-coll-1, #w-coll-2').css('display', 'none');
		$('#w-coll-3').css('display', 'block');
	});
	
	/*Выпадающие списки*/
	$('#men-link').hover(function(){
		openmenu = 1;
		$('#m, #mw').css('display', 'block');
		$('#w').css('display', 'none');
	}, function(){
		openmenu = 0;
	});
	
	$('#woman-link').hover(function(){
		openmenu = 1;
		$('#w, #mw').css('display', 'block');
		$('#m').css('display', 'none');
	}, function(){
		openmenu = 0;
	});
	
	$('#m, #mw, #w, #m a, #w a').hover(function(){
		openmenu = 1;
	}, function(){
		openmenu = 0;
	});
	
	$('.closemenu').hover(function(){
		openmenu = 0;
		$('#w, #mw').css('display', 'none');
		$('#m').css('display', 'none');
	}, function(){});
	
	
	/*Таймер, который будет следить за меню и закрывать его каждые 2 секунды, если это нужно*/
	$(document).everyTime(2000, function(i) {
		if(openmenu == 0) {
			$('#w, #mw').css('display', 'none');
			$('#m').css('display', 'none');
		}
		//$(this).text(i);
	});
	
	/*Кнопка "Изменить вид"*/
	$('#changeview').click(function(){
		if( galleryview == 1 ) {
			galleryview = 2;
			$('#gallery-view1').css('display', 'block');
			$('#gallery-view2').css('display', 'none');
		} else {
			galleryview = 1;
			$('#gallery-view2').css('display', 'block');
			$('#gallery-view1').css('display', 'none');
		}
			setCookie('galleryview', galleryview);
			return false;
	});
	/*Кнопка "Изменить вид"*/
	
	/*Кнопка "Показать только то, что сейчас есть в наличии на складе"*/
	$('#onlyinstock').click(function(){
		document.onlyinstock.submit();
		return false;
	});
	
	
	
	
	/*Плюсик, ездиющий за курсором*/
	$('.gallery-short-item .highslide').hover(function(){
		var cursor = doSomething();
		$('#plus').css({
			'top': cursor.y,
			'left': cursor.x,
			'display': 'block'
		});
		$(document).mousemove(function(event){
			$('#plus').css({
				'top': event.pageY-20,
				'left': event.pageX-20
			});
		});
	}, function(){
		$('#plus').css({
			'display': 'none'
		});
	});
	/*Плюсик, ездиющий за курсором*/
	
	/*Кнопка "Заказать" в категории товаров*/
	$('.button-order').click(function(){
		/*Ajax добавляет товар в корзину*/
		var tempID = $(this).attr('rel'); //Идентификатор товара
		var thisButton = $(this);
		
		var newButton = $(this).parent().find('.button-ordered');
		$.ajax({
			url: '/shop.ajax.php',
			data: 'ajaxaction=addcart&id_product=' + tempID,
			success: function(data) {
				thisButton.css('display', 'none');
				//newButton.css('display', 'block !important');
				newButton.css('display', 'none');
				$('.button-order[rel=' + tempID + ']').css('display', 'none');
				//$('.button-ordered[rel=' + tempID + ']').css('display', 'block !important');
				$('.button-ordered[rel=' + tempID + ']').css('display', 'none');
			}
		});
		
		return false;
	});
	/*Кнопка "Заказать" в категории товаров*/
	
	
	/*Обработчик поиска по артиклу*/
	$('#search').keyup(function(){
		var search = $(this).val();
		$.ajax({
			url: '/shop.ajax.php',
			data: 'ajaxaction=search&art=' + search,
			success: function(data) {
				if(data != '') {
					
					$('#searchbutton').css('cursor', 'pointer');
					
					var JSONObject = JSON.parse(data);
					var img = JSONObject.img;
					$('#searchfoto').css('display', 'block').html('<img src="' + img + '">');
					
					
					$('#searchForm').submit(function(){
						$(this).attr('action', "/shop/category/" + JSONObject.dscid + '-' + JSONObject.altname + '.html');
					});
					
					
					
					$('#searchbutton').click(function(){
						$('#searchForm').submit();
					});
					
				} else {
					$('#searchfoto').css('display', 'none');
					$('#searchbutton').css('cursor', 'default');
					$('#searchbutton').unbind('click');
				}
			}
		});
	});
	
	$('#search').focus(function(){
		var search = $(this).val();
		$.ajax({
			url: '/shop.ajax.php',
			data: 'ajaxaction=search&art=' + search,
			success: function(data) {
				if(data != '') {
					$('#searchfoto').css('display', 'block').html('<img src="' + data + '">');
				} else {
					$('#searchfoto').css('display', 'none');
				
				}
			}
		});
	});
	
	$('#search').blur(function(){
		$('#searchfoto').css('display', 'none');
		$('#searchbutton').css('cursor', 'default');
	});
	
	
	
	/*Большая фотография - наводим на кнопку "Информация"*/
	/*
	$('#big-info').hover(function(){
		$('#big-info-window').css('display', 'block');
		$('#big-info-window').css('visibility', 'visible');
		$('#big-info-window').css('opacity', 1);
	}, function(){
		
	});
	*/
	/*Большая фотография - наводим на кнопку "Информация"*/
	
	$('.button-info').hover(function(){
		$(this).parent().find('.block-info').css('display', 'block');
	}, function(){
		$(this).parent().find('.block-info').css('display', 'none');
	});
	
	
	/*Кнопка вперед*/
	$('#navbar-right').click(function(){
		nextHS();
	});
	/*Кнопка вперед*/
	
	/*Кнопка назад*/
	$('#navbar-left').click(function(){
		prevHS();
	});
	/*Кнопка назад*/
	
});
	
	/*Функция для перелистывания галереи вперед*/
	function nextHS() {
		if( $("#gallery-short").html() != null ) {
			var marginLeft = $("#gallery-short").css('margin-left');
			marginLeft = marginLeft.replace('px', '') * 1 - 191;
			if( navwidth < -1 * marginLeft  ) {
				marginLeft = -1 * navwidth;
			}
			$("#gallery-short").css('margin-left', marginLeft);
			$("#navbar").slider('value', $("#navbar").slider('value') + 190);
		}
		hs.next();
		return false;
	}
	/*Функция для перелистывания галереи вперед*/
	
	/*Функция для перелистывания галереи назад*/
	function prevHS() {
		if( $("#gallery-short").html() != null ) {
			var marginLeft = $("#gallery-short").css('margin-left');
			marginLeft = marginLeft.replace('px', '') * 1 + 191;
			
			if( marginLeft > 0  ) {
				marginLeft = 0;
			}
			$("#gallery-short").css('margin-left', marginLeft);
			$("#navbar").slider('value', $("#navbar").slider('value') - 190);
		}
		hs.previous();
		return false;
	}
	/*Функция для перелистывания галереи назад*/
	
	/*
	function changeInfo( obj ) {
		var htmlTemp = $(obj).parent().parent().find('.block-info').html();
		$('.ggfhedwef').html( htmlTemp );
	}
	*/
	
	/*Функция добавления глобального товара в корзину*/
	function getOrder( obj ) {
		var tempID = globalProductID; //Идентификатор товара
		
		$.ajax({
			url: '/shop.ajax.php',
			data: 'ajaxaction=addcart&id_product=' + tempID,
			success: function(data) {
				$( obj ).css('display', 'none');
				$( '.button-order[rel=' + tempID + ']' ).css('display', 'none');
				$( '.button-ordered[rel=' + tempID + ']' ).css('display', 'block !important');
			}
		});
		return false;
	}
	/*Функция добавления глобального товара в корзину*/
	
	function doSomething(e) {
		var posx = 0;
		var posy = 0;
		if (!e) var e = window.event;
		if (e.pageX || e.pageY) 	{
			posx = e.pageX;
			posy = e.pageY;
		}
		else if (e.clientX || e.clientY) 	{
			posx = e.clientX + document.body.scrollLeft
				+ document.documentElement.scrollLeft;
			posy = e.clientY + document.body.scrollTop
				+ document.documentElement.scrollTop;
		}
		return {x: posx, y:posy};
		// posx and posy contain the mouse position relative to the document
		// Do something with this information
	}

/*Увеличение фотографий*/

	hs.graphicsDir = '/templates/Urbano/css/graphics/';
	hs.align = 'center';
	hs.transitions = ['expand', 'crossfade'];
	hs.wrapperClassName = 'dark borderless floating-caption';
	hs.fadeInOut = true;
	hs.dimmingOpacity = .75;
	hs.outlineType = 'rounded-white';
	hs.numberOfImagesToPreload = 0;
	hs.showCredits = false;
	
	hs.registerOverlay({
		thumbnailId: null,
		overlayId: 'hte-highslide-next',
		position: 'middle right',
		hideOnMouseOut: true,
		offsetX: -20,
		opacity: 0.8
	});
	
	hs.registerOverlay({
		thumbnailId: null,
		overlayId: 'hte-highslide-previous',
		position: 'middle left',
		hideOnMouseOut: true,
		offsetX: 20,
		opacity: 0.8
	});
	
	hs.registerOverlay({
		thumbnailId: null,
		overlayId: 'big-images',
		position: 'top left',
		hideOnMouseOut: true,
		offsetX: -150,
		opacity: 1,
		className: 'o-h'
	});
	
	hs.lang = {
		loadingText :     'Загрузка...',
		playTitle :       'Просмотр слайдшоу (пробел)',
		pauseTitle:       'Пауза',
		previousTitle :   'Предыдущее изображение',
		nextTitle :       'Следующее изображение',
		moveTitle :       'Переместить',
		closeTitle :      'Закрыть (Esc)',
		fullExpandTitle : 'Развернуть до полного размера',
		restoreTitle :    'Кликните для закрытия картинки, нажмите и удерживайте для перемещения',
		focusTitle :      'Сфокусировать',
		loadingTitle :    'Нажмите для отмены'
	};
	/*
	hs.registerOverlay({
		thumbnailId: null,
		overlayId: 'big-info-wrap',
		position: 'bottom left',
		hideOnMouseOut: true,
		opacity: 0.8,
		className: 'o-h'
	});
	*/
	
	// Add the controlbar
	if (hs.addSlideshow) hs.addSlideshow({
		slideshowGroup: 1,
		interval: 5000,
		repeat: false,
		useControls: false,
		fixedControls: 'fit',
		overlayOptions: {
			opacity: 0.6,
			position: 'top center',
			hideOnMouseOut: true
		}
	});


/*Увеличение фотографий*/


function setCookie(name, value, expires, path, domain, secure) {
        var curCookie = name + "=" + escape(value) +
                ((expires) ? "; expires=" + expires.toGMTString() : "") +
                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                ((secure) ? "; secure" : "")
	
        if ((name + "=" + escape(value)).length <= 4000) {
                document.cookie = curCookie
		} else {
                if (confirm("Cookie превышает 4KB и будет вырезан !"))
                        document.cookie = curCookie
		}
}
