jQuery( function ( $ ) {

	// Run tipTip
	function runTipTip() {
		// Remove any lingering tooltips
		$( '#tiptip_holder' ).removeAttr( 'style' );
		$( '#tiptip_arrow' ).removeAttr( 'style' );
		$( '.tips' ).tipTip({
			'attribute': 'data-tip',
			'fadeIn': 50,
			'fadeOut': 50,
			'delay': 200,
			'keepAlive': true
		});
	}

	runTipTip();

	// Allow Tabbing
	$( '#titlediv' ).find( '#title' ).keyup( function( event ) {
		var code = event.keyCode || event.which;

		// Tab key
		if ( code === '9' && $( '#kkart-coupon-description' ).length > 0 ) {
			event.stopPropagation();
			$( '#kkart-coupon-description' ).focus();
			return false;
		}
	});

	$( '.kkart-metaboxes-wrapper' ).on( 'click', '.kkart-metabox > h3', function() {
		$( this ).parent( '.kkart-metabox' ).toggleClass( 'closed' ).toggleClass( 'open' );
	});

	// Tabbed Panels
	$( document.body ).on( 'kkart-init-tabbed-panels', function() {
		$( 'ul.kkart-tabs' ).show();
		$( 'ul.kkart-tabs a' ).click( function( e ) {
			e.preventDefault();
			var panel_wrap = $( this ).closest( 'div.panel-wrap' );
			$( 'ul.kkart-tabs li', panel_wrap ).removeClass( 'active' );
			$( this ).parent().addClass( 'active' );
			$( 'div.panel', panel_wrap ).hide();
			$( $( this ).attr( 'href' ) ).show();
		});
		$( 'div.panel-wrap' ).each( function() {
			$( this ).find( 'ul.kkart-tabs li' ).eq( 0 ).find( 'a' ).click();
		});
	}).trigger( 'kkart-init-tabbed-panels' );

	// Date Picker
	$( document.body ).on( 'kkart-init-datepickers', function() {
		$( '.date-picker-field, .date-picker' ).datepicker({
			dateFormat: 'yy-mm-dd',
			numberOfMonths: 1,
			showButtonPanel: true
		});
	}).trigger( 'kkart-init-datepickers' );

	// Meta-Boxes - Open/close
	$( '.kkart-metaboxes-wrapper' ).on( 'click', '.kkart-metabox h3', function( event ) {
		// If the user clicks on some form input inside the h3, like a select list (for variations), the box should not be toggled
		if ( $( event.target ).filter( ':input, option, .sort' ).length ) {
			return;
		}

		$( this ).next( '.kkart-metabox-content' ).stop().slideToggle();
	})
	.on( 'click', '.expand_all', function() {
		$( this ).closest( '.kkart-metaboxes-wrapper' ).find( '.kkart-metabox > .kkart-metabox-content' ).show();
		return false;
	})
	.on( 'click', '.close_all', function() {
		$( this ).closest( '.kkart-metaboxes-wrapper' ).find( '.kkart-metabox > .kkart-metabox-content' ).hide();
		return false;
	});
	$( '.kkart-metabox.closed' ).each( function() {
		$( this ).find( '.kkart-metabox-content' ).hide();
	});
});
