﻿var currentColor;
var currentSize;
var currentCatId;

jQuery().ready(function () {
	currentColor = null;

	GetCatalogueId();

	jQuery('div.color_block').bind('mouseover', colorHoverIn);
	jQuery('div.color_block').bind('mouseout', colorHoverOut);
	jQuery('div.color_block').bind('click', colorClick);

	jQuery('div.size_block').bind('mouseover', sizeHoverIn);
	jQuery('div.size_block').bind('mouseout', sizeHoverOut);
	jQuery('div.size_block').bind('click', sizeClick);

	jQuery('.frompriceInfo').hide();

	jQuery('input.orderamount').keydown(function (event) {
		if (event.keyCode == 46 || event.keyCode == 8) { //backspace and delete
			//igonore
		}
		else if (event.keyCode < 95) {
			if (event.keyCode < 48 || event.keyCode > 57) {
				event.preventDefault();
			}
		}
		else if (event.keyCode < 96 || event.keyCode > 105) {
			event.preventDefault();
		}
	});

	if (jQuery('div.color_wrapper a').length > 0) {
		jQuery('div.color_wrapper a:first').click();
	}

	var hiddenCartOptionId = jQuery('#selectedOptionColor');
	if (hiddenCartOptionId.length > 0 && hiddenCartOptionId.val() != '') {
		overrideLoad(hiddenCartOptionId);
	}
	else {
		//Initial color select
		jQuery.each(jQuery('div.color_wrapper'), function () {
			jQuery(this).find('a:first div:first img').css('width', '24px');
			jQuery(this).find('a:first div:first img').css('height', '24px');
			jQuery(this).find('a:first div:first').addClass('block_selected');
		});
	}
});

function overrideLoad(hiddenCartOptionId) {
	var optionId = hiddenCartOptionId.val();

	var colorBlock = jQuery('#optioncolor_' + optionId);
	if (colorBlock.length > 0) {
		var selectedBlock = colorBlock.parent().parent().find('div.block_selected:first');
		if (selectedBlock.length > 0) {
			selectedBlock.removeClass('block_selected');
			selectedBlock.find('img').css('width', '26');
			selectedBlock.find('img').css('height', '26');
		}

		colorBlock.find('img').css('width', '24');
		colorBlock.find('img').css('height', '24');
		colorBlock.addClass('block_selected');
	}

	var selectedSize = jQuery('#selectedOptionSize');
	if (selectedSize.length > 0 && selectedSize.val() != '') {
		var sizeBlock = jQuery('#sizeblock_' + selectedSize.val());
		if (sizeBlock.length > 0) {
			sizeBlock.find('div:first').addClass('block_selected_small');
		}
	}

	var parentId = jQuery('#selectedOptionParent');
	var selectedImage = jQuery('#selectedOptionImage');
	if (selectedImage.length > 0 && selectedImage.val() != '') {
		var optionImage = jQuery('#mainProductImage_' + parentId.val());
		if (optionImage.length > 0) {
			optionImage.attr('src', './Controls/CatalogueImage.aspx?file=' + selectedImage.val());
		}
	}

	var colorAttributeName = jQuery('#colorAttributeName');
	var sizeAttributeName = jQuery('#sizeAttributeName');
	if (colorAttributeName.length > 0 && colorAttributeName.val() != '' && sizeAttributeName.length > 0 && sizeAttributeName.val() != '') {
		updateOptionPrice(parentId.val(), colorAttributeName.val(), getSelectedColorValue(parentId.val()), sizeAttributeName.val(), getSelectedSizeValue(parentId.val()), function () {

			PageMethods.FilterSlaveAttributes(getSelectedSizeValue(parentId), sizeAttributeName.val(), colorAttributeName.val(), parentId.val(), function (response) {
				var wrapperId = '#productColorWrapper_' + productId;

				ShowHideFilterBlock(obj, wrapperId, parentId.val(), response, 'colorblock');
			});
		});
	}
}

function colorHoverIn() {
	jQuery(this).addClass('block_hover');
	jQuery(this).find('img').css('width', '24px');
	jQuery(this).find('img').css('height', '24px');
}

function colorHoverOut() {
	jQuery(this).removeClass('block_hover');

	if (jQuery(this).attr('class').indexOf('block_selected') == -1) {
		jQuery(this).find('img').css('width', '26px');
		jQuery(this).find('img').css('height', '26px');
	}
}

function colorClick() {

	var currentSelection = jQuery(this).parent().parent().find('div.block_selected:first');
	if (currentSelection.length > 0) {
		currentSelection.removeClass('block_selected');
		currentSelection.find('img').css('width', '26px');
		currentSelection.find('img').css('height', '26px');
	}

	jQuery(this).addClass('block_selected');
	currentColor = this;
}

function sizeHoverIn() {
	jQuery(this).addClass('block_hover_small');
}

function sizeHoverOut() {
	jQuery(this).removeClass('block_hover_small');
}

function sizeClick() {
	var currentSelection = jQuery(this).parent().parent().find('div.block_selected_small');
	if (currentSelection.length > 0) {
		jQuery(currentSelection).removeClass('block_selected_small');
	}

	jQuery(this).addClass('block_selected_small');
	currentSize = this;
}

function ResetFilter(wrapperid) {
	jQuery(wrapperid + ' a').show();
}

function DisAbleOrderButton(productId) {
	clearOrderButton();

	var btn = jQuery('#orderbuttoncontrols_' + productId + ' a:first');
	if (btn.length > 0) {
		btn.attr('disabled', 'disabled');
	}
}

function EnableOrderButton(productId) {
	var btn = jQuery('#orderbuttoncontrols_' + productId + ' a:first');
	if (btn.length > 0) {
		btn.removeAttr('disabled');
	}
}

function showColor(obj, colorValue, productId, attributeName, sizeAttributeName) {
	DisAbleOrderButton(productId)

	updateOptionPrice(productId, attributeName, colorValue, sizeAttributeName, getSelectedSizeValue(productId));
	
	PageMethods.GetOptionId(productId, attributeName, colorValue, sizeAttributeName, getSelectedSizeValue(productId), function (response) {
		updateOrderButton(productId, response);

		PageMethods.GetOptionImage(attributeName, colorValue, productId, function (response) {
			if (response != '') {
				var productImage = jQuery('#mainProductImage_' + productId);

				if (productImage != null) {
					productImage.attr('src', './Controls/CatalogueImage.aspx?file=' + response);
				}

				var productImageLink = jQuery(productImage).parent();
				var optionSlide = jQuery('#slides_' + productId + ' a[href *= "' + response + '"]');

				var selectedSlideHref = optionSlide.attr('href');
				optionSlide.attr('href', productImageLink.attr('href'));
				productImageLink.attr('href', selectedSlideHref);
			}

			PageMethods.FilterSlaveAttributes(colorValue, attributeName, sizeAttributeName, productId, function (response) {
				var wrapperId = '#productSizeWrapper_' + productId;

				ShowHideFilterBlock(obj, wrapperId, productId, response, 'sizeblock');

				EnableOrderButton(productId);
			});
		});	
	});

	return false;
}

function getSelectedSizeValue(productId) {
	var selectedSize = jQuery('#productSizeWrapper_' + productId + ' div.block_selected_small').parent().attr('id');
	if (selectedSize != null) {
		var start = selectedSize.lastIndexOf('_') + 1;
		
		return selectedSize.substring(start, selectedSize.length);
	}
	else {
		return "";
	}
}

function showSize(obj, sizeValue, productId, attributeName, colorAttributeName) {
	DisAbleOrderButton(productId);

	updateOptionPrice(productId, colorAttributeName, getSelectedColorValue(productId), attributeName, sizeValue);
	
	PageMethods.FilterSlaveAttributes(sizeValue, attributeName, colorAttributeName, productId, function (response) {
		var wrapperId = '#productColorWrapper_' + productId;

		ShowHideFilterBlock(obj, wrapperId, productId, response, 'colorblock');

		PageMethods.GetOptionId(productId, colorAttributeName, getSelectedColorValue(productId), attributeName, sizeValue, function (response) {
			updateOrderButton(productId, response);

			EnableOrderButton(productId);
		});
	});
}

function getSelectedColorValue(productId) {
	var selectedColor = jQuery('#productColorWrapper_' + productId + ' div.block_selected').parent().attr('title');
	
	if (selectedColor != null) {
		var start = selectedColor.lastIndexOf('_') + 1;
		return selectedColor.substring(start, selectedColor.length);
	}
	else {
		return "";
	}
}

function updateOptionPrice(productId, firstAttributeName, firstAttributeValue, secondAttributeName, secondAttributeValue) {
	PageMethods.GetSelectedOptionPrice(productId, firstAttributeName, firstAttributeValue, secondAttributeName, secondAttributeValue, function (response) {
		if (response != '') {
			var seperator = '|';
			var prices;
			if (response.indexOf(seperator) > -1) {
				prices = response.split(seperator);
			}
			else {
				prices = new Array(response);
			}

			var priceLeadContainer = jQuery('#price' + productId + 'lead');
			priceLeadContainer.html('prijs');

			var priceContainer = jQuery('#price' + productId + 'value');
			priceContainer.text(prices[0]);

			var orderContainer = jQuery('#ordercontrols_' + productId);
			orderContainer.css('visibility', 'visible');

			var orderbuttonContainer = jQuery('#orderbuttoncontrols_' + productId);
			orderbuttonContainer.css('visibility', 'visible');

			if (prices.length > 1 && parseInt(prices[0]) < parseInt(prices[1])) {
				priceLeadContainer.html('verkoopprijs');

				var fromPriceContainer = jQuery('#fromprice' + productId + 'value')
				fromPriceContainer.text(prices[1]);

				//TODO: tijdelijk uitgeschakeld naar wens van Tricorp
				//jQuery('.frompriceInfo').show();
			}
		}
	});
}

function showNoOrderMessage(id) {
	//jQuery('#order_help_' + id).animate({ opacity: 'toggle', height: 'toggle' }, "fast");
	//if (jQuery('#order_help_' + id).css('opacity') == 0) {
		jQuery('#order_help_' + id).animate({ opacity: '100', height: '100%' }, "fast");
	//}
}

function hideNoOrderMessage(id) {
	if (jQuery('#order_help_' + id).css('opacity') == 100) {
		jQuery('#order_help_' + id).animate({ opacity: '0', height: 'toggle' }, "fast");
	}
}

//TODO: rancid little trick to prevent ordering wrong color/size combo caused by timing problem/slow DB response, remove after DB optimization!
function clearOrderButton(productId) {
	var orderButton = jQuery('#orderbuttoncontrols_' + productId + ' a');
	orderButton.attr('href', '');
}

function updateOrderButton(productId, optionId) {
	var orderButton = jQuery('#orderbuttoncontrols_' + productId + ' a');
	orderButton.attr('href', '');
	orderButton.attr('href', 'javascript:AddToCart(' + productId + ', ' + optionId + ');');
}

function ShowHideFilterBlock(obj, wrapperId, productId, response, blockPrefix) {
	jQuery.each(jQuery(wrapperId + ' a'), function (i, v) {
		var blockId = jQuery(this).attr('id');
		var start = blockId.lastIndexOf('_') + 1;
		var name = blockId.substring(start, blockId.length);
		
		if (jQuery.inArray(name, response) > -1) {
			jQuery(wrapperId + ' a#' + blockPrefix + '_' + productId + '_' + name).css('display', 'block');
		}
		else {
			jQuery(wrapperId + ' a#' + blockPrefix + '_' + productId + '_' + name).hide();
		}
	});
}

function GetProductLowestPrice(productId) {
	PageMethods.GetLowestCustomerPrice(parseInt(productId), function (response) {
		var container = $('price' + productId + 'value');
		
		if (response != '') {
			container.innerHTML = response;

			jQuery(container).parent().css('visibility', 'visible');
			jQuery(container).parent().css('display', 'block');
		}
	});
}

function ForceOptionSelection(productId, optionId, imageUrl, color, size, sizeAttributeName, colorAttributeName) {
	//TODO: Hier een betere oplossing voor verzinnen.
	//updateOptionPrice(productId, sizeAttributeName, size, colorAttributeName, color);
	
	/*//set image
	var productImage = jQuery('#mainProductImage_' + productId);
	if (productImage != null) {
		productImage.attr('src', './Controls/CatalogueImage.aspx?file=' + imageUrl);
	}

	//set color
	//colorblock_1711047_orange
	var colorBlock = jQuery('#colorblock_' + productId + '_' + color);
	if (colorBlock != null) {
		jQuery(colorBlock).find('div').addClass('block_selected');
		currentColor = colorBlock;
	}*/
}

/* Cart Functions */

function AddToCart(iProduct, iOption) {
	AddToCart(iProduct, iOption, 1, callback);
}

function GetForcedOption(catalogId, productId) {
	var option = jQuery.ajax({
		url: "AutoComplete.asmx/GetOptionIdFromProduct",
		data: "{ 'productId': '" + productId + "', 'catalogId': '" + catalogId + "' }",
		dataType: "json",
		type: "POST",
		contentType: "application/json; charset=utf-8",
		dataFilter: function (data) { return data; }
		,
		success: function (data) {
			return data.d;
		}
	});
}

function GetCatalogueId() {
	var catalog = jQuery.ajax({
		url: "AutoComplete.asmx/GetCurrentCatalogueId",
		dataType: "json",
		type: "POST",
		contentType: "application/json; charset=utf-8",
		dataFilter: function (data) { return data; },
		success: function (data) {
			currentCatId = data.d;
		},

		error: function (XMLHttpRequest, textStatus, errorThrown) {
			//alert(textStatus);
		}
	});
}

function AddToCart(iProduct, iOption, overrideAmount, callback) {
	var amountControl = jQuery('#orderAmount_' + iProduct);
	var result;
	var useColor = true;
	var useSize = true;
	var isLegalOrder = true;

	var colorWrapper = jQuery('#productColorWrapper_' + iProduct);
	if (colorWrapper.length == 0) {
		useColor = false;
	}

	var sizeWrapper = jQuery('#productSizeWrapper_' + iProduct);
	if (sizeWrapper.length == 0) {
		useSize = false;
	}

	if (useColor && colorWrapper.find('div.block_selected').length == 0 && colorWrapper.find('div.block_selected_small').length == 0) {
		isLegalOrder = false;
	}

	if (useSize && sizeWrapper.find('div.block_selected').length == 0 && sizeWrapper.find('div.block_selected_small').length == 0) {
		isLegalOrder = false;
	}
	
	if (isLegalOrder) {
		if (overrideAmount && overrideAmount != '') {
			result = AddToBasket(iProduct, iOption, overrideAmount, callback);
			hideNoOrderMessage(iProduct);
		}
		else if (amountControl != null && amountControl.val() != '') {
			result = AddToBasket(iProduct, iOption, amountControl.val(), callback);
			hideNoOrderMessage(iProduct);
		}
		else {
			result = AddToBasket(iProduct, iOption, 1, callback);
			amountControl.val('1');
			hideNoOrderMessage(iProduct);
		}

		//TODO: make configurable in web.config
		//animateToBasket(iProduct);
	}
	else {
		showNoOrderMessage(iProduct);
	}
}

function animateToBasket(productId) {
	var cart = jQuery('.winkelwagen:first');
	var productImage = jQuery('#mainProductImage_' + productId + ':first');

	if (cart && productImage) {
		var cartX = jQuery(cart).offset().left;
		var cartY = jQuery(cart).offset().top;
		var cartWidth = jQuery(cart).width();
		var originalX = jQuery(productImage).offset().left;
		var originalY = jQuery(productImage).offset().top;

		var animatedImage = jQuery(productImage).clone().appendTo(jQuery(productImage).parent());
		animatedImage.css('position', 'absolute');
		animatedImage.css('left', originalX);
		animatedImage.css('top', originalY);
		animatedImage.css('margin-top', 0);
		animatedImage.css('opacity', 0.5);

		jQuery(animatedImage).animate({ 'left': cartX, 'top': cartY, width: cartWidth }, 700, function () {
			animatedImage.fadeOut(700);
		});
	}
}

function AddToBasket(iProduct, iOption, amountOverride, callback) {
	var iCount = (amountOverride) ? amountOverride : 1;

	PageMethods.AddToBasket(iProduct, iOption, iCount, function (response) {
		if (response) {
			PageMethods.updateCartSummary(function (response) {
				jQuery('#cartContainer').html(response);
				
				if (callback != undefined) {
					callback();
				}
			});
		}
	});

	return false;
}

/*RELATED PRODUCTS*/
function ToggleRelatedProductContainer(obj) {
	var relatedProducts = jQuery(obj).parent().parent().find('div.related_product');
	var relatedHiddenProducts = jQuery(obj).parent().parent().find('div.related_product:hidden');
	
	if (relatedProducts.length > 3 && relatedHiddenProducts.length == 0) {
		jQuery(obj).parent().parent().find('div.related_product:gt(2)').slideUp(500);
		jQuery(obj).parent().prev().show();
		jQuery(obj).parent().hide();
	}
	else {
		relatedProducts.slideDown(500);
		jQuery(obj).parent().hide();
		jQuery(obj).parent().next().show();
	}

	return false;
}

function RefreshCartSummary() {
	PageMethods.updateCartSummary(function (response) {
		jQuery('#cartContainer').html(response);

		if (callback != undefined) {
			callback();
		}
	});
}

/*function simulateClick(id, type) {
	var container = jQuery('#productColorWrapper_' + id)
	if (jQuery(container).length > 0) {
		var color = jQuery(container).find('div.color_block');
		if (jQuery(color).length > 0) {
			jQuery(container).find('div.color_block:first').click();
			EnableOrderButton(id);
			updateOrderButton(id, -1);
		}
	}
}*/
