// classes
function SizeFilter($groups, $refresh_treshhold) {
	this.groups = $groups;
	this.timerId = null;
	this.refreshTreshhold = $refresh_treshhold;

	var $me = this;

	$(document).ready(
		function () {
			for (var $i = 0; $i < $me.groups.length; $i++) {
				$("input[type='checkbox']." + $me.groups[$i] + '-filter').click(
					function ($e) {
						var $value = $(this).val().split('|'); // 0 - group, 1 - size

						$me.update( $value[0] );
					}
				);
			}

			$('a.clear_size_filter').click(
				function($e) {
					$me.clear();

					return false;
				}
			);
		}
	);
}

SizeFilter.prototype.update = function ($group) {
	// remove previous refresh timeout
	clearTimeout(this.timerId);

	// rebuild content of filter to which given checkbox belongs
	var $filter = [];

	$("input[type='checkbox']." + $group + '-filter:checked').each(
		function () {
			var $value = $(this).val().split('|'); // 0 - group, 1 - size
			$filter.push( $value[1] );
		}
	);

	// save filter value
	if ($filter.length) {
		setCookie($group + '_filter', '|' + $filter.join('|') + '|', 1);
	}
	else {
		setCookie($group + '_filter', '');
	}

	// set timer to refresh page after 5 seconds
	this.timerId = setTimeout('window.location.href = window.location.href;', this.refreshTreshhold);
}

SizeFilter.prototype.clear = function () {
	for (var $i = 0; $i < this.groups.length; $i++) {
		// clear all group checkboxes
		$("input[type='checkbox']." + this.groups[$i] + '-filter').each(
			function ($e) {
				$(this).attr('checked', '');
			}
		);

		// remove stored filter
		setCookie(this.groups[$i] + '_filter', '');
	}

	// refresh page
	window.location.href = window.location.href;
}

// global functions
function setCookie($Name, $Value, $ExpireDays)
{
	if (getCookie($Name) == $Value) {
		return ;
	}

	// set cookie
	var $exdate = new Date();
	$exdate.setDate($exdate.getDate() + $ExpireDays);

	document.cookie = $Name + '=' + escape($Value) + (($ExpireDays == null) ? '' : ';expires=' + $exdate.toGMTString()) + ';path=/';
}

function getCookie($Name) {
	// get cookie

	var $cookieString = document.cookie;
	var $index = $cookieString.indexOf($Name+'=');
	if ($index == -1) {
		return null;
	}

	$index = $cookieString.indexOf('=',$index)+1;
	var $endstr = $cookieString.indexOf(';',$index);
	if($endstr == -1) $endstr = $cookieString.length;

	return unescape($cookieString.substring($index, $endstr));
}

function deleteCookie($Name) {
	// deletes cookie
	if (getCookie($Name)) {
    	var d = new Date();
		document.cookie = $Name + '=;expires=' + d.toGMTString() + ';' + ';';
    }
}