
var cookieOptions = { expires: 365 };

var bestellMatrix = {};
var terminOption, terminRabatt;
var versandArt;
var zehnProzent;
var anfrageOderBestellung;

$(document).ready(function() {
	
	//trace('**** bestellung.js ready');
			
	if (typeof $.cookie != 'undefined') {
	
		//trace('PHPSESSID: ' + $.cookie('PHPSESSID'));
		
		displayUploads();
		
		//trace($.cookie('bestellung'));
		
		//$.cookie('bestellung', null, { path: '/', expires: -5 });
		
		bestellMatrix = $.cookie('bestellung') != null && typeof $.cookie('bestellung') == 'string' ?  eval('(' + $.cookie('bestellung') + ')') : null; // eval() durch 'JSON.parse()' ersetzen	
		versandArt = $.cookie('versandArt') != null ?  $.cookie('versandArt') : 'basel';
		terminOption = $.cookie('terminOption') != null ?  $.cookie('terminOption') : '2-3_werktage';
		
	} else {
		trace('$.cookie not found.');
	}

	if ($('.preisliste').length > 0) {
		//trace('preisliste gefunden');	
		$('#produktGrid').text();		
		$('.preisliste').CreaplotKonfigurator();
		
		//$('#bestellungLayout').append('<tr><td class="gesamttotal">Versandspesen: &nbsp;' + versandOptionen() + '</td></tr>');
			
	}
	
	if ($('#warenkorb').length > 0) {
		//trace('ja, warenkorb');
		showBasket();
	}
	
	if ($('.anfrageBestellung').length > 0) {			
		restoreForm($(this));	
		$('input, textarea').keyup(function() {
			var $form = $(this).parents('form').eq(0);
			storeForm($form);
		});				
	}
	
	if ($('.plakatshop3').length > 0) {
		$('tr.dateiUpload').hide();
		changeAnfrageOderBestellung('plakatbestellung');
	} else {
		$('input[type="radio"][name="anfrageOderBestellung"]').click(function() {
			var anfrageOderBestellung = $('input[type="radio"][name="anfrageOderBestellung"]:checked').val();
			changeAnfrageOderBestellung(anfrageOderBestellung);
		});
		changeAnfrageOderBestellung('anfrage');
	}

	
	// übler hack für IE
	if ($.browser.msie == true && parseInt($.browser.version, 10) >= 9) {
		$('tr.rechnungsadresse_abweichend, tr.lieferadresse_abweichend').each(function(){
			$(this).show();
		});
		$('tr.rechnungsadresse_abweichend, tr.lieferadresse_abweichend').each(function(){
			$(this).hide();
		});
	}	
	
	$('#rechnungsadresse_abweichend, #lieferadresse_abweichend').click(function() {
		var matches = $(this).attr('id').match(/^(.*)_abweichend/);		
		var kategorie = matches[1];
		var active = $(this).attr('checked') == 'checked';
		var $rows = $('body').find('tr.' + kategorie + '_abweichend');
		if (active == true) {
			$rows.show();
		} else {
			$rows.hide();
		}
 	});
	
	// ganz allgemein: Fokus auf das erste Formular-Eingabefeld
	
	$('form input[type="text"]').eq(0).focus();
	
});

function displayUploads() {
	// bereits hochgeladene Dateien anzeigen
	var url = '_uploads/uploader.php?sess_id=' + escape($.cookie('PHPSESSID'));
	$.ajax({
		url: url,
		success: function(data) {
			//trace('suckzess');
			//trace(data);
			$('#uploads').remove();
			var $uploadedFiles = $('<ul id="uploads" class="rounded grey"/>');
			$.map(data, function(file) {
				//trace(file.name);
				$uploadedFiles.append('<li>' + file.name + '</li>');
            });
			$('#dateiUploadButton').prepend($uploadedFiles);
		}
	});
}

function terminOptionen() {
	var $deadlineChoice = $('<select id="deadlineChoice">'
		   			      + '<option value="2-3_werktage">innert 2-3 Werktagen (normal)</option>'
						  + '<option value="24_stunden_werktags">innert 24 Stunden werktags (Express): Zuschlag 10%</option>'
					      //+ '<option value="4_tage_plus">innert 4 Werktagen oder mehr: -10%</option>'
	       			      + '</select>');
	$deadlineChoice.find('option').removeAttr('selected');
	$deadlineChoice.find('option[value=' + terminOption + ']').attr('selected', 'selected');
						
	$('#deadlineChoice').live('change', function() {
		//trace('deadline choice changed ' + $(this).val());
		changeTerminOption($(this).val());
	});	
	return $deadlineChoice.clone().wrap('<div></div>').parent().html();
}

function changeTerminOption(terminChoice) {
	//trace('changeTerminOption: ' + terminChoice);
	terminOption = terminChoice;
	$.cookie('terminOption', terminOption, cookieOptions);
	showBasket();
}

function versandOptionen() {
	var $shippingChoice = $('<select id="shippingChoice">'
			   		      + '<option value="basel">Basel und Umgebung * : CHF 15.-, ab CHF 200.- gratis</option>'
						  + '<option value="selbstabholung">Selbstabholung</option>'
		   			      + '<option value="a-post">A-Post: CHF 20.-</option>'
					      + '<option value="express">Express: CHF 30.-</option>'
		   			      + '<option value="sperrgut-express">Sperrgut Express (F200 NP / LP, F12 LP): CHF 50.-</option>'
	       			      + '</select>');
	
	$shippingChoice.find('option').removeAttr('selected');
	$shippingChoice.find('option[value=' + versandArt + ']').attr('selected', 'selected');
	$('#shippingChoice').live('change', function() {
		//trace('shipping choice changed ' + $(this).val());
		changeVersandOption($(this).val());
	});	
	return $shippingChoice.clone().wrap('<div></div>').parent().html();
}


function changeVersandOption(shippingChoice) {
	//trace('changeVersandOption');
	versandArt = shippingChoice;
	$.cookie('versandArt', versandArt, cookieOptions);
	showBasket();
}

function changeAnfrageOderBestellung(aOderB) {
	//trace('changeAnfrageOderBestellung ' + aOderB);
	anfrageOderBestellung = aOderB;
	switch (aOderB) {
		case 'anfrage':
			//trace($('form.anfrageBestellung'));
			$('form.anfrageBestellung').attr('id', 'anfrage');
			$('form .agb').remove();
			$('.rechnungsadresse_abweichend_header, .lieferadresse_abweichend_header').hide();
			$('#uploadButton').removeClass('rot');
			$('#uploadButton').addClass('grey');
			$('#dateiUploadText').text('Datei(en)');			
		break;
		case 'bestellung':
			$('form.anfrageBestellung').attr('id', 'bestellung');
			$('form .agb').remove();
			$('.rechnungsadresse_abweichend_header, .lieferadresse_abweichend_header').show();
			$('#uploadButton').addClass('rot');
			$('#uploadButton').removeClass('grey');
			$('#dateiUploadText').text('Datei(en) *');			
		break;
		case 'plakatbestellung':
			//trace('->>>>>>>>>>plakatbestellung');
			$('tr.submit a').text('Bestellung absenden');
		break;		
	}
}
		
function storeForm($form) {
	var data = {};
	$form.find('input, textarea, input:checkbox:checked').not('[type="radio"]').not('[type="checkbox"]').each(function() {
		//trace($(this).attr('name') + ': ' + $(this).val());
		data[$(this).attr('name')] = $(this).val();
	});
	//trace(JSON.stringify($form.serializeArray()));
	$.cookie('adresse', JSON.stringify(data), cookieOptions);
	//$.cookie('adresse', null);
}

function restoreForm($form) {
	//trace('restoreForm');
	if (typeof $.cookie == 'undefined') { return; }	
	var data = eval('(' + $.cookie('adresse') + ')'); // eval() durch 'JSON.parse()' ersetzen
	for (var key in data) {
		if (key == 'agb_gelesen_und_akzeptiert') { continue; }
		//trace(key + ': ' + data[key]);
		$form.find('[name="' + key + '"]').not('[type="radio"]').val(data[key]);
	};
}

function sendForm(name) {

	//trace('sendForm: ' + name);
		
	var $form = $('form.anfrageBestellung').eq(0);
	
	var typ = $form.attr('id');
	
	//trace('>>>>>>>>typ: ' + typ);
	
	if (typ == 'plakatbestellung') {
		if (typeof bestellMatrix == 'undefined' || typeof bestellMatrix.mengen == 'undefined') {
			showMessage('Sie haben keine Waren im Warenkorb');
			return;
		}
	}
		
	$form.find('td').removeClass('rot');
	$('.pleaseFillOutTheRequiredFields').remove();
	
	// check for required fields
		
	var $elements = $form.find('input[type="text"], input[type="password"], input[type="checkbox"], textarea');
	var numMissingFieldContents = 0;	
	$elements.each(function() {
		if ($(this).hasClass('required') == true) {
			if ($(this).val() == '' || $(this).val() == undefined) {
				$(this).parent().siblings('td').addClass('rot');
				++numMissingFieldContents;
			}
			if ($(this).attr('id') == 'agb_gelesen_und_akzeptiert' && $(this).attr('checked') != 'checked') {
				$(this).parent().addClass('rot');
				++numMissingFieldContents;
			}
		}
	});
	//return;
	
	if (numMissingFieldContents > 0) {
		
		var $row = $form.find('tr.requiredFields').eq(0);
		$row.before('<tr class="pleaseFillOutTheRequiredFields">'
		          + '<td></td>'
		          + '<td class="pleaseFillOutTheRequiredFields">Bitte füllen Sie die <span class="rot">rot markierten Felder</span> aus.</td>'
		          + '</tr>');

	} else {
		
		trace('ok zum Posten');
		
		// prepare data for posting
		
		var data = $form.serializeArray();
		
		data.push({
				name: 'typ',
				value: typ,
			},
			{
				name: 'sessionID',
				value: $.cookie('PHPSESSID')
			}
		);
		
		if (typ == 'plakatbestellung') {
			data.push(
				{
					name: 'bestellung',
					value: JSON.stringify(bestellMatrix)
				},
				{
					name: 'terminOption',
					value: terminOption
				},
				{
					name: 'terminRabatt',
					value: terminRabatt
				},
				{
					name: 'versandart',
					value: versandArt
				}
			);
		}
	
		var rechnungsAdresseAbweichend = $("input:checkbox[name='rechnungsadresse_abweichend']").attr('checked') == 'checked' ? true : false;
	
		data.push({
			name: 'rechnungsAdresseAbweichend',
			value: rechnungsAdresseAbweichend
		});
		
		var lieferAdresseAbweichend = $("input:checkbox[name='lieferadresse_abweichend']").attr('checked') == 'checked' ? true : false;
	
		data.push({
			name: 'lieferAdresseAbweichend',
			value: lieferAdresseAbweichend
		});	
				
		data.push({
			name: 'zehnProzent',
			value: zehnProzent
		});
		
		var url = '_system/libraries/mailer.php';
		
		//trace(data); return;
		
		$.ajax({
			type: 'POST',
			url: url,
			data: data,
			cache: false,
			contentType: "application/x-www-form-urlencoded; charset=UTF-8",
			success: function(data) {
				//trace('data: ' + data);
				if (data == 'OK') {
					formSent(true, typ, $form);
				} else {
					formSent(false, typ, $form);
				}
			},
			error: function() {
				formSent(false, typ, $form);
			}
		});
	}
}

function formSent(success, typ, $form) {
	
	//trace('>>>>>>>>> form sent: ' + success + ' ' +  typ);
	
	$.scrollTo(0, 0);
		
	var $anfrageBestellungDiv;
	if (typ == 'plakatbestellung') {
		$('#warenkorb, .button').hide();
		$anfrageBestellungDiv = $('#unten');
	} else {
		$anfrageBestellungDiv = $('#anfrageBestellung');
	}
	
	$anfrageBestellungDiv.hide();
	
	var $answerDiv = $('<div />');
	$answerDiv.css({marginTop: '16px'});
		
	var anfrageOderBestellungUpper = anfrageOderBestellung.charAt(0).toUpperCase() + anfrageOderBestellung.slice(1);
	
	var answerText;
	if (success === true) {
		answerText = '<h3>Vielen Dank für Ihre ' + anfrageOderBestellungUpper + '!</h3>'
		           + '<p>Wir haben sie erfolgreich entgegengenommen.</p>';
		emptyCart();
	} else {
		answerText = '<p>Es gab ein Problem beim Versand Ihrer ' + anfrageOderBestellungUpper + '.</p>'
		           + '<p>Bitte versuchen Sie es erneut oder kontaktieren Sie uns per <a href="mailto:info@creaplot.ch">e-Mail</a>.</p>';
	}
	
	$answerDiv.html(answerText);
	$anfrageBestellungDiv.html($answerDiv).fadeIn();
		
}

function showMessage(text) {
	//trace('showMessage: ' + text);
	$.colorbox({ 
		'width'		      		:	800,
		'height'		      	:	200,
		'changeSpeed'			: 	300,
		'href': 'de/_spezial/warenkorb_leer.html'
	});
}

function showUpload() {
	//trace('showUpload');
	$.colorbox({ 
		width		: 686,
		height		: 500,
		opacity		: .7,
		href		: 'index.php?module=CreaplotShop/upload/fileupload&mode=main_only',
		onComplete	: function() {
			makeFancyLinks();
		},
		onClosed	: function() {
			//trace('colorbox was closed');
			if ($('#uploads').length > 0) {
				displayUploads();
			};
		}
	});
}

function emptyCart() {
	
	trace('emptyCart');
	
	bestellMatrix = {};
	delete bestellMatrix.mengen;
	
	trace(JSON.stringify(bestellMatrix));
	
	//$.cookie('bestellung', JSON.stringify(bestellMatrix));
	$.cookie('bestellung', '', {path: '/', expires: -1});
	//$.cookie('bestellung', '', { path: '/', expires: -5 }); // delete cookie
	//document.cookie = 'cookiename=bestellung; expires=Thu, 01-Jan-70 00:00:01 GMT;';
	document.cookie = 'bestellung' + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";

	
	$('#bestellung_gesamttotal').text('');
		
	delete terminOption;
	$.cookie('terminOption', null);
	$.cookie('terminOption', '', { expires: -1 }); // delete cookie
	
	delete versandArt;
	$.cookie('versandArt', null);
	$.cookie('versandArt', '', { expires: -1 }); // delete cookie
	
	trace('jetz kommts');
	trace($.cookie('bestellung'));
	
	$('.preisliste').each(function() {
		$(this).find('input.menge').val('');
		var shop = $(this).data('shop');
		shop.update();
	});
}
	
function showBasket() {
	
	//trace('showBasket');
	
	if (typeof bestellMatrix == 'undefined' || typeof bestellMatrix.mengen == 'undefined') {
		//trace('der warenkorb ist leer');
		$('#warenkorb').html('<p>[Der Warenkorb ist leer]</p>'
		                   + '<p><a href="?path=de/_plakatshop">← ändern</a></p>'
		);
		return;
	}
	
	$('#warenkorb').empty();
	
	var $table = $('<table class="warenkorb"/>');
	var $row;
	var menge, bezeichnung;
	
	var summe = 0;
	
	for (var thing in bestellMatrix.mengen) {	
			
		menge = bestellMatrix.mengen[thing];
		summe += menge.subtotal;	
		
		switch (menge.kategorie) {
			case 'plakat':
				bezeichnung = menge.menge == 1 ? 'Plakat' : 'Plakate'; 
			break;
			case 'plakat_220gm':
				bezeichnung = menge.menge == 1 ? 'Plakat 220 g' : 'Plakate 220 g'; 
			break;
			case 'creaflex_plakat':
				bezeichnung = menge.menge == 1 ? 'Creaflex-Plakat' : 'Creaflex-Plakate'; 
			break;				
		} 
		$row = $('<tr/>');
		$row.append($(
		    	'<td>' + menge.menge + '</td>'
			+	'<td>' + bezeichnung + '</td>'
			+	'<td>' + menge.format + '</td>'
			+	'<td>à</td>'
		    +	'<td class="stueckpreis">' + menge.stueckpreis.formatMoney() + '</td>'
		    +	'<td class="subtotal">' + menge.subtotal.formatMoney() + '</td>'
		));
		$table.append($row);
	};	
	
	zehnProzent = (summe * .1).roundPrice();
	
	var numCellsPerRow = $row.find('td').length;
	
	$row = $('<tr/>');
	$row.append(
		  '<td class="total zwischentotal links" colspan="' + (numCellsPerRow - 1) + '">Zwischentotal</td>'
		+ '<td class="total zwischentotal" id="summe">' + summe.formatMoney() + '</td>'
	);
	$table.append($row);
	
	summe -= zehnProzent;
	
	$row = $('<tr/>');
	$row.append(
		  '<td class="rot" colspan="' + (numCellsPerRow - 1) + '">10% Rabatt für Online-Bestellung</td>'
		+ '<td class="subtotal">- ' + zehnProzent + '</td>'
	);
	$table.append($row);
	
	//trace('summe vor terminrabatt: ' + summe);
	
	// Termin-Option
	
	//trace('Terminoption: ' + terminOption);
		
	terminRabatt = 0;
	
	switch (terminOption) {
		case '2-3_werktage':
			terminRabatt = 0;
		break;
		case '24_stunden_werktags':
			terminRabatt = Number(zehnProzent);
		break;
		//case '4_tage_plus':
		//	terminRabatt = summe * -.1;
	//	break;	
	}
	
	trace('terminRabatt: ' + terminRabatt);
	terminRabatt = Number(terminRabatt.roundPrice());
	
	//trace('Termin-Rabatt: ' + terminRabatt);
	
	$row = $('<tr/>');
	$row.append(
		  '<td class="versandart" colspan="' + (numCellsPerRow - 1) + '">' 
		+ '<span class="bestellOption">Liefertermin</span>' + terminOptionen() + '</td>'
		+ '<td class="versandart subtotal">' + terminRabatt.formatMoney() + '</td>'
	);
	$table.append($row);
	
	//trace('summe: ' + summe);
	
	summe += Number(terminRabatt.roundPrice());

	
	// Versandspesen
	
	var versandspesen;
	
	//trace('Versandart: ' + versandArt);
	
	switch (versandArt) {
		case 'a-post':
			versandspesen = 20;
		break;
		case 'express':
			versandspesen = 30;
		break;
		case 'sperrgut-express':
			versandspesen = 50;
		break;
		case 'selbstabholung':
			versandspesen = 0;
		break;
		default:
			versandspesen = summe <= 200 ? 15 : 0;
	}
	
	// Versandart
	
	$row = $('<tr/>');
	$row.append(
		  '<td class="versandart" colspan="' + (numCellsPerRow - 1) + '">'
		+ '<span class="bestellOption">Versandspesen</span>' + versandOptionen() + '</td>'
	    + '<td class="versandart subtotal">'  + (versandspesen == 0 ? (versandArt == 'selbstabholung' ? versandspesen.formatMoney() : 'gratis') : versandspesen.formatMoney()) + '</td>'
	);
	$table.append($row);
	
	//trace('versandspesen: ' + versandspesen);
	
	summe += versandspesen;
	
	// MwSt
	
	var mwst = summe * .08;

	$row = $('<tr/>');
	$row.append(
		  '<td class="" colspan="' + (numCellsPerRow - 1) + '">MwSt 8%</td>'
		+ '<td class="subtotal">'  + mwst.roundPrice()  + '</td>'
	);
	$table.append($row);
	
	//trace('mwst vor Rundung: ' + mwst);
	
	mwst = mwst.roundPrice();

	summe += Number(mwst);

	//trace('mwst: ' + Number(mwst));
		
	// Total

	var total = summe;
	
	$row = $('<tr/>');
	$row.append(
		  '<td class="total links" colspan="' + (numCellsPerRow - 1) + '">Total CHF</td>'
		+ '<td class="subtotal total">' + total.formatMoney() + '</td>'
	);
	$table.append($row);
	
	$row = $('<tr/>');
	$row.append(
		      '<td class="ortschaften" colspan="' + numCellsPerRow + '"> * der Raum Basel beinhaltet folgende Regionen: Basel-Stadt, Riehen, Allschwil, Binningen, Bottmingen, Oberwil, Therwil, Ettingen, Münchenstein, Reinach, Arlesheim, Aesch, Dornach, Muttenz und Pratteln</td>');
	$table.append($row);
	
	$row = $('<tr/>');
	$row.append(
		      '<td colspan="' + numCellsPerRow + '">'
	        + '<a href="?path=de/_plakatshop">← ändern</a>'
	        + '&nbsp;&nbsp;&nbsp;<a href="javascript:offerteAlsPDF();">→ Offerte als PDF ausgeben</a>'
	        + '</td>');
	$table.append($row);
	

	

	
	$('#warenkorb').empty();
	
	var $title = $('<h3>Ihre Bestellung:</h3>');
	$('#warenkorb').append($title);
	$('#warenkorb').append($table);
	
	bestellMatrix.terminOption = terminOption;
	bestellMatrix.terminRabatt = Number(terminRabatt.roundPrice());
	bestellMatrix.mwst = Number(mwst);
	bestellMatrix.total = total;

}

function updateBasket() {
	//trace('updateBasket');
	//var $table = $('#warenkorb');
	//trace($table);
}

(function($){ 
 
/**
* CreaplotKonfigurator plug-in
* @author Peter Chylewski <peter@boring.ch>
* Tue Jul  5 03:43:30 CEST 2011
*/
	
$.fn.CreaplotKonfigurator = function(options) {

	//trace('CreaplotKonfigurator');

	var defaults = {};

	var options = $.extend(defaults, options);

	return this.each(function() {

		var $obj = $(this);

		var $table = $obj;

		var kategorie = $table.attr('class').match(/kat:(.*$)/)[1];
		var beschreibung = $obj.parent('.invisibleTitle').text();

		var auflagen = [];
		$table.find('th.auflage').each(function() {
			auflagen.push($(this).text().replace(' *', ''));
		});
		
		$('input.menge').keyup(function(e) {
			e.preventDefault();
			shop.update();
		});

		var shop = new Shop();
		$obj.data('shop', shop);
		
		shop.restore();
		
		function Shop() {

			this.restore = function() {

				//trace('Shop.restore');
			
				if (bestellMatrix == null || bestellMatrix == {} || typeof bestellMatrix == 'undefined' || typeof bestellMatrix.mengen == 'undefined') { return; }
				
				for (var key in bestellMatrix.mengen) {
					var menge = bestellMatrix.mengen[key];
					if (key.indexOf(kategorie) == 0) {
						var titel = key.match(/^.*_(.*)$/)[1];
						var $cell = $obj.find('td:contains("' + titel +'")');
						var $row = $cell.parent();
						$row.find('input.menge').eq(0).val(menge.menge);
						$row.find('td.subtotal').eq(0).text(menge.subtotal.formatMoney());
					}
				};
				this.update();
			}

			this.update = function() {

				//trace('Shop.update');	

				if (bestellMatrix == null) {
					bestellMatrix = {};
				}
				if (bestellMatrix.mengen == null) {
					bestellMatrix.mengen = {};
				}

				var total = 0;

				$table.find('tr').not(':first').not(':last').each(function() {

					var $row = $(this);
					var $input = $(this).find('td.menge').find('input');

					var titel = $(this).find('td').eq(0).text();
					var key = kategorie + '_' + titel;
	
					var menge = Number($input.val());

					$row.find('td.preis').removeClass('preisAktiv');

					if (menge == undefined || menge == '' || isNaN(menge) || menge == 0) {

						menge = 0;
						$input.val('');
						$row.find('td.subtotal').text('');
						delete bestellMatrix.mengen[key];

					} else {
						
						var preis = findPrice($row, menge);
						var subtotal = preis * menge;
						$row.find('td.subtotal').text(subtotal.formatMoney());
						total += subtotal;

						bestellMatrix.mengen[key] = {
							kategorie: kategorie,
							format: titel,
							stueckpreis: preis,
							menge: menge,
							subtotal: subtotal
						};
					}
				});

				$.cookie('bestellung', JSON.stringify(bestellMatrix), cookieOptions);

				var $total = $table.find('.total').last();
				$total.text(total.formatMoney());			

				var gesamtTotal = 0;
				for (var thing in bestellMatrix.mengen) {
					gesamtTotal +=  bestellMatrix.mengen[thing].subtotal;
				};
				
				bestellMatrix.total = gesamtTotal;
							
				$('#bestellung_gesamttotal').text(gesamtTotal > 0 ? gesamtTotal.formatMoney() : '');
				
				//trace('gesamtTotal: ' + gesamtTotal);
				
				if (gesamtTotal == 0) {
					$('.showIfCartNotEmpty').hide();
				} else {
					$('.showIfCartNotEmpty').show();
				}
			}
			
			this.empty = function() {
				//trace('Shop.empty');
			}

			function findPrice($row, menge) {

				var preise = [];
				$row.find('.preis').each(function() {
					preise.push(Number($(this).attr('class').split(' ')[1].split(':')[1]));
				});
	
				var maxAuflage = auflagen[auflagen.length - 1];
				
				var gesuchterIndex = -1;
				for (var i = 0; i < auflagen.length; i++) {
					var auflage = auflagen[i];
					if (auflage == '1') {
						auflageMin = 1;
						auflageMax = 1;
					} else if (auflage == maxAuflage) {
						auflageMin = Number(maxAuflage.replace('+', ''));
						auflageMax = Infinity;
					} else {
						auflageParts = auflage.split(' bis ');
						auflageMin = auflageParts[0];
						auflageMax = auflageParts[1];
					}
					if (menge >= auflageMin && menge <= auflageMax) {
						gesuchterIndex = i;
						break;
					}
				}
	
				if (gesuchterIndex > preise.length - 1) { gesuchterIndex = preise.length - 1; }

				$row.find('td.preis').eq(gesuchterIndex).addClass('preisAktiv');

				return preise[gesuchterIndex];

			}
			
		} // Shop class

		}); // this.each (end)
	}

})(jQuery);

Number.prototype.roundPrice = function() {
	var decimalPlaces = 2;
	var theNumber = Math.round(this * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces);
	var prefix = this < 0 ? '-' : '+';
	var priceMultiplied = Math.ceil(Math.abs(theNumber) * 100);
	var reminder = priceMultiplied % 5;
	var compliment = reminder ? 5 - reminder : 0;
	var priceRounded = (priceMultiplied + compliment)/100;
	if (prefix == '+') {
		return priceRounded.toFixed(2);
	} else {
		return priceRounded.toFixed(2) * - 1;
	}	
}

Number.prototype.formatMoney = function() {
	if (this % 1 == 0) {
		return this + '.––'; 
	}
	return (Math.round(this * 100) / 100).toFixed(2);
}

function offerteAlsPDF() {
	//trace('offerteAlsPDF');
	//trace(bestellMatrix);
	var data = {};
	data.bestellung = bestellMatrix;
	data.typ = 'offerte';
	data.versandart = versandArt;
	data.zehnProzent = zehnProzent;
	window.open('_system/libraries/CreaplotPDFOfferte.php?data=' + JSON.stringify(data));
}
