/*
 *  Document    :   res.js
 *  Created on  :   30.03.2009, 13:00:00
 *  Author      :   Richard Prillwitz (richard.prillwitz@sixt.de)
 *  Description :   This script (res.js) contains all the functions needed
 *                  several times in the rental application (such as rebooking).
 *                  The specific start functions have to be written
 *                  in the start.js file!
 *
 */

$.fn.alert = function (msg) {
    return this.each(function () {
        $(this).hide().html(msg).animate({
            opacity: 'show'
        }, 1500);
    });
};

$.fn.sxResGET = function (url, data, callback) {

    if (data && typeof data == "object") {
        var tempdata = [];
        for (var i in data)
            tempdata.push(i + "=" + encodeURIComponent(data[i]));
        data = tempdata.join("&");
    }
    if (data)
        url += "?" + data;
    return this.each(function () {
        $(this).load(url, null, callback);
    });
};


/*
 * Try-catch for iframe version
 * Setting res.is_overlay to true in case of iframe version
 * (error at parent.sx_open_reservation_overlay => undefinded)
 */
try {
    res.is_overlay =  parent != window && !!parent.sx_open_reservation_overlay;
} catch (e) {
    res.is_overlay = true;
};


res.utility = {
    clientRect: function (elem) {
        if (elem.getBoundingClientRect) {
            var rect = elem.getBoundingClientRect();
            var scrollY = "scrollY" in window ? window.scrollY : document.documentElement.scrollTop;
            var scrollX = "scrollX" in window ? window.scrollX : document.documentElement.scrollLeft;
            return {
                top: rect.top + scrollY,
                left: rect.left + scrollX,
                bottom: rect.bottom + scrollY,
                right: rect.right + scrollX
            };
        }

        var x = 0, y = 0, sl = 0, st = 0, parent = elem, op;

        do {
            x += parent.offsetLeft;
            y += parent.offsetTop;

            op = parent.offsetParent;
            do {
                sl += parent.scrollLeft;
                st += parent.scrollTop;
                parent = parent.parentNode;
            } while(parent != op);
            parent = op;
        } while (parent && parent != document.body && parent != document.documentElement);

        x -= parseInt($(elem).css('marginLeft')) || 0;
        y -= parseInt($(elem).css('marginTop')) || 0;

        sl -= elem.scrollLeft;
        st -= elem.scrollTop;

        return {
            top: y - st,
            left: x - sl,
            bottom: y - st + elem.offsetHeight,
            right: x - sl + elem.offsetWidth
        };
    },

    /*
     *  logout function
     */
    logout: function () {
        $.getJSON(res.url.expresslogout, {
            redirect: 1,
            hash: new Date().getTime()
        }, function (response) {
            if (response.rec.url)
                location = response.rec.url;
            else if (response.err.length)
                alert(response.err[0]);
        });
    },

    tripinfo_load: function (pagename) {
        var container = $("#sx-res-rentaldetails-container");
        container.find("img.sx-res-info-btn").each(function () {
            $("#" + this.getAttribute("rel")).remove();
        });
        container.sxResGET(res.url.rentaldetails, {
            pagename: pagename,
            occt: res.occt,
            hash: new Date().getTime()
        }, function () {
            res.utility.infobuttons(this);
            var modify_link = $("#sx-res-rentaldetails-modify");
            if (pagename == "offerlist")
                modify_link.children("a").click(function (e) {
                    e.preventDefault();
                    sx_open_reservation_overlay("modifying_existing_res=1");
                });
            else
                modify_link.remove();
        });

        if ($("#sx-res-driverdetails-main") != null) {
            var containerNew = $("#sx-res-driverdetails-main");
            containerNew.find("img.sx-res-info-btn").each(function () {
                res.utility.infobuttons(containerNew);
            });
        }
    },

    tripinfo_load_withoutajax: function (pagename) {
        var container = $("#sx-res-rentaldetails-container");
        res.utility.infobuttons(container);
        var modify_link = $("#sx-res-rentaldetails-modify");
        if (pagename == "offerlist")
            modify_link.children("a").click(function (e) {
                e.preventDefault();
                sx_open_reservation_overlay("modifying_existing_res=1");
            });
        else
            modify_link.remove();

        if ($("#sx-res-driverdetails-main") != null) {
            var containerNew = $("#sx-res-driverdetails-main");
            containerNew.find("img.sx-res-info-btn").each(function () {
                res.utility.infobuttons(containerNew);
            });
        }
    },

    resdetails_load: function (can_be_modified) {
        $("#sx-res-resdetails").sxResGET(res.url.resdetails, {
            occt: res.occt,
            hash: new Date().getTime()
        }, function () {
            if (!can_be_modified) {
                $("#sx-res-resdetails-edit").remove();
                if ($(".sx-res-details-stopper") != null) $(".sx-res-details-stopper").remove();
            }
        });
    },

    resdetails_load_withoutajax: function (can_be_modified) {
        if (!can_be_modified)
            $("#sx-res-resdetails-edit").remove();
    },

    /*
     *  open thickboxlike div
     */
    open_jqm_at_anchor: function (box, anchor) {
        var pos = res.utility.clientRect(anchor);
        box.css("top", -999).appendTo(document.body).jqm().jqmShow();
        var top = pos.top + anchor.offsetHeight;
        var left = pos.left;
        var winHeight = window.innerHeight || document.documentElement.clientHeight;
        var winWidth = window.innerWidth || document.documentElement.clientWidth;
        if (left + anchor.offsetWidth / 2 > winWidth / 2)
            left += anchor.offsetWidth - box[0].offsetWidth;
        box.css({
            top: Math.min(winHeight - box[0].offsetHeight - 10, Math.max(10, top)),
            left: Math.min(winWidth - box[0].offsetWidth - 10, Math.max(10, left))
        });
    },

    infobuttons: function (container) {
        $(container).find("img.sx-res-info-btn").mousedown(function () {
            var box = $("#" + this.getAttribute("rel"));
            if (box.is(".sx-res-small-popup") && !box.children("a.jqmClose").length)
                box.prepend('<a class="jqmClose" title="' + res.close + '"></a>');
            res.utility.open_jqm_at_anchor(box, this);
        }).each(function () {
            if (!this.src)
                this.src = "/common/img/base/rac/bt_info.png";
            if (!this.alt)
                this.alt = "Info";
        });
    },

    offerlist_overlay: {
        overlay: null,
        show: function () {

            /*
             *      Here we take the width and hight of the booking part (including borders, margins and paddings!).
             */

            if (!this.overlay) {

                /*
 *              Modified this part!
 *              Now the overlay will fit on the booking part.
 *
 **/


                /*
 *              **** SAVE (old part) ****
 *              To be removed after testing.
 */
                //                    this.overlay = document.createElement("div");
                //                    this.overlay.id = "sx-res-offerlist-overlay";
                //                    this.overlay.className = "sx-res-loading-overlay";
                //                    this.overlay.innerHTML = "<span>" + res.offerlist_overlay_text + "</span>";
                //                    document.body.insertBefore(this.overlay, document.body.firstChild);


                /*
 *              New Overlay
 *              First we need a div relative positioned afert the offer-form tag
 *              Inside the div we will find an absolute positioned div with the height and width of the form tag.
 *              Inside this one we have (in this case) a loading gif.
 */



                this.overlay = document.createElement("div");
                this.overlay.id = "sx-res-offerlist-overlay";
                this.overlay.className = "sx-res-overlay-outer";

                this.overlay.innerHTML = '<img src="/common/img/app/res/loader-medium.gif" style="height:32px; width:32px; position:absolute; left:45%; top:40%;"></img>'






                /*
 *                  Write the stuff inside the offer form.
 */
                $("#offer").prepend(this.overlay);

                $(window).bind("pageshow", function () {
                    res.utility.offerlist_overlay.hide();
                });
            }
            if (res.utility.hide_selectboxes)
                res.utility.hide_selectboxes();
            this.overlay.style.display = "block";
        },
        hide: function () {
            if (this.overlay && this.overlay.style.display != "none") {
                this.overlay.style.display = "none";
                $("#sx-res-login-overlay").css({
                    'display':'none'
                });
                if (res.utility.show_selectboxes)
                    res.utility.show_selectboxes();
            }
        }
    }
};

var hideSelectBoxesCount = 0;
/*
 *  hide select boxes for IE
 */
res.utility.hide_selectboxes = function () {
    if ($.browser.msie && $.browser.version <= 6 &&
        hideSelectBoxesCount++ <= 0)
        $("#pickup-h, #pickup-m, #return-h, #return-m").css("visibility", "hidden");
};

/*
 *  show select boxes for IE
 */
res.utility.show_selectboxes = function () {
    if ($.browser.msie && $.browser.version <= 6 &&
        --hideSelectBoxesCount <= 0)
        $("#pickup-h, #pickup-m, #return-h, #return-m").css("visibility", "");
};



/*
 *  Initialize the calendar
 */
res.calendar = {
    init: function () {
        var create = function () {
            res.calendar._container =
            $('<div id="sx-res-calendar">\
                      <a class="jqmClose" title="'+ res.close +'"></a>\
                      <h5></h5>\
                      <div></div>\
                  </div>')
            .appendTo(document.body)
            .jqm({
                /*
                 *  show the calendar in jqm (tb-like)
                 */
                onShow: function (hash) {
                    if (res.utility.hide_selectboxes)
                        res.utility.hide_selectboxes();
                    hash.w.show();
                },
                /*
                 *  hide the calendar - close the jqm(tb-like)
                 */
                onHide: function (hash) {
                    if (res.utility.show_selectboxes)
                        res.utility.show_selectboxes();
                    hash.w.hide();
                    hash.o.remove();
                }
            });
        };
        /*
         *  onclick event --> open the calendar
         */
        $('input.sx-res-date').mousedown(function (event) {
            if ((event.offsetX || event.layerX) < this.offsetWidth - 21) {
                return;
            }
            if (create) {
                create();
                create = null;
            }
            res.calendar._input = this;
            var start_date = this.value;
            pickup_date = $(this).parent().parent().find("#pickup-date").val();

            return_date = $(this).parent().parent().find("#return-date").val();

            if (!start_date) {
                switch (this.id) {
                    case "pickup-date":
                        start_date  = $("#return-date").val();
                        break;
                    case "return-date":
                        start_date = $("#pickup-date").val();
                        break;
                }
            }
            res.calendar.load(start_date, pickup_date, return_date, this.title, this);
            this.blur();
            event.preventDefault();
        }).mousemove(function (event) {
            this.style.cursor = ((event.offsetX || event.layerX) < this.offsetWidth - 21) ? "text" : "pointer";
        }).each(function () {
            this.maxLength = this.value.length;
        });
    },
    load: function (start_date, pickup_date, return_date, title, date_field) {
        this._container.children("h5").html(title);

        /*
         *  This is not the final solution - but it's working!
         *  We still get an error cause of mktime()-function.
         *  This function seems to expect four parameters but we only have
         *  (in case of agentlogin) one (start_date).
         *
         */

        /*
          *BEFORE:
          */
        /*  start_date  = prepareDateForLoad(start_date);
           *  pickup_date = prepareDateForLoad(pickup_date);
           *  return_date = prepareDateForLoad(return_date);
           */

        if(start_date != null)
            start_date  = prepareDateForLoad(start_date);
        else if (start_date == null)
        {
            //NOT TESTED!!!
            var today = new Date();
            var startDate = today.getDay() + "." + today.getMonth() + "." + today.getYear();
            start_date = startDate;
            start_date  = prepareDateForLoad(start_date);
        }
        if(pickup_date != null)
            pickup_date = prepareDateForLoad(pickup_date);
        else if(pickup_date == null)
        {
            pickup_date = start_date;
            pickup_date = prepareDateForLoad(pickup_date);
        }

        if(return_date != null)
            return_date = prepareDateForLoad(return_date);

        /*******************************************************************************/

        var content = this._container.children("div").sxResGET(res.url.calendar, {
            start_date: start_date,
            pickup_date: pickup_date,
            return_date: return_date
        }, function () {
            $(this).find("table.sx-res-calendar > tbody td:not(.sx-res-calendar-past):not(.sx-res-calendar-inactive)").click(function () {
                $(res.calendar._input).val($(this).attr("rel")).change();
                $("#sx-res-calendar").jqmHide();
                content.empty();
                res.calendar._input = null;
            });
        });
        if (date_field)
            res.utility.open_jqm_at_anchor(this._container, date_field);
        else
            this._container.jqmShow();
    }
};

$(document).ready(function () {
    if ($.browser.msie && $.browser.version == 7)
        $(document.documentElement).addClass("ie7");

    res.calendar.init();

    var logout_link = document.getElementById("sx-res-logout-link");
    if (logout_link) {
        var box = $('<div class="sx-res-small-popup">\
                    <a class="jqmClose" title="' + res.close + '"></a>\
                    <p>' + res.logout_confirmation + '</p>\
                    <p>\
                      <a href="" class="BtSubmitGrey" onclick="res.utility.logout(); return false"><span>' + res.logout_proceed + '</span></a>\
                      <a href="" class="BtSubmitGrey jqmClose"><span>' + res.logout_cancel + '</span></a>\
                    </p>\
                    </div>');
        $(logout_link).click(function () {
            res.utility.open_jqm_at_anchor(box, this);
        });
    }

    if (res.is_overlay)
        $("#sx-res-close-overlay").click(function (e) {
            e.preventDefault();
            $("#sx-res-close-overlay").sxResGET(res.url.resettopoffer, {
                hash: new Date().getTime()
            }, function () {} );

            try {
                // permission denied if not same origin
                parent.tb_remove();
            } catch (err) {
                tb_remove();
            }
        }).attr("href", "");
});


function prepareDateForLoad(pre_date) {
    var dmy      = [];
    var pre_date = pre_date.split(res.dpDateSep);

    switch (res.dpDateFormat.toLowerCase()) {
        case 'dmy':
            dmy = normalizeDateVariables(pre_date[0], pre_date[1], pre_date[2]);
            break;
        case 'mdy':
            dmy = normalizeDateVariables(pre_date[1], pre_date[0], pre_date[2]);
            break;
        case 'ymd':
            dmy = normalizeDateVariables(pre_date[2], pre_date[1], pre_date[0]);
            break;

        default: break;
    }

    return dmy[0] + '.' + dmy[1] + '.' + dmy[2];
}


function normalizeDateVariables(day, month, year)  {
    if (res.dpDateFormat.indexOf("y") > -1)
        year = '20' + year;
    if (month.length == 1)
        month = '0'  + month;
    if (day.length == 1)
        day = '0'  + day;

    return [day, month, year];
}


/*
 *  initialize res
 */
res.start = function () {
    var uci, rci, uda, rda;
    var form = document.getElementById("offer");
    if (form) {
        uci = form.elements.uci;
        rci = form.elements.rci;
        uda = form.elements.uda;
        rda = form.elements.rda;
    }

    var stationsBlock = $('#stationsBlock');
    var stationsBlock_rect = res.utility.clientRect(stationsBlock[0]);

    function res_error(msg) {
        if (res.is_overlay)
            $('#sx-res-topoffer-data').hide();
        $('#sx-res-rentarea-error').alert(msg);
        //jump to error msg (anchor)
        //check if we are on the bavarian landingpage
        if( $('#start-wiesn-lp').length ){
            self.scrollTo(0,0);
        }
    }


    /*
     *  Submit button --> show offers
     */
    $('#submit-offer').click(function (e) {
        e.preventDefault();
        if (!document.cookie) {
        //res_error(res.ERR_COOKIES);
        //return;
        }
        var expresslogin = document.getElementById("sx-expresslogin");
        var moc = document.getElementById("moc");
        var nam1 = document.getElementById("nam1");
        if (expresslogin &&
            moc.value && moc.value != moc.defaultValue &&
            nam1.value && nam1.value != nam1.defaultValue)
            $(expresslogin).ajaxSubmit({
                dataType : 'json',
                success: function (response, status) {
                    res.login = response.rec.login;
                    if (response.err.length > 0) {
                        var msg = '';
                        for (var i = 0; i < response.err.length; i++)
                            msg += ' ' + response.err[i].txt;
                        $('#loginfailed').alert(msg);
                        return;
                    }
                    /*
                     *  if login data is entered and valid
                     */
                    if (res.login == 1) {
                        $('#loginfailed').hide();
                        $('#sx-express').html(response.htm.txt);
                        bindLogout();
                        offerRequest();
                    } else
                        $('#loginfailed').show();
                }
            });
        else
            offerRequest();
    }).attr("href", "");

    /*
     * Pickup station suggest
     */
    // define the pickup params

    var pickupParam = {
        spra: res.spra,
        por:  'pickup',
        liso: res.pickup_liso,
        anz:  500
    };
    switch (res.cfty) {
        case 'P':
            pickupParam.cftp  = 'Y';
            pickupParam.cftl  = 'N';
            pickupParam.lcit  = 'N';
            pickupParam.noimp = 'Y';
            break;
        case 'L':
            pickupParam.cftp  = 'N';
            pickupParam.cftl  = 'Y';
            pickupParam.lcit  = 'N';
            pickupParam.noimp = 'Y';
            break;
    }


    /*
     *  Pickup station suggest
     */
    $('#suggest-pickup-kst').focus(function () {
        if (!res.uci && this.value == this.defaultValue)
            this.value = "";
    }).blur(function () {
        if (!res.uci && this.value == "")
            this.value = this.defaultValue;
    }).autocomplete(res.url.stationsuggest, {
        minChars: function (keyboardinput) {
            return stationsBlock.is(".select-pickup-empty") ? 2 : (keyboardinput ? 1 : 0);
        },
        preload: true,
        matchContains: true,
        cacheLength: 500,
        extraParams: pickupParam,
        maxItemsToShow: 500,
        onItemSelect: function (li) {
            if (!li) {
                if (rci.value == uci.value)
                    rci.value = '';
                uci.value = '';
                return;
            }
            var cit = li.getAttribute("rel");
            uci.value = cit;
            if (res.return_follows_pickup) {
                var citName = $('#suggest-pickup-kst').val();
                returnParam.liso = pickupParam.liso;
                $('#select-return-liso').val(pickupParam.liso);
                rci.value = cit;
                $('#display-return-kst').text(citName);
                $('#suggest-return-kst').val(citName);
            }
        },
        formatItem: function (row) {
            return ["<li rel='",row[1],"'>",
            row[0],
            "<div class='ac-res-infobox' rel='",
            row[3],
            "'><h4>",
            row[0],
            "</h4>",
            row[2],
            "</div></li>"].join("");
        },
        dropdown: $('#stationsearch-open')
    });

    function bindLogout() {
        $('#sx-expresslogout').click(function () {
            $.getJSON(res.url.expresslogout, {},
                function (response) {
                    res.login = response.rec.login;
                    express();
                }
                );
        });
    }




    function express() {
        var container = $('#sx-express');
        if (container.length)
            $.getJSON(res.url.customerdetails, {
                hash: new Date().getTime(),
                spra: res.spra
            },
            function (response) {
                container.html(response.htm.txt);
                res.utility.infobuttons(container);
                bindLogout();
            }
            );
    }

    var count_offer_requests = 1;
    function reload_offer(){
        if(count_offer_requests <= 5 )
        {
            count_offer_requests ++;
            offerRequest();
        }
        else{
            return;
        }
    }

    /*
     *  Offer call preparation
     */
    function offerRequest() {
        var timeout;

        res.utility.offerlist_overlay.show();

        $('#sx-res-overlay-inline-loading').css({
            'display':'block'
        });

        $('#offer')
        .append('<input type="hidden" name="hash" value="' + new Date().getTime() + '">')
        .ajaxSubmit({
            url: res.url.offer,
            dataType: 'json',
            beforeSubmit: function (formArray, jqForm) {
                var f = jqForm[0].elements;
                var msg;
                if (!$.trim(f.uci.value))
                    msg = res.ERR_START_UCI;
                else if (!$.trim(f.uda.value))
                    msg = res.ERR_START_UDA;
                else if (!$.trim(f.rci.value))
                    msg = res.ERR_START_RCI;
                else if (!$.trim(f.rda.value))
                    msg = res.ERR_START_RDA;
                else {
                    // 10 sec for timeout
                    var timeout_time = 10000;

                    timeout = setTimeout(function () {

                        timeout = 0;
                        $('#offer').prepend('<img id="trackingOfferError' + count_offer_requests + '" name="trackingOfferError' + count_offer_requests + '" style="width:1px; height:1px;" src="/common/img/app/res/zwetschgnmandl_' + count_offer_requests + '.gif">');
                        if(count_offer_requests <= 5)
                        {
                            reload_offer();
                            return false;
                        }

                        res_error(res.ERR_START_TIMEOUT);
                        res.utility.offerlist_overlay.hide();
                    },timeout_time);
                    return true;
                }
                res_error(msg);
                res.utility.offerlist_overlay.hide();
                return false;
            },
            success: function (response, status) {
                if (timeout)
                    clearTimeout(timeout);
                else
                    return;

                if (response.err.length > 0) {
                    res.utility.offerlist_overlay.hide();

                    switch (response.err[0].txt) {
                        case "ERR_ALTCITIES_UCI":
                        case "ERR_ALTCITIES_RCI":
                            $('#sx-res-rentarea-error').hide();
                            var popup = $("#sx-res-altcities");
                            popup.html('<a class="jqmClose" title="' + res.close + '"></a>' + response.htm.txt);
                            res.utility.open_jqm_at_anchor(popup, document.getElementById(
                                response.err[0].txt == "ERR_ALTCITIES_UCI" ?
                                "suggest-pickup-kst" : "display-return-kst"));
                            popup.find("ul a[rel]").click(function () {
                                $("#sx-res-altcities").jqmHide();
                                eval('var city = ' + this.getAttribute("rel"));
                                if (response.err[0].txt == "ERR_ALTCITIES_UCI") {
                                    uci.value = city.cit;
                                    $('#suggest-pickup-kst').val(city.name);
                                } else {
                                    rci.value = city.cit;
                                    $('#display-return-kst').text(city.name);
                                    $('#suggest-return-kst').val(city.name);
                                }
                            });
                            break;
                        default:
                            /*
                             *  Display error in start
                             */
                            var msg = '';
                            for (var i = 0; i < response.err.length; i++)
                                msg += ' ' + response.err[i].txt;
                            res_error(msg);
                    }
                    $('#sx-res-overlay-inline-loading').css({
                        'display':'none'
                    });
                    return;
                }


                try{
                    if(parent != window && !!parent.sx_open_reservation_overlay){
                        parent.location.href = res.url.offerlist;
                        return;
                    }
                }catch(e){
                };

                /*
                *   IE doesn't like submitting forms and prefers to crash.
                *   The following CSS hack, whilst not making any sense, tells
                *   him that we do want to submit the form and not crash this time.
                */
                if ($.browser.msie) {
                    res.utility.offerlist_overlay.hide();
                    //                    $("*").css("position", "static");
                    $("#sx-res-offerlist-overlay").css("position", "static").children().css("position", "static");
                }
                var form = document.getElementById('offer');
                form.elements.STATE.value = response.state.txt;
                form.submit();
            }
        });
    }

    /*
     *  converts the datestring into cobol date format
     *  @TODO: Why doing this in frontend ???
     */
    function stringToCobolDate(input) {
        var date = input.value;
        if (!date) {
            date = new Date();
            date = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
            input.value = dateToString(date);
        } else {
            date = date.split(res.dpDateSep);
            switch (res.dpDateFormat.toLowerCase()) {
                case 'dmy':
                    date = [date[2], date[1], date[0]];
                    break;
                case 'mdy':
                    date = [date[2], date[0], date[1]];
                    break;
                case 'ymd':
                    date = [date[0], date[1], date[2]];
            }
        }
        if (res.dpDateFormat.indexOf("y") > -1)
            date[0] = '20' + date[0];
        if (date[1].length == 1)
            date[1] = '0' + date[1];
        if (date[2].length == 1)
            date[2] = '0' + date[2];
        return [date[0], date[1], date[2]];
    }
    /*
     *  converts the date to a string
     *  @TODO: why?
     */
    function dateToString(date) {
        if (res.dpDateFormat.indexOf("y") > -1)
            date[0] = (date[0] + '').substring(2);
        if (date[1].length == 1)
            date[1] = '0' + date[1];
        if (date[2].length == 1)
            date[2] = '0' + date[2];
        switch (res.dpDateFormat.toLowerCase()) {
            case 'dmy':
                date = [date[2], date[1], date[0]];
                break;
            case 'mdy':
                date = [date[1], date[2], date[0]];
                break;
            case 'ymd':
                date = [date[0], date[1], date[2]];
        }
        return date.join(res.dpDateSep);
    }


    /*
     *  Change the date values
     */
    var returnDate = $('#return-date');
    var pickupDate = $('#pickup-date');
    pickupDate.change(function () {
        var date = stringToCobolDate(this);
        uda.value = date.join("");
        if (rda.value < uda.value) {
            date = new Date(new Date(date[0], date[1] - 1, date[2], 4, 0, 0).getTime() + 3600 * 24 * 1000);
            date = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
            if (date[1] < 10)
                date[1] = '0' + date[1];
            if (date[2] < 10)
                date[2] = '0' + date[2];
            rda.value = date.join("");
            returnDate.val(dateToString(date));
        }
    }).change();
    returnDate.change(function () {
        var date = stringToCobolDate(this);
        rda.value = date.join("");

        var today = new Date();
        today = [today.getFullYear(), today.getMonth() + 1, today.getDate()];

        if (today[1] < 10)
            today[1] = '0' + today[1];
        if (today[2] < 10)
            today[2] = '0' + today[2];

        var join_today = today.join("");

        if (rda.value < uda.value) {
            date = new Date(new Date(date[0], date[1] - 1, date[2], 4, 0, 0).getTime() - 3600 * 24 * 1000);
            date = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
            if (date[1] < 10)
                date[1] = '0' + date[1];
            if (date[2] < 10)
                date[2] = '0' + date[2];
            uda.value = date.join("");
            pickupDate.val(dateToString(date));

            //no return in the past possible
            if (uda.value < join_today) {
                uda.value = join_today;
                pickupDate.val(dateToString(today));
            }
        }

    }).change();

    /*
     *  Tabs for selecting ctyp in corporate-start.tpl
     */
    $('#sx-res-categories > a').click(function (e) {
        e.preventDefault();
        var form = document.getElementById('sx-res-ctypswitch');
        form.elements.ctyp.value = $(this).attr('rel');
        form.submit();
    });


    /*
     *  Define the return station box
     */
    var returnstationBox =
    $('#returnstation').css({
        position: 'absolute',
        left: stationsBlock_rect.left + 40,
        top: stationsBlock_rect.top + 180
    })
    .jqm({
        onShow: function (hash) {
            res.utility.hide_selectboxes();
            hash.w.show();
            $('#return-station-submit').unbind('mousedown').unbind('click').click(function () {
                returnstationBox.jqmHide();
            }).mousedown(function () {
                returnstationBox.jqmHide();
            }).attr("href", "");

            if (rci.value) {
                var input = document.getElementById("suggest-return-kst");
                input.value = $('#display-return-kst').text();
                input.select();
            }
        },
        onHide: function (hash) {
            var input = document.getElementById("suggest-return-kst");
            input.blur();
            input.autocompleter.hideResults();
            res.utility.show_selectboxes();
            hash.w.hide();
            hash.o.remove();
        }
    }).appendTo(document.body);

    /*
     *  Return station suggest
     */
    var returnParam = {
        spra: res.spra,
        por:  'return',
        liso: res.return_liso,
        anz:  500
    };

    $('#suggest-return-kst').autocomplete(res.url.stationsuggest, {
        minChars: function (keyboardinput) {
            return returnstationBox.is(".select-return-empty") ? 2 : (keyboardinput ? 1 : 0);
        },
        matchContains: true,
        cacheLength: 500,
        extraParams: returnParam,
        maxItemsToShow: 500,
        onItemSelect: function (li) {
            var eventListener = function (e) {
                e.preventDefault();
                rci.value = e.data.sValue;
                $('#display-return-kst').text(e.data.nValue);
            };
            var suggest = document.getElementById('suggest-return-kst');
            var data = {
                nValue: suggest.value
            };
            if (!li) {
                data.sValue = uci.value;
                suggest.value = '';
            } else {
                data.sValue = li.getAttribute("rel");
                if (!data.nValue || uci.value == data.sValue)
                    data.nValue = $('#suggest-pickup-kst').val();
            }
            $('#return-station-submit').bind("click", data, eventListener)
            .bind("mousedown", data, eventListener);
        },
        formatItem: function (row) {
            return ["<li rel='",row[1],"'>",
            row[0],
            "<div class='ac-res-infobox' rel='",
            row[3],
            "'><h4>",row[0],"</h4>",
            row[2],
            "</div></li>"].join("");
        },
        dropdown: $('#stationsearch-return')
    });

    $('#change-return-kst').click(function (e) {
        // pickup station has to be selected first!
        // show error if pickup hasn't been selected yet
        try {
            var uci_val = $('input[@name="uci"]').val();
        }
        catch (err) {
            var uci_val = $('input[name="uci"]').val();
        }
        if (uci_val == '') {
            $('#sx-res-rentarea-error').alert(res.ERR_START_UCI);
            //jump to error msg (anchor)
            //check if we are on the bavarian landingpage
            if( $('#start-wiesn-lp').length ){
                self.scrollTo(0,0);
            }

        }
        else {
            e.preventDefault();
            res.utility.open_jqm_at_anchor(returnstationBox, this);
        }
    }).one('click', function () {
        var selectReturnLiso = $('#select-return-liso');

        /*
         *  Display all stations dropdown only for single countries
         */
        if (!selectReturnLiso.length || selectReturnLiso.val())
            returnstationBox.removeClass("select-return-empty");
        else
            returnstationBox.addClass("select-return-empty");

        selectReturnLiso.selectBox({
            css: 'select',
            maxDisplay: 8,
            onSelect: function (i) {
                returnParam.liso = selectReturnLiso[0].options[i].value;

                var suggest = document.getElementById('suggest-return-kst');
                suggest.autocompleter.flushCache();

                /*
                 *  Display all stations dropdown only for single countries
                 */
                if (returnParam.liso) {
                    returnstationBox.removeClass("select-return-empty");
                    suggest.focus();
                    if (rci.value) {
                        rci.value = "";
                        suggest.value = "";
                    }
                    $(suggest).dblclick();
                } else
                    returnstationBox.addClass("select-return-empty");
            }
        });
    });

    /*
     *  Country selection.
     */
    var selectPickupLiso = $('#select-pickup-liso');

    /*
     *  Display all stations dropdown only for single countries
     */
    if (!selectPickupLiso.length || selectPickupLiso.val())
        stationsBlock.removeClass("select-pickup-empty");
    else
        stationsBlock.addClass("select-pickup-empty");

    var bdc_checkbox = document.getElementById('britdelcol');
    var bdc_switcher = function(switchon) {
        if (!bdc_checkbox) return;
        var pickup_suggest = document.getElementById('suggest-pickup-kst');
        var return_chooser = document.getElementById('sx-res-return-kst');
        var dropdown       = document.getElementById('stationsearch-open');
        if (switchon) {
            $(pickup_suggest).val(res.MSG_DELCOL).attr('disabled','disabled');
            $(return_chooser).hide();
            stationsBlock.addClass("select-pickup-empty");
            $(pickup_suggest).siblings('p').hide();
            $(pickup_suggest).siblings('h3').hide();
            uci.value = res.BRITDELCOL_CIT;
            rci.value = res.BRITDELCOL_CIT;
        } else {
            $(pickup_suggest).val('').removeAttr('disabled');
            $(return_chooser).show();
            stationsBlock.removeClass("select-pickup-empty");
            $(pickup_suggest).siblings('p').show();
            $(pickup_suggest).siblings('h3').show();
            $(bdc_checkbox).removeAttr('checked');
            uci.value = '';
            rci.value = '';
        }
    }

    if (bdc_checkbox) {
        $(bdc_checkbox).click(function() {
            bdc_switcher($(bdc_checkbox).attr('checked'));
        });
        if ($(bdc_checkbox).attr('checked')) bdc_switcher(1);
    }

    selectPickupLiso.selectBox({
        css: 'select',
        maxDisplay: 8,
        onSelect: function (i) {
            pickupParam.liso = selectPickupLiso[0].options[i].value;

            var suggest    = document.getElementById('suggest-pickup-kst');
            var britdelcol = document.getElementById('sx-res-britdelcol');
            var coi        = document.getElementById('sx-res-coi');
            var coi_header = document.getElementById('sx-res-coi-header');
            suggest.autocompleter.flushCache();

            /*
             *  Display all stations dropdown only for single countries
             */
            if (pickupParam.liso) {
                stationsBlock.removeClass("select-pickup-empty");
                if (pickupParam.liso == 'GB') {
                    if (britdelcol) $(britdelcol).show();
                    if (coi)        $(coi).show();
                    if (coi_header) $(coi_header).show();
                    bdc_switcher();
                } else {
                    if (britdelcol) $(britdelcol).hide();
                    if (coi)        $(coi).hide();
                    if (coi_header) $(coi_header).hide();
                    bdc_switcher();
                }
                // use getyourcar ibe if USA is selected as pickup country
                if (pickupParam.liso == 'US') {
                    window.location.href = "http://www.sixt.de/php/holiday/?allowedCountries=14";
                    return;
                }
                suggest.focus();
                if (uci.value) {
                    uci.value = "";
                    suggest.value = "";
                }
                setTimeout(function () {
                    $(suggest).dblclick();
                }, 0);
            } else
                stationsBlock.addClass("select-pickup-empty");
        }
    });

    express();

    /*
     *  The house moving calculator
     */
    var calcmove = document.getElementById("sx-res-calcmove");
    if (calcmove)
        $(calcmove).click(function (e) {
            var height = Math.min(630, (window.innerHeight || document.documentElement.clientHeight) - 70);
            var width = Math.min(940, (window.innerWidth || document.documentElement.clientWidth) - 70);
            var query = calcmove.href.indexOf("?") > -1 ? "&" : "?";
            tb_show("", calcmove.href + query + "keepThis=true&TB_iframe=true&height="+ height +"&width=" + width, null);
            e.preventDefault();
        });

    /*
     *  defines the extended-search popup
     */

    $('#sx-res-extended-search').css({
        position: 'absolute',
        left: stationsBlock_rect.left + 40,
        top: stationsBlock_rect.top + 300
    })
    .jqm({
        onShow: function (hash) {
            res.utility.hide_selectboxes();
            hash.w.show();
        },
        onHide: function (hash) {
            res.utility.show_selectboxes();
            hash.w.hide();
            hash.o.remove();
        }
    })
    .appendTo(document.body).hide();

    $('#sx-res-extended-search-pickup').click(function (e) {
        e.preventDefault();
        query = $('#suggest-pickup-kst').val();
        url = res.url.extendedsearch + '?adr=' + query + '&fn=uci';
        $('#sx-res-extended-search-link').attr('href',url);
        $('#sx-res-extended-search-query').text(query);
        box = $('#sx-res-extended-search');
        res.utility.open_jqm_at_anchor(box,this);
    });
    $('#sx-res-extended-search-return').click(function (e) {
        e.preventDefault();
        query = $('#suggest-return-kst').val();
        url = res.url.extendedsearch + '?adr=' + query + '&fn=rci';
        $('#sx-res-extended-search-link').attr('href',url);
        $('#sx-res-extended-search-query').text(query);
        box = $('#sx-res-extended-search');
        res.utility.open_jqm_at_anchor(box,this);
    });


    /*
     *  Function initializeResidence is in start.js
     *  (You can only change your residence on start page.)
     *  if start.js is included --> initialize the residence block.
     */
    if(typeof initializeResidence == "function")
        initializeResidence();

    /*
     *  Load resdetails for rebooking
     */
    res.utility.resdetails_load();
}

/*
 *  function for loading the rebooking overlay
 */
function loadModify(param,div,page)
{
    $('#sx-res-rentaldetails-modify').hide();
    $('#sx-res-rentaldetails-modify-unclickable').show();
    var narrow  =  (typeof sx_res_is_narrow == "undefined")? false : sx_res_is_narrow;
    var twidth  =  narrow? 500 : 710;
    var theight =  narrow? 350 : 300;

    var xurl = location.protocol + "/\/" + location.host + "/php/res/" + (page || "start_overlay_inline") + "?";
    if (param)
        xurl += param + "&";
    $.ajax({
        type: "POST",
        url: xurl,
        data: param,

        /*
         *  load the data inside the defined div, display it,
         *  define res and show it all in a thickbox
         */
        success: function(data){
            document.getElementById(div).innerHTML = data;
            document.getElementById(div).style.display = "block";
            res.start();

            /*
             *  open the div in a thickbox
             */
            tb_show("","#TB_inline?height=" + theight + "&width=" + twidth + "&inlineId=" + div, false);

            /*
             *  initialize the calendar
             */
            res.calendar.init();

            /*
             *  hide the close button
             */
            document.getElementById("TB_closeWindowButton").innerHTML = "";
            document.getElementById("TB_closeAjaxWindow").style.display = "none";

            /*
             *  closing the thickbox will hide the rebooking div content
             */
            $("#TB_overlay").click(function(){
                document.getElementById(div).style.display = "none";
                $('#sx-res-rentaldetails-modify-unclickable').hide();
                $('#sx-res-rentaldetails-modify').show();
            });


            $("#sx-res-close-overlay").click(function (e) {
                e.preventDefault();
                document.getElementById(div).style.display = "none";
                $('#sx-res-rentaldetails-modify-unclickable').hide();
                $('#sx-res-rentaldetails-modify').show();
                $("#sx-res-close-overlay").sxResGET(res.url.resettopoffer, {
                    hash: new Date().getTime()
                }, function () {} );

                try {
                    // permission denied if not same origin
                    parent.tb_remove();
                } catch (err) {
                    tb_remove();
                }
            }).attr("href", "");
        }
    });
}
