$(function() {

	resizeProductsContainer();
	initializeScrolling();
	$('div[id^=product-info]').each(function() {
		var $this = $(this);
/*
		var productId = $this.attr("productId");
		var productCost = $this.attr("productCost");
*/
		$('#sizes_id', $this).change(function() {
			productCalculateTotal($this);
		});
		$('#quantity', $this)
			.blur(function() {
				productCalculateTotal($this);
			})
			.keyup(function() {
				productCalculateTotal($this);
			});
		$('.detailsAdd', $this).click(function() {
			productAddToCart($this);
			return false;
		});
		$('.detailsSend', $this).click(function() {
			return false;
		});
	});
});

function resizeProductsContainer()
{
//	var newWidth = 310*{/literal}{$vals_cnt}{literal}+$('#productLeft-darken').width()+$('#productRight-darken').width();
	var newWidth = vals_width+$('#productLeft-darken').width()+$('#productRight-darken').width();
	if ($('#containerProducts').width() != newWidth)
	{
		$('#containerProducts').width(newWidth);
	}
}
function initializeScrolling()
{
	$scrollPane = $('#containerProducts').jScrollHorizontalPane({
		scrollDivId: 'scroller',
		scrollTrackId: 'slider-bar',
		scrollDragId: 'slider-btn',
		scrollContainerId: 'containerContent',
		scrollLeftId: 'arrow-left',
		scrollRightId: 'arrow-right',
		showArrows: true
	});

}
function showProductsInfo(id)
{
	$('body')
		.unbind('click', productsClickHandler)
		.bind('click', productsClickHandler);

	var doneOnce = false;
	scrollToProduct(id, function () {
		if (!doneOnce)
		{
			greyProducts(id, true);
			showProductsInfoDiv(id);
			doneOnce = true;
		}
	});
}
function showProductsInfoDiv(id)
{
	$('div[id^=product-info]').each(function() {
		if (this.style.display == 'block')
		{
			$(this).slideUp();
			if (view_type == 1)
			{
				var itemId = $(this).attr('productId');
				$('#productText'+itemId+'_ov').hide();
				$('#product-image'+itemId).attr('src', $('#product-image'+itemId).attr('itemSrc'));
				$('#productText'+itemId).show();
			}
		}
	});
	if (id > 0)
	{
		

		if (view_type == 1)
		{
			$('#productText'+id).hide();
			$('#productText'+id+'_ov').show();
			var $el = $('#containerProducts .product[productId='+id+']');
		}
		else
		{
			var $el = $('#containerProducts .productThumb[productId='+id+']');
		}
		$('#product-info'+id)
			.css({'left': ($el.position().left+$el.outerWidth())+'px', 'top': '0px'});
		$('#product-info'+id)
			.slideDown("slow");
		var $img_href = $('#product-image'+id).parent();

	if (('undefined' != typeof $zoomObj) && ($zoomObj != null) && ('undefined' != typeof $zoomObj[0]))
	{
		$('div.preload').remove();
		$zoomObj[0].removeZoom();
		$zoomObj = null;
	}

		if (view_type == 2)
		{
			$('#product'+id)
				.css({'position': 'absolute', 'display': 'block', 'top': '0px', 'left': ($el.position().left-175)+'px'})
		}

		if ($img_href.attr('href') != '#')
		{
//alert();
//alert($('#product'+id).position().left);

			$zoomObj = $img_href.jqzoom({
				lensOffsetLeft: 24,
				lensOffsetTop: 24,
				title: false,
				preloadText: 'zoom loading...',
				zoomWidth: 303,
				zoomHeight: 358,
				xOffset: 330+70,
				yOffset: -15,

				preloadPosition: 'offsetAbsolute',
				preloadTopAbsolute: 120+150,
				preloadLeftAbsolute: 690+200-offsetLeftResize
			});
//			alert($('#product'+id).position().left);
			var $thumbsUl = $('ul[rel=pics]', $('#product-info'+id));
			var $thumbsLis = $("li[id^=detailsT][itemId]", $thumbsUl);
			if ($thumbsLis.length > 3) {
				var liWidth = 94;
				$thumbsUl.css('width', $thumbsLis.length * liWidth);
				$('a.b-thb-scroll', $('#product-info'+id))
					.click(function() {
						var ulMargin = parseInt($thumbsUl.css('marginLeft')) * -1;
						var shouldMove = false;
						if ($(this).hasClass('scr-right')) {
							ulMargin = ulMargin + liWidth;
							if ((ulMargin / liWidth) <= ($thumbsLis.length-3)) {
								shouldMove = true;
							}
						} else if ($(this).hasClass('scr-left')) {
							ulMargin = ulMargin - liWidth;
							if (ulMargin >= 0) {
								shouldMove = true;
							}
						}
						if (shouldMove) {
							$thumbsUl.animate({
								marginLeft: -ulMargin
							});
						}
						return false;
					})
					.show();
			}
			$thumbsLis.each(function() {
				var $this = $(this);
				if ($this.attr('itemLarge') != '')
				{
//					alert(this.id+' {/literal}{$top.server}{literal}/files/products/'+id+'_'+$this.attr('itemId')+'_5.jpg');
//					$zoomObj[0].preloadImage('{/literal}{$top.server}{literal}/files/products/'+id+'_'+$this.attr('itemId')+'_5.jpg');
					$this.find('a').click(function(){
						$zoomObj[0].changeImage(top_url+'/files/products/'+id+'_'+$this.attr('itemId')+'_3.jpg', top_url+'/files/products/'+id+'_'+$this.attr('itemId')+'_5.jpg');
						return false;
					});
				}
				else
				{
					$this.find('a').click(function() { return false; } );
				}
			});
		}
	}
}
function hideProductsInfo()
{
	$('body').unbind('click', productsClickHandler);
	showProductsInfoDiv(0);
	$('#productLeft-darken').width(0);
	var rightWidth = $('#productRight-darken').width();
	$('#productRight-darken').width(0);
	resizeProductsContainer();
	if (rightWidth > 0)
	{
//		initializeScrolling();
		if ($('#containerProducts').width() <= $('#containerContent').width())
		{
			$scrollPane[0].scrollTo(0);
		}
		else
		{
			$scrollPane[0].scrollTo($('#containerProducts').width());
		}
	}
	$scrollPane[0].disableScrolling(false);

	if (('undefined' != typeof $zoomObj) && ($zoomObj != null) && ('undefined' != typeof $zoomObj[0]))
	{
		$('div.preload').remove();
		$zoomObj[0].removeZoom();

	}

	if (view_type == 2)
	{
		$('div.product[productId]').css('display', 'none');
	}

	greyProducts(0, false);
	SWFAddress.setValue('');
	if (is_streetmarket)
	{
		document.location = top_url+"/streetmarket";
	}
}

function scrollToProduct(id, runAfterScroll)
{
	if (view_type == 2)
	{
		var leftOffsetConstant = 360-20;
	}
	else
	{
		var leftOffsetConstant = 170;
	}
	var contentWidth = $('#containerProducts').width();
	var paneWidth = $('#containerContent').width();
	offsetLeftResize = ((1252-paneWidth)/2)+40;
/*
	if (view_type == 1)
	{
		offsetLeftResize += 40;
	}
*/
	
	if (offsetLeftResize > leftOffsetConstant)
		offsetLeftResize = leftOffsetConstant;
	var leftMargin = leftOffsetConstant-offsetLeftResize;
	$('#productLeft-darken').width(0);
	var rightWidth = $('#productRight-darken').width();
	$('#productRight-darken').width(0);
	resizeProductsContainer();
	if (rightWidth > 0)
	{
//		initializeScrolling();
	}
	if (view_type == 2)
	{
		var $el = $('#containerProducts .productThumb[productId='+id+']');
	}
	else
	{
		var $el = $('#containerProducts .product[productId='+id+']');
	}
//	var $el = $('#containerProducts .product[productId='+id+']');
	if ($el.length == 1)
	{
		$scrollPane[0].disableScrolling(false);
		var elPosition = $el.position().left;
		if (elPosition < leftMargin)
		{
			$('#productLeft-darken').width(leftMargin-elPosition);
			resizeProductsContainer();
//			$el.css('left', (leftMargin-elPosition));
		}
		else
		{
			if (elPosition > (contentWidth - paneWidth + leftMargin))
			{
//alert(paneWidth-leftMargin-(contentWidth-elPosition));
				$('#productRight-darken').width(paneWidth-leftMargin-(contentWidth-elPosition));
				resizeProductsContainer();
//				initializeScrolling();	
			}
		}
		$scrollPane[0].scrollTo(elPosition-leftMargin, false, true, runAfterScroll);
		$scrollPane[0].disableScrolling(true);
	}
}

function productsClickHandler(e) {
       	e = e? e: window.event; // e IS passed when using attachEvent though ...
        if (!e.target) e.target = e.srcElement;
	var parentCallback = function(obj, name)
	{
		return (obj.id.indexOf(name) >= 0) ? true : false;
	}
	if (!((inOffsetParent(e.target, 'product', parentCallback)) || (inOffsetParent(e.target, 'product-info', parentCallback)))) {
		hideProductsInfo();
	}
};
function inOffsetParent(obj, name, callbackFunction) {
	var o = obj;
	while (('undefined' != typeof o) && (o != null) && ('undefined' != typeof o.id)) {
		if (callbackFunction(o, name)) {
			return true;
		}
//		o = o.offsetParent;
		o = o.parentNode;
	}
	return false;
}

function greyProducts(id, state)
{
	$('#productLeft, #productRight, .product-darken > .product'+((view_type == 2) ? 'Small' : '')).each(function() {
		var $this = $(this);
		var speed = "slow";
		if (state)
		{
			if ($this.attr('productId') == id)
			{
				if ($this.attr('isGreyed') == 1)
				{
					$this.fadeTo(speed, 1);
					$this.attr('isGreyed', 0);
				}
			}
			else if ($this.attr('isGreyed') != 1)
			{
				$this.fadeTo(speed, 0.3);
				$this.attr('isGreyed', 1);
			}
		}
		else
		{
			if ($this.attr('isGreyed') == 1)
			{
				$this.fadeTo(speed, 1);
				$this.attr('isGreyed', 0);
			}
		}
	});
}


function handleChange(event) {
	var parameters = '';
	switch (event.path)
	{
		case '/products/':
			showProductsInfo(event.parameters['id']);
			break;
	}
	if ('undefined' != typeof event.parameters['source'])
	{
		alert(event.parameters['source']);
	}
}
SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleChange);


function productCalculateTotal($this, is_check)
{
	if ('undefined' == typeof is_check)
	{
		is_check = false;
	}

	var sizes_id = parseInt($('#sizes_id', $this).val());
	var quantity = trim($('#quantity', $this).val());

	if ((quantity.length > 0) && (isInteger(quantity)))
	{
		quantity = parseInt(quantity);
	}
	else
	{
		quantity = 0;
	}

	if (is_check)
	{
		if (sizes_id == 0)
		{
			alert('Please select size!');
			return false;
		}
		if (quantity == 0)
		{
			alert('Please select quantity!');
			return false;
		}
	}

	if (sizes_id == 0)
	{
		quantity = 0;
	}

/*
	if ((is_check) && (sizes_id > 0) && (quantity > 0))
	{
		var stock = parseInt($('#sizes_id :selected', $this).attr('itemStock'));
		if (quantity > stock)
		{
			alert('There is only '+stock+' items left!');
		}
	}
*/

//alert(quantity+' '+productCost);
	var productCost = $this.attr("productCost");
	var total = quantity*parseFloat(productCost);
	var total_str = top_currency_symbol+total.toFixed(2)
	var $productsTotal = $('#productsTotal', $this);
	if ($productsTotal.html() != total_str)
	{
		$productsTotal.html(total_str);
	}
	return true;
}

function productAddToCart($this)
{
	if (productCalculateTotal($this, true))
	{
		var productId = $this.attr("productId");
		var sizes_id = parseInt($('#sizes_id', $this).val());
		var quantity = parseInt(trim($('#quantity', $this).val()));

		xajax_ajaxAddToCart('<xjxquery><q>products_id='+productId+'&sizes_id='+sizes_id+'&quantity='+quantity+'</q></xjxquery>');		
	}
	return false;
}



