// This is bat country
/*
var calendarFilterParams = {
	"calendars" : [
		{
			"id"	     : '',
			"name"       : '',
			"color"      : '',
			"display"    : false,
			"removable"  : false,
			"categories" : [],
			"events"     : [],
			"people"     : [],
			"places"     : [],
			"types"      : [{
					"cat_id"  : '',
					"type_id" : ''
					}],
			"query"      : '',
		}
	],
	"options" : {
		"query"      : '',
		"res_type"   : [],
		"start_date" : '',
		"end_date"   : ''
	}
}
*/
$(document).ready(function(){
	// add info tooltip to sidebar
	$('#filter-list .header .ui-icon').tooltip({
		effect: 'slide',
		position: 'bottom left',
		onShow: function() {
			this.getTip().find('a').colorbox({iframe:true, innerWidth:853, innerHeight:510});
		}
	});
	
	/*
	 * Setup UI Buttons
	 */
	$( '#applyFilters' ).button({
		disabled: true,
		icons: {
			primary: 'ui-icon-circle-check'
		}
	});
	$( '#saveFilters' ).button({
		icons: {
			primary: 'ui-icon-calendar'
		}
	});
		
	$( '.filter-options' ). button({
		icons: {
			primary: 'ui-icon-triangle-1-s'
		},
		text: false
	});
	
	$( '.search-go' ). button({
		icons: {
			primary: 'ui-icon-search'
		}
	});
	
	$( 'button.search-more' ).button({
		icons: {
			primary: 'ui-icon-circle-triangle-e'
		}
	});
	
	$( 'button.search-go' ).bind( 'click', function ( event ) {		
		if ( filterListSemaphore ) {
			event.stopPropagation();
			return false;
		}
		
		navDateUpdate('start_date');
		navDateUpdate('end_date');
		
		if ( $( '#search #q' ).val() != 'Search' ) {
			calendarFilterParams.options.query = $( '#search #q' ).val();
		}
		
		$( 'ul.catBrowseDefaultList, div#catNav' ).animate({
			'opacity' : 0.25
		}, 500);
		
		$('#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>');
		
		// Set the browse list serch term (visual cue) to the current query
		$('.search-term').text(calendarFilterParams.options.query);
		
		var post = {};
		updateBrowseList( post );
	});
	
	$( '.search-reset' ).bind( 'click', function ( event ) {
		$( '#search #q' ).get(0).style.color = '';
		$( '#search #q' ).val('Search');
		
		$( 'input#startDate' ).get(0).style.color = '';
		$( 'input#startDate' ).val('Start Date');
		
		$( 'input#endDate' ).get(0).style.color = '';
		$( 'input#endDate' ).val('End Date');
		
		$('#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>');
		
		calendarFilterParams.options.query = '';
		calendarFilterParams.options.start_date = '';
		calendarFilterParams.options.end_date = '';
		
		// clear all category filters
		$('div.catBrowseDefaultList .filter').each( function (index) {
			var tempId = $(this).data('id');
			var filterId = null;
			$.grep(calendarFilterParams.calendars, function(gindex, id) {
				if (gindex.id == tempId) {
					filterId = id;
					return true;
				}
			});
			
			
			$(this).children().removeClass('on');
			$(this).children().addClass('off');
			
			calendarFilterParams.calendars[filterId].display = false;
		});
		
		// Set the browse list serch term (visual cue) to the current query
		$('.search-term').text('stuff');
		
		var post = {}
		updateBrowseList( post );
	});
	
	$( '#save-dialog' ).dialog({
		width: 400,
		modal: true,
		closeOnEscape: false,
		autoOpen : false,
		overlay: {
			opacity: 0.5,
			background: 'black'
		}
	});	
			
	$( '#saveFilters' ).bind( 'click', function ( event ) {			
		/*
		 * There has to be a better way to do this.......
		 */
		var checkDialog = function () {
			$('#save-dialog').dialog('open');
		};
		
		loginCheck(checkDialog);
		
		$( 'button#saveFilters-form' ).button({
			icons: {
				primary: 'ui-icon-calendar'
			}
		});
		
		$('#saveForm #customCalendarName').val('');
		$( '#saveForm .calendarListing .listing' ).empty();
		
		var filter = calendarFilterParams.calendars;
		var noCats = true;
		$.each(filter, function (i) {
			if ( filter[i].display ) {
				$( '#saveForm .calendarListing .listing' ).append( '<li>' + filter[i].name + '</li>' );
				noCats = false;
			}
		});
		
		if ( noCats ){
			$('#save-dialog').dialog('close');
			alert('You must select at least one category before saving your calendar.');
		}
		
	});
	
	$( '#saveForm' ).delegate('#saveFilters-form', 'click', function ( event ) {
		var url = baseUrl + 'categories/browse/save-filter';
		
		post = {};
		post.name = $( '#saveForm #customCalendarName' ).val();
		post.filter = JSON.stringify(calendarFilterParams);
		post.disableHelper = true;
	
		$.post(
			url,
			post,
			function (msg) {
				if ( msg.status == "success" ) {
					$('#save-dialog').dialog('close');
					alert(msg.message);
				}
				else {
					alert(msg.message);
				}
			},
			'json'
		);
	});
	
	$('#browseTabs').tabs();
	$('#catNavHiddenOptions').hide();
	$('input#startDate').datepicker({ 
		dateFormat: 'mm/dd/yy',
		onSelect : function () {
			navDateUpdate('start_date');
		}
	});
	
	$('input#endDate').datepicker({
		dateFormat: 'mm/dd/yy',
		onSelect : function () {
			navDateUpdate('end_date');
		}
	});
   
	$('#toggleCatNavHiddenOptions').live('click', function(event) {
		event.preventDefault();
		event.stopPropagation();

		if ( $('#catNavHiddenOptions').css('display') == 'none' ) {
			$('#catNavHiddenOptions').show("fast");
			$(this).removeClass('ui-state-default');
			$(this).val('Less');
			$(this).addClass('ui-state-active');
		} else {
			$('#catNavHiddenOptions').hide("fast");
			$(this).removeClass('ui-state-active');
			$(this).val('More');
			$(this).addClass('ui-state-default');
		}
	});
    
	/*
	 * remove 'everything' from search box on click and change
	 * text color to black
	 */
	$('#search #q').live('click', function(event) {
		event.preventDefault();
		event.stopPropagation();
		
		$(this).css('color', '#000000');

		if($(this).val() == 'Search') {
			$(this).val('');
		}
	});

	/*
	 * if they didn't type anything in search box put 'Everything'
	 * back in the box and go back to default color.
	 */
	$( '#search' ).delegate('#q', 'focusout', function (event) {
		if ( $(this).val() == '' ) {
			$(this).get(0).style.color = '';
			$(this).val('Search');
		}
	});

	/*
	 * on click of start date we change text color to black... empty the
	 * value and if it is the fist click on start we display end
	 */
	$( '#search' ).delegate('.hasDatepicker', 'click', function (event) {
		$(this).css('color', '#000000');
		
		if ( $(this).val() == 'Start' ) {
			$(this).next('.hasDatepicker').show();
		}
		
		$(this).val('');
	});

	$( '#search' ).delegate( '#startDate', '', function ( event ) {
	});

	$( '#search' ).delegate( '#endDate', '', function ( event ) {
	});
	
	function navDateUpdate(field){
		if (field == 'start_date'){
			calendarFilterParams.options.start_date = $('#startDate').val();
		}
		
		if (field == 'end_date'){
			calendarFilterParams.options.end_date = $('#endDate').val();
		}
		
		$('#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({});
	}
	
	$( '#search').live('submit', function (event) {
		event.preventDefault();
	});
	
	$( '#search' ).delegate('#q', 'keypress', function (event) {
		if ( filterListSemaphore ) {
			event.stopPropagation();
			return false;
		}
		
		if ( event.keyCode == 13 ) {
			calendarFilterParams.options.query = $(this).val();
			
			if ( $( '#search-filters' ).find('#startDate').val() != 'Start' ) {
				calendarFilterParams.options.start_date = $( '#search-filters' ).find('#startDate').val();
			}
			
			if ( $( '#search-filters' ).find('#endDate').val() != 'End' ) {
				calendarFilterParams.options.end_date = $( '#search-filters' ).find('#endDate').val();
			}
			
			// Set the browse list serch term (visual cue) to the current query
			$('.search-term').text(calendarFilterParams.options.query);
			
			filterListSemaphore = true;
			$( 'ul.catBrowseDefaultList, div#catNav' ).animate({
				'opacity' : 0.25
			}, 500);

			var post = {};
			post.list = ['eventsList', 'venuesList'];
			$('#' + post.list).html('<div class="loading"><p>Loading...<\/p><\/div>');
			updateBrowseList(post);
		}
	});
	$( '#search' ).delegate( 'img.searchSubmit', 'click', function (event) {
		event.preventDefault();
		
		if ( filterListSemaphore ) {
			event.stopPropagation();
			return false;
		}
		var query = $( '#search #q' ).val();
		if(query === 'Search') query = '';
		calendarFilterParams.options.query = query;

			
		if ( $( '#search-filters' ).find('#startDate').val() != 'Start' ) {
			calendarFilterParams.options.start_date = $( '#search-filters' ).find('#startDate').val();
		}
		
		if ( $( '#search-filters' ).find('#endDate').val() != 'End' ) {
			calendarFilterParams.options.end_date = $( '#search-filters' ).find('#endDate').val();
		}

		var post = {};
		post.list = 'eventsList';
		post.objectType = 'event';
		updateBrowseList(post);
	});
	

	$('#toggleCatNavSearch').live('click', function(event){
		event.preventDefault();
		event.stopPropagation();
		$('#catNavSearch').toggle('slow');
	});
	
	$('#toggleCatNavDateFilter').live('click', function(event){
		event.preventDefault();
		event.stopPropagation();
		$('#catNavDateFilter').toggle('slow');
	});
	
	$('#toggleCatNavTypeFilter').live('click', function(event){
		event.preventDefault();
		event.stopPropagation();
		$('#catNavTypeFilter').toggle('slow');
	});
	
	$('#toggleCatNavTree').live('click', function(event){
		event.preventDefault();
		event.stopPropagation();
		$('#catNavTree').toggle('slow');
	});
	
	if ($("#catNavTree").length > 0){
		$("#catNavTree").treeview({
			persist: "cookie",
			collapsed: true,
			cookieId: 'catNav'
		});
	}
	

	$(".viewCategory").live('click', function(event){
		event.preventDefault();
		event.stopPropagation();
		$('#catItemList').html('<div class="loading"><p>loading...<\/p><\/div>');
		var url = $(this).attr('href');
		var splitUrl = url.split('/');
		url = '';
		for(var i=0; i < splitUrl.length; i++) {
			if (splitUrl[i] == 'category'){
				url += '/category/' + splitUrl[++i];
			}
			if (splitUrl[i] == 'calId' || splitUrl[i] == 'cal'){
				url += '/calId/' + splitUrl[++i];
			}
		}
		var types = [];
		if ($("#catNavTypeEvent:checked").val()){
			types[types.length] = 'event';
		}
		if ($("#catNavTypeVenue:checked").val()){
			types[types.length] = 'venue';
		}
		if ($("#catNavTypePeople:checked").val()){
			types[types.length] = 'people';
		}
		url += '/type/' + types.join('%2C');
		if ($('#startDate').val()){
			url += '/startDate/' + $('#startDate').val();
		}
		if ($('#endDate').val()){
			url += '/endDate/' + $('#endDate').val();
		}
		if ($('#q').val()){
                    if ($('#q').val() != 'Search') {
                        url += '/q/' + $('#q').val();
                    }
		}
		if (location.href.indexOf('/browse') > 0 || location.href.indexOf('/my') > 0 || location.href.indexOf('/search/') > 0 || location.href.indexOf('/') > 0){
			url = baseUrl + 'categories/browse/list/disableHelper/true' + url;
			$.ajax({
				url: url,
				success: function(msg){	
					$('#catItemList').html(msg);
					$('.otherDates').hide();
					$('.people').hide();
					$('.peopleEvents').hide();
					$('.venueEvents').hide();
					$('#browseTabs').tabs();
				}
			});
		}
		else{
			url = baseUrl + 'categories/browse/index' + url;
			window.location = url;
		}
	});
	
	var catNavTypeCheckboxLock = [];
	$(".catNavTypeCheckbox").live('click', function(event){
	    if (location.href.indexOf('/browse') > 0 || location.href.indexOf('/my') > 0 || location.href.indexOf('/search') > 0  || location.href.indexOf('/') > 0){
			if ($(this).attr('id') == 'catNavTypeEvent'){
				var list = $('#EventCatBrowseList');
				var type = 'Event';
				var tabname = 'Events';
			}
			else if($(this).attr('id') == 'catNavTypeVenue'){
				var list = $('#VenueCatBrowseList');
				var type = 'Venue';
				var tabname = 'Places';
			}
			else if($(this).attr('id') == 'catNavTypePeople'){
				var list = $('#PeopleCatBrowseList');
				var type = 'People';
				var tabname = 'People';
			}
			
			if ( list.length > 0 ){
				list.toggle('slow');
				list.focus();
				var index = $('#browseTabs > ul a').index($("a[href=#browse"+type+"Tab]")[0]);
				$('#browseTabs').tabs('remove', index);
			}
			else{
				// this little lock scheme keeps people from clicking a checkbox over and over and loading a bunch
				// of crap we don't really want on a page
				if (catNavTypeCheckboxLock[type]){
					event.preventDefault();
					event.stopPropagation();
				}
				else{
					catNavTypeCheckboxLock[type] = 1;
					
					$('#browseTabs').tabs('add', '#browse'+type+'Tab', tabname);
					
					$('#browse'+type+'Tab').prepend('<div id="tmpLoading" class="loading"><p>loading...<\/p><\/div>');
					url = baseUrl + 'categories/browse/object-list/disableHelper/true/displayDiv/true';
					if ($('#catItemListCalId').val()){
						url += '/calId/' + $('#catItemListCalId').val();
					}
					if ($('#catItemListCategory').val()){
						url += '/category/' + $('#catItemListCategory').val();
					}
					if ($('#startDate').val()){
						url += '/startDate/' + $('#startDate').val();
					}
					if ($('#endDate').val()){
						url += '/endDate/' + $('#endDate').val();
					}
					if ($('#q').val()){
						if ($('#q').val() != 'Search') {
							url += '/q/' + $('#q').val();
						}
					}
					url += '/objectType/' + type;
					$.getJSON(url,
						{},
						function(msg){
							$('#tmpLoading').remove();
							$('#browse'+type+'Tab').prepend(msg.html);
							$("a[href=#browse"+type+"Tab]").html(tabname+' ('+msg.count+')');
							$('.otherDates').hide();
							$('.people').hide();
							$('.peopleEvents').hide();
							$('.venueEvents').hide();
							list.show('slow');
							catNavTypeCheckboxLock[type] = 0;
						}
					);
				}
			}
		}
	});
	
	$(".catNavSubmit").live('click', function(event){
		event.preventDefault();
		event.stopPropagation();
		$('#catItemList').html('<div class="loading"><p>loading...<\/p><\/div>');
		url = '';
		var types = [];
		if ($("#catNavTypeEvent:checked").val()){
			types[types.length] = 'event';
		}
		if ($("#catNavTypeVenue:checked").val()){
			types[types.length] = 'venue';
		}
		if ($("#catNavTypePeople:checked").val()){
			types[types.length] = 'people';
		}
		url += '/type/' + types.join('%2C');
		if ($('#startDate').val()){
			url += '/startDate/' + $('#startDate').val();
		}
		if ($('#endDate').val()){
			url += '/endDate/' + $('#endDate').val();
		}
		if ($('#q').val()){
                    if ($('#q').val() != 'Search') {
                        url += '/q/' + $('#q').val();
                    }
		}
		
	    if (location.href.indexOf('/browse') > 0 || location.href.indexOf('/my') > 0 || location.href.indexOf('/search/') > 0  || location.href.indexOf('/') > 0){
			url = baseUrl + 'categories/browse/list/disableHelper/true' + url;
			$.ajax({
				url: url,
				success: function(msg){	
					$('#catItemList').html(msg);
					$('.otherDates').hide();
					$('.people').hide();
					$('.peopleEvents').hide();
					$('.venueEvents').hide();
					$('#browseTabs').tabs();
				}
			});
		}
		else{
			url = baseUrl + 'categories/browse/index' + url;
			window.location = url;
		}
	});

	// make pagination work ajaxily
	$('.paginator a').live("click", function(event){
		event.preventDefault();
		event.stopPropagation();

		var container = $(this).parents('[id$=List]:first');
		var url = $(this).attr('href');
		var post = {
			filter : JSON.stringify(calendarFilterParams)
		}

		$.post(
			url,
			post,
			function(response){
				container.html(response);
				$('.otherDates').hide();
				$('.people').hide();
				$('.peopleEvents').hide();
				$('.venueEvents').hide();

				// TODO Either fix or remove
//				$('#eventsList .featuredSelectable').StickyHeaders({
//					header : '[id^="group_date"]'
//				});
//
//				$('#venuesList .featuredSelectable').StickyHeaders({
//					header : '[id^="group_header"]'
//				});
//
//				$('#peopleList .featuredSelectable').StickyHeaders({
//					header : '[id^="group_header"]'
//				});
			}
		);

		container.html('<div class="loading"><p>Loading...<\/p><\/div>');
	});
	
	var tryLoadType = false;
	if (
		$('#catItemListPageBoolean').val() &&
		!($('#EventCatBrowseList').html()) &&
		!($('#PeopleCatBrowseList').html()) &&
		!($('#VenueCatBrowseList').html())
	){
		tryLoadType = true;
	}

	if (tryLoadType){
		var url = baseUrl + 'categories/browse/list/disableHelper/true';
		if ($('#catItemListCalId').val()){
			url += '/calId/' + $('#catItemListCalId').val();
		}
		if ($('#catItemListCategory').val()){
			url += '/category/' + $('#catItemListCategory').val();
		}
		if ($('#catItemListType').val()){
			var type = $('#catItemListType').val();
			url += '/type/' + type;
		}
		$('#catItemList').html('<div class="loading"><p>loading...<\/p><\/div>');
		$.ajax({
			url: url,
			success: function(msg){
				$('#catItemList').html(msg);
				$('.otherDates').hide();
				$('.people').hide();
				$('.peopleEvents').hide();
				$('.venueEvents').hide();
				$('#browseTabs').tabs();
			}
		});
	}
	
	$( 'div#catItemList') .delegate( 'a.adjust25', 'click', function ( event ) {
		$( 'a.adjust50' ).css('font-weight', 'normal');
		$( 'a.adjust100' ).css('font-weight', 'normal');
		$( this ).css('font-weight', 'bold');
		
		var post = {};
		post.pagesize = 25;
		updateBrowseListNumber( post );
		
		if ( $(event.target).is('a') ) {
			return false;
		}
	});
	
	$( 'div#catItemList') .delegate( 'a.adjust50', 'click', function ( event ) {
		$( 'a.adjust25' ).css('font-weight', 'normal');
		$( 'a.adjust100' ).css('font-weight', 'normal');
		$( this ).css('font-weight', 'bold');
		
		var post = {};
		post.pagesize = 50;
		updateBrowseListNumber( post );
		
		if ( $(event.target).is('a') ) {
			return false;
		}
	});
	
	$( 'div#catItemList') .delegate( 'a.adjust100', 'click', function ( event ) {
		$( 'a.adjust25' ).css('font-weight', 'normal');
		$( 'a.adjust50' ).css('font-weight', 'normal');
		$( this ).css('font-weight', 'bold');
		
		var post = {};
		post.pagesize = 100;
		updateBrowseListNumber( post );
		
		if ( $(event.target).is('a') ) {
			return false;
		}
	});
});

function updateBrowseListNumber ( post ) {
	$('#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>');
	
	// save currently selected tab
	var selected = $('#browseTabs').tabs('option', 'selected');
	
	filterListSemaphore = true;
	var url = baseUrl + 'categories/browse/list';
	
	post = post || {};
	post.type = ['event', 'venue', 'people'];
	post.filter = JSON.stringify(calendarFilterParams);
	
	$.post (
		url,
		post,
		function ( data ) {
			$( '#catItemList' ).html( data );
			tabs = $( '#browseTabs' ).tabs({selected: selected});
			filterListSemaphore = false;
		}
	);
}

/**
 * Updates all 3 tabs on front page. This method is called on initial page load
 * and also whenever filter selection is changed.
 *
 * @param array post post parameters
 */
function updateBrowseList(post){
	filterListSemaphore = true;
	var url        = baseUrl + 'categories/browse/list';
	
	post = post || {};
	post.filter = JSON.stringify(calendarFilterParams);
	post.type = ['event', 'venue', 'people'];
	post.region = $('#catRegion').val();
	
	$.post(url, post, function(msg){
		$('#catItemList').html(msg);

		$('#browseTabs').tabs();
		$('.otherDates').hide();
		$('.people').hide();
		$('.peopleEvents').hide();
		$('.venueEvents').hide();
		filterListSemaphore = false;

		$( '#addFilters' ).button('enable');
		$( 'button#saveFilters' ).button('enable');

		// Refresh the ads
		window.ads.refresh();
	})
	.error(function(){
		alert('There was an error performing your search. Please check your input and try again.');
		filterListSemaphore = false; 
	});
}

/**
 * Renders the default filter list.
 *
 * @param array post post parameters
 */
function updateFilterList(post) {
	var url = baseUrl + 'categories/browse/defaults';
	
	post.filter = JSON.stringify(calendarFilterParams);
	post.disableHelper = true;
	
	$.post(url,	post, function (data) {
		$( '.catNavDefaultList' ).removeClass('loading');
		$( '.catNavDefaultList' ).html(data);
	});
}


$(document).ready(function(){
	$( '#catItemList' ).html("<div class='loading' style='padding-top:40px;'>Loading Content</div>");
	updateFilterList({});

});
 
function Search () {
	var settings = {
		'filterSemaphore' : false,
		'ui' : {
			'buttons' : {
				'add-filters'    : {
					'selector'    : '#addFilters',
					'icon'        : 'ui-icon-circle-plus',
					'text'        : true
				},
				'apply-filters'  : {
					'selector'    : '#applyFilters',
					'icon'        : 'ui-icon-circle-check',
					'text'        : true
				},
				'filter-options' : {
					'selector'    : '.filter-options',
					'icon'        : 'ui-icon-triangle-1-s',
					'text'        : false
				},
				'search-go'      : {
					'selector'    : '.search-go',
					'icon'        : 'ui-icon-search',
					'text'        : true
				},
				'search-reset'   : {
					'selector'    : '.search-reset',
					'icon'        : 'ui-icon-refresh',
					'text'        : true
				}
			}
		}
	};

	var _search    = $('#search');
	var _query     = $('#search #q');
	var _startDate = $('#search-filters #startDate');
	var _endDate   = $('#search-filters #endDate');
	
	var _initUI = function () {
		// Initialize each of the buttson
		$.each( settings.ui.buttons, function ( key, value ) {
			$( value.selector ).button({
				icons : {
					primary : value.icon
				},
				text : value.text
			});
		});

		// Initialize button event bindings
		$( settings.ui.buttons.search-go.selector ).bind( 'click', function ( event ) {
			if ( settings.filterSemaphore ) {
				event.stopPropagation();
				return false;
			}


		});
	};


	// Priviledged Functions
	// ---------------------
	//
	// @returns the user input for a query
	this.getQuery     = function () {
		return _query.val();
	};

	// @returns the user selected start date filter
	this.getStartDate = function () {
		return _startDate.val();
	};

	// @returns the user selected end date filter
	this.getEndDate   = function () {
		return _endDate.val();
	};

	this.init = (function () {
	})();
}

