// This here be 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(){
	$('#browseTabs').tabs();
	$('#catNavHiddenOptions').hide();
	$('#startDate').datepicker({ 
		dateFormat: 'yy-mm-dd',
		onSelect: function(){navDateUpdate('start_date');}}
	);
	$('input#endDate').datepicker({
		dateFormat: 'yy-mm-dd',
		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
	 */
	$('#catNavSearch #q').live('click', function(event) {
		event.preventDefault();
		event.stopPropagation();
		
		$(this).css('color', '#000000');

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

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

	/*
	 * 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
	 */
	$( '#catNavSearch' ).delegate('.hasDatepicker', 'click', function (event) {
		$(this).css('color', '#000000');
		
		if ( $(this).val() == 'Start' ) {
			$(this).next('.hasDatepicker').show();
		}
		
		$(this).val('');
	});
	
	function navDateUpdate(field){
		if (field == 'start_date'){
			calendarFilterParams.options.start_date = $('#startDate').val();
		}
		else if (field == 'end_date'){
			calendarFilterParams.options.end_date = $('#endDate').val();
		}
		var post = {};
		post.list = 'eventsList';
		post.objectType = 'Event';
		$('#' + post.list).html('<div class="loading"><p>Loading...<\/p><\/div>');
		updateBrowseList(post);
	}
	
	$( '#catNavSearchForm').live('submit', function (event) {
		event.preventDefault();
	});
	
	$( '#catNavSearchForm' ).delegate('#q', 'keypress', function (event) {
		if ( event.keyCode == 13 ) {
			calendarFilterParams.options.query = $(this).val();
			
			if ( $( '#catNavSearchForm' ).find('#startDate').val() != 'Start' ) {
				calendarFilterParams.options.start_date = $( '#catNavSearchForm' ).find('#startDate').val();
			}
			
			if ( $( '#catNavSearchForm' ).find('#endDate').val() != 'End' ) {
				calendarFilterParams.options.end_date = $( '#catNavSearchForm' ).find('#endDate').val();
			}

			var post = {};
			post.list = 'eventsList';
			post.objectType = 'Event';
			$('#' + post.list).html('<div class="loading"><p>Loading...<\/p><\/div>');
			updateBrowseList(post);
		}
	});
	
	$( '#catNavSearch' ).delegate('.hasDatepicker', 'focusout', function (event) {
		
	});

	$('#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() != 'Everything') {
                        url += '/q/' + $('#q').val();
                    }
		}
		if (location.href.indexOf('/browse') > 0 || location.href.indexOf('/my-account') > 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-account') > 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() != 'Everything') {
                                                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() != 'Everything') {
                        url += '/q/' + $('#q').val();
                    }
		}
	    if (location.href.indexOf('/browse') > 0 || location.href.indexOf('/my-account') > 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;
		}
	});

	$('.paginatorNav').live("click", function(event){
		var url = $(this).attr('href');
		if (url.indexOf('EventobjectsPage') > 0 || 
			url.indexOf('VenueobjectsPage') > 0 ||
			url.indexOf('PeopleobjectsPage') > 0
		){
			event.preventDefault();
			event.stopPropagation();
			var splitUrl = url.split('/');
			url = baseUrl + 'categories/browse/object-list/disableHelper/true';
			var post = {};
			for(var i=0; i < splitUrl.length; i++) {
				if (splitUrl[i] == 'EventobjectsPage'){
					post.EventobjectsPage = splitUrl[++i];
					post.list = 'eventsList';
					post.objectType = 'Event';
					post.type = 'Event';
				}
				if (splitUrl[i] == 'VenueobjectsPage'){
					post.VenueobjectsPage = splitUrl[++i];
					post.list = 'veuesList';
					post.objectType = 'Venue';
					url += '/VenueobjectsPage/' + splitUrl[++i];
					var list = 'venuesList';
					url += '/objectType/Venue';
				}
				if (splitUrl[i] == 'PeopleobjectsPage'){
					post.PeopleobjectsPage = splitUrl[++i];
					post.list = 'peopleList';
					post.objectType = 'People';
				}
				if (splitUrl[i] == 'type'){
					post.type = splitUrl[++i];
				}
				if (splitUrl[i] == 'category'){
					post.category = splitUrl[++i];
				}
				if (splitUrl[i] == 'calId' || splitUrl[i] == 'cal'){
					post.calId = splitUrl[++i];
				}
			}
			
			$('#' + post.list).html('<div class="loading"><p>Loading...<\/p><\/div>');
			post.disableHelper = true;
			post.filter = JSON.stringify(calendarFilterParams);
			url = baseUrl + 'categories/browse/object-list';
			$.post( 
				url,
				post,
				function(msg){
					$('#' + post.list).html(msg.html);
					$('.otherDates').hide();
					$('.people').hide();
					$('.peopleEvents').hide();
					$('.venueEvents').hide();
				},
				'json'
			);
		}
	});
	
	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();
			}
		});
	}
	
	$('.catNavAccordion').accordion({
		'fillSpace' : true
	});
	
	$('div#catItemList').delegate('div.featuredinfo', 'mouseover', function ( event ) {
		$(this).addClass('feature-hover');
	});
	
	$('div#catItemList').delegate('div.featuredinfo div.event_info_block', 'click', function ( event ) {
		if ( !$( event.target ).is('img') ) {
			var eventId = $(this).find('div.eventInfoBlockText div.eventId').text();

			$.get(baseUrl + 'events/index/info-dialog',
			{
				event : eventId
			},
			function ( result ) {
				$( 'div.eventInfoDialog' ).dialog({ 
					'autoOpen' : false, 
					'modal'       : true,
					'width'        : 600,
					'buttons'    : {
						"Open Events Page" : function () {
							window.location = baseUrl + 'events/' + eventId;
						}
					}
				});
				
				$( 'div.eventInfoDialog' ).html( result );
				$( 'div.eventInfoDialog' ).dialog( 'open' );
			}, 'html');
		}
	});
    
	$('div#catItemList').delegate('div.featuredinfo', 'mouseout', function ( event ) {
		$(this).removeClass('feature-hover');
	});
});

function updateBrowseList(post){
	var url        = baseUrl + 'categories/browse/list';
	post = post || {};
	post.filter = JSON.stringify(calendarFilterParams);
	post.disableHelper = true;
	$.post( url,
			post,
			function(msg){
				$('#catItemList').html(msg);
				$('#browseTabs').tabs();
				$('.otherDates').hide();
				$('.people').hide();
				$('.peopleEvents').hide();
				$('.venueEvents').hide();
			}
		);
}