popuphide = 0;
compare_page = false;

menuTimeout = 0;
function print_r(arr, level) {
    var print_red_text = "";
    if(!level) level = 0;
    var level_padding = "";
    for(var j=0; j<level+1; j++) level_padding += "    ";
    if(typeof(arr) == 'object') {
        for(var item in arr) {
            var value = arr[item];
            if(typeof(value) == 'object') {
                print_red_text += level_padding + "'" + item + "' :\n";
                print_red_text += print_r(value,level+1);
		} 
            else 
                print_red_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
        }
    } 

    else  print_red_text = "===>"+arr+"<===("+typeof(arr)+")";
    return print_red_text;
}
function ObjectCount(obj)
{
	if (obj === null)
		return 0;
	else
	{
		var k = 0;
		for(i=0;obj[i]!==undefined;i++)
		{
			k = k + 1;
		}
		return k;
	}	
}
function SaveInfinityFields(obj)
{
	var Q = '\\"';
	var C = ObjectCount(obj);
	if (C>0)
	{
		var Str = "{";
		for(k=0;k<C;k++)
		{
			Str += Q + k + Q + ':{' + Q + 'id' + Q + ':' + Q + obj[k]['id'] + Q + ',' + Q + 'count' + Q + ':' + Q + obj[k]['count'] + Q + '}';
			if (k != (parseInt(C)-1))
				Str += ',';
		}
		Str += "}";
		return Str;
	}
	else
		return false;
}
$(function() {
	/*if (!$.browser.msie && !$.browser.opera) {*/
		$('#menu span.selected').corner("5px");
		$('#top-search').corner("5px");
	/*}*/
/*
	$('.menu a.category').hover(function() {
		var category = $(this);
		var offset = category.offset();
		var subcategory = $('#sub_' + category.attr('rel'));

		subcategory.css('top', offset.top + category.innerHeight()).css('left', offset.left-9).show();
		if (subcategory.innerWidth() < category.innerWidth())
			subcategory.width(category.innerWidth())

		}, function() {
			var obj = this;
			menuTimeout = setTimeout(function() {$('#sub_' + $(obj).attr('rel')).hide()}, 100);
		}
	);
*/
	$('.menu .subcategories').hover(function() {
		clearTimeout(menuTimeout);
		
		$('#menu_' + $(this).attr('rel')).addClass('hoveractive').addClass('active');
		$(this).show()
	}, function() {
		var obj = this;

		menuTimeout = setTimeout(function() {
			$('#menu_' + $(obj).attr('rel')).removeClass('hoveractive').removeClass('active');
			$(obj).hide()
		}, 100);
	});

	$('.menu .subcategories div').hover(function() {
		$(this).addClass('active');
	}, function() {
		$(this).removeClass('active');
	}).click(function() {
		document.location = $('a', this).attr('href');
	});		

	$('#filter select').change(function() {
		$('#filter').submit();
	});
	
	$('#popup-close img').click(function() {
		$('#popup').hide();
	});
	
	$('#compare_top').click(function() {
		document.location = '/compare/';
	});
	
	$('#basket_top').click(function() {
		document.location = '/order/';
	});	

	$('div.compare a, div.compared a').click(function() {
		var obj = $(this);

		$.get(obj.attr('href'), {compl: obj.attr('rel')}, function(data){

			  if (data != 'ok') {
				  alert(data);
				  return false;
			  }

			  obj.parent().toggleClass('compared');

			if (obj.html() == 'Удалить из сравнения') {
				if (compare_page) {
					document.location = document.location;
					return false;
				}

				obj.html('Добавить к сравнению');
				if(obj.attr('compl') == '1')
					obj.attr('href', '/compare/addcompl/' + obj.attr('rel'));
				else
					obj.attr('href', '/compare/add/' + obj.attr('rel'));
				
			} else {
				obj.html('Удалить из сравнения');
				if(obj.attr('compl') == '1')
					obj.attr('href', '/compare/deletecompl/' + obj.attr('rel'));
				else
					obj.attr('href', '/compare/delete/' + obj.attr('rel'));				
				
				showPopup('Товар добавлен к сравнению', 'Вы можете перейти на <a href="/compare/">страницу сравнения</a> для сравнения отобранных товаров.');
			}
		});

		return false;
	});

	$('.order-add').submit(function() {
		var obj = $(this);
		var mode = $('input[name=mode]', obj).val();
		var kk = 0;
		var compl_ids = {};
		var complObj = {};
		$('tr[compl_id]').each(function(){			
			if ($(this).find('.art_group_chbox').attr('checked'))
			{
				complObj[kk] = {};
				complObj[kk].id = $(this).attr('compl_id') + "," ;
				complObj[kk].count = $(this).find('.art_quality_box').val();
				++kk;
			}
		});
		compl_ids.complect = $('input[name=complect]', obj).val();
		compl_ids.items = SaveInfinityFields(complObj);
		compl_ids.parent_id = $('input[name=id]', obj).val();
		if (mode == 'additem') {
			mode = 'removeitem';

			var action = '/order/additem';
			var img = '/public/images/base/remove-frombasket.gif';
			var button = 'Убрать из корзины';

			showPopup('Товар добавлен в корзину', 'Вы можете перейти в <a href="/order/">вашу корзину</a> для оформления и оплаты заказа');
		} else {
			mode = 'additem';

			var action = '/order/removeitem';
			var img = '/public/images/base/add-tobasket.gif';
			var button = 'Добавить в корзину';
		}
		$.post(
				action, 
				compl_ids,
				function (data){
					$('input.submit', obj).attr('src', img);
					$('input.submit', obj).val(button);
					$('input[name=mode]', obj).val(mode);
				}
			);
		/*$.post(
			action, 
			{
				id: $('input[name=id]', obj).val(), 
				complects: compl_ids,
				quantity: $('input[name=quantity]', obj).val(),
				complect: $('input[name=complect]', obj).val(),
				complect_id_list: $('input[name=complect_id_list]', obj).val(),
				complect_qual_list: $('input[name=complect_qual_list]', obj).val()
			}, 
			function (data){
				$('input.submit', obj).attr('src', img);
				$('input.submit', obj).val(button);
				$('input[name=mode]', obj).val(mode);
			}
		);*/

		return false;
	});


/*******************************/
	$('.order-add-test').submit(function() {
		var obj = $(this);
		var mode = $('input[name=mode]', obj).val();
		if (mode == 'additem') {
			mode = 'removeitem';

			var action = '/basket/addcomplect';
			var img = '/public/images/base/remove-frombasket.gif';
			var button = 'Убрать из корзины';

			showPopup('Товар добавлен в корзину', 'Вы можете перейти в <a href="/order/">вашу корзину</a> для оформления и оплаты заказа');
		} else {
			mode = 'additem';

			var action = '/basket/removecomplect';
			var img = '/public/images/base/add-tobasket.gif';
			var button = 'Добавить в корзину';
		}

		$.post(action, { id: $('input[name=id]', obj).val(), quantity: $('input[name=quantity]', obj).val(),

							complect: $('input[name=complect]', obj).val(),
							complect_id_list: $('input[name=complect_id_list]', obj).val(),
							complect_qual_list: $('input[name=complect_qual_list]', obj).val()

						}, function (data) {
			$('input.submit', obj).attr('src', img);
			$('input.submit', obj).val(button);
			$('input[name=mode]', obj).val(mode);
		});

		return false;
	});
/*******************************/
});
		
function getMorfForm(val, forms, plural) {
	val = Math.floor(val % 100);
	var last = val % 10,
		idx = ((0 == last) || (4 < last) || ((10 < val) && (20 > val)) || (plural && (1 != last)))
			? 2
			: (((1 == last) && !plural) ? 0 : 1); 
	return forms[Math.min(idx, forms.length - 1)];
}

function showPopup(title, message) {
	clearTimeout(popuphide);

	var popup = $('#popup');
	$('h4', popup).html(title);
	$('div.text', popup).html(message);
	var main = $('div.main');
	var h = $(document.window).scrollTop();
	var topPadding = popup.css('top');

	popup.css('left', main.offset().left + main.width() / 2 - popup.width() / 2);
	popup.css('top', h + 300);

	popup.show('fast');

	popuphide = setTimeout("$('#popup').hide('fast')", 3000);
}


function filterCollections(category) {
    var act = [];

    $('#brandDiv').find('input').each(function(){
        if (this.checked) {
            act[act.length] = this.value;
        }
    });

    $.post('/ajax/collections/',{category:category, brands:act.toString()}, function(data){
        document.getElementById('collectionSelect').innerHTML = data;
    });
}
