jQuery(document).ready(function($){

// todo: localize filter to this scope
window.filter = {
	flags: { },
	buttons: { },
	groups: { els: {}, datas: {}, spans:{}, anchors:{} },
	is: function( flag ) { return !!this.flags[flag]; },
	count: function( ) { return ( $H(this.flags).getValues().sum() % 3 ); },
	addButton: function( flag, el ) { if( !flag ) return; this.buttons[flag] = el; },
	addGroup: function( data, el ) {
		var id = data.group;
		delete data.group;
		this.groups.els[id] = el;
		this.groups.datas[id] = data;
		this.groups.spans[id] = el.find('span.count:first');
		this.groups.anchors[id] = el.find('a:first');
	},
	initialize: function( ) {
		$H(this.groups.datas).each(function(data,id){
			if( !data.parent ) return;
			for( var k in data )
			if( 1<=k.length && k.length<=3 )
			{
//				console.debug( 'k:', k, 'parent:', data.parent );
//				console.debug( this.groups.datas, 'groups.datas' );
				this.groups.datas[data.parent] = this.groups.datas[data.parent] || {};
//				console.debug( this.groups.datas[data.parent], 'groups.datas[parent]' );
//				console.debug( this.groups.datas[data.parent][k], 'groups.datas[parent]' );
				this.groups.datas[data.parent][k] = parseInt(this.groups.datas[data.parent][k]||0)+parseInt(data[k]);
			}
		}.bind(this));
		
		this.restoreFromCookie( );
	},
	storeToCookie: function( ) {
		var state = '';
		$A(['home','office','industry']).each(function(el){
			if( this.is( el ) ) state += el[0];
		}.bind(this));
		if( Cookie.read( 'filter' ) != state ) Cookie.write( 'filter', state, { 'path': '/', 'duration': 365 } );
	},
	restoreFromCookie: function( ) {
		var preset = Cookie.read('filter') || '';
		$A(['home','office','industry']).each(function(el){
			//console.debug( el, preset.search(el[0])!=-1 );
			if( preset.search(el[0])!=-1 ) this.toggle( el, true );
		}.bind(this));
	},
	toggle: function( flag, onInit ) {
		onInit = onInit || false;
		this.flags[flag] = !this.flags[flag];
		// 0,3 - reset & recount, 1,2 - just recount
		this.count( ) ? this.recount( ) : this.reset( );
		if( !onInit ) this.storeToCookie( );
	},
	reset: function( ) {
		//console.debug( 'filter.reset' );
		this.flags = { };
		this.recount( );
		this.storeToCookie( );
	},
	recount: function( )
	{
		var count = this.count();
		$H(this.buttons).each( function(el,flag){ var p=$($(el).parent()); (count&&!this.is(flag)?p.addClass:p.removeClass).call(p,'disable'); }.bind(this) );
		
		//console.debug( 'recount', this.flags );
		var flag, flag2;
		switch(count){
			case 2: flag2=this.is('industry')?'industry':(this.is('office')?'office':'home');
			case 1: flag=this.is('home')?'home':(this.is('office')?'office':'industry'); break;
		}
		//console.debug( 'flags', flag, flag2, 'count', count );
		$H(this.groups.els).each(function(el,id){
			var data = this.groups.datas[id], span = this.groups.spans[id], an = this.groups.anchors[id];
			var cc = el.attr('class').replace(/no-(home|office|industry)/g,''); // clean class
			switch(count) {
			case 0: span.html(data.all); el.set('class',cc); if(an.attr('href')) an.attr('href',an.attr('href').replace(/\?flag=((home|office|industry|)\+?)+$/,'')); break;
			case 1: span.html(data[flag.substr(0,1)]);
				el.set('class',cc+' no-home no-office no-industry'.replace('no-'+flag,''));
				if(an.attr('href')) an.set('href',an.attr('href').replace(/\?flag=((home|office|industry|)\+?)+$/,'')+'?flag='+flag); break;
			case 2: var k=flag.substr(0,1)+flag2.substr(0,1);
				if(!$chk(data[k])) k = flag2.substr(0,1)+flag.substr(0,1);
				span.html(parseInt(data[k]));
				//if( span.attr('text') == '' ) console.debug( id, data, k, flag, flag2 );
				el.set('class',cc+' no-home no-office no-industry'.replace('no-'+flag,'').replace('no-'+flag2,''));
				if(an.attr('href')) an.set('href',an.attr('href').replace(/\?flag=((home|office|industry|)\+?)+$/,'')+'?flag='+flag+'+'+flag2);
			}
			if( Browser.Engine.trident4 ) { if( !parseInt(span.text()) ) el.addClass( 'empty' ); else el.removeClass( 'empty' ); }
			//console.debug( id, el.attr('class'), 'all', data.all );
		}.bind(this));
		
		//console.debug( 'recount done' );
	}
};

$('li.group').each(function(){
	var el = $(this);

	var data = null, parent = null;
	var vendorslist = $('li.group.vendor').length > 0;
	
	el.attr('class').split(' ').each(function(s){
		if(!s.contains(':')) return;
		if(s.contains('data')) $try(function(){ data = JSON.decode('{'+s+'}').data; el.removeClass( s ); });
		if(s.contains('parent')) $try(function(){ parent = JSON.decode('{'+s+'}').parent; el.removeClass( s ); });
		});
	if( !data || vendorslist && data && !data.vendor )
		data = {
			group:el.attr('id').replace(/[^0-9]/g,''),
			all:0,h:0,o:0,i:0,ho:0,oi:0,ih:0};

	if( data.vendor )
		data.group = el.attr('id').replace('group','');
	if( parent )
		data.parent = parent;
	filter.addGroup( data, el ); //el.store( 'data', data );
});

$('ul.filter-menu a,ul.filter-menu+span>a').each(function(){
	var el = $(this);

	el.removeAttr('onclick');
	var flag = (el.attr('class').match(/\bhome|office|industry\b/)||[''])[0];
	el.click(function(e){
		if(e)
			e.stopPropagation();
		
		$(this).hasClass('reset-present')
			? filter.reset( )
			: filter.toggle( flag );
	});

	filter.addButton( flag, el );
});

filter.initialize( );

});

