var openQuickMenuID = false;
var teaserAnimationLock = false;

var basketCheckedShipping = 1;
var basketCheckedPayment = 1;

var basketShippingPrice = 0.00;
var basketPaymentPrice = 0.00;
var basketDiscountPercent = 0;

var currentBasketStep = 1;
var skipStep2 = false;
var basketChanged = false;

var userMode = "Normal"; // is normal or business

var currentCatFilter = 0;

var liveSearchPos = 0;

/* ------------------------------------------------------
		++++++++++		LIVE FUNCTIONS     ++++++++++++
------------------------------------------------------ */

function addToBasket(productid, count, variantid){
	jQuery('#liveBasket').load('/home/basket/add?productid=' + productid + '&count=' + count + '&variantid=' + variantid, function(){
		jQuery('#liveBasket').slideDown(400);
		basketEvent();
	});
}

function addToBasketFromPopup(productid){
	jQuery('#liveBasket').slideUp(400, function(){
		addToBasket(productid, jQuery('#stkPopup').val(), '');
	});
}

function delItemFromPopup(productid){
	jQuery('#liveBasket').load('/home/basket/delete?productid=' + productid, function(){
		jQuery('#liveBasket').slideDown(400);
		basketEvent();
	});
}

function changeCount(basketItemID, count){
	jQuery('#liveBasketUpdater').load('/home/basket/change?basketItemID=' + basketItemID + '&count=' + count);
	basketEvent();
}

function closePopup(){
	jQuery('#liveBasket').slideUp(400, function(){
		jQuery('#overlay').hide(0);
	});
}

function loadAddPopup(productid){
	jQuery('#overlay').css('height', FullHeight());
	jQuery('#overlay').show(0);
	var button = document.getElementById('button' + productid);
	//jQuery('#liveBasket').css('left', parseInt(absLeft(button) + 300));
	jQuery('#liveBasket').css('top', parseInt(absTop(button) - 230));
	jQuery('#liveBasket').load('/home/basket/addpopup?productid=' + productid, function(){
		jQuery('#liveBasket').slideDown(400);
	});
}

function loadDelPopup(productid){
	jQuery('body,html').scrollTop('0');
	jQuery('#overlay').css('height', FullHeight());
	jQuery('#overlay').show(0);
	//jQuery('#liveBasket').css('left', parseInt(absLeft(button) + 300));
	jQuery('#liveBasket').css('margin-top', '-150');
	jQuery('#liveBasket').load('/home/basket/delpopup?productid=' + productid, function(){
		jQuery('#liveBasket').slideDown(400);
	});
}


function checkIfEmailExists(){
	var email = jQuery('#checkEmail').val();
	jQuery('#EmailVerify').load('/home/basket/checkEmail?email=' + email, function(){
	});
}

/* 
	updates the mini-basket in the header
*/
function basketEvent(){
	jQuery('#miniBasket').load('/home/basket/minibasket');
}

/* ------------------------------------------------------
		++++++++++		OTHER FUNCTIONS     +++++++++++
------------------------------------------------------ */


function loadAGBpopup(){
	jQuery('body,html').scrollTop('0');
	jQuery('#overlay').css('height', FullHeight());
	jQuery('#overlay').show(0);
	jQuery('#agbOverlay').fadeIn(200);
}

function closeAGBpopup(){
	jQuery('#agbOverlay').fadeOut(200);
	jQuery('#overlay').hide(0);
}

function showCatFilter(id){
	if(id == 0){
		jQuery('#catFilter' + currentCatFilter).slideUp(200);
	}else if(currentCatFilter == 0){
		jQuery('#catFilter' + id).slideDown(300);
	}else{
		jQuery('#catFilter' + currentCatFilter).slideUp(200, function(){
			jQuery('#catFilter' + id).slideDown(300);
		});
	}
	currentCatFilter = id;
}


/* 
	calls gotoBasketStep after checking if this is allowed to do so
	used by direct-number-menu in basket
*/
function gotoBasketStepMenu(step){
	if(step < currentBasketStep){
		gotoBasketStep(step);
	}
}

function showPaymentsAndShippings(){
	jQuery('.PaymentBox').css('display', 'none');
	jQuery('.ShippingBox').css('display', 'none');
	
	var country = jQuery('#Country').val();
	jQuery('.Country_' + country).css('display', 'block');
	
	if(userMode == "Normal")
		jQuery('.Group_Business').css('display', 'none');
	else
		jQuery('.Group_Normal').css('display', 'none');
}

function showCorrectDiscount(){
	jQuery('.CheckoutDiscountDesc').css('display', 'none');
	var country = jQuery('#Country').val();
	jQuery('.DiscountCountry_' + country).css('display', 'block');
	
	if(userMode == "Normal")
		jQuery('.DiscountGroup_Business').css('display', 'none');
	else
		jQuery('.DiscountGroup_Normal').css('display', 'none');
		
	basketDiscountPercent = jQuery('#Discount_' + jQuery('#Country').val() + "_" + userMode).val();
	var discount = calcDiscount();
	jQuery('#CheckoutDiscountPrice').html("&ndash;&nbsp; &euro; " + discount);
	
	if(discount == 0.00){
		jQuery('#CheckoutDiscountAll').css('display', 'none');
	}
}

function gotoBasketStep(step){
	var isAllowed = true;
	
	if(step == 3){
		var setEmail = jQuery('#checkEmail').val();
		if(setEmail)
			jQuery('#Email').val(setEmail);
	}
	
	if(step == 4)
		isAllowed = validateStepThree();
		
	if(step == 4 || step == 5)
		showPaymentsAndShippings();
		
	if(step == 6){
		showCorrectDiscount();
		calcTotal();
	}
	
	if(isAllowed){
		jQuery('body,html').scrollTop('350');
		var oldHeight = jQuery('#tiledContent').height();
		var newHeight = parseInt(jQuery('#basketStep' + step).height() + 50);
		if(newHeight < 600)
			newHeight = 600;
	
		if(newHeight > oldHeight)
			jQuery('#tiledContent').height(newHeight);
	
		if(currentBasketStep < step){
			// go next
			jQuery('#basketStep' + currentBasketStep).hide("slide", { direction: "left" }, 500);
			jQuery('#basketStep' + step).show("slide", { direction: "right" }, 500, function(){
			if(newHeight < oldHeight)
				jQuery('#tiledContent').height(newHeight);
			});
			jQuery('#basketStepMenu_' + step).css('color', '#000000');
			jQuery('#basketStepMenu_' + currentBasketStep).css('cursor', 'pointer');
		}else{
			// go previous
			recGotoBasketStep(currentBasketStep, step);
			var newHeight = parseInt(jQuery('#basketStep' + step).height() + 50);
			if(newHeight < 600)
				newHeight = 600;
			if(newHeight < oldHeight)
				jQuery('#tiledContent').height(newHeight);
		}
		currentBasketStep = step;
		
		
		if(step == 2 && skipStep2 == true)
			gotoBasketStep(3);
	}
}


function loginFromBasket(){
	jQuery('#quickKdnr').val(jQuery('#basketKdnr').val());
	jQuery('#quickPassword').val(jQuery('#basketPassword').val());
	jQuery('#quickReturnToBasket').val(1);
	jQuery('#quickLoginForm').submit();
}

/* 
	recursive function - needed for full control of animation
	only used if go previous
*/

function recGotoBasketStep(current, goal){
	if(current == goal){
		return true;
	}else{
		var anim = 500 - ((current - goal) * 50)
		jQuery('#basketStepMenu_' + current).css('color', '#898989');
		jQuery('#basketStepMenu_' + current).css('cursor', 'default');
		jQuery('#basketStep' + current).hide("slide", { direction: "right" }, anim);
		jQuery('#basketStep' + parseInt(current - 1)).show("slide", { direction: "left" }, anim, function(){
			recGotoBasketStep(parseInt(current - 1), goal);
		});
	}
}

function gotoPrevBasketStep(){
	gotoBasketStep(currentBasketStep - 1);
}

function gotoNextBasketStep(){
	if(currentBasketStep == 1 && basketChanged){
		basketChanged = false;
		document.location = "/home/basket?forceStep=2";
	}else
		gotoBasketStep(currentBasketStep + 1);
}


function fillIn(){
	var needed = new Array(
		'FirstName',
		'Surname',
		'Email',
		'Street',
		'PLZ',
		'Ort',
		'Country'
	);
	for(var i = 0; i < needed.length; i++){
		jQuery('#' + needed[i]).val('foobar');
	}
}

function checkIfNewPasswordOK(){
	var pw1 = jQuery('#NewPassword').val();
	var pw2 = jQuery('#NewPasswordVerify').val();
	
	if(pw1.length > 5 && pw1 == pw2){
		jQuery('#showOnlyIfPasswordNotAccepted').hide(0);
		jQuery('#showOnlyIfPasswordAccepted').show(0);
	}else{
		jQuery('#showOnlyIfPasswordNotAccepted').show(0);
		jQuery('#showOnlyIfPasswordAccepted').hide(0);
	}
}

/*
	validating rechnungs- und lieferdaten
	returns true or false (aka "isAllowed to go to on")
*/

function validateStepThree(){
	var needed = new Array(
		'FirstName',
		'Surname',
		'Email',
		'Street',
		'PLZ',
		'Ort',
		'Country'
	);
	if(jQuery('#usePaymentAddress').val() == 1){
		var neededPay = new Array(
			'payFirstName',
			'paySurname',
			'payEmail',
			'payStreet',
			'payPLZ',
			'payOrt',
			'payCountry'
		);
		
		needed = needed.concat(neededPay);
	}
	
	var success = true;
	
	for(var i = 0; i < needed.length; i++){
		if(jQuery('#' + needed[i]).val() == ""){
			jQuery('#' + needed[i]).css('border', '1px solid #787878');
			success = false;
		}else{
			// standard setzen
			jQuery('#' + needed[i]).css('border', '1px solid #DFDFDF');
		}
	}
	
	if(!success){
		jQuery('#basketValidationMessageStepThree').show(0);
	}else{
		jQuery('#basketValidationMessageStepThree').hide(0);
	}
	
	return success;
}

function calcDiscount(){
	//var products = calcBasket(null, true);
	var products = jQuery('#TotalForDiscount').val();
	var result = (parseFloat(products) / 100 * basketDiscountPercent);
	
	jQuery('#Discount').val(result.toFixed(2));
	return result.toFixed(2);
}

function calcTotal(){
	var products = calcBasket(null, true);
	var discount = calcDiscount();
	var tax = jQuery('#tax').val();
	var result = parseFloat(products) + parseFloat(basketShippingPrice) + parseFloat(basketPaymentPrice) - discount + parseFloat(tax);
	jQuery('#basketResultLastStepOverall').html('Gesamtsumme: &euro; ' + result.toFixed(2));
	jQuery('#Total').val(result.toFixed(2));
}


function calcBasket(showIn, justNumber){
	var allCount = jQuery('#basketCountProducts').val();
	var allPrice = 0.00;
	var i;
	for(i = 1; i <= allCount; i++){
		var price = jQuery('#basketPrice_' + i).val();
		var count = jQuery('#basketStk_' + i).val();
		var result = price * count;
		allPrice += result;
		jQuery('#basketResult_' +i).html('&euro; ' + result.toFixed(2));
	}
	
	if(justNumber)
		return allPrice.toFixed(2);
	else
		jQuery('#' + showIn).html('Summe: &euro; ' + allPrice.toFixed(2));
}

function basketHasChanged(){
	basketChanged = true;
}

function toggleShowIfAGBaccepted(){
	jQuery('#showIfAGBaccepted').toggle();
	jQuery('#BasketAGBHakerl').toggle(20);
}

function toggleBasketPaymentAddress(){
	var currentMode = jQuery('#usePaymentAddress').val();
	if(currentMode == 1)
		jQuery('#usePaymentAddress').val('0')
	else
		jQuery('#usePaymentAddress').val('1')
		
	jQuery('#BasketPaymentAddressHakerl').toggle(20);
	jQuery('#basketPaymentAddress').toggle(300);
}

function setShipping(ID, desc, price, dbID){
	jQuery("#basketCheckboxShipping_" + basketCheckedShipping).fadeOut(200);
	jQuery("#basketShipping_" + basketCheckedShipping).css('opacity', '0.6');
	jQuery("#basketCheckboxShipping_" + dbID).fadeIn(200);
	jQuery("#basketShipping_" + dbID).css('opacity', '1.0');
	
	jQuery('#CheckoutShippingDesc').html('Versand: ' + desc);
	jQuery('#CheckoutShippingPrice').html('&euro; ' + price);
	
	basketShippingPrice = price;
	
	basketCheckedShipping = dbID;
	jQuery('#ShippingID').val(dbID);
	jQuery('#showIfShippingSelected').show(0);
}

function setPayment(ID, desc, price, dbID){
	jQuery("#basketCheckboxPayment_" + basketCheckedPayment).fadeOut(200);
	jQuery("#basketPayment_" + basketCheckedPayment).css('opacity', '0.6');
	jQuery("#basketCheckboxPayment_" + dbID).fadeIn(200);
	jQuery("#basketPayment_" + dbID).css('opacity', '1.0');
	
	jQuery('#CheckoutPaymentDesc').html('Zahlungsmethode: ' + desc);
	jQuery('#CheckoutPaymentPrice').html('&euro; ' + price);
	
	basketPaymentPrice = price;
	
	if(desc == "Kreditkarte")
		jQuery('#mpayNotice').show(0);
	else
		jQuery('#mpayNotice').hide(0);
	
	if(desc == "Bankeinzug")
		jQuery('#Notes').val('Sie haben Bankeinzug als Zahlungsmethode gewählt.\nBitte geben Sie hier eine Kontodaten ein:\n\n');
	else
		jQuery('#Notes').val('');
	
	basketCheckedPayment = dbID;
	jQuery('#PaymentID').val(dbID);
	jQuery('#showIfPaymentSelected').show(0);
}

function setAddress(ID, pre){
	var street = jQuery('#addr_street_' + ID).val();
	var ort = jQuery('#addr_ort_' + ID).val();
	var plz = jQuery('#addr_plz_' + ID).val();
	var country = jQuery('#addr_country_' + ID).val();
	
	jQuery('#' + pre + 'Street').val(street);
	jQuery('#' + pre + 'Ort').val(ort);
	jQuery('#' + pre + 'PLZ').val(plz);
	jQuery('#' + pre + 'Country option[value=' + country + ']').attr('selected', 'selected');
}


function showQuickMenu(ID){
	if(openQuickMenuID){
		if(openQuickMenuID == ID){
			jQuery('#quickmenu_' + openQuickMenuID).slideUp(400);
			openQuickMenuID = false;
		}else{
			jQuery('#quickmenu_' + openQuickMenuID).slideUp(400, function(){
				jQuery('#quickmenu_' + ID).slideDown(400);
			});
			openQuickMenuID = ID;
		}
	}else{
		jQuery('#quickmenu_' + ID).slideDown(400);
		openQuickMenuID = ID;
	}
}

function hideQuickMenu(){
	if(!openQuickMenuID)
		return false;
	
	jQuery('#quickmenu_' + openQuickMenuID).slideUp(400);
	openQuickMenuID = false;
}

function mouseOverTeaser(ID){
	//if(!teaserAnimationLock){
		//teaserAnimationLock = true;
		jQuery('#TeaserTextContent_' + ID).hide(0);
		jQuery('#TeaserText_' + ID).animate({width: '0'}, 300, function(){
			//teaserAnimationLock = false;
		});
		
		//window.setTimeout("deactivateTeaserAnimationLock()", 500);
	//}
}

//function deactivateTeaserAnimationLock(){
//	teaserAnimationLock = false;
//}

function mouseLeaveTeaser(ID){
	jQuery('#TeaserTextContent_' + ID).show(0);
	jQuery('#TeaserText_' + ID).animate({width: '250px'}, 300);
}

function changeStk(ID, add, basketItemID){
	var current = parseInt(jQuery('#' + ID).val());
	if(add)
		current++;
	else if(!add && current > 0)
		current--;
	
	changeCount(basketItemID, current);
	
	jQuery('#' + ID).val(current);
}




function absLeft(el) {
	return (el.offsetParent)?
	el.offsetLeft+absLeft(el.offsetParent) : el.offsetLeft;
}

function absTop(el) {
	return (el.offsetParent)?
	el.offsetTop+absTop(el.offsetParent) : el.offsetTop;
} 

function FullHeight () {
	var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}


/************************************************************
	LIVE SEARCH FUNCTIONS
***************************************************************/

function liveSearch(){
	q = jQuery('#SearchForm_SearchForm_Search').val();
	if(q.length > 2){
		liveSearchPos = 0;
		jQuery('#LiveSearchContainer').load("/home/getLiveResults/?q=" + q, function(){
			jQuery('#LiveSearch').show(0);
		});
	}
}

function liveSearchGoDown(){
	if(liveSearchPos != 0)
		jQuery('#LiveSearchLine' + liveSearchPos).css('background-color', 'transparent');
	if(liveSearchPos < 5)
		liveSearchPos++;
		
	jQuery('#LiveSearchLine' + liveSearchPos).css('background-color', '#DFDFDF');
	jQuery('#SearchForm_SearchForm_Search').val(jQuery('#LiveSearchLine' + liveSearchPos).html());
}

function liveSearchGoUp(){
	if(liveSearchPos != 0)
		jQuery('#LiveSearchLine' + liveSearchPos).css('background-color', 'transparent');
	if(liveSearchPos > 1)
		liveSearchPos--;
		
	jQuery('#LiveSearchLine' + liveSearchPos).css('background-color', '#DFDFDF');
	jQuery('#SearchForm_SearchForm_Search').val(jQuery('#LiveSearchLine' + liveSearchPos).html());
}

function hideLiveSearch(){
	jQuery('#LiveSearch').hide(0);
	jQuery('#ProduktSearch').hide(0);
}





/************************************************************
	GOOGLE MAPS FUNCTIONS
***************************************************************/

function initializeSmallMap(filialNr, lat, lng){
	var latlng = new google.maps.LatLng(lat, lng);
	var myOptions = {
		zoom: 10,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
    disableDefaultUI: true
	};
	var map = new google.maps.Map(document.getElementById("mapFiliale" + filialNr), myOptions);
	google.maps.event.trigger(map, 'resize');
	pointAddress(lat, lng, map);
}

function initializeMap(filialNr, lat, lng){
	var latlng = new google.maps.LatLng(lat, lng);
	var myOptions = {
		zoom: 12,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var map = new google.maps.Map(document.getElementById("mapFiliale" + filialNr), myOptions);
	google.maps.event.trigger(map, 'resize');
	pointAddress(lat, lng, map);
}


function pointAddress(lat, lng, map) {
	var myLatlng = new google.maps.LatLng(lat, lng);
    
	var marker = new google.maps.Marker({
		position: myLatlng, 
		map: map
	});   

	
	var infowindow = new google.maps.InfoWindow({
		content: ""
	});

	google.maps.event.addListener(marker, 'click', function() {
	  infowindow.open(map, marker);
	});
	  infowindow.open(map, marker);
	
}

