$(document).ready(function() {
	$('body').append('<div id="overlay">&nbsp;</div>');
	
	appendCheckboxEvents();
	
	$('#fGruppen').change(function() {
		updateMengeEmpfohlen($('#fGruppen').val());
		updateVorschlag($('#fGruppen').val());
	});
	
	if($('#fGruppen').val() > 0 && $('#event-planer-vorschlag tbody tr').size() <= 1) {
		updateVorschlag($('#fGruppen').val());
		//updateCustomMenge();
	} else {
		updateCustomMenge();
	}
	
	updateMengeEmpfohlen($('#fGruppen').val());
});

function appendCheckboxEvents() {
	$('#event-planer-vorschlag input[type=checkbox]').change(function() {
		prodLine = $(this).val().split('-')[1];
	
		if($(this).is(':checked')) {
			$('#staticProd_' + prodLine).removeClass('disabled');
			$('#staticProd_' + prodLine + ' select').attr('disabled', '');
		} else {
			$('#staticProd_' + prodLine).addClass('disabled');
			$('#staticProd_' + prodLine + ' select').attr('disabled', 'disabled');
		}
		
		$.post('/20_event-planer/vorschlag-manage.html', { product: prodLine }, function(data) {
			//$('#empfohlene-mengen .aktuell .value').html(parseFloat(data).toFixed(2) + ' l');
			//$('#empfohlene-mengen .aktuell .loading').css('display', 'none');
		});
		
		updateSummeVorschlag();
	});
}

function updateVorschlag(gruppeId) {
	$('#event-planer-vorschlag tbody').html('<tr><td colspan="8"><p class="loader"><img src="/images/ajax-loader.gif" alt="Lade..." /></p></td></tr>')
	$('#empfohlene-mengen .aktuell .loading').css('display', 'block');

	$.get('/20_event-planer/vorschlag.html?gruppe=' + gruppeId, function(data) {
		$('#event-planer-vorschlag tbody tr').remove();
		$('#event-planer-vorschlag tbody').append(data);
		
		$('#event-planer-vorschlag input.menge-value').change(function() {
			saveMenge($(this));
		});
		
		updateSummeVorschlag();
		appendCheckboxEvents();
	});
}

function saveMenge(jqSelect) {
	var prodId = jqSelect.attr('name').split('-')[1];
	var typ = jqSelect.parent().find('select').val();
	
	$.post('/20_event-planer/mengen.html', { prodId: prodId, menge: jqSelect.val(), typ: typ });
}

function updateMengeEmpfohlen(gruppeId) {
	if(gruppeId > 0) {
	
		if($('#fAnzFrauen').val().length > 0 || $('#fAnzMaenner').val().length > 0) {
			//$('#empfohlene-mengen .empfohlen .value').append('<img src="/images/ajax-loader-small.gif" alt="Lade..." />');
			$('#empfohlene-mengen .empfohlen .loading').css('display', 'block');
		}
	
		$.get('/20_event-planer/vorschlag.html?gruppe=' + gruppeId + '&js=1', function(data) {
			$('#dyn-js-wrapper').html(data);
			
			updateMengeProGeschlecht();
		});
	} else {
		$('#empfohlene-mengen .empfohlen .value').html('-');
		$('#empfohlene-mengen .empfohlen .loading').css('display', 'none');
	}
}
function updateMengeProGeschlecht() {
	var anzFrauen = parseInt($('#fAnzFrauen').val());
	var anzMaenner = parseInt($('#fAnzMaenner').val());
	
	if (parseInt($('#fGruppen').val()) > 0 && (anzFrauen > 0 || anzMaenner > 0)) {
		var anz = 0
		var konsumEmpfohlen = 0
		
		if(!isNaN(anzFrauen)) {
			konsumEmpfohlen = anzFrauen * konsumFrau;
		}
		if(!isNaN(anzMaenner)) {
			konsumEmpfohlen = konsumEmpfohlen + (anzMaenner * konsumMann);
		}
		
		$('#empfohlene-mengen .empfohlen .value').html(konsumEmpfohlen.toFixed(2) + ' l');
		$('#empfohlene-mengen .empfohlen .loading').css('display', 'none');
		
		
		aktMenge = $('#empfohlene-mengen .aktuell .value').html();
		
		aktMengeFl = 0.0;
		try
		{
			//alert(aktMenge.split(' ')[0]);
			aktMengeFl = parseFloat(aktMenge.split(' ')[0]);
		}
		catch(err) {}
		
		updateCustomMengeColor(aktMengeFl, konsumEmpfohlen);
	} else {
		$('#empfohlene-mengen .empfohlen .value').html('-');
		$('#empfohlene-mengen .empfohlen .loading').css('display', 'none');
	}
}

function getEmpfohleneMenge() {
	var anzFrauen = parseInt($('#fAnzFrauen').val());
	var anzMaenner = parseInt($('#fAnzMaenner').val());
	
	var anz = 0
	var konsumEmpfohlen = 0
	
	if (parseInt($('#fGruppen').val()) > 0 && (anzFrauen > 0 || anzMaenner > 0)) {
		if(!isNaN(anzFrauen)) {
			konsumEmpfohlen = anzFrauen * konsumFrau;
		}
		if(!isNaN(anzMaenner)) {
			konsumEmpfohlen = konsumEmpfohlen + (anzMaenner * konsumMann);
		}
	}
	
	return konsumEmpfohlen;
}

function updateCustomMenge() {
	var prodList = '';
	var prodListItems = {};
	
	// Greiner Vorschlag
	$('#event-planer-vorschlag tbody tr:has(select)').each(function() {
		if($(this).find('input[type="checkbox"]').is(':checked')) {
			menge = parseInt($(this).find('input.menge-value').val());
			prodId = $(this).attr('id').split('_')[1];
			
			if (isNaN(menge))
				menge = 0;
			
			prodListItems[prodId] = menge;
		}
	});
	
	// Custom
	//$('#event-planer-user tbody tr').each(function() {
		//menge = parseInt($(this).find('input.menge-value').val());
		//prodId = $(this).attr('id').split('_')[1];
		
		//if (isNaN(menge))
			//menge = 0;
		
		//prodListItems[prodId] = menge;
	//});
	
	
	
	//$('#empfohlene-mengen .aktuell .value').append('<img src="/images/ajax-loader-small.gif" alt="Lade..." />');
	$('#empfohlene-mengen .aktuell .loading').css('display', 'block');
	$.post('/20_event-planer/aktuelle-menge.html', prodListItems, function(data) {
		aktMenge = parseFloat(data);
	
		$('#empfohlene-mengen .aktuell .value').html(aktMenge.toFixed(2) + ' l');
		$('#empfohlene-mengen .aktuell .loading').css('display', 'none');
		
		updateCustomMengeColor(aktMenge, getEmpfohleneMenge())
	});
}

function updateCustomMengeColor(aktMenge, empfMenge) {
	empfMengeMax = empfMenge + (empfMenge * 0.2)

	if (aktMenge > 0 && empfMenge > 0) {
		if(aktMenge < empfMenge || aktMenge > empfMengeMax) {
			$('#empfohlene-mengen .aktuell .value').attr('class', 'value bad');
		} else {
			$('#empfohlene-mengen .aktuell .value').attr('class', 'value good');
		}
	} else {
		$('#empfohlene-mengen .aktuell .value').attr('class', 'value');
	}
}


function showProducts() {
	var prodListWrapper = $('#product-list-wrapper');
	var overlay = $('#overlay');
	$('embed, object, select').css({ 'visibility' : 'hidden' });
	
	var arrPageScroll = ___getPageScroll();
	var arrPageSizes = ___getPageSize();
	
	//var arrPageSizes = ___getPageSize();

	overlay.css({
		width: arrPageSizes[0],
		height: arrPageSizes[1],
		opacity: 0.8
	}).fadeIn();
	
	prodListWrapper.css({
		top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
		left:	arrPageScroll[0] + ((arrPageSizes[0] / 2) - (prodListWrapper.width() / 2))
	}).show();
	
	overlay.click(function() {
		close();
	});

	
	//showLoadingScreen();
	//$.get('/20_event-planer/suche.html', function(data) {
	//	$('#product-list').html(data);
	//});
	
	searchProducts(undefined, 1);
}

function changePage(page, searchTerm) {
	if(page == undefined) {
		page = 1;
	}

	searchProducts(searchTerm, page);
}

function searchProducts(filter, page) {
	showLoadingScreen();

	if(filter != undefined) {
		$.get('/20_event-planer/suche.html?suchbegriff=' + filter + '&page=' + page, function(data) {
			$('#product-list').html(data);
		});
	}
	else {
		$.get('/20_event-planer/suche.html?page=' + page, function(data) {
			$('#product-list').html(data);
		});
	}
}
function filterProducts() {
	searchProducts($('#event-product-search').val(), 1);
}

function showLoadingScreen() {
	$('#product-list').html('<p class="loader"><img src="/images/ajax-loader.gif" alt="Lade..." /><p>')
}

function replacePagers() {
	var t = $('a[href*="/de/20_event-planer/suche.html"]')
	
	$(t).each(function() {
		cur = $(this);
		
		try {
			var pageParts = cur.attr('href').split('=')
			
			if(pageParts.length > 2) {
				var page = parseFloat(pageParts[2]);
				cur.attr('href', 'javascript:changePage(' + page + ', "' + pageParts[1].split('&')[0] + '");');
			} else {
				var page = parseFloat(pageParts[1]);
				cur.attr('href', 'javascript:changePage(' + page + ');');
			}
		} catch(error) {
			page = 1;
			cur.attr('href', 'javascript:changePage(' + page + ');');
		}
	});
}

function close() {
	$('#product-list-wrapper').fadeOut();
	$('#overlay').fadeOut();
	$('embed, object, select').css({ 'visibility' : 'visible' });
}
function removeProduct(prodId) {
	$('tr#prod_' + prodId).remove();
	
	// Produkt aus Zwischenspeicher löschen
	$.get('/20_event-planer/custom-manage.html?mode=remove&product=' + prodId, function() {
		updateCustomMenge();
	});
	
	updateSummeBenutzerAuswahl();
	
	if($('#event-planer-user tbody tr').size() == 0) {
		$('#event-planer-user tbody').append('<tr class="empty"><td colspan="8"><i>Bitte wählen Sie "Artikel hinzufügen" aus.</i></td></tr>');
	}
}

function addCustomProduct(prodId) {
	close();
	
	$.getJSON('/20_event-planer/prod-infos.html', {product: prodId}, function(data) {
		markCss = '';
		
		// Produkt zwischenspeichern
		$.get('/20_event-planer/custom-manage.html?mode=add&product=' + prodId + '&menge=' + data.minMenge, function() {
			updateCustomMenge();
		});
		
		if($('#event-planer-user').has('tr.empty')) {
			$('#event-planer-user tr.empty').remove();
		}
		
		if(($('#event-planer-user tbody tr').size()+1) % 2 == 1) {
			markCss = ' class="mark"';
		}
	
		newProd = '<tr id="prod_' + prodId + '"' + markCss + '>';
		newProd += '  <td class="right"><a href="javascript:removeProduct(' + prodId + ');"><img title="Artikel entfernen" alt="entfernen" src="/images/remove.gif" /></a></td>';
		newProd += '  <td>' + data.bezeichnung + '</td>';
		newProd += '  <td>' + data.abfuellung + '</td>';
		newProd += '  <td>' + data.gebinde + '</td>';
		newProd += '  <td>CHF</td>';
		newProd += '  <td class="right einzelpreis">' + data.einzelwert + '</td>';
		newProd += '  <td class="right menge">';
		
		newProd += '<select name="menge-typ-' + prodId + '" class="menge-typ">';
		
		if(data.minMenge > 1)
			newProd += '	<option value="gg">GG</option>';
		else
			newProd += '	<option value="fl">Fl</option>';
		
		newProd += '</select>';
		newProd += '<input type="text" value="1" id="menge-' + prodId + '" name="menge-' + prodId + '" class="menge-value" onchange="updateSummeBenutzerAuswahl(' + prodId + ');" />';
		newProd += '<input type="hidden" name="menge-gg" class="menge-gg" value="' + data.minMenge + '" />';
		
		//newProd += '  <select >';
		//for(i=1; i<10; i++) {
			//newProd += '    <option value="' + data.minMenge * i + '">' + data.minMenge * i + '</option>';
		//}
		//newProd += '  </select>';
		
		newProd += '</td>';
		newProd += '  <td class="right summe">' + (data.minMenge * data.einzelwert).toFixed(2) + '</td>';
		newProd += '</tr>';
		
		$('#event-planer-user tbody').append(newProd);
		
		updateSummeBenutzerAuswahl();
	});
}

function getSumme(jqProd) {
	prod = jqProd//$('#staticProd_' + prodId);
	
	gesamtwert = 0;
	menge = parseInt(prod.find('input.menge-value').val());
	wert = parseFloat(prod.find('td.einzelpreis').html());
	mengeProGg = parseInt(prod.find('.menge-gg').val())
	
	if (!isNaN(menge))
		gesamtwert = wert * menge;
	else
		menge = 0
	
	
	gesamtwert = wert * menge;
	
	if (!isNaN(mengeProGg))
		gesamtwert = gesamtwert * mengeProGg;
	
	return gesamtwert;
}

function updateAll() {
	updateSummen();
	updateVorschlagMengen();
}
function updateSummeVorschlag() {
	var sumVorschlag = 0
	var sumMengeVorschlag = 0
	
	updateCustomMenge();
	
	// Update Produktvorschläge
	$('#event-planer-vorschlag tbody tr:has(select)').each(function() {
		if($(this).find('input[type="checkbox"]').is(':checked')) {
			menge = parseInt($(this).find('input.menge-value').val());
			//wert = parseFloat($(this).find('td.einzelpreis').html());
			//gesamtwert = 0;
			
			//if (!isNaN(menge))
				//gesamtwert = wert * menge;
			//else
				//menge = 0
				
			gesamtwert = getSumme($(this));
			
			$(this).find('td.summe').html(gesamtwert.toFixed(2));
		
			sumMengeVorschlag += menge;
			sumVorschlag += gesamtwert;
		}
	});
	
	//$('#event-planer-vorschlag tfoot td.summe').html('<input id="summe-vorschlag" name="summe-vorschlag" type="hidden" value="' + sumVorschlag.toFixed(2) + '" />' + sumVorschlag.toFixed(2));
	$('#event-planer-vorschlag tfoot td.summe').html(sumVorschlag.toFixed(2));
}
function updateSummeBenutzerAuswahl(prodId) {
	var sumVorschlag = 0
	var sumMengeVorschlag = 0
	
	// Zwischengespeichertes Produkt aktualisieren
	if(prodId != undefined) {
		updMenge = $("#event-planer-user input#menge-" + prodId + "").val();
		$.get('/20_event-planer/custom-manage.html?mode=update&product=' + prodId + '&menge=' + updMenge, function() {
			updateCustomMenge();
		});
	}

	// Update Individualauswahl
	$('#event-planer-user tbody tr:has(select)').each(function() {
		menge = parseInt($(this).find('select').val());
		//wert = parseFloat($(this).find('td.einzelpreis').html());
		//gesamtwert = wert * menge;
		
		gesamtwert = getSumme($(this));
		
		$(this).find('td.summe').html(gesamtwert.toFixed(2));
	
		sumMengeVorschlag += menge;
		sumVorschlag += gesamtwert;
	});
	
	//$('#event-planer-user tfoot td.summe').html('<input id="summe-custom" name="summe-custom" type="hidden" value="' + sumVorschlag.toFixed(2) + '" />' + sumVorschlag.toFixed(2));
	$('#event-planer-user tfoot td.summe').html(sumVorschlag.toFixed(2));
}
function updateVorschlagMengen() {
	
}




/**
/ THIRD FUNCTION
* getPageSize() by quirksmode.com
*
* @return Array Return an array with page width, height and window width, height
*/
function ___getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
};

/**
/ THIRD FUNCTION
* getPageScroll() by quirksmode.com
*
* @return Array Return an array with x,y page scroll values.
*/
function ___getPageScroll() {
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
};
