var url = null;
var _data;

function isIe() { return $("body").hasClass("IE"); }

function fitPageBody() {
	var height = $(window).height()-50;
	var width = $(window).width()-50;
	
	if(width<800) {
		var rodsize = ((width - 480) / 2);
		if(rodsize<0)
			rodsize=0;
		if(rodsize>200)
			rodsize=200;
		$(".rod-panel").width(rodsize);
	}
	
	if(height < 750) 
		$("#page-body").css({'height':'750'});
	else
		$("#page-body").css({'height':height});
}

function animate_and_remove(slide) {	
	$(slide).addClass('wobble');
	window.setTimeout(function() {
		$(slide).remove();
	}, (isIe() ? 0 : 4000));
}

function getData(label) {
	return _data[label];
}

function change_my_url(url) {
	try {
		var stateObj = { foo: "bar" };
		if(history.pushState)
			history.pushState(stateObj, "page 2", url);
	} catch(e) {}
}

function switch_slides(response,url) {
	var slide = $(".slide");
	slide.css({'z-Index':200});
	
	$("#slides-container").prepend(response);		
	change_my_url(url);		
	animate_and_remove(slide);		
}

function load_label(label) {	
	$.get(document.location.href, {
		'_X' : true,
		'cmd' : 'load_by_label',
		'label' : label,
		'lang' : getData('lang')
	}, function(response) {
		switch_slides(response, document.location.href);
	});
}

function load_page_slide(t_url) {	
	$.get(t_url, {
		'_X' : true,
		'cmd' : 'get_slide'
	}, function(response) {
		switch_slides(response, t_url);		
	});
}

function load_random_slide(url) {	
	$.get(document.location.href, {
		'_X' : true,
		'cmd' : 'get_random_slide',	
		'clicks' : getData('clicks'),
		'referer' : getData('url'),		
		'lang' : getData('lang')		
	}, function(response) {
		switch_slides(response, url);				
	});
}

$(function() {
	fitPageBody();			
	$("#lang-switch a").click(function() {
		if (typeof urlUpdate != 'undefined') {
			var lang = $(this).attr('data-lang');
			var url = urlUpdate[lang];
			if (typeof url != 'undefined') {
				document.location.href = url;
				return false;
			}
		}
	});

	$(window).resize(function() {
		fitPageBody();
	});
	
	$(".cal-link").live('click', function() {			
		load_page_slide($(this).attr('href'));
		return false;
	});
	
	$(".next-page").live('click', function() {		
		load_random_slide();
		return false;
	});
	
	$("#slides-container a").live('click', function() {
		if($(this).hasClass('nos'))
			return true;
			
		var t_url = $(this).attr('href');
		if(!$(this).hasClass('direct-link')) {
			load_page_slide(t_url);
			return false;	
		}		
	});
	
	$("#spine-flag-img").click(function() {
		load_label('fete-du-vacherin');
		return false;
	});	
});
