﻿jQuery.jAutoSubmit = function(enterBox, submitButton) {
    enterBox.each(function() {
        $(this).keypress(function(e) {
            if (13 == e.keyCode) {
                setTimeout(function() { submitButton.trigger('click'); }, 100);
                e.preventDefault(); e.stopPropagation();
                //}
            }
        });
    });
}

jQuery.pWatermark = function(waterBox, swapColor) {
    if (!waterBox || waterBox.length == 0) {
        return;
    }
    swapColor = swapColor ? swapColor : "#d5d5d5";
    waterBox.each(function() {
    $(this).data('swapValue', $(this).val()).data("oldcolor", $(this).css("color")).css("color", swapColor);
        $(this).unbind("focus").unbind("blur");
        $(this).focus(function() {
            if ($(this).val() == $(this).data('swapValue')) {
                $(this).val('').css("color", $(this).data("oldcolor"));

            }
        }).blur(function() {
            if ($(this).val() == '') {
                $(this).css("color", swapColor);
                $(this).val($(this).data('swapValue'));
            }
        });
    });
}

jQuery.validator.addMethod("validwatermark", function(value, element, param) {
    if ($(element).val() == "" || $(element).val() == $(element).data('swapValue')) {
        return false;
    }
    return true;
});

$(document).ready(function() {
    $("form:eq(0)").validate({
        onsubmit: false,
        errorElement: "span",
        errorElementClass: "err",
        errorClass: "inpe",
        errorPlacement: function(error, element) {
            if (element.next('p').length) {
                error.appendTo(element.next('p'));
            } else {
                error.insertAfter(element);
            }
        },
        rules: {
            shareto: {
                required: true,
                validwatermark: true,
                email: true
            },
            sharefrom: {
                required: true,
                validwatermark: true,
                email: true
            },
            sharemsg: {
                required: true,
                validwatermark: true,
                maxlength: 200
            },
            txtSigninUsername: {
                required: true
            },
            txtSigninPassword: {
                required: true
            }
        },
        messages: {
            sharemsg: {
                required: "Please input your message.",
                validwatermark: "Please input your message."
            },
            shareto: {
                required: "Please input your friend's email",
                validwatermark: "Please input your friend's email",
                email: "Please input a valid email"
            },
            sharefrom: {
                required: "Please input your email.",
                validwatermark: "Please input your email.",
                email: "Please input a valid email"
            },
            txtSigninUsername: {
                required: "Please input your username"
            },
            txtSigninPassword: {
                required: "Please input your password"
            }
        }
    });
    //Update Share Popup
    $.pWatermark($("#shareto,#sharefrom,#sharemsg"));
    $.jAutoSubmit($("#txtSigninUsername,#txtSigninPassword"), $("#btnSignin"));
    $("#btnShare").click(function() {
        var bRet = true;
        bRet = $("#shareto").valid() && bRet;
        bRet = $("#sharefrom").valid() && bRet;
        bRet = $("#sharemsg").valid() && bRet;
        if (bRet) {
            $.post("/share_with_friend/", { shareto: $("#shareto").val(), sharefrom: $("#sharefrom").val(), sharemsg: $("#sharemsg").val(), url: window.location.href }, function(data) {
                eval("var ret = " + data);
                if (ret.ret == 0) {
                    alert("You have shared this page to your friends");
                } else {
                    alert(ret.msg);
                }
            });
        }
    });


    $("#aSignInFacebook").click(function() {
        FB_RequireFeatures(["Connect"], function() {
            FB.Connect.requireSession(function() { window.location.reload(); }, null, true);
        });
    });

    if ($.fancybox) {
        $(".fancyBox").fancybox({
            'titleShow': false
        });
    }
    $("#btnSignin").click(function() {
        var bRet = true;
        bRet = $("#txtSigninUsername").valid() && bRet;
        bRet = $("#txtSigninPassword").valid() && bRet;
        if (bRet) {
            $.post("/login/", { username: $("#txtSigninUsername").val(), password: hex_md5($("#txtSigninPassword").val()) }, function(data) {
                eval('var ret = ' + data);
                if (ret.ret == 0) {
                    window.location.reload();
                } else {
                    $("#txtSigninPassword").next('p').text(ret.msg);
                    setTimeout(function() { $("#txtSigninPassword").next('p').html("&nbsp;"); }, 1000);
                }
            });
        }
    });
});

function add_to_cart(product_id, product_color_id) {
    $.post("/mycart/add/", { product_id: product_id, product_color_id: product_color_id }, function(data) {
        eval("var ret=" + data);
        if (ret.ret == 1) {
            alert(ret.msg);
        } else {
            //alert("Add to Cart successfully");
            //Set Cart Popup field
            var productInfo = ret.productInfo;
            $('#cartpopup').find('img:eq(0)').attr('src', productInfo.product_image);
            $('#cartpopup').find('.details>li:eq(0)>h2').text(productInfo.product_color_title);
            $('#cartpopup').find('.details>li:eq(1)').text("Quantity: " + productInfo.product_num);
            $('#cartpopup').find('.details>li:eq(2)>strong').text("$" + productInfo.product_price + " each");

            $('#cartpopup .popshopdetail>li:eq(0)>h3>strong:eq(1)').text(productInfo.total_item + " Item(s)");
            $('#cartpopup .popshopdetail>li:eq(1)>strong:eq(1)').text("$" + parseFloat(productInfo.total_price).toFixed(2));
            $('#cartpopup').show();
            $('#iframec').show();
            var toppos = ($(window).height() - $("#cartpopup").height()) / 2 + $(window).scrollTop(); $("#cartpopup").css("top", toppos)
            //Update top right
            $("#totalItemCount").text(" Cart (" + productInfo.total_item + ")");
//            for (var i = 0; i < ret.productList.length; i++) {
//                var item = ret.productList[i];
//                var liObj = $("#ulCart").find("li[pc_id=" + item.product_id + "_" + item.product_color_id + "]");
//                if (liObj.length) {
//                    liObj.find('span:eq(1)').text("$" + parseFloat(item.product_price).toFixed(2));
//                } else {
//                    var newLi = $('<li pc_id="' + item.product_id + "_" + item.product_color_id + '"><span class="lf"></span><span class="rg"></span></li>');
//                    newLi.find('span:eq(0)').text(item.product_color_title);
//                    newLi.find('span:eq(1)').text("$" + parseFloat(item.product_price).toFixed(2));
//                    $("#liTotalPrice").before(newLi);
//                }
//            }
//            $("#liTotalPrice").find('strong:eq(1)').text("$" + productInfo.total_price);
        }
    });
}

function add_to_cart_number(product_id, num) {
    $.post("/mycart/add/", { product_id: product_id, number: num }, function(data) {
        eval("var ret=" + data);
        if (ret.ret == 1) {
            alert(ret.msg);
        } else {
            //alert("Add to Cart successfully");
            //Set Cart Popup field
            var productInfo = ret.productInfo;
            $('#cartpopup').find('img:eq(0)').attr('src', productInfo.product_image);
            $('#cartpopup').find('.details>li:eq(0)>h2').text(productInfo.product_color_title);
            $('#cartpopup').find('.details>li:eq(1)').text("Quantity: " + productInfo.product_num);
            $('#cartpopup').find('.details>li:eq(2)>strong').text("$" + productInfo.product_price + " each");

            $('#cartpopup .popshopdetail>li:eq(0) strong:eq(1)').text(productInfo.total_item + " Item(s)");
            $('#cartpopup .popshopdetail>li:eq(1)>strong:eq(1)').text("$" + productInfo.total_price);
            $('#cartpopup').show();
            $('#iframec').show();
            //Update top right
            $("#totalItemCount").text(productInfo.total_item);
            for (var i = 0; i < ret.productList.length; i++) {
                var item = ret.productList[i];
                var liObj = $("#ulCart").find("li[pc_id=" + item.product_id + "_" + item.product_color_id + "]");
                if (liObj.length) {
                    liObj.find('span:eq(1)').text("$" + item.product_price);
                } else {
                    var newLi = $('<li pc_id="' + item.product_id + "_" + item.product_color_id + '"><span class="lf"></span><span class="rg"></span></li>');
                    newLi.find('span:eq(0)').text(item.product_color_title);
                    newLi.find('span:eq(1)').text("$" + item.product_price);
                    $("#liTotalPrice").before(newLi);
                }
            }
            $("#liTotalPrice").find('strong:eq(1)').text("$" + productInfo.total_price);
        }
    });
}

function add_to_wishlist(product_id) {
    if (!gLoggedIn) {
        $('#iframec').show(0);
        $('#signinpopup').show(0);
        return;
    }
    $.post("/mywishlist/add/", { product_id: product_id }, function(data) {
        eval("var ret=" + data);
        if (ret.ret == 1) {
            alert(ret.msg);
        } else {
            $("iframec,#wishlistPopup").show();
        }
    });
}

function remove_from_wishlist(product_id) {
    $.post("/mywishlist/remove/", { product_id: product_id }, function(data) {
        eval("var ret=" + data);
        if (ret.ret == 1) {
            alert(ret.msg);
        }
    });
}