/// <reference path="jquery-1.5-vsdoc.js"/>
$.ajaxSetup({
	// Disable caching of AJAX responses
	cache: false
});

var GSD = {};

GSD.isCheckoutPage = 0; // Is the current page the checkout page
GSD.defaultPageTitle = ''; // The default page document title
GSD.modalNames = {}; // All modals are stored in GSD.modalNames define: GSD.modalNames["NameOfModalDiv"] = 0 (0:disabled | 1:enabled)

GSD.log = function () {
	if (window.console && window.console.log) {
		window.console.log(arguments[0]);
	} else if (window.opera) {
		window.opera.postError(arguments[0]);
	}
};

GSD.pageBackground = {
	/// <summary>
	/// The pageBackground object is used for setting the background image(s)
	/// of the page, via the Supersized jQuery plugin (http://www.buildinternet.com/project/supersized/).
	/// </summary>
	config: {
		slideshow: 1,
		autoplay: 1,
		start_slide: 1,
		slide_interval: 10000, //Length between transitions
		transition: 1, // 0: No transition effect, 1: Fade effect (Default), 2: Slide in from top, 3: Slide in from right, 4: Slide in from bottom, 5: Slide in from left, 6: Carousel from right to left, 7: Carousel from left to right
		transition_speed: 750,
		new_window: 1,
		pause_hover: 0,
		keyboard_nav: 0,
		performance: 3, // 0: No adjustments, 1: Hybrid - Lowers image quality during transitions and restores after completed. (Default), 2: Higher image quality, 3: Faster transition speed, lower image quality
		min_width: 0,
		min_height: 0,
		vertical_center: 0,
		horizontal_center: 0,
		fit_portrait: 0, //Portrait images will not exceed browser height
		fit_landscape: 0, //Landscape images will not exceed browser width
		navigation: 0,
		thumbnail_navigation: 0,
		slide_counter: 0,
		slide_captions: 0
                //slides wird uebergeben 
	},
	init: (function () {
		/// <summary>
		/// Initializes the Supersized plugin using the GSD.pageBackground.config values.
		/// </summary>
		jQuery(function ($) {
			if (GSD.pageBackground.config.slides.length > 0) {
				$.supersized(GSD.pageBackground.config);
			}
		});
	})()
};

// Updates the mini shopping cart in the page header with quantity and amount of shopping cart.
GSD.updateMiniShoppingCart = function(quantity, amount) {
	if (quantity > 0) {
		$("#minishoppingcartquantity").parent().removeClass("cartButtonDisabled");
		$("a.minishoppingcartcheckoutlink").show();
	} else {
		$("#minishoppingcartquantity").parent().addClass("cartButtonDisabled");
		$("a.minishoppingcartcheckoutlink").hide();
	}
	$("#minishoppingcartquantity").text(quantity);
	$("#minishoppingcartordertotal").text(amount);
};

//addArticleToCart

GSD.addArticleToCart = function (cartParams) {
      var href = document.location.protocol + "//" + window.location.href.split("/")[2];
      href += "/order/putCart.html?artID=" + cartParams.productId + "&amount=" + cartParams.quantity + "&pageID=" + cartParams.pageID + "&praefix=" + cartParams.praefix;

       //Put to cart
        $('#choose').load(href, function () {

		// Close product window.
                GSD.updateMiniShoppingCart($("#smallCartquantity").val(),$("#smallCartsum").val());
//console.log($("#smallCartquantity").val());
		GSD.disableModals();
		//GSD.showShoppingCart();
		GSD.loadingAnimation.hide();
       });     
};

/* LS 
GSD.addArticleToCart = function (cartParams) {
	// Update html with no of items in cart and order total
	var handleServerResponse = function (result) {
		GSD.updateMiniShoppingCart(result.TotalItemsInCart, result.TotalAmountOfCart);
		// Close product window.
		GSD.disableModals();
		GSD.showShoppingCart();
		GSD.loadingAnimation.hide();
	};

	var handleFailure = function (result) {
		GSD.loadingAnimation.hide();
		alert('Error. Could not add article to shopping cart.');
	};

	if (GSD.parseCartParams(cartParams)) {
		GSD.loadingAnimation.show({ delay: 250 });
		// Call web service to update shopping cart,
		//App_Code.Site.WebServices.ECommerceService.AddArticleToCart(cartParams.articleNumber, cartParams.productId, cartParams.quantity, handleServerResponse, handleFailure);
	}
};

//updateArticleInCart
GSD.updateArticleInCart = function (cartParams) {
	// Update html with no of items in cart and order total
	var handleServerResponse = function (result) {
		GSD.updateMiniShoppingCart(result.TotalItemsInCart, result.TotalAmountOfCart);
		GSD.showShoppingCart();
		GSD.loadingAnimation.hide();
		//Handle low order value view by removing class on checkout container
		if (GSD.isCheckoutPage) {
			if (result.OrderAmountBelowMinimum) {
				$(".checkoutcontainer").addClass("lowordervalue");
			} else {
				$(".checkoutcontainer").removeClass("lowordervalue");
			}
		}
	};

	var handleFailure = function (result) {
		GSD.loadingAnimation.hide();
		alert('Error. Could not update shopping cart.');
	};

	if (GSD.parseCartParams(cartParams)) {
		GSD.loadingAnimation.show({ delay: 250 });
		// Call web service to update shopping cart,
		App_Code.Site.WebServices.ECommerceService.UpdateArticleInCart(cartParams.articleNumber, cartParams.productId, cartParams.quantity, handleServerResponse, handleFailure);
	}
};

// removeArticleFromCart
GSD.removeArticleFromCart = function (articleNumber) {

	// Callback for success.
	var handleServerResponse = function (result) {
		if (result.TotalItemsInCart <= 0 && GSD.isCheckoutPage) {
			document.location.href = document.location.href;
		} else {
			GSD.updateMiniShoppingCart(result.TotalItemsInCart, result.TotalAmountOfCart);
		}

		//Handle low order value view by removing class on checkout container
		if (result.OrderAmountBelowMinimum && GSD.isCheckoutPage) {
			$(".checkoutcontainer").addClass("lowordervalue");
		}

		GSD.showShoppingCart(true);
		GSD.loadingAnimation.hide();
	};

	// Callback for failure.
	var handleFailure = function (result) {
		GSD.loadingAnimation.hide();
		alert('Error. Could not remove article from shopping cart.');
	};

	GSD.loadingAnimation.show({delay: 250});
	// Call web service to remove article from shopping cart
	App_Code.Site.WebServices.ECommerceService.RemoveArticleFromCart(articleNumber, handleServerResponse, handleFailure);
};

GSD.parseCartParams = function (cartParams) {
	if (cartParams.quantity) {
		cartParams.quantity = cartParams.quantity.replace(',', '.').replace(/[^0-9\.]/g, '');
	}

	return cartParams.articleNumber && cartParams.productId && !isNaN(cartParams.quantity);
};
end LS */

GSD.loadModal = function (ele, path) {
	GSD.closeShoppingCart();

	if (GSD.modalNames[ele] == 0) {
		$("#modalBackground").css({
			"opacity": "0.7"
		});

		if (typeof path !== 'undefined' && path != null) {

			$("#modalBackground").fadeIn("fast");
			GSD.loadingAnimation.show();

			if (path.indexOf('?') != -1) {
				path += '&framework=ajax';
			} else {
				path += '?framework=ajax';
			}

			$("#" + ele).load(path, function () {
				GSD.centerModal(ele);
				$("#" + ele).show();
				GSD.loadingAnimation.hide();
				$("body:first").addClass("ismodal");
				GSD.modalNames[ele] = 1;
			});
		} else {
			GSD.centerModal(ele);
			$("#modalBackground").fadeIn("fast");
			$("#" + ele).show();
			$("body:first").addClass("ismodal");
			GSD.modalNames[ele] = 1;
		}
	}
};

GSD.disableModals = function (keepBackground) {
	$.each(GSD.modalNames, function (key, value) {
		if (value == 1) {
			if (!keepBackground) {
				$("#modalBackground").fadeOut("fast");
			}
			$("#" + key).fadeOut("fast", function () {
				$("#" + key).empty();
			});
			GSD.modalNames[key] = 0;
		}
	});

	$("body").removeClass("ismodal");
};

GSD.centerModal = function centerModal(ele) {
	var $modal = $("#" + ele);
	var windowWidth = $(window).width();
	var windowHeight = $(window).height();
	var hiddenViewPort = jQuery(document).scrollTop(); // Number of pixels not visible due to scrolling.
	var modalHeight = $modal.outerHeight();
	var modalWidth = $modal.outerWidth();
	var leftmargin = (modalWidth / 2) * -1;
	var topmargin = (modalHeight / 2) * -1;
	var top = parseInt((windowHeight / 2) + hiddenViewPort, 10); //"50%";

	if ($modal.height() > windowHeight) {
		topmargin = 0;
		top = "20";
	}

	$modal.css({
		"position": "absolute",
		"top": top + "px",
		"left": "50%",
		"margin-left": leftmargin + "px",
		"margin-top": topmargin + "px"
	});

	//IE6 fix 
	$("#modalBackground").css({
		"height": windowHeight,
		"width": windowWidth
	});
};

GSD.showProductByNumber = function(productNumber) {
	var BASE_URL = '';
	var url = false;

	if (productNumber) {
           $.ajax({
	  	url: "catalog/getSEOLink.html?artNo=" + productNumber,
	        dataType: 'JSON',
		type: 'GET',
		success: function (data) {
		  //url = BASE_URL + '?ProductGroupID=' + productGroupId + '&productnumber=' + productNumber;
                  if(data.length == 1) {
                    url = data[0].link;
		    GSD.loadModal('modalProduct', url);
                  }
                }
           });
	}

};


GSD.scrollable = function (items, options) {

    if (!(items && items.length)) {
        return;
    }

    var defaults = {
        size: 1,
        siblingScrollerWidth: 0,
        hasPrevNextButtonWidth: true
    },
    counter = 0;

    var settings = $.extend(defaults, options);

    items.scrollable();
    var scrollable = items.data("scrollable");

    if (scrollable.getSize() > settings.size) {
        items.find("a.next").removeClass("disabled");
    }

    scrollable.onSeek(function (event, index) {
        if (this.getIndex() >= this.getSize() - settings.size) {
            items.find("a.next").addClass("disabled");
        }
    });

    scrollable.onBeforeSeek(function (event, index) {
        if (this.getIndex() >= this.getSize() - settings.size) {
            if (index > this.getIndex()) {
                return false;
            }
        }
    });

    items.find(".items a").click(function (e) {
        e.preventDefault();
        e.stopPropagation();
        GSD.disableModals(true);
        GSD.loadModal("modalProduct", $(this).attr("href"));
    });

    // Set error handler to all images
    var allImages = items.find('img').bind('error', function () {
        // Could not resolve image link, hide image 						
        $(this).hide();
    }),
    images = allImages.slice(0, settings.size),
    // Add extra width for prev and next button if settings.hasPrevNextButtonWidth = true
    nextWidth = settings.hasPrevNextButtonWidth ? items.find('.next').width() : 0; 

    // Calculate total width of first X items in sibling
    // scroller and set width of scroller to that value.   
    allImages.each(function () {
        var node = $(this).one('load', function () {
            var width = node.closest("div").outerWidth();        
            settings.siblingScrollerWidth = settings.siblingScrollerWidth + width;
            counter += 1;
            if (counter === settings.size || counter === images.length) {
                items.width(settings.siblingScrollerWidth + nextWidth);
            }
        });

        // if image is complete, call load method.
        this.complete && node.load();
    });
};


GSD.modalProduct = {
	addToCartErrorMessage: '',

	addToCart: function () {
		if ($("#AddToCart").hasClass('enabled')) {

                        var size = 0;

                        if($("#Size").val()) {
                          var size = $("#Size").val();
                          $("#ProductID").val(size);
                        }
                          
//console.log(size);
//console.log($("#ProductID").val());

			GSD.addArticleToCart({
				//articleNumber: size,
				productId: $("#ProductID").val(),
				quantity: $("#Quantity").val().replace(",", "."),
				praefix: $("#praefix").val(),
				pageID: $("#pageID").val()
			});
		} else {
			alert(this.addToCartErrorMessage);
		}
	},

	checkArticleValid: function () {
		if ($("#AddToCart").length > 0) {
			// if ($('#ProductID').val() && $('#Quantity').val() && $('#Quantity').val().length > 0 && $('#Quantity').val() != "0" && $('#Size').val().length > 0) {
			if ($('#ProductID').val() && $('#Quantity').val() && $('#Quantity').val().length > 0 && $('#Quantity').val() != "0" ) {
				if ($("#AddToCart").hasClass('disabled')) {
					$("#AddToCart").removeClass('disabled');
					$("#AddToCart").addClass('enabled');
				}
			} else {
				if ($("#AddToCart").hasClass('enabled')) {
					$("#AddToCart").removeClass('enabled');
					$("#AddToCart").addClass('disabled');
				}
			}
		}
	},

	closeModalWindow: function () {
		GSD.disableModals();
		if (typeof GSD.defaultPageTitle === 'string') {
			document.title = GSD.defaultPageTitle;
		}
		return false;
	},

	showSizeGuide: function (title) {
		var $sizeGuide = $("#SizeGuide");

		if ($sizeGuide.length) {
			$sizeGuide.dialog({ autoOpen: true, resizable: false, minHeight: 400, minWidth: 400, title: title, modal: true });
			$sizeGuide.dialog("open");
		}

		return false;
	},

	selectColor: function (color, article, hassizes) {
		if (hassizes != 0) {
			GSD.loadingAnimation.show({ delay: 250 });
			var scrollable = ".product-scrollable";
			var size = 4;

			if ($(scrollable).length == 0) {
				scrollable = scrollable + "-old";
				//size = 3;
			}

                        $scrollable = $(scrollable);

                        if ($scrollable.length && $scrollable.find('.items').children().length) {
                          $scrollable.find(".items .colorcode-" + color + ' :first').trigger('click');
                          scrollableObj = $scrollable.data("scrollable");
                          if (scrollableObj) {
                           scrollableObj.begin(0);
                           window.setTimeout(function () {
                             // Enable/disable scrolling.
                             // Use timeout since the scrollable plugin may change disabled/enabled.
                             var enabledScroll = (scrollableObj.getSize() > size);
                             jQuery(scrollable).find("a.next").toggleClass('disabled', !enabledScroll);
                           }, 10);
                          }
                        }                        
 

			$("#Size").attr('disabled', 'disabled');

			// disable cart button
			if ($("#AddToCart").length > 0) {
				if ($("#AddToCart").hasClass('enabled')) {
					$("#AddToCart").removeClass('enabled');
					$("#AddToCart").addClass('disabled');
				}
			}

			$.ajax({
				//url: "/Site/Ajax/ProductSizes.aspx?ajax=true&color=" + color + "&article=" + article,
				url: "/catalog/getProductSizes.html?artID=" + article,
				dataType: 'JSON',
				type: 'GET',
				success: function (data) {
					var i,
						$option,
						noItems = data.length,
						options = [];

					for (i = 0; i < noItems; i++) {
						$option = $('<option value="' + data[i].optionValue + '">' + data[i].optionDisplay + '</option>');

						//if (i === 1 && noItems === 2) {
						if (i == 0) {
							$option.attr('selected', 'selected');
						}

						options.push($option.get(0));
					}

					$("#Size").empty().append(options).removeAttr('disabled');

                                        /* orbiz has no small images i.e. scrollableObj for old product*/
					if(typeof scrollableObj != 'undefined'){
					 if (scrollableObj.getSize() <= size) {
						jQuery(scrollable + " a.prev").addClass("disabled");
						jQuery(scrollable + " a.next").addClass("disabled");
					 }
			                }	

                                        /* orbiz prices */
                                        jQuery.get("/catalog/getArticlePrice.html?artID=" + data[0].optionValue, function(data) {
                                          $("#ArticlePrice").html(data);
                                        });
                                        
                                        //$('.basic').html(data[0].optionPrice);
                                        $("#ProductID").val(data[0].optionValue);

					GSD.modalProduct.checkArticleValid();
					GSD.loadingAnimation.hide();
				},
				error: function (request, status, error) {
					//alert("Could not get sizes.");
					GSD.loadingAnimation.hide();
				}
			});
		} else {

			// orbiz 
                        // $("#Size").val(article);
                        jQuery.get("/catalog/getArticlePrice.html?artID=" + article, function(data) {
                              $("#ArticlePrice").html(data);
                        });
                        $('#ProductID').val(article);

			GSD.modalProduct.checkArticleValid();
		}
	},

    /// <summary>
    ///  Trac 477 - Make #zoomicon clickable and  display zoom-controls when user moves mouse over the #zoomicon. 
    ///
    ///  - When user moves mouse over the #zoomicon, we don't close the zoom controls anymore.
    ///  - When user clicks the #zoomicon we trigger the cloud-zoom mouseup event to display zoom controls.
    ///
    ///  (cannot save the $('div.mousetrap') in memory beacuse it is removed and added by cloud-zoom everytime a the modal product dialog opens)
    ///
    /// </summary>

    initZoomButtonEvents: function () {
        var zoomIcon = $('#zoomicon');

        // Add mouseout event over zoomicon, trigger cloud-zoom mouseleave if the releated target isn't the mousetrap div.
        zoomIcon.bind('mouseout', function (e) {
            var target = e.relatedTarget;
            if (target && target.className !== 'mousetrap') {
                $('div.mousetrap').trigger('mouseleave');
            }
        });

        // trigger cloud-zoom mouseup event on #zoomicon click 
        $('#page').delegate('#zoomicon', 'click', function () {

            // Remove lens and big zoom-image
            $('.cloud-zoom-big').remove();
            $('.cloud-zoom-lens').remove();

            var link = $('#imageZoom img').attr('src'),
			    images = [];

            // In todays solution, we create a moustrap div everytime we load a image 
            // we need to trigger 'mouseup' event on the last div.moustrap when a user presses the zoomicon. 			
            // (we should fix this in a later release...see TODO in img.onload bellow)			
            $('div.mousetrap').each(function () {
                var node = $(this);
                // find all div.moustrap with the right image and save it to a array
                if (node.data().imgsrc === link) {
                    images.push(node);
                }
            });

            // trigger mouseup on the last item in the image array.
            images.length && images[images.length - 1].trigger('mouseup');
        });

        // trigger cloud-zoom mousemove when user moves the mouse over the #zoomicon (get event from jQuery data).
        var getMousemoveHandler = (function () {
            var data = $('div.mousetrap').data();
            for (var key in data) {
                var fn, e = data[key].events;
                if (e && (fn = e.mousemove[0])) {
                    return fn.handler;
                }

                return new function () { };
            }
        })();

        zoomIcon.bind('mousemove', getMousemoveHandler);
    },

        init: function (options) {

		this.addToCartErrorMessage = options.addToCartErrorMessage;
		this.isTestOrder = options.isTestOrder;
		this.initZoomButtonEvents();

		var initScrollableProductImages = function () {

			var size = 4;
			var ele = ".product-scrollable";
			var $items = $(ele);
			var scrollableOptions = {};
			var scrollable;

			if (!$items.length) {
				ele = ele + "-old";
				$items = $(ele);
				//size = 3;
			} else {
				scrollableOptions.vertical = true;
			}

			if (!$items.length) {
				return;
			}

			$items.scrollable(scrollableOptions);
			scrollable = $items.data("scrollable");
			if (scrollable.getSize() > size) {
				$items.find("a.next").removeClass("disabled");
				$items.find("a.next").addClass("enabled");
			}

			scrollable.onSeek(function (event, index) {
				if (this.getIndex() >= this.getSize() - size || this.getSize <= size) {
					$items.find("a.next").addClass("disabled");
				}
			});

			scrollable.onBeforeSeek(function (event, index) {
				if (this.getIndex() >= this.getSize() - size) {
					if (index > this.getIndex()) {
						return false;
					}
				}
			});

                        var productContainers = $("#ProductLeft, #ProductMediaButtons, #ProductDetailImage, #ProductDetailsContainer"),
			    cloudzoom = $('.cloud-zoom'),
			    imageZoom = $('#imageZoom'),
			    images = $items.find(".items img"),
                            iconoverlay = $('.iconoverlay'), 
                            returnFn = function () { return false; };

                        images.click(function () {

                            var $this = $(this);

                            $("#productvideo").empty();
                
                            GSD.productVideo.close();
                
                            // Do nothing if user clicks the thumb that's already active
                            if ($this.hasClass('active') && !GSD.productVideo.isActive()) {
                               return;
                            }
				
                            if (GSD.productVideo.isVideoNode($this)) {
                                GSD.productVideo.open($this);
                                return;
                            }
 

                            var url = $this.attr("src").replace("/small/", "/large/"),
					wrap = $("#mainimage_wrap"),
					img = new Image();

                            if (ele.indexOf("-old") !== -1) {
					wrap = $("#mainimage_wrap_old");
                            }

                            wrap.find('img').attr({ src: '' });

                            // add click handler on #imageZoom that returns false. Need this so the image don't opens in another window (see Trac #511).
                            imageZoom.bind('click', returnFn);

                            img.onload = function () {
                                wrap.fadeTo("slow", 1);
                                wrap.find("img:first").attr("src", url);

                                
                              /* Hide product info and init zoom, only on new product template! */
                              if (ele.indexOf("-old") == -1) {
                                  var zoomUrl = url.replace("/large/", "/zoom/");
                                  wrap.find("a").attr("href", zoomUrl);
                                  /* TODO: We should not initialize cloud zoom on every image load. This creates a new div.mousetrap with new events every time. We should use cloud-zoom-gallery instead! */
                                  cloudzoom.CloudZoom({
                                      mouseOver: function () {
                                          productContainers.addClass("invisible");
                                      },
                                      mouseOut: function () {
                                          productContainers.removeClass("invisible");
                                      },
                                      mouseLeave: function (event) {
                                          var e = event.relatedTarget;
                                          // if the mouse is over the zoomicon, then do not close the zoom controls.
                                          if (e && e.id == 'zoomicon') {
                                              return false;
                                          }
                                      }
                                  });
                              }
                            };

                            iconoverlay.click(function () {
                              $(this).prev().click();
                            });


                            img.src = url;
 
                            // activate item
			    $items.find(".items img").removeClass("active");
			    $(this).addClass("active");

                        }).parent()
                          .filter('.article, .product')
                          .first()
			  .find('img:first')
                          .trigger('click'); 
		};


                $(document).ready(function () {
                        // init product video

                        $.publish('/gsd/modal/product/init', [{
                        streamingUrl: GSD.settings.streamingUrl
                        }]);

                        // Color fabric images.
			var $colors = $("#product-colors li");

			window.setTimeout(function () {

				initScrollableProductImages();

				if ($colors.length) {
					// Select the first color if there is only one.
					// Must be done after the call to initScrollableProductImages above!
					if ($colors.length === 1) {
						$colors.filter(":first").click();
					}
				}

                                // Init sibling navigation scroller
                                GSD.scrollable($("#siblingscroller"), {
                                size: 3,
                                siblingScrollerWidth: 0
                                });

                                // Init aquarell drawing scrollable
                                GSD.scrollable($(".drawing-scrollable"), {
                                size: 1,
                                siblingScrollerWidth: 0,
                                hasPrevNextButtonWidth: false
                                });

                                // TODO: Adjust and use GSD.scrollable
                                // Init suitable for scroller
                                (function () {
                                    var size = 3,
					counter = 0,
					suitableforScrollerWidth = 0,
					scrollable,
					$items = $("#suitableforscroller"),
					$images;

                                        if (!$items.length) {
                                         return;
                                        }

					$items.scrollable();
					scrollable = $items.data("scrollable");

					if (scrollable.getSize() > size) {
						$items.find("a.next").removeClass("disabled");
					}

					scrollable.onSeek(function (event, index) {
						if (this.getIndex() >= this.getSize() - size) {
							$items.find("a.next").addClass("disabled");
						}
					});

					scrollable.onBeforeSeek(function (event, index) {
						if (this.getIndex() >= this.getSize() - size) {
							if (index > this.getIndex()) {
								return false;
							}
						}
					});

                                        // Calculate total width of first 6 items in suitable
                                        // for scroller and set width of scroller to that value.
                                        $images = $("#suitableforscroller img").slice(0, size);
                                        $images.one('load', function () {
                                          suitableforScrollerWidth = suitableforScrollerWidth + $(this).closest("div").outerWidth();
                                          counter = counter + 1;
                                          if (counter === size || counter === $images.length) {
                                              $("#suitableforscroller").width(suitableforScrollerWidth + $("#suitableforscroller .next").width() + "px");
                                          }
                                          }).each(function () {
                                          if (this.complete) {
                                           $(this).load();
                                          }
                                        });


				})();

			}, 100);

                        if (!options.isModal) {
                           GSD.modalNames['modalProductBase'] = 0;
                           GSD.loadModal('modalProductBase');
                        }

		});
	}
};

/*---------------------------------------------------------------------------
Shopping Cart Summary
---------------------------------------------------------------------------*/
/* LS
GSD.showShoppingCart = function (deleted, callback) {
	var $cart;
	var executeCallback = function() {
		if (typeof callback === 'function') {
			callback();
		}
	};

	if ($("#shoppingcart-checkout").length == 0) {
		$cart = $("#CartSummary");
		$cart.load("/Site/Ajax/ShoppingCart.aspx", function () {
			$cart.slideDown(250);
			executeCallback();
		});
	} else {
		if (deleted) {
			$("#shoppingcart-checkout").load("/Site/Ajax/ShoppingCartSummary.aspx");
		}
		$("#ordertotals-checkout").load("/Site/Ajax/OrderTotalsSummary.aspx");
	}

	$('#header .minishoppingcart').addClass('cartbuttonDisabled');
};

end LS */

GSD.closeShoppingCart = function closeShoppingCart() {
	$("#CartSummary").hide();
	$('#header .minishoppingcart').removeClass('cartbuttonDisabled');
};

/*----------------------------------------------------------------------------
Search Results
-----------------------------------------------------------------------------*/
/// <summary>
/// Init the searchresultspage
/// </summary>
GSD.searchPageInit = function(initIndex) {

	$(document).ready(function() {
		var tabContainer,
			options = {
				enableFragmentSelection: true,
				tabTextSelector: 'h2',
				initialIndex: initIndex,
				tabsId: 'searchtabnav',
				tabsPlacement: $.fn.tabnav.tabsPlacements.before
			};

		// Init tabs
		$('#searchpanes').tabnav(options);
		tabContainer = $('.t-searchresult1 .tabs');

		// Set the correct class on the UL
		$('a:eq(1)', tabContainer).
			css("width", "140px").
			click(function() {
				$(this).closest("ul").addClass("second-tab");
			});

		$("a:eq(0)", tabContainer).click(function() {
			$(this).closest("ul").removeClass("second-tab");
		});

		if ($("#searchpanes-1:hidden").length) {
			// The first pane is hidden
			$(".tabs").addClass("second-tab");
		}
		
		//Make tab links not clickable if only one tab has content.
		var $container = $('.onetabcontent');
		
		// Tabs unclickable if only one kind of hits.
		if ($container.length) {
			$container.find("ul.tabs a").unbind('click').bind('click', function(e){
				e.preventDefault();
			});
		}

		// Search only if search query is given.
		$('#search-box a.button').click(function(e) {
			var $query = $('#search-box input[type=text].searchterm');
			if ($query.length && $query.val().trim()) {
				return true;
			} else {
				e.preventDefault();
			}
		});

		// Redirect user to first link when click on search result list item
		$("ol.searchresult li").click(function () {
			window.location = $(this).find("a").attr("href");
			return false;
		});
	});
};

/*----------------------------------------------------------------------------
Checkout
-----------------------------------------------------------------------------*/
/// <summary>
/// Init the checkoutpage
/// </summary>
GSD.checkout = (function () {
	var checkBoxTermsId,
		customValidatorTermsId;

	var termsIsValid = function () {
		return $('#' + checkBoxTermsId).is(':checked');
	};

	var toggleTerms = function (valid) {
		$('#' + customValidatorTermsId).toggleClass('invalid', !valid);
	};

	var initTermsCheckbox = function () {
		$('#' + checkBoxTermsId).change(function () {
			toggleTerms(termsIsValid());
		});
	};

	return {

		validateTerms: function (source, args) {
			args.IsValid = termsIsValid();
			toggleTerms(args.IsValid);
		},

		updateOrderSummary: function () {
			GSD.loadingAnimation.show();
			$("#ordertotals-checkout").load("/Site/Ajax/OrderTotalsSummary.aspx", function () {
				GSD.loadingAnimation.hide();
			});
		},

		init: function (checkOutPage) {

			var initialCustomerTabIndex,
				tabContainer,
				customerTabOptions;

			initialCustomerTabIndex = $('#' + checkOutPage.selectedCustomerPanelElementId).val() || 0; // The selected tab (login/new customer)
			checkBoxTermsId = checkOutPage.checkBoxTermsId;
			customValidatorTermsId = checkOutPage.customValidatorTermsId;

			customerTabOptions = {
				callBackSelectPane: function (state, $pane, $tab) {
					$('#' + checkOutPage.selectedCustomerPanelElementId).val(state.$panes.index($pane));
				},
				enableFragmentSelection: true,
				tabTextSelector: 'h2',
				initialIndex: initialCustomerTabIndex,
				tabsPlacement: $.fn.tabnav.tabsPlacements.before
			};

			initTermsCheckbox();

			// Init tabs
			$('.user-tabs').tabnav(customerTabOptions);
			tabContainer = $('.t-checkout1 .tabs');

			// Set the correct class on the UL
			$('a:eq(1)', tabContainer).
				css("width", "140px").
				click(function () {
					$(this).closest("ul").addClass("second-tab");
					$(this).parents(".tabholder").addClass("tab2");
				});

			$("a:eq(0)", tabContainer).click(function () {
				$(this).closest("ul").removeClass("second-tab");
				$(this).parents(".tabholder").removeClass("tab2");
			});

			if (initialCustomerTabIndex == 1) {
				tabContainer.parent(".tabholder").addClass("tab2");
				$(".tabs").addClass("second-tab");
			}

			var initDeliveryPointSource = function ($parent) {
				$parent.find('input.deliverypointsource[type=text]').live('change', function () {
					var $this = $(this);
					$this.val($this.val().trim());
					if (!$this.val()) {
						return;
					}
					var $radioButton = $('#blockdeliveries input[type=radio]:checked:first');

					if ($radioButton.length) {
						if (typeof checkOutPage.deliveryTypeUpdatePanelFunction === 'function') {
							checkOutPage.deliveryTypeUpdatePanelFunction();
						}
					}
				});
			};

			initDeliveryPointSource($('#col1'));
		}
	};
})();

/*----------------------------------------------------------------------------
Assortment view
-----------------------------------------------------------------------------*/
GSD.assortmentListSwipe = {};
GSD.assortmentListSwipe.pageWidth = null;
GSD.assortmentListSwipe.swipeSpeed = 500;
GSD.assortmentListSwipe.pageNumber = 1;
GSD.assortmentListSwipe.pageID = null;
GSD.assortmentListSwipe.arttype = 0;
GSD.assortmentListSwipe.init = function (pageID,arttype) {
	//Tooltips
	$('body').append('<div id="tooltip" style="position: absolute; z-index:10;"></div>');
	var previewElem = $('#tooltip');
	var xOffset = 30;
	var queryPageNumber = null;
	var i = 0;
  
  if(pageID) {
    GSD.assortmentListSwipe.pageID = pageID;
  }

  if(arttype) {
    GSD.assortmentListSwipe.arttype = arttype;
  }


	$(".assortment-page li", "#assortment-container").live({
		click: function () {
			$(previewElem).empty().hide();
		},
		mouseenter: function (event) {
			$(".prod-tooltip", this).clone().appendTo($(previewElem)).show();
			$(previewElem).css({
				'top': (event.pageY - 10) + 'px',
				'left': (event.pageX + 30) + 'px'
			}).show();
		},
		mouseleave: function () {
			$(previewElem).empty().hide();
		},
		mousemove: function (event) {

			if (event.pageX > 930) {
				xOffset = -190;
			} else {
				xOffset = 30;
			}

			$(previewElem).css({
				'top': (event.pageY - 10) + 'px',
				'left': (event.pageX + xOffset) + 'px'
			});
		}
	});

	$(".prod-tooltip", "#assortment-container").hide();

	queryPageNumber = GSD.getQueryString("page");
  //console.log('pageNumber:', queryPageNumber);
	if (queryPageNumber) {
		GSD.assortmentListSwipe.pageNumber = queryPageNumber; // Overwrite if page has querystring
	}

	GSD.assortmentListSwipe.pageWidth = $("#assortment-container").css("width").split("px")[0];

	var pageNumber = GSD.assortmentListSwipe.pageNumber;
	var totalPages = $(".pagnation a:not(.step-btn)").size();
  //console.log('totalPages:', totalPages);
  
	if (pageNumber != 1) {
		GSD.assortmentListSwipe.goToPage(pageNumber, false);
	}

	// Create empty pages
	for (i = 1; i <= totalPages; i++) {
		if ($(".page-nr-" + i, "#assortment-pagelist").size() == 0) {
			if (i < pageNumber) {
				$('#assortment-pagelist .page-nr-' + pageNumber).before('<li class="assortment-page page-nr-' + i + '"></li>');
			} else {
				$("#assortment-pagelist").append('<li class="assortment-page page-nr-' + i + '"></li>');
			}
		}
	}

	// Set page width and height for pages  
	$(".assortment-page", "#assortment-container").
		css("width", $("#assortment-container").css("width")).
		css("height", $("#assortment-container").css("height"));

	// Set width of list
	if ($(".pagnation a").size()) {
		$("#assortment-pagelist").css("width", ($(".pagnation a").size() * GSD.assortmentListSwipe.pageWidth) + "px");
	} else {
		// no paging (show all)
		$("#assortment-container, .assortment-page").css("height", "auto");
	}

	$('.pagnation a, .pagnation span').click(function (e) {
		e.preventDefault();

		// What page number?
		if ($(this).hasClass("step-btn")) {
			if ($(this).hasClass("next")) {
				if (pageNumber < totalPages) {
					$(".pagnation .selected").removeClass("selected").next().addClass("selected");
					pageNumber++;
				}
			} else if (pageNumber > 1) {
				$(".pagnation .selected").removeClass("selected").prev().addClass("selected");
				pageNumber--;
			}
		} else {
			pageNumber = $(this).text();
			$(".pagnation .selected").removeClass("selected");
			$(this).addClass("selected");
		}

		var selector = "#assortment-pagelist .page-nr-" + pageNumber;

		// Check if we need to load a new page
		if ($(selector + ":empty").size()) {
			var searchQuery = GSD.getQueryString("CMS_SearchString");
			//var href = window.location.href.split("?")[0];
			//href += "?page=" + pageNumber + "&framework=empty";
      
      // orbiz 10.06.2011
      var pageid = GSD.assortmentListSwipe.pageID;
      var arttype = GSD.assortmentListSwipe.arttype;
      var href = document.location.protocol + "//" + window.location.href.split("/")[2];
      if(pageID == 40011) {
        var searchkey = $('#searchTerm').val();
        var searchcolor = $('#color').val();
        var searchsize = $('#size').val();
        var sort = $('#sort').val();

         href += "/search/searchArticleUl.html?pageID=" + pageid + "&pageNo=" + pageNumber  + "&arttype=" + arttype;
         href += "&search=" + searchkey + "&color=" + searchcolor + "&size=" + searchsize + "&sort=" + sort;  
      }  
      else { 
         href += "/catalog/getArticleUl.html?pageID=" + pageid + "&pageNo=" + pageNumber  + "&arttype=" + arttype;
      }
			if (searchQuery) {
				href += "&CMS_SearchString=" + searchQuery;
			}

			// Load a new page
			$('<div>').load(href + " " + selector, function () {
        $(selector).append($(">li", this).html());

				// Hide tooltips
				$(".prod-tooltip", "#assortment-container").hide();

				// Go to new page
				GSD.assortmentListSwipe.goToPage(pageNumber, true);
			});
		} else { // Go to new page
			GSD.assortmentListSwipe.goToPage(pageNumber, true);
		}
	});
};

GSD.assortmentListSwipe.goToPage = function(pageNumber, swipeEffect) {
	var marLeft = "-" + ((pageNumber - 1) * GSD.assortmentListSwipe.pageWidth) + "px";
	if (swipeEffect) {
		$("#assortment-pagelist").animate({ marginLeft: marLeft }, GSD.assortmentListSwipe.swipeSpeed, 'swing');
	} else {
		$("#assortment-pagelist").css("margin-left", marLeft);
	}
};

GSD.getQueryString = function(name) {
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if (results == null) {
		return "";
	} else {
		return decodeURIComponent(results[1].replace(/\+/g, " "));
	}
};

GSD.initPage = (function () {
	/// <summary>
	/// GSD.initPage is executed on each page load.
	/// </summary>
	$(document).ready(function () {

		// Set property indicating if the current page is the checkout.
		GSD.isCheckoutPage = $("body.p-checkout").length;

		// Set class on cart if empty
		if ($("#minishoppingcartquantity").html() == "0") {
			$("a.minishoppingcartcheckoutlink").hide();

			if ($("#shoppingcart-checkout").length != 0) {
				$("#minishoppingcartquantity").parent().addClass("cartButtonDisabled");
				$("a.minishoppingcartcheckoutlink");
			}
		}
		else {
			$("#minishoppingcartquantity").parent().removeClass("cartButtonDisabled");
			$("a.minishoppingcartcheckoutlink").show();
		}

		// Set click event for the mini shopping cart
		$('#minishoppingcartsum,#minishoppingcartquantity').click(function (e) {
			if (!$("#CartSummary").is(':visible') && $("#minishoppingcartquantity").text() !== "0" && $("#shoppingcart-checkout").length == 0) {
				e.stopPropagation();
				GSD.showShoppingCart();
			}
		});

		/*---------------------------------------------------------------
		MODAL FUNCTIONALITY
		---------------------------------------------------------------*/
		// default product modal
		var productModalName = "modalProduct";

		GSD.modalNames[productModalName] = 0;

		// autoresize when window is moved or resized
		$(window).resize(function () {
			$.each(GSD.modalNames, function (key, value) {
				if (value == 1) {
					GSD.centerModal(key);
				}
			});
		});

		// prevent < and > from being entered in any textbox/textarea
		$('input[type=text], input[type=password], textarea').live('keypress', function (e) {
			if (e.which === 62 || e.which === 60) {
				e.preventDefault();
			}
		});

		// Product class links are displayed in a modal window - detail view
		$('a.product').live('click', function (e) {
      var $this = $(this);

			if ($this.attr('href') !== undefined) {
				var url = $this.attr('href');
				e.preventDefault();
				if (url) {
					url += '';
				}

				GSD.loadModal(productModalName, url);
			}
		});
	});
})();

GSD.setUniqueRadioButton = function(nameAttributePattern, currentRadioButton) {
	/// <summary>
	/// GSD.setUniqueRadioButton ensures that only one radiobutton is checked
	/// among the radiobuttons whose name matches the specified regex.
	/// </summary>
	var i, l, inputElement,
		re = new RegExp(nameAttributePattern),
		inputElements = document.getElementsByTagName('input');
	l = inputElements.length;

	for (i = 0; i < l; i++) {
		inputElement = inputElements[i];

		if (inputElement.type === 'radio') {
			if (re.test(inputElement.name) && inputElement.name != currentRadioButton.name) {
				inputElement.checked = false;
			}
		}
	}

	currentRadioButton.checked = true;
};

GSD.loadingAnimation = (function () {
	var defaultShowDelay = 0, // Number of milliseconds to delay the showing with.
			defaultZIndex = 20000,
			id = 'loadinganimation', // Html id attribute.
			showTimer;

	var getLoader = function () {
		return $('#' + id);
	};

	return {
		show: function (options) {
			var $loader, zIndex, delay;
			if (options) {
				if (options.zIndex) {
					zIndex = options.zIndex;
				}
				if (options.delay) {
					delay = options.delay;
				}
			}
			// Shows the loader element.
			$loader = getLoader();
			if (zIndex) {
				$loader.css('z-index', zIndex);
			}
			if (delay <= 0) {
				$loader.show();
			} else {
				showTimer = setTimeout(function () { // Show the image after an initial time period.
					$loader.show();
				}, delay || defaultShowDelay);
			}
		},
		hide: function () {
			// Hides the loader element.
			if (showTimer) {
				clearInterval(showTimer);
			}
			var $loader = getLoader();
			if ($loader.length) {
				$loader.hide();
				if (defaultZIndex && $loader.css('z-index') !== defaultZIndex) {
					// Reset the default z-index value if another value was set.
					$loader.css('z-index', defaultZIndex);
				}
			}
		}
	};
})();

jQuery.fn.ForceNumericOnly = function(allowDecimal) {
	return this.each(function() {
		$(this).keydown(function(e) {
			var key = e.which;
			// allow backspace, tab, delete, arrows, numbers, comma, period and keypad numbers ONLY
			return (key == 8 ||
				key == 9 ||
				key == 46 ||
				(allowDecimal && key == 110) ||
				(allowDecimal && key == 188) ||
				(allowDecimal && key == 190) ||
				(key >= 37 && key <= 40) ||
				(key >= 48 && key <= 57) ||
				(key >= 96 && key <= 105));
		});
	});
};


 $("#ProductColourAndPatternsOld img").live({
                click: function (event) {
                        $("#ProductColourAndPatternsOldBig").css({
                                'top': (event.pageY - 300) + 'px',
                                'left': (event.pageX - 420) + 'px'
                        }).show();
                }
        });


$("#ProductColourAndPatternsOldBig").live({
                click: function() {
                       $("#ProductColourAndPatternsOldBig").hide();
                       }
        });

 
$(".faq").live({
               click: function () {
                    faqitem = $(this).attr('id'); 
                    $("#" + faqitem + "text").toggle('slow', function() {
                   // Animation complete.
                   });
               }
        });

GSD.modalProduct.setcolortext = function () {
       var selectedcolortext = $("li.product-colors-selected .colourname").text();
        $("#ProductColourName span").text(selectedcolortext);
};

/*----------------------------------------------------------------------------
StartPage
-----------------------------------------------------------------------------*/

GSD.startPage = (function () {

            var eleContent2;
            var getHeight = function ($e) {

                         if ($e.length) {
                                     return $e.outerHeight(true);
                         } else {
                                     return 0;
                         }
            };

            var placePuffs = function () {
                         /// <summary>
                         /// Positions the second content area on the start page dynamically.
                         /// Either absolutely at the bottom of the page or below the first content area if
                         /// there is not sufficient space above the footer.
                         /// </summary>

                         var eleHeader = $("#header"),
                                     elePage = $("#page"),
                                     eleFooter = $("#footer"),
                                     eleContent1 = $("#content1"),
                                     availableHeight,
                                     eleOffset;

 

                         availableHeight = getHeight(elePage) - getHeight(eleHeader) - getHeight(eleFooter) - getHeight(eleContent1) - getHeight(eleContent2);

                         if (eleContent1.length) {
                                     eleOffset = eleContent1.offset().left;
                         } else {
                                     eleOffset = parseInt(($(window).width() - eleContent2.outerWidth(true)) / 2, 10);
                         }

                         if (availableHeight < 0) {
                                     eleContent2.removeClass("absolute").css("left", "auto");
                         } else {
                                     eleContent2.addClass("absolute").css("left", eleOffset);
                         }
            };


            var init = function () {
                         $(function () {
                                     eleContent2 = $("#content2");

                                     if (eleContent2.length) {
                                                  placePuffs();
                                                  $(window).resize(placePuffs);
                                     }
                         });
            };

 

            return {
                         'init': init
            };
} ());

/*----------------------------------------------------------------------------
Elara Benutzerfuehrung
-----------------------------------------------------------------------------*/
$(document).ready(function () {

                   GSD.showcc = function () {

                         var cc = 1;

                         if($("#setdeladr").val()) {
                           /* Lieferadressformular relevant */
                            cc = 0;
                         }

                         if($("#usedeliveraddress:checked").val() == 1) {
                           /* Lieferadressformular relevant */
                            cc = 0;
                         }

                         if($("#hascc").val()) {
                           /* Daten schon verifiziert */
                            cc = 2;
                         }

                         if(cc > 0) {
                           $("#cc_elara").show();
                           if(cc == 1) {
                             $("#deliverandpayment").attr("action", "https://postmaster.clickpay.de/ken_5220.cfm");
                           }
                         }
                   }
   

                if($("#cc:checked").val() == 3) {
                        GSD.showcc(); 
                }



   $("#cc").live({
                click: function() {
                        GSD.showcc(); 
                       }
        });

   $("#usedeliveraddress").live({
                click: function() {
                       $("#cc_elara").hide();
                       $("#deliverandpayment").attr("action", "/order/deliverandpayment_check.html");
                       }
        });

   $("#prepaid").live({
                click: function() {
                       $("#cc_elara").hide();
                       $("#deliverandpayment").attr("action", "/order/deliverandpayment_check.html");
                       }
        });

   $("#bill").live({
                click: function() {
                       $("#cc_elara").hide();
                       $("#deliverandpayment").attr("action", "/order/deliverandpayment_check.html");
                       }
        });

   $("#corr").live({
                click: function() {
                       $("#cc_elara").hide();
                       $("#deliverandpayment").attr("action", "/order/deliverandpayment_check.html");
                       }
        });
});

