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: 50,
			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: 50,
			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: 50,
			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: 50,
			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();
}

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 initAuto()
{
	$io = $("#input_origin");
	$id = $("#input_destination");
	$io2 = $("#input_origin2");
	$id2 = $("#input_destination2");

	$io.autocomplete(
			'autoLocation.groovy?type=array',
			{
				minChars: 50,
				max: 50,
				width: 200
			}
	);
	$id.autocomplete(
			'autoLocation.groovy?type=array',
			{
				minChars: 50,
				max: 50,
				width: 200
			}
	);
	$io2.autocomplete(
			'autoLocation.groovy?type=array',
			{
				minChars: 50,
				max: 50,
				width: 200
			}
	);
	$id2.autocomplete(
			'autoLocation.groovy?type=array',
			{
				minChars: 50,
				max: 50,
				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 ....");
	
}

