var ProductCompare = {};
ProductCompare.init = function (delFn) {
    var outerElm = $('#divCompare');
    var ulElm = outerElm.children('ul');
    var countElm = outerElm.find('h4 > span');

    var count = ulElm.children().length - 1;
    countElm.html('(' + count + ')');
    if (count == 0)
        outerElm.parent().hide();
    
    var msgCallback = function () { };
    outerElm.find('a.msg').confirmOn({
        questionText: '',
        onShow: function () { return true; }, // Cancel the pop-up by letting this funcion return false
        classPrepend: 'myprefix',
        textYes: 'CONFIRM',
        textNo: ''
    }, 'click', function (e, confirmed) {
        msgCallback();
    });

    function showMsg(msg, callback) {
        var msgElm = outerElm.find('a.msg');
        msgElm.data('confirmon').options.questionText = msg;
        if (callback)
            msgCallback = callback;
        else
            msgCallback = function () { };

        msgElm.click();
    }

    ulElm.find('a.remove').confirmOn({ 
        classPrepend: 'uponcomfirm',
        questionText: 'Are you sure to remove all ?',
        textYes: 'CONFIRM',
        textNo: 'CANCEL'
    }, 'click', function (e, confirmed) { // 移除所有
        if (!confirmed) {
            var noList = [];
            ulElm.children('[data-no]').each(function () {
                noList.push($(this).attr('data-no'));
            });
            if (noList.length > 0) {
                $.get('?CompareMethod=RemoveCompare&no=' + encodeURIComponent(JSON.stringify(noList)), function () {
                    if(delFn) {
                        for (var i = 0, len = noList.length; i < len; ++i)
                            delFn(noList[i]);
                    }

                    outerElm.parent().slideUp(function () {
                        ulElm.children('[data-no]').remove();
                        countElm.html('(0)');
                    });
                });
            }
        }
    });

    ulElm.on('click', 'a.delete', function (event) {
        event.stopPropagation();

        var liElm = $(this).parent();
        var pdNo = liElm.attr('data-no');
        $.get('?CompareMethod=RemoveCompare&no=' + encodeURIComponent(pdNo), function () {
            var count = ulElm.children('[data-no]').length;
            if (count == 1) {
                outerElm.parent().slideUp(function () {
                    liElm.remove();
                    countElm.html('(0)');
                });
            } else {
                liElm.fadeOut(function () {
                    liElm.remove();
                    countElm.html(count - 1);
                });
            }

            if (delFn)
                delFn(pdNo);
        });
    });

    ulElm.on('click', 'li[data-no]', function () {
        $.get('?CompareMethod=GetProductUrl&pdNo=' + $(this).attr('data-no'), function (url) {
            window.open(url);
        });
    });

    ulElm.find('a.compare').click(function (e) {
        e.preventDefault();
        var mainTypeId = $(this).attr('data-mainTypeId');
        var url = $(this).prop('href');

        $.get('?CompareMethod=GetProductNumber&mainTypeId=' + mainTypeId + '&r=' + Math.random(), function (num) {
            if (num == '0') {
                showMsg('Please add one product at least.', function () {
                    location.replace(location.href);
                });
            } else {
                window.open(url);
            }
        });
    });

    ProductCompare.add = function (pdNo) {
        $.get('?CompareMethod=AddCompare&no=' + encodeURIComponent(pdNo), function (rs) {            
            if (rs == '-1')
                showMsg('An unknown error occurred ! Please contact the administrator.');
            else if (rs == '0')
                showMsg('The product is in comparison');
            else if (rs == '1')
                showMsg('You can compare up to 5 products each time.');
            else {
                function addProductToCompare() {
                    var html =
                    '<li data-no="' + pdNo + '">' +
                    '   <span>' + rs + '</span>' +
                    '   <a class="tooltip delete" title="delete"><i class="mdi mdi-close agatered"></i></a>' +
                    '</li>';
                    ulElm.children(':last').before(html);                    
                    if (outerElm.parent().is(':hidden')) {
                        outerElm.parent().slideDown();
                    }
                    countElm.html('(' + ulElm.children('[data-no]').length + ')');                    
                }

                if ($(window).width() > 765) { //直式平板以上
                    var cart = $('#divCompare');
                    var imgtodrag = $('#ulImg').find('img:first');                    
                    if (imgtodrag.length) {
                        var imgclone = imgtodrag.clone().offset({
                            top: imgtodrag.offset().top,
                            left: imgtodrag.offset().left
                        }).css({
                            'opacity': '0.5',
                            'position': 'absolute',
                            'height': '150px',
                            'width': '150px',
                            'z-index': '100'
                        }).appendTo($('body')).animate({
                            'top': cart.offset().top + 10,
                            'left': cart.offset().left + 10,
                            'width': 75,
                            'height': 75
                        }, 1000, 'easeInOutExpo');

                        imgclone.animate({
                            'width': 0,
                            'height': 0
                        }, function () {
                            $(this).detach();
                            addProductToCompare();
                        });
                    } else {
                        addProductToCompare();
                    }
                } else { //手機板
                    $.toast({
                        text: 'Added successfully',
                    })

                    addProductToCompare();
                }                
            }
        })
    }
}

ProductCompare.initModule = function () {
    var outerElm = $('#divCompare');
    var ulElm = outerElm.children('ul');
    var countElm = outerElm.find('h4 > span');

    var count = ulElm.children().length - 1;
    countElm.html('(' + count + ')');
    if (count == 0) {
        outerElm.find(".compare-img").show();
        ulElm.hide();
    } else {
        outerElm.find(".compare-img").hide();
        ulElm.show();
    }
        

    ulElm.find('a.remove').confirmOn({
        classPrepend: 'uponcomfirm',
        questionText: 'Are you sure to remove all ?',
        textYes: 'CONFIRM',
        textNo: 'CANCEL'
    }, 'click', function (e, confirmed) { // 移除所有
        if (!confirmed) {
            var noList = [];
            ulElm.children('[data-no]').each(function () {
                noList.push($(this).attr('data-no'));
                $("a.BtnCompare#" + $(this).attr('data-no')).show();
            });
            if (noList.length > 0) {
                $.get('?CompareMethod=RemoveCompare&no=' + encodeURIComponent(JSON.stringify(noList)), function () {
                    //outerElm.parent().slideUp(function () {
                        ulElm.children('[data-no]').remove();
                        countElm.html('(0)');
                        outerElm.find(".compare-img").show();
                        ulElm.hide();
                    //});
                });
            }
        }
    });

    ulElm.on('click', 'a.delete', function (e) {
        e.stopPropagation();
        var liElm = $(this).parent();
        $.get('?CompareMethod=RemoveCompare&no=' + encodeURIComponent(liElm.attr('data-no')), function () {
            $("a.BtnCompare#" + liElm.attr('data-no')).show();
            var count = ulElm.children('[data-no]').length;
            if (count == 1) {
                //outerElm.parent().slideUp(function () {
                    liElm.remove();
                    countElm.html('(0)');
                    outerElm.find(".compare-img").show();
                    ulElm.hide();
                //});
            } else {
                liElm.fadeOut(function () {
                    liElm.remove();
                    countElm.html(count - 1);
                });
            }
        });
    });

    ulElm.on('click', 'li[data-no]', function () {
        $.get('?CompareMethod=GetProductUrl&pdNo=' + $(this).attr('data-no'), function (url) {
            window.open(url);
        });
    });

    ProductCompare.add = function (pdNo) {
        $.get('?CompareMethod=AddCompare&no=' + encodeURIComponent(pdNo), function (rs) {
            if (rs == '-1')
                alert('An unknown error occurred ! Please contact the administrator.');
            else if (rs == '0')
                alert('The product is in comparison');
            else if (rs == '1')
                alert('You can compare up to 5 products each time.');
            else {
                var html =
                    '<li data-no="' + pdNo + '">' +
                    '   <span>' + rs + '</span>' +
                    '   <a class="tooltip delete" title="delete"><i class="mdi mdi-close agatered"></i></a>' +
                    '</li>';
                ulElm.children(':last').before(html);
                if (outerElm.parent().is(':hidden')) {
                    outerElm.parent().slideDown();
                }
                countElm.html('(' + ulElm.children('[data-no]').length + ')');

                outerElm.find(".compare-img").hide();
                ulElm.show();
            }
        })
    }
}