$(document).ready(function(){
	// меню каталогов и коллекций
	$('.side_menu > ul > li > a').click(function(){
		if(!$(this).parent().hasClass('active'))
			$('.side_menu li.active ul').slideUp('fast', function(){
				$(this).parent().toggleClass('active');
			});

		$(this).parent().toggleClass('active');
		$(this).next().slideToggle('fast');
	});

	// Lightbox
	var lighBoxClose = function(){
		$(window).unbind('scroll');
		//$('.main').unbind('click');

		$('#lightbox').fadeOut('fast', function(){
			$('#lightbox').hide();
		});

		$('#overlay').fadeOut('fast', function(){
			$('#overlay').hide();
		});
	};

	//$(window).unbind('resize').resize(function(){ _center_overlay(); _resize_overlay(); });
	var lightBoxShow = function(){
		lightBoxCenter();

		$('#lightbox').fadeIn('normal'/*, function(){ lightBoxCenter(); }*/);

		$('#overlay').height($(document).height() + 'px').show().fadeTo('fast', 0.8);

		//$('.main').bind('click', function(){ lighBoxClose(); });

		$(window).scroll(function(){ lightBoxCenter(); });
	};

	var preloaded = false;

	var lightBoxShowImg = function(src, showBox){
		var img = new Image();
		img.onload = function(){
			$('#imageContainer').html('<img src="' + img.src + '" alt="" />');

			if(showBox)
			{
				lightBoxShow();

				if(!preloaded)
					$('#lightbox .small_img a').each(function(i){
						var load = new Image();
						load.src = this.href;

						preloaded = true;
					});
				//lightBoxCenter();
			}
		};

		img.src = src;
	};

	var lightBoxCenter = function(){
		var windowHeight = $(window).height();
		var windowWidth = $(window).width();

		var lb = $('#lightbox');
		var contentWidth = lb.width();
		var contentHeight = lb.height();
//alert('w ' + contentWidth + ' h ' + contentHeight);
		var pos = lightBoxGetScroll();
		var projectedTop = (windowHeight / 2) + pos['scrollTop'] - (590/*contentHeight*/ / 2);
//alert(contentHeight);
// 1264 / 2 - 942 / 2
		lb.css({
			'top': projectedTop/*,
			'left': (windowWidth / 2) + pos['scrollLeft'] - (contentWidth / 2)*/
		});
	};

	var lightBoxGetScroll = function(){
		if(self.pageYOffset)
			return { scrollTop: self.pageYOffset, scrollLeft: self.pageXOffset };
		else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
			return { scrollTop: document.documentElement.scrollTop, scrollLeft: document.documentElement.scrollLeft };
		else if (document.body) // all other Explorers
			return { scrollTop: document.body.scrollTop, scrollLeft: document.body.scrollLeft };
	};

	$('.big_img a').click(function(){
		if(this.href == 'javascript:void(0)') return false;

		lightBoxShowImg(this.href, true);

		return false;
	});

	$('.img_holder .w360 a').click(function(){
		$('#imageContainer').html('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>'.replace(/{width}/g, 400).replace(/{height}/g, 400).replace(/{wmode}/g, 'opaque').replace(/{path}/g, this.href));

		lightBoxShow();

		return false;
	});

	$('#lightbox .w360 a').click(function(){
		$('#imageContainer').html('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>'.replace(/{width}/g, 400).replace(/{height}/g, 400).replace(/{wmode}/g, 'opaque').replace(/{path}/g, this.href));

		return false;
	});

	$('#lightbox .close').click(function(){ lighBoxClose(); });

	$('.img_holder .small_img a').click(function(){
		lightBoxShowImg(this.href, true);

		return false;
	});

	$('#lightbox .small_img a').click(function(){
		lightBoxShowImg(this.href, false);

		return false;
	});

	// ---

	$('.show_popup').click(function(){
		var wnd = $('#' + this.id.replace('show_', ''));
		$('form', wnd).attr('action', wnd.attr('title'));
		wnd.show();
		//wnd.css('top', $(this).offset().top + $(this).height()).css('left', $(this).offset().left - wnd.width() / 2).show();
	});

	$('.close').click(function(){
		$(this).parent('.popup').hide();
	});

	$('form.filter').submit(function(){
		var form = this;

		$.post($(form).attr('action'), $(form).serialize(), function(data){
			if(!data.Valid)
				$(form).next().css('color', 'red').text(data.Message);
			else
			{
				$('#show_' + $(form).parent('.popup')[0].id).css('color', 'yellow').text(data.Message);
				$(form).parent('.popup').remove();
			}
		});

		return false;
	});
	// ---

	/* ToolTip */
	$('.tt').tooltip({
		effect: 'slide'
		,offset: [10, -150]
	});
	/* - */

	var min = parseInt($('#min_range').val());
	var max = parseInt($('#max_range').val());

	$('#slider').slider({
		range: true
		/*,step: 100*/
		,min: min
		,max: max
		,values: [
			$('#from').val() != '' ? parseInt($('#from').val()) : min
			,$('#to').val() != '' ? parseInt($('#to').val()) : max
		]
		,slide: function(event, ui){
			$('.slider span:eq(0)').text(ui.values[0]);
			$('.slider span:eq(1)').text(ui.values[1]);

			$('#from').val(ui.values[0]);
			$('#to').val(ui.values[1]);
		}
	});

	// Shopping cart
	$('a.gocart').click(function(){
		var off = $(this).offset();

		$('#cart_summary').load(this.href + '?ajax=true', function(){
			var cart = $('#to_cart');
			cart.css('left', off.left - cart.width() * 1.5).css('top', off.top).fadeIn('fast');
		});

		return false;
	});

	$('#to_cart .js').click(function(){
		$(this).parent('.popup').hide();
	});
	// ---

jQuery(".niceCheck").each(
// при загрузке страницы меняем обычные на стильные checkbox
function() {
     
     changeCheckStart(jQuery(this));
     
});

jQuery("#hide").css("display", "none");

$('#hide_link').click(function() {
  $('#hide').slideToggle('slow', function() {
    // Animation complete.
  });
});

var params = {
			changedEl: "select"
		}
		cuSel(params);
		
});


function changeCheck(el)
/* 
	функция смены вида и значения чекбокса при клике на контейнер чекбокса (тот, который отвечает за новый вид)
	el - span контейнер для обычного чекбокса
	input - чекбокс
*/
{

	var el = el,
		input = el.find("input").eq(0);
		  
	if(el.attr("class").indexOf("niceCheckDisabled")==-1)
	{	
   		if(!input.attr("checked")) {
			el.addClass("niceChecked");
			input.attr("checked", true);
		} else {
			el.removeClass("niceChecked");
			input.attr("checked", false).focus();
		}
	}
	
    return true;
}

function changeVisualCheck(input)
{
/*
	меняем вид чекбокса при смене значения
*/
var wrapInput = input.parent();
	if(!input.attr("checked")) {
		wrapInput.removeClass("niceChecked");
	}
	else
	{
		wrapInput.addClass("niceChecked");
	}
}

function changeCheckStart(el)
/* 
	новый чекбокс выглядит так <span class="niceCheck"><input type="checkbox" name="[name check]" id="[id check]" [checked="checked"] /></span>
	новый чекбокс получает теже name, id и другие атрибуты что и были у обычного
*/
{

try
{
var el = el,
	checkName = el.attr("name"),
	checkId = el.attr("id"),
	checkChecked = el.attr("checked"),
	checkDisabled = el.attr("disabled"),
	checkTab = el.attr("tabindex"),
    checkValue = el.attr("value");
	if(checkChecked)
		el.after("<span class='niceCheck niceChecked'>"+
			"<input type='checkbox'"+
			"name='"+checkName+"'"+
			"id='"+checkId+"'"+
			"checked='"+checkChecked+"'"+
            "value='"+checkValue+"'"+
			"tabindex='"+checkTab+"' /></span>");
	else
		el.after("<span class='niceCheck'>"+
			"<input type='checkbox'"+
			"name='"+checkName+"'"+
			"id='"+checkId+"'"+
             "value='"+checkValue+"'"+
			"tabindex='"+checkTab+"' /></span>");
	
	/* если checkbox disabled - добавляем соотвсмтвующи класс для нужного вида и добавляем атрибут disabled для вложенного chekcbox */		
	if(checkDisabled)
	{
		el.next().addClass("niceCheckDisabled");
		el.next().find("input").eq(0).attr("disabled","disabled");
	}
	
	/* цепляем обработчики стилизированным checkbox */		
	el.next().bind("mousedown", function(e) { changeCheck(jQuery(this)) });
	el.next().find("input").eq(0).bind("change", function(e) { changeVisualCheck(jQuery(this)) });
	if(jQuery.browser.msie)
	{
		el.next().find("input").eq(0).bind("click", function(e) { changeVisualCheck(jQuery(this)) });	
	}
	el.remove();
}
catch(e)
{
	// если ошибка, ничего не делаем
}

    return true;
}

