// JavaScript Document
function _(t){
	text = t?t:'Heloo world!!!';
	alert(text);
	}

function _p(t){
	text = t?t:'Heloo world!!!';
	$('#panel')[0].innerHTML+= '<li>'+text+'</li>';
	}


function inputWidth(){
	$('input[type=radio]')
		.each(function(){
					   var ch = this.checked;
					   if(ch){
						   $(this).parents('label').addClass('b');
						   }
						else{
							$(this).parents('label').removeClass('b');
							}
					   });
	}



function questionOthe(id){
	var topX = document.documentElement.scrollTop + 300;
	var el = id?id:'questionOthe';
	$('#'+el)
		.show()
		.css({
			 top:topX+'px',
			 left:'50%',
			 marginLeft:'-100px'
			 });
	}



var tooltipText; //Здесь храниться текст текущей всплывающей подсказки
var tooltipHover = false;//по этой переменной можно узнать отображается ли всплывающая подсказака или она скрыта
var tooltip;
var iIE6 = true; //NO COMMENTS
//======================================================================================================
//==== MAIN READY ======================================================================================
//======================================================================================================
$(function(){//=========================================================================================
//------------------------------------------------------------------------------------------------------
inputWidth();
$('input[type=radio]')
	.click(inputWidth);


//ЗДЕСЬ
tooltip = $('.pop')
$('.littleBasketItem')
	.live('mouseover',function(Event){
								tooltipHover = true;//при наведении на элемент меняем значение переменной
								var img = $(this).children('img');//картинка на которую наводим, из нее нам нужен title
								if(!img.attr('text')){
									//в этом блоке перемещаем значение title в атрибут text
									//для того что бы title не всплывал при наведении
									img
										.attr('text', img.attr('title'))
										.attr('title', '');
									}
								tooltipText = img.attr('text');//сохраняем текст в переменную
								var coordInfo = $(this).offset();//Получаем координаты блока
								var x = coordInfo.left;
								var y = coordInfo.top +100;
								tooltip//записываем координаты в соответствующие атрибуты
									.attr({
										  top:y+'px',
										  left:x+'px'
										  })
							  })
	.live('mouseout',function(){
							  tooltipHover = false;//курсор уходит, соответственно меняется значение переменной
							  });

$('.tooltipClicker').click(function(Event){
									tooltipText = $(this).children('img').attr('alt');
									var x = Number(Event.pageX)-64;
									var y = Number(Event.pageY)+32;
									tooltip
										.attr({
											  top:y+'px',
											  left:x+'px'
											  })
									tooltipHover = true;
									return false;
									});

$('.pop')
	.hover(
		   function(){
			   tooltipHover = true;//при наведении на элемент меняем значение переменной
			   //ничего вычеслять не надо так как подсказка должна отобрадаться в месть где она была до этого
			   },
		   function(){
			   tooltipHover = false;//курсор уходит, соответственно меняется значение переменной
			   }
		   );

$('body')
	.click(function(){
					tooltipHover = false;
					});

//таймер, который проверяет не находиться ли курсор над элементами, для которых необходима подсказка
//и отображает или скрывает ее, добавляя текст
var tooltipTimer = setInterval(function(){
										//переменная для вычисления высоты подсказки
										//Нужна из-за косяков браузеров
									   var height = 10;
									   if(tooltipHover){
										  tooltip
										  		.children('div')
										  		.each(function(){
									   				var h = $(this).height();
									   				height += h;
									   			})
										  tooltip
										   		.css({
													 left:tooltip.attr('left'),
													 top:tooltip.attr('top')//,
													 //marginTop:'-'+height+'px'
													 })
												.find('p')
												.html(tooltipText);

										   }
									   else{
										    tooltip
										   		.css({
													 left:'-200px',
													 top:'-200px'
													 });
									   }
									   }, 300)

//------------------------------------------------------------------------------------------------------


$('.footer .openText a')
	.click(function(){
					$(this)
						.toggleClass('open')
						.parents('.text')
						.children('.hideText')
						.toggle();
						return false;
					});

//
$('.changeCity span a')
	.click(function(){
					$(this)
						.parents('.changeCity')
						.toggleClass('on');
					return false;
					});
//------------------------------------------------------------------------------------------------------
$('.menu li:first').addClass('first');
$('.menu li:eq(3)').addClass('last')

$('.elMenu')
	.hover(
		   function(){
			   $(this).parents('li').addClass('hover');
			   },
		   function(){
			   $(this).parents('li').removeClass('hover');
			   }
		   );

// Открывает/закрывает меню
//
var listLinks = $('.restaurantMenu .topLink .interiorLink');
listLinks
	.click(function(){
					$(this)
						.parent()
						.toggleClass('active')
						.parent()
						.children('ul')
						.slideToggle();
					return false;
					});

var numlistListLinks = listLinks.length;
var numOpenList =  $('.restaurantMenu li ul:visible').length;

if(numOpenList == 0 && numlistListLinks != 0) {
	$('.restaurantMenu li:first')
		.addClass('open')
		.children('span')
		.addClass('active');
	}
//------------------------------------------------------------------------------------------------------

// Открывает/закрывает списак суши
//
/* slideToggle не работает в ie 8 - потому заменяем на show */
/* $('.sectionTitle h3')
	.click(function(){
					$(this)
						.parent('.sectionTitle')
						.toggleClass('open')
						.children('div')
						.slideToggle();
						return false;
					});
	*/

$('.sectionTitle h3')
	.click(function(){
					if ($(this).children('div:hidden')) {
						$(this)
						.parent('.sectionTitle')
						.addClass('open')
						.children('div')
						.show();
						return false;
					} else {
						$(this)
						.parent('.sectionTitle')
						.removeClass('open')
						.children('div')
						.hide();
						return false;
					}
					//return false;
					});

$('body')
	.click(function(){
					$('.sectionTitle')
						.removeClass('open')
						.children('div')
						.hide();
					});
//------------------------------------------------------------------------------------------------------
$('.spiner input')
		.each(function(){
					   var val = this.value;
						$(this).attr('rel', val);
						})
		.blur(function(){
						var val = this.value;
						 var newV= val.replace(/[^0-9]*/g, '');
						 this.value = newV==''?1:newV;
						 $(this).attr('rel', this.value);
						});


$('.products .spiner .spinerTop')
	.mousedown(function(){return false})
	.click(function(){
					changeCount($(this), 'plus');
					return false;
				  	});


$('.products .spiner .spinerBottom')
	.mousedown(function(){return false})
	.click(function(){
					var val = changeCount($(this), 'minus');
					return false;
});
//------------------------------------------------------------------------------------------------------

$('.listProductTopText .leftEl a')
	.click(function(){
					var el = $('.productsHr2');
					if(this.innerHTML == 'картинками'){
						el.addClass('picType')
						this.innerHTML = 'списком'
						}
					else{
						el.removeClass('picType')
						this.innerHTML = 'картинками'
						}
					return false;
					})
//------------------------------------------------------------------------------------------------------
$('.popapSend')
	.click(function(){return false});

$('.popapSendClose a')
	.click(function(){
					$('#sendEmail')
						.hide();
					return false;
					});

$('.extractRecipe .sendRecipe a')
	.click(function(Event){
					var x = Number(Event.pageX);
					var y = Number(Event.pageY);
					$('.popapSend:hidden')
						.css({
							 top:y+'px',
							 left:x+'px',
							 display:'block'})
					return false;
					});

$('.extractRecipe .print a')
	.click(function(){
					DocPrint();
					return false;
					});


$('body')
	.click(function(){
					$('.popapSend').hide();
					});

//------------------------------------------------------------------------------------------------------
$('.basket .name1').hover(function(Event){
									   var x = Number(Event.pageX);
									   var y = Number(Event.pageY);
									   var p = $('.popapProductLittle');
									   var h = p.height();
									   var top = y-h;

									   var img = $(this).next('img');
									   var text = img.attr('alt');
									   var src = img.attr('src');
									   var name = this.innerHTML;


									   p
									   		.css({
												 top:top+'px',
												 left:x+'px',
												 display:'block'})
											.children('.name')
											.html(name);
										p
											.find('img')
											.attr('src',src);
										p
											.children('.text')
											.html(text);

									   //$('.popapCalContentHr1')[0].innerHTML = t;
									   },
								function(){
										var p = $('.popapProductLittle');
									  	 p.css({
										   display:'none'
										   })
										 //this.title = calendarTitle;
										});

var blockPopap = '<div class="popapProductLittle"><div class="name"></div><div class="photo"><img src="" alt="" /></div><div class="text"></div></div>';

$('.main')
	.before(blockPopap);
//-----------------------------------------------------------------------------------------------------
//
$('.oldOrder a')
	.click(function(){
					var topX = document.documentElement.scrollTop + 300;

					$('#questionBasket')
						.show()
						.css({
							 top:topX+'px'
							 });
					return false;
					});

$('#questionBasket .no')
	.click(function(){
					$('#questionBasket').hide();
					return false;
					});
//------------------------------------------------------------------------------------------------------
//Переключение городов
$('.selectCity div')
	.each(function(n){
				   var classN = $(this).attr('class');
				   $(this).children('a').attr('rel',n);
				   if(classN=='active'){
					   $('.map').hide();
					   //_(n)
					   $('.city'+n).show();
					   }
				   });

$('.selectCity a')
	.click(function(){
					$('.map').hide();
					$('.selectCity div')
						.removeClass('active');
					$(this).parent().addClass('active');
					var n = this.rel;
					$('.city'+n).show();
					});

//------------------------------------------------------------------------------------------------------
$('.mainPhoto img')
	.load(function(){
				   $(this).css('opacity',1)
				   });

$('.galleryPreview img')
	.each(function(){
				   $(this).attr('way', this.alt);
				   this.alt='';
				   });

$('.galleryPreview a')
	.click(function(){
					$('.galleryPreview .active')
						.removeClass('active')
					var i = $(this);
					var src = i.children('img').attr('way');
					i
						.addClass('active')
						.parents('.photoGallery')
						.children('.mainPhoto')
						.children('img')
						.css('opacity',0)
						.attr('src', src);
					changeShadow();
					return false;
					});

$('.photoGallery .switchBack')
	.click(function(){
					var prev = photoNEl().prev;
					$('.galleryPreview .active')
						.removeClass('active');
					prev
						.click()
						.addClass('active')
					return false;
					});

$('.photoGallery .switchFront')
	.click(function(){
					var next = photoNEl().next;
					$('.galleryPreview .active')
						.removeClass('active');
					next
						.click()
						.addClass('active')
					return false;
					});

//------------------------------------------------------------------------------------------------------
$(window)
	.resize(function(){
					 w=$(this).width();
					 if(w>1550)$('body').addClass('bigWin');
					 else $('body').removeClass('bigWin');
					 })
	.resize();


var anchors = document.getElementsByTagName('a');
for (var i=0; i < anchors.length; i++) {
	if (anchors[i].getAttribute('href') &&
	anchors[i].getAttribute('rel') == 'external') {
		anchors[i].target = '_blank';
	}
}

//------------------------------------------------------------------------------------------------------
$('.mapPic A')
	.click(function(){
					return false;
					});

//------------------------------------------------------------------------------------------------------
});//===================================================================================================
//==== END MAIN READY ==================================================================================
//======================================================================================================

function changeShadow(){
	var coordInfo = $('.galleryPreview .active').position();//Получаем координаты блока
	var x = coordInfo.left;
	var y = coordInfo.top+3;
	$('.blockShadow')
		.css({
			 top:y+'px',
			 left:x+'px'
			 });
	}

function photoNEl(){
	var next;
	var prev;
	var galery = $('.galleryPreview a');
	var nEl = galery.length - 1;
	galery
		.each(function(n){

					   var cl = $(this).attr('class');
					   if(cl=='active'){
							switch (n) {
							   case 0:
								 	prev = $('.galleryPreview a:last');
							   		next = $('.galleryPreview a:eq(1)');
								 	break;
							   case nEl:
								 	prev = $('.galleryPreview a:eq('+ --n +')');
							   		next = $('.galleryPreview a:first');
								 	break;
							   default:
							   		prev = $(this).prev();
							   		next = $(this).next();
							}
						 }
					 });
		return {next:next, prev:prev}
	}


//------------------------------------------------------------------------------------------------------
// Клик по слайдеру
function changeCount(obj, sign) {
				  	var el = $(obj).parents('.spiner').children('input');
					if (sign=='plus') {
					  	var val = ++el[0].value;
					} else if (sign=='minus') {
						var val = el[0].value!=1? --el[0].value : el[0].value;
					}
				  	el.attr('rel', val);
					return val;
}




//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function DocPrint(){
	var bRes = window.confirm('Вы хотите распечатать страницу?')
	if(!bRes) return;
	window.print();
}




//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Функции работы с Cookie
function setCookie (name, value, expires, path, domain, secure) {
     document.cookie = name + "=" + escape(value) +
          ((expires) ? "; expires=" + expires : "") +
          "; path=/" +
          ((domain) ? "; domain=" + domain : "") +
          ((secure) ? "; secure" : "");
}

function deleteCookie (name) {
     var dtExpires = new Date();
       dtExpires.setTime(dtExpires.getTime() - 1);

    document.cookie = name + "=0" + "; expires=" + dtExpires.toGMTString() + "; path=/; domain=";
}

function getCookie(name) {
     var cookie = " " + document.cookie;
     var search = " " + name + "=";
     var setStr = null;
     var offset = 0;
     var end = 0;
     if (cookie.length > 0) {
          offset = cookie.indexOf(search);
          if (offset != -1) {
               offset += search.length;
               end = cookie.indexOf(";", offset)
               if (end == -1) {
                    end = cookie.length;
               }
               setStr = unescape(cookie.substring(offset, end));
          }
     }
     return(setStr);
}


$(document).ready(function(){
	if(document.domain=='www.nagasaki-sushi.ru'){
		$("div.elMenu a[href='/menu/']").click(function(){
			return false;
		});
		$("div.elMenu a[href='/actions/']").click(function(){
			return false;
		});
	}
	//alert(window.location.pathname);
	if ((document.referrer == 'http://www.spb.nagasaki-sushi.ru/vakansii/') && (window.location.pathname == '/webforms/send/')) {
		$('div.content').append('Ваша заявка принята.');
	}
	
	if ((document.referrer == 'http://www.msk.nagasaki-sushi.ru/vakansii/') && (window.location.pathname == '/webforms/send/')) {
		$('div.content').append('Ваша заявка принята.');
	}
});


