TO_LOAD_INDEX++;
TO_LOAD[TO_LOAD_INDEX]='load_fluidbook();';

function load_fluidbook(){
		load_modals();
		cancel_autoscroll_to_top();
		load_admin_localized();
		load_admin_interface();
		display_post_messages();
		load_paginator();
		fill_views();
		edit_in_place_buttons();
		popup_dimensions();
		top_slideshow();
		//main_slideshow();
		resize_edit_in_place();
		replace_filter_fields();
		slideFields();
		enableDialogHover();
		enable_minislideShow();
}


function enable_minislideShow() {
	$(function(){
		$('#slides').slides({
			preload: true,
			preloadImage: 'img/loading.gif',
			play: 5000,
			pause: 2500,
			hoverPause: true
		});
	});
}

function enableDialogHover(){
	$(".ui-dialog-titlebar").mouseover(function(){
		$("body").css("cursor", "pointer");
	});
	$(".ui-dialog-titlebar").mouseout(function(){
		$("body").css("cursor", "");
	});
}

function slideFields(){
	$('div[id^="SLIDINGFIELD_"]').each(function() {
		fieldDiv = $(this).find('div:first');
		fieldDiv.find('.field_div_inside').slideUp();
		fieldDiv.find('.field_dialog_header').click(function() {
			$(this).parent().find('.field_div_inside').slideToggle();
		});
	});
}
// Limite les textarea à une certain nombre de caractères
function limitTextArea(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    }
}
/**************************************
* JAVASCRIPT MINICAROUSEL
*************************************/
var time_interval = 5000;
var timeout_id = 0;
function top_slideshow(){
	timeout_id = setTimeout("switch_next_carousel_item()", time_interval);
	// Enable buttons
	$('a[id^="goto_fluidbook_slide_"]').click(function() {
		var new_carousel = $(this).attr('id');
		new_carousel = new_carousel.replace('goto_', '');
		var active = $('#fluidbook_slideshow').find('li[rel="active"]').attr('id');
		// Change slide only if new is different from old
		if(active != new_carousel) {
			clearTimeout(timeout_id);
			// Masquer tous les elements visibles
			$('li[id^="fluidbook_slide"]').each(function() {
				if($(this).is(':visible')) {
					$(this).attr('rel', '');
					$(this).fadeOut(1000);
				}
			});
			// Afficher la div cliquée
			$('#'+new_carousel).attr('rel', 'active');
			$('#'+new_carousel).fadeIn(1000);
			timeout_id = setTimeout("switch_next_carousel_item()", time_interval);
		}
	});

	// I*** TRICK
	// Enlarges slideshow div width's to body div width's
	if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1))
	{
     	var bodyWidth = $('body').width();
		$('li[id^="fluidbook_slide"]').each(function() {
			$(this).width(bodyWidth);
		});
	}
}


function switch_next_carousel_item() {
	var slideshowDiv = $('#fluidbook_slideshow');
	var active = $('#fluidbook_slideshow').find('li[rel="active"]');

	clearTimeout(timeout_id);
	// Avoid animation stack
	if (active.is(':animated')) {
		return false;
	}

	// Select next element. Loop back if we reach the end
	var next = active.next();
	if(next.attr('id') == undefined) {
		next = slideshowDiv.find('ul').find('li:first');
	}
	// Performs transition
	$(active).fadeOut(1000);
	$(active).attr('rel', '');
	$(next).fadeIn(1000);
	$(next).attr('rel', 'active');

	// Enable back timer so the animation will continue
	timeout_id = setTimeout("switch_next_carousel_item()", time_interval);
}






// Redimensionne les fenetre 'EDIT IN PLACE'
function resize_edit_in_place(){
	if($('#EDIT_IN_PLACE').length > 0) {
		$(window).resize(function() {
			var containerDiv = $('#EDIT_IN_PLACE');
			var contentDiv = containerDiv.find('.field div:first');
			var windowHeight = $(window).height();
			var contentHeight = contentDiv.height();
			var newWidth = containerDiv.width();
			if(windowHeight < containerDiv.height()) {
				contentDiv.css('height', (windowHeight-100)+'px').css('overflow-y', 'scroll').css('overflow-x', 'hidden');
				popup_dimensions();
			}
		});

			var containerDiv = $('#EDIT_IN_PLACE');
			var contentDiv = containerDiv.find('.field div:first');
			var windowHeight = $(window).height();
			var contentHeight = contentDiv.height();
			var newWidth = containerDiv.width();

			if($.browser.msie && $.browser.version < 8) {
				/* IE 7 behaviour - Force width drawing for header and make close button float right*/
				var header = containerDiv.find('.field span:first');
				containerDiv.css('width', newWidth+'px');
				var headerPaddingX = header.innerWidth()-header.width();
				var headerPaddingY = header.innerHeight()-header.height();
				header.css('width', (contentDiv.innerWidth()-headerPaddingX));
				header.find('.close_button').css('float', 'right').css('padding-top', (headerPaddingY));
				/* end of ie7 behaviour */
			}
			if(windowHeight < containerDiv.height()) {
				contentDiv.css('height', (windowHeight-100)+'px').css('overflow-y', 'scroll').css('overflow-x', 'hidden');
				popup_dimensions();
			}
	}
}

// Gere les zones edit in place
function edit_in_place_buttons(){

	$('.close_button').click(function() {  location.reload(); } );

	$('div[id^="editable_in_place"]').mouseenter( function() {
		$(this).css('background-color', 'rgb(175,175,175)');
		$(this).find('.edit_in_place_button_toggle').show();
	});

	$('div[id^="editable_in_place"]').mouseleave( function() {
		$(this).css('background-color', 'transparent');

		$(this).find('.edit_in_place_button_toggle').hide();
	});

	// Min size of editable div
	$('div[id^="editable_in_place"]').each(function() {
		if($(this).height() < 25)
			$(this).height(25);

		$(this).find('.edit_in_place_button_toggle').hide();
	});
}


// Replace correctement les champs si le filtre est activé (les place les uns a coté des autres au lieu des uns en dessous des autres)
 function replace_filter_fields() {
	var rawFields = $('div[id^="FILTER_"]').find('.rawField');
	rawFields.css('float', 'left').css('padding-left', '10px').css('text-align', 'center');
}

// Gestion des fenetres de confirmation modales
function load_modals(){
		$('input[id^="openDeleteConfirm_"]').click(function() {
			var id = $(this).attr('id');
			var id = id.replace('openDeleteConfirm_', 'dialogDeleteConfirm_');
			$('#'+id).dialog('destroy');
			$('#'+id).dialog({
				modal: true,
				buttons: {
					"Supprimer": function() {
						var formElt = $(this).find('p').attr('title');
						$('#'+formElt).submit();
						$( this ).dialog( "close" );
					},
					"Annuler": function() {
						$( this ).dialog( "close" );
					}
				}
			});
			$('#'+id).dialog('option', 'position', 'center');
		});
}


// Inscrit la vue parent dans chaque champ (pour la mise en cache)
function fill_views(){
	$('div[id^="VIEW_"]').each(function() {
		var viewName = $(this).attr('id');
		viewName = viewName.replace('VIEW_', '');
		$(this).find('input[name="parent_view_id"]').each(function() {
			$(this).val(viewName);
		});
	});
}


// Annule l'autoscroll vertical
function cancel_autoscroll_to_top(){
	$('a[href="#"]').click(function(event) {
		event.preventDefault();
		return false;
	});
}



// Affiche les messages post en fadeIn
function display_post_messages(){
	var message_width_max_ratio = 0.7;
	var message_displayed_time = 5000;
	$('div[id^="FIELD_"]').find('span[id^="FIELDMESSAGE_"]').each(function() {
  		var content = $(this).html();
  		if(content.length > 0) {

  			if(content.slice(0, 9) == '[success]') {
	  			create_post_message('success',  $(this), message_width_max_ratio);
  			} else if(content.slice(0, 7) == '[error]') {
	  			create_post_message('error', $(this), message_width_max_ratio);
  			} else if(content.slice(0, 9) == '[warning]') {
	  			create_post_message('warning', $(this), message_width_max_ratio);
  			} else if(content.slice(0, 6) == '[info]') {
	  			create_post_message('info', $(this), message_width_max_ratio);
  			}
  		}
 	});

	$('div[id^="FIELD_"]').find('span[id^="FIELDMESSAGE_"]').each(function() {
	  			$(this).find('div').delay(message_displayed_time).fadeOut();
	});
}

// Stylise les messages simples en messages complexes
function get_stylized_post_message(type, message){
	if(type=='success') {
		return "<div class='ui-corner-all field_message field_message_success'>"+message+"</div>";
	} else if(type=='info') {
		return "<div class='ui-corner-all field_message field_message_info'>"+message+"</div>";
	} else if(type=='warning') {
		return "<div class='ui-corner-all field_message field_message_warning'>"+message+"</div>";
	} else if(type=='error') {
		return "<div class='ui-corner-all field_message field_message_error'>"+message+"</div>";
	}
}

// Créé un message
function create_post_message(type,element, message_width_max_ratio){
	var content = element.html();
	var successMsg = content.slice((type.length+2), content.length);
	var parentWidth = element.parent().width();

	var contentWidth = element.width();
	var successHtml = get_stylized_post_message(type, successMsg);
	// fit content to message width
	(contentWidth > parentWidth*message_width_max_ratio) ? messageWidth = (parentWidth*message_width_max_ratio) :  messageWidth = contentWidth;
	element.html(successHtml);
	element.find('div').width(contentWidth);

}

// Charge le module de pagination


function load_paginator(){
			$('div[id^="divPaginate_"]').each(function() {
				var eltId = $(this).attr('id');
				eltId = eltId.replace('divPaginate_', '');

				var divParent = $(this);
				var paginateDivPrefix = 'divPagInst_'+eltId+'_';
				var paginateDivs = divParent.find('div[id^="'+paginateDivPrefix+'"]');
				var paginatorElementId='#divPaginatorElement_'+eltId;

				var paginatorElement = divParent.find(paginatorElementId);


				var filterElement = $("#FILTER_"+eltId);

				var numElements = 0;

				if(filterElement.length > 0) {
					numElements = divParent.find('> div').length - 3; // FIELD_[element] and divPaginatorElement_ and filter
				} else {
					numElements = divParent.find('> div').length - 2; // FIELD_[element] and divPaginatorElement_
				}
				(numElements>=10) ? displayElements = 10 : displayElements=numElements;
				var activePage = jQuery.cookie($(paginatorElement).attr('id'));
				if(activePage === undefined || activePage == null) {
					activePage = 1;

				}

				var offsetValue = 0;
				if(filterElement.length > 0) {
					if(filterElement.find('select').length > 0) {
						offsetValue = filterElement.find('select').val();
					}
				}
				divParent.find('._current').removeClass('_current').hide();
				// Display selected element, if possible
				if($('#'+paginateDivPrefix+(activePage-1)).length > 0) {
					$('#'+paginateDivPrefix+(activePage-1)).addClass('_current').show();
				} else {
					$('#'+paginateDivPrefix+0).addClass('_current').show();
					activePage = 1;
				}

				$(paginatorElement).paginate({
					count : numElements,
					display     : displayElements,
					start 		: activePage,

					border					: true,
					offset                  : offsetValue,
					border_color			: '#336633',
					text_color  			: '#000000',
					background_color    	: '#F9F9F9',
					border_hover_color		: '#66CC66',
					text_hover_color  		: '#000',

					background_hover_color	: '#CCFF99',
					images					: false,
					mouse					: 'press',
					onChange     			: function(page){
												page = parseInt(page)-parseInt(offsetValue);
												var currentPageId = divParent.find('._current').attr('id');
												var selectedPageId = $('#'+paginateDivPrefix+(page-1));
												var selectedPage = $(selectedPageId);
												if(currentPageId != selectedPageId) {
													$('#'+currentPageId).find('span').replaceWith( function() { return '<span id="FIELDMESSAGE_"'+eltId+'></span>'; } );
													paginateDivs.hide().end().removeClass('_current');

													selectedPage.addClass('_current').fadeIn(1000).end().find('div[id^="dialogDeleteConfirm_"]').hide();
													if (page > 0) {
														jQuery.cookie(paginatorElement.attr('id'), page);
													}
												}
										  	  }
				});

			});
}

// Charge les accordeons pour l'interface administrateur et change le style des boutons
function load_admin_interface(){
		$("input:submit, input:button").each(function() {
			if(!(strstr($(this).attr('class'), 'instance_') != false)) {
				$(this).button();
			}
		});
		// Build inner accordions first
		$('div[id^="FIELD_"]').each(function() {

			$(this).find('div[id^="divAccordion_"]').each(function() {
				var activeTab = jQuery.cookie($(this).attr('id'));

				if(activeTab === undefined) {
					activeTab = 0;
				}
				$(this).accordion('destroy');
				$(this).accordion({
					active: parseInt(activeTab),
					autoHeight: false,
					clearStyle: true,
					change: function(event,ui) {
						var index = jQuery(this).find('h3').index(ui.newHeader[0]);
						if (index > -1) { jQuery.cookie($(this).attr('id'), index)}
					}
				});
			});
		});
}

// Charge les drapeaux pour chaque pays
function load_admin_localized(){
		$('a[class^="switchLocalized_"]').click(function() {
			var className = $(this).attr('class');
			var strLength = className.length;
			var itemLang = className.substr(strLength-2, strLength);
			itemLang = itemLang.replace('on', 'common');

			var elementName = className.replace('switchLocalized_', '');
			elementName = elementName.replace('_'+itemLang, '');

			$('div[id^="divLocalized_'+elementName+'"]').each(function() {
				$(this).hide();
			});

			var currentItem = 'divLocalized_'+elementName+'_'+itemLang;
			var content_html = $('div[id="'+currentItem+'"]').fadeIn(1500);

			// On met en place l'élement actif
			$(this).parent().find('font[class="langSelected"]').removeClass("langSelected");
			$(this).find('font').addClass("langSelected");
		});
}


/* FONCTIONS UTILITAIRES */
/************************/
/* identique à son homologue php */
function strstr (haystack, needle, bool) {
    var pos = 0;
    haystack += '';
    pos = haystack.indexOf( needle );    if (pos == -1) {
        return false;
    } else{
        if (bool){
            return haystack.substr( 0, pos );        } else{
            return haystack.slice( pos );
        }
    }
}

