$(document).ready(function () {
	$.ajax({
		type: 'POST',
		url: "/html/kiemtrakhachhang/",
		async: true,
		success: function (responseText) {
			$('.kiemtrakhachhang').html(responseText);
		}
	});
	return false;
});
$(document).ready(function() {
    $(".khuvuctinlienquanbaiviet").each(function() {
        var id = $(this).attr("id");
        gettin(id, $(this));
    });
});
function gettin(id, obj) {
    $.ajax({
        type: 'POST',
        url: "/html/tintuc/?id=" + id,
        async: true,
        success: function(responseText) {
            $(obj).html(responseText);
        }
    });
    return false;
}
$(document).ready(function() {
    $(".khuvucsanphamlienquanbaiviet").each(function() {
        var id = $(this).attr("id");
        getsanpham(id, $(this));
    });
});
function getsanpham(id, obj) {
    $.ajax({
        type: 'POST',
        url: "/html/sanpham/?id=" + id,
        async: true,
        success: function(responseText) {
            $(obj).html(responseText);
        }
    });
    return false;
}
$(document).ready(function() {
    $(".loaddataajax").each(function() {
        var link = $(this).attr("data-src");
        getboloc(link, $(this));
    });
});
function getboloc(link, obj) {
    $.ajax({
        type: 'POST',
        url: link,
        async: true,
        beforeSend: function() {
            $('.onload').show();
        },
        success: function(responseText) {
            $(obj).html(responseText);
			var cao = $(obj).parent().parent().height();
			var tong = $("#wrap-left").height();
			$("#wrap-left").height(tong+cao);
        }
    });
    return false;
}
$(document).ready(function() {
    $(".loaddatapagging").each(function() {
        var link = $(this).attr("data-src");
        getpagging(link, $(this));
    });
});
function getpagging(link, obj) {
    $.ajax({
        type: 'POST',
        url: link,
        async: true,
        success: function(responseText) {
            $(obj).html(responseText);
        }
    });
    return false;
}
jQuery.fn.treeListFilter = function(list, timeout) {
    var list = jQuery(list);
    var input = this;
    var keyTimeout;
    var lastFilter = '';
    if (timeout === undefined) {
        timeout = 200;
    }
    function filterList(ulObject, filterValue) {
        if (!ulObject.is('ul') && !ulObject.is('ol')) {
            return false;
        }
        var children = ulObject.children();
        var result = false;
        for (var i = 0; i < children.length; i++) {
            var liObject = jQuery(children[i]);
            if (liObject.is('li')) {
                var display = false;
                if (liObject.children().length > 0) {
                    for (var j = 0; j < liObject.children().length; j++) {
                        var subDisplay = filterList(jQuery(liObject.children()[j]), filterValue);
                        display = display || subDisplay;
                    }
                }
                if (!display) {
                    var text = liObject.text();
                    display = text.toLowerCase().indexOf(filterValue) >= 0;
                }
                liObject.css('display', display ? '' : 'none');
                result = result || display;
            }
        }
        return result;
    }
    input.change(function() {
        var filter = input.val().toLowerCase();
        //var startTime = new Date().getTime();
        filterList(list, filter);
        //var endTime = new Date().getTime();
        return false;
    }).keydown(function() {
        clearTimeout(keyTimeout);
        keyTimeout = setTimeout(function() {
            if (input.val() === lastFilter) return;
            lastFilter = input.val();
            input.change();
        }, timeout);
    });
    return this;
};$.fn.digits = function(){ 
    return this.each(function(){ 
        $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
    })
}
$(document).ready(function(){
   $("div.value, span.so").digits();
});

$(document).ready(function() {
    $(".txtsoluonggiam").click(function() {
        var txtSL = $(this).parent(".formmuahang").children(".txtsoluong");
        var value = parseInt(txtSL.val(), 10);
        value = isNaN(value) ? 2 : value <= 1 ? 2 : value;
        value--;
        txtSL.val(value);
    });

    $(".txtsoluongtang").click(function() {
        var txtSL = $(this).parent(".formmuahang").children(".txtsoluong");
        var value = parseInt(txtSL.val(), 10);
        value = isNaN(value) ? 0 : value > 99 ? 98 : value;
        value++;
        txtSL.val(value);
    });

    jQuery('.txtsoluong').keyup(function() {
        this.value = this.value.replace(/[^0-9\.]/g, '');
        if (this.value == "") {
            this.value = 1;
        }
    });
});

$(document).ready(function() {
    $('.noidungtimkiem').keyup(function() {
        var key = $(this).val();
        if (key.length < 3) {
            $("#autosuggest").hide();
        }
        $.ajax({
            type: 'POST',
            url: "/search/keyword.asp?key=" + key,
            async: true,
            success: function(responseText) {
                if (responseText != "") {
                    $('#autosuggest').html("");
                    $('#autosuggest').html(responseText);
                    $("#autosuggest").show();
                } else {
                    $("#autosuggest").hide();
                }
            }
        });
    });
});
$(document).ready(function() {
    $('.addtowishlist').click(function() {
        var id = $(this).closest(".formmuahang").children(".txtmasanpham").val();
        var sl = 1;
        var thongbao = $(".thongbao");
        $.ajax({
            type: 'POST',
            url: "/cart/addwishlist.asp?IDPart=" + id,
            async: true,
            success: function(responseText) {
                eval(responseText);
                $('.soluongwishlist').html(info.sl);
                thongbao.show();
                thongbao.children(".noidungthongbao").html(info.thongbao);
                thongbao.delay(5000).hide(0);
				$(".resultwishlist").removeClass("show");
				$(".resultwishlist").addClass("hide");
            }
        });

        var cart = $('.fa-heart-o');
        var imgtodrag = $(this).parents('.wrap-sanpham').find(".img img");
        if (imgtodrag) {
            var imgclone = imgtodrag.clone()
                .offset({
                    top: imgtodrag.offset().top,
                    left: imgtodrag.offset().left
                })
                .css({
                    'opacity': '0.5',
                    'position': 'absolute',
                    'width': '150px',
                    'z-index': '100'
                })
                .appendTo($('body'))
                .animate({
                    'top': cart.offset().top + 10,
                    'left': cart.offset().left + 10,
                    'width': 75,
                    'height': 75
                }, 1000, 'easeInOutExpo');

            setTimeout(function() {
                cart.effect("shake", {
                    times: 2
                }, 200);
            }, 1500);

            imgclone.animate({
                'width': 0,
                'height': 0
            }, function() {
                $(this).detach()
            });
        }

    });
    $(".close").click(function() {
        $(this).parent(".thongbao").hide();
    });
});

$(document).ready(function() {
    $('.wishlistcoban').click(function() {
        $.post("/html/wishlist/", function(data) {
            $(".resultwishlist").html(data);
        });

        if ($(".resultwishlist").hasClass("show")) {
            $(".resultwishlist").removeClass("show");
            $(".resultwishlist").addClass("hide");
        } else {
            $(".resultwishlist").removeClass("hide");
            $(".resultwishlist").addClass("show");
        }
    });
});

$(document).ready(function() {
    $('.addtocart').click(function() {
        var id = $(this).closest(".formmuahang").children(".txtmasanpham").val();
        var sl = 1;
        var thongbao = $(".thongbao");
        $.ajax({
            type: 'POST',

            url: "/cart/addgiohang.asp?IDPart=" + id + "&SL=" + sl,

            async: true,
            success: function(responseText) {

                eval(responseText);
                $('.soluongreter').html(info.sl);
                $('.trigiareter').html(info.tongtien);
                thongbao.show();
                thongbao.children(".noidungthongbao").html(info.thongbao);
                thongbao.delay(5000).hide(0);

            }
        });

        var cart = $('.fa-shopping-cart');
        var imgtodrag = $(this).parents('.wrap-sanpham').find(".img img");
        if (imgtodrag) {
            var imgclone = imgtodrag.clone()
                .offset({
                    top: imgtodrag.offset().top,
                    left: imgtodrag.offset().left
                })
                .css({
                    'opacity': '0.5',
                    'position': 'absolute',
                    'width': '150px',
                    'z-index': '100'
                })
                .appendTo($('body'))
                .animate({
                    'top': cart.offset().top + 10,
                    'left': cart.offset().left + 10,
                    'width': 75,
                    'height': 75
                }, 1000, 'easeInOutExpo');

            setTimeout(function() {
                cart.effect("shake", {
                    times: 2
                }, 200);
            }, 1500);

            imgclone.animate({
                'width': 0,
                'height': 0
            }, function() {
                $(this).detach()
            });
        }

    });
    $(".close").click(function() {
        $(this).parent(".thongbao").hide();
    });
});

printSoLuong();
printGiaTri();
printSoLuongWishList();

function printSoLuong() {
    $.get('/cart/soluong.asp', function(data) {
        $(".soluongreter").html(data);
    });
}

function printGiaTri() {
    $.get('/cart/giatri.asp', function(data) {
        $(".trigiareter").html(data);
    });
}

function printSoLuongWishList() {
    $.get('/cart/soluongwishlist.asp', function(data) {
        $(".soluongwishlist").html(data);
    });
}

function CheckActive(id) {
    $.get('/cart/check.asp?IDPart=' + id, function(data) {
        if (data == '0') {
            if (CheckArray(id)) {
                arr.push(id);
                $("#IMG_" + id).css('display', 'block');
                $("#IMG_" + id).attr('src', '/images/deadd.png');
            }
        } else {}
    });
}

function CheckArray(id) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == id)
            return false;
    }
    return true;
}

function OVER_PP(id) {
    if (CheckArray(id)) {
        $("#IMG_" + id).css('display', 'block');
        $("#IMG_" + id).attr('src', '/images/add.png');
    }
}

function OUT_PP(id) {
    if (CheckArray(id)) {
        $("#IMG_" + id).css('display', 'none');
    }
}

function RequestData(Id, Quality, Price) {
    $("#TT_Process").css('display', 'block');
    $("#TT_Process").html(data2);
}

function RemoveArr(Id) {
    var _arr = new Array();
    for (i = 0; i < arr.length; i++) {
        if (arr[i] != Id)
            _arr.push(arr[i]);
    }
    arr = _arr;
}

function validateDomainName(inputForm) {
    var false_string = "!@#$%^&,' '*()+={[}]'?/;";
    var the_char = " ";
    var domainName = inputForm.domain.value;
    if ((inputForm.domain.value.length <= 2)) {
        window.alert("Tên miền không hợp lệ (Invalid Domain Name)! ")
        return false;
    }
    for (loop = 0; loop < false_string.length; loop++) {
        the_char = false_string.charAt(loop);
        if (domainName.indexOf(the_char) != -1) {
            window.alert("Tên miền không hợp lệ (Invalid Domain Name)! ")
            return false;
        }
    }
    return true;
}

var idCounter = 0;

function currentTime() {
    var date = new Date();
    var hour = new String(date.getHours());
    hour = (hour.length == 1) ? '0' + hour : hour;
    var minute = new String(date.getMinutes());
    minute = (minute.length == 1) ? '0' + minute : minute;
    var second = new String(date.getSeconds());
    second = (second.length == 1) ? '0' + second : second;
    var fifteenth = new Date();
    var sixteenth = fifteenth.getFullYear();
    var seventeenth = fifteenth.getDay();
    var month = fifteenth.getMonth();
    var eighteenth = fifteenth.getDate();
    if (eighteenth < 10) eighteenth = '0' + eighteenth;
    var first2 = new Array('Chủ nhật', 'Thứ hai', 'Thứ ba', 'Thứ tư', 'Thứ năm', 'Thứ sáu', 'Thứ bảy');
    var second2 = new Array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12');
    var currentNow = hour + minute;
    currentNow = first2[seventeenth] + ", " + eighteenth + "-" + second2[month] + '-' + sixteenth + "-" + hour + ":" + minute + ":" + second;
    $("#currentTime").html(currentNow);
    setTimeout("currentTime()", 1000);
}
currentTime();

function LayChiTietSanPhamPhu(strclass, id) {
    $.ajax({
        type: 'post',
        url: "/search/spphu.asp",
        data: "q=" + id,
        async: true,
        success: function(responseText) {
            $("." + strclass).html(responseText);
        }
    });
}

$(document).ready(function() {
    $(".masanphamphu").change(function() {
        id = $(this).val();
        LayChiTietSanPhamPhu("noidungsanphamphu", id);
    });
});

function incrementValue() {
    var value = parseInt(document.getElementById('number').value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('number').value = value;
}

function incrementValue0() {
    var value = parseInt(document.getElementById('number').value, 10);
    value = isNaN(value) ? 0 : value;
    value--;
    document.getElementById('number').value = value;
}

function commaSeparateNumber(val) {
    while (/(\d+)(\d{3})/.test(val.toString())) {
        val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
    }
    return val;
}

//load fancybox
$(document).ready(function() {
	$(".fancybox").fancybox();
});
//load countdown
!function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery"],a):a(jQuery)}(function(a){"use strict";function b(a){if(a instanceof Date)return a;if(String(a).match(g))return String(a).match(/^[0-9]*$/)&&(a=Number(a)),String(a).match(/\-/)&&(a=String(a).replace(/\-/g,"/")),new Date(a);throw new Error("Couldn't cast `"+a+"` to a date object.")}function c(a){return function(b){var c=b.match(/%(-|!)?[A-Z]{1}(:[^;]+;)?/gi);if(c)for(var e=0,f=c.length;f>e;++e){var g=c[e].match(/%(-|!)?([a-zA-Z]{1})(:[^;]+;)?/),i=new RegExp(g[0]),j=g[1]||"",k=g[3]||"",l=null;g=g[2],h.hasOwnProperty(g)&&(l=h[g],l=Number(a[l])),null!==l&&("!"===j&&(l=d(k,l)),""===j&&10>l&&(l="0"+l.toString()),b=b.replace(i,l.toString()))}return b=b.replace(/%%/,"%")}}function d(a,b){var c="s",d="";return a&&(a=a.replace(/(:|;|\s)/gi,"").split(/\,/),1===a.length?c=a[0]:(d=a[0],c=a[1])),1===Math.abs(b)?d:c}var e=100,f=[],g=[];g.push(/^[0-9]*$/.source),g.push(/([0-9]{1,2}\/){2}[0-9]{4}( [0-9]{1,2}(:[0-9]{2}){2})?/.source),g.push(/[0-9]{4}([\/\-][0-9]{1,2}){2}( [0-9]{1,2}(:[0-9]{2}){2})?/.source),g=new RegExp(g.join("|"));var h={Y:"years",m:"months",w:"weeks",d:"days",D:"totalDays",H:"hours",M:"minutes",S:"seconds"},i=function(b,c,d){this.el=b,this.$el=a(b),this.interval=null,this.offset={},this.instanceNumber=f.length,f.push(this),this.$el.data("countdown-instance",this.instanceNumber),d&&(this.$el.on("update.countdown",d),this.$el.on("stoped.countdown",d),this.$el.on("finish.countdown",d)),this.setFinalDate(c),this.start()};a.extend(i.prototype,{start:function(){null!==this.interval&&clearInterval(this.interval);var a=this;this.update(),this.interval=setInterval(function(){a.update.call(a)},e)},stop:function(){clearInterval(this.interval),this.interval=null,this.dispatchEvent("stoped")},pause:function(){this.stop.call(this)},resume:function(){this.start.call(this)},remove:function(){this.stop(),f[this.instanceNumber]=null,delete this.$el.data().countdownInstance},setFinalDate:function(a){this.finalDate=b(a)},update:function(){return 0===this.$el.closest("html").length?void this.remove():(this.totalSecsLeft=this.finalDate.getTime()-(new Date).getTime(),this.totalSecsLeft=Math.ceil(this.totalSecsLeft/1e3),this.totalSecsLeft=this.totalSecsLeft<0?0:this.totalSecsLeft,this.offset={seconds:this.totalSecsLeft%60,minutes:Math.floor(this.totalSecsLeft/60)%60,hours:Math.floor(this.totalSecsLeft/60/60)%24,days:Math.floor(this.totalSecsLeft/60/60/24)%7,totalDays:Math.floor(this.totalSecsLeft/60/60/24),weeks:Math.floor(this.totalSecsLeft/60/60/24/7),months:Math.floor(this.totalSecsLeft/60/60/24/30),years:Math.floor(this.totalSecsLeft/60/60/24/365)},void(0===this.totalSecsLeft?(this.stop(),this.dispatchEvent("finish")):this.dispatchEvent("update")))},dispatchEvent:function(b){var d=a.Event(b+".countdown");d.finalDate=this.finalDate,d.offset=a.extend({},this.offset),d.strftime=c(this.offset),this.$el.trigger(d)}}),a.fn.countdown=function(){var b=Array.prototype.slice.call(arguments,0);return this.each(function(){var c=a(this).data("countdown-instance");if(void 0!==c){var d=f[c],e=b[0];i.prototype.hasOwnProperty(e)?d[e].apply(d,b.slice(1)):null===String(e).match(/^[$A-Z_][0-9A-Z_$]*$/i)?(d.setFinalDate.call(d,e),d.start()):a.error("Method %s does not exist on jQuery.countdown".replace(/\%s/gi,e))}else new i(this,b[0],b[1])})}});
