app = {
    map: {},
    data: {},
    url: '',
    viewed: 0,
    url_hash: '',
    url_params: [
        {name: 'noOfReviews', value: 10},
        {name: 'offset', value: 0}
    ],
    templates: {},
    init: function () {
        this._map();
        this._templates();
        this._get_data();


        this._bind_actions();
    },
    _templates: function () {
        var $this = this;
        jQuery('.dot-tmpl').each(function () {
            $this.templates[this.id] = jQuery(this).html();
            jQuery(this).html('Loading reviews....');
        });
    },

    _bind_actions: function () {
        var $this = this;

        this.map.filter_btn.click(function () {
            if (jQuery(this).attr('aria-pressed') == 'false') {
                $this._set_filter_value(jQuery(this).data('param'), 1);
                $this._get_data(jQuery(this));
            }
            else {
                $this._set_filter_value(jQuery(this).data('param'), 0);
                $this._get_data(jQuery(this));
            }
        });
        this.map.next.click(function () {
            var offset = $this._get_filter_value('offset');
            offset += $this._get_filter_value('noOfReviews');
            var data = $this._get_cache('business_info');
            var total = data.total_rating.total_no_of_reviews;
            if (offset < total) {
                $this._set_filter_value('offset', offset);
                $this._get_data(1);
                $this.map.prev.show();
                $this._scrollTop();
            }
            if (offset + $this._get_filter_value('noOfReviews') >= total)
                $this.map.next.hide();
        });
        this.map.prev.click(function () {
            var offset = $this._get_filter_value('offset');
            offset -= $this._get_filter_value('noOfReviews');
            $this.map.next.show();
            if (offset >= 0) {
                $this._set_filter_value('offset', offset);
                $this._get_data(1);
                $this._scrollTop();
            }
            if (!offset)
                $this.map.prev.hide();

        }).hide();
    },
    _scrollTop: function () {
        jQuery('html, body').animate({scrollTop: this.map.reviews_all.offset().top - 100}, 500);
    },
    _map: function () {
        this.map = {
            table: jQuery('#main-tbl'),
            pagination: jQuery('#pagination'),
            info: jQuery('#reputation_management-business_info'),
            reviews: jQuery('#reputation_management-reviews'),
            reviews_all: jQuery('#reputation_management-reviews-all'),
            next: jQuery('#reputation_management-next'),
            prev: jQuery('#reputation_management-prev'),
            filter_btn: jQuery('.filter > button'),
            nums: jQuery('#reputation_management-nums')
        };
    },
    _build_url: function () {

        if (this.url_params.length) {
            var url = [];
            this.url_hash = '';
            for (var j in this.url_params) {
                this.url_hash += this.url_params[j].name + '=' + this.url_params[j].value
                url.push(this.url_params[j].name + '=' + this.url_params[j].value);
            }
        }

        this.url = WP_URL + '/index.php?reputation_management-ajax=1&' + url.join('&');

    },
    _get_data: function (spin) {
        var $this = this;
        $this._build_url();
        if (!this._get_cache()) {
            if (typeof spin !== 'undefined') {
                $this._loading_spin();
            }
            jQuery.ajax({
                url: $this.url,
                timeout: 3000
            }).done(function (data) {
                if (typeof data.errors == 'undefined') {
                    $this._set_cache(data);
                    $this._fill_info();
                    $this._fill_reviews();
                }
                else {
                    if (BEHAVIOR_ON_ERROR == 'cache' && typeof localStorage[$this.url_hash] != 'undefined') {
                        $this._set_cache(localStorage[$this.url_hash]);
                        $this._fill_reviews();
                    } else {
                        $this._set_error_message();
                    }
                }
                if (typeof spin !== 'undefined') {
                    $this._loading_spin(1);
                }
            }).fail(function () {
                if (BEHAVIOR_ON_ERROR == 'cache' && typeof localStorage[$this.url_hash] != 'undefined') {
                    $this._set_cache(localStorage[$this.url_hash]);
                    $this._fill_reviews();
                } else {
                    $this._set_error_message();
                }
                if (typeof spin !== 'undefined') {
                    $this._loading_spin(1);
                }
            });
        }
        else {
            $this._fill_info();
            $this._fill_reviews();
        }

    },
    _set_error_message: function () {
        var message = '';
        if (BEHAVIOR_ON_ERROR == 'show') {
            message = 'Connection error. Try later.';
        } else {
            message = '';
        }
        this.map.reviews.html(message);
        this.map.reviews_all.html(message);
    },
    _loading_spin: function (destroy) {
        jQuery('#rl-load-spin').remove();
        if (typeof destroy === 'undefined') {
            this.map.info.after('<div id="rl-load-spin">Loading Reviews...</div>');
        }
    },
    _fill_info: function () {
        if (typeof this.map.info[0] == 'undefined') {
            return false;
        }
        var tmpl = doT.template(this.templates[this.map.info[0].id]);
        var bi = this._get_cache('business_info');
        if (typeof bi.total_rating === 'undefined') {
            this.map.info.html('');
            return false;
        }
        bi.total_rating.ratingStar = (Math.floor(bi.total_rating.total_avg_rating * 2) / 2).toString();
        bi.total_rating.ratingStar = bi.total_rating.ratingStar.replace('.', '_');
        this.map.info.html(tmpl(bi));
    },
    _fill_reviews: function () {
        if (typeof this.map.reviews_all[0] === 'undefined' && typeof this.map.reviews[0] === 'undefined') {
            this.map.reviews_all.html('No reviews yet');
            this.map.next.html('');
            return false;
        }
        if (typeof this.map.reviews[0] != 'undefined') {
            var tmpl = doT.template(this.templates[this.map.reviews[0].id]);
        }
        if (typeof this.map.reviews_all[0] != 'undefined') {
            var tmpl_all = doT.template(this.templates[this.map.reviews_all[0].id]);
        }
        var data = this._get_cache();
        if (typeof data['reviews'] !== 'undefined') {
            for (var i in  data['reviews']) {
                var dt = data['reviews'][i]['date_of_submission'].replace(/\s+/i, 'T');
                var desc = data['reviews'][i]['description'];
                var url = data['reviews'][i]['review_url'];
                var d = new Date(dt);
                data['reviews'][i]['description_cut'] = data['reviews'][i]['description'];
                data['reviews'][i]['date_of_submission'] =
                    (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
                if (desc.length > TEXT_LENGTH_REP) {
                    data['reviews'][i]['description_cut'] =
                        desc.substr(0, TEXT_LENGTH_REP) + '...' + "<a target='_blank'  href='" + READ_MORE_URL + "'>" + READ_MORE + "</a>"
                }
                if (data['reviews'][i]['review_from'] != 0) {
                    data['reviews'][i]['externalPageUrl'] = data['reviews'][i]['review_url'];
                } else {
                    data['reviews'][i]['externalPageUrl'] = data['business_info']['external_page_url'];
                }
            }
            if (typeof this.map.reviews[0] != 'undefined') {
                this.map.reviews.html(tmpl(data['reviews']));
            }
            if (typeof this.map.reviews_all[0] != 'undefined') {
                this.map.reviews_all.html(tmpl_all(data['reviews']));
            }
        } else {
            if (typeof this.map.reviews[0] != 'undefined') {
                this.map.reviews.html('No reviews yet');
                this.map.next.html('');
            }
            if (typeof this.map.reviews_all[0] != 'undefined') {
                this.map.reviews_all.html('No reviews yet');
                this.map.next.html('');
            }
        }

        jQuery('.slider').bxSlider({
            auto: true,
            pager: false,
            speed: 1000
            //minSlides: 1,
            //maxSlides: 4,
            //slideMargin: 10
        });
    },
    _set_cache: function (data) {
        if (typeof sessionStorage != 'undefined') {
            sessionStorage.setItem(this.url_hash, data);
        }
        if (typeof localStorage != 'undefined') {
            localStorage.setItem(this.url_hash, data);
        }
        this.data[this.url_hash] = JSON.parse(data);
    },
    _get_cache: function (key) {
        var data = '';
        if (typeof this.data[this.url_hash] != 'undefined') {
            data = this.data[this.url_hash];
        } else if (typeof sessionStorage[this.url_hash] != 'undefined') {
            data = this.data[this.url_hash] = JSON.parse(sessionStorage[this.url_hash]);
        } else {
            return false;
        }
        if (typeof key != 'undefined' && typeof data[key] != 'undefined') {
            data = data[key];
        }
        return data;
    },
    _set_filter_value: function (key, value) {
        for (var j in this.url_params) {
            if (this.url_params[j].name == key) {
                this.url_params[j].value = value;
                return;
            }
        }
        this.url_params.push({name: key, value: value});
    }
    ,
    _get_filter_value: function (key) {

        for (var j in this.url_params) {
            if (this.url_params[j].name == key) {
                return this.url_params[j].value;
            }


        }
    }
};

app.init();