var combo = null;
var comboThumb = null;
var functionalText = null;
var initialHistoryLength = 0;

var selectedValues = [];

var estimatedDelivery = '';

$(document).ready(function() {
	combo = getById('combo');
	comboThumb = getById('comboThumb');
	functionalText = getById('functionalText');

	if (topProduct != null) {
		topProduct.prefix = 'top';
		populateColorSelect(topProduct);
	}

	if (middleProduct != null) {
		middleProduct.prefix = 'middle';
		populateColorSelect(middleProduct);
	}

	if (bottomProduct != null) {
		bottomProduct.prefix = 'bottom';
		populateColorSelect(bottomProduct);
	}

	initialHistoryLength = history.length;
	
	$('.reviews_link').click(toggleReviews);
	$('.reviews_close_link').live('click', closeReviews);
	$('.add_review_link').click(addReview);
	
	$('#pager a').live('click', function() {
		var div = $(this).parents('.reviews');
		div.load($(this).attr('href'));
		return false;
	});
});

function toggleReviews() {
	var div = $('#' + $(this).attr('pos') + '_reviews');
	var artNr = $(this).attr('artNr');
	
	if (div.attr('open') == 'review') {
		div.slideUp();
	} 

	if (div.attr('open') == 'true') {
		div.slideUp();
		div.attr('open', '');
	} else {
		$.get('/catalog/reviews/underdelar/' + artNr, function(result) {
			div.hide();
			div.attr('open', 'true');
			div.html(result).slideDown();
		});
	}
}

function closeReviews() {
	var div = $(this).parents('.reviews');
	div.attr('open', 'false');
	div.slideUp();
}

function cancelReview() {
	var div = $(this).parents('.reviews');
	div.slideUp();
	div.attr('open', '');
}

function addReview() {
	var div = $('#' + $(this).attr('pos') + '_reviews');
	var artNr = $(this).attr('artNr');
	
	if (div.attr('open') == 'true') {
		div.slideUp();
	} 
	
	if (div.attr('open') == 'review') {
		div.slideUp();
		div.attr('open', '');
	} else {
		$.get('/catalog/reviewPost/underdelar/' + artNr, function(result) {
			div.hide();
			div.attr('open', 'review');
			div.html(result).slideDown();
		});
	}
}

function populateColorSelect(product) {
	if (!product.colors) return;

	disableAddToCart(product.prefix, false);

	if (product.colors.length == 1) {
		selectedValues[product.prefix + 'color'] = product.colors[0];
		populateCupSelect(product);
		switchDiv(product.colors[0].colorId, product);
	} else {
		for (var i = 0; i < product.colors.length; i++) {
			var c = product.colors[i];
			if (c['default']) {
				selectColor(product, c.colorId, true);
			}
		}
	}
}

function populateCupSelect(product) {
	var select = getById(product.prefix + 'SizeGroupSelect');

	var color = selectedValues[product.prefix + 'color'];

	var length = 0;
	for (var size in color.sizes) length++;

	if (length == 1) {
		select.style.display = 'none';

		var sizeGroupSpan = getById(product.prefix + 'SizeGroupSpan');
		for (var size in color.sizes) {
			sizeGroupSpan.innerHTML = size;
			selectedValues[product.prefix + 'cup'] = color.sizes[size];
			populateSizeNrSelect(product, size);
			return;
		}
	}

	select.options.length = 1;
	select.options[0] = new Option(chooseSize, 0);

	for (var size in color.sizes) {
		//console.log('Created size option: ' + size);
		select.options[select.options.length] = new Option(size, size);
	}

	select.options.selectedIndex = 0;
	resetSizeNrSelect(product.prefix);
}

function populateSizeNrSelect(product, selectedSize) {
	var select = getById(product.prefix + 'SizeNrSelect');

	disableAddToCart(product.prefix, false);

	sizes = selectedValues[product.prefix + 'cup'];
//	console.log('Populating sizes for color: ', sizes);

	var length = 0;
	var lastSize;
	for (var size in sizes) {
		lastSize = size;
		length++;
	}

	select.options.length = 1;
	select.options[0] = new Option(chooseSize, 0);

	for (var size in sizes) {
//		console.log('Created size option: ' + size + ' = ' + sizes[size]);
		displaySize = size;
		select.options[select.options.length] = new Option(displaySize, sizes[size]);
	}


	var sizeNrSpan = getById(product.prefix + 'SizeNrSpan');

	if (length == 1) {
		select.style.display = 'none';
		select.options.selectedIndex = 1;

		sizeNrSpan.innerHTML = lastSize;

		selectedValues[product.prefix + 'size'] = product.colors[0];
		price = getById(product.prefix + 'Price');
		
		estimatedDelivery = '';
		
		var text = "";

		var sizeGroup;
		var sizeGroupSelect = getById(product.prefix + 'SizeGroupSelect');
		var sizeGroupSpan = getById(product.prefix + 'SizeGroupSpan');
		if (sizeGroupSelect.style.display == 'none') {
			sizeGroup = sizeGroupSpan.innerHTML;
		} else {
			sizeGroup = sizeGroupSelect.value;
		}
			
		var size = sizeGroup + ' ' + lastSize;
		var colorId = selectedValues[product.prefix + 'color'].colorId;
		
		for (var i = 0; i < product.sizes.length; i++) {
			if (product.sizes[i].localeName == size && product.sizes[i].colorId == colorId) {
				size = product.sizes[i];
				break;
			}
		}
		
//		console.log(size);
		if (size.stock > 0) {
			text = msgInStock;
		} else {
			if (size.estimatedDelivery == null || size.estimatedDelivery == 0) {
				text = msgNotInStock + " "  + msgWithinFourWeeks;
				estimatedDelivery = "4";
			} else {
				text = msgNotInStock + " " + msgWeeks + " " + size.estimatedDelivery;
				estimatedDelivery = size.estimatedDelivery;
			}
		}
		
		enableAddToCart(sizes[lastSize], product.prefix, text);

		return;
	} else {
		sizeNrSpan.innerHTML = '';
		select.style.display = '';
	}

	select.options.selectedIndex = 0;
}

function selectColor(product, colorId, dontSwitchCombo) {
	disableAddToCart(product.prefix, true);
	
	if (colorId < 10) colorId = '0' + colorId;

	if (product.images && !dontSwitchCombo) {
		setCombo('data/upload/products/' + colorId + '-' + product.artNr.substring(0,4) + '-1_detail.jpg', '');
	}
	switchDiv(colorId, product);
	
	for (i = 0; i < product.colors.length; i++) {
		color = product.colors[i];
		if (color.colorId == colorId) {
			selectedValues[product.prefix + 'color'] = color;
		}
	}
	
	populateCupSelect(product);
}

function onSizeGroupSelect(select, product) {
	disableAddToCart(product.prefix, true);

	if (select.selectedIndex > 0) {
		color = selectedValues[product.prefix + 'color'];
		for (var size in color.sizes) {
			if (size == select.value) {
				selectedValues[product.prefix + 'cup'] = color.sizes[size];
//				console.log('Selected cup: ' + size + ' for color ' + color.colorId);
			}
		}

		populateSizeNrSelect(product);
	} else {
		resetSizeNrSelect(product.prefix);
	}
}

function onSizeNrSelect(select, product) {
	var sizeGroupSelect = getById(product.prefix + 'SizeGroupSelect');
	var sizeNr = getById(product.prefix + 'SizeNrSelect');
	
	colorId = selectedValues[product.prefix + 'color'].colorId;
	
	var sizeGroup;
	var sizeGroupSpan = getById(product.prefix + 'SizeGroupSpan');
	if (sizeGroupSelect.style.display == 'none') {
		sizeGroup = sizeGroupSpan.innerHTML;
	} else {
		sizeGroup = sizeGroupSelect.value;
	}
		
	var size = sizeGroup + ' ' + sizeNr.options[sizeNr.selectedIndex].text
	
	for (var i = 0; i < product.sizes.length; i++) {
		if (product.sizes[i].localeName == size && product.sizes[i].colorId == colorId) {
			size = product.sizes[i];
			break;
		}
	}
	
	estimatedDelivery = '';
	
	if (select.selectedIndex > 0) {
		var text = "";
		
		if (size.stock > 0) {
			text = msgInStock;
		} else {
			if (size.estimatedDelivery == null || size.estimatedDelivery == 0) {
				text = msgNotInStock + " "  + msgWithinFourWeeks;
				estimatedDelivery = "4";
			} else {
				text = msgNotInStock + " " + msgWeeks + " " + size.estimatedDelivery;
				estimatedDelivery = size.estimatedDelivery;
			}
		}
		enableAddToCart(select.value, product.prefix, text);
	} else {
		disableAddToCart(product.prefix, true);
	}
}

function onQuantitySelect(select, product) {
       sizeNrSelect = getById(product.prefix + 'SizeNrSelect');
       onSizeNrSelect(sizeNrSelect, product);
}

function enableAddToCart(unitPrice, prefix, text) {
	button = getById(prefix + 'OrderButton');
	price = getById(prefix + 'Price');
	quantity = getById(prefix + 'Quantity').value;

	button.disabled = false;
	
	var currency = '';
	if (currencySymbol != '') {
		currency = currencySymbol + ' ';
	}
	if (quantity > 1) {
		totalPrice = unitPrice * quantity;
		price.innerHTML = 'Total: ' + currency + totalPrice + '.- a pris ' + currency + unitPrice + '.-';
	} else {
		price.innerHTML = currency + unitPrice + '.-';
	}
	
	if (text) {
		price.innerHTML += "<br>" + text;
	}
}

function resetCupSelect(prefix) {
	var select = getById(prefix + 'SizeGroupSelect');

	select.options.length = 1;
	select.options[0] = new Option('---------', 0);
	select.options.selectedIndex = 0;
	resetSizeNrSelect(prefix);
}

function resetSizeNrSelect(prefix) {
	var select = getById(prefix + 'SizeNrSelect');

	var sizeNrSpan = getById(prefix + 'SizeNrSpan');
	sizeNrSpan.innerHTML = '';
	select.style.display = '';
	select.options.length = 1;
	select.options[0] = new Option('---------', 0);
	select.options.selectedIndex = 0;
	estimatedDelivery = 0;
}

function disableAddToCart(prefix, deleteText) {
	button = getById(prefix + 'OrderButton');
	price = getById(prefix + 'Price');

	button.disabled = true;

	if (deleteText) {
		price.innerHTML = '&nbsp;';
	}
}	

function setCombo(src, text) {
	combo.src = src;
	if (text == '') {
		functionalText.innerHTML = '';
		functionalText.style.display = 'none';
	} else {
		functionalText.innerHTML = '<div style="padding: 4px 6px">' + text + '</div>';
		functionalText.style.display = '';
	}
	comboThumb.style.display = 'inline';
}

function resetComboImage() {
	if (topProduct != null) {
		combo.src = topProduct.combo;
	} else if (middleProduct != null) {
		combo.src = middleProduct.combo;
	} else {
		combo.src = bottomProduct.combo;
	}

	comboThumb.style.display = 'none';
	functionalText.innerHTML = '';
}

function switchDiv(divId, product) {
	if (divId == '') return;

	divId += '-' + product.artNr;

	var oldDiv = getById(product.oldDiv);
	if (oldDiv != null) {
		oldDiv.style.display = 'none';
	}
	product.oldDiv = divId;

	var div = getById(divId);
	div.style.display = '';
}

function onTopSizeGroupSelect(select) {
	onSizeGroupSelect(select, topProduct, 'top');
}

function onMiddleSizeGroupSelect(select) {
	onSizeGroupSelect(select, middleProduct, 'middle');
}

function onBottomSizeGroupSelect(select) {
	onSizeGroupSelect(select, bottomProduct, 'bottom');
}

function onTopSizeNrSelect(select) {
	onSizeNrSelect(select, topProduct, 'top');
}

function onMiddleSizeNrSelect(select) {
	onSizeNrSelect(select, middleProduct, 'middle');
}

function onBottomSizeNrSelect(select) {
	onSizeNrSelect(select, bottomProduct, 'bottom');
}

function onTopQuantitySelect(select)
{
	onQuantitySelect(select, topProduct);
}

function onMiddleQuantitySelect(select)
{
	onQuantitySelect(select, middleProduct);
}

function onBottomQuantitySelect(select)
{
	onQuantitySelect(select, bottomProduct);
}

function checkoutTop() {
	checkout(topProduct);
}

function checkoutMiddle() {
	checkout(middleProduct);
}

function checkoutBottom() {
	checkout(bottomProduct);
}

function checkout(product) {
	var button = getById(product.prefix + 'OrderButton');
	var sizeGroupSelect = getById(product.prefix + 'SizeGroupSelect');
	var sizeNr = getById(product.prefix + 'SizeNrSelect');

	var size = getById(product.prefix + 'Size');
	var color = getById(product.prefix + 'Color');
	var colorId = getById(product.prefix + 'ColorId');
	var artNr = getById(product.prefix + 'ArtNr');
	var name = getById(product.prefix + 'Name');
	var delivery = getById(product.prefix + 'Delivery');
	
	var quantity = getById(product.prefix + 'Quantity');

	colorId.value = selectedValues[product.prefix + 'color'].colorId;
	color.value = selectedValues[product.prefix + 'color'].name;

	var sizeGroup;
	var sizeGroupSpan = getById(product.prefix + 'SizeGroupSpan');
	if (sizeGroupSelect.style.display == 'none') {
		sizeGroup = sizeGroupSpan.innerHTML;
	} else {
		sizeGroup = sizeGroupSelect.value;
	}

	artNr.value = product.artNr;
	
	realSize = sizeNr.options[sizeNr.selectedIndex].text;

	size.value = sizeGroup + ' ' + realSize;
	name.value = product.name;
	
	delivery.value = estimatedDelivery;

	var x = $('#header_cart table').offset().left + 10;
	var y = $('#header_cart table').offset().top + 30;
	
	var c = $('#combo');
	
	var source = c.clone().css({position: 'absolute', left: c.offset().left, top: c.offset().top}).appendTo('#comboContainer').animate({opacity: 0.4}, 100)
				.animate({opacity: 0.1, left: x, top: y, width: 40, height: 40}, 1200, function() {
					$(this).remove();
					Cart.addItem(artNr.value, colorId.value, size.value, quantity.value, function(data) {
						$('#cartAmount').text(data['cartAmount']);
						$('#cartItemCount').text(data['cartItemCount']);
						$('#cart .content table').append("<tr><td>&raquo;" + data['itemName'] + "</td><td>" + data['itemAbbrSize'] + "</td><td>" + data['itemPrice'] + "</td></tr>");
						$('#lastCartItem').show().find('table').html('<tr><td><img src="' + data['itemImage'] + '"/></td><td valign="top">' 
								+ data['itemName'] + '<br>' + data['itemSize'] + '<br>' + msgPrice + ': ' + data['itemPrice'] + '<br>' + msgQuantity + ': ' + data['itemQuantity'] + '</td></tr>');
						Cart.expand();
					});
				});
	
	button.disabled = true;

//	form = getById(product.prefix + 'Form');
//	form.submit();
}

function goBack() {
	for (var i = initialHistoryLength; i < history.length; i++) {
		history.back();
	}
	history.back();
}
