var filterListSemaphore = false;

$(document).ready(function(){
    
	/*
    $.ajax({
        url : baseUrl + 'categories/browse/defaults',
        type : 'GET',
        data : {
            filter : JSON.stringify(calendarFilterParams)
        },
        success : function ( html ) {
            $( '.catNavDefaultList' ).removeClass('loading');
            $( '.catNavDefaultList' ).html( html );
        }
    });
    */

	$('#addFilters').tooltip({effect: 'slide', position: 'bottom left'});

	$('#category-dialog').dialog({
		autoOpen: false,
		width: 300,
		height: 600,
		modal: true,
		closeOnEscape: false,
		overlay: {
			opacity: 0.5,
			background: 'black'
		},
		open: function(event, ui) {
			if(!$('.catTree').hasClass('treeview')){
				$('.catTree').treeview({
					collapsed: true
				});
			}
			$( '.catTree .catTopCat' ).css('font-weight', 'bold');
		},
		buttons: {
			"Add": function() {
				updateCategories($(this));
			}
		}
	});
	
$('body').bind('click', function ( event ) {
	if ( $(event.target).closest('.filter-sub-controls').length == 0 ) {
		$('.filter-sub-controls').hide();
	}
});
// Initial check to determine the state of the filter list
$( 'div.catNavDefaultList .show' ).attr('disabled', true);
	
	$( 'div#filter-list' ).delegate( '#addFilters', 'click', function ( event ) {
		$('#category-dialog').dialog('open');
	});
		
	$( '#applyFilters' ).click(function ( event ) {
		if ( filterListSemaphore ) {
			event.stopPropagation();
			return false;
		}
		
		$('#eventsList').html('<div class="loading"><p>Loading...<\/p><\/div>');
		$('#venuesList').html('<div class="loading"><p>Loading...<\/p><\/div>');
		$('#peopleList').html('<div class="loading"><p>Loading...<\/p><\/div>');
		
		/*
		 * Disable the forms and start the semaphore...
		 */
		$( 'button#saveFilters' ).button('disable');
		$(this).blur().button('disable').removeClass('ui-state-highlight ui-state-hover');
		
		
		var post = {};
		updateBrowseList(post);
	});
	
	$( 'div.catNavDefaultList' ).delegate( '.filter-options', 'click', null, function (event) { 
		if ( filterListSemaphore ) {
			event.stopPropagation();
			return false;
		}
		var position = $(this).position();
		$('.filter-sub-controls').hide();
		$(this).parent().find('.filter-sub-controls').show();
				
		// Prevent that crud from bubbling up to the container...........
		return false;
	});
	
	$( 'div.catNavDefaultList' ).delegate( '.showOnly', 'click', null, function ( event ) {	
		var currentId = $(this).parents('.filter').children().attr('id').split('filter_')[1];
		var id = 'id';
		
		$('div.catBrowseDefaultList .filter').each( function (index) {
			var tempId = $(this).children().attr('id').split('filter_')[1];
			var filterId = null;
			$.grep(calendarFilterParams.calendars, function(gindex, id) {
				if (gindex.id == tempId) {
					filterId = id;
					return true;
				}
			});
			
			if ( tempId == currentId ) {
				$(this).children().removeClass('off');
				$(this).children().addClass('on');
				
				calendarFilterParams.calendars[filterId].display = true;
				
				return true;
			}
			
			$(this).children().removeClass('on');
			$(this).children().addClass('off');
			
			calendarFilterParams.calendars[filterId].display = false;
		});
		
		$( '.filter-sub-controls' ).hide();
		$( '#applyFilters' ).button('enable');
		
		$('#eventsList').html('<div class="loading"><p>Loading...<\/p><\/div>');
		$('#venuesList').html('<div class="loading"><p>Loading...<\/p><\/div>');
		$('#peopleList').html('<div class="loading"><p>Loading...<\/p><\/div>');
		
		
		$(this).blur().button('disable').removeClass('ui-state-highlight ui-state-hover');

		updateBrowseList({});
		
		if ( $(event.target).is('a') ) {
			return false;
		}

	});
	
	$( 'div.catNavDefaultList' ).delegate( '.showAllBut', 'click', null, function ( event ) {				
		var currentId = $(this).parents('.filter').children().attr('id').split('filter_')[1];
		var id = 'id';
		
		$('div.catBrowseDefaultList .filter').each( function (index) {
			var tempId = $(this).children().attr('id').split('filter_')[1];
			var filterId = null;
			$.grep(calendarFilterParams.calendars, function(gindex, id) {
				if (gindex.id == tempId) {
					filterId = id;
					return true;
				}
			});
			
			if ( tempId == currentId ) {
				$(this).children().removeClass('on');
				$(this).children().addClass('off');
				
				calendarFilterParams.calendars[filterId].display = false;
				
				return true;
			}
			
			$(this).children().removeClass('off');
			$(this).children().addClass('on');
			
			calendarFilterParams.calendars[filterId].display = true;
		});
		
		$( '.filter-sub-controls' ).hide();
		$( '#applyFilters' ).button('enable');
		
		$('#eventsList').html('<div class="loading"><p>Loading...<\/p><\/div>');
		$('#venuesList').html('<div class="loading"><p>Loading...<\/p><\/div>');
		$('#peopleList').html('<div class="loading"><p>Loading...<\/p><\/div>');
		
		$(this).blur().button('disable').removeClass('ui-state-highlight ui-state-hover');
	
		updateBrowseList({});
		
		if ( $(event.target).is('a') ) {
			return false;
		}
	});
	
	$( 'div.catNavDefaultList' ).delegate( '.addCatToCalendar', 'click', null, function ( event ) {
		event.stopPropagation();
		event.preventDefault();
		
		var currentId = $(this).parents('.filter').children().attr('id').split('filter_')[1];
		
		if ( currentId.match('cat') ) {
			currentId = currentId.split('_')[0];
		}
	});

	// Click binding for the everything filter
	// It is enabled by default, clicking on any other filter will disable it and
	// if the everything has been disabled reenabling it will disable everything
	$('#filter-everything').click( function ( event ) {
		if ( $(this).hasClass('off') ) {
			$(this).removeClass('off');
			$(this).addClass('on');
			
			// Iterate through the calendarFilters, update styles to disable everything, and modify the 
			// huge local filter object
			$.each(calendarFilterParams.calendars, function (i, calendar) {
				var $filter = $('#filter_' + calendar.id);
				$filter.removeClass('on');
				$filter.addClass('off');
				
				calendar.display = false;
			});

			// Highlight apply button
			$( 'button#applyFilters' ).button('enable').addClass('ui-state-highlight');
		}
	});
	
	/*
	 * Handles the case were a calendar class is clicked. Remove background styling and toggle proper classes.
	 * Also update the calendarFilterParams structure and post the results
	 */
	$( '.catNavDefaultList' ).delegate( '.filter-name', 'click', null, function ( event ) { 
		// Check to see if the list is locked. Return false and kill event
		if ( filterListSemaphore ) {
			event.stopPropagation();
			return false;
		}

		if ( !$( event.target ).is('button') ) {
			// Pull the search term out if it is set or reset it.
			if ( $( '#search #q' ).val() != 'Search' ) {
				calendarFilterParams.options.query = $( '#search #q' ).val();
			}
			else {
				calendarFilterParams.options.query = '';
			}

			$('#filter-everything').removeClass('on');
			$('#filter-everything').addClass('off');
			
			$(this).get(0).style.backgroundColor = '';
			$(this).removeClass( 'hover' );
			
			var parent = $(this).parent();
			var tempId = parent.attr('id').split('filter_')[1];
			var id = 'id';
			// This is some craziness. Read the jquery docs
			var filterId = null;
			$.grep(calendarFilterParams.calendars, function(index, id) {
				if (index.id == tempId) {
					filterId = id;
					return true;
				}
			});
						
			if (parent.hasClass('off')) {
				parent.removeClass('off');
				parent.addClass('on');
				calendarFilterParams.calendars[filterId].display = true;
			}
			else {
				parent.removeClass('on');
				parent.addClass('off');
				calendarFilterParams.calendars[filterId].display = false;
			}
			
			/*
			 * Update apply button to reflect changes
			 */
			$( 'button#applyFilters' ).button('enable')
				.addClass('ui-state-highlight');
		
			$('#eventsList').html('<div class="loading"><p>Loading...<\/p><\/div>');
			$('#venuesList').html('<div class="loading"><p>Loading...<\/p><\/div>');
			$('#peopleList').html('<div class="loading"><p>Loading...<\/p><\/div>');
		
			/*
			 * Disable the forms and start the semaphore...
			 */
			$( 'button#saveFilters' ).button('disable');
			$(this).blur().button('disable').removeClass('ui-state-highlight ui-state-hover');

			updateBrowseList({});
		}
	});
	
	function toggleViewButtons() {
		var filterLength = calendarFilterParams.calendars.length - 1;
		
		var enabledCount = 0;
		for ( cal = 1; cal < filterLength; cal++ ) {
			if ( calendarFilterParams.calendars[cal].display ) {
				enabledCount++;
			}
		}
		
		if ( filterLength == enabledCount ) {
			$( 'div.catNavDefaultList .show' ).attr('disabled', true);
			$( 'div.catNavDefaultList .hide' ).attr('disabled', false);
		} else if ( enabledCount == 0 ) {
			$( 'div.catNavDefaultList .hide' ).attr('disabled', true);
			$( 'div.catNavDefaultList .show' ).attr('disabled', false);
		} else if ( enabledCount > 0 ) {
			$( 'div.catNavDefaultList .hide' ).attr('disabled', false);
			$( 'div.catNavDefaultList .show' ).attr('disabled', false);
		}
	}
	
	function checkEnabledFilters () {
		var filterLength = calendarFilterParams.calendars.length - 1;
		
		var enabledCount = 1;
		for ( cal = 1; cal < filterLength; cal++ ) {
			if ( calendarFilterParams.calendars[cal].display ) {
				enabledCount++;
			}
		}
		
		return enabledCount;
	}
});

/**
 * Adds/removes categories from the filter list based on the checked/unchecked
 * state of items in the category dialog.
 */
function updateCategories(dialog) {
	var catcount = 1;
	var newHtml = '';
	var newCats = new Array();
	
	$('#category-dialog .catCheckBox:checked').each(function(i) {
		catcount++;
		var topCatName = $(this).parents('ul').find('.catTopCat').text();

		var subCatName = '';
		$(this).parents('li').each(function(i) {
			subCatName = $(this).children('label').text() + ' > ' + subCatName;
		});
		
		if (subCatName.length) {
			subCatName = subCatName.substr(0, subCatName.length-2);
		}
		
		/*
		 * Iterate over the calendars in the filterParam and determine if a 
		 * new calendar has already been added. If so, don't add it again.
		 * Keeps track of this by a bool flag 'present'
		 */
		var tempId = $(this).attr('cat');
		var present = false;
		$.each(calendarFilterParams.calendars, function ( key, value ) {
			var id = value.id.toString();
			
			if ( !id.match('cat') ) {
				return true;
			}
			
			if ( id.split('_')[0] == tempId ) {
				present = true;
			}
		});
		
		if ( !present ) {
			newCats[i] = $(this).attr('cat');
		}
	});
	
	$('#eventsList').html('<div class="loading"><p>Loading...<\/p><\/div>');
	$('#venuesList').html('<div class="loading"><p>Loading...<\/p><\/div>');
	$('#peopleList').html('<div class="loading"><p>Loading...<\/p><\/div>');
		
	/*
	 * Disable the forms and start the semaphore...
	 */
	$( 'button#saveFilters' ).button('disable');
	$(this).blur().button('disable').removeClass('ui-state-highlight ui-state-hover');

	var post = {};
	post.category = newCats;
	updateFilter(post, dialog);
	$('#applyFilters').button('enable').addClass('ui-state-highlight');
}

function updateFilter(post, dialog) {
	var url = baseUrl + 'categories/browse/append-filter';
	
	post.filter = JSON.stringify(calendarFilterParams);
	post.disableHelper = true;
	
	$(dialog).dialog('close');
	
	$.post(
		url,
		post,
		function (msg) {
			calendarFilterParams = msg;
			var post = {};
			post.list = 'eventsList';
			post.objectType = 'Event';
			//updateBrowseList(post);
			updateFilterList(post, dialog);
		},
		'json'
		);
}

function updateFilterList(post, dialog) {	
	var url = baseUrl + 'categories/browse/defaults';
	
	post.filter = JSON.stringify(calendarFilterParams);
	post.disableHelper = true;
	
	$( '.filter-options' ).button('disable');
	
	$.post(
		url,
		post,
		function (data) {
			$( 'div.catNavDefaultList' ).html(data);
			$( '.filter-options' ). button({
				icons: {
					primary: 'ui-icon-triangle-1-s'
				},
				text : false
			});
		}
		);

	updateBrowseList({});
}

