var nbrInstance = 0;
jQuery(function(){
//	return ;
	var list = jQuery('#list');
	
	if (typeof(ImageBrowser)!='undefined')
		jQuery('<a href="javascript:" class="modifier">modifier</a>').prependTo(jQuery('.item', list));

	jQuery('.item').click(function() {
		var parent = jQuery(this);
		if (!jQuery('.content', parent).is(':visible')) {
			jQuery('.content').fadeOut();
			jQuery('.content:first', parent).fadeIn();
		}
	});
	jQuery('.sidebar #root').addClass('redselect');
	jQuery('.sidebar #root').click(function(){
		toggle_current_theme('');
		jQuery(this).addClass('redselect');
	});
	jQuery('.sidebar .gov').click(function(){
		toggle_current_theme('GM');
		jQuery(this).addClass('redselect');
	});
	jQuery('.sidebar .lib').click(function(){
		toggle_current_theme('LDC');
		jQuery(this).addClass('redselect');
	});
	jQuery('.sidebar .chg').click(function(){
		toggle_current_theme('CL');
		jQuery(this).addClass('redselect');
	});
	jQuery('.sidebar .ets').click(function(){
		toggle_current_theme('EBP');
		jQuery(this).addClass('redselect');
	});
	jQuery('.sidebar .bio').click(function(){
		toggle_current_theme('RN');
		jQuery(this).addClass('redselect');
	});
	


	jQuery('.modifier', list).click(function() {
		/*if (jQuery('.edit').length) {
			alert('Veuillez sauvergarder votre édition en cours avant de modifier un autre évènement');
			return false ;
		}*/
		var curInstance = ++nbrInstance;
		var input_title = null;
		var url = ''+window.location; 
		var item = jQuery(this).parents('.item');
		item.addClass('edit');
		//item[0].id = 'edit';


		item[0].SavePage = function() {
			var input_title = jQuery('.title input', item);
			var input_theme = jQuery('.theme select', item);
			var input_begin = jQuery('.begin input', item);
			var input_end = jQuery('.end input', item);
			var htmlcontent = '';
			var title = input_title.val();

			var oEditor=FCKeditorAPI.GetInstance('tmp42fck'+curInstance);
			if(oEditor) {htmlcontent=CleanFckEditor(oEditor.GetXHTML(false));}
			jQuery('.content:first', item).html(htmlcontent);
			function	convertText() {
//				item.empty();
				jQuery('.title', item).html(title);
				jQuery('.theme', item).html(input_theme.val());
				jQuery('.begin', item).html(input_begin.val());
				jQuery('.end', item).html(input_end.val());
				var date = '';
				if (input_begin.val()&&input_end.val())
					date = 'du '+input_begin.val()+' au '+input_end.val();
				else
					date = !input_begin.val() ? input_begin.val()  : input_end.val();

				jQuery('.begin', item).hide();
				jQuery('.end', item).hide();
				jQuery('.date', item).html(date);
				jQuery('.date', item).show();
				

				jQuery('.content:first', item).show();
				jQuery('.content:last', item).hide();
				//FCKeditorAPI.RemoveInstance('tmp42fck'+curInstance);
			}

			jQuery.ajax({
				url: url+'?json',
				dataType: 'json',
				type: 'post',
				data: 'Save=Observatoire&title='+encodeURIComponent(title)+'&content='+encodeURIComponent(htmlcontent)+'&begin='+encodeURIComponent(input_begin.val())+'&end='+encodeURIComponent(input_end.val())+'&theme='+encodeURIComponent(input_theme.val())+'&id='+jQuery('input[@type=hidden]', item).val(),
				success: function(json) {
					//console.info('success save');
					if (json.response === true) {
						convertText(item);
//						console.info(json.id);
						item.removeClass('edit');
						var y = input_begin.val().substr(2,2);
						var m = input_begin.val().substr(5,2); 
						if (!jQuery('.year-'+y+'.month-'+m, ul).length)
							add_onglet(y, m, true);
						item[0].className = '';	//!< clean all class (for month-XX and year-YY)
						item.addClass('edit');	//!< re-put the item class
						item.addClass('month-'+m+' year-'+y);
						toggle_current_date(y, m);
					}
					else
						alert(json.error);
				},
				error:function() {
					console.warn('error complete save');
				}
			});
		}
		
		var content = jQuery('.content', item);
		if	(content.length == 1) {
			content.after(content.clone(true));
			convertTextarea(jQuery('.content:last', item), curInstance);
			jQuery('.content:first', item).hide();
		}
		else {
			jQuery('.content:first', item).hide();
			jQuery('.content:last', item).show();
		}
		
		var title = convertInput(jQuery('.title', item), 640);
		var theme = convertInput(jQuery('.theme', item), 200, 'Theme');
		var begin = convertInput(jQuery('.begin', item), 200);
		var end = convertInput(jQuery('.end', item), 200);
		begin.click(function(){
			ShowCalendar(this);
		});
		end.click(function(){
			ShowCalendar(this);			
		});
		jQuery('.date', item).hide();
		return false;
	});
		
	
	var MoisFrancais = {
		'01':'janv.',
		'02':'fév.',
		'03':'mars',
		'04':'avr.',
		'05':'mai',
		'06':'juin',
		'07':'juil.',
		'08':'août',
		'09':'sept.',
		'10':'oct.',
		'11':'nov.',
		'12':'déc.'
	};
	function	ucfirst(str) {
		return str.substr(0,1).toUpperCase()+str.substr(1);
	}
	var currentYear = '';
	var currentMonth = '';
	var currentTheme = '';
	function	toggle_current_date(year, month) {
		if (currentYear == year && currentMonth == month)
			return ;
		//console.info('update to '+year+' / '+month);
		jQuery('.tabulation .onglets li').removeClass('active');
		jQuery('.tabulation .onglets li.year-'+year+'.month-'+month).addClass('active');
		currentMonth = month;
		currentYear = year;
		updateList();
	}
	function	toggle_current_theme(theme) {
		if (currentTheme == theme)
			return ;
		jQuery('.sidebar .redselect').removeClass('redselect');
		currentTheme = theme;
		updateList();
	}
	function	updateList() {
		var criteria = '';
		if (currentTheme)
			criteria += '.theme-'+currentTheme;
		if (currentYear)
			criteria += '.year-'+currentYear;
		if (currentMonth)
			criteria += '.month-'+currentMonth;
		
		var elems = jQuery('#list .item:visible');
		var i = 0;
		if (!elems.length)
			fadeIn();
		else
			elems.fadeOut(function() {
				if (++i == elems.length)
					fadeIn();
			});
		function	fadeIn() {
			jQuery('#list .item').removeClass('first');
			var toShow = jQuery('#list .item'+criteria);
			toShow.filter(':first').addClass('first');
			toShow.fadeIn();
		}
	}
	function	add_onglet(year, month) {
		var tab = base.clone();
		tab.addClass('year-'+year+' month-'+month);
		tab.html(ucfirst(MoisFrancais[month])+' <span>'+month+'</span><em>'+year+'</em>');
		if (ajouter)
			ajouter.before(tab);
		else
			ul.append(tab);
	}
	/** creations des onglets des mois */
	var ul = jQuery('.tabulation .onglets ul');
	var base = jQuery('li:first', ul);
	base.remove();
	base.empty();
	for (var j = 10; j >= 5; j--) {
		var y = (j<10?'0'+j: j);
//		console.group('year: 20'+y);
		for (var i=12; i; i--) {
			var m = (i<10?'0'+i: i);
			var blocs = jQuery('.year-'+y+'.month-'+m, list);
//			console.info('exists: '+y+'/'+m+''+(blocs.length? ' => yes': ''));
			if (blocs.length)
				add_onglet(y, m);
//			var item = jQuery('.month-'+m2);
//			if (item.length) {
//				var year = jQuery('.end', item).html();
//				if (!year || year == '0000-00-00')
//					year = jQuery('.begin', item).html();
//				year = year.substr(0, 4);
////				if (m2 == '09') {
////					console.info('year '+j+' month: '+m2+' '+year);
////				}
//				if (parseInt(year)==j) {
//					year = year.substr(2,2);
//					var m = base.clone();
//					m.addClass('month-'+m2);
//					m.html(ucfirst(MoisFrancais[m2])+' <span>'+m2+'</span><em>'+year+'</em>');
//					ul.append(m);
//				}
//			}
		}
//		console.groupEnd();
	}
	
	
	var ajouter = null;
	if (typeof(ImageBrowser)!='undefined') {
		var last = jQuery('.boxcontent .tabulation .onglets ul li:last');
		ajouter = last.clone(true);
		if (ajouter.length)
			ajouter[0].className = '';
		ajouter.html('ajouter').addClass('ajouter');
		last.after(ajouter);
//		var addbutton = list.before(jQuery('<a href="javascript:" class="ajouter">ajouter</a>'));
		
		jQuery('.ajouter').click(function() {
			jQuery('.tabulation .onglets li').removeClass('active');
			jQuery(this).addClass('active');
			var elems = jQuery('#list .item');
			var i = 0;
			elems.fadeOut(function() {
				i++;
				if (i == elems.length) {
					//console.warn('add');
					var bloc = jQuery('#list .item:last');
					var newbloc = bloc.clone(true);
					jQuery('.title, .content, .theme, .end, .begin', newbloc).empty();
					jQuery('input[@type=hidden]', newbloc).val('');
					newbloc.show();
					bloc.before(newbloc);
					jQuery('.modifier',newbloc).click();
				}
			});
			return false;
		});
	}
	jQuery('.tabulation .onglets li').click(function() {
		if (jQuery(this).is('.active'))
			return ;
		toggle_current_date(jQuery('em', this).html(), jQuery('span', this).html());
	});
	jQuery('.tabulation .onglets li:first').click();
	
	
	jQuery('.onglets').scrollTo('li:eq(0)', 800, {axis:'x'});
	var current = 0;
	var max = jQuery('.onglets li').length;
	jQuery('.onglets .upper').click(function() {
		current += 4;
		current = current >= max - 6? max-7: current;
		jQuery('.onglets .scrollable').scrollTo('li:eq('+(current)+')', 800, {axis:'x'});
	});
	jQuery('.onglets .lower').click(function() {
		current -= 4;
		current = current < 0? 0: current;
		jQuery('.onglets .scrollable').scrollTo('li:eq('+(current)+')', 800, {axis:'x'});
	});
});

function	restoreInput(title, size) {
//	console.info('restore title => '+title.val());	

	title.hide();
	var text = title.val();
	//jQuery('<div class="'+title[0].name+'"></div>').appendTo(title);
	var div = title.parent('div:first');
	div.html(text);
	div.css({width:size+'px'});
}

function	convertInput(title, size, option) {
	option = option || null;
		
	title.show();
	var text = title.html();
	title.empty();
	if (option) {
		jQuery('<select id="'+title[0].className+'" class="'+title[0].className+'" ><option value="Gouvernance Mondiale">Gouvernance mondiale</option>' +
					'<option value="Libéralisation du Commerce">Lib&eacute;ralisation du commerce</option>' +
					'<option value="Entreprise et biens publics">Entreprise et biens publics</option>' +
					'<option value="Changement Climatique">Changement climatique</option>'+
					'<option value="Ressources naturelles">Ressources naturelles</option>' +
				'</select>'
		).appendTo(title);
	}
	else
		jQuery('<input type="text" class="'+title[0].className+'" />').appendTo(title);
	var title= jQuery('input', title)
	title.val(text);
	title.css({width:size+'px'})
	return (title);
}

function	SavePage() {
	var enedit= jQuery('.item.edit:first');
	if (enedit.length)
		enedit[0].SavePage();
}

function	convertTextarea(content, curInstance) {
	content.show();
	var text = content.html();
	content.empty();
	jQuery('<textarea id="tmp42fck'+curInstance+'">'+text+'</textarea>').appendTo(content);
    var editor = new FCKeditor('tmp42fck'+curInstance,'100%','640','Default') ;
    editor.BasePath= '/scripts/FCKeditor/';
    editor.Width = '640px';
    editor.Height = '400px';
//    editor.Config['CustomConfigurationsPath'] = editor.BasePath + 'myconfig.js';
    editor.ReplaceTextarea() ;
    return (editor);
}
(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'y',
		duration:1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window).scrollable();
	};

	// Hack, hack, hack... stay away!
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn.scrollable = function(){
		return this.map(function(){
			// Just store it, we might need it
			var win = this.parentWindow || this.defaultView,
				// If it's a document, get its iframe or the window if it's THE document
				elem = this.nodeName == '#document' ? win.frameElement || win : this,
				// Get the corresponding document
				doc = elem.contentDocument || (elem.contentWindow || elem).document,
				isWin = elem.setInterval;

			return elem.nodeName == 'IFRAME' || isWin && $.browser.safari ? doc.body
				: isWin ? doc.documentElement
				: this;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this.scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(px)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					Dim = axis == 'x' ? 'Width' : 'Height',
					dim = Dim.toLowerCase();

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[dim]() * settings.over[pos];
				}else
					attr[key] = targ[pos];

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});			
			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};
			function max( Dim ){
				var attr ='scroll'+Dim,
					doc = elem.ownerDocument;
				
				return win
						? Math.max( doc.documentElement[attr], doc.body[attr]  )
						: elem[attr];
			};
		}).end();
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );
