/**
 * @author jlang
 */
var Eybl = function() {
	/* private properties */
	var _triggerPasswordRecoveryUrl = null;
	var _showProductsDetailsUrl = null;
	var _addItemToCartUrl = null;
	var _compareProductsUrl = null;
	var _addProductToComparisonUrl = null;
	var _removeProductFromComparisonUrl = null;
	var _showProductSetVariantsUrl = null;
	var _showProductSetVariantUrl = null;
	var _removeItemFromCartCallback = null;
	var _loadFsiViewerUrl = null;
	var _clearProductComparisonUrl = null;
	var _updateProductDetailPriceUrl = null;
	
	
	var _currentFsiSrc = null;

	/* private methods */

	return {
		/* public properties */
		GRABBAG_ID: "fgb_" + (new Date).getTime(),

		init : function(
				triggerPasswordRecoveryUrl,
				showProductsDetailsUrl,
				addItemToCartUrl,
				compareProductsUrl,
				addProductToComparisonUrl,
				removeProductFromComparisonUrl,
				addProductToWishlistUrl,
				removeProductFromWishlistUrl,
				showProductSetVariantsUrl,
				showProductSetVariantUrl,
				clearProductComparisonUrl,
				loadFsiViewerUrl,
				updateProductDetailPriceUrl) {
			_triggerPasswordRecoveryUrl = triggerPasswordRecoveryUrl;
			_showProductsDetailsUrl = showProductsDetailsUrl;
			_addItemToCartUrl = addItemToCartUrl;
			_compareProductsUrl = compareProductsUrl;
			_addProductToComparisonUrl = addProductToComparisonUrl;
			_removeProductFromComparisonUrl = removeProductFromComparisonUrl;
			_addProductToWishlistUrl = addProductToWishlistUrl;
			_removeProductFromWishlistUrl = removeProductFromWishlistUrl;
			_showProductSetVariantsUrl = showProductSetVariantsUrl;
			_showProductSetVariantUrl = showProductSetVariantUrl;
			_clearProductComparisonUrl = clearProductComparisonUrl;
			_loadFsiViewerUrl = loadFsiViewerUrl;
			_updateProductDetailPriceUrl = updateProductDetailPriceUrl;
		},

		setRemoveItemFromCartCallback: function(cb)
		{
			_removeItemFromCartCallback = cb;
		},
		
		removeItemFromCart: function(entryNumber)
		{
			if(_removeItemFromCartCallback != null)
			{
				_removeItemFromCartCallback(entryNumber);
			}
		},
		
		/* public methods */
		triggerPasswordRecovery : function(email, callback) {
			$.getJSON(_triggerPasswordRecoveryUrl, {
				'email' : email
			}, callback);
		},

		formatCurrency : function(value) {
			return '&euro; ' + $.formatNumber(value, {
				format : "#.###,00",
				locale : "at"
			});
		},
		
		showProductsDetails: function(productCode, isClosable)
		{
			if(typeof(isClosable) == 'undefined' || isClosable == null)
			{
				isClosable = true;
			}
			$('#products-details').show();
			$('#products-details').load(_showProductsDetailsUrl, { productCode: productCode, isClosable: isClosable}, function() {
				// Add tab functionality
				$(".tab-me").tabMe();
				custom_selectboxes();
				align_images();
			});
			Eybl.loadProductComparisons(productCode);
		},
		
		hideProductsDetails: function()
		{
			$('#products-details').hide();
			$(document).trigger("contentResized");
		},
		
		showProductSetVariants: function(setProductCode, selectedVariants, saveCallback)
		{
			$('#produktset').load(_showProductSetVariantsUrl, { productCode: setProductCode, selectedVariants: selectedVariants}, function() {
				$('#produktset').show();
				
				if(typeof(saveCallback) != "undefined" && saveCallback != null)
				{
					$('#btn-save-set-variants').click(function() {
						var selectedVariantElems = $('.selected-set-variants');
						var selectedVariants = [];
						selectedVariantElems.each(function() {
							selectedVariants[selectedVariants.length] = $(this).val();
						});
						saveCallback(selectedVariants);
					});
				}
			});
		},
		
		showProductSetVariant: function(domElementId, variantCode)
		{
			if(domElementId)
			{
				$('#' + domElementId).load(_showProductSetVariantUrl, { productCode: variantCode, domElementId: domElementId });
			}
		},
		
		showProductComparisons: function(productCode)
		{
			if (!$('#produktvergleich').is(':visible'))
			{
				Eybl.loadProductComparisons("", true);
				Eybl.hideProductsDetails();
			}
			else
			{
				Eybl.hideProductComparisons();
			}
			$(document).trigger("contentResized");
		},
		
		loadProductComparisons: function(productCode, force)
		{
			if ($('#produktvergleich').is(':visible') || force)
			{
				$('#products-comparisons').load(_compareProductsUrl, { productCode: productCode }, function() {
					if ($('#produktvergleich').html() != null)
					{
						$('#button-compare').html($('#button-close-compare-text').html());
						$('#products-comparisons').show();

						// Produktvergleich equal headlines
						$("#produktvergleich .txt:eq(0) h3, #produktvergleich .txt:eq(1) h3, #produktvergleich .txt:eq(2) h3, #produktvergleich .txt:eq(3) h3").equalHeight();
						$("#produktvergleich .txt:eq(0) h4, #produktvergleich .txt:eq(1) h4, #produktvergleich .txt:eq(2) h4, #produktvergleich .txt:eq(3) h4").equalHeight();

						// Produktvergleich equal property rows
						for (var i = 0; i <= 99; i++) { // maximum number of properties should not be bigger than 99
							$("#produktvergleich .properties:eq(0) div:eq("+i+"), #produktvergleich .properties:eq(1) div:eq("+i+"), #produktvergleich .properties:eq(2) div:eq("+i+"), #produktvergleich .properties:eq(3) div:eq("+i+")").equalHeight();
						} //end for
						
						// Produktvergleich equal columns
						$("#produktvergleich .properties").equalHeight();
						
						// Produktvergleich pretty checkboxes
						$("#produktvergleich input[type=checkbox]").prettyCheckboxes();
					}

					// check uncheck compare checkbox in product list
					$("#produktliste input[type=checkbox]").each(function()
					{
						if ($(this).attr("id").indexOf("prod-vergleich-") == 0)
						{
							id = $(this).attr("id").substring(15);
							if ($("#compared-product-"+id).attr("id") != null)
							{
								$('#prod-vergleich-'+id).attr("checked","checked");
								$('label[for="'+$('#prod-vergleich-'+id).attr("id")+'"]').addClass("checked"); // it's a pretty checkbox
							}
							else
							{
								$('#prod-vergleich-'+id).attr("checked","");
								$('label[for="'+$('#prod-vergleich-'+id).attr("id")+'"]').removeClass("checked"); // it's a pretty checkbox
							}
						}
					});
				});
			}
		},
		
		hideProductComparisons: function()
		{
			$('#products-comparisons').hide();
			$('#button-compare').html($('#button-compare-text').html());
		},
		
		addItemToCart: function(productCode, quantity, setVariants, errorCallback, successCallback)
		{
			$.getJSON(_addItemToCartUrl, {
				'productCode' : productCode,
				'quantity' : quantity,
				'setVariantCodes': setVariants
			}, function(data, textStatus) {
				if(data.success)
				{
					$('.cart-numberOfEntries').html(data.numberOfEntries);
					if(typeof(gb) != 'undefined' && gb != null) gb.setCartValue(data.numberOfEntries);
					EyblTracker.trackAddToCart(productCode, quantity);
//					Grabbag.showCheckout();
					if(typeof(data.message) != 'undefined' && data.message)
					{
						Eybl.showErrorDialog(data.message);
					}
					if(typeof(successCallback) != 'undefined' && successCallback != null)
					{
						successCallback();
					}
				}
				else
				{
					Eybl.showErrorDialog(data.error);
					if(typeof(errorCallback) != 'undefined' && errorCallback != null)
					{
						errorCallback();
					}
				}
			})
		},
		
		toggleProductOnComparison: function(productCode, add)
		{
			if (add == true)
			{
				$.getJSON(_addProductToComparisonUrl, {
					'productCode' : productCode
				}, function() {
					Eybl.loadProductComparisons("");
				});
			}
			else
			{
				$.getJSON(_removeProductFromComparisonUrl, {
					'productCode' : productCode
				}, function() {
					Eybl.loadProductComparisons("");
				});
			}
		},
		
		addProductToComparison: function(productCode)
		{
			$.getJSON(_addProductToComparisonUrl, {
				'productCode' : productCode
			}, function() {
				Eybl.loadProductComparisons("");
			});
		},
		
		removeProductFromComparison: function(productCode, isFirst)
		{
			$.getJSON(_removeProductFromComparisonUrl, {
				'productCode' : productCode
			}, function() {
				Eybl.loadProductComparisons("");
				if (isFirst)
				{
					Eybl.hideProductComparisons();
				}
			});
		},

		clearProductComparison: function()
		{
			$.getJSON(_clearProductComparisonUrl, { }, function() {
				Eybl.loadProductComparisons("");
				Eybl.hideProductComparisons();
			});
		},

		toggleProductOnWishlist: function(productCode, add)
		{
			if (add == true)
			{
				Eybl.addProductToWishlist(productCode);
			}
			else
			{
				Eybl.removeProductFromWishlist(productCode);
			}
		},
		
		addProductToWishlist: function(productCode)
		{	
			$.getJSON(_addProductToWishlistUrl, {
				'productCode' : productCode
			}, function(data, textStatus)
			{
				if(data.success)
				{
					if(typeof(gb) != 'undefined' && gb != null) gb.setWishlistValue(data.numberOfEntries);
				}
			});
		},
		
		removeProductFromWishlist: function(productCode)
		{
			$.getJSON(_removeProductFromWishlistUrl, {
				'productCode' : productCode
			}, function(data, textStatus)
			{
				if(data.success)
				{
					if(typeof(gb) != 'undefined' && gb != null) gb.setWishlistValue(data.numberOfEntries);
				}
			});
		},
		
		showErrorDialog: function(text)
		{
			$("#error-dialog p").html(text);
			$("#error-dialog-trigger").trigger('click');
		},
		
		disableAddToCartButtons: function(cssClass)
		{
			$('.' + cssClass)
				.html('')
				.attr('href', 'javascript: void(0);')
				.attr('onclick', '')
				.css('background-image', 'none');
		},
		
		setCurrentFsiSrc: function(fsiSrc)
		{
			_currentFsiSrc = fsiSrc;
		},
		
		loadFsiViewer: function()
		{
			if(_currentFsiSrc != null)
			{
				$('#fsiViewer').load(_loadFsiViewerUrl, { src: _currentFsiSrc}, function() {

				});
			}
		},
		
		updateProductDetailPrice: function(productCode, quantity, domElementId)
		{
			$.getJSON(_updateProductDetailPriceUrl, {
				'productCode' : productCode,
				'quantity' : quantity
			}, function(data, textStatus) {
				if(data.success)
				{
					$('#' + domElementId).html(Eybl.formatCurrency(data.price));
				}
				else
				{
					alert(data.error);
				}
			})
		}
	};
}();

var EyblProductFinder = function() {
	var _url = null;
	var _xhrUrl = null;
	var _domContainerElementId = null;
	var _params = {};
	
	var getParamsAsQueryString = function()
	{
		var qs = '?';
		for (var k in _params)
		{
			if(typeof(_params[k]) != 'undefined' && _params[k] != null && _params[k].toString().length > 0)
			{
				qs += '&' + k + '=' + _params[k];
			}
		}
		return qs;
	}
	
	return {
		setXhrUrl: function(xhrUrl)
		{
			_xhrUrl = xhrUrl;
		},
		
		setUrl: function(url)
		{
			_url = url;
		},

		setDomContainerElementId: function(domContainerElementId)
		{
			_domContainerElementId = domContainerElementId;
		},

		setParams: function(params)
		{
			_params = params;
		},
		
		setParam: function(name, value)
		{
			// reset category hierarchy
			if(name == 'category1')
			{
				EyblProductFinder.setParam('category2', '');
			}
			if(name == 'category2')
			{
				EyblProductFinder.setParam('category3', '');
			}
			if(name == 'category3')
			{
				EyblProductFinder.setParam('category4', '');
			}
			if(name == 'category4')
			{
				Eybl.clearProductComparison();
				EyblProductFinder.setParam('size', '');
			}
			
			// set the value
			_params[name] = value;
		},
		
		hasParam: function(name)
		{
			return _params[name] != null;
		},

		load: function()
		{
			$('#' + _domContainerElementId).load(_xhrUrl, _params, function() { custom_checkboxes(); });
		},
		
		openList: function()
		{
			window.location.href = _url + getParamsAsQueryString();
		}
	};
}();

var _tag=new WebTrends();
_tag.dcsGetId();
var EyblTracker = function() {
	var _params = {};
	
	return {
		setParam: function(name, value)
		{
			_tag.WT[name] = value;
		},
		
		setExtParam: function(name, value)
		{
			_tag.DCSext[name] = value;
		},
		
		trackAddToCart: function(productCode, qty)
		{
			if (window.location.protocol != "https:") // webtrends-tracking only for non-https requests
			{
				dcsMultiTrack(
					 'DCS.dcsuri', '/cart/add.do'
					,'WT.si_n',    'shoppingcart'
					,'WT.si_x',    '2'
					,'WT.pn_sku',   productCode
					,'WT.tx_u',     qty
					,'WT.tx_e',     'a'
				);
			}
		},
		
		trackRemoveFromCart: function(productCode, qty)
		{
			if (window.location.protocol != "https:") // webtrends-tracking only for non-https requests
			{
				dcsMultiTrack(
					 'DCS.dcsuri', '/cart/remove.do'
					,'WT.si_n',    'shoppingcart'
					,'WT.si_x',    '2'
					,'WT.pn_sku',   productCode
					,'WT.tx_u',     qty
					,'WT.tx_e',     'r'
				);
			}
		},
		
		track: function()
		{
			if (window.location.protocol != "https:") // webtrends-tracking only for non-https requests
			{
				_tag.dcsCollect();
			}
		}
	};
}();


;(function($){
	
	$.fn.JSpinner=function(options){
		
		return this.each(function(options){
			
				var defaults = {
					min: 1,
					max: 99,
					less:"/images/spinner_less.png",
					more:"/images/spinner_more.png",
					size:[16,16]
				};

				//initial variables
				var opts = $.extend(defaults, options),
				$input = $(this),
				$containerDiv = $('<div class="spinnerContainer"></div>'),
				$containerWrap = $('<div></div>');
				
				
								
				$input
				.wrap($containerDiv)
				.wrap(
					$containerWrap
					.css({
						position:"absolute",
						width:opts.size[0]+opts.size[0]+$input.outerWidth()
					})
				)
				.before(
						$("<a href='javascript:void(0);'>&nbsp;</a>").css({
							position:"absolute",
							width:opts.size[0],
							height:opts.size[1],
							overflow:'hidden',
							top:0,
							left:0,
							"font-size":"1px",
							"text-indent":"-1000em",
							"background-image":"url("+opts.less+")"
						}).click(function(){
							var val=parseInt($input.val());
							if(typeof(val) == "number" && val >= opts.min && val-1 >= opts.min){
								val-=1;
								$input.val(val);
							} else {
								$input.val(opts.min);
							}
							// trigger ajax driven recalculation of price depending on quantity
							$input.focus();
							$input.blur();
						})
				).after(
						$("<a href='javascript:void(0);'>&nbsp;</a>").css({
							position:"absolute",
							width:opts.size[0],
							height:opts.size[1],
							overflow:'hidden',
							top:0,
							left:opts.size[0]+$input.outerWidth(),
							"font-size":"1px",
							"text-indent":"-1000em",
							"background-image":"url("+opts.more+")"
						}).click(function(){
							var val=parseInt($input.val());
							if(typeof(val) == "number" && val >= opts.min && val+1 <= opts.max){
								val+=1;
								$input.val(val);
							} else {
								$input.val(opts.max);
							}
							// trigger ajax driven recalculation of price depending on quantity
							$input.focus();
							$input.blur();
						})
				).css({
					position:"absolute",
					left:opts.size[0],
					top:0,
					"text-align":"center"
				}).removeClass("spinner").change(function(){
					var val=parseInt($input.val());
					if(typeof(val) == "number" && val >= opts.min && val <= opts.max){
						$input.val(val);
					} else {
						$input.val(opts.min);
					}					
				});
		});
	};
	
})(jQuery);
