﻿if (undefined != window.TGSregisterNameSpaces && TGSregisterNameSpaces != null) {
    TGSregisterNameSpaces("TGS.HotelReviews");
}
else {
    Ext.ns("TGS.HotelReviews");
}

function HotelReviews() {

    /*private*/
    var clearContainer = function(node) {
        while (node.hasChildNodes()) {
            // fix for firefox copy
            if (document.addEventListener && typeof node.blur == 'function') node.blur();
            node.removeChild(node.firstChild);
        }
    }

    this.Reviews = (function() {
        /*private*/
        var isBusy = false;

        var RedirectToURL = function(valResult) {

            window.location = valResult.TargetUrl;
        }

        return {

            Show: function(showWriteReview) {

                if (!TGS.BookFlow.GlobalVars.HotelDetails.ShowUndercover && TGS.BookFlow.GlobalVars.HotelDetails.ReviewCount > 0) {
                    var revResultsTemplate = new Ext.XTemplate(reviewResultsTemplate);
                    revResultsTemplate.overwrite('reviewsList', TGS.BookFlow.GlobalVars.HotelDetails.ReviewsJSON.ReviewsPage);
                }

                if (showWriteReview)
                    TGS.HotelReviews.WriteReviewPopup.Show();
            },

            FilterResults: function(filterValue) {
                this.UpdateResults("filterBy", TGS.BookFlow.HotelDetailsStep.BuildActionParameters(
                {
                    FilterBy: filterValue,
                    SortBy: TGS.BookFlow.GlobalVars.HotelDetails.ReviewsJSON.ReviewsPage.CurrentSort
                }));
            },

            SortResults: function(sortValue) {
                this.UpdateResults("filterBy", TGS.BookFlow.HotelDetailsStep.BuildActionParameters(
                {
                    FilterBy: TGS.BookFlow.GlobalVars.HotelDetails.ReviewsJSON.ReviewsPage.CurrentFilter,
                    SortBy: sortValue
                }));
            },

            SwitchPage: function(pageIndex) {
                this.UpdateResults("switchPage", TGS.BookFlow.HotelDetailsStep.BuildActionParameters(
                {
                    NewPageIndex: pageIndex,
                    FilterBy: TGS.BookFlow.GlobalVars.HotelDetails.ReviewsJSON.ReviewsPage.CurrentFilter,
                    SortBy: TGS.BookFlow.GlobalVars.HotelDetails.ReviewsJSON.ReviewsPage.CurrentSort
                }));
            },

            UpdateResults: function(type, paramObj) {
                if (isBusy) {
                    return;
                }

                isBusy = true;
                try {
                    Ext.Ajax.request({
                        url: 'handlers/HotelReviews.ashx?type=' + type,
                        method: 'POST',
                        params: { pagePostData: Ext.util.JSON.encode(paramObj) },
                        success: function(response) {
                            isBusy = false;

                            if (response.responseText && response.responseText.indexOf("{") != -1) {
                                var result = Ext.util.JSON.decode(response.responseText);
                                if (result && result.isSuccess) {
                                    var valResult = result.ProcessResult;
                                    for (var i = 0; i < valResult.length; i++) {
                                        switch (valResult[i].TIAction) {
                                            case 'Redirect':
                                                RedirectToURL(valResult[i]);
                                                break;
                                            case 'RunClientScript':
                                                TGS.BookFlow.RunClientScript(valResult[i], null);
                                                break;
                                        }
                                    }
                                }
                            }
                        },
                        failure: function(response) {
                            isBusy = false;
                            window.location = TGS.BookFlow.GlobalVars.ErrorPageUrl;
                        }
                    });
                } catch (e) {
                    isBusy = false;
                    window.location = TGS.BookFlow.GlobalVars.ErrorPageUrl;
                }
            },

            ShowResults: function(param) {
                TGS.BookFlow.GlobalVars.HotelDetails.ReviewsJSON.ReviewsPage = param;

                clearContainer($('reviewsList'));
                var reviewResultsTemplate = Ext.XTemplate.from('reviewResultsTemplate');
                reviewResultsTemplate.overwrite('reviewsList', TGS.BookFlow.GlobalVars.HotelDetails.ReviewsJSON.ReviewsPage);
            }
        };
    })();

    this.WriteReviewPopup = (function() {
        /*private*/
        var isBusy = false;

        var isBuilt = false;

        var previousKeyPress = null;
        var previousKeyDown = null;

        var markRating = function(str, index) {
            var arr = str.split("");
            arr[index] = 1;
            return arr.join("")
        }

        /*private*/
        var InitRatingModule = function(ratingIndex, clientId, value) {

            var ratings = [
                $(clientId + '_1'),
                $(clientId + '_12'),
                $(clientId + '_2'),
                $(clientId + '_23'),
                $(clientId + '_3'),
                $(clientId + '_34'),
                $(clientId + '_4'),
                $(clientId + '_45'),
                $(clientId + '_5')
                ];

            function selectRating(index) {
                for (var j = 0; j < 9; j += 2) {
                    ratings[j].className = index >= ratings[j].index ? "NH_rate_on" : "NH_rate_off";
                }
            }

            var allRatings = $(TGS.BookFlow.GlobalVars.WriteReviewClientIDs.rmAllRatings);

            if (value > 0)
                allRatings.value = markRating(allRatings.value, ratingIndex);

            $(clientId).onmouseout = function() { selectRating($(clientId).value); }

            var k = 1;
            for (var j = 0; j < 9; j++) {
                ratings[j].index = k;
                ratings[j].onmouseover = function() { selectRating(this.index); }

                ratings[j].onclick = function() {
                    selectRating(this.index);
                    $(clientId).value = this.index.toString();

                    allRatings.value = markRating(allRatings.value, ratingIndex);

                    var validator = new TGS.BookFlow.Validator(TGS.BookFlow.GlobalVars.MappingObject);
                    validator.validateControl(TGS.BookFlow.GlobalVars.WriteReviewClientIDs.rmAllRatings);
                }

                if ((j % 2) == 1) k++;
            }

            selectRating(value);
        }

        var getActiveRadio = function(rbs) {
            for (var i = 0; i < rbs.length; i++) {
                var el = $(rbs[i]);
                if (el.checked) return el;
            }
        }

        var getObject = function(elem) {
            if (typeof elem === "string") {
                return $(elem);
            } else {
                return getActiveRadio(elem);
            }
        }

        var getActiveElementIndex = function(tabOrders, eid) {
            for (var i = 0; i < tabOrders.length; i++) {
                if (typeof tabOrders[i] === "string") {
                    if (tabOrders[i] === eid) {
                        return i;
                    }
                }
                else {
                    for (var j = 0; j < tabOrders[i].length; j++) {
                        if (tabOrders[i][j] === eid) {
                            return i;
                        }
                    }
                }
            }

            return -1;
        }

        var OnClosed = function() {
            document.onkeypress = this.previousKeyPress;
            document.onkeydown = null;
        }

        var OnOpened = function() {
            this.previousKeyPress = document.onkeypress;
            document.onkeypress = null;

            var tabOrders = TGS.BookFlow.GlobalVars.WriteReviewClientIDs.tabOrder;

            this.previousKeyDown = document.onkeydown;
            // keep focus in popup with Tab key
            document.onkeydown = function(e) {
                if (!e) e = event;

                var target = e.target ? e.target : e.srcElement;

                if (e.keyCode == 13) { //ENTER
                    if (target == null || typeof target == "undefined" || target.nodeName.toLowerCase() != "textarea") {
                        TGS.HotelReviews.WriteReviewPopup.Submit();
                        return false;
                    }
                }

                if (e.shiftKey && e.keyCode == 9) //SHIFT+TAB
                {
                    var activeObjIndex = getActiveElementIndex(tabOrders, target.id);
                    activeObjIndex--;
                    if (activeObjIndex == -2) activeObjIndex = 0;
                    else if (activeObjIndex == -1) activeObjIndex = tabOrders.length - 1;

                    getObject(tabOrders[activeObjIndex]).focus();

                    return false;
                } else if (!e.shiftKey && e.keyCode == 9) //TAB
                {
                    var activeObjIndex = getActiveElementIndex(tabOrders, target.id);
                    activeObjIndex++;
                    if (activeObjIndex >= tabOrders.length) activeObjIndex = 0;

                    getObject(tabOrders[activeObjIndex]).focus();

                    return false;
                }
            }
        }

        var EscapeBeforeSubmit = function(ctrl) {
            var prev = ctrl.value;
            ctrl.value = ctrl.value.replace(/\&/g, "&amp;").replace(/\</g, "&lt;");
            return prev;
        }

        return {
            ShowThankYou: function() {
                TGS.BookFlow.HotelDetailsStep.ShowPanel('writeReviewContainer', 'mask', false,
                    function() {
                        TGS.BookFlow.HotelDetailsStep.ShowPanel('reviewThankyouContainer', 'mask');
                    });

                document.onkeydown = null;
                document.onkeypress = function(e) {
                    if (codeTouche && codeTouche(e) == 13) {
                        TGS.HotelReviews.WriteReviewPopup.CloseThankYou();
                        return false;
                    }
                }
            },
            CloseThankYou: function() {
                TGS.BookFlow.HotelDetailsStep.ShowPanel('reviewThankyouContainer', 'mask', !TGS.BookFlow.GlobalVars.HotelDetails.IsPopup);

                if (TGS.BookFlow.GlobalVars.HotelDetails.IsPopup) {
                    TGS.BookFlow.HotelDetailsStep.CloseHotelMoreDetailsPopup(false);
                }

                if (!TGS.BookFlow.GlobalVars.HotelDetails.ShowUndercover && TGS.BookFlow.GlobalVars.HotelDetails.ReviewCount > 0)
                    SetTabAppearance('tabGuestReviews');

                OnClosed();
            },

            Cancel: function() {
                TGS.BookFlow.HotelDetailsStep.ShowPanel('writeReviewContainer', 'mask', !TGS.BookFlow.GlobalVars.HotelDetails.IsPopup);
                if (TGS.BookFlow.GlobalVars.HotelDetails.IsPopup) {
                    TGS.BookFlow.HotelDetailsStep.CloseHotelMoreDetailsPopup(false);
                }
                if (!TGS.BookFlow.GlobalVars.HotelDetails.ShowUndercover && TGS.BookFlow.GlobalVars.HotelDetails.ReviewCount > 0)
                    SetTabAppearance('tabGuestReviews');

                OnClosed();
            },

            Close: function() {
                TGS.BookFlow.HotelDetailsStep.ShowPanel('writeReviewContainer', 'mask', true);
                if (!TGS.BookFlow.GlobalVars.HotelDetails.IsPopup) {
                    if (!TGS.BookFlow.GlobalVars.HotelDetails.ShowUndercover && TGS.BookFlow.GlobalVars.HotelDetails.ReviewCount > 0)
                        SetTabAppearance('tabGuestReviews');
                }

                OnClosed();
            },

            Show: function() {
                if (!isBuilt) {
                    var json = TGS.BookFlow.GlobalVars.HotelDetails;
                    var tmpl = Ext.XTemplate.from('writeReviewTemplate');
                    tmpl.overwrite('writeReviewContainer', json);

                    var clientIDs = TGS.BookFlow.GlobalVars.WriteReviewClientIDs;

                    // set min rating as value
                    var allRatings = $(TGS.BookFlow.GlobalVars.WriteReviewClientIDs.rmAllRatings);
                    allRatings.value = "000000";

                    InitRatingModule(0, clientIDs.rmOverallId, json.ReviewsJSON.UserReview.Ratings.Overall);
                    InitRatingModule(1, clientIDs.rmHotelServiceId, json.ReviewsJSON.UserReview.Ratings.Service);
                    InitRatingModule(2, clientIDs.rmHotelConditionId, json.ReviewsJSON.UserReview.Ratings.Condition);
                    InitRatingModule(3, clientIDs.rmHotelLocationId, json.ReviewsJSON.UserReview.Ratings.Location);
                    InitRatingModule(4, clientIDs.rmRoomCleanlinessId, json.ReviewsJSON.UserReview.Ratings.Cleanliness);
                    InitRatingModule(5, clientIDs.rmRoomComfortId, json.ReviewsJSON.UserReview.Ratings.Comfort);

                    if (json.ReviewsJSON.UserReview.IsUpdate) {
                        isBuilt = true;
                    }
                }

                if (TGS.BookFlow.GlobalVars.HotelDetails.IsPopup) {
                    TGS.BookFlow.HotelDetailsStep.CloseHotelMoreDetailsPopup(false);
                }

                TGS.BookFlow.HotelDetailsStep.ShowPanel('writeReviewContainer', 'mask', !TGS.BookFlow.GlobalVars.HotelDetails.IsPopup);

                $('txtEmail').focus();

                OnOpened();
            },

            Submit: function() {
                var prevReview = EscapeBeforeSubmit($('txtReview'));
                var prevHeadline = EscapeBeforeSubmit($('txtHeadline'));
                if (!TGS.BookFlow.ValidateAndContinue()) {
                    $('wrm_onSubmitErr_div').style.display = "";
                } else {
                    $('wrm_onSubmitErr_div').style.display = "none";
                }
                $('txtReview').value = prevReview;
                $('txtHeadline').value = prevHeadline;
            }
        };
    })();
}

TGS.HotelReviews = new HotelReviews();

