function evaluateScroll(hash) {
	$(hash.w).height('auto');	
	if (hash.w.height()+47 > $(window).height()) {
		$(hash.w).height($(window).height()-60).css('overflow', 'auto');
	}
}

function bindModalEvents(hash) {
	hash.w.jqmAddClose($('.jqmClose',hash.w));
	
	$('#thumbnail img', hash.w).click(function() {
		oldPath = $('#firstPicture', hash.w).attr('src');
		newPath = $(this).attr('src');
		
		$(this).attr('src', oldPath);
		
		$('#firstPicture', hash.w).fadeOut(function() {
			$(this).attr('src', newPath);
			$(this).fadeIn(function() {
				evaluateScroll(hash);							
			});
		});
	});
	
	$('img:last', hash.w).load(function() {
		evaluateScroll(hash);
	});
	
	$('.interested', hash.w).click(function() {
		hash.w.empty().append('<div id="loading"></div>').show();
		hash.w.load('objectRequest.ajx.php?source='+source+'&section='+section+'&page='+page+'&id='+hash.t.id.substr(1), function() {
			bindModalEvents(hash);
		});
	});
	
	$('.print', hash.w).click(function() {
		window.print();
	});
}

$(function() {
	$('body').prepend('<div class="jqmWindow" id="modal"></div>');
	
	$('#modal').jqm({
		modal: false,
		onShow: function(hash) {
			hash.w.empty().append('<div id="loading"></div>').show();
			
			//Gmaps
			if (hash.t.href) {
				GUnload();
				$.jmap.searchAddress({ address: $(hash.t).attr('longdesc') }, function(options, point) {
					$('#loading').addClass('objectModal').css('height', '500px').jmap('init', 
						{
							language: "fr",
							mapCenter: [point.y,point.x],
							mapZoom: 15,
							mapControlSize: 'large',
							mapEnableType: true,
							mapEnableOverview: true,
							mapEnableScrollZoom: true,
							mapEnableGoogleBar: false,
							mapShowjMapIcon: false
						}, 
						function(el, options) {
							$(el).jmap('addMarker', { pointLatLng: [point.y,point.x], pointHTML: '<h3>'+$(hash.t).attr('longdesc')+'</h3>' });
						}
					);
					hash.w.append('<div id="buttons" class="objectModal" style="margin-top: 15px"><input type="button" name="button" value="-> Retour à la liste" class="button jqmClose" /></div>');
					bindModalEvents(hash);
				});
				
			//Detail	
			} else {
				hash.w.load('objectDetail.ajx.php?source='+source+'&section='+section+'&page='+page+'&id='+hash.t.id.substr(1), function() {
					bindModalEvents(hash);
				});
				
			}
		}
	});
	
	$('#sortForm select').change(function() {
		$('#sortForm').submit();
	});
});
