(function( j ){
	var methods = {
		'init': function () {
			return this.each(function () {
				switch(this.tagName.toLowerCase())
				{
					case 'a':
						j(this).siteGetFilter('setupAnchor');
						break;
					case 'select':
						j(this).siteGetFilter('setupSelect');
						break;
					case 'input':
						j(this).siteGetFilter('setupInput');
						break;
				}
			});
		},
		'setupAnchor': function () {
			var keyvalue = unescape(j(this).attr('href')).split('=');
			if(document.location.pathname == keyvalue[0].split('?')[0])
			{
				keyvalue[0] = keyvalue[0].split('?')[1];
				if(typeof location.queryString[keyvalue[0]] != 'undefined' && location.queryString[keyvalue[0]] == keyvalue[1])
				{
					j(this).addClass('site-active');
					j('<input type="hidden" name="'+keyvalue[0]+'" value="'+keyvalue[1]+'" />').insertAfter(this);
				}
				j(this).bind('click', function (e) {
					if(j(this).hasClass('site-active'))
					{
						delete location.queryString[keyvalue[0]];
						document.location.href = '?'+j.param(location.queryString);
					} else {
						location.queryString[keyvalue[0]] = keyvalue[1];
						document.location.href = '?'+j.param(location.queryString);
					}
					e.preventDefault();
					return false;
				});
			}
		},
		'setupSelect': function () {
			if(typeof location.queryString[j(this).attr('name')] != 'undefined')
			{
				j(this).find('option[value="'+location.queryString[j(this).attr('name')]+'"]').attr('selected', 'selected');
			}
		},
		'setupInput': function () {
			if(typeof location.queryString[j(this).attr('name')] != 'undefined')
			{
				j(this).val(location.queryString[j(this).attr('name')]);
			}
		}
	};
	
	location.queryString = {};
	var pairs = location.search.split('&');
	if(pairs != '')
	{
		for ( i in pairs )
		{
			var keyval = pairs[ i ].split('=');
			if(i == 0)
			{
				keyval[0] = keyval[0].substr(1, keyval[0].length-1);
			}
			
			location.queryString[ unescape(keyval[0]) ] = unescape(keyval[1]);
		}
	}
	
	// setup the methods
	j.fn.siteGetFilter = function(method) {
		if(methods[method])
		{
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		}
		else if(typeof method === 'object' || ! method)
		{
			return methods.init.apply(this, arguments);
		}
		else
		{
			j.error('Method ' +  method + ' does not exist on jQuery.siteGetFilter');
		} 
	};
	
})( jQuery );

j(document).ready(function () {
	setTimeout(function() {
		j('.site-get-filter').siteGetFilter();
	}, 100);
});
