function log(e){
	//return false; // public mode
	if (typeof(console) == 'object') 
		console.log(e);
	//else alert(e);  
};

function isset(variable)
{
	return typeof(variable)!='undefined';
}

/**
 * Disallow sending x and y coords after click on image button
 */
var inputImageClickFix = {
	init: function(){
		$('*:image').click(function(){
			inputImageClickFix.submitEvent($(this));
			return false;
		})
	},
	submitEvent: function(e){
		e.parents('form').submit();
	}
};


/**
 * Class for switching tabs
 */
var mlist = {
	config: {
		wrapperId: '.boxTabs',
		tabs: 'a',
		itemsClassMask: /itemsInFrame-(\d+)/,
		itemsClassMaskInfinite: 'itemsInFrame-9999',
		itemsInfinite: 9999
	},
	init: function(reinitId){
		var items = $(this.config.wrapperId);
		if (!items.length) 
			return false;
		// for each tab group	
		items.each(function(i){
			var firstTab = $(this).find(mlist.config.tabs + ':first');
			var cookieId = firstTab.attr('href').replace('#','');
			// get opened tab from cookie
			if ( typeof($.cookie) != 'undefined' && $.cookie(cookieId)) {
				mlist.set( $.cookie(cookieId) , cookieId);
			}
			else {
				// set first tab and content active
				mlist.set(firstTab, cookieId);
			}
			
			// for each tab in group
			$(this).find(mlist.config.tabs).each(function(){
				// bind set to click and get target id
				$(this).click(function(){
					return mlist.set($(this), cookieId);
				});
				var targetListId = $(this).attr('href');
				var targetList = $(targetListId)
				// get items in frame count from list class
				itemsInFrame = targetList.attr('class').match(mlist.config.itemsClassMask)[1];
				// still no items count
				if (!itemsInFrame) 
				{
					// default value
					itemsInFrame = 10;
				}
				targetList = targetList.children('.outer');
				// set css
				targetList.children('.items').css({
					height: '10000em',
					position: 'absolute',
					left: 0,
					top: 0
				});
				if (!mlist.itemHeight) 
				{
					// get grid height from first item
					mlist.itemHeight = (parseInt(targetList.children('.items').children(':first').css('height')));
				}
				// set frame height
				targetList.height(mlist.itemHeight * itemsInFrame);
				targetList.css({
					overflow: 'hidden'
				});
				// insert controls
				if(!targetList.prev('.prevPage').length)
				{
					targetList.before('<a class="prevPage"><span class="forBlind">↑</span></a>');
					targetList.after('<a class="nextPage"><span class="forBlind">↓</span></a>');
					targetList.after('<div class="navi"></div>');
				}
				// make scrollable				
				var scapi = targetList.scrollable({
					vertical: true,
					size: itemsInFrame,
					clickable: false
				}).mousewheel().navigator({api: true/*last plugin inits scrollable api*/});
				mlist.resizeScrollbar(targetList);
				// on page change, save position to cookie
				scapi.onSeek(function() { 
					if ( typeof($.cookie) != 'undefined') {
						$.cookie(targetListId+'-page-'+itemsInFrame, this.getPageIndex(), {path:'/'});
					}
			    });
				// if is some saved position, get it
				if ( typeof($.cookie) != 'undefined' && $.cookie(targetListId+'-page-'+itemsInFrame)) {
					scapi.setPage($.cookie(targetListId+'-page-'+itemsInFrame));
				}
			});
		});
	},
	/**
	 * Set tab
	 * @param {Object} tab
	 */
	set: function(tab, cookieId){
		// tab is string
		if(typeof(tab)=='string')
		{
			var targetId = tab;
			tab = $('a[href='+tab+']');
		}
		// tab is object
		else
		{
			var targetId = tab.attr('href');
		}
		// if can set cookie
		if (typeof($.cookie) != 'undefined')
		{
			// set cookie first_tab_id as opened_tab_id
			$.cookie(cookieId, targetId, {path:'/'});
		}
		// hide siblings
		$(targetId).siblings('.mlist:visible').hide();
		// show target
		$(targetId).show();
		// unselect selected
		tab.siblings().removeClass('selected');
		// select current
		tab.addClass('selected');
		mlist.resizeScrollbar($(targetId).children('.outer'));
		return false;
	},
	/**
	 * Resize scrollbar items
	 */
	resizeScrollbar: function(targetList){
		var tnavi = targetList.siblings('.navi');
		var tnitems = tnavi.children();
		tnavi.show();
		var tnheight = tnavi.height() - 14;
		var tniheight = tnheight / tnitems.length;
		tnitems.height(tniheight);
	},
	/**
	 * Mazimize list
	 * @param {Object} el
	 */
	maximize: function(el){
		var itemsCount = 100;
		var targetLists = $(el).parent().prevAll('.mlist');
		targetLists.each(function(){
			$(this).find('.prevPage').remove();
			$(this).find('.nextPage').remove();
			$(this).find('.navi').remove();
			var outer = $(this).children('.outer');
			var targetList = outer.children('.items');
			outer.css({
				height: 'auto'
			});
			targetList.css({
				height: 'auto',
				position: 'relative',
				left: 0,
				top: 0
			});
		});
		$(el).remove();
		return false;
	}
};

/**
 * Tools for menu
 */
var menuTools = {
	/**
	 * Center menu
	 */
	center: function(){
		$('#mainMenu>ul>li').each(function(){
			menuTools.menuWidth += parseInt($(this).width()) + parseInt($(this).css('padding-left')) + parseInt($(this).css('padding-right')) + parseInt($(this).css('margin-left')) + parseInt($(this).css('margin-right'));
		});
		$('#mainMenu>ul').width(menuTools.menuWidth + menuTools.magic + 'px');
	},
	/**
	 * Fix cufon submenu hover bug
	 */
	fixHover: function(){
		$('#mainMenu>ul>li').hover(function(){
			$(this).addClass('hover');
		}, function(){
			$(this).removeClass('hover');
			Cufon.replace($(this).children('a'), {
				hover: true,
				color: '#000000'
			});
		});
	},
	menuWidth: 0,
	magic: 0
}

var ajaxLoader = {
	config: {
	
		ajaxPhpService: '/ajax.php'
	
	},
	/**
	 * Activate loader functions
	 */
	activate: function(){
		ajaxLoader.activated = true;
	},
	/**
	 * Modules loader
	 */
	init: function(){
		var modCache;
		// load modules
		for (var moduleName in ajaxLoader.modules) 
		{
			eval('modCache = ajaxLoader.modules.' + moduleName);
			if (typeof(modCache.init()) == 'function' && typeof(modCache.load()) == 'function') 
			{
				modCache.init();
			}
		}
		ajaxLoader.activate();
		ajaxLoader.popup.init();
	},
	
	modules: {
		/**
		 * Performance big with film stripe
		 *
		 * .performanceBig followed by .performanceStrip - order is important!
		 *
		 */
		perfBWS: {
			config: {
				wrapperId: '.performanceBig',
				outerId: '.outer',
				itemId: '.item',
				ajaxContent: '.ajaxContent',
				controlPrev: '.controlPrev',
				controlNext: '.controlNext',
				reservationInfoId: '.reservationInfo',
				calendarId: '.calendar',
				slideDurationH: 500,
				slideDurationV: 200,
				
				wrapperIdStrip: '.performanceFstrip',
				outerIdStrip: '.outer',
				itemIdStrip: '.item',
				ajaxContentStrip: '.ajaxContent',
				controlPrevStrip: '.controlPrev',
				controlNextStrip: '.controlNext',
				itemsInStrip: 8,
				slideDurationStrip: 1000
			},
			init: function(){
				var items = $(this.config.wrapperId);
				var itemsStrip = $(this.config.wrapperIdStrip);
				if (!items.length || !itemsStrip.length) 
					return false;
				// for each wrapper
				items.each(function(objIndex){
				
					var outer = $(this).find(ajaxLoader.modules.perfBWS.config.outerId);
					var outerStrip = itemsStrip.eq(objIndex).find(ajaxLoader.modules.perfBWS.config.outerIdStrip);
					// save settings
					var it = 'media';
					if (outer.find(ajaxLoader.modules.perfBWS.config.reservationInfoId).length) 
					{
						it = 'reservation';
					}
					else if (outer.find(ajaxLoader.modules.perfBWS.config.calendarId).length) 
					{
						it = 'calendar';
					}
					ajaxLoader.modules.perfBWS.mdata[objIndex] = {
						frameWidth: outer.width() + parseInt(outer.css('padding-left')) + parseInt(outer.css('padding-right')),
						itemNo: 0,
						lock: false,
						frameWidthStrip: outerStrip.width() + parseInt(outerStrip.css('padding-left')) + parseInt(outerStrip.css('padding-right')),
						itemNoStrip: 0,
						lockStrip: false,
						infoType: it
					}
					/** /
					 // prev event bind
					 $(this).find(ajaxLoader.modules.perfBWS.config.controlPrev).click(function(){
					 ajaxLoader.modules.perfBWS.prev(objIndex);
					 return false;
					 });
					 // next event bind
					 $(this).find(ajaxLoader.modules.perfBWS.config.controlNext).click(function(){
					 ajaxLoader.modules.perfBWS.next(objIndex);
					 return false;
					 });
					 /** /
					 var wrapperStrip = itemsStrip.eq(objIndex);
					 // prev event bind
					 wrapperStrip.find(ajaxLoader.modules.perfBWS.config.controlPrevStrip).click(function(){
					 ajaxLoader.modules.perfBWS.prevStrip(objIndex);
					 return false;
					 });
					 // next event bind
					 wrapperStrip.find(ajaxLoader.modules.perfBWS.config.controlNextStrip).click(function(){
					 ajaxLoader.modules.perfBWS.nextStrip(objIndex);
					 return false;
					 });
					 /**/
				});
			},
			next: function(objIndex, limit){
				return ajaxLoader.modules.perfBWS.load(objIndex, 1, limit);
			},
			prev: function(objIndex, limit){
				return ajaxLoader.modules.perfBWS.load(objIndex, -1, limit);
			},
			
			/**
			 * Load main
			 */
			load: function(objIndex, dir, limit){
				// is locked?
				if (ajaxLoader.modules.perfBWS.mdata[objIndex].lock == true) 
				{
					return false;
				}
				// set to locked
				ajaxLoader.modules.perfBWS.mdata[objIndex].lock = true;
				// set slide counter
				ajaxLoader.modules.perfBWS.mdata[objIndex].itemNo += dir;
				// ajaxcontent element
				var ajaxContent = $(ajaxLoader.modules.perfBWS.config.wrapperId).eq(objIndex).find(ajaxLoader.modules.perfBWS.config.ajaxContent);
				// first slide
				if (!prevHeight) 
				{
					var prevHeight = ajaxContent.children().height();
				}
				// fix height
				ajaxContent.parent().height(prevHeight);
				// do ajax
				$.getJSON(ajaxLoader.config.ajaxPhpService, { // send get data
					'module': 'perfBWS',
					'items_in_frame': 1,
					'slide_number': ajaxLoader.modules.perfBWS.mdata[objIndex].itemNo,
					'limit': limit,
					'info_type': ajaxLoader.modules.perfBWS.mdata[objIndex].infoType
				}, function(data){ // callback 
					// if some php error
					if (!data.requestOk) 
					{
						// unlock and do nothing
						ajaxLoader.modules.perfBWS.mdata[objIndex].lock = false;
						return false;
					}
					var sign = '';
					var cselectorRem = ajaxLoader.modules.perfBWS.config.itemId;
					var cselectorRemInv = cselectorRem;
					
					// append data
					if (dir > 0) 
					{
						ajaxContent.append(data.html);
						sign = '-';
						cselectorRem += ':first';
						cselectorRemInv += ':last';
					}
					else 
					{
						ajaxContent.prepend(data.html);
						ajaxContent.children(':first').css('margin-left', '-' + ajaxLoader.modules.perfBWS.mdata[objIndex].frameWidth + 'px')
						sign = '+';
						cselectorRem += ':last';
						cselectorRemInv += ':first';
					}
					
					var prevHeight = ajaxContent.children(cselectorRem).height();
					var newHeight = ajaxContent.children(cselectorRemInv).height();
					// decide slide order
					if (prevHeight < newHeight) 
					{
						// animate height
						ajaxContent.parent().animate({
							'height': newHeight + 'px'
						}, ajaxLoader.modules.perfBWS.config.slideDurationV).queue(function(){
							// animate slide
							ajaxContent.children(':first').animate({
								'margin-left': sign + '=' + ajaxLoader.modules.perfBWS.mdata[objIndex].frameWidth + 'px'
							}, ajaxLoader.modules.perfBWS.config.slideDurationH).queue(function(){
								// remove prev frame
								ajaxContent.children(cselectorRem).remove();
								// remove from queue
								$(this).dequeue();
								// unlock
								ajaxLoader.modules.perfBWS.mdata[objIndex].lock = false;
							});
							// remove from queue
							$(this).dequeue();
						});
					}
					else 
					{
						// animate slide
						ajaxContent.children(':first').animate({
							'margin-left': sign + '=' + ajaxLoader.modules.perfBWS.mdata[objIndex].frameWidth + 'px'
						}, ajaxLoader.modules.perfBWS.config.slideDurationH).queue(function(){
							// animate height
							ajaxContent.parent().animate({
								'height': newHeight + 'px'
							}, ajaxLoader.modules.perfBWS.config.slideDurationV).queue(function(){
								// remove from queue
								ajaxContent.children(cselectorRem).remove();
								// remove from queue
								$(this).dequeue();
								// unlock
								ajaxLoader.modules.perfBWS.mdata[objIndex].lock = false;
							});
							// remove from queue
							$(this).dequeue();
						});
					}
					// get and append new controls
					var outer = ajaxContent.parent();
					outer.nextAll('.control').remove();
					outer.after(data.controls);
				});
				return false;
			},
			
			nextStrip: function(objIndex, limit){
				return ajaxLoader.modules.perfBWS.loadStrip(objIndex, 1, limit);
			},
			prevStrip: function(objIndex, limit){
				return ajaxLoader.modules.perfBWS.loadStrip(objIndex, -1, limit);
			},
			/**
			 * Load strip
			 */
			loadStrip: function(objIndex, dir, limit){
				// is locked?
				if (ajaxLoader.modules.perfBWS.mdata[objIndex].lockStrip == true) 
				{
					return false;
				}// ajaxcontent element
				var ajaxContent = $(ajaxLoader.modules.perfBWS.config.wrapperIdStrip).eq(objIndex).find(ajaxLoader.modules.perfBWS.config.ajaxContentStrip);
				// set to locked
				ajaxLoader.modules.perfBWS.mdata[objIndex].lockStrip = true;
				// set slide counter
				ajaxLoader.modules.perfBWS.mdata[objIndex].itemNoStrip += dir;
				// do ajax
				$.getJSON(ajaxLoader.config.ajaxPhpService, { // send get data
					'module': 'performanceFStrip',
					'items_in_frame': ajaxLoader.modules.perfBWS.config.itemsInStrip,
					'slide_number': ajaxLoader.modules.perfBWS.mdata[objIndex].itemNoStrip,
					'limit': limit
				}, function(data){ //callback
					// if some php error
					if (!data.requestOk) 
					{
						// unlock and do nothing
						ajaxLoader.modules.perfBWS.mdata[objIndex].lockStrip = false;
						return false;
					}
					var cselectorRem = ajaxLoader.modules.perfBWS.config.itemIdStrip;
					if (dir > 0) 
					{
						ajaxContent.append(data.html);
						ajaxContent.animate({
							'margin-left': '-=' + (ajaxLoader.modules.perfBWS.mdata[objIndex].frameWidthStrip - 5) + 'px'
						}, ajaxLoader.modules.perfBWS.config.slideDurationStrip).queue(function(){
							ajaxContent.children(cselectorRem + ':lt(' + (ajaxLoader.modules.perfBWS.config.itemsInStrip) + ')').remove();
							ajaxContent.css('margin-left', '0px');
							ajaxLoader.modules.perfBWS.mdata[objIndex].lockStrip = false;
							// remove from queue
							$(this).dequeue();
						});
					}
					else 
					{
						ajaxContent.prepend(data.html);
						ajaxContent.css('margin-left', '-' + ajaxLoader.modules.perfBWS.mdata[objIndex].frameWidthStrip + 'px');
						ajaxContent.animate({
							'margin-left': '+=' + ajaxLoader.modules.perfBWS.mdata[objIndex].frameWidthStrip + 'px'
						}, ajaxLoader.modules.perfBWS.config.slideDurationStrip).queue(function(){
							ajaxContent.children(cselectorRem + ':gt(' + (ajaxLoader.modules.perfBWS.config.itemsInStrip - 1) + ')').remove();
							ajaxLoader.modules.perfBWS.mdata[objIndex].lockStrip = false;
							// remove from queue
							$(this).dequeue();
						});
					}
					// get and append new controls
					var outer = ajaxContent.parent();
					outer.nextAll('.control').remove();
					outer.after(data.controls);
				});
				return false;
			},
			mdata: []
		},
		
		/**
		 * Performance tiny square 9x9
		 *
		 */
		perfTiny: {
			config: {
				wrapperId: '.performanceTiny',
				outerId: '.outer',
				itemId: '.group',
				ajaxContent: '.ajaxContent',
				controlPrev: '.controlPrev',
				controlNext: '.controlNext',
				itemsInFrame: 8,
				slideDuration: 1000
			},
			init: function(){
				var items = $(this.config.wrapperId);
				if (!items.length) 
					return false;
				// for each wrapper
				items.each(function(objIndex){
					var outer = $(this).find(ajaxLoader.modules.perfTiny.config.outerId);
					// save settings
					ajaxLoader.modules.perfTiny.mdata[objIndex] = {
						frameWidth: outer.width() + parseInt(outer.css('padding-left')) + parseInt(outer.css('padding-right')),
						itemNo: 0,
						lock: false
					}
					/** /
					 // prev event bind
					 $(this).find(ajaxLoader.modules.perfTiny.config.controlPrev).click(function(){
					 ajaxLoader.modules.perfTiny.prev(objIndex);
					 return false;
					 });
					 // next event bind
					 $(this).find(ajaxLoader.modules.perfTiny.config.controlNext).click(function(){
					 ajaxLoader.modules.perfTiny.next(objIndex);
					 return false;
					 });
					 /**/
				});
			},
			next: function(objIndex, limit){
				return ajaxLoader.modules.perfTiny.load(objIndex, 1, limit);
			},
			prev: function(objIndex, limit){
				return ajaxLoader.modules.perfTiny.load(objIndex, -1, limit);
			},
			
			/**
			 * Load main
			 */
			load: function(objIndex, dir, limit){
				// is locked?
				if (ajaxLoader.modules.perfTiny.mdata[objIndex].lock == true) 
				{
					return false;
				}
				// set to locked
				ajaxLoader.modules.perfTiny.mdata[objIndex].lock = true;
				// set slide counter
				ajaxLoader.modules.perfTiny.mdata[objIndex].itemNo += dir;
				// ajaxcontent element
				var ajaxContent = $(ajaxLoader.modules.perfTiny.config.wrapperId).eq(objIndex).find(ajaxLoader.modules.perfBWS.config.ajaxContent);
				// do ajax
				$.getJSON(ajaxLoader.config.ajaxPhpService, { // send get data
					'module': 'perfTiny',
					'items_in_frame': 9, // 1 group with 9 items
					'slide_number': ajaxLoader.modules.perfTiny.mdata[objIndex].itemNo,
					'limit': limit
				}, function(data){ //callback
					// if some php error
					if (!data.requestOk) 
					{
						// unlock and do nothing
						ajaxLoader.modules.perfTiny.mdata[objIndex].lock = false;
						return false;
					}
					var sign = '';
					var cselectorRem = ajaxLoader.modules.perfTiny.config.itemId;
					// append data
					if (dir > 0) 
					{
						ajaxContent.append(data.html);
						sign = '-';
						cselectorRem += ':first';
					}
					else 
					{
						ajaxContent.prepend(data.html);
						ajaxContent.children(':first').css('margin-left', '-' + ajaxLoader.modules.perfTiny.mdata[objIndex].frameWidth + 'px')
						sign = '+';
						cselectorRem += ':last';
					}
					// animate slide
					ajaxContent.children(':first').animate({
						'margin-left': sign + '=' + ajaxLoader.modules.perfTiny.mdata[objIndex].frameWidth + 'px'
					}, ajaxLoader.modules.perfTiny.config.slideDuration).queue(function(){
						// remove prev frame
						ajaxContent.children(cselectorRem).remove();
						// remove from queue
						$(this).dequeue();
						// unlock
						ajaxLoader.modules.perfTiny.mdata[objIndex].lock = false;
					});
					// get and append new controls
					var outer = ajaxContent.parent();
					outer.nextAll('.control').remove();
					outer.after(data.controls);
				});
				return false;
			},
			mdata: []
		},
		
		/**
		 * Big video box
		 *
		 */
		videoBig: {
			config: {
				wrapperId: '.videoBig',
				outerId: '.outer',
				itemId: '.media',
				ajaxContent: '.ajaxContent',
				controlPrev: '.controlPrev',
				controlNext: '.controlNext',
				slideDuration: 600
			},
			init: function(){
				var items = $(this.config.wrapperId);
				if (!items.length) 
					return false;
				// for each wrapper
				items.each(function(objIndex){
					var outer = $(this).find(ajaxLoader.modules.videoBig.config.outerId);
					// save settings
					ajaxLoader.modules.videoBig.mdata[objIndex] = {
						frameWidth: outer.width() + parseInt(outer.css('padding-left')) + parseInt(outer.css('padding-right')),
						itemNo: 0,
						lock: false
					}
				});
			},
			next: function(objIndex, limit){
				return ajaxLoader.modules.videoBig.load(objIndex, 1, limit);
			},
			prev: function(objIndex, limit){
				return ajaxLoader.modules.videoBig.load(objIndex, -1, limit);
			},
			
			/**
			 * Load main
			 */
			load: function(objIndex, dir, limit){
				// is locked?
				if (ajaxLoader.modules.videoBig.mdata[objIndex].lock == true) 
				{
					return false;
				}
				// set to locked
				ajaxLoader.modules.videoBig.mdata[objIndex].lock = true;
				// set slide counter
				ajaxLoader.modules.videoBig.mdata[objIndex].itemNo += dir;
				// ajaxcontent element
				var ajaxContent = $(ajaxLoader.modules.videoBig.config.wrapperId).eq(objIndex).find(ajaxLoader.modules.videoBig.config.ajaxContent);
				// do ajax
				$.getJSON(ajaxLoader.config.ajaxPhpService, { // send get data
					'module': 'videoBig',
					'slide_number': ajaxLoader.modules.videoBig.mdata[objIndex].itemNo,
					'limit': limit
				}, function(data){ //callback
					// if some php error
					if (!data.requestOk) 
					{
						// unlock and do nothing
						ajaxLoader.modules.videoBig.mdata[objIndex].lock = false;
						return false;
					}
					var sign = '';
					var cselectorRem = ajaxLoader.modules.videoBig.config.itemId;
					// append data
					if (dir > 0) 
					{
						ajaxContent.append(data.html);
						sign = '-';
						cselectorRem += ':first';
					}
					else 
					{
						ajaxContent.prepend(data.html);
						ajaxContent.children(':first').css('margin-left', '-' + ajaxLoader.modules.videoBig.mdata[objIndex].frameWidth + 'px')
						sign = '+';
						cselectorRem += ':last';
					}
					// animate slide
					ajaxContent.children(':first').animate({
						'margin-left': sign + '=' + ajaxLoader.modules.videoBig.mdata[objIndex].frameWidth + 'px'
					}, ajaxLoader.modules.videoBig.config.slideDuration).queue(function(){
						// remove prev frame
						ajaxContent.children(cselectorRem).remove();
						// remove from queue
						$(this).dequeue();
						// unlock
						ajaxLoader.modules.videoBig.mdata[objIndex].lock = false;
					});
					// get and append new controls
					var outer = ajaxContent.parent();
					outer.nextAll('.control').remove();
					outer.after(data.controls);
				});
				return false;
			},
			mdata: []
		}
	},
	
	/**
	 * Open new popup
	 */
	popup: {
		config: {
			offsetX: 0,
			offsetY: 0,
			delayIn: 150,
			delayOut: 150,
			delayOutPopup: 350,
			delayOutPreserve: 50
		},
		/**
		 * Prepare popups
		 */
		init: function(){
			ajaxLoader.popup.pwr = $('<div id="popupWrapper"></div>');
			$('body').append(ajaxLoader.popup.pwr);
			$('body').mousemove(function(e){
				ajaxLoader.popup.pwrPos = {
					top: e.pageY + ajaxLoader.popup.config.offsetY,
					left: e.pageX + ajaxLoader.popup.config.offsetX
				};
			});
		},
		/**
		 * Prepare to open popup
		 */
		open: function(el, type, itemId, noMouseOut, callback){
			if (!ajaxLoader.activated) 
				return false;
			if (noMouseOut) 
			{
				// set position
				ajaxLoader.popup.pwr.css(ajaxLoader.popup.pwrPos);
			}
			// clear timers
			clearTimeout(ajaxLoader.popup.timer);
			clearTimeout(ajaxLoader.popup.timerX);
			// preserve close timer
			//			if (!noMouseOut) 
			//			{
			ajaxLoader.popup.timerX = setTimeout(function(){
				// remove popup
				ajaxLoader.popup.close();
			}, ajaxLoader.popup.config.delayOutPreserve);
			//			}
			// set open timer
			ajaxLoader.popup.timer = setTimeout(function(){
				// open popup
				ajaxLoader.popup.sopen(el, type, itemId, noMouseOut, callback);
			}, ajaxLoader.popup.config.delayIn);
			if (!noMouseOut) 
			{
			
				// on mouseout
				$(el).mouseout(function(){
					// clear open timer
					clearTimeout(ajaxLoader.popup.timer);
					clearTimeout(ajaxLoader.popup.timerX);
					// set close timer
					ajaxLoader.popup.timerX = setTimeout(function(){
						// remove popup
						ajaxLoader.popup.close();
					}, ajaxLoader.popup.config.delayOut);
				});
			}
		},
		/**
		 * Open popup
		 */
		sopen: function(el, type, itemId, noMouseOut, callback){
			if (!ajaxLoader.activated) 
				return false;
			// if locked			
			if (ajaxLoader.popup.lock == true) 
			{
				return false;
			}
			
			//set lock
			ajaxLoader.popup.lock = true;
			// do ajax
			$.getJSON(ajaxLoader.config.ajaxPhpService, {
				'module': 'popup',
				'type': type,
				'item_id': itemId
			}, function(data){ // callback 
				// if some php error
				if (!data.requestOk) 
				{
					return false;
				}
				if (!noMouseOut) 
				{
					// set position
					ajaxLoader.popup.pwr.css(ajaxLoader.popup.pwrPos);
				}
				// append popup content
				ajaxLoader.popup.pwr.html(data.html);
				// ie height fix
				ajaxLoader.popup.hFix();
				// set switch
				ajaxLoader.popup.opened = true;
				if (!noMouseOut) 
				{
					// move cursor from thumb to popup
					ajaxLoader.popup.pwr.hover(function(){
						clearTimeout(ajaxLoader.popup.timerX);
					}, function(){
						clearTimeout(ajaxLoader.popup.timerX);
						// set close timer
						ajaxLoader.popup.timerX = setTimeout(function(){
							// remove popup
							ajaxLoader.popup.close();
						}, ajaxLoader.popup.config.delayOutPopup);
					});
				}
				if (typeof(callback) == 'function') 
				{
					callback(data.result);
				}
			});
		},
		/**
		 * IE 6,7 dimensions and css round error fix
		 */
		hFix: function(){
			if (!($.browser.msie && $.browser.version < 8)) 
				return false;
			var pp = ajaxLoader.popup.pwr.children('.popup');
			var pps = pp.children('.shadow');
			var ppab = pps.children('.shadowA,.shadowB');
			var ppcd = pps.children('.shadowC,.shadowD');
			// set auto height
			pp.css({
				height: 'auto'
			});
			// fix height
			pp.height(Math.round(pp.height()));
			ppab.height(Math.round(ppab.height()) + 15);
			ppcd.height(pp.height() - ppab.height() + 16);
		},
		/**
		 * Close popup
		 */
		close: function(){
			//			return false;
			if (ajaxLoader.popup.opened) 
			{
				ajaxLoader.popup.pwr.html('');
				ajaxLoader.popup.lock = false;
				ajaxLoader.popup.opened = false;
			}
		},
		lock: false,
		opened: false
	},
	activated: false
};


/**
 * Asterisks popups and toggle active
 */
var asterisk = {
	config: {
		activeClass: 'asteriskActive'
	},
	/**
	 * Set favorite state
	 * @param {Object} type
	 * @param {Object} itemId
	 * @param {Object} setfav
	 */
	set: function(type, itemId, setfav){
		$.getJSON(ajaxLoader.config.ajaxPhpService, {
			'module': 'favorite-toggle',
			'type': type,
			'item_id': itemId,
			'setfav': setfav
		}, function(data){ // callback
			// if some php error
			if (!data.requestOk) 
			{
				return false;
			}
			if (data.result == 1) 
			{
				$(asterisk.lastel).addClass(asterisk.config.activeClass);
			}
			else if (data.result == -1) 
			{
				$(asterisk.lastel).removeClass(asterisk.config.activeClass);
			}
		});
		ajaxLoader.popup.close();
		return false;
	},
	/**
	 * Toggle state - show popup
	 * @param {Object} el
	 * @param {Object} type
	 * @param {Object} id
	 */
	toggle: function(el, type, id){
		ajaxLoader.popup.open(el, 'favorite-' + type, id, true);
		asterisk.lastel = el;
		return false;
	}
};

/**
 * Create inline labels
 */
function inlineLabel(){
	$(':input[title]').each(function(){
		var $this = $(this);
		if ($this.val() === '') 
		{
			$this.val($this.attr('title'));
		}
		$this.focus(function(){
			if ($this.val() === $this.attr('title')) 
			{
				$this.val('');
			}
		});
		$this.blur(function(){
			if ($this.val() === '') 
			{
				$this.val($this.attr('title'));
			}
		});
	});
};

var theatresMap = {
	/**
	 * Init hover on map
	 */
	init: function(){
		var mapw = $('#mapWrapper');
		if (!mapw.length) 
			return false;
		var boffset = mapw.find('img').attr('src', mapw.find('img').attr('src').replace('tmap.png', 'blank.png')).height();
		mapw.find('area:not(.noTheatres)').hover(function(){
			var offset = $(this).index() + 1;
			offset *= boffset;
			mapw.find('.overlay').css('background-position', '0 -' + offset + 'px');
			clearInterval(theatresMap.delayedCloseInterval);
		}, function(){
			theatresMap.delayedCloseInterval = setInterval(function(){
				theatresMap.delayedClose(mapw);
			}, 100);
		});
		mapw.find('area.noTheatres').css('cursor', 'default');
	},
	/**
	 * Triggered delayed close
	 * @param {Object} mapw
	 */
	delayedClose: function(mapw){
		if (typeof(ajaxLoader.popup.opened) != 'undefined' && !ajaxLoader.popup.opened) 
		{
			mapw.find('.overlay').css('background-position', '0 0px');
			clearInterval(theatresMap.delayedCloseInterval);
		}
	},
	/**
	 * Slider in popup for each area
	 * @param {Object} el
	 */
	slide: function(el){
		// TODO popup ma fixovanou vysku pro IE !!!
		el = $(el);
		var item = el.parents('.item');
		var itemC = item.children('.content');
		var otherItems = item.siblings('.item:visible');
		var otherItemsC = otherItems.children('.content');
		// for IE 7 and older
		if ($.browser.msie && $.browser.version < 8) 
		{
			// use simple transitions
			otherItemsC.hide();
			itemC.show();
			if (typeof(ajaxLoader.popup.hFix) == 'function') 
			{
				// recount popup height
				ajaxLoader.popup.hFix();
			}
		}
		else 
		{
			otherItemsC.slideUp();
			itemC.slideDown();
		}
		otherItems.children('.title').children().removeClass('selected');
		$(el).addClass('selected');
	},
	delayedCloseInterval: false
};

/**
 * Tabs class
 * @param {Object} el
 */
var tab = {
	/**
	 * Toggle tab
	 * @param {Object} el
	 */
	toggle: function(el){
		var thisTab = $(el);
		var thisTabContent = $(thisTab.attr('href'));
		var allTabs = thisTab.parent().children();
		var tabContents = thisTab.parent().siblings('.inner').children('.tabContent');
		allTabs.removeClass('selected');
		thisTab.addClass('selected');
		tabContents.hide();
		thisTabContent.addClass('tabOn').show();
		if (typeof(Cufon) != 'undefined') 
		{
			Cufon.replace('.tabbed .tabs a', {
				hover: true
			});
		}
		return false;
	}
};

/**
 * Google maps class
 */
var gmap = {
	/**
	 * Push map data into stack
	 * @param {Object} id
	 * @param {Object} lat
	 * @param {Object} lon
	 * @param {Object} markerTitle
	 * @param {Object} address
	 * @param {Object} zoom
	 */
	push: function(id, lat, lon, markerTitle, address, zoom){
		var mdata = {
			id: id,
			lat: lat,
			lon: lon,
			markerTitle: markerTitle,
			address: address,
			zoom: zoom
		};
		gmap.stack[gmap.stack.length] = mdata;
		return mdata;
	},
	/**
	 * Show map
	 * @param {Object} id
	 * @param {Object} lat
	 * @param {Object} lon
	 * @param {Object} markerTitle
	 * @param {Object} zoom
	 */
	showMaps: function(){
		if (typeof(google) == 'undefined') 
			return false;
		for (var i = 0; i < gmap.stack.length; i++) 
		{
			var mdata = gmap.stack[i];
			//		map.ggeocoder = new google.maps.Geocoder();
			gmap.placeMap(gmap.stack[i]);
			//map.codeAddress(map.stack[i].address);
		}
	},
	placeMap: function(mdata){
		var myLatlng = new google.maps.LatLng(mdata.lat, mdata.lon);
		var myOptions = {
			zoom: mdata.zoom ? mdata.zoom : 14,
			center: myLatlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		}
		var ngmap = new google.maps.Map(document.getElementById(mdata.id), myOptions);
		var marker = new google.maps.Marker({
			position: myLatlng,
			map: ngmap,
			title: mdata.markerTitle
		});
	},
	/**
	 * Open map in new window
	 * @param {Object} mapdata
	 */
	window: function(mapdata){
		gmap.windowDestroy()
		mapdata.id = 'gmapMapPlaceholder';
		$('body').append('<div id="gmapPopupWrapper"><div id="gmapBar"><p><a href="#" class="more" onclick="gmap.windowDestroy()">Fermir</a></p></div><div id="gmapMapPlaceholder"></div></div>');
		var gmapPopupWrapper = $('#gmapPopupWrapper');
		var gmapMapPlaceholder = $('#gmapMapPlaceholder');
		var gmapBar = $('#gmapBar');
		var  barHeight = gmapBar.outerHeight();
		gmapBar.css({
			top: $(window).scrollTop(),
			left: $(window).scrollLeft()
		});
		gmapMapPlaceholder.css({
			height: $(window).height() - barHeight,
			width: $(window).width(),
			top: $(window).scrollTop() + barHeight,
			left: $(window).scrollLeft()
		});
		$(window).scroll(function(){
			gmapBar.css({
				top: $(window).scrollTop(),
				left: $(window).scrollLeft()
			});
			gmapMapPlaceholder.css({
				top: $(window).scrollTop() + barHeight,
				left: $(window).scrollLeft()
			});
		});
		gmap.placeMap(mapdata);
		return false;
	},
	/**
	 * Destroy popup map
	 */
	windowDestroy: function()
	{
		$('#gmapPopupWrapper').remove();
	},
	// TODO search by address - is necessary ??
	codeAddress: function(address){
		if (map.ggeocoder) 
		{
			map.geocoder.geocode({
				'address': address
			}, function(results, status){
				if (status == google.maps.GeocoderStatus.OK) 
				{
					map.setCenter(results[0].geometry.location);
					var marker = new google.maps.Marker({
						map: map,
						position: results[0].geometry.location
					});
				}
				else 
				{
					alert("Geocode was not successful for the following reason: " + status);
				}
			});
		}
	},
	stack: []
};

var iswitch = {
	open: function(el, hideBase){
		var button = $(el);
		var wrapper = button.parents('.iswitch');
		var openbwrap = wrapper.children('.more');
		var base = wrapper.children('.base');
		var additional = wrapper.children('.additional');
		
		if (typeof(hideBase) != 'undefined' && hideBase) 
		{
			base.slideUp();
		}
		additional.slideDown();
		openbwrap.hide();
		return false;
	},
	close: function(el, hideBase){
		var button = $(el);
		var wrapper = button.parents('.iswitch');
		var openbwrap = wrapper.children('.more');
		var base = wrapper.children('.base');
		var additional = wrapper.children('.additional');
		
		if (typeof(hideBase) != 'undefined' && hideBase) 
		{
			base.slideDown();
		}
		
		additional.slideUp();
		openbwrap.show();
		return false;
		
	}
};

function photoSlider()
{
	// init photoslider
	var pslider = $('.photoSlider');
	var psapi = pslider.filter(function()
	{
		return $(this).children('.items').children('.item').length > 1;
	}).append('<a class="prevPage browse left"></a><a class="nextPage browse right"></a><span class="infoCount"></span>').scrollable({
		size: 1,
		clickable: false,
		onSeek: function()
		{
			pslider.children('.infoCount').text((this.getPageIndex() + 1) + ' de ' + (this.getItems().length - 2/*-2 dute to cloned*/));
		}
	}).circular().navigator({
		api: true
	});
	if (isset(psapi)) 
	{
		pslider.children('.infoCount').text('1 de ' + (psapi.getItems().length - 2/*-2 dute to cloned*/));
	}
}

function displayLPF()
{
	$('#user-login').removeClass('hidden').hide();
	$('#user-lostpwd').removeClass('hidden').show();
	return false;
}

var popup = {
  init: function(inside, popupId, expires){
    if(typeof($.cookie)!=='function') return false;
    popup.id = popupId;
    popup.expires = expires;
    if( $.cookie('popDisplayed-'+popup.id) ) return false;
    $('body').append('<div id="popPlaceholder"><div id="popOverlay"><!-- --></div><table id="popInner"><tr><td><div class="inner"><div class="inside">'+inside+'</div><a href="#" class="close">Fermer la fenêtre</a></div></td></tr></table></div>');
    $('#popInner a').click(function(){ popup.click(); if( $(this).hasClass('close') || !$(this).attr('href') || $(this).attr('href') == '#' ) { return false; } });
    popup.ie6fix();
  },
  click: function()
  {
    $.cookie('popDisplayed-'+popup.id, true, {path:'/', expires: popup.expires });
		popup.remove();
  },
  remove: function()
  {
    popup.ie6unfix();
    $('#popPlaceholder').remove();
  },
  ie6fix: function()
  {
    if(! ($.browser.msie && parseInt($.browser.version) <= 6 )) return false;
    popup.fixedSelects = $('select:visible');
    popup.fixedSelects.css('visibility', 'hidden');
  },
  ie6unfix: function()
  {
    if(typeof(popup.fixedSelects)!=='object') return false;
    popup.fixedSelects.css('visibility', 'visible');
  }
};

var modal = {
  /**
   * Opens modal dialog
   * @param {String} inside HTML content
   * @param {String} popupId Id of modal - for cookie name
   * @param {Integer} expires Cookie expiration in days
   */
  open: function(inside, popupId, expires){
  	// cant use cookies, die
  	if (typeof($.cookie) !== 'function') 
  		return false;
  	modal.id = popupId;
  	modal.expires = expires;
	// set coookie to diplayed once
  	if ($.cookie('popDisplayed-' + modal.id) || $.cookie('popSendedForm-' + modal.id))
  		return false;
	// append html
  	$('body').append('<div id="popPlaceholder" class="modalDialog"><div id="popOverlay"><!-- --></div><table id="popInner"><tr><td><div class="inner"><div class="inside">' + inside + '</div></div></td></tr></table></div>');
	// fix ie6
  	popup.ie6fix();
	// find inner
  	modal.inner = $('#popPlaceholder .inner');
	// get inner height
	modal.height = modal.inner.height();
	// bind reposition on scroll
	$(window).bind('scroll', modal.setPosition);
	$(window).bind('resize', modal.setPosition);
	// reposition for first time
	modal.setPosition();
  },
  
  /**
   * Close modal for period
   */
  close: function()
  {
    popup.ie6unfix();
    $('#popPlaceholder').remove();
    $.cookie('popDisplayed-'+modal.id, true, {path:'/', expires: modal.expires });
	$(window).unbind('scroll');
	$(window).unbind('resize');
  },
  
  /**
   * Close modal forever
   */
  closeForever: function()
  {
    popup.ie6unfix();
    $('#popPlaceholder').remove();
    $.cookie('popDisplayed-'+modal.id, true, {path:'/', expires: 30});
	$(window).unbind('scroll');
	$(window).unbind('resize');
  },
  
  /**
   * Reposition modal
   */
  setPosition: function()
  {
	modal.inner.css({ 'margin-top': ($(window).height()-modal.height)/2+$(window).scrollTop() });
  },
  
  /**
   * Send form in modal if exists
   */
  sendForm: function(onsend, emailInputData)
  {
  	var form = modal.inner.find('form');
		var emailInput = form.find(emailInputData.selector);
		emailInput.parent().find('.warning').remove();
		if( emailInput.attr('value').match(/([a-z0-9._-]+@[a-z0-9._-]+.[a-z]+)/gi) )
		{
		  modal.emailSelectorStack = emailInput;
			var method = form.attr('method') ? form.attr('method') : 'get';
			var action = form.attr('action') ? form.attr('action') : window.location.href;
			$.ajax({
			  url: action,
			  type: method,
	  		  cache: false,
			  data: form.serialize(),
			  success: function(data) {
					if(typeof onsend == 'function')
					{
						onsend(data);
					}
			  }
			});
		}
		else
		{
			emailInput.parent().prepend('<p class="warning">'+emailInputData.message+'</p>');
		}
  }
};


function newsletterRegister (data)
{
	if(data==1)
	{
	  $.cookie('popSendedForm-' + modal.id, true, {path:'/', expires:30 });
    window.location.href = '/mon-compte/creer-un-compte.html?email='+modal.emailSelectorStack.attr('value');
	}
	else if(data==2)
	{
	  modal.emailSelectorStack.parent().prepend('<p class="warning">'+'L’adresse email saisie est déjà enregistrée.'+'</p>');
	}
}

function heightsEqualizer(elements, rwdl){
    var self = this;
    self.elements = elements;
    self.rwdl = typeof rwdl != 'undefined' ? rwdl : false;
    
    self.equalize = function(){
        var max = 0;
        $(self.elements).each(function(){
            if ($(this).css('min-height', '0').height('auto').height() > max) {
                max = $(this).height();
            }
        });
        if ($.browser.msie && parseInt($.browser.version) < 7) {
            $(self.elements).height(max + 'px');
        }
        else {
            $(self.elements).css('min-height', max + 'px');
        }
    }
    
    self.equalize();
    
    if (self.rwdl) {
        self.timer = window.setInterval(function(){
            try {
                self.equalize
            } 
            catch (e) {
            }
        }, 50);
        $(window).load(function(){
            window.clearInterval(self.timer);
        });
    }
};

//--------------------------------------------------------------------------

$(document).ready(function(){

  	//popup.init('<a href="#"><img src="/images/FootDeTheatre40x60.jpg" alt="Foot The Theatre" /></a>', 1, 7); // content, popup id (for cookie), cookie expiration (days, 0 = infinite)
	
	/*  mail form */
	/*if(window.location.href.match('developer'))
	{*/
	modal.open(
		  '<p class="title">Recevez gratuitement notre Newsletter</p>'
		+ '<form method="post" action="/ajax.php" class="content">'
		+ '<p class="question">Pour recevoir gracieusement l’actualité des spectacles des Théâtres Parisiens Associés et gérer vos favoris, inscrivez-vous !</p>'
		+ '<p class="entries"><label for="newsletter-mail">Votre adresse e-mail : </label><input type="text" name="newsletter-email" id="newsletter-mail" class="text email" /></p>'
		+ '<p class="buttons"><button onclick="modal.sendForm(newsletterRegister, { selector: \'.email\', message: \'Merci de saisir votre adresse e-mail afin de vous inscrire.\'});return false;">Je m’inscris</button> <button onclick="modal.close();return false;">Pas maintenant</button> <button onclick="modal.closeForever();return false;">Non, merci</button></p>'
		+ '</form>'
		, 'newsletter-1', 15); // content, popup id (for cookie), cookie expiration (days, 0 = infinite)
	/*}*/
	/**/

	// replace cufon texts (dont replace in 2 phases -> IE thorws error)
	Cufon.replace('#mainMenu>ul>li>a,#headerLinks .cufon,.tabbed .tabs a,.backLinks a,.mainTitle,.boxTitle,.cufon,.secondaryTitle,.bigTitle,.tabTitle', {
		hover: true
	});
	
	// center menu
	menuTools.center();
	
	// initialize multifunction lists
	mlist.init();
	
	// fix cifon menu hover bug
	menuTools.fixHover();
	
	// initilalize ajax loader
	ajaxLoader.init();
	
	// initialize inline labels
	inlineLabel();
	
	// theatres area items in row equal heights
	$('.boxTheatresArea .mapAreaTeatres .item').each(function(i){
		if(i%4==0)
		{
			new heightsEqualizer($('.boxTheatresArea .mapAreaTeatres .item .photo').slice(i, i+4), true);
			new heightsEqualizer($('.boxTheatresArea .mapAreaTeatres .item').slice(i, i+4), true);
		}
	});
	
	// theatres click maps
	theatresMap.init();
	

	$('.moreRoll').hover(function(){
		$(this).addClass('moreRollHover');
	}, function(){
		$(this).removeClass('moreRollHover');
	});
	
	photoSlider();
	
	// FF 3.6.3 mac bug
	//if( !( navigator.userAgent.match('Macintosh') && $.browser.mozilla && $.browser.version == '1.9.2.3' ) )
	//{
	 $('a.lightbox').fancybox().children('.border').append('<span class="zoom"></span>');
	//}
	
});

window.onload = function(){
	if (typeof(gmap) != 'undefined') 
	{
		gmap.showMaps();
	}
};

