/*-------------------- Globals --------------------*/
var mycarousel_itemList;


/*-------------------- init if document is ready --------------------*/
jQuery(document).ready(function() {
	/*-------------------- init topnav --------------------*/
	ManorNav.TopNav.initTopNav();
	
	/*-------------------- init accordion --------------------*/
    jQuery('#accordion li.acc a.acc_handle').click(function(event) {
		event.preventDefault();
        var myParent    = jQuery(this.parentNode);
        var myStage     = jQuery(this.parentNode).find('div.stage');
		
		//console.log(myStage);
		
        jQuery(this).blur();
        if(myParent.hasClass('lock')) {
            return false;
        }

        if(myParent.hasClass('open')) {
            jQuery('#accordion .acc').addClass('lock');

            myStage.slideUp(500, function() {
                myParent.removeClass('open');
                jQuery('#accordion .acc').removeClass('lock');
            });
        } else {
            jQuery('#accordion .acc').addClass('lock');
            var openParent    = jQuery('#accordion li.acc.open');
            var openStage     = jQuery('#'+openParent.attr('id')+' div.stage');
            var openOldHeight = openStage.height();

            openStage.slideUp(500, function() {
                openParent.removeClass('open');
            });

            myStage.slideDown(500, function() {
                myParent.addClass('open');
                jQuery('#accordion .acc').removeClass('lock');
            });
        }
    });
	
	/* Class and Class.extend */
	(function(){var a=false,b=/xyz/.test(function(){xyz})?/\b_super\b/:/.*/;this.Class=function(){};Class.extend=function(g){var f=this.prototype;a=true;var e=new this();a=false;for(var d in g){e[d]=typeof g[d]=="function"&&typeof f[d]=="function"&&b.test(g[d])?(function(h,i){return function(){var k=this._super;this._super=f[h];var j=i.apply(this,arguments);this._super=k;return j}})(d,g[d]):g[d]}function c(){if(!a&&this.init){this.init.apply(this,arguments)}}c.prototype=e;c.constructor=c;c.extend=arguments.callee;return c}})();

	/**
	 * @author: Angelo Dini
	 * @param: trigger, container
	 * @settings: add class "lock" to trigger for autohide
	 * @description: some basic expandable/collapsable function
	 */
	jQuery.fn.expander = function (options) {
		var $this = this;
		// build options
		var settings = {
			triggerClass: '.trigger',
			containerClass: '.trigger-container',
			duration: 500
		};
		var options = jQuery.extend({}, settings, options);
		// attach event
		return {
			init: function () {
				var containers = jQuery(options.containerClass);
				var triggers = jQuery(options.triggerClass);

				$that = this;
				triggers.bind('click', function (event) {
					if (jQuery(this).hasClass('collapsed')) {
						event.preventDefault();
						
						//close all other tabs
						$that1 = this;
						triggers.each(function (index, item) {
							if (!jQuery(item).hasClass('collapsed')) {
								var container = containers[triggers.index(this)];
								$that.trigger(jQuery(this), container);
							}
							
						});
							
						
						var container = containers[triggers.index(this)];
						// init trigger
						$that.trigger(jQuery(this), container);
					}
				});
				
				// check for pre-collapsed elements
				triggers.each(function (index, item) {
					if(jQuery(item).hasClass('collapsed')) {
						jQuery(containers[index]).css('display', 'none');
					}
				});
			},
			trigger: function (target, container) {
				(target.hasClass('collapsed')) ? this.show(target, container) : this.hide(target, container);
			},
			show: function (target, container) {
				target.removeClass('collapsed').addClass('expanded');
				jQuery(container).slideDown(options.duration);
			},
			hide: function (target, container) {
				target.removeClass('expanded').addClass('collapsed');
				jQuery(container).slideUp(options.duration);
			}
		};
	};
	
	var accordionExpander = jQuery('.account_accordion').expander({
		triggerClass: '.account_accordion_drawer',
		containerClass: '.account_accordion_content'
	});
	accordionExpander.init();
	
	var tableExpander = jQuery('.tbl_accordion').expander({
		triggerClass: '.trigger',
		containerClass: '.accordion_container'
	});
	tableExpander.init();
	
	/*-------------------- init mainnav --------------------*/
	ManorNav.MainNav.createNavigation();
	
	jQuery('.productoffering').each(function() {
		jQuery('.productoffering').hover(function() {
			jQuery('.img_off', this).css('display', 'none');
			jQuery('.img_on', this).css('display', 'block');
			
		}, function() {
			jQuery('.img_on', this).css('display', 'none');
			jQuery('.img_off', this).css('display', 'block');
		});
	});
	
	if (jQuery.browser.msie) {
		jQuery('#mainnav > li > a').each(function(){
			var $link = jQuery(this),
				text = $link.find('span').text(),
				$shadow = jQuery('<span class="fakeshadow" />').text(text).appendTo($link);
		});
	}
	
	
	/*-------------------- init jCarousel --------------------*/
	jQuery('#startcarousel').each(function() {
		mycarousel_itemList = jQuery('#startcarousel').children('li');
	
		jQuery('#startcarousel').jcarousel({
			wrap: 'circular',
			scroll: 1,
			itemVisibleInCallback: {onBeforeAnimation: mycarousel_itemVisibleInCallback},
			itemVisibleOutCallback: {onAfterAnimation: mycarousel_itemVisibleOutCallback},
			
			itemLastInCallback: {onBeforeAnimation: resizeImg},
			itemFirstInCallback: {onBeforeAnimation: resizeImg}
		});
	});
	
	jQuery('#campaigncarousel').each(function() {
		mycarousel_itemList = jQuery('#campaigncarousel').children('li');
	
		jQuery('#campaigncarousel').jcarousel({
			wrap: 'circular',
			scroll: 1,
			itemVisibleInCallback: {onBeforeAnimation: mycarousel_itemVisibleInCallback},
			itemVisibleOutCallback: {onAfterAnimation: mycarousel_itemVisibleOutCallback}
		});
	});
	
	jQuery('#inhaltscarousel').each(function() {
		mycarousel_itemList = jQuery('#inhaltscarousel').children('li');
	
		jQuery('#inhaltscarousel').jcarousel({
			wrap: 'circular',
			scroll: 1,
     		visible: 4,
			itemVisibleInCallback: {onBeforeAnimation: mycarousel_itemVisibleInCallback },
			itemVisibleOutCallback: {onAfterAnimation: mycarousel_itemVisibleOutCallback},
			itemFirstInCallback: {onBeforeAnimation: normalCarouselImg,
			                      onAfterAnimation: normalCarouselImg},
			itemFirstOutCallback: {onBeforeAnimation: normalCarouselImg}
		});
	});
	
	jQuery('#produktdetail').each(function() {
		mycarousel_itemList = jQuery('#produktdetail').children('li');
		var productPos = jQuery('#productPos:input').val();
		if (productPos <= 3) {
			var temp = Number(productPos);
			productPos = mycarousel_itemList.size() - 2 + temp;
		} else {
			productPos = productPos - 2;
		}
		jQuery('#produktdetail').jcarousel({
			wrap: 'circular',
			start: productPos,
			scroll: 1,
     		visible: 8,
			itemVisibleInCallback: {onBeforeAnimation: mycarousel_itemVisibleInCallback },
			itemVisibleOutCallback: {onAfterAnimation: mycarousel_itemVisibleOutCallback},
			itemFirstInCallback: {onBeforeAnimation: normalCarouselImg,
			                      onAfterAnimation: normalCarouselImg},
			itemFirstOutCallback: {onBeforeAnimation: normalCarouselImg}
		});
	});
	

	/*-------------------- init tooltip --------------------*/
	initTooltips();
	
	/*-------------------- Tell a Friend --------------------*/
	if((jQuery("#errorId").hasClass("errormsg"))){
		jQuery("#tellafriend").show();
	}else{				
		jQuery("#tellafriend").hide();
	}
	
	/*-------------------- content tabs --------------------*/
	
	// add offs
	jQuery('#tabsContent .tabscontent_jquery').each(function() {
		jQuery(this).removeClass('off');
		jQuery(this).addClass('off');
	});
	//select the first item
	jQuery('#tab0').removeClass('off');
	

	jQuery(".tab_buttons_jquery li a").click(function(){		
		jQuery('.tab_buttons li').each(function() {
			jQuery(this).removeClass('active');
		});
	
		jQuery('#tabsContent .tabscontent_jquery').each(function() {
			jQuery(this).addClass('off');
		});
		
		var tabClasses = jQuery(this.parentNode).attr('class').split(" ");
		var tabId;
		if(tabClasses.length > 1) {
			for(var i = 0; i < tabClasses.length; i++) {
				if(tabClasses[i].search(/tab\d+/) != -1) {
					tabId = tabClasses[i]
				}
			}
		} else {
			tabId = tabClasses[0];
		}
		
		jQuery('#' + tabId).removeClass('off');
		
		jQuery(this.parentNode).addClass('active');
		jQuery(this).blur();
		return false;
	});	
	
	/*----------------------- Init shadowbox ---------------------------*/
	initShadowbox();

	/*--------------------------------- Hide/Display commentbox -------------------------------------*/
	jQuery('.guestBookComment').parent().next().hide();
	jQuery('.editEntryComment').parent().next().next().hide();
	
	
	jQuery('.guestBookComment').click(function(){
		jQuery(this).parent().next().show();
		return false;
	});
	jQuery('.editEntryComment').click(function(){
		jQuery(this).parent().next().next().show();
		jQuery(this).parent().next().hide();
		return false;
	});
	jQuery('#sendComment').click(function(){
		jQuery(this).parent().next().hide();
	});
	jQuery('#editComment').click(function(){
		jQuery(this).parent().next().hide();
	});
});


/*---------------------------------------------------------------------------------------------------*/
/*-------------------------------------- some functions -------------------------------------------*/
/*---------------------------------------------------------------------------------------------------*/
/* helper for carousel */
function initCart() {
	var numberOfProducts = jQuery('#cartcontent tr').length;
	if (numberOfProducts > 3) {
		jQuery('#cartcontent').each(function() {
			jQuery(this).jScrollPane({
				showArrows: true,
				arrowSize: 10,
				maintainPosition: false
			});
			
			// Adapt total size so prices are still right-aligned
			jQuery(this).parents('.cart').addClass('cart-jscroll');
		});
	} else {
		jQuery('#cartcontent').css('height', 'auto');
	}
};

function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt) {
  // The index() method calculates the index from a
  // given index who is out of the actual item range.
	//console.debug(mycarousel_itemList.length);
  var idx = carousel.index(i, mycarousel_itemList.length);
  carousel.add(i, jQuery(mycarousel_itemList[idx - 1]).html());
};

function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt) {
  carousel.remove(i);
};

function resizeImg(carousel, item, i, state, evt) {
	var outbound = jQuery(item);
	var inbound = carousel.container;
	
	/* animation for center image */
	if(state == 'init' || state == 'prev') inbound = jQuery(inbound.find('li')[1]);
	if(state == 'next') inbound = jQuery(inbound.find('li')[2]);
	
	inbound.animate({'width': '200px'}, 300);
	inbound.find('img').animate({'width': '200px'}, 300);

	if(state == 'init') {
		/* prevent flicker and ajust image on "init" */
		outbound.css('width', '158px');
		inbound.find('img').css('width', '199px');
	} else {
		/* animation for left/right-flip */
		outbound.animate({'width': '158px'}, 200);
		outbound.find('img').animate({'width': '158px'}, 200);
	}
}

function reinitShadowbox() {
	Shadowbox.clearCache(); 
	Shadowbox.setup(); 
}
function fadeCarouselImg(carousel, item, i, state, evt) {
	jQuery('.imgcontainer img', item).css('opacity','0.4');
	reinitShadowbox();
}
function normalCarouselImg(carousel, item, i, state, evt) {
	jQuery('.imgcontainer img', item).css('opacity','1');
}
/* helper for tabs */
function textCounter(maxlimit) {  				
	if(jQuery(".comments").val().length > maxlimit){
		jQuery(".comments").attr("value", jQuery(".comments").val().substring(0, maxlimit));
	}				
}

/* set equal columns height */
function setEqualHeight(columns) {  
  var tallestcolumn = 0;  
  columns.each(  
    function() {  
      currentHeight = jQuery(this).height();  
      if(currentHeight > tallestcolumn) {  
        tallestcolumn  = currentHeight;  
      }  
    }  
  );  
  columns.height(tallestcolumn);  
}

function initShadowbox(){
	if(typeof(Shadowbox) != "undefined") {
		Shadowbox.init({
		    handleOversize: "resize",
		    modal: false,
		    viewportPadding: 0,
		    animate: false,
		    resizeDuration: 1000000,
		    enableKeys: true,
		    /*Marjans property, set to false if you want full keys support*/
		    enableKeysEscOnly: true
		});
	}
}

function initTooltips() {
	jQuery('.infoicon').each(function() {
		//hide tooltip
		jQuery(this).next('.tooltip').hide();
		if(jQuery('#Tooltip').length == 0) {
			ManorNav.Tooltip.createTooltip();
		}
		//show tooltip on click
		jQuery(this).mouseover(function(e){
			ManorNav.Tooltip.tooltipClicked(e);
		});
	});
	
	jQuery('.infoicon_cloud').each(function() {
		//hide tooltip
		if (jQuery(this).next('.tooltip_cloud').length > 0) {
			jQuery(this).next('.tooltip_cloud').hide();
			if(jQuery('#TooltipCloud').length == 0) {
				ManorNav.TooltipCloud.createTooltip();
			}
			ManorNav.TooltipCloud.tooltipClicked(this);
		}
	});
}

//format #'###.##
function formatNumber(number) {
	if (number == 0 || isNaN(number)) {
		return "0.00";
	}
	var integerPart = Math.floor(number);
	var decimalPart = "" + Math.round(number * 100);
	decimalPart = decimalPart.substring(decimalPart.length - 2, decimalPart.length);
	var result = "";
	while (integerPart > 0) {
		var part = integerPart % 1000;
		var wholePart = (integerPart - part) / 1000;
		if (wholePart > 0) {
			part = "" + part;
			var i = 3 - part.length;
			while (i > 0) {
				part = "0" + part;
				i--;
			}
			result = "'" + part + result;
		} else {
			result = part + result;
		}
		integerPart = wholePart
	}
	//alert(result + " " + decimalPart);
	
	result = result + "." + decimalPart;
	return result;
}

function recalculateTotal(form, id){
	var selectedProduct;
	if(id != null){
		selectedProduct = id.split(':')[2];
	}
	var arInputs = form.getElementsByTagName('input');
	var amount = 0;
	var price = 0;
	for(var index = 0; index < arInputs.length; index++) {
		if(id == null ||arInputs[index].id.indexOf(selectedProduct) != -1){
			if(arInputs[index].id.indexOf('giftCardAmount') != -1){
				amount = arInputs[index].value;
			} else if(arInputs[index].id.indexOf('price') != -1){
				price = arInputs[index].value;
			} else if(arInputs[index].id.indexOf('total') != -1){
				arInputs[index].value = formatNumber(amount * price);
			}
		}
	}

}
//Script executed on add to cart button click
function onAddToCartButtonClick() {
   	dcsMultiTrack.apply(this, arguments);
    return false;
}

function getQuantityGrid(input){
	//finding the amount input element
	var quantity = jQuery(input).parent().parent().find('.amount').val();
	return quantity;
}

function getQuantityList(input){
	//finding the amount input  
	var quantity = jQuery(input).parent().parent().children().get(0).value;
	return quantity;
}
function changeGridView(flag, isListView) {
	if (isListView) {
		if (flag) {
			var listDiv = jQuery('.active_list');
			var gridDiv = jQuery('.grid');
			//add class to grid, remove it from list
			jQuery(gridDiv).removeClass('grid');
			jQuery(gridDiv).addClass('active_grid');
			jQuery(listDiv).removeClass('active_list');
			jQuery(listDiv).addClass('list');
		} else {
			var listDiv = jQuery('.list');
			var gridDiv = jQuery('.active_grid');
			//remove from grid, add to list
			jQuery(listDiv).removeClass('list');
			jQuery(listDiv).addClass('active_list');
			jQuery(gridDiv).removeClass('active_grid');
			jQuery(gridDiv).addClass('grid');
		}
	}
}

function changeListView(flag, isListView) {
	if (!isListView) {
		if (flag) {
			var listDiv = jQuery('.list');
			var gridDiv = jQuery('.active_grid');
			//add class to list, remove it from grid
			jQuery(gridDiv).removeClass('active_grid');
			jQuery(gridDiv).addClass('grid');
			jQuery(listDiv).removeClass('list');
			jQuery(listDiv).addClass('active_list');
		} else {
			var listDiv = jQuery('.active_list');
			var gridDiv = jQuery('.grid');
			//remove from list, add to grid
			jQuery(listDiv).removeClass('active_list');
			jQuery(listDiv).addClass('list');
			jQuery(gridDiv).removeClass('grid');
			jQuery(gridDiv).addClass('active_grid')
		}
	}
}

