$(document).ready(function(){
	
	{	/* Каталог */
		
		{	// история
			
			$('#selectAll').toggle(function () {
				$('.pid_checkbox').attr('checked', 'checked');
				return false;
			},
			function () {
				$('.pid_checkbox').removeAttr('checked');
				return false;
			});
			
			$('.ckeck_history').click(function () {
				
				var _article = $(this).val();
				if ($(this).is(':checked')) {
					$('.prod_' + _article).attr('checked', $(this).attr('checked'));
				}
				else {
					$('.prod_' + _article).removeAttr('checked');
				}
				
			})
			
			
		}
		
		
		
		{	// расширенный поиск
			$('a.advanced').click(function () {
				
				var _href = _link_catalog;	//document.location.href;//.replace(document.location.search, '');
				
				$.get(_href, {ajax: 1, method: 'advancedSearchForm'}, function (data) {

					$('body').append(data);
					$('#popupSearch').fadeIn();
					
					
					$('#popupSearch .close').click(function () {
						$('#popupSearch').fadeOut();
						$('#popupSearch').remove();
						return false;
					});
					
					var _formData = document.location.search.substring(1).split('&');
					for (var i in _formData) {
						var _temp = _formData[i].split('=');
						$('*[name=' + _temp[0] + ']').val(Url.decode(_temp[1]));
					}
					
					
				});
				
				return false;

			});
			
			
		}
		
		
		// если фоток нет - игнорируем lightbox
		$('a.no_photo')
			.unbind('click')
			.click(function () {
				return false;
			});
			
		$('.imgZoom').click(function () {
			$('a', $(this).parents('.img')).click();
			return false;
		})
		
		
		{	// выставляем значения списков из куков
			$('select[name=season]').val($.cookie('season'));
			$('select[name=valute]').val($.cookie('valute'));
			$('select[name=sorttype]').val($.cookie('sorttype'));
		}

		{	// обработчики выпадающих списков
			
			$('select[name=season]').change(function () {
				$.cookie('season', $(this).val(), {expires: 100, path: '/'});
				_refreshCatalog();
			});	
			
			$('#archive_link').click(function () {
				$.cookie('season', 'archive', {expires: 100, path: '/'});
				_refreshCatalog();
				return false;
			});
			
			$('select[name=valute]').change(function () {
				$.cookie('valute', $(this).val(), {expires: 100, path: '/'});
				_refreshCatalog(true);
			});	
			
			$('select[name=sorttype]').change(function () {
				$.cookie('sorttype', $(this).val(), {expires: 100, path: '/'});
				_refreshCatalog();
			});
			
			var _refreshCatalog = function (useParams) {
				document.location.href = useParams ? document.location.href : document.location.href.replace(document.location.search, '');
			}
			
		}
		
		{	// функция заказа
			
			$('.basketEmpty, .basket').click(function () {
				
				var _href = document.location.href.replace(document.location.search, '');
				
				$.get(_href, {ajax: 1, method: ($(this).is('.basketEmpty') ? 'orderWindow' : 'refineOrderWindow'), article: $(this).attr('rel')}, function (data) {
					
					if (data == '{error}') {
						alert("Внимание: данная модель отсутствует в сезоне заказа!\n\nВы начали формировать заказ из другого сезона. Пожалуйста, перейдите в другой сезон для корректной работы с заказом и завершите текущий заказ.");
						return false;
					}
					
					$('body').append(data);
					$('#popup').show();
					$('#popup').addClass('popupVisible');
					
					$('#popup .close').click(function () {
						$('#popup').remove();
						return false;
					})
					
					$('.popupVisible .overlay').click(function () {
						$('#popup').remove();
						return false;
					})
					
					$("#popup tr:nth-child(even)").addClass("chet");
					
					_cart.init();
					
				})
				
				return false;

			});
			
			/* уточнить заказ */
			$('.refine').click(function () {
				
				var _href = document.location.href.replace(document.location.search, '');
				
				$.get(_href, {ajax: 1, method: 'refineOrderWindow', article: $(this).attr('rel')}, function (data) {
					
					if (data == '{error}') {
						alert("Внимание: данная модель отсутствует в сезоне заказа!\n\nВы начали формировать заказ из другого сезона. Пожалуйста, перейдите в другой сезон для корректной работы с заказом и завершите текущий заказ.");
						return false;
					}
					
					$('body').append(data);
					$('#popup').show();
					$('#popup').addClass('popupVisible');
					
					$('#popup .close').click(function () {
						$('#popup').remove();
						return false;
					})
					
					$('.popupVisible .overlay').click(function () {
						$('#popup').remove();
						return false;
					})
					
					$("#popup tr:nth-child(even)").addClass("chet");
					
					_cart.init();
					
				})
				
				return false;

			});
			
			
			
		}
		
	}
		
	$(".window table tr:nth-child(even)").addClass("chet");
	 
	function carousel_initCallback(_carousel, state) {

		var one = $('.catScroll .jcarousel-clip-horizontal LI:first a').width() + 50,
			all = $('.catScroll').width();
		
		if (all < one * 4) {
			_carousel.options.visible = 3;
		}
		else {
			_carousel.options.visible = 5;
		}
			
	};

	$('.catScroll .scroll ul').jcarousel({
		reloadCallback: carousel_initCallback,
		initCallback: function () {
			setTimeout(function () {
				$(window).trigger('resize.jcarousel');
			}, 1000);
		},
		visible: 3
	});
  
});




/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/ 
 
var Url = { 
 
	// публичная функция для кодирования URL 
	encode : function (string) { 
		return escape(this._utf8_encode(string)); 
	}, 
 
	// публичная функция для декодирования URL 
	decode : function (string) { 
		return this._utf8_decode(unescape(string)); 
	}, 
 
	// приватная функция для кодирования URL 
	_utf8_encode : function (string) { 
		string = string.replace(/\r\n/g,"\n"); 
		var utftext = ""; 
 
		for (var n = 0; n < string.length; n++) { 
 
			var c = string.charCodeAt(n); 
 
			if (c < 128) { 
				utftext += String.fromCharCode(c); 
			} 
			else if((c > 127) && (c < 2048)) { 
				utftext += String.fromCharCode((c >> 6) | 192); 
				utftext += String.fromCharCode((c & 63) | 128); 
			} 
			else { 
				utftext += String.fromCharCode((c >> 12) | 224); 
				utftext += String.fromCharCode(((c >> 6) & 63) | 128); 
				utftext += String.fromCharCode((c & 63) | 128); 
			} 
 
		} 
 
		return utftext; 
	}, 
 
	// приватная функция для декодирования URL 
	_utf8_decode : function (utftext) { 
		var string = ""; 
		var i = 0; 
		var c = c1 = c2 = 0; 
 
		while ( i < utftext.length ) { 
 
			c = utftext.charCodeAt(i); 
 
			if (c < 128) { 
				string += String.fromCharCode(c); 
				i++; 
			} 
			else if((c > 191) && (c < 224)) { 
				c2 = utftext.charCodeAt(i+1); 
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); 
				i += 2; 
			} 
			else { 
				c2 = utftext.charCodeAt(i+1); 
				c3 = utftext.charCodeAt(i+2); 
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); 
				i += 3; 
			} 
 
		} 
 
		return string; 
	} 
 
}
