var WORLDTECHCART = function($) {
    var _p = {
        params: null,
        value: '',
        mode: 1,
        init: function(params) {
            var defaults = {
                wishlistCSS: "wishlist",
                buyNowCSS: "buy",
                wishlistCSSSave: "wishlist_process",
                wishlistCSSExists: "wishlisted",
                submitSendCSS: "Button",
                findSubmitInside: "orderform",
                findWishlistInside: "content",
                findUpdateCartInside: "cart",
                updateID: "updatecart",
                updateStatusID: "process_cart",
                checkDeleteID: "ChkProductDel",
                checkDeleteSelectCSS: "highlight",
                txtboxQtyID: "TxtQty",
                txtboxQtyCSS: "ProductQTY",
                txtboxQtyMaxLength: 5,
                cartName: "clientCart",
                timeoutAddCart: 1000,
                timeoutUpdateStatus: 2000,
                cookieDomain: ""
            }
            //.4bcrm.com
            _p.params = $.extend(defaults, params);
            _p.setupEvent();
            _p.setupQuantity();
        },

        setupEvent: function() {
            //Wish list button click event
            var wishList = $("a." + _p.params.wishlistCSS, $("#" + _p.params.findWishlistInside));
            wishList.each(function() {
                $(this).click(function() {
                    var obj = $(this);
                    var PID = parseInt(obj.attr("id").split("_").slice(-1));
                    if (!_p.isExist(PID)) {
                        //Remove all event
                        obj.unbind();

                        //Change CSS Status
                        obj.removeClass().addClass(_p.params.wishlistCSSSave);

                        //Delay For Display Save Status and Call Function Save to Cart
                        /*setTimeout(function() {
                            _p.addCart(PID);
                            //Change CSS Status
                            obj.removeClass().addClass(_p.params.wishlistCSSExists);
                        }, _p.params.timeoutAddCart);*/

                        //Call Function Save to Cart
                        _p.addCart(PID);

                        //Change CSS Status
                        obj.removeClass().addClass(_p.params.wishlistCSSExists);
                    }

                    return false;
                });
            });

            //Buy Now Button Click Event
            var buyNow = $("a." + _p.params.buyNowCSS, $("#" + _p.params.findWishlistInside));
            buyNow.each(function() {
                $(this).click(function() {
                    var objBuy = $(this);
                    var objW = objBuy.prev();
                    var PID = parseInt(objW.attr("id").split("_").slice(-1));
                    if (!_p.isExist(PID)) {
                        //Remove all event
                        objBuy.unbind();
                        objW.unbind();

                        //Save to Cart
                        _p.addCart(PID);
                    }

                    return true;
                });
            });

            //Update cart button click event
            var BtnUpdate = $("#" + _p.params.updateID, $("#" + _p.params.findUpdateCartInside));
            BtnUpdate.click(function() {
                $("#" + _p.params.updateStatusID, $("#" + _p.params.findUpdateCartInside))
						.fadeIn('slow')
						.animate({ opacity: 1.0 }, _p.params.timeoutUpdateStatus)
						.fadeOut('slow');

                _p.updateCart(BtnUpdate);

                return false;
            });

            //Submit Button
            var submitBtn = $("a." + _p.params.submitSendCSS, $("#" + _p.params.findSubmitInside));
            submitBtn.click(function() {
                _p.updateSend();

                return true;
            });

            //Set product list selected css
            $("ul li:not(:first) input:checkbox[id*=" + _p.params.checkDeleteID + "]",
			$("#" + _p.params.findUpdateCartInside)).click(function() {
			    $(this).parent().parent().toggleClass(_p.params.checkDeleteSelectCSS)
			})
        },

        setupQuantity: function() {
            var txtQtys = $("input:text[id*=" + _p.params.txtboxQtyID + "]",
						  $("#" + _p.params.findUpdateCartInside));
            txtQtys.each(function() {
                var TextboxQTY = $(this);
                //Input number only
                TextboxQTY.removeClass()
				  .addClass(_p.params.txtboxQtyCSS)
				  .attr("maxlength", _p.params.txtboxQtyMaxLength)
				  .focus(function() {
				      TextboxQTY.select();
				  })
				  .keypress(function(e) {
				      if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
				          return false;
				      }
				  });
            });

            return false;
        },

        addCart: function(PID) {
            _p.value = PID + ":1";
            _p.mode = 1;
            _p.updateProducts();
        },

        updateCart: function(obj) {
            var totalProduct = 0;
            var currentVal = "";
            var products_list = $("ul li:not(:first)", $("#" + _p.params.findUpdateCartInside));
            products_list.each(function() {
                var listProduct = $(this);
                var chkDel = $("input:checkbox[id*=" + _p.params.checkDeleteID + "]", listProduct);
                var txtQty = $("input:text[id*=" + _p.params.txtboxQtyID + "]", listProduct);
                var txtQtyVal = parseFloat(txtQty.val());
                if (!txtQtyVal) txtQtyVal = 0;

                if (chkDel.is(":checked") || txtQtyVal == 0) {
                    listProduct.fadeOut('slow', function() {
                        listProduct.remove();
                    });
                } else {
                    txtQty.val(txtQtyVal);
                    currentVal = (currentVal == '') ? '' : currentVal + ',';
                    currentVal = currentVal + chkDel.val() + ":" + txtQtyVal;
                    totalProduct++;
                }
            });

            //Remove Button Update
            if (totalProduct == 0) {
                obj.fadeOut('slow', function() {
                    obj.remove();
                });
            }

            //Update value
            _p.value = currentVal;
            _p.mode = 2;
            _p.updateProducts();
        },

        updateSend: function() {
            var currentVal = "";
            var products_list = $("ul li:not(:first)", $("#" + _p.params.findUpdateCartInside));
            products_list.each(function() {
                var listProduct = $(this);
                var chkDel = $("input:checkbox[id*=" + _p.params.checkDeleteID + "]", listProduct);
                var txtQty = $("input:text[id*=" + _p.params.txtboxQtyID + "]", listProduct);
                var txtQtyVal = parseFloat(txtQty.val());
                if (!txtQtyVal) txtQtyVal = 0;

                if (txtQtyVal != 0) {
                    currentVal = (currentVal == '') ? '' : currentVal + ',';
                    currentVal = currentVal + chkDel.val() + ":" + txtQtyVal;
                }
            });

            //Update value
            _p.value = currentVal;
            _p.mode = 2;
            _p.updateProducts();
        },

        isExist: function(ItemID) {
            var ISexist = false;
            if (ItemID) {
                var cartVal = $.cookie(_p.params.cartName);
                if (cartVal) {
                    var products = cartVal.split(",");
                    $.each(products, function(index, val) {
                        ISexist = false;
                        if (val.split(":").slice(0, 1) == ItemID) {
                            ISexist = true;
                            return false; //break loop
                        }
                    });
                }
            }

            return ISexist;
        },

        updateProducts: function() {
            var currentVal = "";
            var CookieName = _p.params.cartName;
            switch (_p.mode) {
                case 1: //add new value
                    var cartVal = $.cookie(CookieName);
                    cartVal = (!cartVal) ? '' : cartVal + ',';
                    currentVal = cartVal + _p.value;
                    break;
                case 2: //update value
                    currentVal = _p.value;
                    break;
            }

            $.cookie(CookieName, currentVal, { expires: 1, path: '/', domain: _p.params.cookieDomain });
        }
    };
    return {
        init: function(params) {
            _p.init(params);
        }
    }
} (jQuery);
