$(document).ready( function () {

	// initialize the forms
	$('form').filter( function () {
		var formId = $('select.locations').val();
		if (formId == 'Select a location') {
			formId = $('select.locations').children('.default').attr('value');
			$('select.locations').val(formId);
		}
		return $(this).attr('id') !== formId;												
	}).hide();


	// fix css background pngs in IE6
	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
	if (jQuery.browser.msie && (ie55 || ie6)) {

		// select all img elements with pngs and add pngfix class
		$("img[src$=.png]").each(function() {
				$(this).addClass("pngfix");
		});
		// select all elements with png bg and add pngfix class
		$("*").each(function(){
			var bgIMG = jQuery(this).css('background-image');
			if(bgIMG.indexOf(".png")!=-1) {
				$(this).addClass("pngfix");
			}
		});
		// run the png fix
		DD_belatedPNG.fix('.pngfix');
	}
	
	// initialize the datepicker
	$('.datepicker').datepicker({
		dateFormat: 'dd/mm/y',
		constrainInput: true,
		numberOfMonths: 2,
		duration: 10,
		minDate: +1
	});
	
	// initialize the tabs
	$('ul[id=trucks]').hide();
	$('.tabs a').click( function (evt) {
		evt.preventDefault();
		var tab = $(this).attr('rel');
		$('.tabs a').toggleClass('active');
		$('ul.locations').hide();
		$('ul[id=' + tab + ']').show();												
	});
	
	// create the airport only locations dropdown 
	$('<select></select>').attr({
		'id': 'airportLocations',
		'class': 'locations'
	}).css('display', 'none').insertAfter('#allLocations');
	$('<option></option>').attr('value', 'Select a location').text('Select a location').appendTo('#airportLocations');
	
	//add the airports to the dropdown
	$('#allLocations option.airport').each(function (index) {
		var val = $(this).attr('value');
		var txt = $(this).text();
		if($(this).hasClass('default')) {
			$('<option></option>')
				.attr({
					'value': val,
					'class': 'default'
				})
				.text(txt).appendTo('#airportLocations');
		} else {
			$('<option></option>')
				.attr('value', val)
				.text(txt).appendTo('#airportLocations');
		}
	});
	
	// initialize the checkbox toggle for the dropdowns
	$('#airportonly').click(toggleAirportLoc);
	
	// link the location switching to the dropdown
	$('#airportLocations').change(function () {
		toggleLocationForm(this);
    });

    $('#allLocations').change(function () {
        toggleLocationForm(this);
    });

	$('.top10loc a').click( function (evt) {
		evt.preventDefault();
		$('#airportonly').attr('checked', false);
		toggleAirportLoc();
		var loc = $(this).attr('href').slice(1);
		topTenLoc(loc);
	});
	
	// make sure the dropdown state matches the checkbox
	toggleAirportLoc();
	
		
});

// function that toggles the airport locations dropdown
function toggleAirportLoc() {
    var n = $('#airportonly:checked').length;  
	if(n > 0) {
		$('#allLocations').hide();
		$('#airportLocations').show();
		toggleLocationForm($('#airportLocations'));
	} else {
		$('#airportLocations').hide();
		$('#allLocations').show();
		toggleLocationForm($('#allLocations'));
	}
}

// function that toggles the location forms
function toggleLocationForm(that) {
	var formId = $(that).val();
	if (formId == 'Select a location') {
		formId = $('select.locations').children('.default').attr('value');
		$('select.locations').val(formId);
	}
	$('form').hide();
	$('form#' + formId).show();

	//return to different location
	var isChecked = $("#chkReturnSameLocation").attr("checked");	
	if (!isChecked) {
	    fnShowHideLocationsReturn();    
	}
}

// function that toggles the locations when top 10 link is clicked
function topTenLoc(formId) {
	$('form').hide();
	$('form#' + formId).show();
	$('select.locations').val(formId);
}

function popUp(URL) {
		day = new Date();
		id = day.getTime();
		eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=550,height=450');");
		}
 function locationVerified(locationCode, locationType) {
			 var _url ="";
			 if(getParameterByName('ARCIATA') != ""){
			_url = "&ARCIATA="+getParameterByName('ARCIATA');
			}
             var locationCode = locationCode;
             if (flowPath == 'FLOWPATH_RESERVATION') {
				 //http://www.avis.com.au/car-rental/reservation/initialize-reservation.ac?ACTION=1&COUNTRY=AU&COUPON=TPPA022
                //http://www.avis.com.au/car-rental/reservation/initialize-reservation.ac?PICKUP_LOCATION_CODE=SYD
				// document.location.href = "http://www.avis.com.au/car-rental/location/search.ac?STATION_MNE_CODE=" + locationCode + "&LOCATION_TYPE=" + locationType;
				document.location.href ="http://www.avis.com.au/car-rental/reservation/initialize-reservation.ac?PICKUP_LOCATION_CODE="+locationCode+_url
                 var sameAsDropOff = 'true';
                 if (sameAsDropOff == 'true') {
                     //document.location.href = "http://www.avis.com.au/car-rental/reservation/start-reservation.ac?resForm.pickUpLocation=" + locationCode + "&ISSAMELOCATION=TRUE";
					 document.location.href ="http://www.avis.com.au/car-rental/reservation/initialize-reservation.ac?PICKUP_LOCATION_CODE="+locationCode+_url
                 }
             } else {
                // document.location.href = "http://www.avis.com.au/car-rental/reservation/start-reservation.ac?resForm.pickUpLocation=" + locationCode + "&ISSAMELOCATION=TRUE";
				document.location.href ="http://www.avis.com.au/car-rental/reservation/initialize-reservation.ac?PICKUP_LOCATION_CODE="+locationCode+_url
             }
         } 
		 
function reservationLink(COUPON)
{
	var _url = "http://www.avis.com.au/car-rental/reservation/initialize-reservation.ac?ACTION=1&COUNTRY=AU";
	if (COUPON != "") {
	    _url = _url + "&COUPON=" + COUPON;
    }
    if(getParameterByName('ARCIATA') != ""){
        _url = _url + "&ARCIATA=" + getParameterByName('ARCIATA');
	}
	document.location.href =_url;
}

function getParameterByName( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function GetFormId() {
    var formId = "";
    $("form").each(function () {
        var v = $(this).is(":visible");
        if (v == true) {            
            //console.log($(this).attr("id"));
            formId = $(this).attr("id");
        }
    });

    return formId;
}

function fnShowHideLocationsReturn() {
    var formId = GetFormId();
    var isChecked = $("#chkReturnSameLocation").attr("checked");
    var returnLocation = $("#returnLocation" + formId);
    
    returnLocation.hide();
    if (!isChecked) {
        returnLocation.show();
    }

    $("#allStatesReturn" + formId + " option[value='" + DEFAULT_LOCATIONSTORESTATE + "']").attr("selected", "selected");

    populateDefaultStoreReturn();   

    $("#allLocationsReturn" + formId + " option[locationcode='" + $("#allLocations").val() + "']").attr("selected", "selected");

    populateStoreDetailsReturn();
    var sp = $('<span></span>').addClass('ie7_fix');
    $('.info_wrap').append(sp);
    $('.ie7_fix').remove();
    return true;
}

function populateDefaultStoreReturn() {
    var formId = GetFormId();   
    var isShowAirportOnly = $("#airportonly").attr("checked");    
    var selAllLocationsReturn = $("#allLocationsReturn" + formId);      
    var selectedStateReturn = $("#allStatesReturn" + formId).val();

   // console.log(selectedStateReturn);

    selAllLocationsReturn.empty();

    var allLocationsOptions = "";    

    var ctr = 0;
    while (true) {
        var location = STORELOCATIONS[ctr + ""];

        if (location == null) { break; }
        
       // console.log('LocationStoreID ' + location.LocationStoreID + ', LocationCategoryID' + location.LocationCategoryID);

        var locationName = location.Name;
        var locationId = location.LocationStoreID;
        if (location.State == selectedStateReturn) {
            var isIncluded = false;
            if (isShowAirportOnly) {
                if (location.LocationCategoryID == 1) {
                    isIncluded = true;
                }
            } else {
                //if (location.LocationCategoryID == 2) {
                isIncluded = true;
                //}
            }
            if (isIncluded) {
                allLocationsOptions += "<option locationcode='" + location.LocationCode + "' value='" + locationId + "' class=''>" + locationName + "</option>";
            }
        }
       // console.log(location.LocationCode);
        ctr++;
    }
    selAllLocationsReturn.html("<option value='' class=''>Select a location</option>" + allLocationsOptions);    
    
}

function populateStoreDetailsReturn() {
    var formId = GetFormId();
    var isChecked = $("#chkReturnSameLocation").attr("checked");

    if (!isChecked) {
        
        var ctr = 0;
        var selectedLocationStore = null;

        while (true) {
            var selectedLocationStoreId = $("#allLocationsReturn" + formId).val();
           
            var location = STORELOCATIONS[ctr + ""];
            if (location == null) { break; }
            if (location.LocationStoreID == selectedLocationStoreId) {
                selectedLocationStore = location;               
                break;
            }
            ctr++;
        }

        if (selectedLocationStore != null) {
            $("#frmReservationLocationHeadingReturn" + formId).text(selectedLocationStore.Name + " - " + selectedLocationStore.LocationCode);
            var locationAddress = "";
            if ((selectedLocationStore.AddressLine1 != "") && (selectedLocationStore.AddressLine1 != null)) {
                locationAddress += selectedLocationStore.AddressLine1 + "<br />";
            } else {
                locationAddress += selectedLocationStore.Terminals + "<br />";
            }
            locationAddress += selectedLocationStore.Suburb + ", " + selectedLocationStore.State + ", " + selectedLocationStore.PostCode + ", " + selectedLocationStore.CountryCode + "<br />";
            $("#frmReservationLocationAddressReturn" + formId).html(locationAddress);

            $("#frmReservationLocationHoursOfOperationReturn" + formId).html(selectedLocationStore.HoursOfOperation);
            $("#frmReservationLocationCodeReturn" + formId).attr("value", selectedLocationStore.LocationCode);
            //alert('populateStoreDetailsReturn: ' + $("#frmReservationLocationCodeReturn" + formId).val());
            //$("#frmReservation").show();
        } else {
            //$("#returnLocation").hide();
        }
    }

}


