// Global variables (JSON Format)
var temp = { ajaxreq: false };

/* Execute on document ready (DOM Ready state, not fully loaded
=========================================================================================================================================== */
$( document ).ready( function() {


	/* Sidebar Toggle Function (simple class toggle)
	=========================================================================================================================================== */
	$( '.special-sidebar-arrow a' ).on( 'click', function() {

		$( 'body' ).toggleClass( 'sidebar-closed' );
		return false;

	});


	/* Search Toggle (bound but only works when user is allowed to access
	 =========================================================================================================================================== */
	$( '.search-toggle a, .search-toggle-close a' ).on( 'click', function() {

		$( 'body' ).toggleClass( 'open-search' );
		$( '.header .navbar-right' ).toggleClass( 'anim-nodelay' );
		$( '.input-searchbar' ).focus();

		// Create ul element for smart search to use
		if ( $( '.smart-search' ).find( 'ul' )[ 0 ] == null ) { $( '.smart-search' ).append( '<ul class="dropdown-menu search-hidden" style="display: block;"></ul>' ); }

		// Return false for click
		return false;

	});


	/* Service Status
	=========================================================================================================================================== */
	$( '.ajax-query' ).on( 'click', function() {

		// Store object
		var obj = $( this );

		// If already in progress, return false
		if ( temp.ajaxreq !== false || $( obj ).attr( 'data-query' ) == null ) return false;

		// Save few states
		temp.store   = $( obj ).html();
		temp.ajaxreq = true;

		// Add preloader
		$( this ).html( '<i class="fa fa-sync fa-spin"></i>' ); // Preloader

		// Initiate request
		$.ajax({

	        url        : 'system/request.php?query=' + $( obj ).attr( 'data-query' ),
	        dataType   : 'html',
	        cache      : false,
	        processData: false,

	        success: function( data ) {

		        // Parse response
		        var regexp = /([a-z0-9]+)\.png/i;
		        var status = regexp.exec( data );

		        // Delete classes and append new parsed ones
		        $( obj ).removeAttr( 'class' )
			        .addClass( 'ajax-request status-' + status[ 1 ] )
			        .html( '<i class="fa fa-circle"></i> ' + ucfirst( status[ 1 ] ) );

		        // Reset Ajax Status
		        temp.ajaxreq = false;

	        },

	        error: function( jqXHR, textStatus, errorThrown ) {

		        console.log( textStatus + errorThrown );
		        temp.ajaxreq = false; 	// Reset request state
		        $( obj ).html( temp.store );

	        }

        });


		// Clear temp variables
		delete obj;
		temp.store = null;

		return false; // Prevent other browser actions

	});


	/* Search Behaviour (re-writen from scratch to avoid JQuery UI
	=========================================================================================================================================== */
	function initializeSmartSearch() {
		$('.input-searchbar').on('keyup', function (e) {

			if (e.keyCode === 27) {
				$('.smart-search ul').toggle(false);
				$('.smart-search input').val('');
				return;
			}

			var search_value = $(this).val();

			// Clear old timer & create new one (prevents conflicts)
			if (temp.timer != null) {
				clearTimeout(temp.timer);
			}
			temp.timer = setTimeout(function () {

				// If not at least 2 letters clear up search
				if (search_value.length <= 2) {
					$('.smart-search').find('ul').addClass('search-hidden');
					return false;
				}

				// JSON AJAX Request
				$.getJSON("/system/misc/SmartSearch/SmartSearch.json.php?term=" + search_value, '', function (data, status, xhr) {
					// Clear current results
					$('.smart-search').find('ul').empty();

					// Check for ERRORs
					if (data.error != null) {

						$('.smart-search').find('ul').removeClass('search-hidden');
						$('.smart-search ul.dropdown-menu').html('<li><strong style="color: red;">ERROR: ' + data.error + '</strong></li>');
						return false;

					}


					// Loop through results
					$(data).each(function (index, result) {
						if (result.URL == '#')
							var html = '<li><a class="row"><div class="col-xs-12">' + result.LABEL + '</div></a></li>';                // This is GROUP
						else
							var html =
								'<li><a class="row" href="' + result.URL + '">' +
								(typeof result.IMAGE !== "undefined" ? '<div class="col-xs-3 col-md-2 text-left"><img src="' + result.IMAGE + '"/></div>' : '') +
								'<div class="' + (typeof result.IMAGE !== "undefined" ? 'col-xs-9 col-md-10' : 'col-xs-12') + '">' + result.LABEL + '</div>' +
								'</a></li>';   // This is LINK

						$('.smart-search ul').append(html).toggle(true);

					});

					// Now remove hidden status
					$('.smart-search').find('ul').removeClass('search-hidden');

				});

			}, 250);

		}).on('blur', function (e) {
			setTimeout(function () {
				$('.smart-search ul').toggle(false);
				$('.smart-search input').val('');
			}, 250);
		});
	}
	$(document).ready(initializeSmartSearch);
	$(window).resize(function(){
		setTimeout(initializeSmartSearch, 500);
	});



	/* Bootstrap Tooltips */
	$('[data-toggle="tooltip"]').tooltip();


	// END DOCUMENT READY
});


// Helpers
function ucfirst( str ) {
	str += '';
	var f = str.charAt( 0 )
		.toUpperCase();
	return f + str.substr( 1 );
}