var fadeInSuggestion = function(suggestionBox, suggestionIframe) {
	$(suggestionBox).fadeTo(300,0.95);
};

var fadeOutSuggestion = function(suggestionBox, suggestionIframe) {
	$(suggestionBox).fadeTo(300,0);
};


function calcUI() 
{
	
	var tripType = $("#tripType").val();
	//alert("TT: " + tripType);
	if(tripType == 'SOJ')
	{
		if(document.getElementById("openJawInbound")) 
		{
			//alert("openJawInbound - SOJ - SHOW");
			$("#openJawInbound").show();
			var h = $("#ibe_searchbox").find("div.ibe_box_bottom_right").height();
			h = h + 50;
			$("#ibe_searchbox").find("div.ibe_box_bottom_right").height(h);
			//alert("add hight");
		}
		if(document.getElementById("openJawInbound1")) 
		{
			$("#openJawInbound1").show();
			$("#openJawInbound2").show();
		}
	}
	else
	{
		if(document.getElementById("openJawInbound")) 
		{
			//alert("openJawInbound - not SOJ - HIDE");
			//alert("War visible: " + $('#openJawInbound').is(':visible'));
			if($('#openJawInbound').is(':visible'))
			{
				//alert("reduce hight");
				$("#openJawInbound").hide();
				var h = $("#ibe_searchbox").find("div.ibe_box_bottom_right").height();
				h = h - 50;
				$("#ibe_searchbox").find("div.ibe_box_bottom_right").height(h);
			}
		}
		if(document.getElementById("openJawInbound1")) 
		{
			$("#openJawInbound1").hide();
			$("#openJawInbound2").hide();
		}
	}
	
}

function calcUIRadio() 
{
	
	var tripType = $("#tripType").val();
	//alert("TT: " + tripType);
	if(tripType == 'SOJ')
	{
		if(document.getElementById("openJawInbound")) 
		{
			//alert("openJawInbound - SOJ - SHOW");
			$("#openJawInbound").show();
			var h = $("#ibe_searchbox").find("div.ibe_box_bottom_right").height();
			h = h + 50;
			$("#ibe_searchbox").find("div.ibe_box_bottom_right").height(h);
			//alert("add hight");
		}
		if(document.getElementById("openJawInbound1")) 
		{
			$("#openJawInbound1").show();
			$("#openJawInbound2").show();
		}
	}
	else
	{
		if(document.getElementById("openJawInbound")) 
		{
			//alert("openJawInbound - not SOJ - HIDE");
			//alert("War visible: " + $('#openJawInbound').is(':visible'));
			if($('#openJawInbound').is(':visible'))
			{
				//alert("reduce hight");
				$("#openJawInbound").hide();
				var h = $("#ibe_searchbox").find("div.ibe_box_bottom_right").height();
				h = h - 50;
				$("#ibe_searchbox").find("div.ibe_box_bottom_right").height(h);
			}
		}
		if(document.getElementById("openJawInbound1")) 
		{
			$("#openJawInbound1").hide();
			$("#openJawInbound2").hide();
		}
	}
	
}

// :::::::: welcher Browser ? ::::::::
if (document.layers) {navigator.family = "nn4"}
if (document.all) {navigator.family = "ie4"}
if (window.navigator.userAgent.toLowerCase().match("gecko")) {navigator.family = "gecko"}

//  :::::::: PopUp-Box ::::::::
function popLayer(a) {
	var pad;
	var bord;
	var desc;
	if (navigator.family == "gecko") {pad="0"; bord="1 bordercolor=black";}
	else {pad="1"; bord="1";} //org: pad="1"; bord="0"; aber dafuer muss die bgcolor auf schwarz
	
	desc = "<table class=poplayertable cellspacing=0 cellpadding="+pad+" border="+bord+"  bgcolor=FFFFFF><tr><td>\n"
	        + a 
	        +"</td></tr></table>";
	
	if(navigator.family =="nn4") {
	        document.poplayer.document.write(desc);
	        document.poplayer.document.close();
	        //document.poplayer.left=x+15;
	        //document.poplayer.top=y-5;
	        }
	else if(navigator.family =="ie4") {
	        poplayer.innerHTML=desc;
	        //poplayer.style.pixelLeft=x+15;
	        //poplayer.style.pixelTop=y-5;
	        }
	else if(navigator.family =="gecko") {
	        document.getElementById("poplayer").innerHTML=desc;
	        //document.getElementById("poplayer").style.left=x+15;
	        //document.getElementById("poplayer").style.top=y-5;
	        }
}

//  :::::::: versteckt die PopUp-Box ::::::::
function hideLayer(){
        if(navigator.family =="nn4") {eval(document.poplayer.top="-500");}
        else if(navigator.family =="ie4"){poplayer.innerHTML="";}
        else if(navigator.family == "gecko") {
				document.getElementById("poplayer").innerHTML= "";
				document.getElementById("poplayer").style.top="-500";
	}
}

var x = 0;
var y = 0;

var isNav = (navigator.appName.indexOf("Netscape") !=-1);

function handlerMM(e) {
	if(document.poplayer)
	{
		var x = (isNav) ? e.pageX : event.clientX + document.body.scrollLeft;
		var y = (isNav) ? e.pageY : event.clientY + document.body.scrollTop;
	
		if(navigator.family =="nn4") {
		        document.poplayer.left=x+15;
		        document.poplayer.top=y-5;
		        }
		else if(navigator.family =="ie4"){
		        poplayer.style.pixelLeft=x+15;
		        poplayer.style.pixelTop=y-5;
		        }
		else if(navigator.family =="gecko"){
		        document.getElementById("poplayer").style.left=x+15;
		        document.getElementById("poplayer").style.top=y-5;
		        }
	}
}


function /*out: String*/ number_format( /* in: float   */ number,
                                       /* in: integer */ laenge,
                                       /* in: String  */ sep,
                                       /* in: String  */ th_sep ) 
   {

 		number = Math.round( number * Math.pow(10, laenge) ) / Math.pow(10, laenge);
 		var str_number = number+"";
 		var arr_int = str_number.split(".");
 		var nachkomma;
 		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];
  			var i;
   		for(i=arr_int[1].length+1; i <= laenge; i++)
   		{  
   			nachkomma += "0";  
   		}
  			 arr_int[1] = nachkomma;
 		}
  	if(th_sep != "" && arr_int[0].length > 3)
  	{
  		var Begriff;
    	Begriff = arr_int[0];
    	arr_int[0] = "";
    	var j;
    	for(j = 3; j < Begriff.length ; j+=3)
    	{
    		var Extrakt;
      		Extrakt = Begriff.slice(Begriff.length - j, Begriff.length - j + 3);
      		arr_int[0] = th_sep + Extrakt +  arr_int[0] + "";
    	}
    	var str_first;
    	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];
}

function initAutocompleter_BAK() {
	$('#input_origin').Autocomplete(
		{
			source: encodeGetURL('autoLocation.groovy?type=xml'),
			delay: 400,
			fx: {
				type: 'slide',
				duration: 400
			},
			helperClass: 'autocompleter',
			selectClass: 'selectAutocompleter',
			minchars: 34,
			onShow : fadeInSuggestion,
			onHide : fadeOutSuggestion
		}
	);
	
	$('#input_origin2').Autocomplete(
		{
			source: encodeGetURL('autoLocation.groovy?type=xml'),
			delay: 100,
			fx: {
				type: 'slide',
				duration: 400
			},
			helperClass: 'autocompleter',
			selectClass: 'selectAutocompleter',
			minchars: 34,
			onShow : fadeInSuggestion,
			onHide : fadeOutSuggestion
		}
	);
	
	$('#input_destination').Autocomplete(
		{
			source: encodeGetURL('autoLocation.groovy?type=xml'),
			delay: 100,
			fx: {
				type: 'slide',
				duration: 400
			},
			helperClass: 'autocompleter',
			selectClass: 'selectAutocompleter',
			minchars: 34,
			onShow : fadeInSuggestion,
			onHide : fadeOutSuggestion
		}
	);	
	
	$('#input_destination2').Autocomplete(
		{
			source: encodeGetURL('autoLocation.groovy?type=xml'),
			delay: 100,
			fx: {
				type: 'slide',
				duration: 400
			},
			helperClass: 'autocompleter',
			selectClass: 'selectAutocompleter',
			minchars: 34,
			onShow : fadeInSuggestion,
			onHide : fadeOutSuggestion
		}
	);	
}

var maxAirlines = 4;
var page = 1;
var pages = 1;
var indicatorVisible = false;
var airlinesLoaded = false;
var fpisLoaded = false;
var isListInit = false;
var airlineSize  = 1;
var start = 1; 
var isNav = (navigator.appName.indexOf("Netscape") !=-1);

var showOngoingInfos = true;
var mdebug = false;
var mapReady = false;

var _debug;
var _next_airlines;
var _prev_airlines;
var _ibe_list_summary;
var _flights;
var _maximize;
var _minimize;
var _fpis;
var _ow_flights;
var _flight_list_container;
var _next_airlines;
var _prev_airlines;
var _ibe_list_summary;


$(document).ready(function(){
	$.metadata.setType("attr", "data");
	
	showOngoingInfos = true;
	initSelections();
	
	$("#clearDebug").click(function(){
		_debug.empty();
	});
	if(mdebug) $("#debugArea").show();
	
	jQuery.executeEach = function (seconds,timeout, fn) {
        var scope = {
                stop: function () {     clearInterval(this.timer); },
                timer: setInterval(function () { fn(scope);     } , seconds),
                to: setTimeout(function(){scope.isTimeout = true;}, timeout),
                isTimeout : false
        };
	};
	
	$.fn.check = function(mode) {
		var mode = mode || 'on'; // if mode is undefined, use 'on' as default
		return this.each(function() {
			switch(mode) {
			case 'on':
				this.checked = true;
				break;
			case 'off':
				this.checked = false;
				break;
			case 'toggle':
				this.checked = !this.checked;
				break;
			}
		});
	};
	
});


function initSelections() {
	_ibe_list_summary = $("div#ibe_list_summary");	
	_flight_list_container = $("div#flightListContainer");
	_debug = $("div#debug");
}

function log(msg) {
	if(!mdebug) return;
	$(_debug).append(msg + "<br>");
}

function nextDisplay() {
	if( (page*maxAirlines)-airlineSize >= 0    )	$(_next_airlines).hide();
	else $(_next_airlines).show();
}

function prevDisplay() {
	if (page < 2) $(_prev_airlines).hide();
	else $(_prev_airlines).show();
}

function renderPageNumbers(num) {
	pages = num;
	if(pages < 2) return;
	for(i=1; i <= pages; i++)
	{
		log("render page: " + i);
		var n = $('<a style="cursor: pointer;" ></a>').append(i);
		if (i+1 <= pages) $(n).append('<span> , </span>');
		$(n).click(function(){
			page = parseInt($(this).text());
			zap();
			prevDisplay();
			nextDisplay();
		});
		$("span#pages").append(n);
	}
}

function kaufm(x) {
  var k = (Math.round(x * 100) / 100).toString();
  k += (k.indexOf('.') == -1)? '.00' : '00';
  var ret = k.substring(0, k.indexOf('.') + 3)
  ret = ret.replace(".",",");
  return ret;
}

function updatePrice(radio, highlight) {
	log("updatePrice");
    sum = 0;
	var fpi = $(radio).parent().parent().parent().parent().parent().parent();
	$("input[@type=radio][@checked]", fpi)
			.each(function(i){ 
				sum = parseFloat(sum) + parseFloat($(this).parent().find("div.routeprice").text()); 
			}
	);
	var container = $(radio).parents("div.ibe_singlecontainer"); 									
	var tp = $("span.totalPrice", $(container));
	$(tp).empty();
	$(tp).append(kaufm(sum));
	if(sum > 0 && highlight)$("div.ibe_singlecontainer_head", $(container)).eq(0).effect("highlight", {}, 2000);
	$(tp).append("&nbsp;EUR");
	$(tp).wrap("<b></b>");

}

function highlightFlight(radio) {
	var container = radio.parents("div.ibe_singlecontainer_center");
	$("table.highlight", container).removeClass("highlight");
	$("input[@type=radio][@checked]", container).each(function(i){ 
				$(this).parents("table").addClass("highlight");
			}
	);
}



function zap() {
	log("zap");
	$(".ibe_list_summary").slice(start + 1).each(function(i){
		if (i < page * maxAirlines && i >= (page -1) * maxAirlines) $(this).show();
		else $(this).hide();
	});
}

function initAirlines() {
	_next_airlines = $("a.next",_ibe_list_summary);
	_prev_airlines = $("a.prev",_ibe_list_summary);
	
	airlineSize = $("div.ibe_list_summary",_ibe_list_summary).slice(start + 1).size();
	var pages = Math.ceil(airlineSize / maxAirlines);
	
	log("pages: " + pages);
	log("airlineSize: " + airlineSize);
	
	if(airlineSize <= maxAirlines)
	{
		_next_airlines.hide();
		_prev_airlines.hide();
	}
	nextDisplay();
	prevDisplay();

	_next_airlines.click(function(){
		if (  page * maxAirlines <= airlineSize  )
		{ 
			page = page + 1;
			zap();
		}
		prevDisplay();
		nextDisplay();
	});

	_prev_airlines.click(function(){
		page = page - 1;
		zap();
		nextDisplay();
		prevDisplay();
	});
	
	var aselect = $("a.select", _ibe_list_summary);
	aselect.click(function(){
		selectAirline($(this));
	});
	
	aselect.parent().hover(
		function(){$(this).addClass("hoverFlight");},
		function(){$(this).removeClass("hoverFlight");}
	);
	
	aselect.parent().click(function(){
		selectAirline($(this).children().eq(0));
	});
	
	zap();	
	log("initAL end");
}

function selectAirline(aselect) {
	var table = aselect.parent().parent().parent();
	var container = table.parent().parent().parent();
	$("tbody.highlight", container).removeClass("highlight");
	table.addClass("highlight");
	toggleFpis(aselect.metadata().ix);
}

function toggleFpis(idx) {
	$(_fpis).hide();
	for(i = 0; i < idx.length; i++) {
		$(_fpis).eq(idx[i]).show();
	}
}

function initList() {
	_fpis = $("div.fpi", _flight_list_container);
	_flights = $("table.flight",_fpis);
	_maximize = $("img.maximize",_fpis);
	_minimize = $("img.minimize",_fpis);
	_ow_flights = $("div.ow", _fpis);
	
	checkCheapest();
	
	_flights.hover(
		function(){$(this).addClass("hoverFlight");},
		function(){$(this).removeClass("hoverFlight");}
	);
	
	_flights.bind("click", function(){
		var radio = $("input.flightRadio", $(this));
		$(radio).attr("checked","checked");
		highlightFlight($(radio));
		$(this).removeClass("hoverFlight")		
	});
	

	$("input[@type=radio][@checked]", _ow_flights).each(function(i){updatePrice($(this),false)});
	
	_maximize.bind("click", function(){
		maximizeFlight($(this));
	});
	
	_minimize.bind("click", function(){
		minimizeFlight($(this));
	});
	
	_maximize.toggle();
	initAuto();
}

function checkCheapest() {
	_ow_flights.each(function(i) {
		var tmpPrice = 10000000;
		$(".routeprice", this).each(function(o) {
			var p = $(this).metadata().price;
			if(p < tmpPrice) {
				$(this).prev().check();
				tmpPrice = p;
			}
		});
	});
}

function isReady(what) {
	log("ready: "+what);
	if(what == 'list')  {
		if(! fpisLoaded  ) { 
			initList();
		}
		fpisLoaded = true;
	}
	if(what == 'airlines')  {
		if(! airlinesLoaded  ) {
			initAirlines(); 
		}
		airlinesLoaded = true;
	}
}

function minimizeFlight(button) {
	button.parent().find("img.maximize").toggle();
	button.toggle();
	button.parents("div.ibe_singlecontainer").find("div.ibe_singlecontainer_center").toggle();
}

function maximizeFlight(button) {
	button.parent().find("img.minimize").toggle();
	button.toggle();
	button.parents("div.ibe_singlecontainer").find("div.ibe_singlecontainer_center").toggle();
}

function minimizeCar(button) {
	$(button).parent().find(".maximizeCar").toggle();
	$(button).toggle();
	first = 1;
	last = $(cars).size() - 1;
	mid = $(cars).size() / 2;
	$(cars).each( function(i) {
	   	if (i != first && i != last && i != mid && i != 0 && $(this).attr("class").indexOf('highlight') == -1 )$(this).hide();
 	});	
}

function maximizeCar(button) { 
	$(button).parent().find(".minimizeCar").toggle();
	$(button).toggle();
	$(cars).show();
}

function calculatePrice() {
	log( "calculatePrice... " );
	var sum = 0;
	var infantPrice = 0;
	var childPrice = 0;
	var adultPrice = 0;
	var carPrice = 0;
	var hotelPrice = 0;
    var atmosfairPrice = 0;
	var flightPrice = 0;
	var childCount = 0;
	var infantCount = 0;
	var adultCount = 0;
	var totalPrice = 0;
	var cur = " EUR";
	var i = 0;
	
	if(! document.initCheckOutForm.priceFlight)
		log("noFlightPrice");
	
	if(document.initCheckOutForm.priceFlight) {
		flightPrice = document.initCheckOutForm.priceFlight.value * 1;
		log("flightPrice: " + flightPrice);
	}

	if(document.initCheckOutForm.carId) {
		for(i=0; i < document.initCheckOutForm.carId.length; i++) {
			if (document.initCheckOutForm.carId[i].checked) {
				carPrice = document.initCheckOutForm.carprice[i].value * 1;
				carDiscount = document.initCheckOutForm.carpriceDiscount[i].value * 1;
				carPrice = carPrice + carDiscount;
			}
		}
	}
	
	if(document.initCheckOutForm.hotelId) {
		for(i=0; i < document.initCheckOutForm.hotelId.length; i++) {
			if (document.initCheckOutForm.hotelId[i].checked == true) {
				hotelPrice = document.initCheckOutForm.hotelprice[i].value * 1;
			}
		}
	}
 
	if(document.initCheckOutForm.atmosfairPrice) { 
		for(i=0; i < document.initCheckOutForm.atmosfairPrice.length; i++) { 
			if (document.initCheckOutForm.atmosfairPrice[i].checked == true) { 
				atmosfairPrice = document.initCheckOutForm.atmosfairPrice[i].value * 1; 
			} 
		} 
	}   
	
	totalPrice = totalPrice + flightPrice;
	log("totalPrice: " + totalPrice);
	var out;
	
	var cform = document.initCheckOutForm;
	
	if(document.initCheckOutForm.childCount) {
		childCount = document.initCheckOutForm.childCount.value * 1;
	}
	if(document.initCheckOutForm.infantCount) {
		infantCount = document.initCheckOutForm.infantCount.value * 1;
	}
	if(document.initCheckOutForm.adultCount) {
		adultCount = document.initCheckOutForm.adultCount.value * 1;
	}
	
	if(carPrice > 0) {
		carPrice = carPrice.toFixed(2);
		totalPrice += carPrice * 1;
		carPrice = number_format(carPrice, 2, ",", "."); 
		try{
			document.getElementById( "carPriceArea" ).innerHTML = carPrice + cur;
			$( "#carPriceRow" ).show();
		}catch(e){
			;
		} 
	}
	
	if(carPrice == 0) {
		$( "#carPriceRow" ).hide();
	}
	
	if(hotelPrice > 0) {	
		hotelPrice = hotelPrice.toFixed(2);
		totalPrice += hotelPrice * 1;
		hotelPrice = number_format(hotelPrice, 2, ",", ".");
		try{
			document.getElementById( "hotelPriceArea" ).innerHTML = hotelPrice + cur;
			document.getElementById( "hotelPriceArea" ).style.display="block";
			document.getElementById( "hotelPriceDesc" ).style.display="block";
		}catch(e){
			;
		}
	}
	
	if(hotelPrice == 0) {
		$( "#hotelPriceRow" ).hide();
	} else {
		$( "#hotelPriceRow" ).show();
	}
     
	try{
	    if(document.getElementById( "atmosfairPriceDesc" )){
			document.getElementById( "atmosfairPriceDesc" ).style.display="none";
		}
	}catch(e){
		;
	}
	
	if(atmosfairPrice > 0) {  
		personCount =  (childCount + adultCount);
		atmosfairPriceTotal = atmosfairPrice * personCount;
		totalPrice += atmosfairPriceTotal * 1;
		atmosfairPrice = number_format(atmosfairPrice, 2, ",", ".");
		atmosfairPriceTotal = number_format(atmosfairPriceTotal, 2, ",", ".");
		try{
			document.getElementById( "atmosfairPriceArea" ).innerHTML = atmosfairPriceTotal + cur;
			document.getElementById( "atmosfairPricePerson" ).innerHTML = atmosfairPrice + cur;
			document.getElementById( "atmosfairPersonCount" ).innerHTML = personCount + " Reisende";
			document.getElementById( "atmosfairPriceArea" ).style.display="block";
			document.getElementById( "atmosfairPriceDesc" ).style.display="block";
			document.getElementById( "atmosfairPricePerson" ).style.display="block";
			document.getElementById( "atmosfairPersonCount" ).style.display="block";
		}catch(e){
			;
		}
		// alert("hello");
	}
	if(atmosfairPrice == 0) {
		$( "#atmosfairPriceRow" ).hide();        
	}
	else
	{
		$( "#atmosfairPriceRow" ).show();    
	}

	totalPrice = totalPrice.toFixed(2);
	totalPrice = number_format(totalPrice, 2, ",", ".");
	
	try{
		if(document.getElementById( "totalPriceArea" )){
			document.getElementById( "totalPriceArea" ).innerHTML = totalPrice + cur;
		}
	}catch(e){
		;
	}
	
	$("#totalPriceRow").effect("highlight", {}, 400);
}

function extractBaggagePriceFromCheckoutForm() {
	var sel = $("#checkOutForm :input[@name='travellersBaggage']");
	var retVal = 0; 
	if(document.getElementById("checkOutForm").travellersBaggage) {
		var anz = sel.size();
		if(anz > 1) {
			for(i=0; i < anz; i++) {
			 	var f = document.getElementById("checkOutForm").travellersBaggage[i];
				for(y=0; y < f.options.length; y++) {
					if(f.options[y].selected == true) {
				       var id = f.options[y].value;
				       var tmp = $("span#baggageprice_" + id).metadata().price;
				       retVal = retVal + tmp;
					}
				}
			}    
		} else {
			for(i=0; i < document.getElementById("checkOutForm").travellersBaggage.length; i++) {
			 	if(document.getElementById("checkOutForm").travellersBaggage[i].selected) {
			       var id = document.getElementById("checkOutForm").travellersBaggage[i].value;
			       var tmp = $("span#baggageprice_" + id).metadata().price;
			       retVal = retVal + tmp;	
				}
			}     
		}
	}
	sel = $("#checkOutForm :input[@name='travellersBaggageMixed']");
	if(document.getElementById("checkOutForm").travellersBaggageMixed) {
		var anz = sel.size();
		if(anz > 1) {
			for(i=0; i < anz; i++) {
			 	var f = document.getElementById("checkOutForm").travellersBaggageMixed[i];
				for(y=0; y < f.options.length; y++) {
					if(f.options[y].selected == true) {
				       var id = f.options[y].value;
				       var tmp = $("span#baggagepricemixed_" + id).metadata().price;
				       retVal = retVal + tmp;	
					}
				}
			}    
		} else {
			for(i=0; i < document.getElementById("checkOutForm").travellersBaggageMixed.length; i++) {
			 	if(document.getElementById("checkOutForm").travellersBaggageMixed[i].selected) {
			       var id = document.getElementById("checkOutForm").travellersBaggageMixed[i].value;
			       var tmp = $("span#baggagepricemixed_" + id).metadata().price;
			       retVal = retVal + tmp;	
				}
			}     
		}
	}
	return retVal * 1; 
}

// Baggage
function processBaggagePrice() {
	var selPrice = 0; 
	try{
		selPrice = extractBaggagePriceFromCheckoutForm(); 
	} catch (e) {
		selPrice = 0;   
	}
	showBaggagePrice(selPrice);
	return selPrice;
}
function showBaggagePrice(price){
	var outPrice = price.toFixed(2);
	var out = number_format(outPrice, 2, ",", ".");
	document.getElementById( "baggagePriceArea" ).innerHTML = out + "&nbsp;EUR";
	document.getElementById( "baggagePriceArea" ).style.display="block";
	document.getElementById( "baggagePriceArea" ).style.display="block";
	if ( price <= 0 ){
		$("#baggagePriceRow").hide(); 
	} else {
		$("#baggagePriceRow").show();
	}
}

// Payment - cc
function processPaymentPrice() { 
	var selPrice = 0; 
	try{
		var ccType = document.getElementById("checkOutForm").ccType.value;
		selPrice = $("span#cctype_" + ccType).metadata().price * 1;
	} catch (e) {
		selPrice = 0; 
	}
	showPaymentPrice(selPrice);
	return selPrice;  
}
function showPaymentPrice(price){
	var outPrice = price.toFixed(2);
	var out = number_format(outPrice, 2, ",", ".");
	document.getElementById( "paymentPriceArea" ).innerHTML = out+ "&nbsp;EUR";
	document.getElementById( "paymentPriceArea" ).style.display="block";
	document.getElementById( "paymentPriceArea" ).style.display="block"; 
	if ( price <= 0 ){
		$( "#paymentPriceRow" ).hide();
	} else {
		$( "#paymentPriceRow" ).show();
	}
}

// Delivery
function processDeliveryPrice() {

	var selPrice = 0;
	try {
		var id = $("#checkOutForm :input[@name='deliveryType'][@checked]");
		var tmp = $("span#deliverymode_" + id.val()).metadata().price;
		selPrice = tmp * 1;
	} catch (e) {
		selPrice = 0;
	}

	showDeliveryPrice(selPrice)
	return selPrice;
}

function showDeliveryPrice(price) {
	var outPrice = price.toFixed(2);
	var out = number_format(outPrice, 2, ",", ".");
	$("#deliveryPriceArea").empty();
	$("#deliveryPriceArea").prepend(out + "&nbsp;EUR");
	if ( price <= 0 ){
		$("#deliveryPriceRow").hide();
	} else {
		$("#deliveryPriceRow").show();
	}
}

function processAtmosfairPrice()
{
	log(" start processAtmosfairPrice");
	
	var childCount = 0;
	var infantCount = 0;
	var adultCount = 0;
	var personCount = 0;
	var atmosfairPriceTotal = 0;
	var atmosfairPrice = 0;
	
	if(document.orderForm.childCount) {
		childCount = document.orderForm.childCount.value * 1;
	}
	if(document.orderForm.infantCount) {
		infantCount = document.orderForm.infantCount.value * 1;
	}
	if(document.orderForm.adultCount) {
		adultCount = document.orderForm.adultCount.value * 1;
	}
	
	if(document.orderForm.atmosfairPrice) { 
		for(i=0; i < document.orderForm.atmosfairPrice.length; i++) { 
			if (document.orderForm.atmosfairPrice[i].checked == true) { 
				atmosfairPrice = document.orderForm.atmosfairPrice[i].value * 1; 
			} 
		} 
	}   
	if(atmosfairPrice > 0) {
		personCount =  (childCount + adultCount);
		atmosfairPriceTotal = atmosfairPrice * personCount;
	}
	
	showAtmosfairPrice(personCount, atmosfairPrice, atmosfairPriceTotal); 		
	return atmosfairPriceTotal * 1;
}

function showAtmosfairPrice(personCount, atmosfairPriceIn, atmosfairPriceTotalIn){
	var cur = "&nbsp;EUR";

	var atmosfairPriceOut = atmosfairPriceIn.toFixed(2);
	var atmosfairPrice = number_format(atmosfairPriceOut, 2, ",", ".");
	var atmosfairPriceTotalOut = atmosfairPriceTotalIn.toFixed(2);
	var atmosfairPriceTotal = number_format(atmosfairPriceTotalOut, 2, ",", ".");
	
	if(atmosfairPriceIn > 0) {
		$("#atmosfairPriceArea").empty(); 
		$("#atmosfairPricePerson").empty(); 
		$("#atmosfairPersonCount").empty(); 
		$("#atmosfairPriceArea").prepend(atmosfairPriceTotal + cur);
		$("#atmosfairPricePerson").prepend(atmosfairPrice + cur);
		if( personCount > 1 ){
			$("#atmosfairPersonCount").prepend(personCount + " Personen");
		}else{
			$("#atmosfairPersonCount").prepend(personCount + " Person");
		}
	}
	
	if(atmosfairPriceIn <= 0) {
		$( "#atmosfairPriceRow" ).hide();        
	}
	else{
		$( "#atmosfairPriceRow" ).show();    
	}
}

// insurance
function processInsurancePrice() {
	var selPrice = 0; 
	try { 
		var radio = $("#checkOutForm :input[@name='erv'][@checked]");
		selPrice = radio.parent().metadata().ervPrice * 1; 
	} catch (e) {
		selPrice = 0; 
	} 
	showInsurancePrice(selPrice); 
	return selPrice * 1;
}

function showInsurancePrice(price){
	var outPrice = price.toFixed(2);
	var out = number_format(outPrice, 2, ",", ".");
	$("#insurancePriceArea").empty();
	$("#insurancePriceArea").prepend(out + "&nbsp;EUR");
	if ( price <= 0 ){
		$("#insurancePriceRow").hide();
	} else {
		$("#insurancePriceRow").show();
	}
	showInsuranceConditions()
}

function processTicketSafePrice() {
	var selPrice = 0; 
	try { 
		var radio = $("#checkOutForm :input[@name='erv_ticketsafe'][@checked]");
		selPrice = radio.parent().metadata().ticketSafePrice * 1; 
	} catch (e) {
		selPrice = 0; 
	} 
	showTicketSafePrice(selPrice); 
	return selPrice * 1;
}

function showTicketSafePrice(price){
	var outPrice = price.toFixed(2);
	var out = number_format(outPrice, 2, ",", ".");
	$("#ticketSafePriceArea").empty();
	$("#ticketSafePriceArea").prepend(out + "&nbsp;EUR");
	if ( price <= 0 ){
		$("#ticketSafePriceRow").hide();
	} else {
		$("#ticketSafePriceRow").show();
	}
	showInsuranceConditions()
}

function showInsuranceConditions()
{
	var retPrice = 0;
	var selPrice = 0;
	try { 
		var radioTs = $("#checkOutForm :input[@name='erv_ticketsafe'][@checked]");
		selPrice = radioTs.parent().metadata().ticketSafePrice * 1; 
	} catch (e) {
		selPrice = 0; 
	} 
	 retPrice = retPrice + selPrice;
	
	try { 
		var radioIns = $("#checkOutForm :input[@name='erv'][@checked]");
		selPrice = radioIns.parent().metadata().ervPrice * 1; 
	} catch (e) {
		selPrice = 0; 
	} 
	
	retPrice = retPrice + selPrice;
	
	if ( retPrice <= 0 ){
		$("#insuranceConditions").hide();
	} else {
		$("#insuranceConditions").show();
	}
}

// terreDesHommes
function processTerreDesHommes() {
	var selPrice = 0; 
	try {
		var check = $("#checkOutForm :input[@name='terreDesHommes']");
		if ( check[0].checked ) {
			selPrice = parseFloat($("#terreDesHommes").metadata().price) * 1;
		}
	} catch (e) {
		selPrice = 0;   
	}
	showTerreDesHommes(selPrice); 
	return selPrice * 1; 
}
function showTerreDesHommes(price){
	var outPrice = price.toFixed(2);
	var out = number_format(outPrice, 2, ",", ".");
	$("#terreDesHommesPriceArea").empty();
	$("#terreDesHommesPriceArea").prepend(out + "&nbsp;EUR");
	if ( price <= 0 ){
		$("#terreDesHommesConditions").hide();
		$("#terreDesHommesPriceRow").hide();
	} else {
		$("#terreDesHommesConditions").show();
		$("#terreDesHommesPriceRow").show();
	}
}

//payback
function processPayback() {
	; 
}

function showPayback() {
	; 
}


function calculateAdditionalPrices() {

	var total = 0;

	var carPrice = 0; 
	var baggagePrice = 0;
	var paymentPrice = 0 ;
	var insurancePrice = 0;
	var terreDesHommesPrice = 0; 
	var deliveryPrice = 0;
	var atmosfairPrice = 0;
	var insuranceTicketSafePrice = 0;

	// serverside given
	try {
		total = $("#calculatedTotalPriceInclFee").metadata().price * 1; 
	} catch (e) {
		total = 0; 
	}
	try {
		carPrice = $("#carPriceSelected").metadata().price * 1; 
	} catch (e) {
		carPrice = 0; 
	}
	try {
		//atmosfairPrice = $("#atmosfairPriceSelected").metadata().price * 1; 
		atmosfairPrice = processAtmosfairPrice();
		log("atmosfair price: " + atmosfairPrice );
	} catch (e) {
		atmosfairPrice = 0; 
	}
	try {	
		baggagePrice = processBaggagePrice();
		log("baggage price: " + baggagePrice );
	} catch (e){
		baggagePrice = 0; 
	}
	try{
		paymentPrice = processPaymentPrice();
		log("payment price: " + paymentPrice );
	} catch (e) {
		paymentPrice = 0; 
	}
	try{
		insurancePrice = processInsurancePrice(); 
		log("insurance price: " + insurancePrice );
	} catch (e) {
		insurancePrice = 0;  
	}
	
	try{
		ticketSafePrice = processTicketSafePrice(); 
		log("ticketSafePrice price: " + ticketSafePrice );
	} catch (e) {
		ticketSafePrice = 0;  
	}	
	
	try{
		terreDesHommesPrice = processTerreDesHommes();  
		log("terreDesHommes price: " + terreDesHommesPrice );
	} catch (e) {
		terreDesHommesPrice = 0;  
	}
	try{
		deliveryPrice = processDeliveryPrice();
		log("delivery price: " + deliveryPrice );
	} catch (e) {
		deliveryPrice = 0;  
	}
	
    $("#totalPriceArea").empty();
	total = total + carPrice + baggagePrice + insurancePrice + paymentPrice + terreDesHommesPrice + deliveryPrice + atmosfairPrice + ticketSafePrice;
	total = total.toFixed(2);
	total = number_format(total, 2, ",", ".");
	$("#totalPriceArea").prepend(total + "&nbsp;EUR");
}

var cars;
function initCars(){
	if ( isNav ){ 
		document.captureEvents(Event.MOUSEMOVE);
	}
	document.onmousemove = handlerMM;
	tb_init('a.thickbox, area.thickbox, input.thickbox');
	cars = $('.carProduct');
	//$(cars).hide();
	$(cars).hover(
		function(){$(this).addClass("hoverFlight");},
		function(){$(this).removeClass("hoverFlight");}
	);
	$(cars).bind("click", function(){
		var radio = $("input:radio", this);
		$(radio).attr("checked","checked");
		highlightFlight($(radio));
		$(this).removeClass("hoverFlight");
		calculatePrice();
		if ($(radio).val() != 0){
			$("#carPriceRow").effect("highlight", {}, 300);
		}
		if ($(".minimizeCar").css("display") != "none" ){
			minimizeCar($(".minimizeCar")); 
		}
	});
	
	highlightFlight($("input[@type=radio][@checked]", cars));
	
	log("cars: " + $(cars).size());
	first = 1;
	last = $(cars).size() - 1;
	mid = $(cars).size() / 2;
	
	$(cars).each(function(i){
   		if (i != first && i != last && i != mid && i != 0)$(this).hide();
 	});
 	
	$(".maximizeCar").bind("click", function(){
		maximizeCar($(this));
	});
	
	$(".minimizeCar").bind("click", function(){
		minimizeCar($(this));
	});
	
	$(".minimizeCar").toggle();
	
	$("#moreCars").bind("click", function(){
		maximizeCar($(".maximizeCar"));
	});
}


var atmosfairs;
function initAtmosfairs(){
	if ( isNav ){ 
		document.captureEvents(Event.MOUSEMOVE);
	}
	document.onmousemove = handlerMM;
	$('.atmosfairProduct :checked').parent().parent().addClass("highlight");
	atmosfairs = $('.atmosfairProduct');
	//$(cars).hide();
	$(atmosfairs).hover(
		function(){$(this).addClass("hoverFlight");},
		function(){$(this).removeClass("hoverFlight");}
	);
	$(atmosfairs).bind("click", function(){
		var radio = $("input:radio", this);
		$(radio).attr("checked","checked");	
		var row = $(this);
		$(this).parent().find("input[@type=radio]").each(
			function(i)
			{
				if($(this).attr("checked") != true) $(this).parent().parent().removeClass("highlight");
			}
		);
		$(this).addClass("highlight");
		$(this).removeClass("hoverFlight");
		calculatePrice();
	});
	

}

var hotels;
function initHotels(){
	if (isNav){
		document.captureEvents(Event.MOUSEMOVE);
	}
	document.onmousemove = handlerMM;
	tb_init('a.thickbox, area.thickbox, input.thickbox');
	hotels = $('.hotelProduct');
	//$(cars).hide();
	$(hotels).hover(
		function(){$(this).addClass("hoverFlight");},
		function(){$(this).removeClass("hoverFlight");}
	);
	$(hotels).bind("click", function(){
		var radio = $("input:radio", this);
		$(radio).attr("checked","checked");
		highlightFlight($(radio));
		$(this).removeClass("hoverFlight");
		calculatePrice();
		if ($(radio).val() != 0){
			$("#hotelPriceRow").effect("highlight", {}, 300);
		}
		if ($(".minimizeHotel").css("display") != "none" )minimizeCar($(".minimizeHotel"));
			
	});
	
	highlightFlight($("input[@type=radio][@checked]", cars));
	
	log("hotels: " + $(hotels).size());
	first = 1;
	last = $(hotels).size() - 1;
	mid = $(hotels).size() / 2;
	
	/*
	$(hotels).each(function(i){
   	if (i != first && i != last && i != mid && i != 0)$(this).hide();
 	});
 	*/
	$(".maximizeHotel").bind("click", function(){
		maximizeCar($(this));
	});
	
	$(".minimizeHotel").bind("click", function(){
		minimizeCar($(this));
	});
	
	$(".minimizeHotel").toggle();
	
	$("#moreHotels").bind("click", function(){
		maximizeCar($(".maximizeHotel"));
	});
}

function initLeanCheckout() {
	// total = $("#totalPriceArea").metadata().totalPrice
	log("initLeanCheckout");
	$("#depcheck").click(function(){showAddress($(this), 'ibe_checkout_shipping_post_adress');});
	if($("#dep").val() == "false"  ) {
		showAddress($("#dep"), "ibe_checkout_shipping_post_adress");
	} else {
		$('#depcheck').each(function() {
			this.checked = "checked";
		});
	}
	initRadios();
	$("input[@name='deliveryType']").click(function(){
		initRadios();
	});
	var delModeRadio = $("#checkOutForm :input[@name='deliveryType'][@checked]");
	deliveryModeClick($(delModeRadio));
	calculateAdditionalPrices();
	checkDeliveryModes();
	var payTypeRadio = $("#checkOutForm :input[@name='paymentType'][@checked]");
	paymentTypeClick($(payTypeRadio));
	checkTerreDesHommesInput();
	disablePaymentEmail();
}


function checkDeliveryModes() {
	var delivery_country = document.getElementById("checkOutForm").paymentCountry;
	var c = "";	
	for(y=0; y < delivery_country.options.length; y++) {
		if(delivery_country.options[y].selected == true) {
			c = delivery_country.options[y].value;
		}
	}
	var tmp = $("span#country").metadata().countrycode;
	var isPTA = false;
	if(tmp != 'DE') {
		isPTA = true;	
	}
	
	if(document.getElementById("delivery_mode_tod")) {
		document.getElementById("delivery_mode_tod").style.display = 'none';
	}
	if(document.getElementById("delivery_mode_pta")) {
		document.getElementById("delivery_mode_pta").style.display = 'none'; 
	}
	if(document.getElementById("delivery_mode_tod") && !isPTA) {
		document.getElementById("delivery_mode_tod").style.display = 'block';
	}
	if(document.getElementById("delivery_mode_pta") && isPTA) {
		document.getElementById("delivery_mode_pta").style.display = 'block';
	}
	//alert(isPTA); 
}

function stepDone() {
	log("stepDone");
	
	var price = 0;
	var cur = " EUR";
	var tmp = $("span#sumBaggage").metadata().price;
	price = tmp * 1;
	
	if(price > 0) {	
		price = price.toFixed(2);
		price = number_format(price, 2, ",", ".");
		document.getElementById( "baggagePriceArea" ).innerHTML = price + cur;
		document.getElementById( "baggagePriceArea" ).style.display="block";
		document.getElementById( "baggagePriceArea" ).style.display="block";
		
		$("#baggagePriceRow").show();
	}
	
	if(price == 0) {
		$("#baggagePriceRow").hide();
	}
	
	price = 0;
	price = $("span#sumPayment").metadata().price * 1;
	
	if(price > 0) {	
		price = price.toFixed(2);
		price = number_format(price, 2, ",", ".");
		document.getElementById( "paymentPriceArea" ).innerHTML = price + cur;
		document.getElementById( "paymentPriceArea" ).style.display="block";
		document.getElementById( "paymentPriceArea" ).style.display="block";
		
		$( "#paymentPriceRow" ).show();
	}
			
	if(price == 0) {
		$( "#paymentPriceRow" ).hide();
	}
	
}

function initRadios() {
	//$("input[@name='deliveryType']").parent().parent().parent().parent().next().hide();
	$("input[@name='deliveryType']:checked").parent().parent().parent().parent().next().show();
	if($("input[@name='deliveryType']:checked").val() == 1) {
		$("#deliveryEqualsPaymentBox").hide(); $("#dep").val("true"); 
	} else { 
		$("#deliveryEqualsPaymentBox").show(); 
	}
}


function showAddress(clickedElement, id) {
	var address = $("#"+id);
	if($(clickedElement).attr("checked") == true ||  $(clickedElement).val()   ==     "true" ) {
		if ($(clickedElement).val() == "true") $(clickedElement).attr("checked","checked");
		$("#dep").val("true");
		$(address).hide();
	} else {
		$(address).show();
		$("#dep").val("false");
	}
	log("val: " + $(clickedElement).val());
}

function createGoogleMap() {
   try{
		if (GBrowserIsCompatible()) {
			var gmap = new GMap2(document.getElementById("map"));
			if(typeof destination_latlng == 'undefined') {
				$.getJSON(
					encodeURL("autoLocation.groovy"), 
					{ type: "google", like: "${str.destination}"},
					function(json){
						log("dest: " + json.coordinates);
						dst = json.coordinates;
						dstCty = json.city;
						log("json.coordinates[0]" + json.coordinates[0]);
					}
				);
			}
			if(typeof origin_latlng == 'undefined') {
				$.getJSON(
					encodeURL("autoLocation.groovy"), 
					{ type: "google", like: "${str.origin}"},
					function(json){
						log("org: " + json.coordinates);
						org = json.coordinates;
						orgCty = json.city;
					}
				);
			}
	   }
	}
	catch(e) {
		log(e);
	}
	
	if(org[0] != 1000 && dst[0] != 1000 && !mapReady ) {
		try {
			if (GBrowserIsCompatible()) {

				log("org::" + org);
				log("dst::" + dst);
				gmap.addControl(new GSmallMapControl());
				gmap.addControl(new GMapTypeControl());
				var points = [];
				
				var gllorg = new GLatLng(org[1],org[0]);
				var glldst = new GLatLng(dst[1],dst[0]);
				points.push(gllorg);
				points.push(glldst);
				
				points.sort(function(p1, p2) {
				  return p1.lng() - p2.lng();
				});
				
				var bounds = new GLatLngBounds(points[0],  points[1]);
				gmap.setCenter(bounds.getCenter(), gmap.getBoundsZoomLevel(bounds)-1);
				gmap.addOverlay(new GPolyline(points));
				var mkorg = new GMarker(gllorg);
				var mkdst = new GMarker(glldst);
				gmap.addOverlay(mkorg);
				gmap.addOverlay(mkdst);
			}				
		}
		catch(e) {
			log(e);
		}
		mapReady = true;		
	}
}

function deliveryModeClick(radio) {
	var delModeRadio = $("#checkOutForm :input[@name='deliveryType'][@checked]");
	
	processDeliveryPrice();
	if (delModeRadio.val() != 1) {
		$("#etixIdentText").hide();
		$("#etixIdentInput").hide();
	} else {
		$("#etixIdentText").show();
		$("#etixIdentInput").show();
	}
}

function paymentTypeClick(radio) {
	var payModeRadio = $("#checkOutForm :input[@name='paymentType'][@checked]");
	if (payModeRadio.val() == 1) {
		$("#ibe_checkout_payment_cc").show();
		$("#ibe_checkout_payment_invoice").hide();
		$("#ibe_checkout_payment_debit").hide();
		manipulatePaymentCountries("paymentcountry");
		//Birthday
		$("#paymentBirthDate").hide();
		$("#paymentBirthDateText").hide();
	} else if(payModeRadio.val() == 2) {
		$("#ibe_checkout_payment_cc").hide();
		$("#ibe_checkout_payment_invoice").show();
		$("#ibe_checkout_payment_debit").hide();
		//Birthday
		$("#paymentBirthDate").show();
		$("#paymentBirthDateText").show();
		//DeliveryCountries
		manipulatePaymentCountries("paymentcountry_invoice");
		
	} else if(payModeRadio.val() == 3) {
		$("#ibe_checkout_payment_cc").hide();
		$("#ibe_checkout_payment_invoice").hide();
		$("#ibe_checkout_payment_debit").show();
		manipulatePaymentCountries("paymentcountry_elv");
		//Birthday
		$("#paymentBirthDate").show();
		$("#paymentBirthDateText").show();
	} else if(payModeRadio.val() == 4) {
		$("#ibe_checkout_payment_cc").hide();
		$("#ibe_checkout_payment_invoice").hide();
		$("#ibe_checkout_payment_debit").hide();
		manipulatePaymentCountries("paymentcountry");
		//Birthday
		$("#paymentBirthDate").show();
		$("#paymentBirthDateText").show();
	}
}

function manipulatePaymentCountries(name)
{
	var oLength = this.document.orderForm.paymentCountry.options.length;
	var firstOption = this.document.orderForm.paymentCountry.options[0];
	var newOptions = new Array();
	newOptions[0] = firstOption;		
	
	for(i=0;i<=20;i++)
	{
		if(document.getElementById(name + "_" + i ))
		{
			var str = $("span#" + name + "_" + i).metadata().dc;
			var split = str.split("_");
			var newOption = new Option(split[1],split[0],false,false );
			newOptions[i+1] = newOption;
		}
		else break;
		
	}
	
	var l = this.document.orderForm.paymentCountry.options.length;
	
	var selectedCountry;
	for(i=0;i<l;i++)
	{
		var tmpOption = this.document.orderForm.paymentCountry.options[i];
		if(tmpOption.selected) 
		{ 
			selectedCountry = tmpOption.value;
		}
	}
	
	this.document.orderForm.paymentCountry.options.length = 0;
	
	for(i=0;i<newOptions.length;i++)
	{
		this.document.orderForm.paymentCountry.options[i] = newOptions[i];
		if(newOptions[i].value == selectedCountry) this.document.orderForm.paymentCountry.options[i].selected = true;
	}
}

var arVersion = navigator.appVersion.split("MSIE");
var version = parseFloat(arVersion[1]);

function fixPng() {
	if ((version >= 5.5) && (document.body.filters)) {
		for(var i=0; i<document.images.length; i++) {
			var img = document.images[i];
			var imgName = img.src.toUpperCase();
			if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
				if(imgName.indexOf('GOOGLE') != -1 || imgName.indexOf('ICON') != -1 ) continue;
				var imgID = (img.id) ? "id='" + img.id + "' " : "";
				var imgClass = (img.className) ? "class='" + img.className + "' " : "";
				var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
				var imgStyle = "display:inline-block;" + img.style.cssText ;
				if (img.align == "left") imgStyle = "float:left;" + imgStyle;
				if (img.align == "right") imgStyle = "float:right;" + imgStyle;
				if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
				var strNewHTML = "<span " + imgID + imgClass + imgTitle
				+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
				+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
				+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"; 
				img.outerHTML = strNewHTML;
				i = i-1; 
			} 
		} 
	}
}

function submitSearchTripForm(depDay, depMonthYear, retDay, retMonthYear, formNumber)
{
	//alert(document.getElementById("searchForm"));
	document.getElementById("searchForm").departureDay.value = depDay;
	document.getElementById("searchForm").departureMonthYear.value = depMonthYear;
	document.getElementById("searchForm").returnDay.value = retDay;
	document.getElementById("searchForm").returnMonthYear.value = retMonthYear;
	document.getElementById("searchForm").simpleFlexibilityOption.checked = false;
	document.getElementById("searchForm").submit();
}

function calcDay(day, monthYear, field, lang, formNumber){

 var startAt = 1;
 var dayName = {
			en : new Array('Mon','Tue','Wed','Thu','Fri','Sat','Sun'),
			de : new Array('Mo','Di','Mi','Do','Fr','Sa','So'),
			pl : new Array('Mon','Tue','Wed','Thu','Fri','Sat','Sun')
		};
 var mDays = Array (31,0,31,30,31,30,31,31,30,31,30,31);
 if (lang != null && lang != '') language = lang;
 
 if(field == 'departure')
 {
 	dateVal = document.forms["searchTripForm"].departureDay.value;
 	monthYearVal = document.forms["searchTripForm"].departureMonthYear.value;
 	//alert("departure: " + dateVal + " " + monthYearVal);
 }
 else if(field == 'return')
 {
 	dateVal = document.forms["searchTripForm"].returnDay.value;
 	monthYearVal = document.forms["searchTripForm"].returnMonthYear.value;
 	//alert("return: " + dateVal + " " + monthYearVal);
 }
 //alert(" hghg" + monthYearVal.substr(0,2));
 //monthVal = document.forms[frm].elements[nm2].options[document.forms[frm].elements[nm2].selectedIndex].value;
 var isLeapYear = (((monthYearVal.substr(3,6) % 4 == 0) && (monthYearVal.substr(3,6) % 100 != 0)) || (monthYearVal.substr(3,6) % 400 == 0));
 mDays[1] = (isLeapYear)?29:28;
 if(dateVal > mDays[monthYearVal.substr(0,2)-1]){
   if(field=='departure')
   {
  	setDDValue(document.forms["searchTripForm"].departureDay,mDays[monthYearVal.substr(0,2)-1]);
  	dateVal = document.forms["searchTripForm"].departureDay.value;
   }
   else if (field == 'return')
   {
   	setDDValue(document.forms["searchTripForm"].returnDay,mDays[monthYearVal.substr(0,2)-1]);
  	dateVal = document.forms["searchTripForm"].returnDay.value;
   }
  }
 newDate = new Date(monthYearVal.substr(3,6)+"/"+monthYearVal.substr(0,2)+"/"+dateVal);
 //alert("newDate " + newDate.getDay());
 if(field=='departure')
 {
 	dayIndex = newDate.getDay();
 	//alert("index: " + monthIndex);
 	if(dayIndex == 0 && startAt == 1)
 		dayIndex = 7;
 	if(dayIndex > 0 && startAt == 1)
 		dayIndex = dayIndex - 1; 
 	//document.forms["searchTripForm"].departureDayOfWeek.value = dayName[language][dayIndex];
 	
 	// calendar setzen
 	var dateStr = newDate.getDate() + "";
 	if(dateStr.length == 1)
 		dateStr = "0" + dateStr;
 	var monthStr = (newDate.getMonth()+1)  +"";
 	if(monthStr.length == 1)
 		monthStr = "0" + monthStr;
 	var yearStr = newDate.getFullYear();
 	var str = dateStr + monthStr + "-" + yearStr;
 	//alert(str);
 	if(document.forms["searchTripForm"].departure_f_date_d != null)
 	 	document.forms["searchTripForm"].departure_f_date_d.value = str;
 }
 else if (field=='return')
 {
 	var dayIndex = newDate.getDay();
 	//alert("index: " + monthIndex);
 	if(dayIndex == 0 && startAt == 1)
 		dayIndex = 7;
 	if(dayIndex > 0 && startAt == 1)
 		dayIndex = dayIndex - 1; 
 	//document.forms["searchTripForm"].returnDayOfWeek.value = dayName[language][dayIndex];
 	
 	// calendar setzen
 	var dateStr = newDate.getDate() + "";
 	if(dateStr.length == 1)
 		dateStr = "0" + dateStr;
 	var monthStr = (newDate.getMonth()+1) +"";
 	if(monthStr.length == 1)
 		monthStr = "0" + monthStr;
 	var yearStr = newDate.getFullYear();
 	var str = dateStr + monthStr + "-" + yearStr;
 	//alert(document.forms["searchTripForm"].return_f_date_d);
 	if(document.forms["searchTripForm"].return_f_date_d != null)
 		document.forms["searchTripForm"].return_f_date_d.value = str;
 }
 }
 
  function setDDValue(oDropDown, sValue){
 for(var iIndex=0; iIndex<oDropDown.options.length; ++iIndex){
  if(oDropDown.options[iIndex].value == sValue){
   oDropDown.selectedIndex = iIndex;
   break;
   }
  }
 }
 
 function copyNameFields()
 {
   document.getElementById("paymentFirstName").onchange = function() { this._changed = true; };
   document.getElementById("ccFirstName").onchange = function() { this._changed = true; };
   
   document.getElementById("travellersFirstName0").onkeyup = function() 
   { 
	   var e = document.getElementById("paymentFirstName"); 
	   var f = document.getElementById("ccFirstName"); 
   
	   if(!e._changed) 
	   { 
		   e.value = document.getElementById("travellersFirstName0").value;
	   } 
	   if(!f._changed) 
	   { 
		   f.value = document.getElementById("travellersFirstName0").value;
	   }
   }; 
   
   document.getElementById("paymentLastName").onchange = function() { this._changed = true; };
   document.getElementById("ccLastName").onchange = function() { this._changed = true; };
   document.getElementById("travellersLastName0").onkeyup = function() 
   { 
	   var e = document.getElementById("paymentLastName"); 
	   var f = document.getElementById("ccLastName"); 
	   
	   if(!e._changed) { 
		   e.value = document.getElementById("travellersLastName0").value;
	   } 
	   if(!f._changed) { 
		   f.value = document.getElementById("travellersLastName0").value;
	   } 
   }; 
   
   //birthday
   document.getElementById("travellersBirthDay0").onchange = function() { var e = document.getElementById("paymentBirthDay") ;
   if(!e._changed) { e.value = document.getElementById("travellersBirthDay0").value;} }; 
   document.getElementById("travellersBirthMonth0").onchange = function() { var e = document.getElementById("paymentBirthMonth") ;
   if(!e._changed) { e.value = document.getElementById("travellersBirthMonth0").value;} }; 
   document.getElementById("travellersBirthYear0").onchange = function() { var e = document.getElementById("paymentBirthYear") ;
   if(!e._changed) { e.value = document.getElementById("travellersBirthYear0").value;} }; 
 }


function debugMe(obj)
{
	console.log("debug: " + obj);
}

function initAuto()
{
	$io = $("#input_origin");
	$id = $("#input_destination");
	$io2 = $("#input_origin2");
	$id2 = $("#input_destination2");

	$io.autocomplete(
			'autoLocation.groovy?type=array',
			{
				minChars: 30,
				max: 30,
				width: 200
			}
	);
	$id.autocomplete(
			'autoLocation.groovy?type=array',
			{
				minChars: 30,
				max: 30,
				width: 200
			}
	);
	$io2.autocomplete(
			'autoLocation.groovy?type=array',
			{
				minChars: 30,
				max: 30,
				width: 200
			}
	);
	$id2.autocomplete(
			'autoLocation.groovy?type=array',
			{
				minChars: 30,
				max: 30,
				width: 200
			}
	);
	
	$io.bind("change", function(e){ 
		window.setTimeout( "validateField('input_origin', true)", 500);
	});
	$io2.bind("change", function(e){ 
		window.setTimeout( "validateField('input_origin2', true)", 500);
	});
	$id.bind("change", function(e){ 
		window.setTimeout( "validateField('input_destination', true)", 500);
	});
	$id2.bind("change", function(e){ 
		window.setTimeout( "validateField('input_destination2', true)", 500);
	});
}


function validateField( fieldname, isAsync)
{
	var forceac = true;
	
	var isValid = false;
	var field = $("#" + fieldname);
	
	log( "ac visble: " + $('.ac_results').is(':visible') + " for field: " + fieldname);
	
	if(field.val().length < 33 && field.val().length > 32	) 
	{
		log("input < 33");
		isValid = false;
		$(field).addClass('locationError');
		return isValid;
	}
		
	
	if( true  )
	{
		var location = field.fieldValue(); 
		log("validatingLocation for " + fieldname + ": " + location);
		 
		if(field.val().length >= 33)
		{
			log("start validating for: " + location);
			$.ajax({
			  type: "POST",
			  url: encodeURL("validateLocation.groovy"),
			  dataType: "json",
			  data: "location=" + location,
			  async: isAsync,
			  success: function(json){
					log("JSON: " + json);
				
					 if( json.isvalid == 'false'   )
				     {		
				     		log("json.isvalid == 'false'");
				     		$(field).addClass('locationError');
				     		isValid = false;
				     }
				  /*   else if( json.isvalid == 'false' && json.issuggestion == 'true' && forceac  )
				     {
				     		log("json.isvalid == 'false' && json.issuggestion == 'true' && forceac");
				     		
				     		$(field).click();
				     		$(field).focus();
				     		$(field).click();
				     		$(field).focus();
				     		
				     		//$(field).addClass('locationError');
				     		isValid = false;
				     		
				     } */
				     else
				     {
				     		log("JSON isValid: " +  json.isvalid);
				     		field.removeClass('locationError');
				     		field.val(json.location);
				     		isValid = true;
				     }
				 }
			});
			 
		}
		if(field.val().length == 0) 
		{
			field.removeClass('locationError');
			isValid = true;
		}
	}
	
	try{
		$(field).bgiframe();
	}catch (e){
		;
	}
	
	return isValid; 
}



function resetField(field)
{
	log("resetField: " + field.name)
	$(field).removeClass('locationError');
	log("try to get focus: " + field.name)
	$(field).select();
	$(field).focus();
}

function checkLength( fieldname )
{
	var field = $("#" + fieldname);
	
	log(" ..checkLength: " + $(field).val().length );
	
	if($(field).val().length < 2)
	{
		return false;
	}
	else
	{
		return true;
	}
	
}

function setError(fieldname)
{
	var field = $("#" + fieldname);
	$(field).addClass('locationError');
}

function validateAndSubmit()
{
	log( "validateAndSubmit start ....");
	var isValid = true;
	
	isValid = isValid && validateField('input_origin', false) && checkLength('input_origin');
	if( checkLength('input_origin') == false ) setError('input_origin');
	
	isValid = isValid && validateField('input_destination', false) && checkLength('input_destination');
	if( checkLength('input_destination') == false ) setError('input_destination');
	
	if($('#tripType').attr('value') == 'SOJ' )
	{
		log("SOJ");
		isValid = isValid && validateField('input_origin2', false) && checkLength('input_origin2');
		if( checkLength('input_origin2') == false ) setError('input_origin2');
		
		isValid = isValid && validateField('input_destination2', false) && checkLength('input_destination2');
		if( checkLength('input_destination2') == false ) setError('input_destination2');
		
	}
	log("validateAndSubmit: " + isValid);
	if( isValid )
	{ 
		$("#submitbutton").addClass('SubmitButtonSearching');
		document.searchTripForm.submit();
	}
	log( "validateAndSubmit end ....");
	
}

function checkTerreDesHommesInput()
{
	var check = $("#checkOutForm :input[@name='terreDesHommes']");
	if ( check[0].checked ) {
		$("#checkOutForm :input[@name='terreDesHommesPrice']").removeAttr("disabled");
	}
	else $("#checkOutForm :input[@name='terreDesHommesPrice']").attr("disabled", true); 
}

function disablePaymentEmail()
{
	if(! $("#checkOutForm :input[@name='paymentEmail2']"))return;
	else
	{
		$("#checkOutForm :input[@name='paymentEmail']").attr("autocomplete", "off");
		$("#checkOutForm :input[@name='paymentEmail']").attr("onpaste", "return false;");
		$("#checkOutForm :input[@name='paymentEmail2']").attr("autocomplete", "off");
		$("#checkOutForm :input[@name='paymentEmail2']").attr("onpaste", "return false;");
	}	
}

