$(document).ready(function() {

	$.extend({

		// --------------------------------------------------------------------------------------------
		// CLICK: alle Flugauswahl-Radios
		newPrice: function(objInput) {

			if (!objInput.length) return;

			// Zuschlaege auslesen
			var objContainer = objInput.parent("td").next("td");
			var priceNet = parseFloat(objContainer.children(".priceNet").text());
			var priceChd = objContainer.children(".priceChd").text();
			var priceInf = objContainer.children(".priceInf").text();
			var priceTaxes = objContainer.children(".priceTaxes").text();
			var priceAdditional = objContainer.children(".priceAdditional").text();
			var claimServiceCharge = objContainer.children(".claimServiceCharge").text(); // Werbepreis
			var promotionalMiles = objContainer.children(".promotionalMiles").text();
			var tariffName = objContainer.children(".tariffName").text();
			var redemptionMiles = objContainer.children(".redemptionMiles").text();
			
			var currencySymbol = $("#currencySymbol").html();
			var thouSep = $("#thouSeparator").html();
			var deciSep = $("#deciSeparator").html();
			var deciPla = $("#deciPlaces").html();

			// Preis berechnen
			var priceBrutto = (parseFloat(priceNet)) ? parseFloat(priceNet) : 0;
				priceBrutto+= (parseFloat(priceTaxes)) ? parseFloat(priceTaxes) : 0;
				priceBrutto+= (parseFloat(priceAdditional))	? parseFloat(priceAdditional) : 0;
								
			// Zuschlaege des Legs aktualisieren
			var objTfoot = objInput.parent().parent().parent().parent().children("tfoot");
			objTfoot.children("tr.priceNet").children("td.value").html(currencySymbol+"&nbsp;"+$.formatNumber(priceNet, deciPla, deciSep, thouSep));
			objTfoot.children("tr.priceNet").children("td.floatValue").children("span").html(priceNet);
			objTfoot.children("tr.priceTaxes").children("td.value").html(currencySymbol+"&nbsp;"+$.formatNumber(priceTaxes, deciPla, deciSep, thouSep));
			objTfoot.children("tr.priceTaxes").children("td.floatValue").children("span").html(priceTaxes);
			objTfoot.children("tr.priceAdditional").children("td.value").html(currencySymbol+"&nbsp;"+$.formatNumber(priceAdditional, deciPla, deciSep, thouSep));
			objTfoot.children("tr.priceAdditional").children("td.floatValue").children("span").html(priceAdditional);
			objTfoot.children("tr.priceChd").children("td.floatValue").children("span").html(priceChd);
			objTfoot.children("tr.priceInf").children("td.floatValue").children("span").html(priceInf);
			objTfoot.children("tr.claimServiceCharge").children("td.value").text(claimServiceCharge);
			objTfoot.children("tr.priceBrutto").children("td.value").html(currencySymbol+"&nbsp;"+$.formatNumber(priceBrutto, deciPla, deciSep, thouSep));
			objTfoot.children("tr.priceBrutto").children("td.floatValue").children("span").html(priceBrutto);
			objTfoot.children("tr.priceBrutto").children("td").find(".promotionalMiles").html($.formatNumber(promotionalMiles, 0, '', thouSep));
			objTfoot.children("tr.redemptionMiles").children("td.floatValue").children("span").html(redemptionMiles);

			//$.markPrice(objInput);	// gew. Preis markieren
			$.markRow(objInput);	// gew. Flugzeile markieren
			$.setSeats(objInput);	// Freie Plaetze des gew. Fluges anzeigen
			$.calcPriceTotal();		// Gesamtpreis aktualisieren

		},

		// ... Preis formatieren ..................................................................
		formatNumber: function(value, laenge, sep, th_sep) {
			
			if (isNaN(value)) value = 0;
			
			number = Math.round( value * Math.pow(10, laenge) ) / Math.pow(10, laenge);
			str_number = number+"";
			arr_int = str_number.split(".");
			if (!arr_int[0]) arr_int[0] = "0";
			if (!arr_int[1]) arr_int[1] = "";
			if (arr_int[1].length < laenge) {
				nachkomma = arr_int[1];
				for (i = arr_int[1].length+1; i <= laenge; i++) nachkomma += "0";
				arr_int[1] = nachkomma;
			}
			if (th_sep != "" && arr_int[0].length > 3) {
				Begriff = arr_int[0];
				arr_int[0] = "";
				for (j = 3; j < Begriff.length ; j+=3) {
					Extrakt = Begriff.slice(Begriff.length - j, Begriff.length - j + 3);
					arr_int[0] = th_sep + Extrakt +  arr_int[0] + "";
				}
				str_first = Begriff.substr(0, (Begriff.length % 3 == 0) ? 3 : (Begriff.length % 3));
				arr_int[0] = str_first + arr_int[0];
			}
			return arr_int[0]+sep+arr_int[1];
		},

		// ... Gesamtpreis berechnen ..............................................................
		calcPriceTotal: function() {

			// Preise auslesen
			var outboundNetto = parseFloat($("table.vakanz:eq(0) tfoot tr.priceNet .floatValue").text());
			if (!outboundNetto) {
				outboundNetto = 0;
			}
			var outboundTaxes = parseFloat($("table.vakanz:eq(0) tfoot tr.priceTaxes .floatValue").text());
			if (!outboundTaxes) {
				outboundTaxes = 0;
			}
			var outboundAdditional = parseFloat($("table.vakanz:eq(0) tfoot tr.priceAdditional .floatValue").text());
			if (!outboundAdditional) {
				outboundAdditional = 0;
			}
			var outboundChd = parseFloat($("table.vakanz:eq(0) tfoot tr.priceChd .floatValue").text());
			if (!outboundChd) {
				outboundChd = 0;
			}
			var outboundInf = parseFloat($("table.vakanz:eq(0) tfoot tr.priceInf .floatValue").text());
			if (!outboundInf) {
				outboundInf = 0;
			}
						
			var outboundClaimServiceCharge = parseFloat($("table.vakanz:eq(0) tfoot tr.claimServiceCharge .value").text());

			var outboundBrutto = parseFloat($("table.vakanz:eq(0) tfoot tr.priceBrutto .floatValue").text());
			if (!outboundBrutto) {
				outboundBrutto = 0;
			}
			var returnNetto	= parseFloat($("table.vakanz:eq(1) tfoot tr.priceNet .floatValue").text());
			if (!returnNetto) {
				returnNetto = 0;
			}
			var returnTaxes = parseFloat($("table.vakanz:eq(1) tfoot tr.priceTaxes .floatValue").text());
			if (!returnTaxes) {
				returnTaxes = 0;
			}
			var returnAdditional = parseFloat($("table.vakanz:eq(1) tfoot tr.priceAdditional .floatValue").text());
			if (!returnAdditional) {
				returnAdditional = 0;
			}
			var returnChd	= parseFloat($("table.vakanz:eq(1) tfoot tr.priceChd .floatValue").text());
			if (!returnChd) {
				returnChd = 0;
			}
			var returnInf	= parseFloat($("table.vakanz:eq(1) tfoot tr.priceInf .floatValue").text());
			if (!returnInf) {
				returnInf = 0;
			}
			
			var returnClaimServiceCharge = parseFloat($("table.vakanz:eq(1) tfoot tr.claimServiceCharge .value").text());
			
			var returnBrutto = parseFloat($("table.vakanz:eq(1) tfoot tr.priceBrutto .floatValue").text());
			if (!returnBrutto) {
				returnBrutto = 0;
			}

			// TSC berechnen
			var priceTsc = parseFloat($("#VarTscAmount").text());
			if (outboundClaimServiceCharge == 0 && 
				(returnClaimServiceCharge == 0 || returnClaimServiceCharge == '' || isNaN(returnClaimServiceCharge))) {
				priceTsc = 0;
			}
			
			// Gesamtpreise berechnen
			var priceTotal = outboundBrutto + returnBrutto;
			var priceIncl = priceTotal + priceTsc;
			var priceKind = 
				outboundChd + outboundTaxes + outboundAdditional + 
				returnChd + returnTaxes + returnAdditional +
				priceTsc
			;			
			var priceBaby =	outboundInf + returnInf;

			// Gesamtpreise aktualisieren
			var currencySymbol = $("#currencySymbol").html();
			var thouSep = $("#thouSeparator").html();
			var deciSep = $("#deciSeparator").html();
			var deciPla = $("#deciPlaces").html();
			
			$("#priceTotal").html(currencySymbol+"&nbsp;"+$.formatNumber(priceTotal, deciPla, deciSep, thouSep));
			$("#priceTsc").html(currencySymbol+"&nbsp;"+$.formatNumber(priceTsc, deciPla, deciSep, thouSep));
			$("#priceIncl").html(currencySymbol+"&nbsp;"+$.formatNumber(priceIncl, deciPla, deciSep, thouSep));
			$("#priceInfant").html(currencySymbol+"&nbsp;"+$.formatNumber(priceKind, deciPla, deciSep, thouSep));
			$("#priceBaby").html(currencySymbol+"&nbsp;"+$.formatNumber(priceBaby, deciPla, deciSep, thouSep));

			// miles (Praemienmeilen einloesen)
			var outboundRedemptionMiles	= parseInt($("table.vakanz:eq(0) tfoot tr.redemptionMiles .floatValue").text());
			if (!outboundRedemptionMiles) {
				outboundRedemptionMiles = 0;
			}
			var returnRedemptionMiles = parseInt($("table.vakanz:eq(1) tfoot tr.redemptionMiles .floatValue").text());
			if (!returnRedemptionMiles) {
				returnRedemptionMiles = 0;
			}
			var redemptionMilesTotal = outboundRedemptionMiles + returnRedemptionMiles;
			$("#redemptionMilesTotal").html($.formatNumber(redemptionMilesTotal, 0, '', thouSep));
		},

		// ... gew. Preis markieren ...............................................................
		markPrice: function(objRadio) {
			/*
			var tarif = objRadio.parent().attr("class");
			objRadio.parent().parent().parent().parent().find(".netto").removeClass("priceMarked");
			objRadio.parent().parent().children("."+tarif).find(".netto").addClass("priceMarked");
			*/
		},

		// ... gew. Flugzeile markieren ...........................................................
		markRow: function(objRadio) {
			objRadio.parent().parent().parent().parent().find("tr").removeClass("rowMarked");
			if (objRadio.val() != "") {
				objRadio.parent().parent("tr").addClass("rowMarked");
			}
		},

		// ... freie Plaetze anzeigen .............................................................
		setSeats: function(objRadio) {
			var tarif = objRadio.parent().attr("class");
			var seats =	$("#VarTxtFreeSeats").text();
			seats+= ': ';
			seats+=	objRadio.parent().parent().children("."+tarif).find(".vacantSeats").text();
			objRadio.parent().parent().parent().parent().find(".legSeats").text(seats);
		},

		// ... ECO vs. BUS anzeigen ...............................................................
		showTariff: function(idxLeg, idxTarif) {
			var objLeg = $("#vakanz div.legBox").eq(idxLeg);

			// Tarif-TBody anzeigen
			var objTbodys = objLeg.find("div table.vakanz tbody");
			objTbodys.css("display", "none");
			if ($.browser.msie) {
				objTbodys.eq(idxTarif).css("display", "block");
			} else {
				objTbodys.eq(idxTarif).css("display", "table-row-group");
			}

			// Tarif-Kladde markieren
			var objInnerTariffs = objLeg.find("div.innerTariffs div");
			objInnerTariffs.removeClass("selected");
			objInnerTariffs.eq(idxTarif).addClass("selected");
		},

		// ... Datum wandeln ......................................................................
		makeDateObject: function(input) {
			var dateString = input;
			// 2008-12-31
			var expr = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/;
			var dateParts = expr.exec(dateString);
			if (dateParts != null) {
				dateString+= ' 00:00';
			}
			// 2008-12-31 17:55
			var expr = /^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2})/;
			var dateParts = expr.exec(dateString);
			if (dateParts == null) {
				return false;
			}
			var output = new Date(
				dateParts[1],
				dateParts[2]-1,
				dateParts[3],
				dateParts[4],
				dateParts[5],
				0
			);
			return output;
		}

	});

	// ============================================================================================
	// ONREADY
	// ============================================================================================

var timer = new Date();
var start = timer.getTime();

	// ... Elemente mit JavaScript-Funktionalitaeten anzeigen .......
	$("#col1_content .showWithJs").removeClass("showWithJs");
	$("#col1_content .hideWithJs").hide();

	// ... TarifKladde vorauswaehlen ................................
	var objLegBoxes = $("#vakanz div.legBox");

	// 1. Outbound
	var objTariffs = objLegBoxes.eq(0).children("div.tariffs");
	if (objTariffs.children("div.innerTariffs").children("div").length > 1) {
		var idxTarif = objTariffs.children("div.legShowTariff").text();
		if (!idxTarif) {
			idxTarif = 0;
		}
		$.showTariff(0, idxTarif);
	} else {
		objTariffs.children("div").children("div").css("visibility", "hidden");
	}
	// 2. Return
	var objTariffs = objLegBoxes.eq(1).children("div.tariffs");
	if (objTariffs.children("div.innerTariffs").children("div").length > 1) {
		var idxTarif = objTariffs.children("div.legShowTariff").text();
		if (!idxTarif) {
			idxTarif = 0;
		}
		$.showTariff(1, idxTarif);
	} else {
		objTariffs.children("div").children("div").css("visibility", "hidden");
	}

	// ... Init: Preis berechnen usw. ...............................
	var objInput = $("#vakanz table.vakanz input[name=HFLUGNR]:checked");
	$.newPrice(objInput);
	var objInput = $("#vakanz table.vakanz input[name=RFLUGNR]:checked");
	$.newPrice(objInput);

	// ... ToolTipp "via" ...........................................
	$("#vakanz table.vakanz tbody a.via").each(function() {
		var txt = $(this).attr("title");
		$(this).attr("onmouseover", "Tip('"+txt+"')");
	});

	// --------------------------------------------------------------------------------------------
	// CLICK: TarifKladden (ECO|BUS)
	$(".tariffs button").click(function() {
		var thisButton =		$(this).parent();
		var arrThisButtons = 	thisButton.parent().parent().children().eq(0).children();
		var idxTarif =			arrThisButtons.index(thisButton[0]);

		var thisLeg = 			thisButton.parent().parent().parent();
		var arrThisLegs =		thisButton.parent().parent().parent().parent().children(".legBox");
		var idxLeg =			arrThisLegs.index(thisLeg[0]);

		$.showTariff(idxLeg, idxTarif);
	});

	// --------------------------------------------------------------------------------------------
	// CLICK: Preis-ToolTipp
	$("#vakanz table tbody tr td label.flightPrice").mouseover(function() {

		var objTd = $(this).parent("td");

		// Freie Sitzplaetze
		var txt = objTd.children(".vacantSeats").text();
		var objTipp1;
		if (txt) {
			var objTipp1 = $("#tplTippSeats").clone();
			objTipp1.find(".seats").html(txt);
		}

		// TarifKlasse
		var txt = objTd.children(".tariffName").text();
		var objTipp2
		if (txt) {
			objTipp2 = $("#tplTippTarifname").clone();
			objTipp2.find(".tarifname").html(txt);
		}

		// TB-Meilen
		var currencyFormat = $("#currencyFormat").html();

		var thouSep = $("#thouSeparator").html();		
		var txt = $(this).parent().find(".promotionalMiles").text();
		var objTipp3;
		if (txt) {
			objTipp3 = $("#tplTippMiles").clone();
			objTipp3.find(".miles").html($.formatNumber(txt, 0, '', thouSep));
		}

		// concat String
		var txtTipp = ((objTipp1) ? objTipp1.html() : '')
					+ ((objTipp2) ? objTipp2.html() : '')
					+ ((objTipp3) ? objTipp3.html() : '')
					;

		// Economy -> Hinweis auf Business
		// 1. spar || flex
		var thisPrice =		$(this).parent();	// <td class="flugpreis">...</td>
		var arrThisPrice = 	thisPrice.parent().children(".flugpreis");
		var idxPrice =		arrThisPrice.index(thisPrice[0]);

		// 2. welcher flug
		var thisFlight =	$(this).parent().parent(); // <tr>...</tr>
		var arrThisFlights = thisFlight.parent().children();
		var idxFlight =		arrThisFlights.index(thisFlight[0]);

		// 3. BUS-preis suchen
		var thisTbody = 	thisFlight.parent();
		var arrThisTbody =	thisTbody.parent().children("tbody");
		var idxTbody =		arrThisTbody.index(thisTbody[0]);

		// nur wenn Economy
		if (idxTbody == 0 && arrThisTbody.length > 1) {
			var txt = arrThisTbody.eq(1).children().eq(idxFlight).children(".flugpreis").eq(idxPrice).find(".netto").text();
			var thisLeg = 	thisTbody.parent();
			var arrThisLeg = thisLeg.parent().children("table.vakanz");
			var idxLeg =	arrThisLeg.index(thisLeg[0]);
			var objTipp4
			if (txt) {
				objTipp4 = $("#tplTippBusiness").clone();
				objTipp4.find(".price").html(txt);
				objTipp4.find(".showTariffLink").attr("href", "javascript:$.showTariff("+idxLeg+",1)");
			}
		}

		txtTipp += ((objTipp4) ? objTipp4.html() : '')

		// ToolTipp-Funktion
		if (txtTipp != '') {
			Tip(txtTipp);
		}

	});

	// --------------------------------------------------------------------------------------------
	// SUBMIT: Formular
	$("#col1_content form[name=vakanz]").submit(function() {

		$("#txtError").hide();

		var radioObjOutbound = $(this).find("input[name=HFLUGNR]:checked");
		var valueHF = (radioObjOutbound.val()) ? radioObjOutbound.val() : null;

		var radioObjReturn = $(this).find("input[name=RFLUGNR]:checked");
		var valueRF = (radioObjReturn.val()) ? radioObjReturn.val() : null;

		// ... Fluege gwaehlt? ....
		if (valueHF == null) {
			var error = $("#TxtErrNoOutbound").html();
			$("#txtError").html(error);
			$("#txtError").show();
			return false;
		}

		// ... Oneway nach Aegypten? ...
		var route = radioObjOutbound.parent().parent();
		var departure = route.find(".departure").text();
		var destination = route.find(".destination").text();
		var unlicensedAirportList = new Array("HRG", "LXR", "RMF", "SSH", "EBL", "ISU");
		var isUnlicensedDeparture = false;
		var isUnlicensedDestination = false;
		for (var i = 0; i < unlicensedAirportList.length; i++) {
			if (departure == unlicensedAirportList[i]) isUnlicensedDeparture = true;
			if (destination == unlicensedAirportList[i]) isUnlicensedDestination = true;
		}
		if (!valueRF && (isUnlicensedDeparture || isUnlicensedDestination)) {
			var error = $("#TxtErrOnewayToEgypt").html();
			$("#txtError").html(error);
			$("#txtError").show();
			return false;
		}

		// ... Rueckflug vor Hinflug? ...
		if (valueRF) {
			// Hin (2008-12-31 17:55)
			var date = radioObjOutbound.parent().parent("tr").children().children(".dateArr").text();
			var outboundArrival = $.makeDateObject(date);

			// Rueck
			var date = radioObjReturn.parent().parent("tr").children().children(".dateDep").text();
			var returnDeparture = $.makeDateObject(date);
			if (outboundArrival > returnDeparture) {
				var error = $("#TxtErrCombination").html();
				$("#txtError").html(error);
				$("#txtError").show();
				return false;
			}
		}
		
		// ... mehr Babies als Erwachsene?
		if ($("form[name=vakanz] select[name=numberOfAdults]").val() < $("form[name=vakanz] select[name=numberOfInfants]").val()) {
			var error = $("#TxtErrMoreInfantsThanAdults").html();
			$("#txtError").html(error);
			$("#txtError").show();
			return false;
		}

		// ... Umbuchen eines Legs: Flugkombination moeglich? ... <<--
		// 1 Leg Umbuchen ~> Oneway
		if ($("form[name=vakanz] input[name=woher]").val() == 'umbuchen' && valueHF && !valueRF) {

			// HF umbuchen
			if ($("form[name=vakanz] input[name=hinfl]").val() == '1') {
				// selected flight outbound
				var outboundArrival = $.makeDateObject(radioObjOutbound.parent().parent("tr").children().children(".dateArr").text());
				// original flight return
				var dateReturnUmbuchen = $.makeDateObject($("#VarDateUmbuchen1").text());
				if (!(outboundArrival < dateReturnUmbuchen)) {
					var error = $("#TxtErrCombination").html();
					$("#txtError").html(error);
					$("#txtError").show();
					return false;
				}
			}

			// RF umbuchen
			if ($("form[name=vakanz] input[name=rueckfl]").val() == '1') {
				// selected flight ( = return)
				var departure = $.makeDateObject( radioObjOutbound.parent().parent("tr").children().children(".dateDep").text() );
				// original flight outbound
				var dateOutboundUmbuchen = $.makeDateObject($("#VarDateUmbuchen0").text()+' 23:59');
				if (!(dateOutboundUmbuchen < departure)) {
					var error = $("#TxtErrCombination").html();
					$("#txtError").html(error);
					$("#txtError").show();
					return false;
				}
			}
		}

		// ... Miles: PraemienMiles > redemptionMiles? ...
/*
		if ($("input[name=woher]").val() == 'miles') {
			var premiumMilesAmount = parseInt($("#VarPremiumMilesAmount").text());
			if (!premiumMilesAmount) {
				premiumMilesAmount = 0;
			}
			var redemptionMilesTotal = parseInt($("#redemptionMilesTotal").text());
			var cntPersons = parseInt($("#PERSONEN").val());
			if (!redemptionMilesTotal) {
				redemptionMilesTotal = 0;
			}
			if (premiumMilesAmount < (redemptionMilesTotal * cntPersons)) {
				var error = $("#TxtErrNotEnoughMiles").html();
				$("#txtError").html(error);
				$("#txtError").show();
				return false;
			}
		}
*/

	});

	// --------------------------------------------------------------------------------------------
	// CLICK: alle Flugauswahl-Radios
	$("#vakanz table.vakanz input").click(function() {
		$.newPrice($(this));
	});

var timer = new Date();
var end = timer.getTime();
//$("#timer").val(end-start);

});