/* Minification failed. Returning unminified contents.
(332,18-19): run-time error JS1003: Expected ':': ,
(334,5-6): run-time error JS1003: Expected ':': }
 */
var Map = Map || {};
Map.detailPoi = null;

Map.mode = 'results';
Map.selectedPoiIndex = 0;

var map = null;

// Base layer for markers
var baseLayer = null;
var markersLayer = null;

Map.init = function () {
    var mapPlaceholder = $('.map-placeholder')[0];

    if (!mapPlaceholder) {
        // Just quit if there's no placeholder for the map
        return;
    }

    Map.mode = $(mapPlaceholder).data('mode') || 'results';
    Map.pois = Map.loadPois('map-item');

    if (Map.pois.length > 0) {
        Map.map = L.map(mapPlaceholder).setView([0, 0], 13);

        var tileLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 17
        });
        Map.baseLayer = L.layerGroup();

        Map.map.addLayer(tileLayer);
        Map.map.addLayer(Map.baseLayer);

        Map.refreshPois();
    } else {
        Map.hidePlaceholder();
    }
};

Map.hidePlaceholder = function () {
    $(".map-placeholder").hide();
};

Map.showPlaceHolder = function() {
    $(".map-placeholder").show();
};

Map.refreshPois = function () {
    Map.baseLayer.clearLayers();

    if (Map.mode === 'detail') {
        var poi = Map.getPoi(Map.selectedPoiIndex);
        Map.renderSinglePoi(poi);
    }

    if (Map.mode === 'results') {
        Map.renderMultiplePois();
    }
};

Map.loadPois = function (mapItemClass) {
    var pois = [];

    $("." + mapItemClass).each(function () {
        var location = $(this).data("location");
        var index = $(this).data("index");

        if (typeof location == "object") {
            var poi = {
                location: location,
                index: index || 0
            };

            pois.push(poi);
        }
    });

    return pois;
};

Map.createMarker = function (location, index) {
    index = index || 0;
    var className = index > -1 ? "gold-poi" + (index + 1) : "center-poi";

    return L.marker([location.latitude, location.longitude], {
        icon: L.divIcon({
            className: "alq-poi " + className,
            iconSize: [21, 37]
        })
    });
};

Map.renderMultiplePois = function () {
    var markers = Map.pois.map(function (poi) {
        return Map.createMarker(poi.location, poi.index);
    });

    var markersLayer = L.layerGroup(markers);
    Map.baseLayer.addLayer(markersLayer);

    if (markers.length === 1) {
        Map.map.setView(markers[0].getLatLng(), 15);
    } else {
        Map.fitPois();
    }
};

Map.renderSinglePoi = function (poi) {
    if (poi === null) {
        Map.hidePlaceholder();
        return;
    }

    Map.showPlaceHolder();

    var marker = Map.createMarker(poi.location, -1);
    Map.map.addLayer(marker);
    Map.map.setView(marker.getLatLng(), 17);
};

Map.fitPois = function () {
    var bounds = Map.getBoundingBox(Map.pois);
    Map.map.fitBounds(bounds);
};

Map.getBoundingBox = function (pois) {
    return L.latLngBounds(pois.map(function (poi) {
        return L.latLng([poi.location.latitude, poi.location.longitude]);
    }));
};

Map.zoomDetail = function (poiIndex) {
    Map.mode = 'detail';
    Map.selectedPoiIndex = poiIndex;
    Map.refreshPois();
};

Map.refresh = function () {
    Map.map.invalidateSize();
};

Map.getPoi = function (poiIndex) {
    for (var i = 0; i < Map.pois.length; i++) {
        if (Map.pois[i].index === poiIndex) {
            return Map.pois[i];
        }
    }

    return null;
};

$(function () {
    Map.init();
});;
// Reviews and ratings
var RaR = RaR || {};
RaR.Reviews = RaR.Reviews || {};
RaR.Ratings = RaR.Ratings || {};

// Reviews
RaR.Reviews.initReviewForm = function (formElement, onSaveCallback) {
    if (typeof (formElement) === 'string') {
        formElement = $('#' + formElement);
    }

    // If this is not a form element, try to find the form element inside
    if (!formElement.is('form')) {
        formElement = formElement.find('form');
    }

    formElement.find("input, textarea").on('keydown', function () {
        $(this).removeClass('input-validation-error');
    });

    formElement.on('submit', function (e) {
        RaR.Reviews.onSubmit(e, onSaveCallback);
    });
};

RaR.Reviews.onSubmit = function (e, onSaveCallback) {
    e.preventDefault();
    var form = $(e.target);

    var inputs = {
        userName: "UserName",
        userEmail: "UserEmail",
        review: "Review",
        listingId: "ListingId"
    };
    var review = {};
    var valid = true;

    for (var key in inputs) {
        var input = form.find("#" + inputs[key]);
        var inputValid = !!input.val();

        if (input.attr('type') == 'email') {
            inputValid &= RaR.Reviews.isEmailValid(input.val());
        }

        if (!inputValid) {
            input.addClass('input-validation-error');
            valid = false;
        }

        review[key] = input.val();
    }

    if (!valid) {
        return;
    }

    RaR.Reviews.saveReview(review, form, onSaveCallback);
};

RaR.Reviews.saveReview = function (review, form, onSaveCallback) {
    $.post('/api/reviews', review, function (response) {
        if (onSaveCallback !== undefined) {
            onSaveCallback(response, form);
        }
    }, 'json');
};

RaR.Reviews.isEmailValid = function (email) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
};

// Ratings
RaR.Ratings.getRatingItemIndicators = function (ratingItem) {
    return $(ratingItem).find('.rating-indicator');
};

RaR.Ratings.initRatingIndicators = function () {
    $('.rating-item').each(function () {
        var ratingItem = $(this);

        RaR.Ratings.getRatingItemIndicators(ratingItem).each(function () {
            RaR.Ratings.renderRatingIndicator(ratingItem, $(this));
        });
    });
};

RaR.Ratings.renderRatingIndicator = function (ratingItem, indicator) {
    var listingId = ratingItem.data('id');
    var active = indicator.hasClass('active');

    var stars = $(indicator).find(".star");

    if (stars.length === 0) {
        stars = [];

        for (var i = 1; i <= 5; i++) {
            var star = $("<div class='star'></div>");

            stars.push(star);
            indicator.append(star);
        }
    }

    // Only initialize star-related actions if the indicator is marked as active
    if (active) {
        $(stars).each(function (index) {
            var star = $(this);
            var currentRating = index + 1;

            star.on('mouseover', function () {
                RaR.Ratings.refreshIndicatorHover(ratingItem, indicator, currentRating);
            });

            star.on('mouseleave', function () {
                RaR.Ratings.refreshIndicatorHover(ratingItem, indicator);
            });

            star.on('click', function () {
                RaR.Ratings.sendRating(listingId, currentRating, ratingItem);
            });
        });
    }

    RaR.Ratings.refreshIndicatorLabel(ratingItem, indicator);
    RaR.Ratings.refreshIndicatorHover(ratingItem, indicator);
};

RaR.Ratings.refreshIndicatorLabel = function(ratingItem, indicator) {
    // Try to find rating label inside this indicator
    var indicatorLabel = indicator.find(".rating-label");

    if (indicatorLabel.length > 0) {
        // Get current rating count
        var count = ratingItem.data('rating-cnt');

        // Get template label name specific for this count
        var specificTemplateName = 'RatingLabelTemplate_' + count;
        
        // Try to find the specific template, fallback to generic tempalte
        var template = Resources[specificTemplateName] || Resources['RatingLabelTemplate'];

        // If a template was found, we can use it
        if (template !== undefined) {
            // Just substitue {} for the number of reviews
            template = template.replace('{}', count);
            // And set it as the label
            indicatorLabel.text(template);
        }
    }
};

RaR.Ratings.refreshIndicatorHover = function (ratingItem, indicator, currentRating) {
    if (currentRating === undefined) {
        currentRating = ratingItem.data('rating-avg');
    }

    $(indicator).find('.star').removeClass('half').removeClass('full').each(function (index) {
        var star = $(this);
        var status = currentRating - index;

        if (status >= 1) {
            star.addClass('full');
            return;
        }

        if (status >= 0.5) {
            star.addClass('half');
        }
    });
};

RaR.Ratings.sendRating = function (listingId, rating, ratingItem) {
    $.post('/api/ratings', {
        listingId,
        rating
    }, function (response) {
        RaR.Ratings.setCurrentRating(ratingItem, response.currentRating.average, response.currentRating.count);
        RaR.Ratings.getRatingItemIndicators(ratingItem).each(function () {
            RaR.Ratings.refreshIndicatorHover(ratingItem, $(this));
            RaR.Ratings.refreshIndicatorLabel(ratingItem, $(this));
            RaR.Ratings.deactivateIndicator(ratingItem);
        });
    }, 'json');
};

RaR.Ratings.deactivateIndicator = function (indicator) {
    indicator.removeClass('active');
    indicator.find('.star').off('click mouseover mouseleave');
};

RaR.Ratings.setCurrentRating = function (ratingItem, ratingAvg, ratingCnt) {
    $(ratingItem).data('rating-avg', ratingAvg);
    $(ratingItem).data('rating-cnt', ratingCnt);
};

// Integration with Modals
RaR.Reviews.initModalForm = function(modalElement) {
    RaR.Reviews.initReviewForm(modalElement, function(response, form) {
        // Transform modal into a message after the form has been submitted

        form.hide();

        var messageTitle = response.success ? Resources.ReviewAddedTitle : Resources.ReviewError;
        var messageText = response.success ? Resources.ReviewAdded : response.message;

        var reviewMessage = modalElement.find('.review-message');

        reviewMessage.find('.review-message-title').text(messageTitle);
        reviewMessage.find('.review-message-text').text(messageText);

        reviewMessage.show();
    });
};

$(function () {
    // Init rating indicators
    RaR.Ratings.initRatingIndicators();
});;
