$(document).ready(function() {
	//------------------------------------------------------//
	//                          INIT                        //
	//------------------------------------------------------//
	//Tooltip
	$('a').tooltip({
		animation : false
	})
	
	//Reports
	$(".recipient-click-export").tooltip("destroy");
	$(".recipient-click-export").tooltip({animation : false, placement: "left"});
	
	//Campaigns
	$(".delete-campaign").tooltip("destroy");
	$(".delete-campaign").tooltip({animation : false, placement: "left"});
	
	//Templates
	$(".delete-template").tooltip("destroy");
	$(".delete-template").tooltip({animation : false, placement: "left"});
	
	//Lists
	$(".delete-list").tooltip("destroy");
	$(".delete-list").tooltip({animation : false, placement: "left"});
	
	//Subscribers
	$(".delete-subscriber").tooltip("destroy");
	$(".delete-subscriber").tooltip({animation : false, placement: "left"});
	
	//Campaigns RSS
	$(".campaigns-rss-btn").tooltip("destroy");
	$(".campaigns-rss-btn").tooltip({animation : false, placement: "left"});
	
	//Automatic selct all text in code
	$("code").mouseover(function(){
		$(this).selectText();
	});
	
	$(".accordion-toggle").on("mouseup mouseleave", function(){
		$(this).blur();
	});

	$(".dashboard-ses-toggle").on("click", function(){
		var $toggle = $(this);
		var isOpen = $toggle.attr("aria-expanded") === "true";

		$toggle.attr("aria-expanded", isOpen ? "false" : "true");
		$("#dashboard-ses-panel").toggleClass("is-open", !isOpen);
	});

	// Focus top page search with "/".
	$(document).on("keydown", function(e){
		var tag = document.activeElement && document.activeElement.tagName ? document.activeElement.tagName.toLowerCase() : '';
		var isTyping = tag == 'input' || tag == 'textarea' || tag == 'select' || $(document.activeElement).is('[contenteditable="true"]');
		
		if(e.key == '/' && !e.ctrlKey && !e.metaKey && !e.altKey && !isTyping)
		{
			var $searchField = $('.form-search .search-query:visible').first();
			
			if($searchField.length)
			{
				e.preventDefault();
				$searchField.focus();
			}
		}
	});
	//------------------------------------------------------//
	//                        BUTTONS                       //
	//------------------------------------------------------//
	
	//------------------------------------------------------//
	//                      FUNCTIONS                       //
	//------------------------------------------------------//	
	
	jQuery.fn.selectText = function(){
	    var doc = document
	        , element = this[0]
	        , range, selection
	    ;
	    if (doc.body.createTextRange) {
	        range = document.body.createTextRange();
	        range.moveToElementText(element);
	        range.select();
	    } else if (window.getSelection) {
	        selection = window.getSelection();        
	        range = document.createRange();
	        range.selectNodeContents(element);
	        selection.removeAllRanges();
	        selection.addRange(range);
	    }
	};
});
