// JavaScript Document
$(document).ready(function () {
    var countryValue = parseInt($("#pickcountry").val());
    var selectedPickCityId = parseInt($("#pickcity option:selected").val());
    if (countryValue != 0 || countryValue != "") {
       // callAJAX('pickcity', 'dropcity', countryValue, 'city', selectedPickCityId)
    }
   
    
    $("#searchForm").submit(function () {
        if ($('#countryName').val() != "" && $('#pickcity').val() != "" && $('#pickloc').val() != "" && ($('#drvAge').val() != "" && $('#drvAge').val() >= 18) && ($('#pickdate').val() != "" && $('#pickdate').val() != 'mm/dd/yyyy') && $('#dropcountry').val() != "" && $('#dropcity').val() != "" && $('#dropLoc').val() != "" && ($('#dropdate').val() != "" && $('#dropdate').val() != 'mm/dd/yyyy') && $('#countryName').val() != "" ) {
            var addval = "%ad%";
            var selectedText = $('#pickloc :selected').text();
            var dropSelectedText = $('#dropLoc :selected').text();
            $('#locationName').val(selectedText);
			if($('#dropLoc :selected').val()=="")
			{
				$('#dropLocationName').val(selectedText)
			}
            else
			{				
				$('#dropLocationName').val(dropSelectedText)
			}
			
            $('#pickcountry :selected').val($.base64Encode($('#pickcountry').val() + addval));
            $('#dropcountry :selected').val($.base64Encode($('#dropcountry').val() + addval));
            $('#pickcity :selected').val($.base64Encode($('#pickcity').val() + addval));
            $('#dropcity :selected').val($.base64Encode($('#dropcity').val() + addval));
            $('#pickloc :selected').val($.base64Encode($('#pickloc').val() + addval));
            $('#dropLoc :selected').val($.base64Encode($('#dropLoc').val() + addval));
            $('#pickdate').val($.base64Encode($('#pickdate').val() + addval));
            $('#dropdate').val($.base64Encode($('#dropdate').val() + addval));
            $('#picktime :selected').val($.base64Encode($('#picktime').val() + addval));
            $('#droptime :selected').val($.base64Encode($('#droptime').val() + addval));
            $('#drvAge').val($.base64Encode($('#drvAge').val() + addval));
            $('#locationName').val($.base64Encode($('#locationName').val()));
            $('#dropLocationName').val($.base64Encode($('#dropLocationName').val()));
            //$('#countryName').val($.base64Encode($('#countryName').val()));
            //$('#currency').val($.base64Encode($('#currency').val()));
            if ($('#reservation_id').val() != undefined || $('#reservation_id').val() != null) {
                $('#reservation_id').val($.base64Encode($('#reservation_id').val() + addval))
            }
				
           // showLoading()
        }
    });
/*
	$(".returndetail").hide();	
	
	$(".detailsame").click(function (){
		
		if(!$(this).attr('checked')) 
		 {
			
			$(".returndetail").show();
			$(".returndetail select").val('');
			if($('#pickloc').val()=="")
			{
				$(".returndetail select").attr('disabled','disabled');
			}
			else
			 {
				$(".returndetail select").attr('disabled','');
				changereturnboxvalues('pickcountry','dropcountry');
				changereturnboxvalues('pickcity','dropcity');
				changereturnboxvalues('pickloc','dropLoc');
			 }
			}
			 else
			  {
 					$(".returndetail").hide();		 
				}
	});
	
	*/
	
	
    $("#selectD").click(function () {
        if (!$(this).attr('checked')) {
            $("#dropcountry").attr('value', '');
            $("#dropcity").attr('value', '');
            $("#dropLoc").attr('value', '')
        } else {
            $("#dropcountry").val($("#pickcountry option:selected").val());
            $("#dropcity").val($("#pickcity option:selected").val());
            $("#dropLoc").val($("#pickloc option:selected").val())
        }
    });
    $('#changeSearch').click(function () {
        $('#reSearch').css("display", "block");
        $('#reSearch').css("visibility", "visible");
        $('#alldata').css("display", "none")
    });
    
    
    
    
    $("#bookingrequest").validate({
        rules: {
        /*   firstname: {
                required: true
            },
            lastname: {
                required: true
            },
            drvAge: {
                required: true,
                min: 18
            },
            email: {
                required: true,
                email: true
            },
            termCheck: {
                required: true
            }
            */
        },
        messages: {
            firstname: "Please enter first name",
            lastname: "Please enter last name",
            email: "Please enter a valid email ",
            termCheck: "Please checked it"
        }
    });
    
    $("#bookingrequest").submit(function () {
        if ($('#firstname').val() != "" && $('#lastname').val() != "" && $('#drvAge').val() != "" && ($('#email').val() != "" && $('#cFname').val() != "") && $('#cLastName').val() != "" && $('#cardType').val() != '' && $('#cardNumber').val() != '' && $('#cardCvn').val() != '' && $('#termCheck').attr('checked') == true) {
            showLoading()
        }
    })
/* Code to COR and  Price list selected */
$("#countryName").change(function(){
 var cor_name = $(this).val().split("_");
 var pickcountry_val =$('#pickcountry').val();

 var usa_pick_country_code = new Array();
  for(var i =170; i< 222; i++) 
	{
		usa_pick_country_code[i] = i;
	}
  if(cor_name[0]=='gb' && pickcountry_val==165)
	{
		 $("#currency").val(11);
	}
	else if((cor_name[0]=='us' && pickcountry_val in usa_pick_country_code) ||(cor_name[0]=='ca' && pickcountry_val==24))
	{
		$("#currency").val(12);
	}
	else 
	{
		 $("#currency").val(12);
	}
});
/* End COR */
});



function callAJAX(pick, drop, id, name, cityId) {
	
	 $.ajax({
        url: 'ajaxresponce.php?name=' + name + '&cid=' + id + "&cityID=" + cityId,
        beforeSend: function () {
            selectPickText = "<option>Please Wait ...</option>";
            if (pick != "") {
                jQuery('#' + pick).html(selectPickText);
                jQuery('#' + pick).attr("disabled", "disabled")
            }
          //  jQuery('#' + drop).html(selectPickText);
          //  jQuery('#' + drop).attr("disabled", "disabled")
        },
        success: function (data) {
            var responeValue = data;
            if (pick != "") {
                jQuery('#' + pick).html(responeValue);
                jQuery('#' + pick).removeAttr("disabled")
            }
            jQuery('#' + drop).html(responeValue);
          //  jQuery('#' + drop).removeAttr("disabled")
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {}
    })

	 
}
$(function () {
  
    var dates = $('#pickdate, #dropdate').datepicker({
        changeMonth: true,
        changeYear:true,
        dateFormat: 'yy/mm/dd',
        numberOfMonths: 2,
        showAnim: 'slideDown',
        minDate: 0,
        onSelect: function (selectedDate) {
            var option = this.id == "pickdate" ? "minDate" : "maxDate";
            var today = new Date();
            var SelectCalDay = new Date(selectedDate);
            if (this.id == "pickdate" && today.getDate() == SelectCalDay.getDate() && today.getMonth() == SelectCalDay.getMonth()) {
                var valueofcurrentDate = SelectCalDay.valueOf();
                AddedDate = valueofcurrentDate + (24 * 60 * 60 * 1000);
                var newDate = new Date(AddedDate);
                selectedDate = newDate.getFullYear() + '/' + (newDate.getMonth() + 1) + '/' + (newDate.getDate());
                $("#pickdate").val(selectedDate)
            }
            var instance = $(this).data("datepicker");
            var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
            dates.not(this).datepicker("option", option, date);
            if (this.id == "pickdate") {
                selectDate()
            }
        }
        
    });

	
    
 /*$("#dob").datepicker({
        dateFormat: 'yy-mm-dd',
        changeMonth: true,
        //changeYear: true,
        showAnim: 'slideDown'
        
    });
   */ 
    
    $("#cancelBooking").validate({
        rules: {
            term: {
                required: true
            }
        },
        messages: {
            term: "Please read the cancel term and checked this box"
        }
    })
});

function changecountry(selectBox, targetbox) {
	
		
	if($(".detailsame").attr("checked"))
	 {
	   //	 alert("checked");
	    jQuery('#' + targetbox).attr("selectedIndex", selectBox.selectedIndex);
	 }
	 else{
		 jQuery('#' + targetbox).attr("selectedIndex", selectBox.selectedIndex)
	 }
	  /*else if(selectBox.id=='pickloc')
	   {
		 
		  if($('#pickloc').val()=="")
		   {
			 //$(".returndetail select").val('');
			 //$(".returndetail select").attr('disabled','disabled');
		   }
		   else
		   {
				changereturnboxvalues('pickcountry','dropcountry');
				changereturnboxvalues('pickcity','dropcity');
				changereturnboxvalues('pickloc','dropLoc');
		   }
		}*/

		
}

function changereturnboxvalues(selectBox,targetbox) {
	
  /*alert(selectBox);
  alert(jQuery("#"+selectBox));
    jQuery('#' + targetbox).attr("selectedIndex", jQuery("#"+selectBox).selectedIndex);*/
	var selectedText = $('#'+selectBox+' :selected').text();
    $('#'+targetbox).val(selectedText)
	$('#'+targetbox).removeAttr('disabled');
 }


function filldrop()
 {	 	
	jQuery('#dropcountry').attr("selectedIndex", selectBox.selectedIndex);		
}

function selectDate() {
    var dateArray = new Array();
    var dropDate = "";
    var dateValue = "";
    var newDate = "";
    var month = "";
    dateValue = $('#pickdate').val();
    dateArray = dateValue.split('/');
    newDate = dateArray[1] + '/' + dateArray[2] + '/' + dateArray[0];
    var dropNextDate = new Date(newDate);
    dropNextDate.setDate(dropNextDate.getDate() + 1);
    month = dropNextDate.getMonth() + 1;
    dropDate = (dropNextDate.getFullYear()) + '/' + (("0" + month).slice(-2)) + "/" + (("0" + dropNextDate.getDate()).slice(-2));
    if (!isNaN(dropNextDate.getDate())) $('#dropdate').val(dropDate)
}
function showDiv(div1, div2, modal) {
    $(div1).jqm({
        modal: modal,
        trigger: div2,
        overlay: 30,
        overlayClass: 'whiteOverlay'
    }).jqDrag('.jqDrag');
    $(div1).jqmShow();
    $('div.jqmdX').hover(function () {
        $(this).addClass('jqmdXFocus')
    }, function () {
        $(this).removeClass('jqmdXFocus')
    }).focus(function () {
        this.hideFocus = true;
        $(this).addClass('jqmdXFocus')
    }).blur(function () {
        $(this).removeClass('jqmdXFocus')
    })
}
function getLocationText(pickloc) {
	var selectedText = $('#pickloc :selected').text();
    $('#locationName').val(selectedText)
}

function filterSearch(className, groupId) {
    if ($('#' + groupId).attr('checked') == true) {
        $('.' + className).show()
    }
    if ($('#' + groupId).attr('checked') == false) {
        $('.' + className).hide()
    }
}
function filterSearchOther(className, groupId) {
    if ($('#' + groupId).attr('checked') == true) {
        $('.' + className).hide()
    }
    if ($('#' + groupId).attr('checked') == false) {
        $('div .' + className).show()
    }
	
}
function showLoading() {
    ProgressImage = $('#progress_image').attr('src');
    //$("#outer").hide();
   // $("#outer").addClass("hideOuter");
    $("#progress").show();
    setTimeout(function () {
        $('#progress_image').attr('src', ProgressImage), 200
    })
}
function changePrice(selectid, divPriceId, counter, rentalPlan, numOfdays,maxpricetotal) {
	
	
    var totalPrice = "";
    var roundedNumber = "";
    var maxAmount = "";
    var netAmount = "";
    var totalVehiclePrice = "";
    var depositAmount1_cost = "";
    var depositAmount2_cost = "";
    var depositAmount_cost = "";
    var carBalanceCost = "";
    var rettypedays = 1;
	var extraChagesAmount ="";
	var extraChargesPrice=0;
	var selected_field_value ="";
	maxpricetotal =Number(maxpricetotal);
    if (rentalPlan != 'per day') {
            numOfdays = 1
    }
    var additional_name =$('#'+selectid).attr('title');
	
    var selectvalue = Number($('#' + selectid).val());
	
	if(additional_name=='1st Additional Driver' && selectvalue >0 )
	{
		$('#AddDrvAgeText').show();
		$('#AddDrvAge').show();
		
	}
	else if(additional_name=='1st Additional Driver' && selectvalue ==0 )
	{
		$('#AddDrvAgeText').hide();
		$('#AddDrvAge').hide();
	}

    var totalRecord = $("#totalExtra").val();
	
    var price = Number($("#" + divPriceId).attr('name'));

    totalPrice = selectvalue * price*numOfdays;
	if(maxpricetotal !=0 && (price* numOfdays) > maxpricetotal)
	{
		totalPrice =maxpricetotal*selectvalue;
	}
    depositAmount2_cost = selectvalue * price;
    depositAmount2_cost = roundNumber(depositAmount2_cost, 2);
    localAmount = roundNumber(totalPrice, 2);
    $("#" + divPriceId).text(localAmount);


	$("#extraCharges_"+counter).val(localAmount);
	$("#selectedValue_"+counter).val(selectvalue);


    $("#extraLocalPrice_" + counter).val(localAmount);
    var maxprice = $("#extraMaxPrice_" + counter).attr('name');
    maxprice = selectvalue * maxprice;
    maxAmount = roundNumber(maxprice, 2);
    $("#extraMaxPrice_" + counter).val(maxAmount);
    var netprice = $("#extraNetPrice_" + counter).attr('name');
    netprice = selectvalue * netprice;
    netAmount = roundNumber(netprice, 2);
    $("#extraNetPrice_" + counter).val(netAmount);
    totalVehiclePrice = Number($('#totalVehiclePrice').attr('name'));
    depositAmount1_cost = Number($('#depositAmount1_cost').attr('name'));
    depositAmount_cost = Number($('#depositAmount_cost').attr('name'));
    carBalanceCost = Number($('#carBalanceCost').attr('name'));
	

    for (var i = 0; i < totalRecord; i++) {
        rentType = $('#forWhat_' + i).val();
        if (rentType == 'per day') {
            rettypedays = numOfdays
        } else {
            rettypedays = 1
        }
		selected_field_value = $("#selectedValue_"+i).val();
        maxpriceNew = Number($("#extraMaxPrice_" + i).val() * rettypedays);
		extraTotalMaxPrice = Number($("#extraTotalMaxPrice_" + i).val());
		extraChagesAmount = Number($("#extraCharges_"+i).val());
		
       // localpriceNew = Number($("#extraLocalPrice_" + i).val() * rettypedays);
	    localpriceNew = Number($("#extraLocalPrice_" + i).val());
        netPriceNew = Number($("#extraNetPrice_" + i).val() * rettypedays);
		
		if(extraTotalMaxPrice !=0 && localpriceNew > extraTotalMaxPrice)
	   {
		localpriceNew =extraTotalMaxPrice*selected_field_value;
		
	   }
	   
	   if(extraTotalMaxPrice !=0 && maxpriceNew > extraTotalMaxPrice)
		{
		   maxpriceNew =extraTotalMaxPrice*selected_field_value;
		}
		extraChargesPrice =(extraChargesPrice+extraChagesAmount);

        totalVehiclePrice = Number(totalVehiclePrice + localpriceNew);
		
        depositAmount1_cost = Number(depositAmount1_cost + netPriceNew);
        depositAmount_cost = Number(depositAmount_cost + netPriceNew);
        carBalanceCost = Number(carBalanceCost + maxpriceNew);
		
    }
		
    totalVehiclePrice = roundNumber(totalVehiclePrice, 2);
    depositAmount1_cost = roundNumber(depositAmount1_cost, 2);
    depositAmount_cost = roundNumber(depositAmount_cost, 2);
    carBalanceCost = roundNumber(carBalanceCost, 2);
    $('#totalVehiclePrice').text(totalVehiclePrice);
    //$('#depositAmount1_cost').text(depositAmount1_cost);
    $('#depositAmount_cost').text(depositAmount_cost);
    $('#carBalanceCost').text(carBalanceCost);
    $('#totalPrice').val(totalVehiclePrice);
    $('#depositAmount2_cost').val(totalVehiclePrice);
    $('#depositAmount1').val(depositAmount1_cost);
    $('#depositAmount').val(depositAmount_cost);
    $('#carBalance').val(carBalanceCost);
    currencyRate = $('#execur').val();
    convertedCurrency = Number(currencyRate * carBalanceCost);
    $('#exchangeCurrency').text(convertedCurrency);
    $('#basicAmount').text(carBalanceCost);
	$('#othercharges').text(roundNumber(extraChargesPrice,2));
}
function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    num_re = result.toString();
    if (num_re.indexOf(".") == -1) {
        num_re = num_re + '.00'
    }
    return num_re
}
function clearText(field){

    if (field.defaultValue == field.value) field.value = '';
    else if (field.value == '') field.value = field.defaultValue;

}

