
var mouseoffset = [30,30];
var picsize = [250,250];
var shadowsize = [15,15];
var bordersize = 5;
var cartsto, picsto;
var preview, shadow;
var docheight, docwidth;

var dumpObj = function (obj) {
    var dump = "";
    for (var i in obj) {
        dump += i + ":" + obj[i] + "; ";
    }
    return dump;
}

//function truebody()
//{
//	return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
//}

function screenSize() 
{
    var w, h; // Объявляем переменные, w - длина, h - высота
    w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
    h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
    return {w:w, h:h};
}

function ScrollOffset() 
{
	var x, y;
	// Gecko поддерживает свойства scrollX(scrollY)
	// Для IE & Opera приходится идти в обход
	x = (window.scrollX) ? window.scrollX : document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft;
	y = (window.scrollY) ? window.scrollY : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
	return { x: x, y: y };
}


	$(document).ready(function()
	{
		preview = $("#preview_div");
		shadow  = $("#shadow_div");

		var last_scroll_y = 0;
		var wide_page = ($("body").height() > 3000);
		var ear_open = true;
		var ear_closed = false;

//			var scroll = ScrollOffset();
//alert(scroll.x + ' ' + scroll.y );
		$(window).scroll(function(e)
		{
			var scroll = ScrollOffset();
//alert(scroll.x + ' ' + scroll.y );
			if (wide_page && !ear_closed && (last_scroll_y != scroll.y)) // catches only vertical scroll
			{
				if (scroll.y > 2000)
				{
//					$("#ear").css("display", "block");
					$("#ear").stop().animate({ 'right': '0px' }, "fast");
				}
				else
				{
//					$("#ear").css("display", "none");
					$("#ear").stop().animate({ 'right': '-124px' }, "fast");
				}
				last_scroll_y = scroll.y;
			}
		});
		$("#ear a img.close").click(function()
		{
			ear_closed = true;
			$("#ear").stop().hide();
		});
		$(document).keypress(function(e)
		{
//			alert(e.keyCode);
			if ((e.keyCode == 10) || (e.keyCode == 13))
			{
				var txt = getText();
				if (txt != '')
				{
					$.post("/ajax/send_error.php", { text : txt, url: document.location.href }, function() 
					{
						alert("Спасибо! Сообщение об ошибке отправлено!");
					});
				}
			}
		});
		$('#search input[type="text"]').focus(function() 
		{
			if (this.value == 'Поиск товаров') this.value=''; 
		});
		$('#search input[type="text"]').blur(function()
		{ 
			if (this.value == '') this.value='Поиск товаров'; 
		});
		$("#checkall").click(function()
		{
			$('input[type="checkbox"]').attr("checked", this.checked);
		});
		$("img.up").click(function()
		{
			var id = this.id;
			var input = $('#Quantity'+id);
//			input.attr("value", parseInt(input.attr("value")) + 1);
			input.val(parseInt(input.val()) + 1);
		});
		$("img.dn").click(function()
		{
			var id = this.id;
			var input = $('#Quantity'+id);
			var value = parseInt(input.attr("value"));
			if (value > 0) 
			{
				input.val(parseInt(value - 1));
//				input.attr("value", value - 1);
			}
		});
		$(".photo").mouseover(function(e) 
		{
			var reg = /^(\w+)\/(\d+)\.(.+)$/;
			var file = $(this).attr('src');
			var b_file = file.replace(reg, "/pics/$1/b_$2.$3");
			docwidth  = screenSize().w;
			docheight = screenSize().h;
//			picsto = setTimeout(function()
//			{
				preview.css({
					'width':  picsize[0]+'px', 
					'height': picsize[1]+'px', 
					'border': bordersize+'px solid #ccf',
					'padding': '0px',
					'background': "url('/@/img/load.gif') 50% 50% no-repeat #000"
				});
				shadow.css({
					'width':  picsize[0]+bordersize*2+'px',
					'height': picsize[1]+bordersize*2+'px' 
				});
				movePreview(e);
				$(document).mousemove(movePreview);
				preview.show();
				shadow.show();

				preview.html('<img src="'+b_file+'" onLoad="imgLoaded(this)" width="'+picsize[0]+'" height="'+picsize[1]+'" border="0" style="display: none;">');
//			}, 200);
		});
		$(".photo").mouseout(function () 
		{
//			clearTimeout(picsto);
			$(document).mousemove(function() {});
			$("#preview_div img").html('');
//			$("#preview_div img").load(function () {});
			preview.hide();
			shadow.hide();
//					$("#preview_div").html('<img src="/@/img/wait3.gif"/>');
//					$("#preview_div").html('');
		});
		$("#frame").fancybox(
		{
			'autoDimensions': false,
			'width'		: 470,
			'height'	: 640,
			'autoScale'	: false,
			'transitionIn'	: 'none',
			'transitionOut'	: 'none',
			'type'		: 'iframe',
			'scrolling'	: 'no',
			'modal'		: false,
			'centerOnScroll': true,
			'hideOnOverlayClick': false

		});
		$(".register").fancybox(
		{
			'autoDimensions': false,
			'width'		: 435,
			'height'	: 470,
			'autoScale'	: false,
			'transitionIn'	: 'none',
			'transitionOut'	: 'none',
			'type'		: 'iframe',
			'scrolling'	: 'no',
			'modal'		: false,
			'centerOnScroll': false,
			'hideOnOverlayClick': false
		});
		$(".auth").fancybox(
		{
			'autoDimensions': false,
			'width'		: 260,
			'height'	: 240,
			'autoScale'	: false,
			'transitionIn'	: 'none',
			'transitionOut'	: 'none',
			'type'		: 'iframe',	
			'scrolling'	: 'no',
			'modal'		: false,
			'centerOnScroll': false,
			'hideOnOverlayClick': false
		});
		$("#print").click(function()
		{
			$("#counters").fadeOut(500);
			$("#print_pad").slideUp(500, function() 
			{
				window.print();
				window.close(); 
			});
		});
		$("#ahide").click(function()
		{
			$("div #subs").slideUp("slow", function()
			{
				$("div#hideSubs").hide();
				$("div#showSubs").show();
				setCookie("showsubs", 0);
			});
		});
		$("#showSubs").click(function()
		{
			$("div#subs").slideDown("slow", function()
			{
				$("div#showSubs").hide();
				$("div#hideSubs").show();
				setCookie("showsubs", 1);
			});
		});
		$(".slr").click(function()
		{
			var slider = $(this).parents(".arts_container").find(".slider").eq(0);
			var slide  = $(this).parents(".arts_container").find(".slide").eq(0);
			var left   = $(this).parents(".arts_container").find(".sll").eq(0);
			var right  = $(this);
			var pos    = parseInt(slider.attr("rel"));
			var count  = parseInt(slide.attr("rel"));
			if (pos < (count - 4))
			{
				slide.animate({ "left": "-=162px" }, 300);
				pos++;
				slider.attr("rel", pos);
			}
			if (pos > 0)
			{
				left.show();
//				left.attr("src", "/@/img/aln.gif");	
			}
			if (pos > (count - 5))
			{
				right.hide();
//				right.attr("src", "/@/img/ar.gif");
			}
		});
		$(".sll").click(function()
		{
			var slider = $(this).parents(".arts_container").find(".slider").eq(0);
			var slide  = $(this).parents(".arts_container").find(".slide").eq(0);
			var pos    = parseInt(slider.attr("rel"));
			var count  = parseInt(slide.attr("rel"));
			var left   = $(this);
			var right  = $(this).parents(".arts_container").find(".slr").eq(0);
			if (pos > 0)
			{
				slide.animate({ "left": "+=162px" }, 300);
				pos--;
				slider.attr("rel", pos);
			}
			if (pos == 0)
			{
				left.hide();
//				left.attr("src", "/@/img/al.gif");
			}
			if (pos < (count  - 4))
			{
				right.show();
//				right.attr("src", "/@/img/arn.gif");
			}
		});
		$("a.addfav").click(function()
		{
			$(this).css("display", "none");
			$(this).next().css("display", "inline");
		});
		var rates = [ "очень плохо", "плохо", "нормально", "хорошо", "отлично" ];
		var nrate = "оценить товар";
		var rated = "написать отзыв";
		var ul;
		$("div.rating span.toggle_list").click(function()
		{
			ul = $(this).parents("ul.rated_list");
			ul.toggleClass("full_list");
		});
		$("div.rating span.set_rating img").mouseover(function() 
		{
			if (ul != undefined) ul.removeClass("full_list");
			if (!$(this).parent().hasClass("set_rating"))
			return;

			stars = $(this).parent().children();
			selected = stars.index(this);
			for (i = 0; i < stars.length; i++)
			{
				stars.eq(i).attr("src", ((i > selected) ? "/img/star_.gif" : "/img/star.gif"));
			}
			$(this).parent().next().text(rates[selected]);
		});
		$("div.rating span.set_rating img").mouseout(function()
		{
			if (!$(this).parent().hasClass("set_rating"))
			return;

			$(this).parent().children().each(function() 
			{
				$(this).attr("src", "/img/star_.gif");
			});
			$(this).parent().next().text(nrate);
		});
		$("div.rating span.set_rating img").click(function()
		{
			stars = $(this).parent().children();
			selected = stars.index(this);
			$("#mark_form input").val(selected+1);
			$("#mark_form").submit();
//			$(this).parent().removeClass("set_rating");
//			em = $(this).parent().next().html('<img src="/img/request.gif" border="0">');
//			$.post("/ajax/set_mark.php", { mark: selected }, function()
//			{
//				em.html(rated);
//				em.wrapInner("<a/>");
//				em.children().attr("href", "#addcomment");
//			});
		});		

	});
	
	$(document).blur(function() 
			{
				clearTimeout(picsto);
				$(document).mousemove(function() {});
				$("#preview_div img").html('');
//				$("#preview_div img").load(function () {});
				preview.hide();
				shadow.hide();		
			});

/*	$(document).focus(function() 
			{
				clearTimeout(picsto);
				$(document).mousemove(function() {});
				$("#preview_div img").html('');
//				$("#preview_div img").load(function () {});
				preview.hide();
				shadow.hide();		
			});
*/
function movePreview(e)
{
	if (docheight < (e.clientY + picsize[1] + bordersize*2 + shadowsize[1] + mouseoffset[1]))
	{
		preview.css('top', e.pageY - (picsize[1] + bordersize*2 + mouseoffset[1]) + 'px');
		shadow.css ('top', e.pageY - (picsize[1] + bordersize*2 + mouseoffset[1]) + shadowsize[1] + 'px');
	}
	else
	{
		preview.css('top', e.pageY + mouseoffset[1] + 'px');
		shadow.css ('top', e.pageY + mouseoffset[1] + shadowsize[1] + 'px');
	}
	if (docwidth < (e.clientX + picsize[0] + bordersize*2 + shadowsize[0] + mouseoffset[0]))
	{
		preview.css('left', e.pageX - (picsize[0] + bordersize*2 + mouseoffset[0]) + 'px');
		shadow.css ('left', e.pageX - (picsize[0] + bordersize*2 + mouseoffset[0]) + shadowsize[0] + 'px');
	}
	else
	{
		preview.css('left', e.pageX + mouseoffset[0] + 'px');
		shadow.css ('left', e.pageX + mouseoffset[0] + shadowsize[0] + 'px');
	}
}

function imgLoaded(img)
{
	preview.css({'background': '#000'});
	$(img).fadeIn(300); //show();
}

function duzzleCart(price, cartTotal, article, quantity)
{
	$(document).ready(function()
	{
//		clearTimeout(cartsto);
//alert(cartTotal);
		$("#cart_total").text(cartTotal);
		$("#price"+article).text(price);
		var inCart = $("#incart"+article+" div");
		inCart.text(parseInt(inCart.text())+parseInt(quantity));
		$("#incart"+article).css("visibility", "visible").show();
//		$("#cart_added").fadeIn('slow', function()
//		{
//			cartsto = setTimeout(function ()
//			{
//				$("#cart_added").fadeOut('fast');
//			}, 1000);
//		});
	});		
}

function drawFavorite(article)
{
	$("#onhold_button"+article).hide();
	$("#onhold_img"+article).fadeIn('slow');
}

function OpenWindow(th, width, height, scroll)
{
	if (window.screen)
	{
		var ah = screen.availHeight - 30;
		var aw = screen.availWidth - 10;
		var xc = (aw - width) / 2;
		var yc = (ah - height) / 2;
		str = ",left=" + xc + ",screenX=" + xc;
		str += ",top=" + yc + ",screenY=" + yc;
	}
	var newwin = window.open(th, '', 'width=' + width + ',height=' + height + ',resizable=no,location=no,toolbar=no,menubar=no,status=no,scrollbars=' + scroll + str);
	newwin.focus();
	return newwin;
}

function setCookie (name, value, expires, path, domain, secure) 
{
	document.cookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
}

function getCookie(name) 
{
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) 
	{
		offset = cookie.indexOf(search);
		if (offset != -1) 
		{
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) 
			{
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}


function getText()
{
    var txt = '';
    if (txt = window.getSelection) // Not IE, используем метод getSelection
      txt = window.getSelection().toString();
    else // IE, используем объект selection
      txt = document.selection.createRange().text;
    return txt;
}

