/*!
 * iloPanel 1.2.0
 *
 * Copyright (c) 2010 iloWeb
 *
 * http://www.iloweb.com
 *
 * @requires jQuery($), jQuery timers jQuery UI & jQuery Multiselect
 */

var Admin = {

  /**
     * render log message
     * @param mixed
     */
  log: function() {
	var msg = '[Sonata.Admin] ' + Array.prototype.join.call(arguments,', ');
	if (window.console && window.console.log) {
	  window.console.log(msg);
	}
	else if (window.opera && window.opera.postError) {
	  window.opera.postError(msg);
	}
  },

  /**
     * display related errors messages
     *
     * @param subject
     */
  add_pretty_errors: function(subject) {
	jQuery('div.sonata-ba-field-error', subject).each(function(index, element) {
	  var input = jQuery('input, textarea', element);

	  var message = jQuery('div.sonata-ba-field-error-messages', element).html();
	  jQuery('div.sonata-ba-field-error-messages', element).html('');
	  if (!message) {
		message = '';
	  }

	  if (message.length == 0) {
		return;
	  }

	  input.qtip({
		content: message,
		show: 'focusin',
		hide: 'focusout',
		position: {
		  corner: {
			target: 'rightMiddle',
			tooltip: 'leftMiddle'
		  }
		},
		style: {
		  name: 'red',
		  border: {
			radius: 2
		  },
		  tip: 'leftMiddle'
		}
	  })
	});
  },

  /**
     * Add the collapsed toggle option to the admin
     *
     * @param subject
     */
  add_collapsed_toggle: function(subject) {
	jQuery('fieldset legend a.sonata-ba-collapsed', subject).live('click', function(event) {
	  event.preventDefault();

	  var fieldset = jQuery(this).closest('fieldset');

	  jQuery('div.sonata-ba-collapsed-fields', fieldset).toggle();
	  fieldset.toggleClass('sonata-ba-collapsed-fields-close');
	}).click();
  }
}

function bindNotificationsEvents(time)
{
  if(time==undefined)
	time=5000;
  jQuery.fn.extend({
	hideNotification : function(){
	  $(this).stopTime('hidingNotification');
	  $(this).fadeTo(400, 0, function () {
		$(this).slideUp(400,function(){
		  $(this).remove()
		});
	  });
	}
  });
  //Close button:
  $(".close").unbind('click');
  $(".close").click(	function () {
	$(this).parent().hideNotification();
	return false;
  }	);

  //fadeout for notification div after X mseconds
  //$("div.notification.flash:not('.error')").each(function(){	$(this).oneTime(time, 'hidingNotification', function(){ $(this).hideNotification();});});
  $("div.notification.flash").each(function(){
	$(this).oneTime(time, 'hidingNotification', function(){
	  $(this).hideNotification();
	});
  });
}

function replaceCommasByDots(event){
  value = $(event.target);
  value.val(value.val().replace(",", "."));
}

function moveSidebar(indent)
{
  $bodywrapper.stop(true).animate({
	left: indent
  },{
	queue: false,
	duration: 'fast'
  });
  $body.stop(true).animate({
	'background-position' : indent+'px'
  },{
	queue: false,
	duration: 'fast'
  });
}

function bindShiftSidebar()
{
  //au redimensionnement on supprime les anciens hooks
  $sidebar.die('mouseenter.sidebar mouseleave.sidebar');
  //fenêtre trop petite
  if ( $document.width()-$window.width()  > $delta )
  {
	// on calcul le décalage
	var decalage='-'+($sidebar.width()-15);
	//on décale
	moveSidebar(decalage);
	//on ajoute le bouton de controle
	$('<a id="collapse-button" href="#"></a>').bind('click',function(){
	  var indent = 0;
	  if ($(this).hasClass('uncollapsed'))
	  {
		indent = decalage;
	  }
	  $(this).toggleClass('uncollapsed collapsed');
	  moveSidebar(indent);

	  return false;
	}).addClass('collapsed').appendTo($sidebar);
  } else {
	//fenêtre assez large, retour à la normale
	$('a#collapse-button').remove();
	//si la sidebar est masquée
	if(parseFloat($bodywrapper.css('left'))<0)
	{
	  // on arrête toute animation, est on replace instantanément en position normale
	  $bodywrapper.stop(true).css('left',0);
	  $body.css({
		'background-position' : 'left top'
	  })
	  // on revérifie que désormais ça ne soit pas trop large
	  if ( $document.width()-$window.width() > $delta  )
	  {
		bindShiftSidebar();
		return;
	  }
	}

	// on arrête toute animation, est on replace progressivement en position normale
	$bodywrapper.stop(true).animate({
	  left: 0
	},'fast');
  }
}

$(document).ready(function()
{
  //Admin.add_pretty_errors(document);
  //Admin.add_collapsed_toggle();

  //Sidebar
  $document = $(document);
  $window = $(window);
  $body = $('body#body');
  $sidebar = $('#sidebar');
  $bodywrapper = $('#body-wrapper');
  $delta = parseInt($("#main-content").css('margin-right'));
  $(window).resize(function(){
	$(document).stopTime('shiftSidebar');
	bindShiftSidebar()
  });
  $(document).oneTime(500,'shiftSidebar',function(){
	bindShiftSidebar();
  });

  //Sidebar Accordion Menu:
  $("#main-nav li a:not(.current)").parent().find("ul").hide(); // Hide all sub menus
  //$("#main-nav li a.current").parent().find("ul").show(); // Slide down the current menu item's sub menu
  $("#main-nav li a.nav-top-item:not('.no-submenu')").click( // When a top menu item is clicked...
	function () {
	  $(this).parent().siblings().find("ul").slideUp("normal"); // Slide up all sub menus except the one clicked
	  $(this).next().slideToggle("normal"); // Slide down the clicked sub menu
	  return false;
	}
	);

  // Sidebar Accordion Menu Hover Effect:
  $("#main-nav li .nav-top-item").hover(
	function () {
	  $(this).stop().animate({
		paddingRight: "15px"
	  }, 200);
	//$(this).stop().animate({ paddingRight: "25px" }, 200);
	},
	function () {
	  $(this).stop().animate({
		paddingRight: "5px"
	  });
	//$(this).stop().animate({ paddingRight: "15px" });
	}
	);

  bindNotificationsEvents();

  $('div > .tooltip.error').each(function()
  {
	$(this).hide().parent('div').hover(
	  function()
	  {
		$(this).children('.tooltip.error').slideDown('fast');
	  },
	  function()
	  {
		$(this).children('.tooltip.error').fadeOut();
	  }
	  ).children('input,select,textarea').focusin(
	  function()
	  {
		$(this).parent('div').next('.tooltip.error').slideDown('fast');
	  }
	  ).focusout(
	  function()
	  {
		$(this).parent('div').next('.tooltip.error').fadeOut();
	  }
	  );
  });

  $('p .tooltip.error').each(function()
  {
	$(this).hide().parent('p').hover(
	  function()
	  {
		$(this).children('.tooltip.error').slideDown('fast');
	  },
	  function()
	  {
		$(this).children('.tooltip.error').fadeOut();
	  }
	  ).children('input,select,textarea').focusin(
	  function()
	  {
		$(this).next('.tooltip.error').slideDown('fast');
	  }
	  ).focusout(
	  function()
	  {
		$(this).next('.tooltip.error').fadeOut();
	  }
	  );
  });

  // Initialise jQuery WYSIWYG:
  $(".wysiwyg").wysiwyg(); // Applies WYSIWYG editor to any textarea with the class "wysiwyg"

  //disable click on disabled objects
  $('.disabled').click(function(){
	return false
  });

  //Minimize Content Box
  $(".content-box-header h3").css({
	"cursor":"s-resize"
  }); // Give the h3 in Content Box Header a different cursor
  $(".closed-box .content-box-content").hide(); // Hide the content of the header if it has the class "closed"
  $(".closed-box .content-box-tabs").hide(); // Hide the tabs in the header if it has the class "closed"
  $(".content-box-header h3").click( // When the h3 is clicked...
	function () {
	  $(this).parent().next().toggle(); // Toggle the Content Box
	  $(this).parent().parent().toggleClass("closed-box"); // Toggle the class "closed-box" on the content box
	  $(this).parent().find(".content-box-tabs").toggle(); // Toggle the tabs
	}
	);

  // Content box tabs:
  $('.content-box .content-box-content div.tab-content:not(#tab_filters)').hide(); // Hide the content divs
  $('ul.content-box-tabs li a.default-tab').addClass('current'); // Add the class "current" to the default tab
  $('.content-box-content div.default-tab').show(); // Show the div with class "default-tab"
  $('.content-box-tabs li a.default-tab').each(function()
  {
	$(this).parent('li').addClass('default-tab');
  });
  $('.content-box-tabs li a.current').each(function()
  {
	$(this).parent('li').addClass('current');
  });


  $('.content-box ul.content-box-tabs li a:not(.normal_link,#filters)').click( // When a tab is clicked...
	function() {
	  $(this).parent().siblings().find("li").removeClass('current'); // Remove "current" class from all tabs
	  $(this).parent('li').addClass('current'); // Add class "current" to clicked tab
	  var currentTab = $(this).attr('href'); // Set variable "currentTab" to the value of href of clicked tab
	  if(previous_tab!=undefined && $('#tab_filters').is(':visible')){
		$('#tab_filters').slideUp(800);
		previous_tab=undefined;
	  }
	  $(currentTab).siblings(":not('#tab_filters')").hide(); // Hide all content divs
	  $(currentTab).show(); // Show the content div with the id equal to the id of clicked tab
	  return false;
	}
	);

  $('.content-box ul.content-box-tabs li a#filters:not(\'.disabled\')').click(
	function(){
	  if(previous_tab==undefined){
		previous_tab=$('ul.content-box-tabs li.current');
		previous_tab.removeClass('current');
		$(this).parent('li').addClass('current');
	  }else{
		$(this).parent('li').removeClass('current');
		previous_tab.addClass('current');
		previous_tab=undefined
	  }
	  /*$('#tab_filters').slideToggle(800);*/
	  // équivalent à la ligne au dessus
	  // l'opacity est pour la compatibilité IE7
	  $('#tab_filters').animate({
		height: "toggle",
		opacity:"toggle"
	  }, 800);
	  return false;
	}
	)

  // Alternating table rows:
  //$('tbody tr:even').addClass("alt-row"); // Add class "alt-row" to even table rows

  // Check all checkboxes when the one in a table head is checked:
  $('.check-all')
  .live('check-all',function(){
	var checkboxes_checked = 0, $this=$(this), checkboxes = $this.parents('thead:first').nextAll('tbody:first').find(".batch_actions_checkbox");
	checkboxes.each(function(){
	  checkboxes_checked += $(this).is(':checked')?1:0;
	});
	if ( 0 < checkboxes_checked &&  checkboxes_checked < checkboxes.length )
	{
	  $this.addClass('disable');
	} else {
	  $this.removeClass('disable');
	}
	$this.attr('checked', 0 < checkboxes_checked);
  })
  .trigger('check-all')
  .live('click',function(){
	$(this).parents('thead:first').nextAll('tbody:first').find(".batch_actions_checkbox").attr('checked', $(this).is(':checked')).trigger('change');
  });

  $('.batch_actions_checkbox').live('change',function(){
	$(this).parents('tbody:first').prevAll('thead:first').find('.check-all').trigger('check-all');
  }).shiftcheckbox();//Shift select on checkboxes


  // Initialise Facebox Modal window:
  $('a[rel*=modal]').facebox(); // Applies modal window to any link with attribute rel="modal"

  if(typeof(previous_tab) == "undefined"){
	previous_tab=undefined;
  }

  $([	$(".double_list select")
	]).each(function(){
	$(this).multiselect_autocomplete();
  });

  // Enables the third sample
  $('table:not(".not-sticky")').sticky_table();
  $('.sf_admin_actions, .admin_form_actions').sticky_block();
});
