var xg = Ext.grid;
var xd = Ext.data;
var xu = Ext.util;

// Hold on to our stores - These are assigned in browse.js
// and search.js
var store_objs = new Object();
var filter_stores = new Object();
	
var existing_filters = {};

var using_preferred_filters = false;

var preferred_url = ALBase.make_uri('/user/contentfilters');

Ext.onReady(function(){
	if((typeof param_filters != 'undefined') && param_filters > ''){
		existing_filters = param_filters.evalJSON();
	}
});

var grouping_view =  new xg.GroupingView({
	forceFit:		false,
	autoFill:		false,
	showGroupName: 		false,
	enableNoGroups:		false,
	deferEmptyText:		false,
	startCollapsed:		true,
	hideGroupedColumn:	true,
	scrollOffset:		0,
	groupTextTpl:		'{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
});

// Utility function to determine the name
// of the filter. Filters have different names
// on the Tutorials and Projects page so this 
// just figures out where we are
function _get_general_filter(filter){
	 var f = filter.split('_');
	 f.shift();
     return f.join('_');
}

function preferred_filters_checkbox(text,id){
	var empty_text =  'View Only Preferred';
	var elem_id = 'use_preferred_filters';

    	if(text > ''){
     		empty_text = text;
	}

	if(id > ''){
     		elem_id = id;
	}

	var checkbox = '';

	if(has_preferred_filters && !is_visitor){
		checkbox = filters_checkbox = {
			xtype: 'checkbox',
			name: 'use_preferred_filters',
			id: elem_id,
			hideLabel: true,
			checked: use_preferred_filters,
			boxLabel: text,
			handler: function(chkbox,checked){
				filter_filters(checked);
				apply_filters();
			}
		};
	}

	return checkbox;
}

// Apply the filter of the elem passed.  This loops
// through all the records and all the filters, returning
// true to the records that match all filter criteria.
function apply_filters(){
	var the_grid = Ext.getCmp('results_grid');

	if(the_grid){
		var the_store = the_grid.getStore();
		if(the_grid.getXType() == 'grid'){
			the_grid.loadMask.show();
			the_grid.suspendEvents();
		}
		var filter_count = 0;
		var total_count = 0;
		var has_filters = false;
		if(the_store){
			// Reset all the filters
			the_store.clearFilter();
			total_count = the_store.getCount();

			// Get all the filter values
			var current_filters = new Object;
			var filter_boxes = $$('.filter_select').pluck('id');
			Ext.each(filter_boxes,function(filter){
				// Get the combobox associated with the filter we are looking at.
				var filter_id = filter + '_combo';

				// Try to fetch ExtJs combo box to test the filter
				var filter_combo = Ext.getCmp(filter_id);
				
				// Only continue if filter actually exists on page
				if(filter_combo){
					// Grab the current value of the filter
					var current_value = filter_combo.getValue();
					if(current_value > ''){
						current_filters[filter] = current_value;
						has_filters = true;
					}
				}
			});
				
			// Loop over each of the records. For each record, see if each filter
			// matches approriate matching column. If match, return true.
			if(has_filters || using_preferred_filters){
				the_store.filterBy(function(record,id){
					// Get the values from each of the filters and compare
					// to this record
					var include_row = true;

					// Check if this has a preferred filter
					if(using_preferred_filters){
						// Default to not include a row
						include_row = false;

						// Platforms
						if(preferred_filters.platform.length > 0){
							Ext.each(record.get('platforms_id'),function(platform_id){
								if(preferred_filters.platform.indexOf(platform_id) >= 0){
									include_row = true;
									filter_count++;
								}
							});
						}

						// Applications
						if(preferred_filters.application.length > 0){
							Ext.each(record.get('app_id'),function(app_id){
								if(preferred_filters.application.indexOf(app_id) >= 0){
									include_row = true;
									filter_count++;
								}
							});
						}
						
						// Applications for Platforms
						var app_ids = $H(preferred_filters.app_platforms).keys();
						if(app_ids.length > 0){
							Ext.each(app_ids,function(a_id){
								Ext.each(record.get('app_id'),function(app_id){
									if(app_id == a_id){
										Ext.each(record.get('platforms_id'),function(platform_id){
											if(preferred_filters.app_platforms[a_id].indexOf(platform_id) >= 0){
												include_row = true;
												filter_count++;
											}
										});
									}
								});
							});
						}
					}

					if(include_row){
						Ext.each($H(current_filters).keys(),function(filter){
								// If we have already marked this row as false we don't do any more checks
								if(include_row){
									var current_value = current_filters[filter];
									// Adjust for filter names. Search and Browse have different
									// names for the dataindex, so we make a call out to adjust_filter_name
									// which exists in two places, once for search and once for browse
									filter = adjust_filter_name(filter);

									var record_value = record.get(filter);

									if(typeof record_value == 'object'){
										var either_true = false;
										$A(record_value).each(function(val){
											if(!either_true){
												// Test if record matches current_value of filter
												var record_re = _get_re(current_value); 
												var is_match = record_re.test(val);

												if(is_match){
													either_true = true;
												}
											}
										});
										if(!either_true){
											include_row = false;
										}
									} else {
										// Test if record matches current_value of filter
										var record_re = new RegExp(current_value,'i');
										var is_match = record_re.test(record_value);

										if(!is_match){
											include_row = false;
										}
									}
								}
						});
					}
					return include_row;
				});
			}
		}
		set_title_count(filter_count,total_count);
		if(the_grid.getXType() == 'grid'){
			the_grid.resumeEvents();
			the_grid.loadMask.hide();
		}
	}
}

function set_title_count(filter_count,store_total){
	// 21st Projects don't show tutorial count
	if(current_page == 'projects_21'){
     	return;
	}
	var the_grid = Ext.getCmp('results_grid');
	var total = 0;
	var current = the_grid.getStore().getCount();

        // Fix for array indices
        store_total++;
        filter_count++;
        current++;

	var current_title = the_grid.title;
	if(typeof current_title == 'undefined'){
     	current_title = the_grid.ownerCt.title;
	}
	current_title = current_title.substring(0,current_title.indexOf(':'));
	var new_title = current_title + ": " + current + " of ";

	if(using_preferred_filters){
		new_title += filter_count;
		new_title += ' (filtered ' + (parseInt(store_total) - parseInt(filter_count)) + ' non-preferred)';
	} else {
		new_title += store_total;
		if(current != store_total){
			new_title += ' (filtered)';
		}
	}
	if(typeof the_grid.title == 'undefined'){
		the_grid.ownerCt.setTitle(new_title);
	} else {
		the_grid.setTitle(new_title);
	}
}

// Build an ExtJs combobox filter.  
var filters_selects = new Object();
function _build_filter_select(params){

	var filters_url = ALBase.make_uri('/filters');

	var root_node 	= params.root_node; 
	
	var input_id 		= params.input_id;
	var empty_text 		= params.empty_text;
	var subfilter 		= params.subfilter;  // Should be has_subfilter
	var is_subfilter	= params.is_subfilter ? true : false;
	var is_disabled		= params.is_disabled ? true : false;

	var store = new Ext.data.JsonStore({
		url: 			filters_url,
		autoDestroy: 	true,
		storeId: 		input_id + '_store',
		baseParams: 	{
         	root_node: 	root_node
		}
	});

	if(is_subfilter){
		// If parent has a value, enable
		var version_id = input_id + '_combo';
		var app_id = version_id.replace('version','applications');
		var app_combo = Ext.getCmp(app_id);
		var app_name = app_combo.getValue();

		if(app_name > ''){
			is_disabled = false;
		}
	}

	var combo = new Ext.form.ComboBox({
		xtype: 		'combo',
		store: 		store,
		displayField:	'name',
		forceSelection: true,
		typeAhead: 	true,
		mode: 		'local',
		anyMatch:	true,
		triggerAction: 	'all',
		listWidth: 	'500',
		lazyRender: 	true,
		emptyText: 	empty_text,
		selectOnFocus:	true,
		applyTo: 	input_id,
		id: 		input_id + '_combo',
		lastQuery: 	'',
		disabled: 	is_disabled,
		title: 		'Start typing to show matching filters.',
		listeners: 	{
			'blur': function(filter_combo){
				filter_combo.collapse();
			},
         		'select': function(filter_combo,filter_record,idx){
				// Apply filters
				apply_filters();
			},
			scope: this
		}
	});

	// If we are a subfilter we want our store to be filtered
	// according to our parents value. Our parent is in charge
	// of enabling/disabling us so we filter on enable.
	if(is_subfilter){
		combo.on('disable',function(cmp){
			// Force a new request if not a subfilter
			cmp.store.clearFilter();
			return;
		});
		combo.on('focus',function(filter_combo){
			
            		// Lookup associated applications
			var app_id = filter_combo.id.replace('version','applications');
			var app_combo = Ext.getCmp(app_id);
			var app_name = app_combo.getValue();

			if(app_name > ''){
				filter_combo.store.filterBy(function(record,id){
					var include_row = false;

					// Make sure the version's app matches
					// the selected app
					if(record.get('app') == app_name){
                                        	include_row = true;
					}

					// If the version's app matches the selected app
					// and we are using preferred filters, make sure
					// the version's id matches a preferred id otherwise
					// uninclude it
					if(include_row && using_preferred_filters){
						var app_filters	= preferred_filters.application;
						var version_filters = preferred_filters.app_platforms;

						var rec_id = record.get('id');
						
						// Mark false if not allowed by apps
						if(app_filters.indexOf(rec_id) < 0){
							include_row = false;
						}
						// But add back in if allowed by apps->version
						if(typeof version_filters[rec_id] != 'undefined' && version_filters[rec_id].length > 0){
							include_row = true;
						}
					}

					return include_row;
				});
			} else {
            			// If app_name is empty we shouldn't be here so
				// we disable and exit
				filter_combo.disable();
				return;
			}

			filter_combo.doQuery();
			filter_combo.expand();
			return;
		});
	} else {
		combo.on('beforequery',function(qe){
			// Force a new request if not a subfilter
			if(!using_preferred_filters){
				delete qe.combo.lastQuery;
			}
		});
		combo.on('focus',function(filter_combo){
			filter_combo.doQuery();
		});
	}

	// Apply various events for combos that have a subfilter
	if(subfilter){
		combo.on('focus',function(filter_combo){
			Ext.getCmp(subfilter + '_combo').disable();
		});
		// Delete any value from the subfilter and make sure it is
		// enabled
		combo.on('select',function(filter_combo,filter_record,idx){
			Ext.getCmp(subfilter + '_combo').clearValue();
			Ext.getCmp(subfilter + '_combo').enable();
		});
	}

	store.suspendEvents();
	store.load();
	store.resumeEvents();
	Ext.get(input_id).addClass('filter');

	// Attach the clear event
	Ext.get(input_id + '_clear').on('click',function(){
		combo.setValue('');

		if(subfilter){
			filters_selects[subfilter].combo.setValue('');
			filters_selects[subfilter].combo.disable();
		}
		apply_filters();
	});

	// Apply any filters to this combo if they exist on the page
	if(existing_filters[input_id]){
		combo.enable();
		combo.setValue(existing_filters[input_id]);
	}
	
	// Store these so we can call them outside this function
	filters_selects[input_id] = { combo: combo };
}

function _get_default_name(filter_name){
	return filter_name.substr(0,1).toUpperCase() + filter_name.substr(1) + '...';
}

function _get_filter_id(filter){
	return filter + '_search_filter';
}

function _get_filter_name(filter){
	return filter.split('_')[0];
}

function _get_select_value(filter_name){
       return $(filter_name).value;
}

function filter_tutorial_filters(checked){
	if(checked){
		do_preferred_filter_filters('browse_tutorials');
	} else {
		clear_filter_filter('browse_tutorials');
	}
}

function filter_project_filters(checked){
	if(checked){
		do_preferred_filter_filters('browse_projects');
	} else {
		clear_filter_filter('browse_projects');
	}
}

function filter_search_filters(checked){
	if(checked){
		do_preferred_filter_filters('search_filter');
	} else {
		clear_filter_filter('search_filter');
	}
}

function do_preferred_filter_filters(type){
	var app_combo 		= Ext.getCmp('applications_' + type + '_combo');
	var version_combo 	= Ext.getCmp('version_' + type + '_combo');
	var platforms_combo 	= Ext.getCmp('platforms_' + type + '_combo');

	if((typeof app_combo == 'undefined') || (typeof platforms_combo == 'undefined') || (typeof version_combo == 'undefined')){
         	return;
	}

	// Clear out any existing values before we give preferred
	//app_combo.clearValue();
	//platforms_combo.clearValue();

	var app_store 		= app_combo.store;
	//var version_store 	= version_combo.store;
	var platforms_store 	= platforms_combo.store;

	var app_value 		= app_combo.getValue();
	//var version_value 	= version_combo.getValue();
	var platforms_value 	= platforms_combo.getValue();

	var app_filters 	= preferred_filters.application;
	var version_filters 	= preferred_filters.app_platforms;
	var platforms_filters 	= preferred_filters.platform;

	if(app_filters.length > 0){
		app_store.filterBy(function(record,id){
			var include_row = false;
			var rec_ids = record.get('id');

                        Ext.each(rec_ids,function(rec_id){
				if(app_filters.indexOf(rec_id) >= 0){
					include_row = true;
				}
				if(typeof version_filters[rec_id] != 'undefined' && version_filters[rec_id].length > 0){
					include_row = true;
				}
			});

			// Clear the value if this row is not preferred but matches currently selected
                        if((!include_row) && (app_value == record.get('name'))){
				app_combo.clearValue();
			}

			return include_row;
		});
	}
	if(platforms_filters.length > 0){
		platforms_store.filterBy(function(record,id){
			var include_row = false;
			var rec_id = record.get('id');
			if(platforms_filters.indexOf(rec_id) >= 0){
				include_row = true;
			}
			return include_row;
		});
	}

	using_preferred_filters = true;
}

function clear_filter_filter(type){
	var app_combo 		= Ext.getCmp('applications_' + type + '_combo');
	var version_combo 	= Ext.getCmp('version_' + type + '_combo');
	var platforms_combo 	= Ext.getCmp('platforms_' + type + '_combo');

	if((typeof app_combo == 'undefined') || (typeof platforms_combo == 'undefined') || (typeof version_combo == 'undefined')){
         	return;
	}
	
	// Clear out any existing values before we give preferred
	app_combo.clearValue();
	version_combo.clearValue();
	platforms_combo.clearValue();

	var app_store 		= app_combo.store;
	var version_store 	= version_combo.store;
	var platforms_store 	= platforms_combo.store;

	app_store.clearFilter();
	version_store.clearFilter();
	platforms_store.clearFilter();

	using_preferred_filters = false;
}

function _get_re(val){
	// Scrub some offending chars we have
	val = val.replace('(','\\(').replace(')','\\)');

	var re = new RegExp(val,'i');

	return re;
}

