TO_LOAD_INDEX++;
TO_LOAD[TO_LOAD_INDEX]='load_ajax();';


function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return  hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}




function load_ajax(){
		load_modals();
		cancel_autoscroll_to_top();
		load_admin_localized();
		load_admin_interface();
		display_post_messages();
		load_paginator();
		load_tooltips();
		fill_views();
		input_file();
}

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');
		});

}
function input_file(){
      $('input[type="file"]').each(function() {
	  		$(this).filestyle({
          		image: SITE_PATH+"/framework/js/jquery/filestyle/undelete_files_button.png",
          		imageOver:SITE_PATH+"/framework/js/jquery/filestyle/undelete_files_button_act.png",
          		imageheight : 48,
          		imagewidth : 48,
          		width : 100
      		});
	  });
}


// write parent view id variable to each field
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);
		});
	});
}

function load_tooltips(){
	$('.tooltip').tooltip({
		track: true,
		delay: 0,
		showURL: false,
		extraClass: "right"
	});
}


function cancel_autoscroll_to_top(){
	$('a[href="#"]').click(function(event) {
		event.preventDefault();

		return false;
	});
}

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();
	});
}



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+"<br/></div>";
	} else if(type=='error') {
		return "<div class='ui-corner-all field_message field_message_error'>"+message+"</div>";
	}
}



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);
}


function load_paginator(){
			$('div[id^="divPaginate_"]').each(function() {
				var eltId = $(this).attr('id');
				eltId = eltId.replace('divPaginate_', '');

				var divParent = '#'+$(this).attr('id');
				var paginateDivs = $(divParent).find('div[id^="divPaginateInstance_"]');
				var paginatorElement = $(divParent).find('#divPaginatorElement_'+eltId);

				var numElements = 0;
				$(divParent).find('div[id^="divPaginateInstance_"]').each(function() { numElements++; } );

				(numElements>10) ? displayElements = 10 : displayElements=numElements;

				var activePage = jQuery.cookie($(paginatorElement).attr('id'));
				if(activePage === undefined || activePage == null) {
					activePage = 1;
				}

				$(divParent).find('._current').removeClass('_current').hide();
				// Display selected element, if possible
				if($('#divPaginateInstance_'+(activePage-1)).length > 0) {
					$('#divPaginateInstance_'+(activePage-1)).addClass('_current').show();
				} else {
					$('#divPaginateInstance_'+0).addClass('_current').show();
					activePage = 1;
				}

				$(paginatorElement).paginate({
					count : numElements,
					display     : displayElements,
					start 		: activePage,
					border					: true,
					border_color			: '#EC8E0C',
					text_color  			: '#4895C6',
					background_color    	: '#F9F9F9',
					border_hover_color		: '#ccc',
					text_hover_color  		: '#000',
					background_hover_color	: '#FDF9E1',
					images					: false,
					mouse					: 'press',
					onChange     			: function(page){
												var currentPageId = $(divParent).find('._current').attr('id');
												var selectedPageId = $('#divPaginateInstance_'+(page-1)).attr('id');
												if(currentPageId != selectedPageId) {
													$(divParent).find('._current').removeClass('_current').hide();
													$('#divPaginateInstance_'+(page-1)).addClass('_current').fadeIn(1000);
													$('#divPaginateInstance_'+(page-1) + ' > div').show();
													$('#divPaginateInstance_'+(page-1)).find('div[id^="dialogDeleteConfirm_"]').hide();
													if (page > 0) {
														jQuery.cookie($(paginatorElement).attr('id'), page);
													}
												}
										  	  }
				});
				$(paginateDivs).find('div:first').addClass('_current').show();
				// use cookie maybe...
			});

}


function load_admin_interface(){
		$("input:submit, input:button").not('[class^="instance_"]').button();
		$("input:submit, input:button").each(function() {
			var name = $(this).attr('name');
			if(name.length > 0) {
				$(this).click(function() {
					$(this).closest('form').attr('action', name);
				});
			}
		});


		// 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)}
					}
				});
			});
		});


}

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);

		});
}
