/*function country_sel(){
	$.post("/ip_country_currency.php", {}, function(msg_data){
		var data=eval("("+msg_data+")");
		if(data.country_user_sel.length >0) {
			select_cbo_by_value('country_user',data.country_user_sel);
			select_cbo_by_value('currency',data.cur_sel);
		}
	});
}*/

function country_sel() {
    $.post("/includes/ip_country_xml_sel.php?lan=" + $("#lan").val(), {}, function(a) {
        result = eval("(" + a + ")"),  $("#country_user_hd").val(result.country_id), $("#cntry_name").html(result.country_name_translated), $("#currency_text").html(result.currency+" "+result.currency_name),  $("#currency_hd").val(result.currency)
    })
}
/*
function diff_droploc(toggle){ currency_name
		if (toggle.checked) {
			gtObj('dropoffDiv').style.display = '';
		}
		else {
			gtObj('dropoffDiv').style.display = 'none';
		}
	}
	
function country_sel() {
    $.post("https://static.myrentalcar.com/ip_country_xml_sel.php?lan=" + $("#lan").val(), {}, function(a) {
        result = eval("(" + a + ")"), 0 < result.country.length && (select_cbo_by_value("country_user", result.country_id), 0 < result.country.length ), $("#cntry_name").html(result.country_name_translated), $("#currency_text").html(result.currency), $("#currency_hd").val(result.currency)
    })
}
*/
function select_cbo_by_value(id, v) { 
	var cbo=document.getElementById(id); 
	for(var i=0; i<cbo.length; i++)	{ 
		if(cbo.options[i].value==v)	{ 
			cbo.selectedIndex=i; 
			return; 
		} 
	} 
}

	
var totalmonth= 2;
if($( window ).width() <= 780)
	totalmonth=1;
$(function() {
	var dates = $( "#pickupdates, #dropoffdates" ).datepicker({
		defaultDate: "+1w",
		minDate: 0, maxDate: "+48M +10D" ,
		numberOfMonths: totalmonth,
		dateFormat: "dd-mm-yy",
		showOn: "both",
		changeMonth: false,
		changeYear: false,			
		buttonImage: "https://1b72baaee35757a86404-7610be60af2ebcae44739170e09e9aeb.ssl.cf1.rackcdn.com/images/calendar_responsive_icon_new.svg",
		buttonImageOnly: true,
		onClose: function(dateText, inst) 
		{ 
			$(this).attr("disabled", false);
		},
		beforeShow: function(input, inst) 
		{
			$(this).attr("disabled", true);
		},			
		//beforeShow: changeDayText,
		//onChangeMonthYear: changeDayText,
		//altField: this.id == "from"? "#alternate":"#alternate2",
		//altFormat: "DD, d MM, yy",
		onSelect: function( selectedDate ) {
			var option = this.id == "pickupdates" ? "minDate" : "",
				instance = $( this ).data( "datepicker" ),
				date = $.datepicker.parseDate(
					instance.settings.dateFormat ||
					$.datepicker._defaults.dateFormat,
					selectedDate, instance.settings );
			dates.not( this ).datepicker( "option", option, date );
			//this.
			
		}
	});
	//alert(dates.html());
});

function changeDayText()
{
  setTimeout(function(){
	var str =  '<table cellspacing="0" cellpadding="0" class="ui-datepicker-table-monthName"><tr>';
	var lang = $("#lan").val();
	for(var i=0; i < ($.datepicker.regional[lang].monthNamesShort).length; i++)
	{
		str = str + '<td><a href="javascript:;" onClick="selectMonthCalender('+i+')" class="ui-datepicker-monthsName">'+$.datepicker.regional[lang].monthNamesShort[i]+'</a></td>';
	}
	str = str + '</tr></table>';
	$(".ui-datepicker").each(function(){
	  //var newday = $("#calendarHeader").html() + $(this).html();
	  var newday = str + $(this).html();
	  $(this).html(newday);
	});
  }, 100); //allows calendar to render
}
function selectMonthCalender(v)
{
	$('.ui-datepicker-month').val(v);	
	$('.ui-datepicker-month').trigger("onchange");
}
function diff_droploc(a)
{
	a.checked?$("#dropoffDiv").show():
	$("#dropoffDiv").hide()
}
function diff_country(a)
{
//	alert($("#country_des_drop_id").val());
	a.checked?$("#country_des_drop_id").val(''):
	$("#country_des_drop_id").val($("#country_des_id").val());

}

var fullDate=new Date((new Date).getTime()+864E5);
$("#pickupdates").val(("0"+fullDate.getDate()).slice(-2)+"-"+("0"+(fullDate.getMonth()+1)).slice(-2)+"-"+fullDate.getFullYear());fullDate=new Date((new Date).getTime()+6912E5);$("#dropoffdates").val(("0"+fullDate.getDate()).slice(-2)+"-"+("0"+(fullDate.getMonth()+1)).slice(-2)+"-"+fullDate.getFullYear());

$( document ).ready(function() {		
		$("#age_driver18").change(function() {
			console.log("Start 3");
			if ($("#age_driver18").val() > 17) {
				$("#age_driver").val($("#age_driver18").val());
				console.log("Val "+$("#age_driver18").val());
				console.log("Val 3 "+$("#age_driver").val());
			}
		});	
		$("#age_driver66").change(function() {
			if ($("#age_driver66").val() > 65)
				$("#age_driver").val($("#age_driver66").val());
		});	
		$("#driver-age-range").click(function(){
	//		$("#driver-input-box").slideToggle("fast","swing", function(){  $("p").hide(); driver-age-range66
				$("#age_driver").val('30');
				$("#driver-age-range18").show();
//				$("#driver-input-box18").hide();
				$("#age_driver18").hide();
				$("#driver-age-range66").show();
//				$("#driver-input-box66").hide();
				$("#age_driver66").hide();
				$("#driver-age-range").removeClass( "age-groups" );
				if(!$("#driver-age-range").hasClass("age-groups25")){
					$("#driver-age-range").addClass("age-groups25");
				}			
				if(!$("#driver-age-range18").hasClass("age-groups")){
					$("#driver-age-range18").addClass("age-groups");
				}			
				if(!$("#driver-age-range66").hasClass("age-groups")){
					$("#driver-age-range66").addClass("age-groups");
				}			
				
	//		}); 
		}); 
		$("#driver-age-range18").click(function(){
			$("#driver-age-range18").hide();
//			$("#driver-input-box18").show();
			$("#age_driver18").show();
			$("#driver-age-range66").show();
//			$("#driver-input-box66").hide();
			$("#age_driver66").hide();
			$("#driver-age-range").removeClass( "age-groups25" );						
			if(!$("#driver-age-range").hasClass("age-groups")){
				$("#driver-age-range").addClass("age-groups");
			}
			$("#age_driver18").focus();		
		});
	
		$("#driver-age-range66").click(function(){
			$("#driver-age-range66").hide();
//			$("#driver-input-box66").show();
			$("#age_driver66").show();
			$("#driver-age-range18").show();
//			$("#driver-input-box18").hide();
			$("#age_driver18").hide();
			$("#driver-age-range").removeClass( "age-groups25" );		
			if(!$("#driver-age-range").hasClass("age-groups")){
				$("#driver-age-range").addClass("age-groups");
			}
			$("#age_driver66").focus();
		});
			
	$.widget( "custom.catcomplete", $.ui.autocomplete, {
    _create: function() {
      this._super();
      this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
    },
    _renderMenu: function( ul, items ) {
      var that = this,
        currentCategory = "";
		
      $.each( items, function( index, item ) {
        var li;
        if ( item.category != currentCategory ) {
          ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
          currentCategory = item.category;
		  cat = 1;
        }
		
        li = that._renderItemData( ul, item );
/*		if(item.code != null)
			li.html("<a><label>"+li.html().replace( new RegExp(item.q, "ig"), " <b><u>"+item.q+"</u></b>")+" <b>" + item.code + " </b> [" + item.CountryCode + "] </label><span class=\"flag flag-"+item.CountryCode.toLowerCase()+"\"></span> </a>");
		else
			li.html("<a><label>"+li.html().replace( new RegExp(item.q, "ig"), " <b><u>"+item.q+"</u></b>")+"  [" + item.CountryCode + "] </label><span class=\"flag flag-"+item.CountryCode.toLowerCase()+"\"></span> </a>");
*/	
		if(item.is_airport != null && item.is_airport == '1')
			li.html("<a><label >"+li.html()+" (" + item.code + ")</label><span class=\"flag flag-"+item.CountryCode.toLowerCase()+"\"></span> </a>");
		else
			li.html("<a><label class=\"city-"+item.is_airport+"\">"+li.html()+"</label><span class=\"flag flag-"+item.CountryCode.toLowerCase()+"\"></span> </a>");
	
      });
    },
	
  });
	$(function() {
		var cache = {};		
		$( ".autocomplete" ).catcomplete({			
		  delay: 0,
		  minLength: 0,
		  source: function( request, response ) {
			var term = request.term;
			var str = '';
			if($(this.element).attr('id') == 'drop_off_autocomplete')
				var str = '&loc_id='+$( "#pickupLocation" ).val();
			else{
				if ( term in cache ) {
				  response( cache[ term ] );
				  return;
				}
			}
			//$(".emptytext").hide();
			var new_element = $(this.element);
			new_element.addClass( "load" );
			$.ajax({				
			  //url: "http://gd.geobytes.com/AutoCompleteCity",
			  url: "/includes/location_dropdown.php?lan="+$("#lan").val()+'&pkid='+$("#country_des_drop_id").val()+str ,
			  dataType: "jsonp",
			  data: {
				q: request.term
			  },
			  success: function( data ) {
//				  alert(this.id);
				new_element.removeClass( "load" );
				cache[ term ] = data;
				response( data);
//				response( data.slice(0, 20));
			  },
			  complete : function( data ) {
				//$(".emptytext").show();
			  }
			});
		  },
		  
		  open: function(event, ui) {
//			  alert("test");
			  if($("#is_mobile").val() == 1)
			  	$('.ui-autocomplete').off('menufocus ').css('width','100%').css('height','100%').css('margin-top','10px');
			  else
			  	$('.ui-autocomplete').off('menufocus ');
		  },
		  select: function( event, ui ) {
			//alert($(this).attr('new_id'));		 
//			alert("test 2");
			if($(this).attr('new_id') == 'pick_up_autocomplete' || $(this).attr('id') == 'pick_up_autocomplete'){
//				$(this).prop('readonly', true);
				$("#diff_drop").prop('disabled', false);
				$( "#pickupLocation" ).val( ui.item.loc_id );
				$("#dropoffLocation").val(ui.item.loc_id);
				//$("#drop_off_autocomplete").val(ui.item.value);
				//document.main.country_des.value = ui.item.FK_COUNTRIES;
				//document.main.country_des_drop.value = ui.item.FK_COUNTRIES;
				$("#pick_up_autocomplete").val( ui.item.value).focus();
				$("#drop_off_autocomplete").val( ui.item.value);
				$("#show_dropdown").hide();
				$("#diff_drop").removeAttr("disabled");
				
			}else{
				$("#dropoffLocation").val(ui.item.loc_id);
				$("#drop_off_autocomplete").val( ui.item.value).focus();
				$("#show_dropdown").hide();
				//document.main.country_des_drop.value = ui.item.FK_COUNTRIES;
			}
			
		  }
		})
	  });
	country_sel();
	
		$( ".boxdropdown select" )
			.change(function () {
//				alert("Try 1");
				var str = "";
				var attr = $(this).parent().prev().attr('id');				
				// For some browsers, `attr` is undefined; for others,
				// `attr` is false.  Check for both.
				if (typeof attr !== typeof undefined && attr !== false) {
					$(this).parent().prev().children().html($(this).parent().prev().prev().html()+ ' '+$( this  ).find(":selected").text());
				}else{
					$(this).parent().prev().children().html($( this  ).find(":selected").text());
				}
			//console.log($(this).parent().prev().attr('id'));				
			//$( "div" ).text( str );
			//console.log(str);
		});
	
		$("#country-residence").click(function(){
			if ($("#country_user").val() != $("#country_user_hd").val())
				country_list_ajax();			
			$("#country-residence-input-box").slideToggle("fast","swing", function(){     	
		
			});
		});
		$("#currency-box").click(function(){
			if ($("#currency").val() != $("#currency_hd").val())
				currency_list_ajax();
			$("#currency-input-box").slideToggle("fast","swing", function(){     	
		
			});
		});			
	
	  
	});
	
	function aut_focus(id) {
//		alert("#"+id+" test 34");
//		$( "#"+id ).placeholder = '';
//		$( "#"+id).addClass( "load" );
		
//			$( ".autocomplete" ).autocomplete("search");
	}
	
	
	function emptythis(obj)
	{
		$("#"+obj).val('').focus();
		
	}
	
	function chg_currency(scur){
//		alert($("#currency_text").html()); //chg_currency 
//		alert($( "#currency option:selected" ).text());
		$("#currency_text").html($( "#currency option:selected" ).text());
		$("#currency_hd").val($( "#currency" ).val());
	}
	
	
	function chg_country(scur){
		$("#cntry_name").html($( "#country_user option:selected" ).text());
		$("#country_user_hd").val($( "#country_user" ).val());
	}	
	
	function currency_list_ajax() {	 
		$.ajax({
			type: "POST",
			url: "/includes/currency_list.php?lan=" + $("#lan").val()+"&cur="+$("#currency_hd").val(),
			error: function() {
				alert("Some error Please try again")
			},
			success: function(t) {				
				$("#currency-input-box").html(t);
				$("#currency_hd").prop("disabled", "disabled");
			}
		})
	}
	
	function country_list_ajax() {	 
		$.ajax({
			type: "POST",
			url: "/includes/country_list.php?lan=" + $("#lan").val()+"&country="+$("#country_user_hd").val(),
			error: function() {
				alert("Some error Please try again")
			},
			success: function(t) {				
				$("#country-residence-input-box").html(t);
				$("#country_user_hd").prop("disabled", "disabled");
			}
		})
	}	
	
/*$('a').bind('touchstart MozTouchDown',function(e) {
		var el = $(this);
		var link = el.attr('href');
		window.location = link;
	});*/
//Checking mobile device
var isMobile = false; //initiate as false
// device detection
if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent) 
    || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))) { 
   
    isMobile = true;
//	if(isMobile==true)
	if(screen.width <= 767)
	{
		$("#is_mobile").val(1); // .width(100)
//		alert($('#pick_up_autocomplete').width());
		$('#pick_up_autocomplete').removeAttr("style");
		$('#drop_off_autocomplete').removeAttr("style");
//		alert($('#pick_up_autocomplete').width());
		$('#pick_up_autocomplete').on('click', function() {
			$('#pickuplabeltop').css('display','block');
			$('#dropofflabeltop').css('display','none');
			$('#show_dropdown').show().attr('new_id','pick_up_autocomplete').css('height',$( window ).height());
			$('#autocomplete').focus().attr('new_id',$(this).attr('id'));
			$('#ui-id-1').show().css('overflow','scroll');
//			$(this).attr('readonly', true);
			
		});
		$('#drop_off_autocomplete').on('click', function() {
			$('#pickuplabeltop').css('display','none');
			$('#dropofflabeltop').css('display','block');
			$('#show_dropdown').show().attr('new_id','pick_up_autocomplete').css('height',$( window ).height());
			$('#autocomplete').focus().attr('new_id',$(this).attr('id'));
			$('#ui-id-1').show().css('overflow','scroll');
//			$(this).attr('readonly', true);
			
		});
		$('.closemobile').on('click', function() {
			//alert('hi');
			$('#show_dropdown').hide();
//			$("#pick_up_autocomplete").focus();
		});
		$('#show_dropdown').on('focusout', function() {
				//$(this).hide();
		});		

	}
}

function callList(id){
//	alert(screen.width); 
  if($("#country_des_drop_id").val() != 227){
	if(screen.width <= 767){ // isMobile==true
		$('#autocomplete').val('');
		$('#autocomplete').keydown();
	} else {
		$('#'+id).val('');
		$('#'+id).keydown();
	}
  }
}