var LIMO_FOLDER='limosearch/'; 
$(document).ready(function() {
    $("#ride_date").datepicker({minDate:'0d',maxDate:'+1y',numberOfMonths:1});
    $('#dropofftime_span').show();
    $('#dropoff_location_span').hide();
});
$(function(){
	$('#service_type').change(function(){
		resetError('err_service_type','');
		var droptimearray=$('#dropofftime_service_types_ids').val().split(',');
		var droplocationarray=$('#dropoffplace_service_types_ids').val().split(',');
		var service = parseInt($(this).val());
	    var vehicle_list = "1,2,3,4,5,6,7";
	    var trollyWorthy = [64, 16384, 4, 8192, 16, 32, 512, 2048];
	    var classicWorthy = [4,8];
	    if( jQuery.inArray(service, trollyWorthy ) >= 0 ) vehicle_list += ",9,10";
	    if( jQuery.inArray(service, classicWorthy ) >= 0 ) vehicle_list += ",8";
	    $('#vehicle_types').val(vehicle_list);
		show_hide_drop_offs(droptimearray);
		show_hide_drop_location(droplocationarray);
		change_labels();
	});
	$('#ride_date').change(function(){
		if($('#ride_date').val()!=''){
			resetError('err_ride_date','pickup_place');
		}
	});
	$('#pickup_zip').blur(function(){
		if($('#pickup_zip').val()!=''){
			resetError('err_pickup_place','');
		}
	});
	$('#drop_off_place').blur(function(){
		if($('#drop_off_place').val()!=''){
			resetError('err_drop_off_place','');
		}
	});
	$('#pax').change(function(){
		if($('#pax').val()!=''){
			resetError('err_pax','');
		}
	});
	$('#pickup_time').change(function(){
		if($('#pickup_time').val()!=''){
			resetError('err_pickup_time','');
		}
	});
	$('#drop_off_time').change(function(){
		if($('#drop_off_time').val()!=''){
			resetError('err_drop_off_time','');
		}
	});
	
	$('#submit_search').click(function(){
		callAPI(false);									   
		return false;	
	});
	$('#contact_info').submit(function(){
		    resetAllErrors();	
		    var errflag=0;
			var first_name = $.trim($('#passenger_first_name').val());
			var last_name = $.trim($('#passenger_last_name').val());
			var email = $.trim($('#passenger_email').val());
			var phone_num = $.trim($('#passenger_phone_num').val());
				
			if(first_name=='' && last_name=='') {
				displayError('err_full_name','Please enter your first and last name');
				errflag=1;
			}else if(first_name==''){
				displayError('err_full_name','Please enter your first name');
				errflag=1;
			} else if(last_name==''){
				displayError('err_full_name','Please enter your last name');
				errflag=1;
			}
			if (email==''){
				displayError('err_emailid','Please enter your email address');
				errflag=1;
			}else if(!VdEm(email)){
				displayError('err_emailid','Please enter valid email address');
				errflag=1;
			}
			if(phone_num!=''){
				if(!isNumeric(phone_num)){
					displayError('err_phoneno','Please enter valid phone number');
					errflag=1;
				}else if(phone_num.length < 6 || phone_num.length > 10){
					displayError('err_phoneno','Please enter valid phone number');
					errflag=1;
				}
			}
			if(errflag==0) { 
				resetAllErrors();	
				$('#progress_indicator').removeClass('ls_hide');
				$('#user_passenger_info_submit').attr('disabled','disabled');
				return true;
			} else{
				return false;
			}
	});

});
//http://plugins.jquery.com/files/jquery.cookie.js.txt
jQuery.cookie = function(name, value, options) {
  if (typeof value != 'undefined') { // name and value given, set cookie
      options = options || {};
      if (value === null) {
          value = '';
          options.expires = -1;
      }
      var expires = '';
      if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
          var date;
          if (typeof options.expires == 'number') {
              date = new Date();
              date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
          } else {
              date = options.expires;
          }
          expires = '; expires=' + date.toUTCString(); // use expires
      }
      var path = options.path ? '; path=' + (options.path) : '';
      var domain = options.domain ? '; domain=' + (options.domain) : '';
      var secure = options.secure ? '; secure' : '';
      document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
  } else { // only name given, get cookie
      var cookieValue = null;
      if (document.cookie && document.cookie != '') {
          var cookies = document.cookie.split(';');
          for (var i = 0; i < cookies.length; i++) {
              var cookie = jQuery.trim(cookies[i]);
              // Does this cookie string begin with the name we want?
              if (cookie.substring(0, name.length + 1) == (name + '=')) {
                  cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                  break;
              }
          }
      }
      return cookieValue;
  }                                                                  
};
function validate_form(){
	var droptimearray=$('#dropofftime_service_types_ids').val().split(',');
	var droplocationarray=$('#dropoffplace_service_types_ids').val().split(',');
	var service_typeval=$('#service_type :selected').val();
	var alertmsg = '';
	var errflag=0;
	var errfields = new Array();
	var extraerr = '';
	svctype = $('#service_type').val();
	sdop = $('#drop_off_place').val();
	spup = $('#pickup_place').val();
	$('#searchresponseError').html('');
	if (svctype==''){
		errflag=1;
		displayError('err_service_type','Please select service type');
	}
	if ($('#pax').val()==''){
		errflag=1;
		displayError('err_pax','Please select number of passengers');
	}
	if ($('#ride_date').val()=='' || $('#ride_date').val()=='Select Date'){
		displayError('err_ride_date','Please enter date of service');
		errflag=1;
	}
	if ($('#pickup_time').val()==''){
		displayError('err_pickup_time','Please select pickup time');
		errflag=1;
	}
	if ( $('#drop_off_time').val()=='' && (jQuery.inArray(svctype, droptimearray ) < 0) ){
			displayError('err_drop_off_time','Please select dropoff time');
			errflag=1;
	}
	if ($('#pickup_zip').val()==''){
		displayError('err_pickup_place','Please enter your pickup zip');
		errflag=1;	
	}
	if ( jQuery.inArray(svctype, droplocationarray ) >= 0 && sdop=='') {
		displayError('err_drop_off_place','Please enter your drop-off address');
		errflag=1;
	}
	if (errflag==0  && (jQuery.inArray(svctype, droptimearray ) < 0) ) 
	{
		var drophour = parseInt($('#drop_off_time').val().substring(0,2),10);
		if( $('#drop_off_time').val().substring(3)=="30" ) drophour += 0.5;
		var pickhour = parseInt($('#pickup_time').val().substring(0,2),10);
		if( $('#pickup_time').val().substring(3)=="30" ) pickhour += 0.5;
		var timediff = drophour - pickhour;
		if( timediff < 0 ){ timediff += 24; /*
											 * account for times spanning
											 * midnight
											 */ }
		// special circumstance for prom
		if( $('#service_type').val() == '16384' && timediff < 6 && $.cookie('promTimeWarning') != 1 ) {
		  if( confirm('Prom Tip! Limo companies generally require 6+ hours for prom.\nClick OK to see the best deals for 6+ hour rides.') ){ 
	       changeTimeSlot(); // update back to 6 hours and continue;
	       $.cookie('promTimeWarning', 1); // set a cookie so we only show them
											// the warning once.
	    }
		}
		if( timediff >= 12 && !confirm( 'You have selected a ride duration of '+timediff+' hours. Is this correct?\n\nClick OK to continue.' ) ){
			displayError('err_pickup_time','Please select a valid time span');
			errflag=1;
		}
	}
	if(errflag==0){
		return true;
	}else{
		return false;
	}
}
// If first time is set, change second time to an hour later
function changeTimeSlot() {
  var index_offset = 8; // half hour increments = 3 hours
  // put 6 hours for prom
  if( $('#service_type').val() == '16384' ){ index_offset = 12; }

	var hs = $('#pickup_time').attr('selectedIndex');
	var et = $('#drop_off_time').attr('selectedIndex');
	if (hs <= 48) {
		var do_time_idx = hs+index_offset;
		if (do_time_idx>48) {do_time_idx=48;}
		$('#drop_off_time').attr('selectedIndex', do_time_idx);
	} else {
		$('#drop_off_time').attr('selectedIndex', hs-48);
	}
}
function displayError(element,errormsg){
	$('#'+element).html(errormsg);
	$('#'+element).slideDown('slow');
}
function resetError(element,nextelement){
	$('#'+element).slideUp('slow');
	$('#'+element).html('');
	if(nextelement!=''){
		$('#'+nextelement).focus();
	}
}
function resetAllErrors(){
	$(".errRed").html('');
	$("#searchresponseError").html('');
}
function VdEm(email){
	if(email.match(/^[a-zA-Z0-9]+([_.\-]+[a-zA-Z0-9]+)*?@[a-zA-Z0-9]+([_\-]+[a-zA-Z0-9]+)*?(\.(([a-zA-Z]{2,4})|([A-Za-z]{2,4}\.[a-zA-Z]{2,4})))$/g)==null){
		return false;
	}
	return true;
}
function isNumeric(s){
   var i;
   for (i = 0; i < s.length; i++){   
   var c = s.charAt(i);
   if (((c < "0") || (c > "9"))) return false;
   }
   return true;
}
function show_hide_drop_offs(droptimearray) {
	var val=$('#service_type :selected').val();
	if( jQuery.inArray(val, droptimearray ) >= 0 ){
		$('#dropofftime_span').hide();
	}else{
		 $('#dropofftime_span').show();
	}
	resetError('err_drop_off_time','');
}
function show_hide_drop_location(droplocationarray) {
	var val=$('#service_type :selected').val();
	if( jQuery.inArray(val, droplocationarray ) >= 0 ){
		$('#dropoff_location_span').show();
	}else{
		$('#dropoff_location_span').hide();
	}
	resetError('err_drop_off_place','');
}
function change_labels() {
	var val=$('#service_type :selected').val();
	var pval=$('#pickup_place').val();
	var dval=$('#drop_off_place').val();
	if(val == 100) {
		// to airport
		$('#pickup_location_label').text('Pick-up Address');
		$('#drop_off_location_label').text('Airport');
	} else if ( val == 99 ) {
		// from airport
		$('#pickup_location_label').text('Airport');
		$('#drop_off_location_label').text('Drop-off Address');
	} else if (val == 102) {
		// to cruise port
		$('#pickup_location_label').text('Pick-up Address');
		$('#drop_off_location_label').text('Cruiseport');
	} else if (val == 101) {
		// from cruise port
		$('#pickup_location_label').text('Cruiseport');
		$('#drop_off_location_label').text('Drop-off Address');
	} else {
		$('#pickup_location_label').text('Pick-up Address');
		$('#drop_off_location_label').text('Drop-off Address');
	}
}

function returnSearchAdd(zFlag)
{
	var searchAddress = '';
	if(zFlag)
	{
		return 	$.trim($("#pickup_zip").val());
	}
	if($.trim($("#pickup_place").val()))
	{
		searchAddress += $.trim($("#pickup_place").val());
	}
	if($.trim($("#pickup_city").val()))
	{
		searchAddress += (searchAddress==''?$.trim($("#pickup_city").val()):','+$.trim($("#pickup_city").val()));
	}
	if($.trim($("#pickup_state").val()))
	{
		searchAddress += (searchAddress==''?$.trim($("#pickup_state").val()):','+$.trim($("#pickup_state").val()));
	}
	if($.trim($("#pickup_zip").val()))
	{
		searchAddress += (searchAddress==''?$.trim($("#pickup_zip").val()):','+$.trim($("#pickup_zip").val()));
	}
	return searchAddress;
}

function callAPI(zFlag)
{
	resetAllErrors();
	formvalid = validate_form();
	if (formvalid!=true){
		return false;
	}
	$('#search_submit').attr('disabled','disabled');
	$('#progress_indicator').removeClass('ls_hide');
	var searchAddress = returnSearchAdd(zFlag);
	$.ajax({
	   type: "POST",
	   url: LIMO_FOLDER+"limoapi.php",
	   data: "action=LimoSearch&service_type="+$("#service_type").val()+
	   "&pax="+$("#pax").val()+"&ride_date="+$("#ride_date").val()+
	   "&pickup_time="+$("#pickup_time").val()+"&pickup_place="+searchAddress+
	   "&vehicle_types="+$("#vehicle_types").val()+"&drop_off_time="+$("#drop_off_time").val()+
	   "&drop_off_place="+$("#drop_off_place").val(),
	   success: function(data){
		var searchResult = data.split('##');
		if(searchResult.length==3 && searchResult[0]=='0'){
			if(searchResult[1]=='invalid_pickuptime'){
				displayError('err_pickup_time',searchResult[2]);
			}else if(searchResult[1]=='disambiguation' || searchResult[1]=='invalid_search_param' || searchResult[1]=='invalid_api_key' || searchResult[1]=='no_result_found' || searchResult[1]=='failure' || searchResult[1]=='api_not_responded'){
				if(searchResult[1]=='disambiguation' && searchAddress != $.trim($("#pickup_zip").val()))
				{
					callAPI(true);
					return;
				}else{
					$('#searchresponseError').removeClass('ls_hide');
					displayError('searchresponseError',searchResult[2]);
				}
			}
			$('#search_submit').attr('disabled','');
			$('#progress_indicator').addClass('ls_hide');
		}else if(data==''){
			displayError('searchresponseError','There is some internal error, please try after sometime');
			$('#search_submit').attr('disabled','');
			$('#progress_indicator').addClass('ls_hide');
		}else{
			$("#ls_search_div").html(data);
		}
		return false;
	   }
	 });	
	
}