
/*
*
* C 2009 Open Hospitality, Inc.  All rights reserved.
*
*/

$(document).ready(function() {

    //Initialize cookie values
    $.cookie('multiroomversion', 'false', { path: '/' });

    //Modify Res Remove Progress Bar
    var psk50 = $.query.get('psk50');
    if (isvalidbrowser() && psk50.toLowerCase() == "psk50") {
        //$.cookie('jsaction', 'modifyres', { path: '/' });
        showprogress(true, false);
    };


    if (isvalidbrowser() == true && $.cookie('jsaction') != 'modifyres') {
        initializeComponents();
    };

    if ($.cookie('jsaction') == 'modifyres') {
        $('#buttons').hide();
    };

    function initializeComponents() {

        try {
            if (typeof BE.hotelinfo === "undefined") { throw "jquery.oh.be.dates.js --> BE.hotelinfo undefined"; }
            if (typeof BE.hotelstringresources === "undefined") { throw "jquery.oh.be.dates.js --> BE.hotelstringresources undefined"; }
        }
        catch (e) { errorresponsehandler(e, ajaxresult); }

        createnavigationbar(BE.hotelstringresources);

        //Multi-Room Support
        if (typeof $('#supports_multi_room').val() !== "undefined") {
            createmultiroomoption(BE.hotelinfo, BE.hotelstringresources);
            //show disclaimer information if room number selected is more than 1
            $('#controls button').click(function() {
                if (parseInt($('#pdrooms').val(), 10) !== 1) { $.cookie('multiroomversion', 'true', { path: '/' }); }
            });
        }


        if (isvalidbrowser()) {
            //Profile Landing Page
            var pageID = $.query.get('jsaction');
            if (typeof pageID != "undefined" && pageID == "guestprofile") {
                $('body').profilesignin({
                    onload: function() { showopaquelayer(); },
                    onclose: function() { showprogress(true); },
                    loginpassed: function(jsonresult) { initializeProfile(jsonresult); }
                });
            };

            //'Change/Cancel Reservations'
            $('#buttons').empty().html('<button>' + BE.hotelstringresources.$$FORM_CONTROL_PROFILE_MANAGER + '</button>');

            //Profile SignIn
            $('#buttons button').click(function() {
                profileSignin(initializeProfile);
            });

            function profileSignin(loginpassedFunction) {
                $('body').profilesignin(
				{
				    onload: function() { showopaquelayer(); },
				    onclose: function() { showprogress(true); },
				    loginpassed: function(jsonresult) { loginpassedFunction(jsonresult); }
				});
            };

            var _guestprofile;
            var _currentBooking;
            var _currentCCRecord;

            function initializeProfile(jsonresult) {
                var resLink = $('li#a-dates a').attr("href");
                if (typeof resLink != "undefined" && resLink.indexOf("#") >= 0) {
                    $("li#a-dates a").attr("href", resLink.split("#")[0]);
                }

                if (jsonresult !== "") {

                    var result = JSON.parse(jsonresult);
                    _guestprofile = result.guestprofile;

                    //hide dates page
                    $('#buttons, #steps, #message2, #datesselection, #languages, #flags, div#bookingengine > div#flags').hide();

                    //remove all profile parts
                    $('#active_reservations, #profile_shopperdetails, #save_guestinfo, #cancel_save_guestinfo, #guestccsummary, .ccrecords').remove();

                    $('#bookingengine').append("<div id='guestprofile'>");

                    //Active Reservations
                    $('#guestprofile').append($($('#profile_active_reservations_temp').parsetemplate(_guestprofile)));
                    emptyProfileTableMessage('#active_reservations', BE.hotelstringresources.$$FORM_CONTROL_NO_ACTIVE_RES);

                    //Guest Info
                    $('#guestprofile').append($($('#profile_guestinfo_temp').parsetemplate(_guestprofile.guestinfo)));
                    if (_guestprofile.guestinfo.customfieldids.length > 0) {
                        $.map(_guestprofile.guestinfo.customfieldids, function(customfieldid, i) {
                            $('#' + customfieldid).val(_guestprofile.guestinfo.customfieldvalues[i]);
                        });
                    }

                    //Guest CC Records
                    $('#guestprofile').append($($('#profile_ccsummary_temp').parsetemplate(_guestprofile)));
                    $('#ccinfowrap').hide();
                    emptyProfileTableMessage('#guestccsummary', BE.hotelstringresources.$$FORM_CONTROL_NO_ACTIVE_CC);

                    //Form Display Options

                    //Guest table sorting
                    $('#active_reservations > table').tablesorter();
                    $('.ccrecords > table').tablesorter({
							headers: { 
								5: { sorter: false }	
							} 
						});

                    $('#returnguestdetails').show();
                    $('#guestdetails, #save_guestinfo, #cancel_save_guestinfo').hide();
                    $('#specialRequests, ').remove();

                    //Guest title selected value
                    $('#title option[value=' + _guestprofile.guestinfo.title.toUpperCase() + ']').attr("selected", "selected");

                    //Guest state selected value
                    $('#state_js option[value=' + _guestprofile.guestinfo.addressinfo.statecode + ']').attr("selected", "selected");

                    //Guest country selected value
                    $('#country option[value=' + _guestprofile.guestinfo.addressinfo.countrycode + ']').attr("selected", "selected");

                    hideopaquelayer();

                    //Form Action Handlers


                    // ================================================================================================= CC MANAGER
                    $('div#active_reservations table th').click(function() {
                        $('tr.modifyMenu').hide();
                    });

                    //Modify Reservation
                    $('.modifyres').click(function(event) {
                        event.preventDefault();
                        $('tr.modifyMenu').hide();
                        $($('#profile_modifyres_menu_temp').parsetemplate({})).insertAfter($(this).parents('tr:eq(0)'));
                        _currentBooking = getsinglequeryresult(_guestprofile.bookings, "resnumber", $(this).attr('id'))

                        //Modify Booking Handler    
                        $('a.modifyreslink').click(function(event) {
                            event.preventDefault();
                            handleModifyRes(event, _currentBooking.resnumber);
                            return false;
                        });

                        //Modify Booked CC Info Handler
                        $('a.viewccsummary').click(function(event) {
                            event.preventDefault();
                            $('#ccinfowrap, .profile_ccinfo_update, #guestccinfo, .addcccontrols').hide();
                            $('#ccinfowrap').insertAfter($(this));
                            $('#ccinfowrap, #returnguestccinfo').show();
                            $($(".ccrecords tr:contains('" + _currentBooking.ccid + "')")).each(function() {
                                $(this).find("td:eq(1) input:radio").attr('checked', 'checked');
                            });

                            var $firstRow = $('div#returnguestccinfo .ccrecords tr:eq(0)');
                            var $selectedRow = $($('div#returnguestccinfo .ccrecords tr td input:checked')).parents('tr:eq(0)');

			if ($firstRow.get(0) !== $selectedRow.get(0)) {
				$selectedRow.insertBefore($firstRow);
			}

                            return false;
                        });

                        //Set New Booked CC Info
                        $('.setbookedcc').click(function(event) {

                            var newCCID = $('div#returnguestccinfo .ccrecords input:radio:checked').val();
                            event.preventDefault();

                            $.ajax({
                                type: "post",
                                timeout: 30000,
                                url: "be.ashx",
                                contentType: "application/x-www-form-urlencoded",
                                data: {
                                    'cmd': 'post',
                                    'psk588': 'psk588',
                                    'task': 'setbookedcc',
                                    'guestccrecord': _currentBooking.resnumber + "_" + newCCID,
                                    'pg': 'updateguestprofile'
                                },
                                success: function(ajaxresult) {

                                    //Check for error
                                    var errorCode = JSON.parse(ajaxresult).errorcode;
                                    if (typeof errorCode === "undefined") {
                                        _currentBooking.ccid = newCCID;
                                    }
                                    else {
                                        if (errorCode === "LOGIN") {
                                            profileSignin(initializeProfile);
                                            return false;
                                        }
                                        $('body').popupwarning({
                                            warningheader: BE.hotelstringresources.$$FORM_CONTROL_SORRY,
                                            warningmessage: 'Your transaction could not be processed.',
                                            buttondisplaytext: 'Try Again',
                                            onload: function() { showopaquelayer(); },
                                            onclose: function() { hideopaquelayer(); },
                                            onbuttonclick: function() { }
                                        });
                                    }
                                },

                                error: function(request, errorType, errorThrown) { ajaxerrorhandler(request, errorType, errorThrown); }

                            });
                            $('.modifyMenuTitle').hide();
                            return false;

                        });

                        $('.cancelsetbookedcc').click(function(event) {
                            event.preventDefault();
                            $('.modifyMenuTitle').hide();
                            return false;
                        });

                    });

                    //Modify CC Info
                    handleModifyCC();

                    // ================================================================================================= CC MANAGER

                    //Cancel Reservation
                    handleCancelRes();

                    //View Reservation
                    handleViewConfirmation();

                    //Save Guest Info
                    handleSaveGuestInfo();

                    //Edit Guest Info
                    $('#returnguestdetails a.userbutton').click(function(event) {
                        $('#returnguestdetails').hide();
                        $('#guestdetails, #save_guestinfo, #cancel_save_guestinfo').show();
                        event.preventDefault();
                        return false;
                    });

                }
            };


            function handleModifyCC() {

                $('.ccrecords, #guestccinfo').unbind('click');

                $('div#guestccsummary .ccrecords a.ccmodify').click(function(event) {
                    event.preventDefault();
                    $.ccmanager.ccexpcontroldate = null;
                    $.ccmanager.ccmodifylink = "div#guestccsummary .ccrecords a.ccmodify";
                    $.ccmanager.loadccrec = GetCCRecord2;
                    $.ccmanager.showremovecc = true;
                    return false;
                });

                $('div#returnguestccinfo .ccrecords a.ccmodify').click(function(event) {
                    event.preventDefault();
                    $('#setbookedcccontrols').hide();
                    $.ccmanager.ccexpcontroldate = _currentBooking.checkoutgeneric;
                    $.ccmanager.ccmodifylink = "div#returnguestccinfo .ccrecords a.ccmodify";
                    $.ccmanager.loadccrec = GetCCRecord1;
                    $.ccmanager.showremovecc = false;
                    return false;
                });

                $('div#returnguestccinfo a#addnewcc').click(function(event) {
                    event.preventDefault();
                    $('#setbookedcccontrols').hide();
                    $.ccmanager.ccexpcontroldate = _currentBooking.checkoutgeneric;
                    $.ccmanager.showremovecc = false;
                    return false;
                });

                $('.ccrecords').ccmanager({
                    booking: _currentBooking,
                    loadccrec: GetCCRecord2,
                    oncomplete: RefreshCCRecords
                });
            }

            function GetCCRecord1(ccRow) {
                var ccRec = new CCRecord();
                ccRec.ccid = $($(ccRow).children('td')[0]).html();
                ccRec.cctype = $($(ccRow).children('td')[2]).html();
                ccRec.ccnumber = $($(ccRow).children('td')[3]).html();
                ccRec.ccexpmonth = $($(ccRow).children('td')[4]).html().split("/")[0];
                ccRec.ccexpyear = $($(ccRow).children('td')[4]).html().split("/")[1];
                ccRec.ccbillingname = $($(ccRow).children('td')[5]).html();
                ccRec.ccbillingaddress = $($(ccRow).children('td')[7]).html();
                return ccRec;
            };

            function GetCCRecord2(ccRow) {
                var ccRec = new CCRecord();
                ccRec.ccid = $($(ccRow).children('td')[0]).html();
                ccRec.cctype = $($(ccRow).children('td')[1]).html();
                ccRec.ccnumber = $($(ccRow).children('td')[2]).html();
                ccRec.ccexpmonth = $($(ccRow).children('td')[3]).html().split("/")[0];
                ccRec.ccexpyear = $($(ccRow).children('td')[3]).html().split("/")[1];
                ccRec.ccbillingname = $($(ccRow).children('td')[4]).html();
                ccRec.ccbillingaddress = $($(ccRow).children('td')[6]).html();
                return ccRec;
            };

            function RefreshCCRecords(ccrec) {

                $('.profile_ccinfo_update').remove();
                $('#setbookedcccontrols').show();

                if (typeof ccrec != "undefined" && ccrec != null) {

                    $($(".ccrecords tr:contains('" + ccrec.ccid + "')")).removeClass("ccexpired");

                    if (ccrec.removeccinfo) {
                        $($(".ccrecords tr:contains('" + ccrec.ccid + "')")).remove();
                        emptyProfileTableMessage('#guestccsummary', BE.hotelstringresources.$$FORM_CONTROL_NO_ACTIVE_CC);
                        return;
                    };

                    if ($($("div#guestccsummary .ccrecords tr:contains('" + ccrec.ccid + "')")).length > 0) {

                        $($("div#guestccsummary .ccrecords tr:contains('" + ccrec.ccid + "')")).each(function() {
                            $(this).find("td:eq(3)").text(ccrec.ccexpmonth + '/' + ccrec.ccexpyear);
                            $(this).find("td:eq(4)").text(ccrec.ccbillingname);
                            $(this).find("td:eq(5)").text((ccrec.ccbillingaddress.length > 20 ? ccrec.ccbillingaddress.substr(0, 20) + "..." : ccrec.ccbillingaddress));
                            $(this).find("td:eq(6)").text(ccrec.ccbillingaddress);
                        });

                    }
                    else {

                        $('div#guestccsummary .ccrecords table tr:last').after(
                        '<tr>' +
			                '<td class="hidden">' + ccrec.ccid + '</td>' +
                            '<td style="padding-left: 11px;">' + ccrec.cctypedesc + '</td>' +
                            '<td>' + ccrec.ccnumber + '</td>' +
                            '<td>' + ccrec.ccexpmonth + '/' + ccrec.ccexpyear + '</td>' +
                            '<td>' + ccrec.ccbillingname + '</td>' +
                            '<td>' + (ccrec.ccbillingaddress.length > 20 ? ccrec.ccbillingaddress.substr(0, 20) + "..." : ccrec.ccbillingaddress) + '</td>' +
                            '<td class="hidden">' + ccrec.ccbillingaddress + '</td>' +
                            '<td><a class="ccmodify" href="#">modify</a></td>' +
			            '</tr>');

                        $('div#guestccsummary .ccrecords table tr:last a.ccmodify').click(function(event) {
                            event.preventDefault();
                            handleModifyCC();
                            return false;
                        });

                    };

                    if ($($("div#returnguestccinfo .ccrecords tr:contains('" + ccrec.ccid + "')")).length > 0) {

                        $($("div#returnguestccinfo .ccrecords tr:contains('" + ccrec.ccid + "')")).each(function() {
                            $(this).find("td:eq(4)").text(ccrec.ccexpmonth + '/' + ccrec.ccexpyear);
                            $(this).find("td:eq(5)").text(ccrec.ccbillingname);
                            $(this).find("td:eq(6)").text((ccrec.ccbillingaddress.length > 20 ? ccrec.ccbillingaddress.substr(0, 20) + "..." : ccrec.ccbillingaddress));
                            $(this).find("td:eq(7)").text(ccrec.ccbillingaddress);
                        });

                    }
                    else {

                        $('div#returnguestccinfo .ccrecords table tr:last').after(
                        '<tr>' +
			              '<td class="hidden">' + ccrec.ccid + '</td>' +
			              '<td><input type="radio" value="' + ccrec.ccid + '" name="ccrecord"></td>' +
			              '<td>' + ccrec.cctypedesc + '</td>' +
			              '<td>' + ccrec.ccnumber + '</td>' +
			              '<td>' + ccrec.ccexpmonth + '/' + ccrec.ccexpyear + '</td>' +
			              '<td>' + ccrec.ccbillingname + '</td>' +
                          '<td>' + (ccrec.ccbillingaddress.length > 20 ? ccrec.ccbillingaddress.substr(0, 20) + "..." : ccrec.ccbillingaddress) + '</td>' +
                          '<td class="hidden">' + ccrec.ccbillingaddress + '</td>' +
			              '<td><a class="ccmodify" href="#">modify</a></td>' +
			            '</tr>');

                        $($(".ccrecords tr:contains('" + ccrec.ccid + "')")).each(function() {
                            $(this).find("td:eq(1) input:radio").attr('checked', 'checked');
                        });

                        $('div#returnguestccinfo .ccrecords table tr:last a.ccmodify').click(function(event) {
                            event.preventDefault();
                            handleModifyCC();
                            return false;
                        });

                    };
                }
            };

            function handleSaveGuestInfo() {

                $('#save_guestinfo a').click(function(event) {

                    event.preventDefault();

                    //form validation 
                    var _formvalidated = true;
                    $('#guestdetails .regrequired').each(function() {
                        $(this).removeClass('errorfield');
                        if (trim($(this).val()) === '') {
                            $(this).addClass('errorfield');
                            _formvalidated = false;
                        }
                    });

                    $('#guestdetails .errorfield').blur(function() {
                        if ($(this).val() !== '') { $(this).removeClass('errorfield'); }
                    });

                    if (_formvalidated === false) { $($('#guestdetails .errorfield')[0]).focus(); return false; }

                    // custom fields
                    var guestcsfd = new objectcollection();
                    $('#guestdetails .csfd').each(function() {
                        guestcsfd.add({ "id": this.id, "value": $(this).val() });
                    });

                    var _guest = {
                        guestid: $('#guestid').val(),
                        title: $('#title').val(),
                        firstname: $('#firstname').val(),
                        lastname: $('#lastname').val(),
                        companyname: $('#companyname').val().replace('&', ' '),
                        address: $('#streetaddress').val(),
                        city: $('#city_js').val(),
                        state: $('#state_js').val(),
                        addressother: $('#addressother').val(),
                        zipcode: $('#zipcode').val(),
                        country: $('#country').val(),
                        phone: $('#phone').val(),
                        fax: $('#fax').val(),
                        emailaddressalternate: $('#emailaddressalternate').val(),
                        passwordinitial: $('#passwordinitial').val(),
                        passwordconfirm: $('#passwordconfirm').val(),
                        specialoffersignup: $('#promooption').attr("checked"),
                        csfd: guestcsfd
                    };

                    $('#profile_shopperdetails').empty().html('<img src="./images/ajax-loader.gif" />');
                    $('#save_guestinfo, #cancel_save_guestinfo').empty();

                    $.ajax({
                        type: "post",
                        timeout: 30000,
                        url: "be.ashx",
                        contentType: "application/x-www-form-urlencoded",
                        data: {
                            'cmd': 'post',
                            'psk588': 'psk588',
                            'task': 'updateguestprofile',
                            'updateguest': $('#profile_modify_guestinfo_temp').parsetemplate(_guest),
                            'pg': 'updateguestprofile'
                        },
                        success: function(ajaxresult) {
                            var result = JSON.parse(ajaxresult);
                            if (typeof result.error != "undefined" && result.error) {
                                HandleServerErrorResponse(result);
                                return false;
                            };

                            var errorCode = result.errorcode;
                            var errorMsg;

                            if (typeof errorCode !== "undefined") {
                                errorMsg = result.errormsg;
                                if (errorCode === "LOGIN") {
                                    profileSignin(initializeProfile);
                                    return false;
                                }
                            }
                            else {

                                //Refresh all guest info from the server
                                $('#profile_shopperdetails, #specialRequests, #formError, #save_guestinfo, #cancel_save_guestinfo').remove();
                                _guestprofile = result.guestprofile;

                                $($('#profile_guestinfo_temp').parsetemplate(_guestprofile.guestinfo)).insertAfter('#active_reservations');
                                if (_guestprofile.guestinfo.customfieldids.length > 0) {
                                    $.map(_guestprofile.guestinfo.customfieldids, function(customfieldid, i) {
                                        $('#' + customfieldid).val(_guestprofile.guestinfo.customfieldvalues[i]);
                                    });
                                }
                                $('#save_guestinfo, #cancel_save_guestinfo').appendTo('#guestdetails');

                                $('#returnguestdetails a').click(function(event) {
                                    $('#returnguestdetails').hide();
                                    $('#guestdetails, #save_guestinfo, #cancel_save_guestinfo').show();
                                    $('#title option[value=' + _guestprofile.guestinfo.title.toUpperCase() + ']').attr("selected", "selected");
                                    $('#state_js option[value=' + _guestprofile.guestinfo.addressinfo.statecode + ']').attr("selected", "selected");
                                    $('#country option[value=' + _guestprofile.guestinfo.addressinfo.countrycode + ']').attr("selected", "selected");
                                    event.preventDefault();
                                    return false;
                                });

                                $('#guestdetails, #save_guestinfo, #cancel_save_guestinfo').hide();

                                handleSaveGuestInfo();
                            }

                        },
                        error: function(request, errorType, errorThrown) { ajaxerrorhandler(request, errorType, errorThrown); }
                    });

                    return false;
                });

                $('#cancel_save_guestinfo a').click(function(event) {
                    $('#returnguestdetails').show();
                    $('#guestdetails, #save_guestinfo, #cancel_save_guestinfo').hide();
                    event.preventDefault();
                    return false;
                });

            };

            function handleModifyRes(event, resNumber) {

                //Process Reservation Modification
                if (resNumber !== '') {

                    $('body').popupwarning({
                        onload: function() { showopaquelayer(); },
                        onclose: function() { hideopaquelayer(); },
                        warningheader: BE.hotelstringresources.$$FORM_CONTROL_CHANGE_RESERVATION,
                        warningmessage: BE.hotelstringresources.$$DIALOG_TO_MODIFY_RESERVATION + " " + resNumber + BE.hotelstringresources.$$DIALOG_PLEASE_CLICK_OK,
                        showhyperlink: true,
                        buttondisplaytext: "OK",
                        hyperlinkdisplaytext: BE.hotelstringresources.$$FORM_CONTROL_NOT_MODIFY_RES,
                        onhyperlinkclick: function() { hideopaquelayer(); },
                        onbuttonclick: function() {

                            showActionProgress(false);

                            $.ajax({
                                type: "post",
                                timeout: 30000,
                                url: "be.ashx",
                                contentType: "application/x-www-form-urlencoded",
                                data: {
                                    'cmd': 'post',
                                    'psk588': 'psk588',
                                    'task': 'modifyres',
                                    'resnumber': resNumber,
                                    'pg': 'modifyres'
                                },
                                success: function(ajaxresult) {
                                    var result = JSON.parse(ajaxresult);
                                    if (typeof result.error != "undefined" && result.error) {
                                        HandleServerErrorResponse(result);
                                        return false;
                                    };

                                    var errorCode = result.errorcode;
                                    var errorMsg;

                                    if (typeof errorCode !== "undefined") {
                                        errorMsg = result.errormsg;
                                        if (errorCode === "LOGIN") {
                                            profileSignin(initializeProfile);
                                            return false;
                                        }
                                    }

                                    if (typeof errorCode == "undefined" && result.modifyredirect != "undefined") {
                                        window.location = result.modifyredirect;
                                    }

                                    else {
                                        $('body').popupwarning(
								        {
								            onload: function() { },
								            onclose: function() { hideopaquelayer(); },
								            warningheader: BE.hotelstringresources.$$FORM_CONTROL_SORRY,
								            warningmessage: errorMsg,
								            showhyperlink: false,
								            buttondisplaytext: BE.hotelstringresources.$$BUTTON_CLOSE,
								            hyperlinkdisplaytext: "",
								            onhyperlinkclick: function() { },
								            onbuttonclick: function() {
								                showActionProgress(true);
								            }
								        });

                                    }

                                }

                            });
                        }
                    });
                }
            };

            function handleCancelRes() {

                $('.cancelreslink').click(function(event) {

                    event.preventDefault();

                    if ($(this).attr("resnum") !== '') {

                        var canxRes = $(this);
                        var resNumber = $(canxRes).attr("resnum");

                        $('body').popupwarning({
                            onload: function() { showopaquelayer(); },
                            onclose: function() { hideopaquelayer(true); },
                            warningheader: BE.hotelstringresources.$$FORM_CONTROL_CANCEL_RESERVATION,
                            warningmessage: BE.hotelstringresources.$$DIALOG_RESERVATION + " " + resNumber + " " + BE.hotelstringresources.$$DIALOG_WILL_BE_CANCELLED,
                            showhyperlink: true,
                            buttondisplaytext: "OK",
                            hyperlinkdisplaytext: BE.hotelstringresources.$$FORM_CONTROL_NOT_CANCEL_RES,
                            onhyperlinkclick: function() { hideopaquelayer(); },
                            onbuttonclick: function() {

                                $('#errorMD').remove();
                                showprogress(false);

                                //Process Cancellation
                                $.ajax(
								{
								    type: "post",
								    timeout: 30000,
								    url: "be.ashx",
								    contentType: "application/x-www-form-urlencoded",
								    data: {
								        'cmd': 'post',
								        'psk588': 'psk588',
								        'task': 'cancelres',
								        'resnumber': resNumber,
								        'pg': 'cancelres'
								    },
								    success: function(ajaxresult) {

								        var result = JSON.parse(ajaxresult);
								        if (typeof result.error != "undefined" && result.error) {
								            HandleServerErrorResponse(result);
								            return false;
								        };

								        var errorCode = result.errorcode;
								        var errorMsg;
								        var msgHeader;

								        if (typeof errorCode !== "undefined") {
								            msgHeader = BE.hotelstringresources.$$FORM_CONTROL_RES_CANCELLED_ERRORTITLE;
								            errorMsg = result.errormsg;
								            if (errorCode === "LOGIN") {
								                profileSignin(initializeProfile);
								                return false;
								            }
								        }

								        else {
								            var canxconfirm = result.canxconfirm;
								            canxconfirm.hotelstringresources = BE.hotelstringresources;
								            msgHeader = BE.hotelstringresources.$$FORM_CONTROL_RES_CANCELLED;
								            errorMsg = $('#reservation_canx_confirm_temp').parsetemplate(canxconfirm);
								        }


								        $('body').popupwarning(
										{
										    onload: function() { },
										    onclose: function() { showprogress(true); },
										    warningheader: msgHeader,
										    warningmessage: errorMsg,
										    showhyperlink: false,
										    buttondisplaytext: BE.hotelstringresources.$$BUTTON_CLOSE,
										    hyperlinkdisplaytext: "",
										    onhyperlinkclick: function() { },
										    onbuttonclick: function() {
										        showprogress(true);

										        if (typeof errorCode === "undefined") {
										            var canxrecord = {
										                resnumber: $($(canxRes).parent().siblings('td')[0]).html(),
										                checkin: $($(canxRes).parent().siblings('td')[1]).html(),
										                checkout: $($(canxRes).parent().siblings('td')[2]).html(),
										                name: $($(canxRes).parent().siblings('td')[3]).html(),
										                room: $($(canxRes).parent().siblings('td')[4]).html(),
										                total: $($(canxRes).parent().siblings('td')[5]).html(),
										                action: $($(canxRes).parent().siblings('td')[8]).html()
										            };

										            var newRowHTML =
												'<tr>' +
													'<td>' + canxrecord.resnumber + '</td>' +
													'<td>' + canxrecord.checkin + '</td>' +
													'<td>' + canxrecord.checkout + '</td>' +
													'<td>' + canxrecord.name + '</td>' +
													'<td>' + canxrecord.room + '</td>' +
													'<td>' + canxrecord.total + '</td>' +
													'<td><span class="viewreslink" resnum="' + resNumber + '"><a href="#">view confirmation</a></td>' +
												'</tr>'

										            //$('div#old_reservations').show();
										            //$(newRowHTML).insertBefore('#old_reservations table tbody>tr:first');
										            //$('.viewreslink').click(function() { viewConfirmation(this); return false; });
										            $(canxRes).parent('td').parent('tr').remove();
										            $('tr.modifyMenu').hide();
										            emptyProfileTableMessage('#active_reservations', BE.hotelstringresources.$$FORM_CONTROL_NO_ACTIVE_RES);
										        }

										    }
										});
								    },
								    error: function(request, errorType, errorThrown) { ajaxerrorhandler(request, errorType, errorThrown); }
								});

                            }
                        });
                    }

                    return false;
                });      // cancel res

            };

            function handleViewConfirmation() {

                $('.viewreslink').click(function() {

                    //$('#opaquelayer').css({ width: $(document).width(), height: $(document).height() });
                    showprogress(false, false);

                    if ($(this).attr("resnum") !== '') {

                        var resNumber = $(this).attr("resnum");

                        //Request Email
                        $.ajax({
                            type: "post",
                            timeout: 30000,
                            url: "be.ashx",
                            contentType: "application/x-www-form-urlencoded",
                            data: {
                                'cmd': 'post',
                                'psk588': 'psk588',
                                'task': 'viewres',
                                'resnumber': resNumber,
                                'pg': 'viewres'
                            },
                            success: function(ajaxresult) {

                                showprogress(true);
                                var result = JSON.parse(ajaxresult);
                                if (typeof result.error != "undefined" && result.error) {
                                    HandleServerErrorResponse(result);
                                    return false;
                                };

                                var errorCode = result.errorcode;
                                var errorMsg;

                                if (typeof errorCode !== "undefined") {
                                    errorMsg = result.errormsg;
                                    if (errorCode === "LOGIN") {
                                        profileSignin(initializeProfile);
                                        return false;
                                    }
                                }
                                else {
                                    errorMsg = result.canxconfirm;
                                }

                                $('#save_guestinfo, #cancel_save_guestinfo, #active_reservations, #profile_shopperdetails, #guestccsummary, .ccrecords').hide();

                                var _bookingrecord = result.bookingrecord;
                                _bookingrecord.hotelstringresources = BE.hotelstringresources;

                                var shoppercsfd = new objectcollection();
                                for (var i = 0; i < _bookingrecord.primaryguest.csfd.length; i++) {
                                    var _customitem = _bookingrecord.primaryguest.csfd[i];
                                    shoppercsfd.add({ "id": _customitem.id, "value": _customitem.value });
                                };
                                _bookingrecord.primaryguest.csfd = shoppercsfd;

                                $('#guestprofile').append($($('#profile_confirmation_temp').parsetemplate(_bookingrecord)));

                                $('#goback').click(function() {
                                    $('#confirmation').remove();
                                    $('#active_reservations, #profile_shopperdetails, #guestccsummary, .ccrecords').show();
                                });

                                $('#printconfirm').click(function() { printConfirmation() });
                                $('#emailconfirm').click(function() { emailConfirmation(resNumber) });
                            },

                            error: function(request, errorType, errorThrown) { ajaxerrorhandler(request, errorType, errorThrown); }
                        });
                    }

                    return false;

                });

            }; //view confirmation

            function printConfirmation() {

                var confirm = $("#bewrapper").clone();

                $(confirm).find('#languages, #flags, #controls, #goback, #printconfirm, #emailconfirm').remove();
                var html = "<HTML>\n<HEAD>\n" +
										$("head").html() + "\n" +
										"</HEAD>\n<BODY>\n" +
										confirm.html() +
										"\n</BODY>\n</HTML>";

                var printWP = window.open("", "PrintConfirmation");
                printWP.document.open();

                printWP.document.write(html);
                printWP.document.close();
                printWP.print();

            }; //print confirmation

            function emailConfirmation(resNumber) {

                //$('#opaquelayer').css({ width: $(document).width(), height: $(document).height() });
                showprogress(false, false);

                //Request Email
                $.ajax({
                    type: "post",
                    timeout: 30000,
                    url: "be.ashx",
                    contentType: "application/x-www-form-urlencoded",
                    data: {
                        'cmd': 'post',
                        'psk588': 'psk588',
                        'task': 'emailres',
                        'resnumber': resNumber,
                        'pg': 'emailres'
                    },
                    success: function(ajaxresult) {

                        if (ajaxresult !== "") {
                            if (ajaxresult.indexOf("error") >= 0) {
                                var result = JSON.parse(ajaxresult);
                                if (typeof result.error != "undefined" && result.error) {
                                    HandleServerErrorResponse(result);
                                    return false;
                                };
                                var errorCode = result.errorcode;
                                var errorMsg;
                                if (typeof errorCode !== "undefined") {
                                    errorMsg = result.errormsg;
                                    if (errorCode === "LOGIN") {
                                        profileSignin(initializeProfile);
                                        return false;
                                    }
                                }
                            }
                            //Show Sent Email Confirmation
                            $('body').popupwarning({
                                onload: function() { showopaquelayer(); },
                                onclose: function() { showprogress(true); },
                                warningheader: BE.hotelstringresources.$$FORM_CONTROL_EMAIL_CONFIRM,
                                warningmessage: ajaxresult,
                                showhyperlink: false,
                                buttondisplaytext: BE.hotelstringresources.$$BUTTON_CLOSE,
                                onbuttonclick: function() { showprogress(true); }
                            });
                        }

                    },
                    error: function(request, errorType, errorThrown) { ajaxerrorhandler(request, errorType, errorThrown); }
                });

            }; // email res


            function showActionProgress(hide) {

                $('#progress').remove();

                if (hide) {
                    hideopaquelayer();
                }
                else {

                    $('body').append($('#progress_temp').parsetemplate({ hotelstringresources: BE.hotelstringresources }));

                    // position the popup on the center of the page
                    leftVal = $(window).width() / 2 - ($('#progress').width() / 2); // -$('#bookingengine').offset().left;
                    topVal = $(window).height() / 2 - ($('#progress').height() / 2) + $(window).scrollTop(); // -$('#bookingengine').offset().top;
                    $('#progress').css({ top: topVal, left: leftVal });
                    $('#progress').show();

                    showopaquelayer();
                }
            };

            function trim(stringToTrim) {
                return stringToTrim.replace(/^\s+|\s+$/g, "");
            };

            function emptyProfileTableMessage(locationID, msgContent) {

                if ($(locationID + ' table:eq(0) tbody tr').length === 0) {
                    $(locationID + ' table').remove();
                    $('<h3>' + msgContent + '</h3>').insertAfter(locationID + ' hr');
                }

            };

        }
        else {
            $.cookie('multiroomversion', 'true', { path: '/' });
        }

    };
});



