
var documentIsLoaded = false;
$(document).ready(function(){ documentIsLoaded = true; });

var Filter = 
{
	ignoreRequestId: true, // for debugging against a static JSON file
	requestId: 0,
	currentTab: 'overview',
    perfPeriod: 'month', // applies to performance tab only
    perfType: 'nav', // applies to performance tab only
	sortField: 'Name',
	sortDirection: 'asc',
	facetOptions: { },
	
	checkBrowserCapabilities: function()
	{
		try {
			// check for AJAX support
			if(!(window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest()))
				return;
			if(navigator.userAgent.match(/(MIDP|CLDC|BlackBerry)/))
				return;

			// indicate, via CSS, that the filter is supported
			$('body').addClass('filter-enabled');
		}
		catch(e) {
			// do nothing
		}
	},
	
	checkHistory: function()
	{	
		var locationHash = window.location.hash.replace(/^#/, '');
		if(locationHash != Filter.serializedState)
		{
			var state = Filter.createFilterStateFromQueryString(locationHash);
			Filter.sortField = state.sort || Filter.sortField;
			Filter.sortDirection = state.direction || Filter.sortDirection;
			Filter.currentTab = state.tab || Filter.currentTab;
			Filter.facetOptions = state.options;
			if(documentIsLoaded)
			{
				Filter.updateFilterCode();
				Filter.applyFacetState();
				Filter.requestUpdate(false);
			}			
		}
		Filter.serializedState = locationHash;
		setTimeout(Filter.checkHistory, 100);
	},
	
    getCurrentTab: function()
    {
        return this.currentTab;
    },

    getPerfPeriod: function()
    {
        return this.perfPeriod;
    },

	getPerfType: function()
	{
		return this.perfType;
	},
	
	getSortField: function()
	{
		return this.sortField;
	},
	
	sortBy: function(field)
	{
		this.sortDirection = (this.sortField == field && this.sortDirection == 'asc') ? 'desc' : 'asc';
		this.sortField = field;
		this.requestUpdate(true);
	},
	
	getSortDirection: function()
	{
		return this.sortDirection;
	},
	
	showTab: function(tab)
	{
		this.currentTab = tab;
		this.sortField = 'Name';
		this.sortDirection = 'asc';
		this.requestUpdate(true);
	},

	showPerformancePeriod: function(period)
	{
	    this.perfPeriod = period;

		// Chnage the sort field
		if ( this.sortField != 'Name' && this.sortField != 'Ticker' && 
				this.sortField != 'DailyObjective' &&
				this.sortField != 'InceptionDate' &&
				this.sortField != 'ExpenseRatio' &&
				this.sortField != 'NetExpense' ) {
			this.sortField = 'Name';
			this.sortDirection = 'asc';
		}
		_gaq.push(['_trackEvent', 'Performance Tab', 'Month or Quarter', period]);  
		this.requestUpdate(true);
	},

	showPerformanceType: function(type)
	{
	    this.perfType = type;

		// Chnage the sort field
		if ( this.sortField != 'Name' && this.sortField != 'Ticker' && 
				this.sortField != 'DailyObjective' &&
				this.sortField != 'InceptionDate' &&
				this.sortField != 'ExpenseRatio' &&
				this.sortField != 'NetExpense' ) {
			this.sortField = 'Name';
			this.sortDirection = 'asc';
		}
		_gaq.push(['_trackEvent', 'Performance Tab', 'Nav or Market Return', type]);  
		this.requestUpdate(true);
	},
		
	setFilterTemplate: function(path) 
	{ 
		this.filterTemplate = path;
	},

	setResultsTemplate: function(path)
	{
		this.resultsTemplate = path;
	},
	
	getInitCode: function()
	{
		return '<script type="text/javascript" src="/funds/filter?' +
				'sort=Name&direction=asc&' +
				'requestId=' + (++this.requestId) + '&' + 
				this.serializedState + '"></script>';
	},
	
	writeFilterCode: function()
	{
		return Bumble.Inline(this.filterTemplate, { filter: this });
	},
	
	writeResultsCode: function()
	{
		return Bumble.Inline(this.resultsTemplate, { filter: this });
		if(window.Disclaimers) { Disclaimers.Install(); }
	},
	
	updateFilterCode: function()
	{
		Bumble.Update($('#filter-products')[0], this.filterTemplate, { filter: this });
	},
	
	updateResults: function()
	{
		Bumble.Update($('#filter-results')[0], this.resultsTemplate, { filter: this });
		if(window.Disclaimers) { Disclaimers.Install(); }
	},
	
	applyFacetState: function()
	{
		$('#product-list input[type=checkbox]').removeAttr('checked');
		$('#product-list input.filter-item').each(function()
		{
			var group = this.name;
			var item = this.value;
			if(Filter.facetOptions[group] && Filter.facetOptions[group][item])
			{
				$(this).attr('checked', 'checked');
				Filter.refreshSubGroupForItem(this.id);
				Filter.refreshGroupForItem(this.id);
			}
		});
	},
	
	toggleGroup: function(id)
	{
		// toggle child boxes accordingly
		var checked = ($('#' + id + ':checked').val() != null);
		$('#group_' + id + ' input[type=checkbox]').each(function(){ this.checked = checked; });
		
		this.requestUpdate(true);
	},
		
	toggleSubGroup: function(id)
	{
		// toggle child boxes accordingly
		var checked = ($('#' + id + ':checked').val() != null);
		$('#subgroup_' + id + ' input[type=checkbox]').each(function(){ this.checked = checked; });
		
		// check parent group status
		var group = $('#' + id).closest('.group');
		if(group.find('input[type=checkbox]:not(:checked):not(.group-check)').val() == null)
			group.find('.group-check').attr('checked', 'checked');
		else
			group.find('.group-check').removeAttr('checked');
		
		this.requestUpdate(true);
	},
	
	toggleItem: function(id)
	{
		this.refreshSubGroupForItem(id);
		this.refreshGroupForItem(id);
		this.requestUpdate(true);
	},
	
	refreshSubGroupForItem: function(id)
	{
		var subGroup = $('#' + id).closest('.subgroup');
		if(subGroup.find('input[type=checkbox]:not(:checked):not(.subgroup-check)').val() == null)
			subGroup.find('.subgroup-check').attr('checked', 'checked');
		else
			subGroup.find('.subgroup-check').removeAttr('checked');
	},
	
	refreshGroupForItem: function(id)
	{
		var group = $('#' + id).closest('.group');
		if(group.find('input[type=checkbox]:not(:checked):not(.group-check)').val() == null)
			group.find('.group-check').attr('checked', 'checked');
		else
			group.find('.group-check').removeAttr('checked');
	},
	
	readFilterState: function()
	{
		var state = 
		{ 
			sort: Filter.sortField, 
			sortDirection: Filter.sortDirection, 
			tab: Filter.currentTab, 
			options: { } 
		};
		
		$('input.filter-item:checked').each(function()
		{
			var key = this.name;
			var value = this.value;
			if(!state.options[key]) { state.options[key] = { }; }
			state.options[key][value] = true;
		});
		
		return state;
	},	
	
	getObjectKeys: function(obj)
	{
		var keys = [ ];
		for(var key in obj) { keys.push(key); }
		return keys;
	},
	
	createQueryStringFromFilterState: function(state)
	{
		var queryPairs = [ ];
		if(state.sort) { 
			queryPairs.push('sort=' + state.sort); 
			_gaq.push(['_trackEvent', 'Fund Filter', 'Sort', state.sort]);  
		}
		if(state.sortDirection) {
			 queryPairs.push('direction=' + state.sortDirection); 
			_gaq.push(['_trackEvent', 'Fund Filter', 'Sort Direction', state.sortDirection]);
		}
		if(state.tab) { 
			queryPairs.push('tab=' + state.tab); 
			_gaq.push(['_trackEvent', 'Fund Filter', 'Tab', state.tab]);  
		}
		if(state.options) {
			for(var group in state.options) {
				queryPairs.push(group + '=' + this.getObjectKeys(state.options[group]).join(','));
				_gaq.push(['_trackEvent', 'Fund Filter', group, this.getObjectKeys(state.options[group]).join(',')]);
			}
		}	
		var queryString = queryPairs.join('&');

		return queryString;
	},
	
	createFilterStateFromQueryString: function(queryString)
	{
		var state = { };
		state.options = { };
		if(queryString.length > 0)
		{
			var queryPairs = queryString.split('&');		
			for(var i=0;i<queryPairs.length;i++)
			{	
				var keyValue = queryPairs[i].split('=');				
				if(keyValue.length > 1)
				{					
					state[keyValue[0]] = keyValue[1];					
					state.options[keyValue[0]] = { };
					var items = keyValue[1].split(',');
					for(var j=0;j<items.length;j++)
						state.options[keyValue[0]][items[j]] = true;
				}
			}
		}
		return state;
	},
	
	addHistory: function(queryString)
	{
		queryString = queryString || this.createQueryStringFromFilterState(this.readFilterState());
		// might need this code for IE6
		if(typeof document.body.style.maxHeight === "undefined")
			$('a#history-anchor').attr('name', queryString);
		this.serializedState = queryString;
		window.location.hash = '#' + queryString;
	},
	
	requestUpdate: function(updateHistory)
	{
		var queryString = this.createQueryStringFromFilterState(this.readFilterState());
		if(updateHistory) { this.addHistory(queryString); }
		var url = '/funds/filter?requestId=' + (++this.requestId) + '&' + queryString;
		$.getScript(url);
	},
	
	loadData: function(data)
	{	
		if(this.ignoreRequestId || data.requestId == this.requestId)
		{
			this.criteria = data.initialization;
			this.closingDate = data.closingDate;
			this.monthEffectiveDate = data.monthEffectiveDate;
			this.quarterEffectiveDate = data.quarterEffectiveDate;
			this.quarter = data.quarter;
			this.results = data.results;
			if(this.initialLoadComplete)
				this.updateResults();
			this.initialLoadComplete = true;
		}
	}
	
};

Filter.checkHistory();

