(function($) {
    $.eway = {
        popup: function(title, message, button, width) {
            $(".bg_opacity").show();
            $("#popup-window").css("top", $(window).scrollTop()+100 + "px");
            if (!width){
                $(".user-popup-c").css('width', '467px');
            } else {
                $(".user-popup-c").css('width', width + 'px');
            }
            // Show popup nếu chưa show
            if ($("#popup-window").css('display') == 'none'){
                $("div.bg_opacity").show();
                $('#show_title_popup').html('Đang tải ...');
                $('#show_content_popup').html('');
                $("#popup-window").show();
            }
            
            // Set title cho popup
            $('#show_title_popup').html(title + '<span class="flr" style="margin-right:10px;"><a href="javascript:void(0)" onclick="closePopup();" style="color:#fff; font-weight: normal;">X</a></span>');
            // Set nội dung
            $('#show_content_popup').html(message);
            // Set button
            $('#show_button_popup').html('');
            if (button.request){
                $('#show_button_popup').append('<input type="button" value="' + button.request.value + '" class="popup-btn-close" onclick="' + button.request.callback + '"/>');
            }
            if (button.accept){
                $('#show_button_popup').append('<input type="button" value="' + button.accept.value + '" class="popup-btn" onclick="' + button.accept.callback + '"/>');
            }
            if (button.reject){
                $('#show_button_popup').append('<input type="button" value="' + button.reject.value + '" class="popup-btn" onclick="' + button.reject.callback + '"/>');
            }
            if (button.cancel || button == 1){
                //if (message) $('#show_content_popup').html('<p>' + message + '</p>');
                if (message) $('#show_content_popup').html(message);
                $('#show_button_popup').append('<input type="button" value="Đóng" class="popup-btn-close" onclick="closePopup();"/>');
            }
            
        }
    }

    ePopup = function(message, title, button, width) {
        $.eway.popup(message, title, button, width);
    }

})(jQuery);
$(function() {
    var offset = $("#popup-window").offset();
    var topPadding = 1;
    //    $(window).scroll(function() {
    //        if ($(window).scrollTop() > offset.top) {
    //            $("#popup-window").css('marginTop', $(window).scrollTop() - offset.top + topPadding);
    //        } else {
    //            $("#popup-window").css('marginTop', 0);
    //        };
    //    });
    $(window).scroll(function () {
        //$("#popup-window").css("top", $(window).scrollTop()+100 + "px");
        });

});
function openPopup(){
    $(window).scroll(function () {
        //$("#popup-window").css("top", $(window).scrollTop()+100 + "px");
        });
    $("div.bg_opacity").show();
    $('#show_title_popup').html('Đang tải ...');
    $('#show_content_popup').html('');
    $('#show_button_popup').html('');
    $("#popup-window").show();
}
function closePopup(){
    $(".user-popup-c").attr("style", "width:467px");
    $("div.bg_opacity").hide();
    $('#btn_close').hide();
    $("#popup-window").hide();
}
function showObj(objId){
    $("#"+objId).show();
}
function hideObj(objId){
    $("#"+objId).hide();
}
function requireLogin(){
    var title = 'Thông báo lỗi !';
    var content = '<br/><center><b>Có lẽ bạn cần đăng nhập để thực hiện !</b><br/><br/><img src="http://ca7.upanh.com/17.729.22119455.gHp0/291615412256033.gif"></center>';
    ePopup(title, content, 1);
}

// Like shop
var check_likeshop = new Array;
function likeShop(id, like, block){
    if (check_likeshop[id] != 1){
        check_likeshop[id] = 1;
        if (!block) block = 0;
        // Check block
        if (block != 0) {
            var block_id = block + "_" + id;
            block = "'" + block + "'";
        } else {
            var block_id = id;
        }
        $.ajax({
            type: "POST",
            url: "/ajax.php?mod=shop&act=likeshop",
            data: "shopId=" + id + "&likeId=" + like,
            success: function(data){
                data = eval( "("+data+")");
                $('#likeshoptotal_' + block_id).html(data.total);
                if (like == 0){
                    $('#likeshop_' + block_id).html("<a href=\"javascript:void(0)\" onclick=\"likeShop('" + id + "', 1, " + block + ");\" >Bỏ thích</a>");
                } else {
                    $('#likeshop_' + block_id).html("<a href=\"javascript:void(0)\" onclick=\"likeShop('" + id + "', 0, " + block + ");\" >Thích</a>");
                }
                check_likeshop[id] = 0;
            }
        });
    }
}
// Like nhóm
var check_likegroup = new Array;
function likeGroup(id, like){
    if (check_likegroup[id] != 1){
        check_likegroup[id] = 1;
        $.ajax({
            type: "POST",
            url: "/ajax.php?mod=groups&act=likegroup",
            data: "groupId=" + id + "&likeId=" + like,
            success: function(data){
                data = eval( "("+data+")");
                $('#likegrouptotal_' + id).html(data.total);
                if (like == 0){
                    $('#likegroup_' + id).html("<a href=\"javascript:void(0)\" onclick=\"likeGroup('" + id + "', 1);\" class=\"light\" >Bỏ thích</a>");
                } else {
                    $('#likegroup_' + id).html("<a href=\"javascript:void(0)\" onclick=\"likeGroup('" + id + "', 0);\" class=\"light\" >Thích</a>");
                }
                check_likegroup[id] = 0;
            }
        });
    }
}
function joinGroup(groupId, type){
    openPopup();
    $.ajax({
        type: "GET",
        url: "/ajax.php?mod=groupsnew&act=join-group",
        data: "groupId=" + groupId + "&type=" + type,
        dataType: "json",
        success: function(returnData){
            if (type == 0){
                popTitle = 'Tham gia nhóm ' + returnData.title + '?';
                ePopup(popTitle, returnData.data, returnData.button);
            } else {
                if (returnData == 'success'){
                    closePopup();
                    location.reload();
                } else {
                    joinGroup(id, 0);
                }
            }
        }
    });
}
// Hiển thị user like
var check_likegroupdetail = new Array;
function likeGroupDetail(id, option, sCount){
    if (option == 1){
        $("#ng-t-"+id).hide();
    } else {
        if (!check_likegroupdetail[id]){
            var returnText = "";
            $.ajax({
                type: "POST",
                url: "/ajax.php?mod=groups&act=get-like-group",
                data: "groupId=" + id + "&sCount=" + sCount,
                success: function(returnData){
                    returnData = eval( "("+returnData+")");
                    var user = returnData.data;
                    var total = returnData.total;
            
                    var last_item = user.length-1;
                    for (i=0;i<=last_item;i++){
                        if (i < last_item-1){
                            returnText = returnText + user[i] + ", ";
                        } else if (i < last_item){
                            returnText = returnText + user[i];
                        } else {
                            if (last_item == 0){
                                returnText = user[i] + ' thích nhóm này.';
                            } else {
                                if (total == 0){
                                    returnText = returnText + " và " + user[i] + ' thích nhóm này.';
                                } else if (total > 0){
                                    returnText = returnText + ", " + user[i] + ' và ' + total + ' người khác thích nhóm này.';
                                }
                            }
                        }
                    }
                    check_likegroupdetail[id] = returnText;
                    $("#ng-t-s-"+id).html(returnText);
                    $("#ng-t-"+id).show();
                }
            });
        } else {
            $("#ng-t-s-"+id).html(check_likegroupdetail[id]);
            $("#ng-t-"+id).show();
        }
    }
}
// Like com
var check_likecom = new Array;
function likeCom(id, like){
    if (check_likecom[id] != 1){
        check_likecom[id] = 1;
        $.ajax({
            type: "POST",
            url: "/ajax.php?mod=default&act=likecom",
            data: "comId=" + id + "&likeId=" + like,
            success: function(data){
                data = eval( "("+data+")");
                $('#likecomtotal_' + id).html(data.total);
                if (like == 0){
                    $('#likecom_' + id).html("<a href=\"javascript:void(0)\" onclick=\"likeCom('" + id + "', 1);\" class=\"light\" >Bỏ thích</a>");
                } else {
                    $('#likecom_' + id).html("<a href=\"javascript:void(0)\" onclick=\"likeCom('" + id + "', 0);\" class=\"light\" >Thích</a>");
                }
                check_likecom[id] = 0;
            }
        });
    }
}
$(".like_com").livequery("click", function (e){
    if (notLogin){
        requireLogin();
        return false;
    }
    var commodity = $(this);
    var comId = $(this).attr('rel');
    var like =0;
    if($(this).hasClass('unlike_com')) like = 1;
    $.ajax({
        url: '/ajax.php?mod=default&act=like-com',
        type:'GET',
        data: "comId=" + comId + "&likeId=" + like,
        success:function(data){
            if (data == 0){
                if(like == 0){
                    $(commodity).addClass('unlike_com').text("Bỏ thích");
                }else{
                    $(commodity).removeClass('unlike_com').text("Thích");   
                }
            }
        }  
    });
});
// Like ware
$(".like_ware").livequery("click", function (e){
    if (notLogin){
        requireLogin();
        return false;
    }
    var warehouse = $(this);
    var whid = $(this).attr('rel');
    var like =0;
    if($(this).hasClass('unlike_com')) like = 1;
    $.ajax({
        url: '/ajax.php?mod=default&act=like-ware',
        type:'GET',
        data: "whid=" + whid + "&likeId=" + like,
        dataType: "json",
        success:function(data){
            if (data.code == 0){
                $('#likewhtotal_' + whid).text(data.total);
                if(like == 0){
                    $(warehouse).addClass('unlike_com').text("Bỏ thích");
                }else{
                    $(warehouse).removeClass('unlike_com').text("Thích");   
                }
            }
        }  
    });
});
function ntAcFriend(id, option, index){
    $('#loading_accept_friend').show();
    $.ajax({
        type: "POST",
        url: "/ajax.php?mod=trader&act=accept-friend",
        data: "userId=" + id + "&send=1&option=" + option + "&notice_index=" + index,
        success: function(data){
            if (data == 'success'){
                $('#loading_accept_friend').hide();
                $('div.notice_accept_friend_' + id).remove();
            } else {
                $('#loading_accept_friend').hide();
            }
        }
    });
}
$('a.close_ware_teaser').livequery("click", function(){
    var whId = $(this).attr('rel');
    if ($('#wh_teaser_' + whId).hasClass("ware_teaser_close")){
        $('#wh_teaser_' + whId).removeClass("ware_teaser_close").addClass("ware_teaser");
        $(this).text("Thu nhỏ");
    } else {
        $('#wh_teaser_' + whId).removeClass("ware_teaser").addClass("ware_teaser_close");
        $(this).text("Xem thêm");
    }
});
function sell_this_product(wh_id){
    openPopup();
    $.ajax({
        url: '/ajax.php?mod=default&act=sell-warehouse',
        type:'GET',
        data: "type=1&whid=" + wh_id,
        dataType: "json",
        success:function(data){
            popTitle = 'Tôi bán sản phẩm này';
            var button = new Array;
            button.request = new Array;
            button.request.value = "Chọn gian hàng";
            button.request.callback = "selectShop(" + wh_id + ")";
            //button.cancel = 1;
            ePopup(popTitle, data.value, button);
        }  
    });
}

function add_product(){
    openPopup();
    $.ajax({
        url: '/ajax.php?mod=default&act=sell-warehouse',
        type:'GET',
        data: "type=1",
        dataType: "json",
        success:function(data){
            if(data.code==1){
                popTitle = 'Đăng sản phẩm';
                var button = new Array;
                button.request = new Array;
                button.request.value = "Đăng sản phẩm";
                button.request.callback = "selectShopAdd()";
                //button.cancel = 1;
                ePopup(popTitle, data.value, button);
            }else{
                alert('Bạn chưa có gian hàng, hãy tạo gian hàng để đăng sản phẩm.');
                window.location="http://eway.vn/management/create-shop.html";
            }
        }  
    });
}

$("choose_shop").change(function () {
    var str = "";
    $("select option:selected").each(function () {
        str += $(this).val() + " ";
    });
    $("div").text(str);
})
.trigger('change');


function selectShopAdd(){
    var shop = $("#choose_shop").val();
    window.location="http://eway.vn/"+shop+"/admin/add-product";
}

function selectShop(wh_id){
    initMCE();
    $.ajax({
        url: '/ajax.php?mod=default&act=sell-warehouse',
        type:'GET',
        data: "type=2&whid=" + wh_id + "&shop_link=" + $("#choose_shop").val(),
        dataType: "json",
        success:function(data){
            if(data.error==1){
                closePopup();
                $(".bg_opacity").hide();
                $("#pay-ttcn").hide();
                alert('Gian hàng của bạn đã đăng sản phẩm này!');
                return;
            }
            popTitle = 'Tôi bán sản phẩm này';
            var button = new Array;
            //button.cancel = 1;
            ePopup(popTitle, data.value, button, 763);
        //            $(".bg_opacity").show();
        //            closePopup();
        //            if ($("#popup-sell-this-product").hasClass("popup")){
        //                $("#popup-sell-this-product").remove();
        //            }
        //            $("body").append(data.value);
        }  
    });
}
function initMCE(){
    tinyMCE.init({
        // General options
        mode : "textareas",
        theme : "advanced",
        plugins : "autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave,",

        // Theme options
        theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,fontselect,fontsizeselect,bullist,numlist,undo,redo,|,link,unlink,image,forecolor,backcolor,pasteword",
        theme_advanced_buttons2 : "",
        theme_advanced_buttons3 : "",
        theme_advanced_buttons4 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : false,

        // Example content CSS (should be your site CSS)
        content_css : "css/content.css",

        // Drop lists for link/image/media/template dialogs
        template_external_list_url : "lists/template_list.js",
        external_link_list_url : "lists/link_list.js",
        external_image_list_url : "lists/image_list.js",
        media_external_list_url : "lists/media_list.js",

        // Style formats
        style_formats : [
        {
            title : 'Bold text', 
            inline : 'b'
        },

        {
            title : 'Red text', 
            inline : 'span', 
            styles : {
                color : '#ff0000'
            }
        },

        {
            title : 'Red header', 
            block : 'h1', 
            styles : {
                color : '#ff0000'
            }
        },

        {
            title : 'Example 1', 
            inline : 'span', 
            classes : 'example1'
        },

        {
            title : 'Example 2', 
            inline : 'span', 
            classes : 'example2'
        },

        {
            title : 'Table styles'
        },

        {
            title : 'Table row 1', 
            selector : 'tr', 
            classes : 'tablerow1'
        }
        ],

        // Replace values for the template plugin
        template_replace_values : {
            username : "Some User",
            staffid : "991234"
        }
    });
}
function upProduct(sp_whid, sp_shop){
    $.ajax({
        url: '/ajax.php?mod=trader&act=upsp',
        type:'POST',
        data:"sp_shop=" + sp_shop + "&sp_whid=" + sp_whid,
        success:function(data){
            alert(data);
        }
    });
}
function openPayAds(){
    openPopup();
    $.ajax({
        url: '/ajax.php?mod=shop&act=get-my-shop',
        type:'GET',
        dataType:"json",
        success:function(data){
            $("#pay-shop").html('');
            $.each(data.value, function(){
                $("#pay-shop").append("<option value='" + this.shop_id + "'>" + this.shop_name + "</option>");
            });
            closePopup();
            $(".bg_opacity").show();
            $("#pay-ttcn").show();
        }
    });
}
$('.close-pay').livequery("click", function(){
    $(".bg_opacity").hide();
});
$('#pay-productid').livequery("change", function(){
    //getMyProduct();
    });
$('#button-next-pay').livequery("click", function(e){
    if (!$("#pay-productid").val()){
        alert("Bạn chưa chọn sản phẩm!");
        e.stopPropagation();
        return false;
    }
    if ($("#not-money").isVisible){
        alert("Bạn không đủ tiền để tiếp tục, vui lòng nạp thêm tiền!");
        e.stopPropagation();
        return false;
    }
    getMyProduct();
});
var get_product_done = false;
function getMyProduct(){
    $.ajax({
        url: '/ajax.php?mod=shop&act=get-my-product',
        type:'GET',
        data: 'shopid=' + $("#pay-shop").val() + '&productid=' + $("#pay-productid").val() + '&cid=' + cid,
        dataType:"json",
        success:function(data){
            if (data.value){
                $(".result-product").show();
                $(".pay-product-name").html(data.value.product);
                $.each(data.value.category, function(){
                    $(".pay-category-name").append(this + "/");
                })
                $(".pay-btn").show();
                get_product_done = true;
                showObj_hideObj('pay-tt', 'pay-ttcn');
            } else {
                alert("Không có sản phẩm này hoặc sản phẩm này đã có trong danh mục.");
                return false;
            }
        }
    });
}
function payAdsProduct(){
    openPopup();
    $.ajax({
        url: '/ajax.php?mod=default&act=pay-ads-product',
        type:'GET',
        data: 'shopid=' + $("#pay-shop").val() + '&productid=' + $("#pay-productid").val() + '&day=' + $("#count_day").val() + '&cid=' + cid,
        dataType:"json",
        success:function(data){
            alert("Bạn đã thanh toán thành công, xin vui lòng đợi trong ít phút !");
            window.location = urlReload;
        }
    });
}

function showObj_hideObj(objId1, objId2){
    $("#"+objId1).show();
    $("#"+objId2).hide();
}

function depositMoney(){
    openPopup();
    $.ajax({
        url: '/ajax.php?mod=default&act=deposit-money',
        type:'GET',
        dataType:"json",
        success:function(data){
            //closePopup();
            //if ($("#popup-pay").hasClass("popup")){
            //$("#popup-pay").remove();
            //}
            //$("body").append(data.value);
            var button = new Array;
            ePopup('Nạp tiền vào tài khoản', data.value, button, 710);
        }
    });
}
function depositFinish(){
    $("#deposit-form").submit();
}

function view_comment(cm_id){
    $.ajax({
        url: '/ajax.php?mod=warehouse&act=view-comment',
        type:'GET',
        data: 'cm_id=' + cm_id,
        dataType:"html",
        success:function(data){
            //$('rel').attr(cm_id);
            $('#'+cm_id).html(data);
        }
    });
	
}

function new_comment(){
    if(user){
        $.ajax({
            url: '/ajax.php?mod=warehouse&act=new-comment',
            type:'GET',
            dataType:"html",
            success:function(data){
                //$('rel').attr(cm_id);
                $('#add_comment').html(data);
            }
        });
    }
    else{
        alert('Bạn chưa đăng nhập');
    }
}

function add_comment(){
    $.ajax({
        url: '/ajax.php?mod=warehouse&act=new-comment',
        type:'POST',
        dataType:"html",
        success:function(data){
            $('#add_comment').html(data);
        }
    });
}

function new_reply(cm_id){
    $.ajax({
        url: '/ajax.php?mod=warehouse&act=new-reply',
        type:'GET',
        data:'cm_id='+cm_id,
        dataType:"html",
        success:function(data){
            $('.reply').html('');
            $('#reply_'+cm_id).html(data);
            $('#reply_'+cm_id).focus();
        }
    });
}

function datMua(productid, shoplink, price, secret){
    $('#show_content_popup').css('padding', '0');
    openPopup();
    $.ajax({
        url: '/ajax.php?mod=shop&act=buy',
        type: 'GET',
        data: 'productId=' + productid + '&shopLink=' + shoplink + '&price=' + price + '&secret=' + secret,
        dataType:"json",
        success:function(data){
            var button = new Array;
            ePopup('', data.value, button, 710);
        }
    });
}
var buy_type = 1;
var buy_bank = 'vietcombank';
function selectTypeBuy(type){
    buy_type = type;
    $("#payment-option-image").attr('src', $("#select-payment-" + type).attr('src'));
    $("#payment-option-info").html($("#select-payment-info-" + type).html());
    if (type == 3){
        $("#bank-info").show();
        buy_bank = 'vietcombank';
    } else {
        $("#bank-info").hide();
    }
    $("#payment_type").val(type);
}
function selectBankBuy(bank){
    buy_bank = bank;
    $("#payment-option-image-bank").html('<img src="' + $("#select-image-" + bank).attr('src') + '">');
    $("#payment-option-info-bank").html($("#select-" + bank).html());
    $("#payment_bank").val(bank);
}
function deleteWh(wh_id){
    var flag = confirm('Bạn có chắc chắn muốn xóa sản phẩm này không?');
    if(flag){
        $.ajax({
            url: '/ajax.php?mod=warehouse&act=delete-wh',
            type:'POST',
            data:'wh_id='+wh_id,
            dataType:"html",
            success:function(data){
                window.location = data;
            }
        });
    }else{
        return false;
    }
    
}

function editWh(wh_id){
    initMCE();
    $.ajax({
        url: '/ajax.php?mod=warehouse&act=edit-wh',
        type:'POST',
        data:'wh_id='+wh_id,
        dataType:"html",
        success:function(data){
            popTitle = 'Sửa thông tin sản phẩm';
            var button = new Array;
            //button.cancel = 1;
            ePopup(popTitle, data, button,1000);
        }
    })
}
function moveWh(wh_id){
    openPopup();
    $.ajax({
        url: '/ajax.php?mod=warehouse&act=move-wh',
        type:'GET',
        data:'wh_id='+wh_id,
        dataType:"html",
        success:function(data){
            popTitle = 'Thay đổi sản phẩm shop tới sản phẩm kho khác';
            var button = new Array;
            //button.cancel = 1;
            ePopup(popTitle, data, button,1000);
        }
    });
}
function moveWhSend(wh_id, wh_change){
    openPopup();
    $.ajax({
        url: '/ajax.php?mod=warehouse&act=move-wh&wh_id=' + wh_id,
        type:'POST',
        data:'wh_chage='+wh_change,
        dataType:"json",
        success:function(data){
            if (data.value='success'){
                popTitle = 'Thay đổi sản phẩm shop tới sản phẩm kho khác';
                var button = new Array;
                //button.cancel = 1;
                ePopup(popTitle, "Bạn đã thay đổi thành công", button,1000);
            }
        }
    });
}
function formatCurrency(nStr){
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    }
    return x1;
}

function editfast(pro_whid, pro_shop){
    openPopup();
    $.ajax({
        url: '/ajax.php?mod=adminshop&act=edit-fast-product',
        type:'POST',
        data:'pro_whid=' + pro_whid + '&pro_shop=' + pro_shop,
        dataType:"html",
        success:function(data){
            popTitle = 'Thay đổi nhanh sản phẩm của gian hàng';
            var button = new Array;
            //            button.cancel = 1;
            ePopup(popTitle, data, button,500);
        }
        
    });
}

function editprofast(){
    var sp_whid = $('#sp_whid_fast').val();
    var sp_shop = $('#sp_shop_fast').val();
    var sp_price = $('#sp_price_fast').val();
    var sp_up_quantity = $('#sp_up_quantity_fast').val();
    
    $.ajax({
        url: '/ajax.php?mod=adminshop&act=edit-fast-product-act',
        type:'POST',
        data: 'sp_whid=' + sp_whid + '&sp_shop=' + sp_shop + '&sp_price='+sp_price + '&sp_up_quantity=' + sp_up_quantity,
        dataType:"json",
        success:function(data){
            closePopup();
            location.reload();
        }
    });
}
