	var dataLoaded = false;
	var forceSearch = false;
       var clickEnter = false;
       var dateNotValidStart = 0;
	var dateNotValidEnd = 0;

function checkOrt (Ereignis) {

clickEnter = false;

  if (!Ereignis)
    Ereignis = window.event;
  if (Ereignis.which) {
    Tastencode = Ereignis.which;
  } else if (Ereignis.keyCode) {
    Tastencode = Ereignis.keyCode;
  }

  if (Tastencode == 13) {

    if (document.getElementById('dropDownLine1') == null) {
      clickEnter = false;

    } else {
	 clickEnter = true;
        document.getElementById('dropDownLine1').onclick();
    } 
  }
}

		//iphone-popup wenn es ein iphone ist
			var gespeichert="";
			if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1)) {  
				if (document.cookie) {
					gespeichert = document.cookie;
				} else {
					gespeicher="";
				}
				if (gespeichert.indexOf('phonehinweis')>0){
				}else{
					var a = new Date();
					a = new Date(a.getTime() +1000*60*60*24*30);
					gespeichert = 'iphonehinweis=1; expires='+a.toGMTString()+';'; 
					document.cookie = gespeichert;
					if (confirm("M�chten Sie die kostenlose iPhone-App zur Mietwagensuche aus dem Appstore laden?")) document.location = "http://itunes.apple.com/de/app/mietwagen-preisvergleich/id368717956?mt=8";  
				}
			}
		// ende iphone umleitung

    var ajaxCall;
    var oldValue='';
    var searchLayerId;

	$(document).ready(function () {
	
		// keine default belegung
		$('#pucity').val(''); 
		$('#pucountry').val('');
		
		$('#endPlaceSearch').val('');
		$('#docity').val('');
		$('#docountry').val('');

		// dialog setup
		$("#errorDialog").dialog({
			modal: true,
			autoOpen: false,
			buttons: {
				'Abbrechen': function() 
				{	
					$(this).dialog('close');
				}
			}
		});

		$("#errorPlaceDialog").dialog({
			modal: true,
			autoOpen: false,
			buttons: {
				'Abbrechen': function() 
				{	
					$(this).dialog('close');
				}
			}
		});				
		
		$("#errorTimeDialog").dialog({
			modal: true,
			autoOpen: false,
			buttons: {
				'Abbrechen': function() 
				{	
					$(this).dialog('close');
				}
			}
		});

		$("#errorMobilDialog").dialog({
			modal: true,
			autoOpen: false,
			buttons: {
				'Abbrechen': function() 
				{	
					$(this).dialog('close');
				}
			}
		});

		$("#confirm24Dialog").dialog({
			modal: true,
			autoOpen: false,
			buttons: {
				'Suche fortsetzen': function() 
				{
					forceSearch = true;
					$(this).dialog('close');
					$('#mietwagenSearchForm').submit();
				},
				'Abbrechen': function() 
				{
					forceSearch = false;
					$(this).dialog('close');
				}
			}
		});
		
		$("#confirmFutureDialog").dialog({
			width: 600,
			modal: true,
			autoOpen: false,
			buttons: {
				'Suche fortsetzen': function() 
				{
					forceSearch = true;
					$(this).dialog('close');
					$('#mietwagenSearchForm').submit();
				},
				'Abbrechen': function() 
				{
					forceSearch = false;
					$(this).dialog('close');
				}
			}
		});
		
		
		$("#confirmDoDialog").dialog({
			modal: true,
			autoOpen: false,
			buttons: {
				'Suche fortsetzen': function() 
				{
					forceSearch = true;
					$(this).dialog('close');
					$('#mietwagenSearchForm').submit();
				},
				'Abbrechen': function() 
				{
					forceSearch = false;
					$(this).dialog('close');
				}
			}						
		});
		

		$("#confirmDoCountryDialog").dialog({
			modal: true,
			autoOpen: false,
			buttons: {
				'OK': function() 
				{
					forceSearch = false;
					$(this).dialog('close');
				}
			}						
		});

		$("#errorStartDate").dialog({
			modal: true,
			autoOpen: false,
			buttons: {
				'OK': function() 
				{
					forceSearch = false;
					$(this).dialog('close');
				}
			}						
		});
		
		$("#errorEndDate").dialog({
			modal: true,
			autoOpen: false,
			buttons: {
				'OK': function() 
				{
					forceSearch = false;
					$(this).dialog('close');
				}
			}						
		});
		
		$("#errorAnmietDate").dialog({
			modal: true,
			autoOpen: false,
			buttons: {
				'OK': function() 
				{
					forceSearch = false;
					$(this).dialog('close');
				}
			}						
		});

		$("#errorAbgabeDate").dialog({
			modal: true,
			autoOpen: false,
			buttons: {
				'OK': function() 
				{
					forceSearch = false;
					$(this).dialog('close');
				}
			}						
		});

		$("#startDatepicker").datepicker({
			minDate: 0,
			showOn: 'both', 
			buttonImageOnly: true,
			maxDate: getMaxDate(),
			buttonImage: '/js/jquery.datepick/calendar-green.gif',
			onSelect: function(selectedDate) {
				var option = "minDate";
				var instance = $(this).data("datepicker");
				
				var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
				
				$('#endDatepicker').datepicker("option", option, date);
				
				var d = new Date(date); 
				d.setDate(d.getDate() + 7); 
				$('#endDatepicker').datepicker('setDate', d);
				
				$('#startDatepicker').datepicker("hide");
				$('#endDatepicker').datepicker("show");
				
			}

		});
		
		$('#endDatepicker').datepicker({
			 
			showOn: 'both', 
			buttonImageOnly: true,
			maxDate: getMaxDate(),
			buttonImage: '/js/jquery.datepick/calendar-green.gif',
			onSelect: function() {
			      $('#ui-datepicker-div').toggle();
			}
			
		});
		
		function getMaxDate()
		{
			var now = new Date();
			var year = parseInt( now.getFullYear()) + 1 ;
			
			return new Date(year, 12 - 1, 31);
		}
		
		$('#lnkEndPlace').click(function()
		{
			if (document.getElementById('lnkEndPlace').checked == true) {
			  $('#endPlaceSearch').fadeIn('slow');
			 } else {
			  $('#endPlaceSearch').hide('fast');
			  document.getElementById('endPlace').value = '';
			}
			
		});

		$('#putime').change(function(){
			$('#dotime').val($('#putime').val());
		});
	
		$('#suchestarten').click(function(){
      if (document.getElementById('lnkEndPlace').checked == true) {
		  	clickEnter = false
			  $('#mietwagenSearchForm').submit();
			}
		});	

		// form submit und validierung
		$('#mietwagenSearchForm').submit(function() 
		{

			if (document.getElementById('startDatepicker').value.match(/\d\d\.\d\d\.\d\d\d\d/)) {
				dateNotValidStart = 0;
                     } else {
				dateNotValidStart = 1;
			}

			if (dateNotValidStart) {
  				$('#errorStartDate').dialog('open');
				return false;
			}

			if (document.getElementById('endDatepicker').value.match(/\d\d\.\d\d\.\d\d\d\d/)) {
				dateNotValidEnd = 0;
                     } else {
				dateNotValidEnd = 1;
			}

			if (dateNotValidEnd) {
  				$('#errorEndDate').dialog('open');
				return false;
			}

	    	var tmpStartDate = $("#startDatepicker").val().split('.');
	    	var tmpEndDate = $("#endDatepicker").val().split('.');

		//check ob das Startdatum existiert  
    	   	var StartYear = tmpStartDate[2];
    	   	var StartMonth = tmpStartDate[1];
    	   	var StartDay = tmpStartDate[0];
	   	var StartSchaltjahr = 0;

	   	if (((StartYear % 4 == 0) && (StartYear % 100 != 0)) || ( StartYear % 400 == 0)) StartSchaltjahr = 1;

	 	if (StartMonth == 04 || StartMonth == 06 || StartMonth == 09 || StartMonth == 11) {
    	   	  if (StartDay < 01 || StartDay > 30) {
  				$('#errorAnmietDate').dialog('open');
				return false;  
    	   	  }
	 	} else if (StartMonth == 01 || StartMonth == 03 || StartMonth == 05 || StartMonth == 07 || StartMonth == 08 || StartMonth == 10 || StartMonth == 12) {
    	   	  if (StartDay < 01 || StartDay > 31) {
  				$('#errorAnmietDate').dialog('open');
				return false;  
    	   	  }
	 	} else if (StartMonth == 02) {
  	         if (StartSchaltjahr == 1) {
    	  	    if (StartDay < 01 || StartDay > 29) {
  				$('#errorAnmietDate').dialog('open');
				return false;
 	           }
  	     	  } else {

    		    if (StartDay < 01 || StartDay > 28) {
   				$('#errorAnmietDate').dialog('open');
				return false;
                  }
  	     	  }
	   	} else {
   				$('#errorAnmietDate').dialog('open');
				return false;
    	  	}
        
	   	//check ob das Abgabedatum existiert  
    	   	var EndYear = tmpEndDate[2];
    	   	var EndMonth = tmpEndDate[1];
    	   	var EndDay = tmpEndDate[0];
	   	var EndSchaltjahr = 0;

	   	if (((EndYear % 4 == 0) && (EndYear % 100 != 0)) || ( EndYear % 400 == 0)) EndSchaltjahr = 1;

	 	if (EndMonth == 04 || EndMonth == 06 || EndMonth == 09 || EndMonth == 11) {
    	   	  if (EndDay < 01 || EndDay > 30) {
  				$('#errorAbgabeDate').dialog('open');
				return false;  
    	   	  }
	 	} else if (EndMonth == 01 || EndMonth == 03 || EndMonth == 05 || EndMonth == 07 || EndMonth == 08 || EndMonth == 10 || EndMonth == 12) {
    	   	  if (EndDay < 01 || EndDay > 31) {
  				$('#errorAbgabeDate').dialog('open');
				return false;  
    	   	  }
	 	} else if (EndMonth == 02) {
  	     	  if (EndSchaltjahr == 1) {
    		    if (EndDay < 01 || EndDay > 29) {
  				$('#errorAbgabeDate').dialog('open');
				return false;
 	           }
  	     	  } else {

    		    if (EndDay < 01 || EndDay > 28) {
   				$('#errorAbgabeDate').dialog('open');
				return false;
                  }
  	     	  }
	       } else {
   				$('#errorAbgabeDate').dialog('open');
				return false;
 	       }
			
			var tmpDateArray = $("#startDatepicker").val().split('.');
			var tmpTimeArray = $("#putime").val().split(':');
		
			var startDate = new Date(tmpDateArray[2], tmpDateArray[1].replace( /^(0+)/g, '' )-1, tmpDateArray[0], tmpTimeArray[0], tmpTimeArray[1], 0, 0);

			tmpDateArray = $("#endDatepicker").val().split('.');
                        tmpTimeArray = $("#dotime").val().split(':');
			
			var endDate = new Date(tmpDateArray[2], tmpDateArray[1].replace( /^(0+)/g, '' )-1, tmpDateArray[0], tmpTimeArray[0], tmpTimeArray[1], 0, 0);
			
			if (clickEnter == true)
			{

		$('#suchestarten').click(function(){
			clickEnter = false;	
		});

		if (clickEnter == true) {
				return false;

		}
	
			}

			if ($('#pucity').val() == '')
			{
				$('#errorPlaceDialog').dialog('open');
				return false;
			}
			
			if (startDate >= endDate)
			{
				$('#errorDialog').dialog('open');
				return false;
			}
			

			if ($('#endPlace').val() == '')
			{
				$('#docity').val('');
				$('#docountry').val('');
			}
				
			if (forceSearch != true)
			{
			
				if (((startDate - new Date()) / (1000 * 60 * 60 * 24)) < 0.0)
				{
					$('#errorTimeDialog').dialog('open');
					return false;
				}
				
				if ((endDate - startDate) > (86400000 * 250))
				{
					$('#confirmFutureDialog').dialog('open');
					return false;
				}

				if ($('#endPlace').val() != '')
				{
					if ($('#docountry').val() != $('#pucountry').val())
					{
						$('#confirmDoCountryDialog').dialog('open');
						return false;		
					}
					else
					{
						$('#confirmDoDialog').dialog('open');
						return false;
					}	
				}
			}

			return true;
		});

        if(ajaxCall) {
            ajaxCall.stop();
            ajaxCall=0;
        }

        // suggest search box jquery
        $('#startPlace,#endPlace').keyup(function(){      

          searchLayerId = this.id;
          var currentValue = document.getElementById(searchLayerId).value;

          if (clickEnter == false && searchLayerId == "startPlace") {
            $("#pucity").val('');
            $("#pucountry").val('');
	   }

          if(currentValue != oldValue && currentValue.length > 0) {
            if(ajaxCall) {
                ajaxCall.abort();
                ajaxCall=0;
            }
            ajaxCall=$.ajax({
              url: "/ajax/search.fast",
              dataType: 'json',
              type: 'GET',
              data: "token="+encodeURIComponent(document.getElementById(searchLayerId).value)+"&max_matches=100&use_similar=0",
              success: displayMe
            });

            oldValue = document.getElementById(searchLayerId).value;
          }

          if(currentValue.length == 0) {
            var result = document.getElementById('resultLayer');
            if(result) {
              oldValue = "";
              result.innerHTML = "";
            }
          }
        });

	});

    var lineOutput;
    var lineSelected;
    var searchActive;

    function displayMe(json) {

      if(!document.getElementById('resultLayer')) {
        $('<div id="resultLayer" style="position:absolute;"></div>').appendTo('body');
      }

      if(json) {
        var result = document.getElementById('resultLayer');
        var textinput = document.getElementById(searchLayerId);
        result.style.top = (findElementPosY(textinput)+findElementHeight(textinput))+"px";
        result.style.left = findElementPosX(textinput)+"px";

        var ausgabe = "";
   
        lineOutput = 0;
        searchActive = 0;
 
        jQuery.each(json, function(i,val) {
            lineOutput = lineOutput + 1;
            var loc = val[1]["Location"]; 
            var cnt = val[1]["Country"];

            var loc_hl = doHighlight(loc,textinput.value);
            var cnt_hl = doHighlight(cnt,textinput.value);

			var cnt_id=val[1]["CountryKey"];

            loc = loc + ", " +cnt;

            var styleAdder = "";

            ausgabe = ausgabe + "<div id='dropDownLine"+lineOutput+"' style='"+styleAdder+"border-bottom:1px solid #aaaaaa;cursor:pointer;height:45px;padding-top:4px;padding-left:4px;' onmousemove='selectEntry("+lineOutput+",0);' onclick='setInputValue(\""+loc+"\",\""+val[1]['ID']+"\",\""+cnt_id+"\");'>" + loc_hl +"<br />"+ cnt_hl +"</div>";
        });

        if(lineOutput > 0) {
          searchActive = 1;
/*
	   if (textinput.id == 'startPlace') {
	     document.getElementById('startPlaceLabel').style.color = "#000";
	     document.getElementById('startPlace').style.background = "#FFF";
            document.getElementById('startPlace').style.color = "#000";
            document.getElementById('startPlace').style.border = "";
	   }

	   if (textinput.id == 'endPlace') {
	     document.getElementById('endPlaceLabel').style.color = "#000";
	     document.getElementById('endPlace').style.background = "#FFF";
            document.getElementById('endPlace').style.color = "#000";
	     document.getElementById('endPlace').style.border = "";
	   }
*/
          if(lineOutput > 4) {
            ausgabe = "<div style='background-color:#fff;overflow:auto;height:250px;width:"+(findElementWidth(textinput)-3)+"px;border:1px solid #000;' id='dropHolder'>"+ausgabe+"</div>";
          } else {
            ausgabe = "<div style='background-color:#fff;width:"+(findElementWidth(textinput)-3)+"px;border:1px solid #000;'>"+ausgabe+"</div>";
          }
        } else {
          searchActive = 0;
          oldValue = "";
          ausgabe = "";

/*
          if (clickEnter == true) {

 		ausgabe = "";

	   } else {

            ausgabe = "<div style='background-color:#FFF;font-size:12px;color:#000;font-style:italic;width:"+(findElementWidth(textinput)-3)+"px;border:1px solid #000;'><p style='font-size:14px;font-weight:bold;'>--- keinen passenden Ort gefunden ---</p>Bitte &uuml;berpr&uuml;fen Sie die Schreibweise.<br/><br><b>Tipp:</b> zur Eingabe reicht auch der 3-Letter-Code des Flughafens</div>";
	   
        
	     if (textinput.id == 'startPlace') {
	       document.getElementById('startPlaceLabel').style.color = "#F00";
	       document.getElementById('startPlace').style.background = "#F8E0E6";
	       document.getElementById('startPlace').style.color = "#F00";
	       document.getElementById('startPlace').style.border = "1px solid #F00";
	     }

	     if (textinput.id == 'endPlace') {
	       document.getElementById('endPlaceLabel').style.color = "#F00";
	       document.getElementById('endPlace').style.background = "#F8E0E6";
	       document.getElementById('endPlace').style.color = "#F00";
	       document.getElementById('endPlace').style.border = "1px solid #F00"
	     }

           
	   }
*/
        }

        result.innerHTML = ausgabe;

        if(lineOutput > 0) {
          selectEntry(1,1);
        }
      }
    }

    function setInputValue(description,city,country) {

        if(searchLayerId == "startPlace") {
          document.getElementById('pucity').value=city;
          document.getElementById('pucountry').value=country;
	   $("#pucity").val(city).change();
          $("#pucountry").val(country).change();
        } else {
          document.getElementById('docity').value=city;
          document.getElementById('docountry').value=country;
	   $("#docity").val(city).change();
          $("#docountry").val(country).change();
	   clickEnter = true;
        }

        document.getElementById(searchLayerId).value=description;

        var result = document.getElementById('resultLayer');
        result.innerHTML = "";
        oldValue = "";
        searchActive = 0;
    }

    function doHighlight(haystack, needle) {
      var snip = haystack.substring(0,needle.length).toLowerCase();
      if(snip == needle.toLowerCase()) {
        haystack = "<b>"+haystack.substring(0,needle.length)+"</b>"+haystack.substring(needle.length);
      }
      return(haystack);
    }

    function selectEntry(i,scrollTo) {
        if(lineSelected && lineSelected > 0) {
            document.getElementById('dropDownLine' + lineSelected).style.backgroundColor = "#ffffff";
        }

        lineSelected = i;
        document.getElementById('dropDownLine' + lineSelected).style.backgroundColor = "#b2b4bf";

        if(scrollTo) {
          //$("#dropHolder").scrollTo("#dropDownLine"+lineSelected);
        }
    }

    function keypressHandler(e) {
        if(e) {
          if(searchActive) {
            if(e.keyCode==13) {
                  document.getElementById('dropDownLine'+lineSelected).onclick();
                  var result = document.getElementById('resultLayer');
                  result.innerHTML = "";
                  oldValue = "";
                  searchActive = 0;
                }

            if(e.keyCode==38 && lineSelected > 1) {
                selectEntry(lineSelected - 1,1);
            }
            if(e.keyCode==40 && lineSelected < lineOutput) {
                selectEntry(lineSelected + 1,1);
            }
          }
        }
    };

    if($.browser.mozilla) {
        $(document).keyup(function(e) {
          keypressHandler(e);
        });

    } else {
      if($.browser.msie) {
        $(document).keyup(function(e) {
          keypressHandler(e);

        });
      } else {
        $(document).keyup(function(e) {
          keypressHandler(e);
        });
      }
    }



    $(document).click(function() {
        if(searchActive) {
          var result = document.getElementById('resultLayer');
          result.innerHTML = "";
          oldValue = "";
          searchActive = 0;
        }
    });

function findElementPosX(obj) {
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    curleft = obj.offsetLeft
    curtop = obj.offsetTop
    while (obj = obj.offsetParent) {
      curleft += obj.offsetLeft
      curtop += obj.offsetTop
    }
  }
  return curleft;
}

function findElementPosY(obj) {
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    curleft = obj.offsetLeft
    curtop = obj.offsetTop
    while (obj = obj.offsetParent) {
      curleft += obj.offsetLeft
      curtop += obj.offsetTop
    }
  }
  return curtop;
}

function findElementHeight(elem) {
  var browser = sniffBrowsers();

  if (browser == "ns4") {
    return elem.clip.height;
  } else {
    if (browser == "op5") {
      xPos = elem.style.pixelHeight;
    } else {
      xPos = elem.offsetHeight;
    }
    return xPos;
  }
}

function findElementWidth(elem) {
  var browser = sniffBrowsers();

  if (browser == "ns4") {
    return elem.clip.width;
  } else {
    if (browser == "op5") {
      xPos = elem.style.pixelWidth;
    } else {
      xPos = elem.offsetWidth;
    }
    return xPos;
  }
}


function sniffBrowsers() {
  if(document.layers) {
    return("ns4");
  }
  if((navigator.userAgent.indexOf("Opera 5")!=-1)
     || (navigator.userAgent.indexOf("Opera/5")!=-1)) {
    return("op5");
  }

  if((navigator.userAgent.indexOf("Opera 6")!=-1)
    ||(navigator.userAgent.indexOf("Opera/6")!=-1)) {
    return("op6");
  }

  var agt=navigator.userAgent.toLowerCase();

  if(agt.indexOf("msie") != -1) {
    return("ie");
  }

  return("default");
}	
