var mousepos = [0,0];
var loginfocus = false, userprefsfocus = false, logoutfocus = false;

$(function() {
    // fix the default select for dropdownlist
    $("option:selected").each(function() {
        $(this).parent().val(this.value);
    });

    // track mouse position
    $(document.body).mousemove(function(e) { mousepos = [e.pageX, e.pageY]; });
    // if focus, do not collapse the pane
    $("#login input").focus(function() { loginfocus = true; }).blur(function() { loginfocus = false; });
    $("#userprefs select").focus(function() { userprefsfocus = true; }).blur(function() { userprefsfocus = false; });
    $("#usersettings .logintrigger").mouseover(function() {
        $("#usersettings").slideUp("fast", function() {
            $("#login").slideDown("fast");
            $("#logo1").css("opacity", 0.4);
            loginfocus = false;
            window.setTimeout("hideLoginPane()", 1000);
        });
    });
    $("#usersettings .logouttrigger").mouseover(function() {
        $("#logout").slideDown("fast");
        $("#logo1").css("opacity", 0.4);
        logoutfocus = false;
        window.setTimeout("hideLogoutPane()", 1000);
    });
    $("#usersettings .userprefstrigger").mouseover(function() {
        $("#usersettings").slideUp("fast", function() {
            $("#userprefs").slideDown("fast");
            $("#logo1").css("opacity", 0.4);
            userprefsfocus = false;
            window.setTimeout("hideUserPrefsPane()", 1000);
        });
    });

    $("ul.pane").each(function() {
        var expand = $(this).attr("expand");
        if (typeof expand == "undefined") expand = imageUrl + "iocn5.gif";
        var collapse = $(this).attr("collapse");
        if (typeof collapse == "undefined") collapse = imageUrl + "icon4.gif";
        $(this).attr("expand", expand);
        $(this).attr("collapse", collapse);

        $("li.tit", this).each(function() {
            var $content = $(this).next(".main_content").children("div:first");
            var $tit = $(this).children("div:first");
            if ($content.css("display") != "none")
                $tit.css("backgroundImage", "url('" + expand + "')");
            else
                $tit.css("backgroundImage", "url('" + collapse + "')");

            $(this).click(function() {
                var $pane = $(this);
                var $content = $pane.next(".main_content").children("div:first");
                if ($content.css("display") != "none") {
                    var collapse = $pane.parent().attr("collapse");
                    $pane.children("div:first").css("backgroundImage", "url('" + collapse + "')");
                } else {
                    var expand = $pane.parent().attr("expand");
                    $pane.children("div:first").css("backgroundImage", "url('" + expand + "')");
                }

                $content.slideToggle("fast");

                var onshow = $pane.attr("onshow");
                var onhide = $pane.attr("onhide");
                if (onshow && $content.css("display") != "none")
                    eval(onshow + "()");
                if (onhide && $content.css("display") == "none")
                    eval(onhide + "()");
            });
        });
    });
});

function showPane(pane, raiseEvent) {
    var $content = $(pane).next(".main_content").children("div:first");
    if ($content.css("display") == "none") {
        var expand = $(pane).parent().attr("expand");
        $(pane).children("div:first").css("backgroundImage", "url('" + expand + "')");
        $content.slideToggle("fast");
        if (raiseEvent) {
            var onshow = $(pane).attr("onshow");
            if (onshow) eval(onshow + "()");
        }
    }
}

function hidePane(pane, raiseEvent) {
    var $content = $(pane).next(".main_content").children("div:first");
    if ($content.css("display") != "none") {
        var collapse = $(pane).parent().attr("collapse");
        $(pane).children("div:first").css("backgroundImage", "url('" + collapse + "')");
        $content.slideToggle("fast");
        if (raiseEvent) {
            var onhide = $(pane).attr("onhide");
            if (onhide) eval(onhide + "()");
        }
    }
}

function hideLoginPane() {
	if (!loginfocus) {
	    var el = $("#login");
		var pos = findPos(el[0]);
		if (mousepos[0] - pos[0] < 0 || mousepos[0] - pos[0] > el.width() || mousepos[1] - pos[1] > el.height()) {
			el.slideUp("fast", function() {
				$("#usersettings").slideDown("fast");
				$("#logo1").css("opacity", 1);
			});
			return;
		}
	}
	window.setTimeout("hideLoginPane()", 1000);
}
function hideLogoutPane() {
    var el = $("#logout");
    var pos = findPos(el[0]);
    if (mousepos[0] - pos[0] < 0 || mousepos[0] - pos[0] > el.width() || mousepos[1] - pos[1] > el.height()) {
		el.slideUp("fast");
		$("#logo1").css("opacity", 1);
		return;
	}
	window.setTimeout("hideLogoutPane()", 1000);
}
function hideUserPrefsPane() {
	if (!userprefsfocus) {
	    var el = $("#userprefs");
		var pos = findPos(el[0]);
		if (mousepos[0] - pos[0] < 0 || mousepos[0] - pos[0] > el.width() || mousepos[1] - pos[1] > el.height()) {
			el.slideUp("fast", function() {
			    $("#usersettings").slideDown("fast");
				$("#logo1").css("opacity", 1);
			});
			return;
		}
	}
	window.setTimeout("hideUserPrefsPane()", 1000);
}
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	
	return [curleft,curtop];
}

function BookerDetailsLogin() {
    if($("#Has_BookerAccount")[0].checked) {
        if($("#BookerDetails_UserName").val() != "") {
            $.ajax({
                url: "back/login.aspx",
                data: "LoginUserName=" + encodeURIComponent($("#BookerDetails_UserName").val()) + "&LoginUserPassWord=" + encodeURIComponent($("#BookerDetails_Password").val()),
                async: false,
                success: function(data) {
                    try
                    {   // copied from the module 1
                        var intStartPos	= data.indexOf("<AccountID>");
	                    var intEndPos	= data.indexOf("</AccountID>");
	                    var intStartPosType	= data.indexOf("<Type>");
	                    var intEndPosType	= data.indexOf("</Type>");
	                    if(intStartPos > 0 && intEndPos > 0)
	                    {	
		                    var strAccountID	= data.substring(intStartPos + 11, intEndPos);
		                    var url = window.location.href;
		                    if (url.indexOf('#') == url.length - 1) url = url.substring(0, url.length - 1);
		                    var posAccount = url.search("account=");
		                    if(posAccount == -1)
		                    posAccount = url.search("account=");
		                    var strRedirect = "";
                            if(posAccount != -1)
	                            url = url.substring(0,posAccount-1);
    	                        
		                    strRedirect += "account=" + strAccountID;
var strType = data.substring(intStartPosType + 6, intEndPosType);
if (strType == 'User')
{
if (strAccountID == '11924' || strAccountID == '15822' || strAccountID == '13790')
{
strRedirect += "&module=1290";
}
else
{
strRedirect += "&module=3";
}
strRedirect += "&language=" + language;
}
                            document.location = url + (url.indexOf("?") >= 0 ? "&" : "?") + strRedirect;
                        } else 
                            loginFailed();
                    } catch(e) {
                        loginFailed();
                    }
                },
                error: loginFailed
            });
        }
        else {
            alert(LOGIN_FAILS);
        }
    }
}

function login() {
    $.ajax({
        url: "back/login.aspx",
        data: "LoginUserName=" + encodeURIComponent($("#LoginUserName").val()) + "&LoginUserPassWord=" + encodeURIComponent($("#LoginUserPassWord").val()),
        async: false,
        success: function(data) {
            try
            {   // copied from the module 1
                var intStartPos	= data.indexOf("<AccountID>");
	            var intEndPos	= data.indexOf("</AccountID>");
	            var intStartPosType	= data.indexOf("<Type>");
	            var intEndPosType	= data.indexOf("</Type>");
	            if(intStartPos > 0 && intEndPos > 0)
	            {	
		            var strAccountID = data.substring(intStartPos + 11, intEndPos);
		            var url = window.location.href;
		            if (url.indexOf('#') == url.length - 1) url = url.substring(0, url.length - 1);
		            var strRedirect = "";
		            var posAccount = url.search("account=");
		            if(posAccount == -1)
		                posAccount = url.search("account=");
                    if(posAccount != -1)
	                    url = url.substring(0,posAccount-1);
	                    
		            strRedirect += "account=" + strAccountID;
var strType = data.substring(intStartPosType + 6, intEndPosType);
if (strType == 'User')
{
if (strAccountID == '11924' || strAccountID == '15822' || strAccountID == '13790')
{
strRedirect += "&module=1290";
}
else
{
strRedirect += "&module=3";
}
strRedirect += "&language=" + language;
}
                    document.location = url + (url.indexOf("?") >= 0 ? "&" : "?") + strRedirect;
                } else
                    loginFailed();
            } catch(e) {
                loginFailed();
            }
        },
        error: loginFailed
    });
}
function loginFailed() {
    alert(LOGIN_FAILS);
    $("#LoginUserPassWord").val("");
    $("#LoginUserName").focus();
}
function logout() { // copied from the module 1
    // remove userXML
    showWaitingPage();
    $.ajax({
        url: "back/ws.aspx?method=logout",
        async: false
    });

    var url = window.location.href;
    if (url.indexOf('#') == url.length - 1) url = url.substring(0, url.length - 1);
    var strRedirect = "";
	var posAccount = url.search("account=");
	if(posAccount == -1)
	    posAccount = url.search("account=");
	if(posAccount != -1)
	    url = url.substring(0,posAccount-1);
	    
	document.location = url + (url.indexOf("?") >= 0 ? "&" : "?") + "account=0";
}
function submitIfEnter(event, submitFunc)   // copied from the module 1
{
    var intKeynum;
	if(window.event)
		intKeynum = event.keyCode;
	else if(event.which)
		intKeynum = event.which;
	
	if(intKeynum == 13) submitFunc();
}

function customRange(input) {
    return {
           minDate: (input.id == "dropoffdate" ? max($("#pickupdate").datepicker("getDate"), new Date()) : new Date()),
           maxDate: (input.id == "pickupdate" ? null : null)
           //maxDate: (input.id == "pickupdate" ? $("#dropoffdate").datepicker("getDate") : null)
           };
}
function setLocalizedDateTime(id) {
    // convert date time YYYY-MM-DD to the localized format
    var date = parseDate($("#" + id + "_DT").val());
    var inst = $.datepicker._getInst(document.getElementById(id));
    $.datepicker._setDate(inst, date);
}
function setDateTime(date, input) {
    $("#" + $(input).attr("id") + "_DT").val(pad(input.selectedYear) + "-" + pad(input.selectedMonth + 1) + "-" + pad(input.selectedDay));
    if ($(input).attr("id") == "pickupdate") {
        // add 7 days
        var date = new Date(input.selectedYear, input.selectedMonth, input.selectedDay);
        date.setDate(date.getDate() + 7);
        $("#dropoffdate_DT").val(pad(date.getFullYear()) + "-" + pad(date.getMonth() + 1) + "-" + pad(date.getDate()));
        setLocalizedDateTime("dropoffdate");
    }
    //checkDateRange();
}
function parseDate(dateStr) {
    var date = dateStr.split('-');
    return new Date(parseInt(date[0], 10), parseInt(date[1], 10) - 1, parseInt(date[2], 10));
}
function pad(i) {
    return (i < 10 ? "0" + i : i);
}
function checkDateRange() {
    var date1 = $("#pickupdate").datepicker("getDate");
    var date2 = $("#dropoffdate").datepicker("getDate");
    var hour1 = $("#pickuptime").val().split(":");
    var hour2 = $("#dropofftime").val().split(":");
    try {
       date1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate(), parseInt(hour1[0], 10), parseInt(hour1[1], 10));
       date2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate(), parseInt(hour2[0], 10), parseInt(hour2[1], 10));
       if (date1 >= date2) {
          alert(TIMEONEQUALDATE_ERR);
          return false;
       }
    } catch(e) {
        return false;
    }
    
    return true;
}
function parseLocation(data) {
    var groupByTypes = [];
    $(data).find("Locations").children("Location").each(function() {
        var type = $(this).children("Type").text();
        if (typeof groupByTypes[type] == "undefined")
            groupByTypes[type] = [];
        var group = groupByTypes[type];
        group[group.length] = this;
    });

    var parsed = [];
    insertLocationGroup(parsed, groupByTypes, "airport", AIRPORT_TYPE);
    insertLocationGroup(parsed, groupByTypes, "city", CITY_TYPE);
    insertLocationGroup(parsed, groupByTypes, "province", REGION_TYPE);
    insertLocationGroup(parsed, groupByTypes, "country", COUNTRY_TYPE);

    return parsed;
}
function insertLocationGroup(parsed, group, groupName, groupText) {
    if (typeof group[groupName] == "undefined") return;

    parsed[parsed.length] = {
        data: [groupText, 0, groupText],
        value: 0,
        result: groupText
    };
    
    var temp = [];
    for(var i = 0; i < group[groupName].length; i++) {
        var $row = $(group[groupName][i]);
        var id = $row.children("ID").text();
        var desc = trim($row.children("FullDescription").text());
        temp[temp.length] = {
           data: [desc, id, $row],
           value: id,
           result: desc
        };
    }
    
    // sort
    for(var i = 0; i < temp.length; i++) {
        var k = i;
        for(var j = i + 1; j < temp.length; j++) {
            if (temp[k].result > temp[j].result) k = j;
        }
        parsed[parsed.length] = temp[k];
        temp[k] = temp[i];
    }
}
function formatLocation(row) {
    if (row[1] == 0)
        return "<div class=\"ac_group\">" + row[0] + "</div>";
    else
        return "<div class=\"ac_subitem\">" + row[0] + "</div>";
}

function parseISODate(date) {
    var dateParts = date.split(/[^\d]/);
    return new Date(parseInt(dateParts[0], 10), parseInt(dateParts[1], 10) - 1, parseInt(dateParts[2], 10), parseInt(dateParts[3], 10), parseInt(dateParts[4], 10), parseInt(dateParts[5], 10));
}
function submitStep1() {
    var err = [];
    if (isEmpty("pickuplocation") || isEmpty("pickuplocationId") ||
        $("#pickuplocation").val() != $("#location_ac").val()) {
        err[err.length] = PICKUPLOCATION_ERR;
    }
    if (isEmpty("pickupdate_DT")) err[err.length] = PICKUPDATE_ERR;
    if (isEmpty("dropoffdate_DT")) err[err.length] = RETURNDATE_ERR;
    if (isEmpty("pickuptime")) err[err.length] = PICKUPTIME_ERR;
    if (isEmpty("dropofftime")) err[err.length] = RETURNTIME_ERR;
    
    if (err.length) {
        alert(err.join("\n"));
        return false;
    }
    
    if (!checkDateRange()) return false;
    
    if (typeof landings["l" + $("#pickuplocationId").val()] != "undefined") {
        window.location = landings["l" + $("#pickuplocationId").val()];
        return;
    }
    
    /*if ($("#pickuplocationType").val() == "country") {
        // if the location type is country, redirect to the dictionary page
      if ($("#languagecode").val() == 'en') var land = '/Carrental/' + $("#pickuplocation").val();
      if ($("#languagecode").val() == 'nl') var land = '/Autoverhuur/' + $("#pickuplocation").val();
      i = land.indexOf ('(');
      land = land.substring(0,i);
      window.location = land;
        return;
    }*/
    
    showWaitingPage();
    
    $("#searchForm")[0].submit();
    
    return true;
}
function isEmpty(id) {
    return trim($("#" + id).val()) == "";
}
function trim(s) {
    return s.replace(/^\s+|\s+$/g, "");
}
function min(v1, v2) {
    return (v1 <= v2 ? v1 : v2);
}
function max(v1, v2) {
    return (v1 >= v2 ? v1 : v2);
}

// $.inArray()
function findItem(collection, fn) {
    for(var i = 0; i < collection.length; i++) {
        if (fn(collection[i]))
            return collection[i];
    }
    
    return null;
}

function setEnv(country, lang, currency) {
    var q = "";
    if (country) q += "setCountry=" + country + "&";
    if (lang) q += "setLang=" + lang + "&";
    if (currency) q += "setCurrency=" + currency + "&";
    
    showWaitingPage();
    $.ajax({
        url: "back/setLang.aspx",
        data: q.substring(0, q.length - 1),
        cache: false,
        success: function(data) {
            if (data != "ok") {
                hideWaitingPage();
                return true;
            }
            // prevent caching
            if (window.location.pathname == '/default.aspx')
            {
							var newLocation = window.location.protocol + "//" + window.location.host + window.location.pathname;
							newLocation += "?module=" + moduleId + "&language=" + lang;
							if ($("#pickuplocationId").val() != "") {
									newLocation += "&locationId=" + $("#pickuplocationId").val();
							}
							newLocation += "&pickupdate_DT=" + $("#pickupdate_DT").val();
							newLocation += "&pickuptime=" + $("#pickuptime").val();
							newLocation += "&dropoffdate_DT=" + $("#dropoffdate_DT").val();
							newLocation += "&dropofftime=" + $("#dropofftime").val();
							if ($("#drivercode").val() != "") {
									newLocation += "&drivercode=" + $("#drivercode").val();
							}
							navigateWithReferrer(newLocation);
						}
						else
						{
							var newLocation = window.location.href;
							newLocation = removeParamFromURL(newLocation,"language");
							var language = "language=" + lang;
							window.location.href = newLocation + (newLocation.indexOf("?") >= 0 ? "&" : "?") + language;
						}
        }
    });
}

function removeParamFromURL(URL,param)
{
	URL = String(URL);
	var regex = new RegExp( "\\?" + param + "=[^&]*&?", "gi");
	URL = URL.replace(regex,'?');
	regex = new RegExp( "\\&" + param + "=[^&]*&?", "gi");
	URL = URL.replace(regex,'&');
	URL = URL.replace(/(\?|&)$/,'');
	regex = null;
	return URL;
}

function addParamToURL(URL,param,value)
{
	URL = removeParamFromURL(URL,param);
	URL = URL + '&' + param + '=' + value
	if (!(/\?/.test(URL))) URL = URL.replace(/&/,'?');
	return URL;
}


function navigateWithReferrer(url) {
    var fakeLink = document.createElement("a");
    if (typeof (fakeLink.click) == 'undefined') {
        window.location.href = url; // sends referrer in FF, not in IE        
    }
    else {
        fakeLink.href = url;
        document.body.appendChild(fakeLink);
        fakeLink.click(); // click() method defined in IE only
    }
}

function submitStep3()
{
    var err = [];

    if ($("#Driver_sameAsCustomer").length && $("#Driver_sameAsCustomer")[0].checked) {
        // add the values from the customer to driver:
        if ($("#Customer_GenderCode_mr")[0].checked)
	    {
		    $("#Driver_TitleCode_mr")[0].checked = true;
	    }
	    else
	    {
		    $("#Driver_TitleCode_mrs")[0].checked = true;
	    }
	    $("#Driver_FirstName").val($("#Customer_Initials").val());
	    $("#Driver_Surname").val($("#Customer_Surname").val());
    }
	
	err = $.merge(err, validateOffice());
	err = $.merge(err, validateCustomer());
	err = $.merge(err, validateDriver());
	err = $.merge(err, validatePayment());

	submitError(err, "accept_agreement", AGREEMENTNOTACCEPTED_ERR);
	
	if (err.length > 0) {
	    alert(err.join('\n'));
	    return false;
	}
	
	showWaitingPage();
	
	validatePaymentAlias(createOrder);
	
	return false;
}

function createOrder() {
    // SUBSCRIBE:
    if ($("#subscribe")[0].checked) {
        // exec the JS and send the email for subscribtion:
        emailSubscribe($("#newsletterID").val(), $("#Customer_Email").val());
    }

    // submit form to the booking overview page:
    $("#BookCar").val("true");
    var $checkboxes = $("#booking_form input[disabled]");
    $checkboxes.attr("disabled", "");
    $("#booking_form")[0].submit();
    $checkboxes.attr("disabled", "disabled");
}

//Validate Alias
function validatePaymentAlias(callback) {
    // only check CreateAlias if it turned on
    if (CC_CHECK != 1) {
        callback();
        return true;
    }

    var isCC = $("#Payment_PaymentTypeCode").val() == "cc";
    if (!isCC) {
        callback();
        return true;
    }
    
    // only
    $.ajax({
        url: "back/ws.aspx?method=CreateAlias",
        async: false,
        data:
            {
                "Payment_CreditCard_CardTypeCode": $("#Payment_CreditCard_CardTypeCode").val(),
                "moduleid": moduleId,
                "accountid": accountId,
                "Customer_Email": $("#Customer_Email").val(),
                "CurrencyCode": currency,
                "Payment_CreditCard_CreditCardNR": $("#Payment_CreditCard_CreditCardNR").val(),
                "Payment_CreditCard_HolderName": $("#Payment_CreditCard_HolderName").val(),
                "Payment_CreditCard_ExpireDate": $("#Payment_CreditCard_ExpireDate").val(),
                "cardVerCode": $("#cardVerCode").val()
            },
        cache: false,
        success: function(data) {
            if ($(data).find('Alias').length > 0) {
                callback();
                return true;
            }

            hideWaitingPage();
            alert(ALIAS_ERR);
            return false;
        },
        error: function(data) {
            hideWaitingPage();
            alert(ALIAS_ERR);
            return false;
        }
    });
}

function changeOrder() {
    var err = [];

    if ($("#Driver_sameAsCustomer").length && $("#Driver_sameAsCustomer")[0].checked) {
        // add the values from the customer to driver:
        if ($("#Customer_GenderCode_mr")[0].checked) {
            $("#Driver_TitleCode_mr")[0].checked = true;
        }
        else {
            $("#Driver_TitleCode_mrs")[0].checked = true;
        }
        $("#Driver_FirstName").val($("#Customer_Initials").val());
        $("#Driver_Surname").val($("#Customer_Surname").val());
    }

    //err = $.merge(err, validateOffice());
    err = $.merge(err, validateCustomer());
    err = $.merge(err, validateDriver());
    err = $.merge(err, validatePayment());

    submitError(err, "accept_agreement", AGREEMENTNOTACCEPTED_ERR);

    if (err.length > 0) {
        alert(err.join('\n'));
        return false;
    }

    showWaitingPage();
    $("#action").val("confirm");

    validatePaymentAlias(createOrder); 
    
    return false;
}

function cancelOrder() {
    showWaitingPage();
    $.ajax({
        url: "back/ws.aspx",
        cache: false,
        data: { method: "cancelOrder", quote: document.getElementById("quote").value },
        success: function(data) {
            var error = "";
            if ($(data).find("Error").length > 0) {
                error = $(data).find("Error").find("Message").text();
            } else if ($(data).find("OrderCancelled").text() == "N") {
                error = $(data).find("Message").text();
            }

            if (error.length > 0) {
                hideWaitingPage();
                alert(error);
                return;
            }
            //window.location
        }
    });
}

function emailSubscribe(newsLetterId, email)
{
	// http://www.holidaycars.com/enieuwsbrief/afmeldenXML.asp
	$.ajax({
	    url: "back/aanmeldenXML.aspx",
	    data: "leterID="+newsLetterId+"&emailAddress="+email,
	    async: true
	});
}

// copy from module 1
function pwOpen(sUrl, ID, type)
{
	if (sUrl != '') 
	{
		var qStr = "";
		
		var windowProps = "";
		
		if (type == 'cardetails')
		{
			qStr = "CarID=" + ID;
			qStr += "&" + getSelectCarFormValuesToQueryString5('searchForm');
			windowProps = "width=650, height=300, resizable=yes, scrollbars=yes";
			sUrl += "?" + qStr;
		}
		else if (type == 'callme') windowProps = "width=370, height=450, resizable=no, scrollbars=no";
		else if (type == 'productdetails')
		{
			qStr = "ProductID=" + ID;
			windowProps = "width=950, height=600, resizable=yes, scrollbars=yes";
			sUrl += "?" + qStr;
		}
		else if (type == 'printcarlist') windowProps = "width=580, height=500, resizable=yes, scrollbars=yes";
		else if (type == 'emailcarlist') windowProps = "width=350, height=450, resizable=no, scrollbars=no";
		else if (type == 'printBooking') windowProps = "width=580, height=500, resizable=yes, scrollbars=yes";
		else if (type == 'cvcInfo') windowProps = "width=350, height=400, resizable=no, scrollbars=no";
		// else windowProps = "width=780, height=500, resizable=yes, scrollbars=yes";
		 else windowProps = "width=950, height=600, resizable=yes, scrollbars=yes";
		
		window.open(sUrl, type, windowProps);
	}
}
function getSelectCarFormValuesToQueryString5(formId) 
{
	// especially for the cardetails of upgrade in the booking details:
	
	var qsStr = "";
	
	qsStr += "PickUpLocationID=" + document.getElementById('pickuplocationId').value;
	qsStr += "&ReturnLocationID=" + document.getElementById('dropofflocationId').value;
	qsStr += "&PickUpDateTime=" + document.getElementById('pickupdate_DT').value + "T" + document.getElementById('pickuptime').value;
	qsStr += "&ReturnDateTime=" + document.getElementById('dropoffdate_DT').value + "T" + document.getElementById('dropofftime').value;
	qsStr += "&CurrencyCode=" + currency;
	qsStr += "&LanguageCode=" + language;
	qsStr += "&ModuleID=" + moduleId;
	qsStr += "&AccountID=" + accountId;
	
	return qsStr;
}

// step 3, get phone prefix by selected country
function customerCountryChanged() {
  if($("#Customer_PhoneNumberDaytime").val().length <= 4 ||
     (!isQuote && $("#Customer_PhoneNumberEvening").val().length <= 4))
  {
    $.ajax({
      url: "back/phonePrefix.aspx",
      data: "countryCode=" + $(this).val(),
      async: false,
      success: function(data) {
              var phoneCode = data.substring(data.indexOf(">")+1, data.indexOf("</"));
              $("#Customer_PhoneNumberDaytime").val(phoneCode);
              if (!isQuote)
                $("#Customer_PhoneNumberEvening").val(phoneCode);
          }
      });
  }
  
  if($(this).val().toLowerCase() != "nl") {
    // only support visa payment
    $("#Payment_CreditCard_CardTypeCode option[value=Authorisation]").remove();
    $("#Payment_CreditCard_CardTypeCode option[value=BankTransfer]").remove();
    //displayAdditionFee();

    $("#Payment_CreditCard_CardTypeCode").val("");
    $("#Payment_CreditCard_CardTypeCode_Valid").attr("class","icon notset");
    $("#creditRight").hide(); $("#creditLeft").hide();
    $("#Authorisation_Div").hide();
    $("#BankTransfer_Div").hide();
  }
  else {
    // support visa, authorization and bank transfer
     $("#Payment_CreditCard_CardTypeCode").append("<option value=\"Authorisation\" group=\"cn\">Authorisation</option>");
     $("#Payment_CreditCard_CardTypeCode").append("<option value=\"BankTransfer\" group=\"tr\">Bank Transfer</option>");
     //displayAdditionFee();
  }
}
function paymentChanged() {
    $("#Payment_PaymentTypeCode").val(this.options[this.selectedIndex].getAttribute("group"));

    switch($(this).val()) {
        case "visa":
        case "master":
        case "amex":
            $("#creditRight").show(); $("#creditLeft").show();
            $("#Authorisation_Div").hide();
            $("#BankTransfer_Div").hide();
            break;
        case "Authorisation":
            $("#creditRight").hide(); $("#creditLeft").hide();
            $("#Authorisation_Div").show();
            $("#BankTransfer_Div").hide();
            break;
        case "BankTransfer":
            $("#creditRight").hide(); $("#creditLeft").hide();
            $("#Authorisation_Div").hide();
            $("#BankTransfer_Div").show();
            break;
        default:
            $("#creditRight").hide(); $("#creditLeft").hide();
            $("#Authorisation_Div").hide();
            $("#BankTransfer_Div").hide();
            break;
    }
}

/*function displayAdditionFee() {
    $("#payment_desc span").hide();
    $("#Payment_CreditCard_CardTypeCode option").each(function() {
        $("#payment_desc span[value='" + this.value + "']").show();
    });
}*/

function equalHeights() {
  var right = $("#booking_form").children("div.content").children("div.right_cl");
  right.next().height(right.height() - 30);
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function setMenuStyle(menuitem, posx, posy, width, height) {
  var backgroundX = posx + "px";
  var backgroundY = posy + "px";
  var backgroundPos = backgroundX + " " + backgroundY;
  $(menuitem).css({ "width": width, "height": height, display: "block", "background-position": backgroundPos });
}

function SetEnd(tb) {
  if (tb.createTextRange) {
    var FieldRange = tb.createTextRange();
    FieldRange.moveStart('character', tb.value.length);
    FieldRange.collapse();
    FieldRange.select();
  }
}
