var more_param = '';

var get_query = function () {
    var data = {};
    if (location.href.split('?').length > 1) {
        var querystring = location.href.split('?')[1];
        var param_pairs = querystring.split('&');
        for (i = 0; i < param_pairs.length; i++) {
            var param_pair = param_pairs[i].split('=');
            data[param_pair[0]] = param_pair[1];
        }
    }
    return data;
};
var setup_selectors = function () {
    $('.selector_category a').on('click', function () {
        $('.type-active, .category-active, .author-active').removeClass("type-active category-active author-active");
        $(this).addClass('category-active');

        if ($('div.head_category').length != 0) {
            $('div.head_category').text($(this).data('value'));
        }

        var data = {
            category: $(this).data('value')
        };

        more_param = 'hcategory=' + $(this).data('value');
        get_ajax_result('get_house_images', data, function (res) {
            clear_section('#house_list');

            for (i = 0; i < res.results.length; i++) {
                var ret = res.results[i];
                put_article(ret, '#house_list');
            }
            more_param += '&rs=' + res.query.rs;
            var max_page = Math.floor(res.founds / res.query.limit) + ((res.founds % res.query.limit) ? 1 : 0);
            put_pagenavi(1, max_page, '/house/', more_param, '#wp-pagenavi_box');

            update_screen();
        });
        $(this).parents('.selector').slideUp();
        return false;
    });

    $('.selector_type a').on('click', function () {
        $('.type-active, .category-active, .author-active').removeClass("type-active category-active author-active");

        if ($(this).hasClass('type-active') && $(this).parents('ul').find('.type-active').length <= 1) {
            // 外せない
        } else {
            $(this).toggleClass('type-active');
        }

        if ($('div.head_category').length != 0) {
            $('div.head_category').text($(this).data('value'));
        }

        var type = [];
        $(this).parents('ul').find('.type-active').each(function () {
            type.push($(this).data('value'));
        });
        var data = {
            type: type.join(',')
        };

        more_param = 'htype=' + type.join(',');
        get_ajax_result('get_house_images', data, function (res) {
            clear_section('#house_list');

            for (i = 0; i < res.results.length; i++) {
                var ret = res.results[i];
                put_article(ret, '#house_list');
            }
            more_param += '&rs=' + res.query.rs;
            var max_page = Math.floor(res.founds / res.query.limit) + ((res.founds % res.query.limit) ? 1 : 0);
            put_pagenavi(1, max_page, '/house/', more_param, '#wp-pagenavi_box');

            update_screen();
        });
        $(this).parents('.selector').slideUp();
        return false;
    });

    $('.selector_author a').on('click', function () {
        $('.type-active, .category-active, .author-active').removeClass("type-active category-active author-active");
        $(this).addClass('category-active');

        if ($('div.head_category').length != 0) {
            $('div.head_category').text($(this).text());
        }

        var data = {
            author: $(this).data('value')
        };
        more_param = 'hauthor=' + $(this).data('value');
        get_ajax_result('get_house_images', data, function (res) {
            clear_section('#house_list');

            for (i = 0; i < res.results.length; i++) {
                var ret = res.results[i];
                put_article(ret, '#house_list');
            }
            more_param += '&rs=' + res.query.rs;
            var max_page = Math.floor(res.founds / res.query.limit) + ((res.founds % res.query.limit) ? 1 : 0);
            put_pagenavi(1, max_page, '/house/', more_param, '#wp-pagenavi_box');

            update_screen();
        });
        $(this).parents('.selector').slideUp();
        return false;
    });

    $('#house_more').on('click', function () {
        location.href = site_url + '/house/' + (more_param ? '?' + more_param : '');
        return false;
    });
};

var update_screen = function () {
    $(window).trigger('scroll');
};
var clear_section = function (target) {
    $(target).empty();
};
var put_article = function (data, target) {
    var link_url = site_url + '/' + data.post_name;
    var image_url = data.image_url;
    image_url = image_url.replace(/\.(jpg|jpeg|png|gif)$/, "-640x640.$1");

    var html = '<article class="width30 fadein">';
    html += '<div class="photo-box">';
    html += '<a href="' + link_url + '">';
    html += '<img src="' + image_url + '" alt="" />';
    html += '</a>';
    html += '<div class="photo-box-overlay"><div class="photo-box-contents"><p>この写真の施工例を見る</p></div></div>';
    html += '<p class="photo-box-text01">' + data.display_name + '</p>';
    html += '</div>';
    html += '<p class="font-size-14">' + data.post_title + '</p>';
    html += '</article>';

    $(target).append(html);
};
var put_pagenavi = function (cur, max, path, query, target) {
    if ($(target).length === 0) {
        return;
    }

    var html = '';
    if (max > 1) {
        html += '<div class="wp-pagenavi" role="navigation">';
        html += '<span class="pages">' + cur + ' / ' + max + '</span>';
        if (cur != 1) {
            html += '<a class="prevpostslink" rel="prev" href="' + site_url + path + '?' + query + '&hpaged=' + (cur - 1) + '">←</a>';
        }
        for (i = 0; i < max; i++) {
            t = i + 1;
            if (cur == t) {
                html += '<span aria-current="page" class="current">' + t + '</span>';
            } else {
                html += '<a class="page larger" title="Page ' + t + '" href="' + site_url + path + '?' + query + '&hpaged=' + t + '">' + t + '</a>';
            }
        }
        if (cur != max) {
            html += '<a class="nextpostslink" rel="next" href="' + site_url + path + '?' + query + '&hpaged=' + (cur + 1) + '">→</a>';
        }
        html += '</div>';
    }
    $(target).empty().append(html);
};
var update_view_num = function () {
    var view_house = Cookies.get('history_house');
    var view_house_list = (!view_house) ? [] : view_house.split(',');

    $('#view_num').text(view_house_list.length);
    $('#view_num_2').text(view_house_list.length);
};
var update_view_num = function () {
    var view_house = Cookies.get('history_house');
    var view_house_list = (!view_house) ? [] : view_house.split(',');

    //★ADD ↓↓↓↓
    //空白の項目を排除
    data_tmp = [];
    var index = 0;
    for (j = 0; j < view_house_list.length; j++) {
        if( view_house_list[j] != "" ){
            data_tmp[index] = view_house_list[j]
            index++;
        }
    }
    view_house_list = data_tmp;
    //★ADD ↑↑↑↑

    $('#view_num').text(view_house_list.length);
    $('#view_num_2').text(view_house_list.length);
    $('#view_num_sp').text(view_house_list.length);
    $('#view_num_sp_2').text(view_house_list.length);
};
var update_fav_num = function () {
    var fav_house = Cookies.get('fav_house');
    var fav_photo = Cookies.get('fav_photo');
    var fav_house_list = (!fav_house) ? [] : fav_house.split(',');
    var fav_photo_list = (!fav_photo) ? [] : fav_photo.split(',');

    $('#fav_num').text(fav_house_list.length + fav_photo_list.length);
    $('#fav_num_2').text(fav_house_list.length + fav_photo_list.length);
    $('#fav_num_sp').text(fav_house_list.length + fav_photo_list.length);
    $('#fav_num_sp_2').text(fav_house_list.length + fav_photo_list.length);
};

var setup_fav_btn = function () {
    var fav_house = Cookies.get('fav_house');
    var fav_photo = Cookies.get('fav_photo');
    var history_house = Cookies.get('history_house');

    var fav_house_list = (!fav_house) ? [] : fav_house.split(',');
    var fav_photo_list = (!fav_photo) ? [] : fav_photo.split(',');
    var history_house_list = (!history_house) ? [] : history_house.split(',');

    Cookies.set('fav_house', fav_house_list.join(','), { expires: 365 * 3 });
    Cookies.set('fav_photo', fav_photo_list.join(','), { expires: 365 * 3 });

    data = [];
    max_index = 30;
    cur_id = $('.fav_house_add').data('id');
    data.push(cur_id);
    for (i = 0; i < history_house_list.length; i++) {
        if (i > (max_index - 1)) {
            break;
        }
        target_id = parseInt(history_house_list[i], 10);
        if (target_id == cur_id) {
            continue;
        }
        data.push(history_house_list[i]);
    }
    //★ADD ↓↓↓↓
    //空白の項目を排除
    data_tmp = [];
    var index = 0;
    for (j = 0; j < data.length; j++) {
        if( data[j] != "" ){
            data_tmp[index] = data[j]
            index++;
        }
    }
    data = data_tmp;
    //★ADD ↑↑↑↑
    history_house_list = data;
    Cookies.set('history_house', history_house_list.join(','), { expires: 365 * 3 });

    //$('.fav_house_add').on('click', function ()と同じ内容（施工例一覧のajax対応のため）
    //$('.fav_house_add').on('click', function () { //★COMMENTOUT
    $(document).on("click", ".fav_house_add", function(){ //★ADD
        id = $(this).data('id');
        data = [];
        data.push(id);
        for (i = 0; i < fav_house_list.length; i++) {
            if (id == fav_house_list[i]) {
                continue;
            }
            data.push(fav_house_list[i]);
        }
        fav_house_list = data;
        Cookies.set('fav_house', fav_house_list.join(','), { expires: 365 * 3 });

        //★ADD 施工例一覧ページでポップアップのハートマークを反転
        $('.pop-houseinfo').find('.fav_btn').each( function( index, element ) {
            if( $(element).attr("data-id") == id ){
                //お気に入り：白抜きのハートは非表示
                $(element).children('i.fas.fa-heart').removeClass('is-hide');                  
                $(element).children('i.far.fa-heart').addClass('is-hide');
            }
        })
        //★ADD 施工例詳細画面で「この物件をお気に入りに追加」のハートの色を反転
        $obj = $(this).find('.btn-fav-house-add-text');
        $obj.children('i.fas.fa-heart').removeClass('is-hide');
        $obj.children('i.far.fa-heart').addClass('is-hide'); 
        // $('.mas-item').each(function(index, element){
        //     $(element).find('.icon').each( function( index, element ) {
        //         if( $(element).attr("data-id") == id ){
        //             //お気に入り：白抜きのハートは非表示
        //             $(element).children('i.fas.fa-heart').removeClass('is-hide');                  
        //             $(element).children('i.far.fa-heart').addClass('is-hide');
        //         }
        //     })
        // })

        //alert('物件をお気に入りに追加しました！');
        update_fav_num();
    });

    // $('.fav_house_remove').on('click', function () { //★COMMENTOUT
    $(document).on("click", ".fav_house_remove", function(){ //★ADD
        if (!window.confirm('お気に入り物件を削除しますか？')) {
            return false;
        }
        id = $(this).data('id');
        data = [];
        for (i = 0; i < fav_house_list.length; i++) {
            if (id == fav_house_list[i]) {
                continue;
            }
            data.push(fav_house_list[i]);
        }
        fav_house_list = data;
        Cookies.set('fav_house', fav_house_list.join(','), { expires: 365 * 3 });

        update_fav_num();

        //$(this).parents('article').fadeOut(1000, function () {  //★COMMENTOUT
        $(this).parents('div.mas-item').fadeOut(1000, function () {
            $(this).remove();
        });
    });

    var show_myphoto_mask = function ($mask) {
        $mask
            .addClass('moving')
            .css('display', 'block')
            .animate({ opacity: 1.0 }, 300, function () {
                $(this).removeClass('moving');
            });
    };
    var hide_myphoto_mask = function ($mask) {
        $mask
            .addClass('moving')
            .animate({ opacity: 0.0 }, 300, function () {
                $(this).removeClass('moving').css('display', 'none');
            });
    };

    $('.click-my-photo')
        .on('mouseenter', function () {
            show_myphoto_mask($('.mask', this));
        })
        .on('mouseleave', function () {
            hide_myphoto_mask($('.mask', this));
        })
        .on('click', function () {
            var $mask = $('.mask', this);
            if ($mask.hasClass('moving')) return false;

            if ($mask.css('display') === 'block') {
                hide_myphoto_mask($mask);
            } else {
                show_myphoto_mask($mask);
            }
            return false;
        });
    $('.fav_photo_add_cancel').on('click', function (e) {
        var $mask = $(this).parents('.mask');
        if ($mask.hasClass('moving') || $mask.css('display') != 'block') {
            e.preventDefault();
        } else {
            hide_myphoto_mask($mask);
            return false;
        }
    });
    $('.fav_photo_add').on('click', function (e) {
        var $mask = $(this).parents('.mask');
        if ($mask.hasClass('moving') || $mask.css('display') != 'block') {
            e.preventDefault();
        } else {
            id = $(this).data('id');
            data = [];
            data.push(id);
            for (i = 0; i < fav_photo_list.length; i++) {
                if (id == fav_photo_list[i]) {
                    continue;
                }
                data.push(fav_photo_list[i]);
            }
            fav_photo_list = data;
            Cookies.set('fav_photo', fav_photo_list.join(','), { expires: 365 * 3 });

            update_fav_num();

            //★ADD ポップアップのハートマークを反転
			$('.pop-houseinfo').find('.fav_btn').each( function( index, element ) {
                if( $(element).attr("data-id") == id ){
                    //お気に入り：白抜きのハートは非表示
                    $(element).children('i.fas.fa-heart').removeClass('is-hide');                  
                    $(element).children('i.far.fa-heart').addClass('is-hide');
                }
			})
            //★ADD 施工例詳細画面（ポップアップから見て親画面）のハートの色を反転
            $('.mas-item').each(function(index, element){
                $(element).find('.icon').each( function( index, element ) {
                    if( $(element).attr("data-id") == id ){
                        //お気に入り：白抜きのハートは非表示
                        $(element).children('i.fas.fa-heart').removeClass('is-hide');                  
                        $(element).children('i.far.fa-heart').addClass('is-hide');
                    }
                })
              })
            return false;
        }
    });

    //$('.fav_photo_remove').on('click', function ()と同じ内容（施工例一覧のajax対応のため）
    // $('.fav_photo_remove').on('click', function () { //★COMMENTOUT
    $(document).on("click", ".fav_photo_remove", function(){ //★ADD
        if (!window.confirm('お気に入り写真を削除しますか？')) {
            return false;
        }
        id = $(this).data('id');
        data = [];
        for (i = 0; i < fav_photo_list.length; i++) {
            if (id == fav_photo_list[i]) {
                continue;
            }
            data.push(fav_photo_list[i]);
        }
        fav_photo_list = data;
        Cookies.set('fav_photo', fav_photo_list.join(','), { expires: 365 * 3 });

        update_fav_num();

        //$(this).parents('article').fadeOut(1000, function () { //★COMMENTOUT
        $(this).parents('div.mas-item').fadeOut(1000, function () { //★ADD
            $(this).remove();
        });

        return false;
    });
};

var get_ajax_result = function (action, data, success_callback, fail_callback) {
    if (!success_callback) {
        success_callback = function (data) { };
    }
    if (!fail_callback) {
        fail_callback = function () { };
    }
    data['action'] = action;
    $.ajax({
        type: 'POST',
        url: wp_ajax_url,
        data: data,
        cache: false,
        dataType: 'jsonp',
    })
        .done(success_callback)
        .fail(fail_callback);
};
