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();
				var styleHeight = $( "#ibe_searchbox" ).find( "div.ibe_box_bottom_right" ).attr("style");
				
				if( typeof styleHeight != "undefined" && styleHeight.length > 0 )
					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: 4,
			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: 4,
			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: 4,
			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: 4,
			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 paymentFee = $(this).parent().find("div.routeprice").metadata().pf;
				
				if(paymentFee > 0) sum = parseFloat(sum) + parseFloat(paymentFee);
				
			}
	);
	var container = $(radio).parents("div.ibe_singlecontainer");
	var tp = $("span.totalPrice", $(container));
	var currency = $("input[name='fpiCurrency']", $(container))[0].value;
	$(tp).empty();
	$(tp).append(kaufm(sum));
	if(sum > 0 && highlight)
	{
		log("highlight start");
		$("div.ibe_singlecontainer_head").toggleClass(" ibe_singlecontainer_head_hl", true);
		$("div.ibe_singlecontainer_head", $(container)).eq(0).effect("highlight", {}, 2000);
		setTimeout(removeClass, 2000);
	}
	$(tp).append("&nbsp;" + currency );
	$(tp).wrap("<b></b>");
	
}

function removeClass()
{
	$("div.ibe_singlecontainer_head").removeClass("ibe_singlecontainer_head_hl");
	
	return false;
}

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);
	log("maxAirlines: " + maxAirlines);
	
	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 initAirlineMatrix() {
	
	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));
	});

}


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;
	}
	if(what == 'fpilAirlineInfo.groovy')  {
		if(! airlinesLoaded  ) {
			initAirlines();
		}
		airlinesLoaded = true;
	}
	if(what == 'fpilAirlineInfo.jsp')  {
		initAirlineMatrix();
	}
}

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();
	
	$(cars).each( function(i) {
	   	if (i > 3 && $(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 railAndFlyPrice = 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.orderForm.priceFlight)
		log("noFlightPrice");
	
	if(document.orderForm.priceFlight) {
		flightPrice = document.orderForm.priceFlight.value * 1;
		log("flightPrice: " + flightPrice);
	}

	if(document.orderForm.carId) {
		for(i=0; i < document.orderForm.carId.length; i++) {
			if (document.orderForm.carId[i].checked) {
				carPrice = document.orderForm.carprice[i].value * 1;
				carDiscount = document.orderForm.carpriceDiscount[i].value * 1;
				carPrice = carPrice + carDiscount;
			}
		}
	}
	
	if(document.orderForm.hotelId) {
		for(i=0; i < document.orderForm.hotelId.length; i++) {
			if (document.orderForm.hotelId[i].checked == true) {
				hotelPrice = document.orderForm.hotelprice[i].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( document.orderForm.railAndFlyId ) {
		for( i = 0; i < document.orderForm.railAndFlyId.length; i++ )
		{
			if ( document.orderForm.railAndFlyId[i].checked )
				railAndFlyPrice = document.orderForm.railAndFlyPrice[i].value * 1;
		}
	}
	
	totalPrice = totalPrice + flightPrice;
	log("totalPrice: " + totalPrice);
	var out;
	
	var cform = document.orderForm;
	
	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(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( railAndFlyPrice > 0 )
	{
		if( document.getElementById( "ibe_bigprice" ) )
		{
			var tempPrice = ( document.orderForm.priceFlight.value * 1 ) + railAndFlyPrice;
			tempPrice = tempPrice.toFixed(2);
			tempPrice = number_format(tempPrice, 2, ",", ".");
			document.getElementById( "ibe_bigprice" ).innerHTML = tempPrice + cur;
		}
		
		railAndFlyPrice = railAndFlyPrice.toFixed( 2 );
		totalPrice += railAndFlyPrice * 1;
		railAndFlyPrice = number_format( railAndFlyPrice, 2, ",", "." );
		
		try{
			document.getElementById( "railAndFlyPriceArea" ).innerHTML = railAndFlyPrice + cur;
			$( "#railAndFlyPriceRow" ).show();
			
			document.getElementById( "paymentRailAndFlyPriceArea" ).innerHTML = railAndFlyPrice + cur;
			$( "#paymentRailAndFlyPriceRow" ).show();
		}catch(e){
			;
		}
	}
	
	if( railAndFlyPrice == 0 ) {
		$( "#railAndFlyPriceRow" ).hide();
		$( "#paymentRailAndFlyPriceRow" ).hide();
		
		if( document.getElementById( "ibe_bigprice" ) )
		{
			var tempPrice = ( document.orderForm.priceFlight.value * 1 ) - railAndFlyPrice;
			tempPrice = tempPrice.toFixed(2);
			tempPrice = number_format(tempPrice, 2, ",", ".");
			document.getElementById( "ibe_bigprice" ).innerHTML = tempPrice + cur;
		}
	}
	
	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 calculatePriceForlist() {
	log( "calculatePriceForList... " );
	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.carForm.priceFlight) {
		flightPrice = (document.carForm.priceFlight.value * 1) + 0;
		//alert("der alte flightprice " + flightPrice);
		log("flightPrice: " + flightPrice);
	}

	if(document.carForm.carId) {
		for(i=0; i < document.carForm.carId.length; i++) {
			if (document.carForm.carId[i].checked) {
				carPrice = document.carForm.carprice[i].value * 1;
				carDiscount = document.carForm.carpriceDiscount[i].value * 1;
				carPrice = carPrice + carDiscount;
				//alert("der alte carprice " + carPrice);
			}
		}
	}
	
	totalPrice = totalPrice + flightPrice;
	//alert("der alte total " + totalPrice);
	log("totalPrice: " + totalPrice);
	var out;
	
	if(document.carForm.childCount) {
		childCount = document.carForm.childCount.value * 1;
	}
	if(document.carForm.infantCount) {
		infantCount = document.carForm.infantCount.value * 1;
	}
	if(document.carForm.adultCount) {
		adultCount = document.carForm.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();
	}
	
	$( "#hotelPriceRow" ).hide();
     
	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, ",", ".");
	var currency = $("#calculatedTotalPriceInclFee").metadata().currency;
	document.getElementById( "baggagePriceArea" ).innerHTML = out + "&nbsp;" + currency;
	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; 
	
	var paymentTypeClicked = $("input[@id='paymentType']:checked").val();
	if( !paymentTypeClicked )
	{
		paymentTypeClicked= $('#paymentType').val();
	}
	var sumPaymentFee = $("span#cctype_DEFAULT").metadata().price * 1;
	
	if(paymentTypeClicked == '1') // CreditCard
	{
		try{
			var ccType = document.getElementById("checkOutForm").ccType.value;
			selPrice = $("span#cctype_" + ccType).metadata().price * 1;
		} catch (e) {
			// selPrice = 0;
			selPrice = $("span#cctype_DEFAULT").metadata().price * 1;
		}
	}
	else if( paymentTypeClicked == '2' ) // Invoice
	{
		selPrice = $("span#invoicePaymentPrice").metadata().price * 1;
	}
	else if( paymentTypeClicked == '5' ) // DirectDebit
	{
		selPrice = $("span#directDebitPaymentPrice").metadata().price * 1;
	}
	else
	{
		selPrice = $("span#paymentfee_DEFAULT").metadata().price * 1;
	}
	
	// fix double ccFee
	if( paymentTypeClicked == '1' ) // CreditCard
	{
		$("#paymentFeePriceRow").hide();
		showPaymentPrice( selPrice, "paymentPriceArea", "paymentPriceRow" );
	}
	else if( paymentTypeClicked == '2' || paymentTypeClicked == '5' ) // Invoice,
																		// DirectDebit
	{
		$("#paymentPriceRow").hide();
		showPaymentPrice( selPrice, "paymentFeePriceArea", "paymentFeePriceRow" );
	}
	
	return selPrice;  
}

function showPaymentPrice( price, area, row )
{
	var outPrice = price.toFixed( 2 );
	var out = number_format( outPrice, 2, ",", "." );
	var currency = $("#calculatedTotalPriceInclFee").metadata().currency;
	
	document.getElementById( area ).innerHTML = out + "&nbsp;" + currency;
	document.getElementById( area ).style.display = "block";
	document.getElementById( area ).style.display = "block";
	
	if ( price <= 0 )
		$( "#" + row ).hide();
	else
		$( "#" + row ).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;
}

// SpecialOffer
function processSpecialOfferPrice() {

	var selPrice = 0;
	try {
		var ids = $("#checkOutForm :input[@class='ibe_special_offer_checkbox']");
		if( ids && ids.length > 0 )
		{
			for( i=0; i<ids.length; i++ )
			{
				var id = $(ids[i]).attr('id');
				
				if( $(ids[i]).is( ':checked') )
				{
					var name= $("span#" + id + "_info").metadata().name;
					var price= $("span#" + id + "_info").metadata().price * 1;
					var unit = $("span#" + id + "_info").metadata().unit;
					var person = $("span#" + id + "_info").metadata().person;
					var personLabel = $("#personLabel").text();
					selPrice += showSpecialOfferPrice(id, name, price, unit, person, personLabel );
				}
				else
				{
					showSpecialOfferPrice(id, 0, 0, 0, 0, 0 );
				}
			}
		}
	} catch (e) 
	{
		selPrice = 0;
	}

	return selPrice;
}

function showSpecialOfferPrice(id, name, price, unit, person, personLabel ) {
	
	var productPrice = "&nbsp;";
	var personCount = "&nbsp;";
	var currency = $("#calculatedTotalPriceInclFee").metadata().currency;
	
	if( unit == 2 )
	{
		productPrice = price.toFixed(2);
		productPrice = number_format(productPrice, 2, ",", ".") + "&nbsp;" + currency;
		price = price * person;
		personCount = personLabel;
	}
	
	var outPrice = price.toFixed(2);
	outPrice = number_format(outPrice, 2, ",", ".") + "&nbsp;" + currency;
	
	$('#' + id + "_Row").remove();
	
	var html = '<tr id="' + id +'_Row">';
		html += '<td><span id="">' + name + '</span></td>';
		html += '<td class="align_right border_left">' + productPrice + '</td>';
		html += '<td class="align_right border_left">' + personCount + '</td>';
		html += '<td class="align_right border_left"><span id="' + id + '_totalPrice">' + outPrice + '</span></td>';
		html += '</tr>';

	if( price > 0 )
	{
		$('#orderBillTable tr:last').after( html );
		return price;
	}
	
	return 0;
}



function showDeliveryPrice(price) {
	var outPrice = price.toFixed(2);
	var out = number_format(outPrice, 2, ",", ".");
	var currency = $("#calculatedTotalPriceInclFee").metadata().currency;
	$("#deliveryPriceArea").empty();
	$("#deliveryPriceArea").prepend(out + "&nbsp;" + currency);
	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.getElementById("checkOutForm").childCount) {
		childCount = document.getElementById("checkOutForm").childCount.value * 1;
	}
	if(document.getElementById("checkOutForm").infantCount) {
		infantCount = document.getElementById("checkOutForm").infantCount.value * 1;
	}
	if(document.getElementById("checkOutForm").adultCount) {
		adultCount = document.getElementById("checkOutForm").adultCount.value * 1;
	}
	
	if(document.getElementById("checkOutForm").atmosfairPrice) { 
		for(i=0; i < document.getElementById("checkOutForm").atmosfairPrice.length; i++) { 
			if (document.getElementById("checkOutForm").atmosfairPrice[i].checked == true) { 
				atmosfairPrice = document.getElementById("checkOutForm").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]");
		
		if( !radio.val() )
		{
			radio = $("#checkOutForm :input[@name='hmrv'][@checked]");
		}
		
		if( !radio.val() )
		{
			radio = $("#checkOutForm :input[@name='iiip'][@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;" + $("#calculatedTotalPriceInclFee").metadata().currency );
	
	
	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; 
		
		if( !(parseInt( selPrice ) >= 0 ) )
		{
			selPrice = 0;
		}
	} 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;
	
	try { 
		var radioIns = $("#checkOutForm :input[@name='iiip'][@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;
	var specialOfferPrice = 0;
	var railAndFlyPrice = 0;

	// serverside given
	try {
		total = $("#calculatedTotalPriceInclFee").metadata().price * 1; 
	} catch (e) {
		total = 0; 
	}
	try {
		carPrice = $("#carPriceSelected").metadata().price * 1; 
	} catch (e) {
		carPrice = 0; 
	}
	try {
		railAndFlyPrice = $("#railAndFlyPriceSelected").metadata().price * 1; 
	} catch (e) {
		railAndFlyPrice = 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;  
	}
	
	try{
		specialOfferPrice = processSpecialOfferPrice();
		log("specialOffer price: " + specialOfferPrice );
	} catch (e) {
		specialOfferPrice = 0;  
	}
	

    $("#totalPriceArea").empty();
	total = total + carPrice + railAndFlyPrice + baggagePrice + insurancePrice + paymentPrice + terreDesHommesPrice + deliveryPrice + atmosfairPrice + ticketSafePrice + specialOfferPrice;
	total = total.toFixed(2);
	
	if( $("#creditVoucherPriceSelected").metadata().flag )
		total = total - $("#creditVoucherPriceSelected").metadata().price;
	
	total = number_format(total, 2, ",", ".");
	$("#totalPriceArea").prepend(total + "&nbsp;" + $("#calculatedTotalPriceInclFee").metadata().currency );
}

var cars;
function initCars( bindClick ){
	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");}
	);
	
	if( bindClick )
	$(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());

	$(cars).each(function(i){
		if (i > 3 && i != 0)$(this).hide();
	});
 	
	$(".maximizeCar").bind("click", function(){
		maximizeCar($(this));
	});
	
	$(".minimizeCar").bind("click", function(){
		minimizeCar($(this));
	});
	
	$(".minimizeCar").toggle();
	
	$("#moreCars").bind("click", function(){
		maximizeCar($(".maximizeCar"));
	});
	
}

function preselectCarForListView()
{
	$('input:radio[name="carId"]').filter('[value="0"]').attr('checked', true);
}

function sendCarIdValue( input )
{
	var val =  $("#carForm :input[@name='carId'][@checked]").val();
	
	$("#form-0 :input[@name='carId']").val( val ); 
	
	calculatePriceForlist();
}

function submitFlightForm()
{
	document.getElementById('form-0').submit();
}

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]");
	if( ! payTypeRadio.val() ) payTypeRadio = $("#checkOutForm :input[@name='paymentType']");
	paymentTypeClick($(payTypeRadio));
	checkTerreDesHommesInput();
	disablePaymentEmail();
	voucherClick();
}

function voucherClick()
{
	var checked = $('#voucherCheckbox').attr('checked');
	
	if( checked )
	{
		$('#ibe_checkout_payment_voucher').show();
	}
	else
	{
		$('#ibe_checkout_payment_voucher').hide();
	}
}




function checkDeliveryModes() {
	
	var delivery_country = document.getElementById("checkOutForm").paymentCountry;
	// alert( if(delivery_country.options) );
	if( delivery_country.options )
	{
		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 = " " + $("#calculatedTotalPriceInclFee").metadata().currency;
	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();
	}
	
	tmp = $("span#additionalBaggagePriceSelected").metadata();
	
	if( price == 0 && ( !tmp.flag && tmp.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) {
	try
	{
		var payModeRadio = $("#checkOutForm :input[@name='paymentType'][@checked]");
		if( !payModeRadio.val() ) payModeRadio = $("#checkOutForm :input[@name='paymentType']");
		
		if (payModeRadio.val() == 1) {
			$("#ibe_checkout_payment_cc").show();
			$("#ibe_checkout_payment_invoice").hide();
			$("#ibe_checkout_payment_debit").hide();
			$("#ibe_checkout_payment_direct_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();
			$("#ibe_checkout_payment_direct_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();
			$("#ibe_checkout_payment_direct_debit").hide();
			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();
			$("#ibe_checkout_payment_direct_debit").hide();
			manipulatePaymentCountries("paymentcountry");
			// Birthday
			$("#paymentBirthDate").show();
			$("#paymentBirthDateText").show();
		} else if(payModeRadio.val() == 5) {
			$("#ibe_checkout_payment_cc").hide();
			$("#ibe_checkout_payment_invoice").hide();
			$("#ibe_checkout_payment_debit").hide();
			$("#ibe_checkout_payment_direct_debit").show();
			manipulatePaymentCountries("paymentcountry_directDebit");
			// Birthday
			$("#paymentBirthDate").show();
			$("#paymentBirthDateText").show();
		}
		
		calculateAdditionalPrices();
	} catch (e) { log(e); }
}

jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ? 
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

function manipulatePaymentCountries(name)
{
	var oLength = this.document.getElementById("checkOutForm").paymentCountry.options.length;
	var firstOption = this.document.getElementById("checkOutForm").paymentCountry.options[0];
	var newOptions = new Array();
	newOptions[0] = firstOption;		
	
	var spanLength = $('span:regex(id, ' + name +'_\\d)').length;
	for(i=0;i<spanLength;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.getElementById("checkOutForm").paymentCountry.options.length;
	
	var selectedCountry;
	for(i=0;i<l;i++)
	{
		var tmpOption = this.document.getElementById("checkOutForm").paymentCountry.options[i];
		if(tmpOption.selected) 
		{ 
			selectedCountry = tmpOption.value;
		}
	}
	
	this.document.getElementById("checkOutForm").paymentCountry.options.length = 0;
	
	for(i=0;i<newOptions.length;i++)
	{
		this.document.getElementById("checkOutForm").paymentCountry.options[i] = newOptions[i];
		if(newOptions[i].value == selectedCountry) this.document.getElementById("checkOutForm").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( withBirthday )
{
	// nothing to copy
	if( document.getElementById("ccFirstName") == null ) return;	 
	 
	document.getElementById("paymentFirstName").onchange = function() { this._changed = true; };
	document.getElementById("ccFirstName").onchange = function() { this._changed = true; };
	
	if( document.getElementById("elvFirstName") != null )
		document.getElementById("elvFirstName").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;
		}
		
		if( document.getElementById("elvFirstName") != null )
		{
			var l = document.getElementById("elvFirstName");
			if(!l._changed) 
			{ 
				l.value = document.getElementById("travellersFirstName0").value;
			}
		}
		
	};
   
	document.getElementById("paymentLastName").onchange = function() { this._changed = true; };

	if( document.getElementById("ccLastName") != null )
		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;
		}
		
		if( document.getElementById("elvLastName") != null )
		{
			var l = document.getElementById("elvLastName"); 
			if(!l._changed) { 
				l.value = document.getElementById("travellersLastName0").value;
			}
		}
	};
   
	$("select[@name=paymentTitle]")[0].onchange = function() {
		this._changed = true;
	};
	
	$("select[@name=travellersGender]")[0].onchange = function()
	{
		var paymentTitle = $("select[@name=paymentTitle]")[0];
		
		if( !paymentTitle._changed )
		{
			var selectedValue = parseInt( $("select[@name=travellersGender]")[0].value );
			
			if( parseInt( selectedValue ) > 2 )
				selectedValue = ( selectedValue % 2 ) + 1;
			
			for( var index = 0; index < $("select[@name=travellersGender]")[0].length; index++ )
			{
				var newIndex = index % ( $("select[@name=paymentTitle]")[0].length );
				
				if( parseInt( paymentTitle[newIndex].value ) == selectedValue )
					paymentTitle.selectedIndex = newIndex;
			}
		}
	}
   
   // birthday
	if( withBirthday == 'false' )
	{	
	   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: 3,
				max: 30,
				width: 200
			}
	);
	$id.autocomplete(
			'autoLocation.groovy?type=array',
			{
				minChars: 3,
				max: 30,
				width: 200
			}
	);
	$io2.autocomplete(
			'autoLocation.groovy?type=array',
			{
				minChars: 3,
				max: 30,
				width: 200
			}
	);
	$id2.autocomplete(
			'autoLocation.groovy?type=array',
			{
				minChars: 3,
				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 < 3 && field.val().length > 0	) 
	{
		log("input < 3");
		isValid = false;
		$(field).addClass('locationError');
		return isValid;
	}
		
	
	if( true  )
	{
		var location = field.fieldValue(); 
		log("validatingLocation for " + fieldname + ": " + location);
		 
		if(field.val().length >= 3)
		{
			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.length > 0 && check != null && 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']").bind( "paste", function(){ return false; } );
		$("#checkOutForm :input[@name='paymentEmail2']").attr("autocomplete", "off");
		$("#checkOutForm :input[@name='paymentEmail2']").bind( "paste", function(){ return false; } );
	}	
}

function toggleElement( id )
{
	$('#' + id ).toggle();
	
	try
	{
		var txt = $('#readMoreLink').metadata().open;
	
		if( $('#' + id).is(':hidden') )
		{
			txt = $('#readMoreLink').metadata().close;	
		}
				
		$('#' + id + '_readMore').html( txt );
	}
	catch (e)
	{
		;
	}
}

function showCouponAgb( params )
{
	var link = '/engine/showCouponAgb.do';
 	var voucher = $('#voucherCode').val();
 	if( !voucher || voucher == '' )
 		voucher = 'na';
 	
 	link = link + '?voucher=' + voucher;
 	
 	if( params && params.length > 0 )
 	{
 		link += '&' + params;
 	}

	var t = null;
	var a = link;
	var g = false;
	
	// thickbox
	tb_show(t,a,g);
}

function showProductPlacementInfo( link, params, id )
{
 	if( !id || id == "" || !link || link == "" | !params || params == "" )
 		return false;
 	
 	link = link + "_" + id + ".html";
 	
 	if( params && params.length > 0 )
 		link += '?' + params;

	var t = null;
	var a = link;
	var g = false;
	
	// Thickbox
	tb_show( t, a, g );
}

