var delay = 10000;
var showing = 5;
var i = 0;
function move(i) {
   return function() {
   $('#recent'+i).remove().css('display', 'none').prependTo('#items');
   }
}
function shift() {
  var toShow = (i + showing) % count;
  $('#recent'+toShow).slideDown(1000, move(i));
  $('#recent'+i).slideUp(1000, move(i));
  i = (i+1) % count;
  setTimeout('shift()', delay);
}
$(document).ready(function() {
	updatePredictedFare(); // grab an initial fare prediction
	function format(airport) {
      var str;
      str = airport.apName + " (" + airport.code + ")";
      if(airport.city != null && airport.city != '')
      str += ", "+airport.city;
      if(airport.state != null && airport.state != '')
      str += ", "+airport.state;
      return str;  
    }
    function parseData(row)
    {
        var str;
        str = row.apName + " (" + row.code + ")";
        if(row.city != null && row.city != '')
        str += ", "+row.city;
        if(row.state != null && row.state != '')
        str += ", "+row.state;
        return {
          data: row,
          value: str,
          result: str
        }
    }         
    $("#name").autocomplete(local+'/user/searchairport', {    //flight
      minChars: 3,
      matchContains: true,
      max: autoCompBoxLimit,
      selectFirst: true,
      pare:'nameh',
       parse: function(data) {
        return $.map(eval(data), function(row) {
                     return parseData(row);
        });
      },
      formatItem: function(item) {
      return format(item);
      }
    });
	$("#name, #airport, .passengerclass").change(function () {
		updatePredictedFare();
	});
	$("#RoundTrip, #OneWay, #nonStopSearch, #restricting, #restricting1, #restrictinghome").click (function () {
		updatePredictedFare();
	});
	$("#airport").autocomplete(local+'/user/searchairport', {     //flight
      selectFirst: true,
      minChars: 3,
      matchContains: true,
      max: autoCompBoxLimit,
      pare:'airporth',
      parse: function(data) {
        return $.map(eval(data), function(row) {
                     return parseData(row);
        });
      },
      formatItem: function(item) {
      return format(item);
      }
    });
 
    $("#city").autocomplete(local+'/user/searchcity', {   //hotel
      matchContains: true,
      max: autoCompBoxLimit,
      autoFill: false,
      selectFirst: true,
      cityCode: "citycode",
      pare:'cityh',
      minChars: 3,
      parse: function(data) {
        return $.map(eval(data), function(row) {
          return {
            data: row,
            value: row.city+"(_"+row.code+"_)",
            result: row.city+"(_"+row.code+"_)"
          }
        });
      },
      formatItem: function(item) {
      return item.city;
      }
    });

  });

$(document).ready(function() {
  setTimeout('shift()', delay);       //activity slider


$("#residencyId").change(function(){   //residency
  $("#residency").attr("value",$("#residencyId :selected").text());
                     })
  $(".hometabs").click(function(){
      $(".allhometabs").hide();                 
      $("#"+this.id+"div").show();
      return false;
  })
                  
  //$("#t_returndate").datepicker("disable");
	$(".hometab").click(function(){
		id=this.id;
		$(".inact").css("display","block");
		$(".actclass").css("display","none");
		$("#"+this.id+"_actdiv").css("display","block");
		$("#"+this.id+"_inactdiv").css("display","none");
		$(".hometabdiv").css("display","none");
		$("#home"+id).fadeIn(2000);
        if(this.id=="plan")
            $("#slideMov1").css("display","block");
        else    
            $("#slideMov1").css("display","none");
		return false;
	})
	$(".hometabact").click(function(){
		return false;
	})
$("input[@name='carround']").click(function() {
    if($("input[@name='carround']:checked").val()=="0")
    {
        $("#dropoffCountry").removeAttr('disabled');
        $("#dropoffCountry").css('background-color','#fff');
        if($("#dropoffCountry").val()!="00")
        {
            $("#dropoff").removeAttr('disabled');
            $("#dropoff").css('background-color','#fff');
        }     
    }
    else
    {
        $("#dropoffCountry").attr('disabled', 'disabled');
        $("#dropoffCountry").css('background-color','#ECE9D8');
        $("#dropoff").attr('disabled', 'disabled');
        $("#dropoff").css('background-color','#ECE9D8');
    } 
});


if($("#country").val()!="00")      //pick-up country
{
$("#pickupdiv").load(local+"/car/getlocations",{'country':$("#country").val(),'type':"pickup"},function(){
      $("#pickup").attr("value",pickupCode);              
      $("#fullPickup").val($('#pickup :selected').text());
      changelocation();
     });
}

$("#country").change(function(){   //pick-up country

   $("#pickup").attr('disabled', 'disabled'); 
   $("#pickupdiv").load(local+"/car/getlocations",{'country':$("#country").val(),'type':"pickup"},function(){
   if(!$("#pickup").val()) 
   {
       $('#alertErrorText').text("No locations are available for this country.");
       errormsg("alertError");
       $("#pickup").attr('disabled', 'disabled');
   }
   else
   { 
      $("#fullPickup").val($('#pickup :selected').text());
      changelocation();
      hideerrormsg('alertError');
   } 
    });
})

if($("#dropoffCountry").val()!="00")          //drop-of country
{
$("#dropoffdiv").load(local+"/car/getlocations",{'country':$("#dropoffCountry").val(),'type':"dropoff"},function(){
      $("#dropoff").attr("value",dropoffCode);              
      $("#fullDropoff").val($('#dropoff :selected').text());
      changelocation();
     if($("input[@name='carround']:checked").val()=="1")
     {
        $("#dropoff").attr('disabled', 'disabled');
        $("#dropoff").css('background-color','#ECE9D8');
     }   
     });
}

$("#dropoffCountry").change(function(){     //drop-off country

   $("#dropoff").attr('disabled', 'disabled');
   $("#dropoffdiv").load(local+"/car/getlocations",{'country':$("#dropoffCountry").val(),'type':"dropoff"},function(){
   if(!$("#pickup").val()) 
   {
       $('#alertErrorText').text("No locations are available for this country.");
       errormsg("alertError");
       $("#dropoff").attr('disabled', 'disabled');
   }
   else
   { 
     $("#fullDropoff").val($('#dropoff :selected').text());
     changelocation();
     hideerrormsg('alertError');
     }  
    });
})

$("#flightsubmit").submit(function()        //flight submit
{
  if(($("#name").val().length<1||$("#nameh").val()=="0")&&($("#name").val()!=to||$("#name").val().length<1))
  {
    $('#alertErrorText').text("Please select a departure city or airport from the list.");
    errormsg("alertError");
    return false;
  }
  if(($("#airport").val().length<1||$("#airporth").val()=="0")&&($("#airport").val().length<1||$("#airport").val()!=from))
  {
    $('#alertErrorText').text("Please select a destination city or airport from the list.");
    errormsg("alertError");
    return false; 
  }
  if($("#restricting").val().length<1)
  {
    $('#alertErrorText').text("Please enter a departure date.");
    errormsg("alertError");
    return false;
  }
  if($("input[@name='round']:checked").val()==1)
  {  
    if($("#restricting1").val().length<1)
    {
      $('#alertErrorText').text("Please enter a return date");
      errormsg("alertError");
      return false;
    }
  }
  var departing = new Date($("#restricting").val());
  var returning = new Date($("#restricting1").val());
  if(departing > returning )
  {
    $('#alertErrorText').text("Departure date must be before return date.");
    errormsg("alertError");
    return false;
  }
});

 $("#formsubmit").submit(function()     //hote submit
   {
      if($("input[@name='location']:checked").val()==0)
      {           
        if($("#address1").val().length<1)
        {
          $('#alertErrorText').text("Please enter a address.");
          errormsg("alertError");
          return false;
         }
      }
      if($("#city").val().length<1||($("#cityh").val()=="0"&&$("#city").val()!=city))
      {
          $('#alertErrorText').text("Please type the destination you wish to travel to.");
          errormsg("alertError");
          return false;
      }
      if($("#t_departdate").val().length<1)
      {
          $('#alertErrorText').text("Please select the date you will be \"Getting There\".");
          errormsg("alertError");
          return false;
      }
      if($("#t_returndate").val().length<1)
      {
          $('#alertErrorText').text("Please select the date you will be \"Returning On\".");
          errormsg("alertError");
          return false;
      }
      var departdate = new Date($("#t_departdate").val());
      var returndate = new Date($("#t_returndate").val()) ;
      if(departdate > returndate)
      {
          $('#alertErrorText').text("\"Getting There\" date must be before \"Returning On\" date.");
          errormsg("alertError");
          return false;
      }

});

$("#carformsubmit").submit(function()     //car submit
{    
   if(!$("#pickup").val())
    {
       $('#alertErrorText').text("No locations available for this country.");
       errormsg("alertError");
       return false;
    } 
    if(!$("#dropoff").val()&& $("input[@name='carround']:checked").val()=="0")
    {
       $('#alertErrorText').text("No locations available for this country.");
       errormsg("alertError");
       return false;
    }    
   if($("#t_pickup").val().length<1)
      {
          $('#alertErrorText').text("Please enter pick-up date.");
          errormsg("alertError");
          return false;
      }
      if($("#t_dropoff").val().length<1)
      {
          $('#alertErrorText').text("Please enter drop-off date.");
          errormsg("alertError");
          return false;
      }

       var pickup = new Date($("#t_pickup").val());
       var dropoff = new Date($("#t_dropoff").val());
      if(pickup > dropoff )
      {
          $('#alertErrorText').text("Pickup time must be before dropoff time.");
          errormsg("alertError");
          return false;
      }
})
$("#t_pickup").change(function() {
        var date1=$("#t_pickup").val();
        var myday = new Date(date1);
        var today=new Date();
        var one_day=1000*60*60*24;
        chan_date=Math.ceil((myday.getTime() - today.getTime())/(one_day));
        myday.setDate(myday.getDate()+1);
        var month = myday.getMonth()+1;
        if(month<10)
            month="0"+month;
         var dat=myday.getDate();
         if(dat<10)
            dat="0"+dat;         
       //$("#t_dropoff").datepicker('enable');
       $("#arrChoice").removeAttr('disabled');
       var pickup = new Date($("#t_pickup").val());
       var dropoff = new Date($("#t_dropoff").val());
       if($("#t_dropoff").val()=="" || pickup > dropoff )
       {
         $("#t_dropoff").attr("value",month+"/"+dat+"/"+myday.getFullYear()) ;
       }
});
$("#restricting").change(function() {
  var date1=$("#restricting").val();
  var myday = new Date(date1);
  var today=  new Date();     
  var one_day=1000*60*60*24
  chan_date=Math.ceil((myday.getTime()-today.getTime())/(one_day))+0;
    
  myday.setDate(myday.getDate()+3);
  var month = myday.getMonth()+1;
  if(month<10)
    month="0"+month;
  var dat=myday.getDate();
  if(dat<10)
    dat="0"+dat;        
  
  if($("input[@name='round']:checked").val()=="1")
  {
    var departing = new Date($("#restricting").val());
    var returning = new Date($("#restricting1").val());
    if($("#restricting1").val()=="" || departing > returning)
    {
      $("#restricting1").attr("value",month+"/"+dat+"/"+myday.getFullYear()); 
    }
    $("#arrChoice").removeAttr('disabled');
    $("#arrTime").removeAttr('disabled');
    $("#restricting1").datepicker('enable');
  }
});

$("#t_departdate").change(function() {
  var date1=$("#t_departdate").val();
  var myday = new Date(date1);
  var today=  new Date();     
  var one_day=1000*60*60*24;
  chan_date=Math.ceil((myday.getTime()-today.getTime())/(one_day));
  myday.setDate(myday.getDate()+2);
  var month = myday.getMonth()+1;
  if(month<10)
    month="0"+month;
  var dat=myday.getDate();
  if(dat<10)
    dat="0"+dat;         
        
  $("#t_returndate").datepicker('enable');
  var departdate = new Date($("#t_departdate").val());
  var returndate = new Date($("#t_returndate").val()) ;
  if( $("#t_returndate").val()=="" || departdate > returndate )
  {
    $("#t_returndate").attr("value",month+"/"+dat+"/"+myday.getFullYear()); 
  }
});

$(".linksearch").click(function() {
  var id=this.id;
  id="#"+id.replace("hidd",'');
  var obj=$(id);
  obj.submit();
  return false;
});

$(".linksearchCar").click(function() {
  var id=this.id;            
  id="#"+id.replace("hiddCar",'');
  var obj=$(id+'Car');
  obj.submit();
  return false;
});

$(".homesearch").click(function() {
  var id=this.id;            
  id="#"+id.replace("form",'');
  var obj=$(id);
  obj.submit();
  return false;
});

$("#morefares").click(function() {
  $(".nondisplayleftinner").css("display","block");
  $(".moredetails").css("display","none");
  return false;
});

$(".linksearchFlt").click(function() {
  var id=this.id;            
  id="#"+id.replace("hiddFlt",'');
  var obj=$(id+'Flt');
  obj.submit();
  return false;
});
$(".linksearch").click(function() {
         var id=this.id;
         id="#"+id.replace("hidd",'');
         var obj=$(id);
         obj.submit();
         return false;
      });
$(".linksearchHtl").click(function() {
     var id=this.id;            
     id="#"+id.replace("hiddHtl",'');
     var obj=$(id+'Htl');
     obj.submit();
     return false;
});

$(".linksearch").click(function() {
  var id=this.id;            
  id="#"+id.replace("hidd",'');
  var obj=$(id);
  obj.submit();
  return false;
});

$("input[@name='location']").click(function() {
  if($("input[@name='location']:checked").val()=="1")
  {
    $("#address").css('display', 'none');
  }
  else
  {
    $("#address").css('display', 'block');
  } 
});

$("input[@name='round']").click(function() {
 if($("input[@name='round']:checked").val()=="0")
 {
    $("#arrChoice").attr('disabled', 'disabled');
    $("#arrTime").attr('disabled', 'disabled');
    $("#restricting1").datepicker("disable");
 }
 else
 {
    $("#arrChoice").removeAttr('disabled');
    $("#arrTime").removeAttr('disabled');
    $("#restricting1").datepicker('enable');
 }  
});   
});


function changelocation()
{
$("#dropoff").change(function(){
  $("#fullDropoff").val($('#dropoff :selected').text());
});
$("#pickup").change(function(){
  $("#fullPickup").val($('#pickup :selected').text());
});
}
// TODO: Copy/pasted from flight.js - DRY DRY DRY!
function updatePredictedFare() {
	// extract airport code from between parenthesis
	//if (search_source.search(/\(/)) var search_source=from_search.split('(')[1].split(')')[0];
	//if (search_dest.search(/\(/)) var search_dest=to_search.split('(')[1].split(')')[0];
	
	$.ajax({
			type: "POST",
			url: local+"/flight/predict",
			data: $('#flightsubmit').serialize(), //+"&source="+search_source+"&dest="+search_dest,
			success: function(result){
				if (result > 0) {
					$('#predictedfare').html('Predicted Lowest Fare: <span id=predictedfareprice>$' + result + '</span>'); // + ' ('+search_source+' to '+search_dest+')');
					$('#predictedfare').fadeIn('.4');
				} else {
					$('#predictedfare').fadeOut('.4');
				}
			}
		});
}
