jQuery.noConflict();

// Set Base URL
var baseUrl = '';
function setBaseUrl(url) {
	baseUrl = url;
}

// Set Skin URL
var skinUrl = '';
function setSkinUrl(url) {
	skinUrl = url;
}

/*
 * ************************** *** Navigation-Actions ***
 * **************************
 */

function toggleAjaxFunctions(show, preloader, bgHeight, navigation, mouseout) {
	defaultHeight = 120;

	// Show some AJAX-Functions
	if (show == 'true') {
		// Scroll to top
		jQuery('html, body').animate( {
			scrollTop : 0
		}, 'slow');

		// Hide Content
		jQuery('#header_ajax_content').html('');
		// Show Overlay
		/*
		if (jQuery('#overlay').css('display') == 'none') {
			Effect.Appear($('overlay'), {
				duration : 0.5,
				to : 0.8
			});
		}*/

		if (jQuery('#overlay_small').css('display') == 'none') {
			if (document.body.clientHeight < 1200) {
				//jQuery('#overlay_small').css('height', parseFloat(jQuery('.col-main').css('height'))+258);
				//fix ie
				jQuery('#overlay_small').css('height', parseFloat(jQuery('.col-main').height())+258);
			} else {
				jQuery('#overlay_small').css('height', document.body.clientHeight-240);
			}
			Effect.Appear($('overlay_small'), {
				duration : 0.5,
				to : 0.5
			});
		}

		// Show Background
		if (bgHeight) {
			var currentHeight = jQuery('#navigation-menue').css('height');
			currentHeight = Number(currentHeight.replace("px", ''));
			currentHeight -= defaultHeight;
			if (currentHeight > bgHeight) {
				bgHeight = currentHeight - bgHeight;
				jQuery('#navigation-menue').animate( {
					'height' : "-=" + bgHeight + "px"
				});
			} else if (currentHeight < bgHeight) {
				bgHeight = bgHeight - currentHeight;
				jQuery('#navigation-menue').animate( {
					'height' : "+=" + bgHeight + "px"
				});
			}
		}
		// Show PreLoader
		if (preloader == 'true') {
			if (jQuery('#header_wait').css('display') == 'none') {
				jQuery('#header_wait').show();
			}
		}
		// Hide Navigation
		if (navigation == 'true') {
			jQuery('#nav-container').hide();
			jQuery('#opennavi').hide();
		}

		// Hide everything
	} else {
		// Hide Overlay
		/*
		if (jQuery('#overlay').css('display') != 'none') {
			Effect.Fade($('overlay'), {
				duration : 0.5,
				to : 0.0
			});
		}
		*/

		if (jQuery('#overlay_small').css('display') != 'none') {
			Effect.Fade($('overlay_small'), {
				duration : 0.5,
				to : 0.0
			});
		}

		// Hide PreLoader
		jQuery('#header_wait').hide();
		// Hide Background
		var currentHeight = jQuery('#navigation-menue').css('height');
		currentHeight = Number(currentHeight.replace("px", ''));
		currentHeight -= defaultHeight;
		if (currentHeight > defaultHeight) {
			bgHeight = Math.abs(defaultHeight - currentHeight);
			bgHeight = bgHeight + defaultHeight;
			jQuery('#navigation-menue').animate( {
				'height' : "-=" + bgHeight + "px"
			});
		}

		// Show Navigation
		jQuery('#nav-container').show();
		// Hide Content
		jQuery('#header_ajax_content').hide();
		jQuery('#opennavi').hide();
		jQuery('#langSelect').hide();
	}
}

/*
 * ************************* *** Show Ajax Content *** *************************
 */
function showAjaxContent(xhr) {
	jQuery('#header_wait').hide();
	jQuery('#header_ajax_content').html(xhr.responseText);
	jQuery('#header_ajax_content').show();
}

/*
 * ************************* *** Load Ajax Content *** *************************
 */
function loadAjaxContent(url) {
	var myAjax = new Ajax.Request(url, {
		method : 'post',
		onException : function(xhr, e) {
			return ('An error occurred please try again later');
		},
		onComplete : function(xhr) {
			showAjaxContent(xhr);
		}
	});
}

/*
 * ************************
 * *** Load Header Cart ***
 * ************************
 */
function loadHeaderCart() {
	var myAjax = new Ajax.Request(baseUrl + 'addtocart/index/headercart/', {
		method : 'get',
		onComplete : function(xhr) {
			jQuery('#headercart').html(xhr.responseText);
		}
	});
}

/*
 * ************************** *** Load Shopping Cart ***
 * **************************
 */
function loadShoppingCart() {
	toggleAjaxFunctions('true', 'true', '350', 'true', 'false');
	loadAjaxContent(baseUrl + 'addtocart/index/cart/');
	loadHeaderCart();
}

/*
 * ************************** *** Load Compare Cart ***
 * **************************
 */
function loadCompare() {
	toggleAjaxFunctions('true', 'true', '350', 'true', 'false');
	loadAjaxContent(baseUrl + 'compare/index/compare');
}

/*
 * ************************** *** Load Wishlist Cart ***
 * **************************
 */
function loadWishlist() {
	toggleAjaxFunctions('true', 'true', '350', 'true', 'false');
	loadAjaxContent(baseUrl + 'vnmwishlist');
}

/*
 * *************************** *** Add Product to Cart ***
 * ***************************
 */
function sendcart() {
	url = ($('product_addtocart_form').action).replace('checkout',
			'addtocart/index/cart');

	toggleAjaxFunctions('true', 'true', '380', 'true', 'false');
	var myAjax = new Ajax.Request(url, {
		method : 'post',
		postBody : $('product_addtocart_form').serialize(),
		parameters : Form.serialize("product_addtocart_form"),
		onException : function(xhr, e) {
			return ('An error occurred please try again later');
		},
		onComplete : function(xhr) {
			showAjaxContent(xhr);
			loadHeaderCart();
		}
	});
}

/*
 * ************************************* *** Listener for add to cart form ***
 * *************************************
 */
document.observe("dom:loaded", function() {

	var cartInt = setInterval(function() {
		if (typeof productAddToCartForm != 'undefined') {
			productAddToCartForm.submit = function(url) {
				if (this.validator && this.validator.validate()) {
					sendcart();
					clearInterval(cartInt);
				}
				return false;
			};
		} else {
			clearInterval(cartInt);
		}
	}, 500);
});

/*
 * ****************************** *** Add Product from Compare ***
 * ******************************
 * This function is also used to add to cart in product list page 
 */
function addToCartFromCompare(id) {
	url = ($('product_addtocart_form' + id).action).replace('checkout',
			'addtocart/index/cart');

	toggleAjaxFunctions('true', 'true', '350', 'true', 'false');
	var myAjax = new Ajax.Request(url, {
		method : 'post',
		postBody : $('product_addtocart_form' + id).serialize(),
		parameters : Form.serialize("product_addtocart_form" + id),
		onException : function(xhr, e) {
			return ('An error occurred please try again later');
		},
		onComplete : function(xhr) {
			showAjaxContent(xhr);
			loadHeaderCart();
		}
	});
}

/*
 * ****************************** *** Add Product to Compare ***
 * ******************************
 */
function addToCompare(url) {
	toggleAjaxFunctions('true', 'true', '350', 'true', 'false');
	var myAjax = new Ajax.Request(url, {
		method : 'post',
		onException : function(xhr, e) {
			return ('An error occurred please try again later');
		},
		onComplete : function(xhr) {
			// loadCompare();
		showAjaxContent(xhr);
	}
	});
}

/*
 * ******************************* *** Add Product to Wishlist ***
 * *******************************
 */
function addToWishlist(url) {
	toggleAjaxFunctions('true', 'true', '350', 'true', 'false');
	var myAjax = new Ajax.Request(url, {
		method : 'post',
		onException : function(xhr, e) {
			return ('An error occurred please try again later');
		},
		onComplete : function(xhr) {
			loadWishlist();
		}
	});
}

/*
 * ********************************** *** Delete a Product from Cart ***
 * **********************************
 */
function deleteProductFromCart(url, needConfirm) {
	
	var confirmation = false;
	if ( needConfirm == 0 ) {
		confirmation = true;
	}
	else {
		if ( confirm('This product is a Free Gift. Do you really want to remove it from your cart ?') ) {
			confirmation = true;
		}
	}
	
	if ( confirmation ) {
		toggleAjaxFunctions('true', 'true', '350', 'true', 'false');
		var myAjax = new Ajax.Request(url, {
			method : 'post',
			onException : function(xhr, e) {
				return ('An error occurred please try again later');
			},
			onComplete : function(xhr) {
				loadShoppingCart();
			}
		});
	}
}

/*
 * ************************************* *** Delete a Product from Compare ***
 * *************************************
 */
function deleteProductFromCompare(url) {
	toggleAjaxFunctions('true', 'true', '350', 'true', 'false');
	var myAjax = new Ajax.Request(url, {
		method : 'post',
		onException : function(xhr, e) {
			return ('An error occurred please try again later');
		},
		onComplete : function(xhr) {
			// loadCompare();
		showAjaxContent(xhr);
	}
	});
}

/*
 * ************************************** *** Delete a Product from Wishlist ***
 * **************************************
 */
function deleteProductFromWishlist(url) {
	toggleAjaxFunctions('true', 'true', '350', 'true', 'false');
	var myAjax = new Ajax.Request(url, {
		method : 'post',
		onException : function(xhr, e) {
			return ('An error occurred please try again later');
		},
		onComplete : function(xhr) {
			loadWishlist();
		}
	});
}

/*
 * *************************************** *** Update Product Quantity in Cart
 * *** ***************************************
 */
function updateCartQuantity(id, qty) {
	toggleAjaxFunctions('true', 'true', '350', 'true', 'false');
	var myAjax = new Ajax.Request(baseUrl + 'addtocart/index/qty/id/' + id + '/qty/' + qty, {
		method : 'post',
		onException : function(xhr, e) {
			return ('An error occurred please try again later');
		},
		onComplete : function(xhr) {
			showAjaxContent(xhr);
			loadHeaderCart();
		}
	});
}

/*
 * *********************************** *** Change Country and Language ***
 * ***********************************
 */
function changeCountry() {
	toggleAjaxFunctions('true', 'true', '430', 'true', 'false');
        if(typeof(current_product)=='undefined'){current_product = 0;}
	var myAjax = new Ajax.Request(baseUrl + 'countryselector/', {
		method : 'post',
                parameters : {product_id: current_product},
		onException : function(xhr, e) {
			return ('An error occurred please try again later');
		},
		onComplete : function(xhr) {
			showAjaxContent(xhr);
		}
	});
}

/*
 * **************** *** Warranty *** ****************
 */

function changeWarrantyCountry() {
                var id = jQuery("#warrantycountry option:selected").val();
                if(!id){
                    var currentLocation =  document.location.href;
                    var matches = currentLocation.match(/([a-z]{2})-[a-z]{2}/);
                    id = matches[0];
                    if(matches[1] != "eu"){
                        jQuery('#warrantycountry option[value='+id+']').attr("selected", "selected");
                    }
                }
                jQuery('.warrantylist').hide();
                id = '#' + id;
                jQuery(id).show();
}


/*
 * *********** *** FAQ *** ***********
 */
//Function for show and hide FAQ-Answer-Box
function changeFaq(parent, child)
{
	try {
		if (jQuery(parent).hasClass('faq-li-active')) {
			jQuery(parent).removeClass('faq-li-active');
			jQuery('#'+child).slideUp('fast');
		} else {
			jQuery(parent).addClass('faq-li-active');
			jQuery('#'+child).slideDown('fast', function() {});
		}
	} catch (e) {
	}		
}

/*
 * ************************************
 * *** Set position of subcategories **
 * ************************************
 */
function posSubcats(subCat){	
	var left = subCat.find('a:first-child').position().left;
	var list = subCat.find('ul');
        if(left > 550 && subCat.find('ul div:last-child').attr("class") == 'listSecond'){
            left = left - 140;
        }
	list.css('left',left);
}

/*
 * ****************************
 * *** Set SubCategory List ***
 * ****************************
 */
function setSubCategories(){
	var categories = jQuery('#nav').children().length;
	var catChilds;
	var pos;
	
	for(i=1; i<=categories; i++){
		catChilds = jQuery('.nav-'+i+ ' ul').children().length;
		pos = 0;
		for(j=1; j<=catChilds; j++){
			pos++;
			if(pos<7){
				jQuery('.nav-'+i+'-'+j).addClass('firstList');
			}else if(pos>=7 && pos<13){
				if(pos==7 && j==catChilds){
					jQuery('.nav-'+i+'-'+j).addClass('firstList');
				}else{
					jQuery('.nav-'+i+'-'+j).addClass('secondList');
				}
			}else if(pos>=13){
				if(pos==13 && j==catChilds){
					jQuery('.nav-'+i+'-'+j).addClass('secondList');
				}else{
					jQuery('.nav-'+i+'-'+j).addClass('thirdList');
				}
			}
			if(jQuery('.nav-'+i+'-'+j).hasClass('spacer') && ((j+1)!=catChilds)){pos++;}
		}
		jQuery('.nav-'+i+' .firstList').wrapAll('<div class="listFirst" />');
		jQuery('.nav-'+i+' .secondList').wrapAll('<div class="listSecond" />');
		jQuery('.nav-'+i+' .thirdList').wrapAll('<div class="listThird" />');
	}
}

/*
 * ************************
 * *** Set footer height **
 * ************************
 */
function setFooterHeight(){
	var footerHeight = 0;
	
	//set footer height
	jQuery('.footer-content ul li.footer-block').each(function(){
		height = jQuery(this).height();
		if(height > footerHeight){
			footerHeight = height;
		}
	});

	jQuery('.footer-content ul li.footer-block').each(function(){
		jQuery(this).css({height: footerHeight});
	});

}

/*
 * ******************************
 * *** Set width of categories **
 * ******************************
 */
function setWidth(){
	var width = 0;
	var navWidth = 0;
	navNumber = jQuery('#nav').children().length;
	var widthHome = jQuery('#nav li:first-child a.level0').width();
	jQuery('#nav li:first-child a.level0').width(widthHome);
	for(i=1;i<=navNumber;i++){
		width = jQuery('.nav-'+i+' a.level0').width();
		jQuery('.nav-'+i+' a.level0').width(width);
		navWidth = navWidth + width;
	}
	//navWidth += widthHome;
	//alert(navWidth);
	if(navWidth > 615){
		if(navWidth >685){
			jQuery('li.level0 a.level0').addClass('navSmall');
			jQuery('ul.level0').addClass('subPosSmall');
		}else{
			jQuery('li.level0 a.level0').addClass('navMedium');
			jQuery('ul.level0').addClass('subPosMedium');
		}
	}else{
		jQuery('li.level0 a.level0').addClass('navBig');
		jQuery('ul.level0').addClass('subPosBig');
	}
}

// Make list ready
jQuery(document)
		.ready(function() {
			
				// set default input value on blur
				jQuery("input").live("blur",function() {
					try {
						insertDefaults();
					} catch (e) {

					}
				});

				try {
					// ID for each faq-li-element
					jQuery('#faqlayout ul li').each(function(index) {
						jQuery(this).bind("click", function() {
							changeFaq(this, 'faq_' + index);
						});
					});

					// ID for each faq-li-div-element
					jQuery('#faqlayout ul li div').each(function(index) {
						jQuery(this).attr("id", "faq_" + index);
					});
				} catch (e) {
				}
	
				jQuery('.footer-content ul li.footer-block:last').addClass('lastList');
				
/** *************Navigation Events*************** */
	
	// set the columns of the subcategories list
	setSubCategories();
	
	// On li with children, open menu and show children
	var timeoutId;
	jQuery('#nav li.withChildren').mouseenter(function(){
		posSubcats(jQuery(this));
		jQuery('#nav li.level0 ul').hide();
		list = jQuery(this).find('ul');
		
		
		if(jQuery('#navigation-menue').height() == 260){
			list.show();
		}
		else {
			jQuery(this).css({'height':"240px"});
			timeoutId = setTimeout(function(){ 
				jQuery('#navigation-menue').animate({'height' : "260px"}, function(){
					list.show();
				});
			}, 500);
		}
	});
	
	// On li without children, close menu
	jQuery('#nav li.withoutChildren').mouseenter(function(){
		jQuery('#nav li.withChildren').css({'height':"37px"});
		jQuery('#nav li.level0 ul').hide();
		jQuery('#navigation-menue').animate({'height' : "80px"}, function(){
			jQuery('#nav li.level0 ul').hide();
		});
	});
	
	// Out of the navigation box, close menu
	jQuery('#nav').mouseleave(function(){
		clearTimeout(timeoutId);
		jQuery('#nav li.withChildren').css({'height':"37px"});
		jQuery('#nav li.level0 ul').hide();
		jQuery('#navigation-menue').animate({'height' : "80px"}, function(){
			jQuery('#nav li.level0 ul').hide();
		});
	});
	

/** ******************************************* */
	
	// Language Events
	jQuery('a.languageHead').bind('click', function(){
		changeCountry();
	});
	jQuery('#langHead span#close').live('click', function(){
		toggleAjaxFunctions();
	});
	
	// ShoppingCart
	jQuery('#headercart a.cursor').live('click', function(){
		loadShoppingCart();
	});
	jQuery('#back-ajax-add h6.close').live('click', function(){
		toggleAjaxFunctions();
	});
	
	// load compare
	jQuery('#header_compare').bind('click', function(){
		loadCompare();
	});
	
	// Open Wishlist if logged in
	jQuery('.vi_resultHeaderMenu5 a:first').bind('click', function(){
		if(jQuery('#signIn').length){
			document.location.href='customer/account/';
		}else{
			loadWishlist();
		}
	});
	
	//add product to shopping cart
	jQuery('.add-to-cart').bind('click', function(){
		productAddToCartForm.submit();
	});
	
	//search
	jQuery('#searchbutton').bind('click', function(){
		document.search_mini_form.submit();
	});
	
	//underline images
	jQuery('.category-products .products-grid li.item, #crosssell-products-list li.item, .box-collateral li.item').mouseover(function(){
		jQuery(this).find('.prodImgList').addClass('img_over');
	});
	
	jQuery('.category-products .products-grid li.item, #crosssell-products-list li.item, .box-collateral li.item').mouseout(function(){
		jQuery(this).find('.prodImgList').removeClass('img_over');
	});
	
	//reset Contact form
	jQuery('#contactform .buttons a').bind('click', function(){
		jQuery('#contactform :input').not(':submit').val("");
	});
	
	setFooterHeight();
	
	//
	// issue with add to cart button onclick before page is fully loaded
	//
	jQuery('.add_to_cart_link').bind('click', function(){
		var productId = this.id.replace('add_to_cart_', '');
		addToCartFromCompare(productId);
		return false;
	});
	
});

