var curPageClass;
$(document).ready(function(){
	//LightBox
	//$(function() {
	//    $('.image-container a').lightBox();
	//});


	//Field placeholder
	$("#lozung").focus(function(){
		if ($(this).attr("value") == $(this).attr("title"))
			$(this).attr("value", "")
	});

	$("#lozung").blur(function(){
		if ($(this).attr("value") == "")
			$(this).attr("value", $(this).attr("title"))
	});

	//Custom select  
	var params = {
		changedEl: "select",
		visRows: 3,
		scrollArrows: true        
	}
	cuSel(params);	
	

	if($.browser.opera){
		$('.image-container, .walp-image, .mus-image').each(function(){
			var repImage = $(this).children("img").attr("src");
			$(this).css('background','url("'+ repImage +'") no-repeat');
			$(this).children("img").css("opacity", "0");
		});	
	}


	// Set up Sliders
	// **************

	$('#main-slider').anythingSlider({
		easing          : 'easeInOutExpo',
		delay : 4000,
		animationTime : 1200,
		autoPlay : true,
		delay : 5000	
	//				autoPlayLocked  : true,  // If true, user changing slides will not stop the slideshow
	//				resumeDelay     : 10000, // Resume slideshow after user interaction, only if autoplayLocked is true (in milliseconds).
	});
	$('.b-prod-coctails #main-prod-slider').anythingSlider({
		easing          : 'easeInOutExpo'
	//				autoPlayLocked  : true,  // If true, user changing slides will not stop the slideshow
	//				resumeDelay     : 10000, // Resume slideshow after user interaction, only if autoplayLocked is true (in milliseconds).
	});	
	$('#slider-hist').anythingSlider({
		easing          : 'linear',
		autoPlayLocked  : true,  // If true, user changing slides will not stop the slideshow
		autoPlay : true,
		delay : 4000,
		animationTime : 600,
		startStopped : true
	});	

	
	
	/*Custom headers*/	
	Cufon.replace("h1", {
		color: "-linear-gradient(#920819, #53050f)",
		fontFamily: "helioscond"
	});	

});

$(window).load(function(){

	/*Coloring images on hover*/
	var paircount = 0;

	/* If you want to desaturate after page loaded - use onload event
   * of image.
  */
	jQuery(function($)
	{
		$(".des").each(function() {
			var $newthis = $(this);
			// class for easy switch between color/gray version
			$newthis.addClass("pair_" + ++paircount);
			var $cloned = $newthis.clone().attr('id', '');
			// add cloned after original image, we will switch between
			// original and cloned later
			$cloned.insertAfter($newthis).addClass("color").hide();
			// desaturate original
			$newthis.desaturate({
				onswitch: function() {
				// this functon called after replace image with canvas
				}
			});
			// add events for switch between color/gray versions
			$cloned.closest(".switched_images").bind("mouseenter mouseleave", desevent);
		});
	});

	function desevent(event) 
	{
		var classString = new String($(this).attr('class'));
		var pair = classString.match(/pair_\d+/);

		if (event.type == 'mouseenter')
			$(".des.color", this).fadeIn(500);


		if (event.type == 'mouseleave')
			$(".des.color", this).fadeOut(500);

	}











});



//Compact form
function initOverLabels () {
	if (!document.getElementById) return;      

	var labels, id, field;

	// устанавливаем обработчики onfocus и onblur
	// чтобы скрывать и отображать метки
	// с именем класса 'overlabel'
	labels = document.getElementsByTagName('label');
	for (var i = 0; i < labels.length; i++) {

		if (labels[i].className == 'overlabel') {

			// пропускаем метки которые не связаны
			// с полем ввода
			id = labels[i].htmlFor || labels[i].getAttribute('for');
			if (!id || !(field = document.getElementById(id))) {
				continue;
			} 

			// изменяем класс метки 
			// чтобы расположить ее перед полем ввода.
			labels[i].className = 'overlabel-apply';

			// скрываем метку если поле
			// имеет значение по умолчанию
			if (field.value !== '') {
				hideLabel(field.getAttribute('id'), true);
			}

			// устанавливаем обработчики
			// скрывающие и отображающие метки
			field.onfocus = function () {
				hideLabel(this.getAttribute('id'), true);
			};
			field.onblur = function () {
				if (this.value === '') {
					hideLabel(this.getAttribute('id'), false);
				}
			};

			// обрабатываем клики на метки (для Safari).
			labels[i].onclick = function () {
				var id, field;
				id = this.getAttribute('for');
				if (id && (field = document.getElementById(id))) {
					field.focus();
				}
			};

		}
	}
};

function hideLabel (field_id, hide) {
	var field_for;
	var labels = document.getElementsByTagName('label');
	for (var i = 0; i < labels.length; i++) {
		field_for = labels[i].htmlFor 
		|| labels[i].getAttribute('for');
		if (field_for == field_id) {
			labels[i].style.textIndent = (hide) ? '-1000px' : '0px';
			return true;
		}
	}
}

window.onload = function () {
	setTimeout(initOverLabels, 50);
};
input = false;
function changeCheck(el)
/* 
	функция смены вида и значения чекбокса при клике на контейнер чекбокса (тот, который отвечает за новый вид)
	el - span контейнер для обычного чекбокса
	input - чекбокс
*/
{

	var el = el,
//	input = el.find("input").eq(0);
	input = jQuery(el).find("input").eq(0);
	
	if(el.attr("class").indexOf("niceCheckDisabled")==-1)
	{	
		if(!input.attr("checked")) {
			el.addClass("niceChecked");
			input.attr("checked", true);
		} else {
			el.removeClass("niceChecked");
			input.attr("checked", false).focus();
		}
	} else {
		console.log('niceCheckDisabled');
	}
	return true;
}

function changeVisualCheck(input)
{
	/*
	меняем вид чекбокса при смене значения
*/
	var wrapInput = input.parent();
	if(!input.attr("checked")) {
		wrapInput.removeClass("niceChecked");
	}
	else
	{
		wrapInput.addClass("niceChecked");
	}
}

function changeCheckStart(el)
/* 
	новый чекбокс выглядит так <span class="niceCheck"><input type="checkbox" name="[name check]" id="[id check]" [checked="checked"] /></span>
	новый чекбокс получает теже name, id и другие атрибуты что и были у обычного
*/
{

	try
	{
		var el = el,
		checkName = el.attr("name"),
		checkId = el.attr("id"),
		checkChecked = el.attr("checked"),
		checkDisabled = el.attr("disabled"),
		checkTab = el.attr("tabindex"),
		checkValue = el.attr("value");
		if(checkChecked)
			el.after("<span class='niceCheck niceChecked'>"+
				"<input type='checkbox'"+
				"name='"+checkName+"'"+
				"id='"+checkId+"'"+
				"checked='"+checkChecked+"'"+
				"value='"+checkValue+"'"+
				"tabindex='"+checkTab+"' /></span>");
		else
			el.after("<span class='niceCheck'>"+
				"<input type='checkbox'"+
				"name='"+checkName+"'"+
				"id='"+checkId+"'"+
				"value='"+checkValue+"'"+
				"tabindex='"+checkTab+"' /></span>");
	
		/* если checkbox disabled - добавляем соотвсмтвующи класс для нужного вида и добавляем атрибут disabled для вложенного chekcbox */		
		if(checkDisabled)
		{
			el.next().addClass("niceCheckDisabled");
			el.next().find("input").eq(0).attr("disabled","disabled");
		}
		/* цепляем обработчики стилизированным checkbox */		
//		el.next().bind("mousedown", function(e) { // stupid mousedown !
		el.next().parent().bind("click", function(e) {
//			changeCheck(jQuery(this)); 
			changeCheck(jQuery(this).children());
		});
		// wtf ? stupid !
//		el.next().find("input").eq(0).bind("change", function(e) {
//			console.log('input change');
//			changeVisualCheck(jQuery(this));
//		});
		if(jQuery.browser.msie)
		{
			el.next().find("input").eq(0).bind("click", function(e) {
				changeVisualCheck(jQuery(this))
			});	
		}
		el.remove();
	}
	catch(e)
	{
	// если ошибка, ничего не делаем
	}

	return true;
}


	




//Accordeon menu

function initMenus() {
	$('ul.main-menu ul').hide();
	$.each($('ul.main-menu'), function(){
		$('#' + this.id + '.expandfirst ul:first').show();
	});
	$('ul.main-menu li a').click(
		function() {
			var checkElement = $(this).next();
			var parent = this.parentNode.parentNode.id;
			var subPar = $(this).parent();


$("ul.main-menu li.page_item").removeClass('current_page_item');
//$("ul#main-menu li").removeClass('active');
			
			if($('#' + parent).hasClass('noaccordion')) {
				$(this).next().slideToggle('normal');
				
				return false;
			}
			if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
				if($('#' + parent).hasClass('collapsible')) {
					$('#' + parent + ' ul:visible').slideUp('normal');
					subPar.toggleClass('active');
				}
				return false;
			}
			if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
				$('#' + parent + ' ul:visible').slideUp('normal', function(){$('.menu-itm').not(subPar).removeClass('active');});
				checkElement.slideDown('normal');
				subPar.addClass('active');
				return false;
			}

		}
	
		);
}

gallery = false;
imagecnt = 0;
imagecalledcnt = 0;

var hidePreloaderAction = function() {
	var image_i = jQuery('ul.thumbs').children().eq(0).find('img');
	var image_url = encodeURIComponent(jQuery('ul.thumbs').children().eq(0).find('img').attr('src').replace('l_', ''));
	var share_link_vk = 'http://vkontakte.ru/share.php?url=';
	var share_link_fb = 'http://www.facebook.com/sharer.php?u=';
	share_link_vk += image_url;
	share_link_fb += image_url;	
	var title_text = "Бар "+image_i.attr('data-bar')+" "+image_i.attr('data-city')+" @ "+image_i.attr('data-date');
	share_link_vk += '&title='+encodeURIComponent(title_text);
	share_link_fb += '&t='+encodeURIComponent(title_text);
	share_link_vk += '&image='+image_url;

	image_url_fb = jQuery('ul.thumbs').children().eq(0).find('img').attr('src').replace('l_', '');
	
	jQuery('#add-to-vk').attr('href', share_link_vk);
	jQuery('#add-to-fb').attr('href', share_link_fb);	
	
	jQuery('#add-to-fb').unbind('click');
	jQuery('#add-to-fb').bind('click', function(e) {
		e.preventDefault();		
		FB.ui(
		{
		 method: 'stream.publish',
		 message: 'Это я на фотке!!! :-)',
		 attachment: {
			'name': title_text,
			'caption': 'Поединок вкусов - Jim vs. Jack',
			'href': image_url_fb,
			'description': title_text + 'Вкусовой поединок за звание лучшего. Jeam Beam и Jack Daniels слились в решающей схватке. Собираемся в лучших заведениях столицы. Пробуем в слепую. Журим и попадаем на фото.',
			'media': [{
				'type': 'image',
				'src': image_url_fb,
				'href': image_url_fb}]
			},
			 user_message_prompt: 'Разместить это на своей странице Facebook.com'
			}
		);
		return false;
	});		
	
	jQuery('.rombg').hide();
	imagecalledcnt = 0;
}

var hidePreloader = function(data) {
//	hidePreloaderAction();
	if (imagecalledcnt + 1 == imagecnt) {
		setTimeout(hidePreloaderAction, 7000);
	}
	
	imagecalledcnt++;
}

var bGallery = function() {
	// Initially set opacity on thumbs and add
	// additional styling for hover effect on thumbs	
	var onMouseOutOpacity = 0.67;
	jQuery('#thumbs ul.thumbs li').opacityrollover({
		mouseOutOpacity:   onMouseOutOpacity,
		mouseOverOpacity:  1.0,
		fadeSpeed:         'fast',
		exemptionSelector: '.selected'
	});		
	
	// Initialize Advanced Galleriffic Gallery
	gallery = jQuery('#thumbs').galleriffic({
//		delay:                     2500,
		delay:                     10,		
		numThumbs:                 8,
		preloadAhead:              8,
		enableTopPager:            false,
		enableBottomPager:         true,
		maxPagesToShow:            1,
		imageContainerSel:         '#slideshow',
		controlsContainerSel:      '#controls',
		captionContainerSel:       '#caption',
		loadingContainerSel:       '#loading',
		renderSSControls:          false,
		renderNavControls:         false,
		playLinkText:              'Play Slideshow',
		pauseLinkText:             'Pause Slideshow',
		prevLinkText:              'НАЗАД',
		nextLinkText:              'ДАЛЕЕ',
		nextPageLinkText:          'ДАЛЕЕ',
		prevPageLinkText:          'НАЗАД',
		enableHistory:             false,
		autoStart:                 false,
//		syncTransitions:           true,
		syncTransitions:           false,
		defaultTransitionDuration: 900,
		onSlideChange:             function(prevIndex, nextIndex) {
			// 'this' refers to the gallery, which is an extension of $('#thumbs')
			this.find('ul.thumbs').children()
				.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
				.eq(nextIndex).fadeTo('fast', 1.0);
				
			// also change share links
			var image_i = this.find('ul.thumbs').children().eq(nextIndex).find('img');
			var image_url = encodeURIComponent(this.find('ul.thumbs').children().eq(nextIndex).find('img').attr('src').replace('l_', ''));
			var share_link_vk = 'http://vkontakte.ru/share.php?url=';
			var share_link_fb = 'http://www.facebook.com/sharer.php?u=';
			share_link_vk += image_url;
			share_link_fb += image_url;
			var title_text = "Бар "+image_i.attr('data-bar')+" "+image_i.attr('data-city')+" @ "+image_i.attr('data-date');
			share_link_vk += '&title='+encodeURIComponent(title_text);
			share_link_fb += '&t='+encodeURIComponent(title_text);
			share_link_vk += '&image='+image_url;

			var image_url_fb = this.find('ul.thumbs').children().eq(nextIndex).find('img').attr('src').replace('l_', '');

			jQuery('#add-to-vk').attr('href', share_link_vk);
			jQuery('#add-to-fb').attr('href', share_link_fb);
			
			jQuery('#add-to-fb').unbind('click');
			jQuery('#add-to-fb').bind('click', function(e) {
				e.preventDefault();					
				FB.ui(
				{
				 method: 'stream.publish',
				 message: 'Это я на фотке!!! :-)',
				 attachment: {
					'name': title_text,
					'caption': 'Поединок вкусов - Jim vs. Jack',
					'href': image_url_fb,
					'description': title_text + 'Вкусовой поединок за звание лучшего. Jeam Beam и Jack Daniels слились в решающей схватке. Собираемся в лучших заведениях столицы. Пробуем в слепую. Журим и попадаем на фото.',
					'media': [{
						'type': 'image',
						'src': image_url_fb,
						'href': image_url_fb}]
					},
					 user_message_prompt: 'Разместить это на своей странице Facebook.com'
					}
				);
				return false;
			});			
		},
		onPageTransitionOut:       function(callback) {
			this.fadeTo('fast', 0.0, callback);
		},
		onPageTransitionIn:        function() {
			this.fadeTo('fast', 1.0);
		},
		onImageAdded:              function(imageData, $li) {
			$li.opacityrollover({
				mouseOutOpacity:   onMouseOutOpacity,
				mouseOverOpacity:  1.0,
				fadeSpeed:         'fast',
				exemptionSelector: '.selected'
			});
			hidePreloader(gallery.data);
		}				
	});	
}

// onchange method for #photo-city
var getGalleryBars = function(el) {

var batyear = parseInt($('#batyear').attr('value'));
if(batyear==1){
var fils='photos.php';
}else{
var fils='photo.php';
}

	var galscript = ''+fils+'?method=get_bars';
	var city_id = jQuery(el).val() || 1;
	var params = '&photo-city='+city_id;
//	console.log('method=get_bars');
	
	jQuery.ajax({
		url		: galscript+params,
		type	: 'GET',
		data	: {},
		success: function(responce) {
			responce = JSON.parse(responce);
			
			if (responce.status != 'success') {
				console.log('method=get_bars ajax status error');
			} else {
				
				// make new selects with bars
				var bar_selected = false;
				var bars = responce.bars;
				
				
				var slct = '<select name="photo-bar" id="photo-bar" onchange="getGalleryDates(this);">';
				for (var ii = 0; ii < bars.length; ii++) {
					if (bar_selected == false) {
						bar_selected = bars[ii].id
					}
					slct += '<option value="'+bars[ii].id+'">'+bars[ii].name+'</option>';
				}
				slct += '</select>';
				
				var cuselbar = jQuery('#cuselFrame-photo-bar');
				if (cuselbar.length != 0) {
					jQuery('#cuselFrame-photo-bar').replaceWith(slct);
				} else {
					jQuery('#img_filter').append(slct);
				}
				
				// reinit cusel for this select
				var params_sels = {
					changedEl: "#photo-bar",
					visRows: 3,
					scrollArrows: true     											
				};
				cuSel(params_sels);				
				
				// make new selects with dates
				buildGalleryDates(city_id, bar_selected);
			}
		}		
	});
}

// after success ajax we are building dates select for that bar in city
var buildGalleryDates = function(city_id, bar_id) {


var batyear = parseInt($('#batyear').attr('value'));
if(batyear==1){
var fils='photos.php';
}else{
var fils='photo.php';
}

	var galscript = ''+fils+'?method=get_dates';
	var params = '&photo-city='+city_id+'&photo-bar='+bar_id;
	
//	console.log('method=get_dates');
	jQuery.ajax({
		url		: galscript+params,
		type	: 'GET',
		data	: {},
		success: function(responce) {
			responce = JSON.parse(responce);
			
			if (responce.status != 'success') {
				console.log('method=get_dates ajax status error');
			} else {
				var dates = responce.dates;
				var date_selected = false;
				
				var slct = '<select name="photo-date" id="photo-date" onchange="getGalleryItems(this);">';
				for (var ii = 0; ii < dates.length; ii++) {
					if (date_selected == false) {
						date_selected = dates[ii].id
					}
					slct += '<option value="'+dates[ii].timestamp+'">'+dates[ii].date+'</option>';
				}
				slct += '</select>';
				
				var cuselbar = jQuery('#cuselFrame-photo-date');
				if (cuselbar.length != 0) {
					jQuery('#cuselFrame-photo-date').replaceWith(slct);
				} else {
					jQuery('#img_filter').append(slct);
				}
				
				// reinit cusel for this select
				var params_sels = {
					changedEl: "#photo-date",
					visRows: 3,
					scrollArrows: true     											
				};
				cuSel(params_sels);
				
				// reinit gallery with new images for that city and first bar
				buildGalleryImages(city_id, bar_id, date_selected);	
			}
		}
	});
}

// onchange method for #photo-bar
var getGalleryDates = function() {
	var city_id = jQuery('#photo-city').val();
	var bar_id = jQuery('#photo-bar').val();
	buildGalleryDates(city_id, bar_id);	
}

// onchange method for #photo-date
var getGalleryItems = function() {
	var city_id = jQuery('#photo-city').val();
	var bar_id = jQuery('#photo-bar').val();
	var date = jQuery('#photo-date').val();
	buildGalleryImages(city_id, bar_id, date);
}

// init city select on page load
// then we should get all bars for that city and all dates and all photos
var getGalleryCities = function() {

var batyear = parseInt($('#batyear').attr('value'));
if(batyear==1){
var fils='photos.php';
}else{
var fils='photo.php';
}

	var galscript = ''+fils+'?method=get_cities';
	
//	console.log('method=get_cities');
	jQuery.ajax({
		url		: galscript,
		type	: 'GET',
		data	: {},
		success: function(responce) {
			responce = JSON.parse(responce);
			if (responce.status != 'success') {
				console.log('method=get_dates ajax status error');
			} else {
				// make new selects with cities
				var city_selected = false;
				var cities = responce.cities;
				
				
				var slct = '<select name="photo-city" id="photo-city" onchange="getGalleryBars(this);">';
				for (var ii = 0; ii < cities.length; ii++) {
					if (city_selected == false) {
						city_selected = cities[ii].id
					}
					slct += '<option value="'+cities[ii].id+'">'+cities[ii].name+'</option>';
				}
				slct += '</select>';
				
				jQuery('#img_filter').html(slct);
				
				// reinit cusel for this select
				var params_sels = {
					changedEl: "#photo-city",
					visRows: 3,
					scrollArrows: true     											
				};
				cuSel(params_sels);			
				
				getGalleryBars(jQuery('#photo-city'));
			}
		}
	});		
}

// ajax get gallery images after some changes
var buildGalleryImages = function(city_id, bar_id, date, page) {
	jQuery('.rombg').show();
	var pagenum = page || 1;

var batyear = parseInt($('#batyear').attr('value'));
if(batyear==1){
var fils='photos.php';
}else{
var fils='photo.php';
}

	var galscript = ''+fils+'?method=get_photos';
	var params = '&photo-city='+city_id+'&photo-bar='+bar_id+'&date='+date;	
	
	// yeah if your are looking here - you need some optimization... 
	//	var params = '&photo-city='+city_id+'&photo-bar='+bar_id+'&date='+date+'&photo-page='+pagenum;	
	
//	console.log('method=get_photos');
	jQuery.ajax({
		url		: galscript+params,
		type	: 'GET',
		data	: {},
		success: function(responce) {
			responce = JSON.parse(responce);
			if (responce.status != 'success') {
				console.log('method=get_dates ajax status error');
			} else {
				buildGallery(responce.photos);
			}
		}
	});	
}

// remove old images and insert new on data changes
var buildGallery = function(items) {
	gallery.removeAllImages();
	imagecnt = items.length;
	
	var city_name = jQuery('div.cuselText', '#cuselFrame-photo-city').text();
	var bar_name = jQuery('div.cuselText', '#cuselFrame-photo-bar').text();
	var date_name = jQuery('div.cuselText', '#cuselFrame-photo-date').text();	
	
	var fixed_path = '';
	
	for (var ii = 0; ii < imagecnt; ii++) {
		fixed_path = '/wp-content/themes/JeamBeam/download.php?image_path='+encodeURIComponent(items[ii].image_filepath);
		
		gal = '<li>';
		gal += '<a class="thumb" title="" data-id="'+items[ii].id+'" href="'+items[ii].image_filepath+'">';
		gal += '<img src="'+items[ii].thumb_filepath+'" alt="" data-city="'+city_name+'" data-bar="'+bar_name+'" data-date="'+date_name+'"/>';
		gal += '</a>';
		gal += '<div class="caption"><div class="download">';
		gal += '<a href="'+fixed_path+'">Download Original</a>';
		gal += '</div></div>';
		gal += '</li>';
		
		gallery.insertImage(gal, ii);
		
	}
	
	gallery.gotoIndex(0);
}

$(document).ready(function() {
	/*Custom check box*/
	jQuery(".niceCheck").each(
		/* при загрузке страницы меняем обычные на стильные checkbox */
		function() {
			changeCheckStart(jQuery(this));
		});	
	
	initMenus();

	$(".current-cat").parents(".menu-itm").addClass('active');
	$(".current-cat").parent(".sub-menu").show();
	$(".current_page_item").parents(".menu-itm").addClass('active');
	$(".current_page_item").parent(".sub-menu").show();
	$(".current_page_item").parents(".panel").show();
	
	$('a.fanc').fancybox();
	
$('.media-itm .current-cat').next("li").find("a").css("border-top","1px solid #9B081B");	
}

);

