var height_ = jQuery.fn.height;
jQuery.fn.height = function() {
    if ( this[0] == window && jQuery.browser.opera && jQuery.browser.version >= 9.50)
        return window.innerHeight;
    else return height_.apply($(this[0]));
};

$.fn.show_floating = function(options) {
	var defaults = {
		foreground: 'red',
		background: 'yellow'
	};
  // Extend our default options with those provided.
	var opts = $.extend(defaults, options);
  // Our plugin implementation code goes here.
  
	$('body').append('<div id="overlay"></div><table id="floating_window"><tbody><tr><td id="top_left"></td><td id="top_middle"></td><td id="top_right"></td></tr><tr><td id="middle_left"></td><td id="middle_middle"><div id="floating_window_content"></div></td><td id="middle_right"></td></tr><tr><td id="bottom_left"></td><td id="bottom_middle"></td><td id="bottom_right"></td></tr></tbody></table>');

	$(this).appendTo('#floating_window_content');

	if($.browser.msie) {
//		$('#overlay').show();
	} else {
//		$('#overlay').fadeIn('slow');
	}

	if($.browser.msie) {
		$('#floating_window').show();
	} else {
		$('#floating_window').fadeIn('slow');
	}
//alert($(window).height()+' '+$(window).innerHeight( ));
	$('#floating_window').css('left',($(window).width()-$('#floating_window').width())/2);
	$('#floating_window').css('top',($(window).height()-$('#floating_window').height())/2);
	$("#floating_window #button_cancel").click(function() { $.fn.dialog_hide(); });
	$("#floating_window #button_ok").click(function() { $.fn.dialog_hide(); });

};
/*
function show_floating_message( initialize )
{
	$('body').append('<div id="overlay"></div><table id="floating_window"><tbody><tr><td id="top_left"></td><td id="top_middle"></td><td id="top_right"></td></tr><tr><td id="middle_left"></td><td id="middle_middle"><div id="container"></div></td><td id="middle_right"></td></tr><tr><td id="bottom_left"></td><td id="bottom_middle"></td><td id="bottom_right"></td></tr></tbody></table><img id="loading_indicator" src="/pic/ajax-loader.gif" />');

	if($.browser.msie) {
		$('#overlay').show();
	} else {
		$('#overlay').fadeIn('slow');
	}

	$('#section_message').appendTo('#floating_window #container');

	if($.browser.msie) {
		$('#floating_window').show();
	} else {
		$('#floating_window').fadeIn('slow');
	}
//alert($(window).height()+' '+$(window).innerHeight( ));
	$('#floating_window').css('left',($(window).width()-$('#floating_window').width())/2);
	$('#floating_window').css('top',($(window).height()-$('#floating_window').height())/2);
	$("#floating_window #button_cancel").click(function() { $.fn.dialog_hide(); });
	$("#floating_window #button_ok").click(function() { $.fn.dialog_hide(); });
	
	if(initialize) {
		initialize();
	}
}
*/
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

(function($) {

$.fn.dialog_hide = function(options)
{
	if($.browser.msie) {
		$('#floating_window').remove();
		$('#overlay').remove();
	} else {
		$('#floating_window').fadeOut('fast', function() {$(this).remove();});
		$('#overlay').fadeOut('fast', function() {$(this).remove();});
	}
}


$.fn.internal_label = function(text) {

	var bound_global_events = $.fn.internal_label.bound_global_events;

	if (bound_global_events == 0) {
		$(window).unload(function() {
			$('.internal_label').val('');
		});

		$(this).parents('form:first').submit(function() {
			if(admin_on_board) {
				$('.internal_label').val('');
			}
		});

		bound_global_events = 1;
		$.fn.internal_label.bound_global_events = bound_global_events;
	}

	return this.each(function() {
		var $this = $(this);

		if ($this.val() == '') {
			$this.addClass('internal_label');
			$this.val(text);
		}

		$this.focus(function() {
			if ($(this).is('.internal_label')) {
				$(this).val('');
				$(this).removeClass('internal_label');
			}
		});

		$this.blur(function() {
			if (jQuery.trim($(this).val()) == '') {
				$(this).addClass('internal_label');
				$(this).val(text);
			}
		});
	});
};

$.fn.internal_label.bound_global_events = 0;

})(jQuery);

function simple_dialog(message)
{
	$('body').append('<div id="section_message"><p>' + message + '</p><button id="button_ok">OK</button></div>');
	if(message.length>20) {
		$('#section_message').width(300);
	}
	show_floating_message( null );
}

function create_review_editor( o, field_body, field_author, field_evaluation, field_review_id, field_location_id )
{
/*
	switch( field_evaluation ) {
		case '4': evaluation_name = 'ZACHWYCAJĄCE'; break;
		case '3': evaluation_name = 'BARDZO FAJNE'; break;
		case '2': evaluation_name = 'FAJNE'; break;
		case '1': evaluation_name = 'TAKIE SOBIE'; break;
		case '0': evaluation_name = 'NIECIEKAWE'; break;
		default: evaluation_name = 'Twoja ocena...';
	}
*/
//	o.after('<div id="section_review_editor"><textarea id="field_body">'+field_body+'</textarea><div id="buttons"><img id="combobox_arrow" src="/pic/combobox_arrow.png" /><input type="button" id="combobox_evaluation" value="'+evaluation_name+'" /><input id="field_author" type="text" value="'+field_author+'" /><input id="field_email" type="text" value="'+field_email+'" /><input  id="button_submit" type="BUTTON" value="ZAPISZ" /><input id="field_evaluation" type="text" value="'+field_evaluation+'" /><input id="field_review_id" type="text" value="'+field_review_id+'" /><div id="list_evaluations"><div class="evaluation_name" data-evaluation="4">ZACHWYCAJĄCE</div><div class="evaluation_name" data-evaluation="3">BARDZO FAJNE</div><div class="evaluation_name" data-evaluation="2">FAJNE</div><div class="evaluation_name" data-evaluation="1">TAKIE SOBIE</div><div class="evaluation_name" data-evaluation="0">NIECIEKAWE</div></div></div>');

	$('#section_review_editor').remove();
//	$('#section_reviews .one_review').show();

	//o.after('<div id="section_review_editor"><form id="review_editor_form" method="POST" action="/review_manipulation"><fieldset><textarea name="field_body" id="review_editor_field_body">'+field_body+'</textarea><div id="review_editor_fields"><div id="review_editor_evaluation_dropdown" class="evaluation_dropdown_empty">Twoja ocena...</div><div id="review_editor_evaluation_dropdown_icon"></div><div id="review_editor_evaluation_dropdown_list"><div class="evaluation_dropdown_list_element evaluation_dropdown_list_element_4" data-evaluation="4">ZACHWYCAJĄCE<span>, fantastyczne, niesamowite, jedyne w swoim rodzaju</span></div><div class="evaluation_dropdown_list_element evaluation_dropdown_list_element_3" data-evaluation="3">BARDZO FAJNE<span>, rewelacja, polecam</span></div><div class="evaluation_dropdown_list_element evaluation_dropdown_list_element_2" data-evaluation="2">FAJNE<span>, nic dodać, nic ująć</span></div><div class="evaluation_dropdown_list_element evaluation_dropdown_list_element_1" data-evaluation="1">TAKIE SOBIE<span>, raczej nie warto sobie zawracać głowy</span></div><div class="evaluation_dropdown_list_element evaluation_dropdown_list_element_0" data-evaluation="0">NIECIEKAWE<span>, nie ma tu absolutnie nic ciekawego, w miarę możliwości lepiej omijać</span></div></div><input type="text" name="field_author" value="'+field_author+'" id="review_editor_field_author"><div id="review_editor_button_submit">ZAPISZ</div><input type="hidden" id="review_editor_field_review_id" name="field_review_id" value="'+field_review_id+'"><input type="hidden" id="review_editor_field_location_id" name="field_location_id" value="'+field_location_id+'"><input type="hidden" id="review_editor_field_evaluation" name="field_evaluation" value="'+field_evaluation+'" /></div></fieldset></form></div>');
	o.after('<div id="section_review_editor"><form id="review_editor_form" method="POST" action="/review_manipulation"><fieldset><textarea name="field_body" id="review_editor_field_body">'+field_body+'</textarea><div id="review_editor_fields"><div id="review_editor_evaluation_dropdown" class="evaluation_dropdown_empty">Twoja ocena...</div><div id="review_editor_evaluation_dropdown_icon"></div><div id="review_editor_evaluation_dropdown_list"><div class="evaluation_dropdown_list_element evaluation_dropdown_list_element_4" data-evaluation="4">ZACHWYCAJĄCE<span>, fantastyczne</span></div><div class="evaluation_dropdown_list_element evaluation_dropdown_list_element_3" data-evaluation="3">BARDZO FAJNE<span>, rewelacja, polecam</span></div><div class="evaluation_dropdown_list_element evaluation_dropdown_list_element_2" data-evaluation="2">FAJNE<span>, nic dodać, nic ująć</span></div><div class="evaluation_dropdown_list_element evaluation_dropdown_list_element_1" data-evaluation="1">TAKIE SOBIE<span>, raczej nie warto</span></div><div class="evaluation_dropdown_list_element evaluation_dropdown_list_element_0" data-evaluation="0">NIECIEKAWE<span>, lepiej unikać</span></div></div><input type="text" name="field_author" value="'+field_author+'" id="review_editor_field_author"><div id="review_editor_button_submit">ZAPISZ</div><input type="hidden" id="review_editor_field_review_id" name="field_review_id" value="'+field_review_id+'"><input type="hidden" id="review_editor_field_location_id" name="field_location_id" value="'+field_location_id+'"><input type="hidden" id="review_editor_field_evaluation" name="field_evaluation" value="'+field_evaluation+'" /></div></fieldset></form></div>');
	
	if( field_review_id ) {
		$('#review_editor_evaluation_dropdown').html( $('.evaluation_dropdown_list_element_'+field_evaluation).html() ).removeClass('evaluation_dropdown_empty').addClass('evaluation_dropdown_'+field_evaluation);
	}

	$('#review_editor_field_body').animate({height: 80},'fast',function(){$('#review_editor_fields').slideDown('fast')});
	//if( field_evaluation ) {
	//	$("#evaluation_"+field_evaluation).attr("checked", "checked");
	//}

	$('#review_editor_field_body').internal_label('Twoja opinia...');
	$('#review_editor_field_author').internal_label('Twój podpis...');
	//$('#section_review_editor #field_email').internal_label('Twój e-mail...');

	$('#review_editor_field_body').focus();
	$('#review_editor_evaluation_dropdown, #review_editor_evaluation_dropdown_icon').click(function() {
		$('#review_editor_evaluation_dropdown_list').show();
	});
	$('#review_editor_evaluation_dropdown_list').mouseleave(function(){
		$(this).fadeOut('fast');
	});

	$('.evaluation_dropdown_list_element').click(function(){
		$('#review_editor_evaluation_dropdown_list').fadeOut('fast');
		$('#review_editor_evaluation_dropdown').html($(this).html()).removeClass('evaluation_dropdown_empty').removeClass('evaluation_dropdown_4').removeClass('evaluation_dropdown_3').removeClass('evaluation_dropdown_2').removeClass('evaluation_dropdown_1').removeClass('evaluation_dropdown_0').addClass('evaluation_dropdown_'+$(this).data('evaluation')); //.css('padding-left','72px');
		$('#review_editor_field_evaluation').val($(this).data('evaluation'));
	});

/*
	$('#evaluation_tabs .evaluation').click(function() {
		$('#evaluation_tabs .marked_evaluation').removeClass('marked_evaluation');
		$(this).addClass('marked_evaluation');
		$('#section_review_editor #field_evaluation').val( $(this).attr('data-evaluation') );
	});
*/
//	$('#section_review_editor #field_body').focus( function() {
//		if( $(this).hasClass('minified') ) {
//			$('#section_review_editor #evaluation_tabs').slideDown();
//			$(this).val('').animate({height: 80+'px'}, 300, 'linear', function() { $('#review_editor_fields').slideDown(); });
//			$(this).removeClass('minified');
//		}
//	});

	$('#review_editor_button_submit').click(function() {
		$('#review_editor_form').submit();
	});

	$('#review_editor_form').submit(function() {
//		var empty_body      = $('#review_editor_form #field_body').hasClass('internal_label');
//		var empty_author    = $('#review_editor_form #field_author').hasClass('internal_label');
//		var empty_email     = $('#review_editor_form #field_email').hasClass('internal_label');

		if( $('#review_editor_field_review_id').val()!='' &&  $('#review_editor_field_body').hasClass('internal_label') && $('#review_editor_field_author').hasClass('internal_label') ) {
			$('#review_editor_field_body').val('');
			$('#review_editor_field_author').val('');
			return true;
		}

		if( $('#review_editor_field_body').hasClass('internal_label') || $('#review_editor_field_body').val().length < 10 ) {
			alert('Proszę choć o kilka słów komentarza.');
			return false;
		}

		if( $('#review_editor_field_author').hasClass('internal_label') ) {
			alert('Nie zapomnij się podpisać.');
			return false;
		}

		if( $('#review_editor_field_evaluation').val() == '' ) {
			alert('Wskaż proszę swoją ocenę.');
			return false;
		}

	});
/*
	$('#section_review_editor #combobox_evaluation').click( function() {
		$('#section_review_editor #list_evaluations').show();
		$('#section_review_editor #list_evaluations').mouseleave( function() {
			$(this).hide();
			$('#section_review_editor #combobox_evaluation').blur();
		});
		$('#section_review_editor #list_evaluations .evaluation_name').click( function() {
			$('#section_review_editor #field_evaluation').val( $(this).attr('data-evaluation') );
			$('#section_review_editor #combobox_evaluation').val( $(this).text() );
			$('#section_review_editor #list_evaluations').hide();
//			$('#section_review_request #combobox_evaluation').blur();
		});
	});
*/
}

function autocompleteFormatItem(row,i,j)
{
  return '<strong>'+row[0]+'</strong>, <i>'+row[1]+'</i>';
}

function autocompleteSelected(li)
{
//  autocompleteFindValue(li);
//	$('#section_search #search_box').val('Szukaj...');
	window.location = li.extra[1];
}



function Map() {

	this.animate_marker = function( location_id ) {
		animate( markers[location_id] );
	}

	var section_map = $('#section_map');
	var map_canvas  = $('#map_canvas');
	var tooltip_country = $('#map_tooltip_country');

	var	map     = {width: section_map.width(), height: section_map.height()};
	var	canvas  = {width: map.width * 3, height: map.height * 3};
	var viewbox = {left: 0, top: 0, width: 0, height: 0};
	var offset  = {left: 0, top: 0, horizontal_min: 0, horizontal_max: 0, vertical_min: 0, vertical_max: 0};
	//var boundary = {left: 3200, right: 15500, top: 3500, bottom: 10500};
	var boundary = {left: 1300, right: 15500, top: 3000, bottom: 10500};

	var attributes_country         = {fill: '#e0e0e0', stroke: '#ffffff', 'stroke-width': 1};
	var attributes_country_current = {fill: '#f8f8f8', stroke: '#ffffff', 'stroke-width': 1};
	var attributes_route           = {stroke: '#d0d0d0', 'stroke-width': 1, 'stroke-dasharray': '.'};

	var paper, zoom, markers=[], countries=[], markers_on_map, current_animated_marker;

	var map_offset = section_map.offset();

	if(typeof(region_boundary) == 'undefined') {
		zoom = Math.min( (map.width - 20) / (paths[current_country].right - paths[current_country].left), (map.height - 20) / (paths[current_country].bottom - paths[current_country].top) );
	} else {
		zoom = Math.min( (map.width - 20) / (region_boundary.right - region_boundary.left), (map.height - 20) / (region_boundary.bottom - region_boundary.top) );
	}		

	var zoom_limit = Math.max( map.width / (boundary.right - boundary.left), map.height / (boundary.bottom - boundary.top) );

	map_canvas.css({width: canvas.width, height: canvas.height});

	//render();
	
	if( typeof(region_boundary) == 'undefined' ) {
		center_map( paths[current_country].left+(paths[current_country].right-paths[current_country].left)/2, paths[current_country].top+(paths[current_country].bottom-paths[current_country].top)/2, Math.round(map.width/2), Math.round(map.height/2) );
	} else {
		center_map( (region_boundary.left+(region_boundary.right-region_boundary.left)/2), region_boundary.top+(region_boundary.bottom-region_boundary.top)/2, Math.round(map.width/2), Math.round(map.height/2) );
		//var xx = paper.rect(region_boundary.left, region_boundary.top, region_boundary.right-region_boundary.left, region_boundary.bottom-region_boundary.top);
		//xx.attr({stroke: '#ff6060', 'stroke-width': 1});
	}		

	function render()
	{
		paper = Raphael('map_canvas', canvas.width, canvas.height);

		for (var country in paths) {
			var o = [], z = 0;
			for (var pi in paths[country].path) {
				pl = paths[country].path[pi].length;
				for(var i=0;i<pl;i+=6) {
					x = parseInt(paths[country].path[pi].substr(i,3),36);
					y = parseInt(paths[country].path[pi].substr(i+3,3),36);
					o[z++] = ((i==0?'M':(i==6?'L':''))+x+','+y);
				}
				if( paths[country].label!='Route' ) {
					o[z++] = 'z ';
				}
			}

			var p   = o.join(' ');

			var obj = paper.path(p);

			countries[obj.id] = country;

			if( country==current_country ) {
				obj.attr(attributes_country_current);
			} else if( paths[country].label=='Route' ) {
				obj.attr(attributes_route);
			} else {
				obj.attr(attributes_country);
				obj.attr({label: country});
				//obj.attr({fill: paths[country].color});
				obj.hover(function (event) {
					this.attr({fill: '#dcdcdc'});
					country_tooltip_show( countries[this.id] );
				}, function (event) {
					this.attr({fill: '#e0e0e0'});
					country_tooltip_hide();
				});
				//if( map_countries[country] ) {
					//obj.attr({cursor: 'pointer'});
					//obj.dblclick(function (event) {
					//	window.location =  '/' + map_countries[countries[this.id]].folder;
					//});
				//}
			}
			
			paths[country].object = obj;
		}

		if(map_places) {
			paper.setStart();
			$.each( map_places, function(k,place) {

				var marker_fill;
				switch( place['evaluation'] ) {
					case '0': marker_fill = '#f0f0f0'; break;
					case '1': marker_fill = '#d2d2d2'; break;
					case '2': marker_fill = '#ffff00'; break;
					case '3': marker_fill = '#ffb401'; break;
					case '4': marker_fill = '#fe3e20'; break;
					default: marker_fill = '#606060'; break;
				}


				var obj=paper.circle( place['longitude']*100 /**factor-map_offset_x*/, (90-place['latitude'])*100 /**factor-map_offset_y*/, 4/zoom);
				obj.attr({fill: marker_fill, stroke: '#606060', 'stroke-width': 1, cursor: 'pointer'});

				markers[k] = obj;

			  	obj.mouseover(function() {
			  		//console.log('mouseover');
			  		obj.attr({r: 5/zoom});
		   			location_tooltip_show( place['id'] );
				});
			  	obj.mouseout(function() {
			  		//console.log('mouseout');
			  		obj.attr({r: 4/zoom});
		   			location_tooltip_hide();
				});
			  	obj.click(function() {
		   			load_location( place['id'] );
					//animate( obj );
					map_current_location_id=place['id'];
				});
				if( map_current_location_id==place['id'] ) {
					animate( obj );
				}
			});
			markers_on_map = paper.setFinish();
		}
	}
	//var xx = r.rect(boundary.left, boundary.top, boundary.right-boundary.left, boundary.bottom-boundary.top);
	//xx.attr({stroke: '#ff6060', 'stroke-width': 1});

//console.log(typeof(region_boundary));


	function animate( obj )
	{
		if( current_animated_marker ) {
			current_animated_marker.stop();
			current_animated_marker.animate({r:4/zoom},500);
		}
		var inner_animate = function() {
			obj.animate({'50%':{r:0,easing: '<'}, '100%':{r:5/zoom,easing: '>',callback: inner_animate}},1000);
		}
		inner_animate();
		current_animated_marker = obj;
	}

	function country_tooltip_show( country )
	{
		section_map.mousemove( function(e) {

			//var newX = (e.pageX-map_offset.left) - tooltipWidth/2 + scroll.left;
			var newX = (e.pageX-map_offset.left) + 14/*- offset.left*/;
			//var newY = (e.pageY-map_offset.top) - tooltipHeight-5 + scroll.top;
			var newY = (e.pageY-map_offset.top)/* - offset.top*/;

			//console.log(newX, newY);
			tooltip_country.css({'left': newX, 'top': newY});
		});

		tooltip_country.html(paths[country].label);

		var tooltipWidth = tooltip_country.width();
		var tooltipHeight = tooltip_country.height();

//		if($.browser.msie) {
			tooltip_country.show();
//		} else {
//			tooltip_country.stop(true).animate({ opacity: 1}, 100);
//		}
	}

	function country_tooltip_hide()
	{
		section_map.unbind('mousemove');

//		if($.browser.msie) {
			$('#map_tooltip_country').hide();
//		} else {
//			$('#map_tooltip_country').stop(true).animate({ opacity: 0}, 100, function() {$(this).css('left',-10000);});
//		}
	}

	function location_tooltip_show( location_id )
	{
		var tooltip = $('#map_tooltip_location');

		tooltip.html('<strong>'+map_places[ location_id ].name+'</strong><br />'+map_places[ location_id ].description);

		var tooltipWidth = tooltip.width() + 10;
		var tooltipHeight = tooltip.height() + 10;

		var x = Math.round(map_places[ location_id ].longitude*100*zoom - viewbox.left*zoom - tooltipWidth/2 - map.width);
		var y = Math.round((90-map_places[ location_id ].latitude)*100*zoom - viewbox.top*zoom - tooltipHeight - map.height - 10);

		if( x < 5 ) {
			x = 5;
		}
		if( y < 5 ) {
			y = y + tooltipHeight + 30;
		}
		if( x + tooltipWidth > map.width - 5 ) {
			x = map.width - tooltipWidth - 5;
		}

		tooltip.css({'left': x, 'top': y});

		if($.browser.msie) {
			tooltip.show();
		} else {
			tooltip.stop(true).animate({ opacity: 1}, 100);
		}
	} 

	function location_tooltip_hide()
	{
		if($.browser.msie) {
			$('#map_tooltip_location').hide().css('left',-10000);
		} else {
			$('#map_tooltip_location').stop(true).animate({ opacity: 0}, 100, function() {$(this).css('left',-10000);});
		}
	}

	function center_map( gx, gy, mx, my )
	{
		viewbox.left   = Math.round(gx-(mx+map.width)/zoom);
		viewbox.top    = Math.round(gy-(my+map.height)/zoom);
		viewbox.width  = Math.round(canvas.width/zoom);
		viewbox.height = Math.round(canvas.height/zoom);

		viewbox.left   = Math.round(Math.min(Math.max( gx-(mx+map.width)/zoom, boundary.left-map.width/zoom ), boundary.right-2*map.width/zoom));
		viewbox.top    = Math.round(Math.min(Math.max( gy-(my+map.height)/zoom, boundary.top-map.height/zoom ), boundary.bottom-2*map.height/zoom));

		if(typeof(paper)=='undefined' || Raphael.type!='SVG') {
			render();
		}

		paper.setViewBox(viewbox.left, viewbox.top, viewbox.width, viewbox.height, false);

		offset.left = -map.width;
		offset.top  = -map.height;
		map_canvas.css({left: offset.left, top: offset.top});

		offset.horizontal_min = Math.round((viewbox.left-boundary.right)*zoom+map.width);
		offset.horizontal_max = Math.round((viewbox.left-boundary.left)*zoom);
		offset.vertical_min = Math.round((viewbox.top-boundary.bottom)*zoom+map.height);
		offset.vertical_max = Math.round((viewbox.top-boundary.top)*zoom);
	}

	$('#map_canvas').mousewheel(function(event, delta) {
		event.preventDefault();

		var zoom_old = zoom;

		zoom = Math.max( zoom * (delta==1?1.2:1/1.2), zoom_limit );

		markers_on_map.attr({r: 4/zoom});
		//for(k in markers) {
		//	markers[k].attr({r: 4/zoom});
		//}

		center_map( viewbox.left+(map.width+event.pageX-map_offset.left)/zoom_old, viewbox.top+(map.height+event.pageY-map_offset.top)/zoom_old, event.pageX-map_offset.left, event.pageY-map_offset.top );
	});
	
	$('#map_canvas').dblclick(function(event) {
		event.preventDefault();
		var zoom_old = zoom;
		zoom = zoom * 2;
		markers_on_map.attr({r: 4/zoom});
		center_map( viewbox.left+(map.width+event.pageX-map_offset.left)/zoom_old, viewbox.top+(map.height+event.pageY-map_offset.top)/zoom_old, event.pageX-map_offset.left, event.pageY-map_offset.top );
	});

	$('#map_canvas').bind('dragstart', function( event, dd ){
		dd.left = offset.left;
		dd.top  = offset.top;
		map_canvas.css('cursor', 'move');
	});

	$('#map_canvas').bind('dragend', function( event, dd ){
		map_canvas.css('cursor', 'default');
		//scroll.top = section_map.scrollTop();
		//scroll.left = section_map.scrollLeft();
		center_map( viewbox.left+(map.width/2-offset.left)/zoom, viewbox.top+(map.height/2-offset.top)/zoom, map.width/2, map.height/2 );
	});

	$('#map_canvas').bind('drag', function( event, dd ){
		offset.left = dd.left + dd.deltaX;
		offset.top  = dd.top  + dd.deltaY;
		//console.log('drag',dd.top,dd.deltaY,offset.vertical_min,offset_top,offset.vertical_max);
		if(offset.left < offset.horizontal_min) {
			offset.left = offset.horizontal_min;
		} else if(offset.left > offset.horizontal_max) {
			offset.left = offset.horizontal_max;
		}
		if(offset.top < offset.vertical_min) {
			offset.top = offset.vertical_min;
		} else if(offset.top > offset.vertical_max) {
			offset.top = offset.vertical_max;
		}
		map_canvas.css({top: offset.top, left: offset.left});	
		//r.translate(dd.deltaX, dd.deltaY);
		//console.log
		//markers_on_map.translate(offset.left - dd.left, offset.top - dd.top);
	});

	$('#map_zoom_in').click(function() {
		var zoom_old = zoom;
		zoom = zoom * 1.5;
		markers_on_map.attr({r: 4/zoom});
		center_map( viewbox.left+viewbox.width/2, viewbox.top+viewbox.height/2, map.width/2, map.height/2 );
	});

	$('#map_zoom_out').click(function() {
		var zoom_old = zoom;
		zoom = Math.max( zoom / 1.5, zoom_limit );
		markers_on_map.attr({r: 4/zoom});
		center_map( viewbox.left+viewbox.width/2, viewbox.top+viewbox.height/2, map.width/2, map.height/2 );
	});
}

function initialize_google_map() {
/*  var myLatlng = new google.maps.LatLng(-34.397, 150.644);
  var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("section_map_google"), myOptions);

return;
*/
	var myLatlng = new google.maps.LatLng(90-(paths[current_country].top+(paths[current_country].bottom-paths[current_country].top)/2)/100, (paths[current_country].left+(paths[current_country].right-paths[current_country].left)/2)/100);

//console.log((paths[current_country].left+(paths[current_country].right-paths[current_country].left)/2)/100, 90-(paths[current_country].top+(paths[current_country].bottom-paths[current_country].top)/2)/100);
	var myOptions = {
	    zoom: 4/*map_location.zoom*/,
	    center: myLatlng,
	    panControl: false,
	    streetViewControl: false,
	    zoomControlOptions: { style: google.maps.ZoomControlStyle.SMALL },
	    mapTypeId: google.maps.MapTypeId.ROADMAP,
	    mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU, mapTypeIds: [google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN], position: google.maps.ControlPosition.RIGHT_TOP }
	}
	var map = new google.maps.Map(document.getElementById('section_map_google'), myOptions);
//return;
//  $('#floating_map').css('position','fixed');

//	var styledMapOptions = { name: "Mandalay" }

	//var jayzMapType = new google.maps.StyledMapType( stylez, styledMapOptions );

	//map.mapTypes.set('mandalay', jayzMapType);
	//map.setMapTypeId('mandalay');

//    alert(map_places);

/*
	var image_dot   = new google.maps.MarkerImage('/pic/new_dot_red.png',	new google.maps.Size(10, 10),new google.maps.Point(0,0),new google.maps.Point(5, 5));
	var image_dot_current   = new google.maps.MarkerImage('/pic/dot_current.png',new google.maps.Size(10, 10),new google.maps.Point(0,0),new google.maps.Point(5, 5));
	var image_dot_0 = new google.maps.MarkerImage('/pic/markers.png',	new google.maps.Size(10, 10),new google.maps.Point(0,0),new google.maps.Point(5, 5));
	var image_dot_1 = new google.maps.MarkerImage('/pic/markers.png',	new google.maps.Size(10, 10),new google.maps.Point(10,0),new google.maps.Point(5, 5));
	var image_dot_2 = new google.maps.MarkerImage('/pic/markers.png',	new google.maps.Size(10, 10),new google.maps.Point(20,0),new google.maps.Point(5, 5));
	var image_dot_3 = new google.maps.MarkerImage('/pic/markers.png',	new google.maps.Size(10, 10),new google.maps.Point(30,0),new google.maps.Point(5, 5));
	var image_dot_4 = new google.maps.MarkerImage('/pic/markers.png',	new google.maps.Size(10, 10),new google.maps.Point(40,0),new google.maps.Point(5, 5));
	var image_animated_0 = new google.maps.MarkerImage('/pic/markers_animated.gif',	new google.maps.Size(10, 10),new google.maps.Point(0,0),new google.maps.Point(5, 5));
	var image_animated_1 = new google.maps.MarkerImage('/pic/markers_animated.gif',	new google.maps.Size(10, 10),new google.maps.Point(10,0),new google.maps.Point(5, 5));
	var image_animated_2 = new google.maps.MarkerImage('/pic/markers_animated.gif',	new google.maps.Size(10, 10),new google.maps.Point(20,0),new google.maps.Point(5, 5));
	var image_animated_3 = new google.maps.MarkerImage('/pic/markers_animated.gif',	new google.maps.Size(10, 10),new google.maps.Point(30,0),new google.maps.Point(5, 5));
	var image_animated_4 = new google.maps.MarkerImage('/pic/markers_animated.gif',	new google.maps.Size(10, 10),new google.maps.Point(40,0),new google.maps.Point(5, 5));
	var image;
*/
	var marker_animated, markers=[];

	$.each( map_places, function(k,place) {
		var myLatLng = new google.maps.LatLng(place['latitude'], place['longitude']);
		var marker = new google.maps.Marker({
		    position: myLatLng,
		    map: map,
		    title: place.name
		});
		markers[place['id']] = marker;

	  	google.maps.event.addListener(marker, 'click', function() {
	  		if(marker_animated) {
	  			marker_animated.setAnimation(null);
	  		}
	  		this.setAnimation(google.maps.Animation.BOUNCE);
	  		marker_animated = this;
   			load_location( place['id'] );
		});

		if( map_current_location_id==place['id'] ) {
			marker_animated = marker;
			marker_animated.setAnimation(google.maps.Animation.BOUNCE);
		}
	});
}

function load_location( location_id ) {
	var folder;
	if( map_places[location_id] ) {
		folder = map_places[location_id].folder;
	} else {
		return;
	}
	if (typeof(history.replaceState) != 'undefined') { 
		history.replaceState({ location_id: location_id }, 'page 2', '/'+folder);
	}
//	$('#section_location_social_buttons').appendTo('#section_locations');
	$('#section_location').fadeOut('fast');
	$('#section_locations').fadeOut('fast');
	$('#section_location_loading').show();
	
	$('#section_location_content').load('/location/'+location_id, function() {
		if( typeof(_gaq) != 'undefined' ) { 
			_gaq.push(['_trackPageview', '/'+folder]);
		}
		$('#section_location_loading').hide();
		$('#section_location').stop(true,true).fadeIn('fast');
		$('#section_locations').hide();
		$('#section_location .switch_article_button').click(function() {
			console.log('click');
			$('#section_location').toggle();
			$('#section_locations').toggle();
		});

		initialize_section_gallery();
		initialize_section_reviews();
		initialize_section_admin();
		map.animate_marker( location_id );
		$('#section_locations .current_location').removeClass('current_location');
		$('#section_locations .one_location[data-location_id='+location_id+']').addClass('current_location');
	});
}


var thumbnails = {};
var thumbnails_count = 0;
var thumbnails_preloaded_first,thumbnails_preloaded_last;
var floating_picture, previous_picture;
var thumbnails_counter = 0;
var image_width = 0;

var image_view_mode = false;
var pointer_x = 0;
var pointer_y = 0;

function position_picture()
{
	var section_image = $('#section_image');
	var section_image_img = $('#section_image_img');

	var document_width = $(document).width();
	var section_width  = section_image.width();
	var section_height  = section_image.height();
	var delta = image_width - section_width;
	var shift = 0;

	console.log('position_picture '+section_image_img.height()+' '+section_height+ ' '+(section_image_img.height()/section_height));

	if( section_image_img.height()/section_height < 0.75 ) {
		section_image_img.css({'height': section_image_img, 'top': Math.round((section_height-section_image_img.height())/2), 'border-top-width': '1px', 'border-bottom-width': '1px'});
	} else {
		section_image_img.css({'height': '100%', 'top': 0, 'border-top-width': '0', 'border-bottom-width': '0'});
	}

	var image_width  = section_image_img.width();

	if( image_width < section_width ) {
		section_image_img.css({'left': Math.round((section_width-image_width)/2), 'border-left-width': '1px', 'border-right-width': '1px'});
	} else {
		$('body').mousemove( function(e) {
			shift = -Math.round((image_width - section_width) * ((e.pageX) / document_width));
			//$('#section_image_img').stop(true).animate({ left: shift }, 'fast' );
			section_image_img.css('left',shift);
			//console.log('mousemove '+(e.pageX / document_width * 100)+' '+image_width+' '+section_width+' '+delta+' '+shift);
		});
	}
}

function create_floating_picture( c, i )
{
	if( c==0 ) {
		thumbnails_preloaded_first = i;
		thumbnails_preloaded_last = i;
	}
	var p = thumbnails[i];
	var preload = new Image();
	preload.onload = function() {
		if( c==0 ) {
			$('#loading_indicator').remove();
			$('body').append('<div id="overlay"></div>');
//			$('body').append('<div class="floating_picture" id="floating_picture_'+i+'">'+(i>0?'<div class="floating_picture_left"></div>':'')+(i+1<thumbnails_counter?'<div class="floating_picture_right"></div>':'')+($.browser.msie?'':'<div class="floating_picture_caption_overlay"></div>')+'<div class="floating_picture_caption"><a href="/'+p['lf']+'">'+p['ln']+'</a> <img src="/pic/photo.png" /> <a href="/galeria/'+p['af']+'">'+ p['an'] + '</a>'+(admin_on_board?' <span class="button_edit_picture" data-picture_id="'+p['pid']+'">edytuj</span>':'')+'<br />'+p['d']+(p['lic']==''?'':'<br /><span class="floating_picture_license">Licencja: <a href="'+p['liu']+'">'+p['lic']+'</a>'+(p['su']==''?'':' <a href="'+p['su']+'">Źródło</a>')+'</span>')+'</div></div>');
//			$('body').append('<div id="overlay"></div>');
			if($.browser.msie) {
				$('#overlay').show();
			} else {
				$('#overlay').fadeIn();
			}
//			if( $('#image_img').length ) {
//				$('#image_img').attr('src','/pictures/'+thumbnails[thumbnail.data('picture').i]['pid']+'.jpg')
//			} else {
/*			if( !$('#section_image').length ) {
				$('#panel').append('<div id="section_image"><img id="section_image_img" /></div>');
				var section_image = $('#section_image');
				var section_image_img = $('#section_image_img');
				$('#section_map').hide();
			}
*/
//			section_image_img.attr('src', preload.src);

//			$('#section_image').css('width',$('#section_map').width()).css('height',$('#section_map').height());
//			$('#section_image_img').css('height',$('#section_map').height());

//			position_picture();


//			image_width    = section_image_img.width();
//			}
		} else {
			previous_picture = floating_picture;
		}
//				create_floating_picture( 0, picture_id, picture.data('location_folder'), picture.data('location'), picture.data('author_folder'), picture.data('author'), picture.data('description') )
//				$('body').append('<div class="floating_picture" id="floating_picture_'+i+'">'+(i>0?'<div class="floating_picture_left"></div>':'')+(i+1<thumbnails_counter?'<div class="floating_picture_right"></div>':'')+'<div class="floating_picture_caption"><div class="caption_overlayy" /><div class="caption_text">'+'<a href="/'+p['lf']+'">'+p['ln']+'</a> <img src="/pic/photo.png" /> <a href="/galeria/'+p['af']+'">'+ p['an'] + '</a>'+(p['lic']==''?'':' Licencja <a href="'+p['liu']+'">'+p['lic']+'</a>')+(p['su']==''?'':' <a href="'+p['su']+'">Źródło</a>')+(admin_on_board?' <span class="button_edit_picture" data-picture_id="'+p['pid']+'">edytuj</span>':'')+'<br />'+p['d']+'</div></div></div>');
		
		$('body').append('<div class="floating_picture" id="floating_picture_'+i+'">'+(i>0?'<div class="floating_picture_left"></div>':'')+(i+1<thumbnails_counter?'<div class="floating_picture_right"></div>':'')+($.browser.msie?'':'<div class="floating_picture_caption_overlay"></div>')+'<div class="floating_picture_caption"><a href="/'+p['lf']+'">'+p['ln']+'</a> <img src="/pic/photo.png" /> <a href="/galeria/'+p['af']+'">'+ p['an'] + '</a>'+(admin_on_board?' <span class="button_edit_picture" data-picture_id="'+p['pid']+'">edytuj</span>':'')+'<br />'+p['d']+(p['lic']==''?'':'<br /><span class="floating_picture_license">Licencja: <a href="'+p['liu']+'">'+p['lic']+'</a>'+(p['su']==''?'':' <a href="'+p['su']+'">Źródło</a>')+'</span>')+'</div></div>');
		floating_picture = $('#floating_picture_'+i);
		floating_picture_caption = floating_picture.find('.floating_picture_caption');
		floating_picture_caption_overlay = floating_picture.find('.floating_picture_caption_overlay');

		if($.browser.msie) {
//					alert($('.floating_picture_caption .caption_overlay').css('background-color'));
			floating_picture_caption.css('background-color','#303030');
		}
		//floating_picture_caption.css('background-color','#303030');
		floating_picture_caption.css({ 'width':preload.width-8 });
		//console.log(floating_picture_caption.height());
		floating_picture_caption.css({ 'top':preload.height-floating_picture_caption.height()-8 });
		floating_picture_caption_overlay.css({ 'top':preload.height-floating_picture_caption.height()-8, 'width':preload.width, 'height':floating_picture_caption.height()+8 });
		//console.log(floating_picture_caption.css('top'));
//				$('#floating_picture img').css({width: thumbnail_width, height: thumbnail_height});
		if( c==0 ) {
//					floating_picture.css({left: p.offset.left, top: p.offset.top, backgroundImage: 'url(' + preload.src + ')', width: thumbnail_width, height: thumbnail_height});
			floating_picture.css({left: p.offset.left, top: (p.offset.top-$('#section_location').scrollTop()), backgroundImage: 'url(' + preload.src + ')', width: p.tw, height: p.th});
			floating_picture.show();
//					exit;
//floating_picture_caption_overlay.css( 'height', floating_picture_caption.css('height') );
//alert(floating_picture.height());
			floating_picture.animate(	{
											opacity: 1,
											top: ($(window).scrollTop()+($(window).height()-preload.height)/2),
											left: ($(window).width()-preload.width)/2, 
											width: preload.width,
											height: preload.height
										},
										'slow', 
										function() {
							//				floating_picture_caption.css( 'top', floating_picture.height() );
											floating_picture_caption.fadeIn();
											floating_picture_caption_overlay.fadeIn();
//debugger
//alert( floating_picture_caption.css('height') );
											//$('.caption_text').css('color','#ff00ff');
											//floating_picture_caption.show();
											//floating_picture_caption.data( 'height', floating_picture_caption.height() );
											floating_picture.mouseleave( function() {
												//console.log(c+' mouseleave');
												floating_picture_caption.fadeOut('fast');
												floating_picture_caption_overlay.fadeOut('fast');
								//				floating_picture_caption.animate( { height: 0 } );
											});
											floating_picture.mouseenter( function() {
												floating_picture_caption.fadeIn('fast');
												floating_picture_caption_overlay.fadeIn('fast');
												//console.log(c+' mouseenter');
								//				floating_picture_caption.animate( { height: floating_picture_caption.data( 'height' ) } );
											});
										}
									);
		} else {
			floating_picture.css({	left: ($(window).width()-preload.width)/2,
									top: ($(window).scrollTop()+($(window).height()-preload.height)/2),
									backgroundImage: 'url(' + preload.src + ')',
									width: preload.width,
									height: preload.height
								});
			previous_picture.animate(	{ opacity: 0 },
										'slow', 
										function() {
											previous_picture.remove();
										}
									);
			floating_picture_caption.show();
			//floating_picture_caption_overlay.css({ 'top':preload.height-34, 'width':preload.width, 'height':floating_picture_caption.height()+8 });
			floating_picture_caption_overlay.show();
			floating_picture.animate(	{ opacity: 1 },
										'slow', 
										function() {
							//				floating_picture_caption.css( 'top', floating_picture.height() );
										//	floating_picture_caption.fadeIn('fast');
											floating_picture.css('cursor','normal');
											// floating_picture_caption.show();
											floating_picture_caption.data( 'height', floating_picture_caption.height() );
											floating_picture.mouseleave( function() {
												floating_picture_caption.fadeOut('fast');
												floating_picture_caption_overlay.fadeOut('fast');
												//console.log(c+' mouseleave');
						//						floating_picture_caption.animate( { height: 0 } );
											});
											floating_picture.mouseenter( function() {
												floating_picture_caption.fadeIn('fast');
												floating_picture_caption_overlay.fadeIn('fast');
												//console.log(c+' mouseenter');
						//						floating_picture_caption.animate( { height: floating_picture_caption.data( 'height' ) } );
											});
										}
									);
		}

		$('#overlay').unbind().click( function() { // alert(p.pid);
			floating_picture.animate({	opacity: 0,
										left: p.offset.left, 
										top: (p.offset.top-$('#section_location').scrollTop()), 
										width: p.tw, 
										height: p.th },
										'slow', 
										function() {
											floating_picture.remove();
										}
									);
//					$('#floating_picture').fadeOut( 'fast', function() { $('#floating_picture').remove(); } );
			$('#overlay').fadeOut( 'fast', function() { $('#overlay').remove(); } );
		});

		floating_picture.find('.floating_picture_left').click( function() {
			if( i>0 ) {
				floating_picture.unbind();
				$(this).remove();
				floating_picture.find('.floating_picture_right').remove();
				floating_picture.css('cursor','wait');
				create_floating_picture( c+1, i-1 );
			}
		});
		floating_picture.find('.floating_picture_right').click( function() {
			if( i+1<thumbnails_counter ) {
//						console.log(c+' przed unbind');
				floating_picture.unbind();
				$(this).remove();
				floating_picture.find('.floating_picture_left').remove();
				floating_picture.css('cursor','wait');
//						console.log(c+' po unbind');
				create_floating_picture( c+1, i+1 );
			}
		});
/*
		$('body').append('<div id="overlay"></div><div id="floating_picture"><img src="'+preload.src+'" /><div id="caption">Test test test</div></div>');
		$('#floating_picture img').css({width: thumbnail_width, height: thumbnail_height});
		$('#floating_picture').css({left: offset.left, top: offset.top});
		$('#floating_picture').animate({ opacity: 1,
										 top: ($(window).scrollTop()+($(window).height()-preload.height)/2),
										 left: ($(window).width()-preload.width)/2 }, 'slow');
		$('#floating_picture img').animate({ width: preload.width,
										     height: preload.height }, 'slow');
*/

//				$('#floating_picture').css({top: ($(window).scrollTop()+($(window).height()-$('#floating_picture').height())/2),
//											left:($(window).width()-$('#floating_picture').width())/2});
		floating_picture.find('.button_edit_picture').click(function() {
			floating_picture.remove();
			load_floating_window('/picture_editor/PICTURE/'+$(this).data('picture_id'), picture_editor_initialization);
		});				
	};

	preload.src = '/pictures/'+p['pid']+'.jpg';

	if( i==thumbnails_preloaded_last && i+1<thumbnails_counter ) {
		thumbnails_preloaded_last = i+1;
		var preload_next = new Image();
		preload_next.src = '/pictures/'+thumbnails[i+1]['pid']+'.jpg';
	}
	if( i==thumbnails_preloaded_first && i>0 ) {
		thumbnails_preloaded_first = i-1;
		var preload_prev = new Image();
		preload_prev.src = '/pictures/'+thumbnails[i-1]['pid']+'.jpg';
	}

//			$('body').append('<div class="floating_picture" id="floating_picture_'+id+'"><div id="floating_picture_caption"><div id="caption_overlay" /><div id="caption_text"><a href="'+location_folder+'">'+location_name+'</a> <img src="/pic/photo.png" /> <a href="/galeria'+author_folder+'">'+ author_name + '</a>'+(admin_on_board?' <span id="button_edit_picture" data-picture_id="'+picture_id+'">edytuj</span>':'')+'<br />'+description+'</div></div></div>');

}

function initialize_section_admin()
{
	if(admin_on_board) {
		$("#section_admin_button_add_picture").click(function() {
			load_floating_window('/picture_editor/LOCATION/'+$(this).data('location_id'), picture_editor_initialization);
		});

		$("#section_admin_button_add_place").click(function() {
			load_floating_window('/location_editor/COUNTRY/'+$(this).data('country_id'), location_editor_initialization);
		});

		$("#section_admin_button_edit_place").click(function() {
			load_floating_window('/location_editor/LOCATION/'+$(this).data('location_id'), location_editor_initialization);
		});

		$("#section_admin_button_add_note").click(function() {
			load_floating_window('/note_editor/LOCATION/'+$(this).data('location_id'), note_editor_initialization);
		});

		$("div.one_review").dblclick(function() {
			edit_review( $(this) );
		});

		$("#section_location div.note").dblclick(function() {
			load_floating_window('/note_editor/NOTE/'+$(this).data('note_id'), note_editor_initialization);
		});

		$("#section_notes div.one_comment").dblclick(function() {
			load_comment_editor( 'COMMENT', $(this).attr("id").substring(8) );
		});
	}
}

function initialize_section_reviews()
{
	$('#section_reviews div.section_reviews_button_edit').click(function() {
		edit_review( $(this).parent() );
	});

	$('#section_reviews #field_body_fake').focus(function() {
		$(this).hide();
		create_review_editor( $('#section_reviews h2'), '', ($.cookie('author')=== null?'':$.cookie('author')), '', '', $(this).data('location_id') );
	});
}

function initialize_section_gallery()
{
	thumbnails_counter = 0;

	$('#section_gallery .picture_thumbnail').each(function() {
		thumbnails[$(this).data('picture').i] = $(this).data('picture');
		thumbnails[$(this).data('picture').i].offset = $(this).offset();
		thumbnails_counter++;
	});

//		var current_thumbnail = 0;

	$('#section_gallery a').click(function(e) { return false; });

	$('#section_gallery .picture_thumbnail').click(function(e) {
		var thumbnail = $(this);

//			alert(thumbnail.data('picture').i);
//			var picture_id = picture.data('picture_id');
//			current_thumbnail = 0;
//			while( current_thumbnail<thumbnails_count && thumbnails[current_thumbnail]!=picture_id ) {
//				current_thumbnail++;
//			}
		var offset = thumbnail.offset();
		$('body').append('<div id="loading_indicator"><img src="/pic/ajax-loader.gif" /></div>');

//			$('body').append('<div class="floating_picture" id="floating_picture_'+picture_window+'"><div id="floating_picture_caption"><div id="caption_overlay" /><div id="caption_text">'+'<a href="'+picture.attr('data-location_folder')+'">'+picture.attr('data-location')+'</a> <img src="/pic/photo.png" /> <a href="/galeria'+picture.attr('data-author_folder')+'">'+ picture.attr('data-author') + '</a>'+(admin_on_board?' <span id="button_edit_picture" data-picture_id="'+picture_id+'">edytuj</span>':'')+'<br />'+picture.attr('data-description')+'</div></div></div>');

		var thumbnail_width = thumbnail.width() + 8;
		var thumbnail_height = thumbnail.height() + 8;

		$('#loading_indicator').css({left: offset.left, top: offset.top, width: thumbnail_width, height: thumbnail_height});
		$('#loading_indicator img').css({left: thumbnail_width/2-15, top: thumbnail_height/2-15});

//			$('#loading_indicator').css('left',($(window).width()-$('#loading_indicator').width())/2)
//								   .css('top',($(window).height()-$('#loading_indicator').height())/2);
		$('#loading_indicator').fadeIn();

		create_floating_picture( 0, parseInt(thumbnail.data('picture').i) )
	});
/*
	if( pictures ) {
		var tr1 = '';
		var tr2 = '';
		var td = '';
		var pictures_loaded = 0;
		var picture;
		var columns_total = 0;			
		var first_visible_column = 1;
		var max = gallery_mode=='COUNTRY'?12:pictures_total;
		for( var i=1; i<=max; i++ ) {
			pictures_loaded = i;
			picture = pictures[i];
			td = td + '<td><img class="thumbnail" src="/thumbnails/'+picture.id+'.jpg" alt="'+picture.name+'" attr-picture_index="'+i+'" title="'+picture.name+'" /></td>';
			if( i%6 == 0 ) {
				$('#gallery_table tbody').append('<tr>'+td+'</tr>');
				td = '';
			}
		}
		if( td ) {
			$('#gallery_table tbody').append('<tr>'+td+'</tr>');
		}
		columns_total = Math.min(pictures_loaded,6);
		$('#gallery_button_previous').click( function() {
			if( first_visible_column>1 ) {
				var delta = Math.min(first_visible_column-1, 6);
//					alert(delta+' - '+first_visible_column);
				if( delta>0 ) {
					$('#gallery_table').animate({'left': '+='+(delta*124)+'px'}, 1500);
					first_visible_column = first_visible_column - delta;
				}
			}
		});

		$('#gallery_button_next').click( function() {
//debugger
			if( first_visible_column==columns_total-6 && pictures_loaded<pictures_total ) {
				tr1 = '';
				tr2 = '';
				td = '';
				max = Math.min(pictures_total,pictures_loaded+12)
				for( var i=pictures_loaded+1; i<=max; i++ ) {
					pictures_loaded = i;
					picture = pictures[i];
					td = '<td><img class="thumbnail" src="/thumbnails/'+picture.id+'.jpg" alt="'+picture.name+'" attr-picture_index="'+i+'" /></td>';
					if( i%2==1 ) {
						tr1 = tr1 + td;
						columns_total++;
					} else {
						tr2 = tr2 + td;
					}
				}
				$('#gallery_table tr:eq(0)').append(tr1);
				$('#gallery_table tr:eq(1)').append(tr2);
			}
			var delta = Math.min(columns_total-first_visible_column-6+1, 6);
//				alert(delta+' - '+columns_total+' - '+first_visible_column);
			if( delta>0 ) {
				$('#gallery_table').animate({'left': '-='+(delta*124)+'px'}, 1500);
				first_visible_column = first_visible_column + delta;
			}
		});
	}
	*/
	
}

var map;


function coordinates_to_string(g,x,y)
{
	return Math.floor(Math.abs(g))+'°'+Math.round((Math.abs(g)-Math.floor(Math.abs(g)))*60)+"'"+(g>0?x:y);
}

function edit_review ( review )
{
	review.hide();
	create_review_editor( review, review.data('body'), review.data('author'), review.data('evaluation'), review.data('review_id'), '' );
}
		
function map_is_loaded()
{ //alert(9);
//	if (GBrowserIsCompatible()) { 
		google_map = new GMap2(document.getElementById('location_editor_google_map'));
		google_map.addControl(new GSmallMapControl());
		google_map.addControl(new GMapTypeControl());
		google_map.enableScrollWheelZoom();
		if( $('#location_editor #field_latitude').val()==0 && $('#location_editor #field_longitude').val()==0 ) {
			google_map.setCenter( new GLatLng( 27.1667, 78.0167 ), 3);
		} else {
			google_map.setCenter( new GLatLng( parseFloat($('#location_editor #field_latitude').val()), parseFloat($('#location_editor #field_longitude').val()) ), 10);
		}
//		alert(google_map.getSize());
//	}
}
/*
function refresh_google_map_mini()
{
	z = parseInt($('#location_editor #field_zoom').val());
	if( z>0 && z<=18) {
		var now = new Date();
		s = 'http://maps.google.com/staticmap?center='+$('#location_editor #field_latitude').val()+','+$('#location_editor #field_longitude').val()+'&zoom='+$('#location_editor #field_zoom').val()+'&size=100x118&key='+google_map_key+'&mandalay='+now.getTime();
		$('#location_editor #google_map_mini').attr('src',s);
	}
}
*/
function location_editor_initialization()
{
	$('#location_editor #field_name').internal_label('Nazwa');
	$('#location_editor #field_dopelniacz').internal_label('Dopełniacz (kogo? czego?)');
	$('#location_editor #field_miejscownik').internal_label('Miejscownik (komu? czemu?)');
	$('#location_editor #field_folder').internal_label('Folder');
	$('#location_editor #field_keywords').internal_label('Słowa kluczowe');
	$('#location_editor #field_alternates').internal_label('Alternatywne nazwy');
	$('#location_editor #field_description').internal_label('Opis');
	$('#location_editor #field_coordinates').internal_label('Współrzędne');
	$('#location_editor #field_przyimek').internal_label('Przyimek');

	$("#location_editor #field_coordinates").change(function() {
		refresh_google_map_mini();
	});

	$('#location_editor #field_coordinates').keyup(function() {
//		alert('change '+$("#location_editor #field_coordinates").val());
		var re = new RegExp( '^([0-9]{1,3})[^0-9]([0-9]{1,3})([^0-9]([0-9]{1,3}))?[^0-9]?([NnSs])[^0-9]?([0-9]{1,3})[^0-9]([0-9]{1,3})([^0-9]([0-9]{1,3}))?[^0-9]?([WwEe])$' );
		var m = re.exec( $("#location_editor #field_coordinates").val() );
		if (m == null) {
//			alert("No match");
			$("#location_editor #field_coordinates").addClass('error');
		} else {
			var s = "Match at position " + m.index + ":\n";
			for (i = 0; i < m.length; i++) {
				s = s + i+ ' ' + m[i] + "\n";
			}
			$("#location_editor #field_coordinates").removeClass('error');
			
//			latitude = (parseInt(m[1])+parseFloat(m[2]/60))*(m[5]=='S' || m[5]=='s'?-1:1);
			latitude = (parseInt(m[1])+parseFloat(m[2]/60)+parseFloat(m[4]>0?m[4]/360:0))*(m[5]=='S' || m[5]=='s'?-1:1);
			longitude = (parseInt(m[6])+parseFloat(m[7]/60)+parseFloat(m[9]>0?m[9]/360:0))*(m[10]=='W' || m[10]=='w'?-1:1);

			$('#location_editor #field_latitude').val(latitude);
			$('#location_editor #field_longitude').val(longitude);
			
			google_map.setCenter( new GLatLng( latitude, longitude) );
		}

	});

	$("#location_editor #section_thumbnails img").click(function() {
		$("#location_editor #field_thumbnail_id").val( $(this).attr("attr-picture_id") );
		$("#location_editor #section_thumbnails img.selected").removeClass("selected");
		$(this).addClass("selected");
	});

	$("#location_editor #button_set_coordinates").click(function() {
		var center = google_map.getCenter();
		$('#location_editor #field_latitude').val(center.lat());
		$('#location_editor #field_longitude').val(center.lng());
		$('#location_editor #field_coordinates').val(coordinates_to_string(center.lat(),'N','S')+' '+coordinates_to_string(center.lng(),'E','W'));
		refresh_google_map_mini();
	});

	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = "http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAlD798re0kTZbjdflpeoVTxRGqqh-D6mRIPdDfLAY22rxga22FxS7L8HbY1ESlQCl60SV5tHE6te__A&async=2&callback=map_is_loaded";
	document.getElementsByTagName("head")[0].appendChild(script);

}

function contact_initialization()
{
	$("#section_contact #button_cancel").click(function() {
		$.fn.dialog_hide();
	});

	$('#section_contact #field_body').internal_label('Twoja wiadomość...');
	$('#section_contact #field_email').internal_label('Twój e-mail...');


	$('#section_contact #button_submit').click(function() {
		if( $('#section_contact #field_body').hasClass('internal_label') ) {
			alert('A co z wiadomością?');
			return false;
		}
		if( $('#section_contact #field_email').hasClass('internal_label') ) {
			$('#section_contact #field_email').val('');
		}
		$.post('/email', { field_body: $('#section_contact #field_body').val(), field_email: $('#section_contact #field_email').val() }, function(data) {
			alert(data);
		});
		$.fn.dialog_hide();
	});
	

}

function picture_editor_initialization()
{
	$('#picture_editor #preview_picture img').upload({
		name: 'file',
		method: 'post',
		enctype: 'multipart/form-data',
		action: '/picture_upload/PICTURE',
		onSubmit: function() {
			$('#picture_editor #preview_picture .dimensions').text('Uploading...');
		},
		onComplete: function(data) {
			var now = new Date();
			$('#picture_editor #preview_picture img').attr('src','/thumbnail/temp/100?'+now.getTime());
			$('#picture_editor #preview_picture .dimensions').html(data);
			$('#picture_editor #field_picture_uploaded').val('Y');
		}
	});
	$('#picture_editor #preview_thumbnail img').upload({
		name: 'file',
		method: 'post',
		enctype: 'multipart/form-data',
		action: '/picture_upload/THUMBNAIL',
		onSubmit: function() {
			$('#picture_editor #preview_thumbnail .dimensions').text('Uploading...');
		},
		onComplete: function(data) {
			var now = new Date();
			$('#picture_editor #preview_thumbnail img').attr('src','/thumbnails/temp.jpg?'+now.getTime());
			$('#picture_editor #preview_thumbnail .dimensions').html(data);
			$('#picture_editor #field_thumbnail_uploaded').val('Y');
		}
	});
}

function note_editor_initialization()
{
}

function distances_editor_initialization()
{
	$('#distances_editor #field_author').internal_label('Twoje imię / pseudonim');
	$('#distances_editor #field_email').internal_label('Email');

	$('#distances_editor_form select').change(function() {
		if( $(this).val()=='0' ) {
			$(this).removeClass('modified');
		} else {
			$(this).addClass('modified');
		};
	});

	$('#distances_editor_form').submit(function() {
		empty_author    = $('#distances_editor_form #field_author').hasClass('internal_label');
		empty_email     = $('#distances_editor_form #field_email').hasClass('internal_label');
		empty_delete	= !($('#distances_editor_form #field_delete').attr("checked")==true);

		if(empty_delete && (empty_body || empty_author)) {
			return false;
		} else {
			$('#distances_editor_form .internal_label').val('');
			return true;
		}
	});
}

function comment_editor_initialization()
{
	$('#comment_form_body').internal_label('Zapraszam do komentowania');
	$('#comment_form_author').internal_label('Twoje imię / pseudonim');

	$("#comment_editor_form").submit(function() {
		body_empty       = $('#comment_form_body').is('.internal_label');
		author_empty     = $('#comment_form_author').is('.internal_label');
		comment_id_empty = ($('#comment_form_comment_id').val() == '');
		
//		alert(body_empty + '/' + author_empty + '/' + review_id_empty);
		
		if(comment_id_empty && (body_empty || author_empty)) {
			return false;
		} else if ((body_empty && !author_empty) || (!body_empty && author_empty)) {
			return false;
		}
		if(body_empty) {
			$('#comment_form_body').val('');
		}
		if(author_empty) {
			$('#comment_form_author').val('');
		}
		return true;
	});
}

function load_floating_window(url, initialize, transparent)
{	
	console.log('load_floating_window',url);

	if(transparent) {
		$('body').append('<div id="overlay"></div><div id="floating_window"><div id="container"></div></div><img id="loading_indicator" src="/pic/ajax-loader.gif" />');
	} else {
		$('body').append('<div id="overlay"></div><div id="floating_window"><img id="loading_indicator" src="/pic/ajax-loader.gif" />');
	}

	if($.browser.msie) {
		$('#overlay').show();
		$('#loading_indicator').show();
	} else {
		$('#overlay').fadeIn('slow');
		$('#loading_indicator').fadeIn('slow');
	}

	$('#loading_indicator').css('left',($(window).width()-$('#loading_indicator').width())/2);
	$('#loading_indicator').css('top',($(window).height()-$('#loading_indicator').height())/2);

//	$('#floating_window').css('left',($(window).width()-$('#floating_window').width())/2);
//	$('#floating_window').css('top',($(window).height()-$('#floating_window').height())/2);

	$.post( url, {}, function(data)
		{
			$('#loading_indicator').fadeOut('fast');
			$('#floating_window').html( data );
			if($.browser.msie) {
				$('#floating_window').show();
			} else {
				$('#floating_window').fadeIn('slow');
			}
			$('#floating_window').css('left',($(window).width()-$('#floating_window').width())/2);
			$('#floating_window').css('top',($(window).height()-$('#floating_window').height())/2);
			$("#floating_window #button_cancel").click(function() { $.fn.dialog_hide(); });
			initialize();
		}
	);
}

function show_floating_message( initialize )
{
	$('body').append('<div id="overlay"></div><table id="floating_window"><tbody><tr><td id="top_left"></td><td id="top_middle"></td><td id="top_right"></td></tr><tr><td id="middle_left"></td><td id="middle_middle"><div id="container"></div></td><td id="middle_right"></td></tr><tr><td id="bottom_left"></td><td id="bottom_middle"></td><td id="bottom_right"></td></tr></tbody></table><img id="loading_indicator" src="/pic/ajax-loader.gif" />');

	if($.browser.msie) {
		$('#overlay').show();
	} else {
		$('#overlay').fadeIn('slow');
	}

	$('#section_message').appendTo('#floating_window #container');

	if($.browser.msie) {
		$('#floating_window').show();
	} else {
		$('#floating_window').fadeIn('slow');
	}
//alert($(window).height()+' '+$(window).innerHeight( ));
	$('#floating_window').css('left',($(window).width()-$('#floating_window').width())/2);
	$('#floating_window').css('top',($(window).height()-$('#floating_window').height())/2);
	$("#floating_window #button_cancel").click(function() { $.fn.dialog_hide(); });
	$("#floating_window #button_ok").click(function() { $.fn.dialog_hide(); });
	
	if(initialize) {
		initialize();
	}
}

function hide_floating_window()
{
	if($.browser.msie) {
		$('#overlay').show();
	} else {
		$('#overlay').fadeOut('slow');
	}
}

function load_comment_editor( mode, id )
{
	var url = '/comment_editor/'+mode+'/'+id;
	load_floating_window(url, comment_editor_initialization);
}

function load_review_editor( mode, object_id, evaluation_id)
{
	var url = '/review_editor/'+mode+'/'+object_id+'/'+evaluation_id;
	load_floating_window(url, review_editor_initialization);
}

function initialize() {
  var myLatlng = new google.maps.LatLng(-34.397, 150.644);
  var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("section_map_google"), myOptions);
}

function show_map_google() {
	var thumbmap = $('#thumbmap');
	location_latitude = parseFloat( thumbmap.data('location_latitude') );
	location_longitude = parseFloat( thumbmap.data('location_longitude') );
	location_zoom = parseFloat( thumbmap.data('location_zoom') );

	$('#section_map').append('<div id="section_map_google"></div>');//.css({width: '96%', height: '96%', left: '2%', top: '2%' });
	var script = document.createElement("script");
	script.type = "text/javascript";
	//script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize_google_map";
	script.src = "http://maps.googleapis.com/maps/api/js?key="+google_map_key+"&sensor=false&callback=initialize_google_map";
	document.body.appendChild(script);
}

function show_map_bing() {
	location_latitude = 90-(paths[current_country].top+(paths[current_country].bottom-paths[current_country].top)/2)/100;
	location_longitude = (paths[current_country].left+(paths[current_country].right-paths[current_country].left)/2)/100;
	location_zoom = 5;//parseFloat( thumbmap.data('location_zoom') );

	$('#section_map').append('<iframe id="floating_map_microsoft" class="map_external" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://dev.virtualearth.net/embeddedMap/v1/ajax/road?zoomLevel='+location_zoom+'&center='+location_latitude+'_'+location_longitude+'" />');// .css({width: '96%', height: '96%', left: '2%', top: '2%' });
/*
	if( $('#floating_map_microsoft').length ) {

		$('#floating_map').css({width: '96%', height: '96%', left: '2%', top: '2%' });
		$('#floating_map_microsoft').show();

	} else {

		$('#floating_map').append('<iframe id="floating_map_microsoft" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://dev.virtualearth.net/embeddedMap/v1/ajax/road?zoomLevel='+location_zoom+'&center='+location_latitude+'_'+location_longitude+'" />').css({width: '96%', height: '96%', left: '2%', top: '2%' });

	}
*/
}

function show_map_yahoo() {
	location_latitude = 90-(paths[current_country].top+(paths[current_country].bottom-paths[current_country].top)/2)/100;
	location_longitude = (paths[current_country].left+(paths[current_country].right-paths[current_country].left)/2)/100;
	location_zoom = 5;//parseFloat( thumbmap.data('location_zoom') );

	$('#section_map').append('<iframe id="floating_map_yahoo" class="map_external" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="/yahoo/'+String(location_latitude).replace('.',',')+'/'+String(location_longitude).replace('.',',')+'/'+location_zoom+'" />'); //.css({width: '96%', height: '96%', left: '2%', top: '2%' });

/*
	if( $('#floating_map_yahoo').length ) {

		$('#floating_map').css({width: '96%', height: '96%', left: '2%', top: '2%' });
		$('#floating_map_yahoo').show();

	} else {
// <html><head><script type="text/javascript" src="http://api.maps.yahoo.com/ajaxymap?v=3.8&appid=YD-eQRpTl0_JX2E95l_xAFs5UwZUlNQhhn7lj1H"></script></head><body><div id="map" style="width:100%;height:100%;"></div><script type="text/javascript">var map = new YMap(document.getElementById("map"));map.addTypeControl();map.setMapType(YAHOO_MAP_REG);map.drawZoomAndCenter("San Francisco", 3);</script></body></html>
		$('#floating_map').append('<iframe id="floating_map_yahoo" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="/yahoo/'+String(location_latitude).replace('.',',')+'/'+String(location_longitude).replace('.',',')+'/'+location_zoom+'" />').css({width: '96%', height: '96%', left: '2%', top: '2%' });

	}
*/
}

function show_floating_map() {
//			alert(preload.width);
	$('#loading_indicator').remove();
	$('#section_map_container').css({backgroundImage: "url(" + preload.src + ")", width: preload.width, height: preload.height});
	$('#section_map_container #caption').css('width', preload.width-6);
//			alert(preload.width);
	$('#floating_map').css('top',$(window).scrollTop()+($(window).height()-$('#floating_map').height())/2)
					  .css('left',($(window).width()-$('#floating_map').width())/2);
//			$('#floating_picture').css('top',($(window).height()-$('#floating_window').height())/2);
}

$(document).ready(function() {

	$('#nav_main_menu').on('click',function(e) {
		//e.stopPropagation();
		//console.log(e.target.tagName, $(e.target).children('a'));
		if(e.target.tagName == 'LI') {
			//e.stopPropagation();
			//e.preventDefault();
			location.href = $(e.target).children('a').attr('href');
			//console.log('inside', e.target, $(e.target).children('a'));
			//$(e.target).children('a').click();
		} else {
			console.log('out');
		}
		//$(this).children('a').click();
		//console.log($(this).children('a');
		//console.log(e.target.tagName);
	});

/*
	$("#box_review_request td").click(function() {
		load_floating_window( '/review_editor/'+$(this).attr('attr-mode')+'/'+$(this).attr('attr-object_id')+'/'+$(this).attr('attr-evaluation'), review_editor_initialization);
	});

	$("#box_landmarks span.one_landmark").click(function() {
		load_floating_window('/floating_landmark/'+$(this).attr('attr-landmark_id'), floating_landmark_initialization, true);
	});
*/
	$('footer .button_contact').click(function() {
		load_floating_window('/contact', contact_initialization, true);
	});

	$("#box_distances #button_add_distances").click(function() {
		load_floating_window('/distances_editor/'+$(this).attr('attr-location_id'), distances_editor_initialization);
	});
/*
	$("#section_notes span.add_comment").click(function() {
		load_comment_editor( 'NOTE', $(this).parent().attr('id').substring(5) );
	});

	$("#section_notes div.one_comment span.comment_edit_button").click(function() {
		load_comment_editor( 'COMMENT', $(this).parent().parent().attr('id').substring(8) );
	});
*/
//	$('#section_reviews #button_new_review').css( 'left', $('#section_reviews h2').width() );

/*
	$('#search_box').focus(function() {
		t = $(this);
		t.addClass('focused');
		if( t.val()=='Szukaj' ) t.val('');
	});

	$('#search_box').blur(function() {
		$(this).removeClass('focused');
		t.val('Szukaj');
	});

	$('#search_box').autocomplete('/autocomplete', {mustMatch:0, autoFill:false, selectFirst:true, minChars:2, formatItem:autocompleteFormatItem, onItemSelect:autocompleteSelected, matchContains:1, cacheLength:10});	
*/

//	$('#section_review_request #review_contentx').blur( function() {
//		$(this).val('Twoja opinia...').animate({height: 27+'px'}, 500);
//		$('#section_review_request #evaluations').slideUp();
//		$('#section_review_request').css({'background-color':'transparent','border-color':'transparent'});
//	});


	if( $('#section_map').length ) {
//		show_google_map();
		map = new Map();

//		show_mandalay_map();
	}

/*
	$('#button_map_google').click(function(e) {
//		alert(9);
//		e.stopPropagation();
//		$('#section_map_buttons .current').removeClass('current');
//		$(this).addClass('current');
//		$('#floating_map_mandalay').hide();
//		$('#floating_map_yahoo').hide();
		show_map_google();
	});
*/

//	if( $('#section_navigation').length ) {
//		var n = $('#section_navigation');
//		var d = $('#container').offset().left - n.width() - 20 + 300;
//		n.hide().css('left',d).fadeIn('slow');
//		n.animate({left: d+'px'}, 1500);
//		alert($('#container').offset().left);
//	}
//		debugger;


	if( $('#section_gallery').length )
	{
		initialize_section_gallery();
	}

	if( $('#section_reviews').length )
	{
		initialize_section_reviews();
	}
	
	if( $('#section_admin').length )
	{
		initialize_section_admin();
	}

	if( $('#section_location').length )
	{
		$('#section_location .switch_article_button').click(function() {
			$('#section_location').toggle();
			$('#section_locations').toggle();
		});
	}

	if( $('#section_locations').length )
	{
		$('#section_locations .switch_article_button').click(function() {
			$('#section_location').toggle();
			$('#section_locations').toggle();
		});
		$('.one_location').click(function(e) {
			if( $(this).data('type')=='R' ) {
				window.location = $(this).children('a').attr('href');
			} else {
				e.preventDefault();
				load_location( $(this).data('location_id') );
			}
		});
	}

	var weather_tooltip = $('#weather_table_tooltip');
	var weather_table_offset = $('#weather_table').offset();

	//$('#weather_table').mouseenter(function(e) {
	//	weather_tooltip.fadeIn('fast');
	//});

	$('#weather_table tbody').mouseleave(function(e) {
		weather_tooltip.fadeOut('fast');
	});

	$('#weather_table tbody').on('mousemove',function(e) {
		var st = $('#page_container').scrollTop();
		var x = e.pageX-weather_table_offset.left+20;
		var y = e.pageY-weather_table_offset.top+st-10;
		if(x>930) {
			x = x - 260;
		}
		weather_tooltip.css({top: y, left: x});
	});

	$('#weather_table tbody').on('mouseenter','td, th',function(e) {
		t = $(this);
		//console.log('mouseenter',t.hasClass('table_content'));
		if(t.hasClass('cell_content')) {
			weather_tooltip.html('<table><tbody><tr><th>temperatura minimalna:</th><td><strong>'+t.data('temperature_min')+'</strong> &#8451;</td></tr><tr><th>temperatura maksymalna:</th><td><strong>'+t.data('temperature_max')+'</strong> &#8451;</td></tr><tr><th>opady:</th><td><strong>'+t.data('precipitation')+'</strong> mm</td></tr><tr><th>dni deszczowe:</th><td><strong>'+t.data('wet_days')+'</strong></td></tr></tbody></table>');
			weather_tooltip.fadeIn('fast');
		} else {
			weather_tooltip.fadeOut('fast');
		}
	});
	
/*
	$('#section_search #search_box').focus(function() {
		if($('#section_search #search_box').val()=='Szukaj...') $('#section_search #search_box').val('');
		return true;
	});

	$('#section_search #search_box').blur( function() { $('#section_search #search_box').val('Szukaj...'); } );
*/	

/*
	if( $('#section_message').length ) {
		show_floating_message( more_reviews_request_initialization );
	}
*/
/*
	$('#section_map #scroll_up').click(function() {
		offset = $('#section_map #list_of_places #list').scrollTop() - $('#section_map #list_of_places #list').height() + 18;
		$('#section_map #list_of_places #list').animate({scrollTop: offset}, 500);
	});

	$('#section_map #scroll_down').click(function() {
//		$('#section_map #list_of_places').scrollTop($('#section_map #list_of_places').scrollTop()+$('#section_map #list_of_places').height()-13);
		offset = $('#section_map #list_of_places #list').scrollTop() + $('#section_map #list_of_places #list').height() - 18;
		$('#section_map #list_of_places #list').animate({scrollTop: offset}, 500);
	});
*/
//	var nav_active_region;

	$('nav li.nav_main_menu_item').mouseenter( function() {
		var submenu = $(this).find('ul');
		if( submenu.length ) {
//			nav_active_region = n;
			var p = $(this).position();
			//console.log(p.left);
			submenu.css('left', p.left).css('min-width',$(this).width()+20).show();
			$(this).mouseleave( function() {
				$('nav ul.nav_sub_menu').hide();
			});
		}
	});

	$('#map_switch_buttons').hover(
		function(e) {
			$('#map_switch_buttons_dropdown').show();
		},
		function() {
			$('#map_switch_buttons_dropdown').hide();
		}
	);

	$('#map_switch_buttons_dropdown').click(function(e) {
		e.stopPropagation();
		$('#map_canvas').hide();
		$('#map_zoom_in').hide();
		$('#map_zoom_out').hide();
		$('#map_switch_buttons').hide();
		switch(e.target.id) {
			case 'button_map_google':
				show_map_google();
				break;
			case 'button_map_yahoo':
				show_map_yahoo();
				break;
			case 'button_map_bing':
				show_map_bing();
				break;
		}
	})
/*	$('#button_map_yahoo').click(function(e) {
		e.stopPropagation();
		show_map_yahoo();
	});

	$('#button_map_bing').click(function(e) {
		e.stopPropagation();
		show_map_bing();
	});

	$('#button_map_google').click(function(e) {
		e.stopPropagation();
		show_map_google();
	});
*/

});


