IMVU.ProductJSParsed = false;
    
IMVU.ProductPurchaseService = new function() {
    var self = this;
    
    this.cn = null;
    
    this.purchaseEvent = new YAHOO.util.CustomEvent("purchase", this);
    this.addToCartEvent = new YAHOO.util.CustomEvent("addToCart", this);
    this.addToWishlistEvent = new YAHOO.util.CustomEvent("addToWishlist", this);

    this.init = function() {
        this.initializeDialogs();
        this.inProgress = false;
    };
    
    this.setCreditValues = function(credits, fredits) {
        var credits_element = YAHOO.util.Dom.get("credits_real_value");
        if (credits_element) credits_element.innerHTML = credits;
        
        var fredits_element = YAHOO.util.Dom.get("credits_promo_value");
        if (fredits_element) fredits_element.innerHTML = fredits;
    };
    
    this.initializeDialogs = function() {
        // Need to make sure that the markup is present prior to creating this dialog
        YAHOO.util.Event.onAvailable(["shopConfirm", "cartDialog"], function() {
            self.confirmBuyDialog = new YAHOO.widget.Dialog("shopConfirm", { width:"350px",
                                                                             zIndex: 10000,
                                                                             modal:true, 
                                                                             draggable:false,
                                                                             fixedcenter:true,
                                                                             close:true,
                                                                             visible:false,
                                                                             monitorresize:false } );                 
            self.confirmBuyDialog.showMaskEvent.unsubscribeAll();          
            self.confirmBuyDialog.hideMaskEvent.unsubscribeAll();
        
            self.confirmAddToCartDialog = new YAHOO.widget.Dialog("cartDialog", { width:"350px",
                                                                                  zIndex: 10000,
                                                                                  modal:true, 
                                                                                  draggable:false,
                                                                                  fixedcenter:true,
                                                                                  close:true,
                                                                                  visible:false,
                                                                                  monitorresize:false } );                
            self.confirmAddToCartDialog.showMaskEvent.unsubscribeAll();          
            self.confirmAddToCartDialog.hideMaskEvent.unsubscribeAll(); 
            
            self.confirmAddToCartDialog.showEvent.subscribe(function() {
                IMVU.ProductPurchaseService.cartDialogShown = true;
            });
            
            self.waitDialog = new YAHOO.widget.Dialog("waitDialog", { width:"250px", 
                                                                      draggable:false, 
                                                                      fixedcenter:true, 
                                                                      close:false } );    
            self.waitDialog.setHeader("Completing your purchase...");
            self.waitDialog.setBody("<img width=\"220\" height=\"19\" src=\"/common/img/loading.gif\"/>");                
            self.waitDialog.showMaskEvent.unsubscribeAll();          
            self.waitDialog.hideMaskEvent.unsubscribeAll(); 
               
            self.waitDialog.showEvent.subscribe(function() {
                IMVU.ProductPurchaseService.waitDialogShown = true;
            });
            self.waitDialog.hideEvent.subscribe(function() {
                IMVU.ProductPurchaseService.waitDialogHidden = true;
            });

            self.purchaseCompleteDialog = new YAHOO.widget.SimpleDialog("dlgShop", { text: "DialogText",
                                                                                     zIndex: 10000,
                                                                                     width: "300px",
                                                                                     fixedcenter: true,
                                                                                     draggable: false,
                                                                                     modal: true,
                                                                                     visible: false });                
            self.purchaseCompleteDialog.showMaskEvent.unsubscribeAll();          
            self.purchaseCompleteDialog.hideMaskEvent.unsubscribeAll();
        });
        
        YAHOO.util.Event.onAvailable("shopConfirm", function() {
            IMVU.ProductPurchaseService.shopConfirmReady = true;
        });
        YAHOO.util.Event.onAvailable("cartDialog", function() {
            IMVU.ProductPurchaseService.cartDialogReady = true;
        });     
    };
    
    this.handleFailure = function() {
        self.purchaseCompleteDialog.setHeader("An Error Has Occurred");
        self.purchaseCompleteDialog.cfg.queueProperty("text", "<h3>An error has occurred. Please wait a few moments, and then try again.</h3>");
        self.purchaseCompleteDialog.cfg.queueProperty("buttons", [{ text:"OK", handler: function() { this.hide(); } }] );
        self.purchaseCompleteDialog.render(document.body);
        self.purchaseCompleteDialog.show();
    };
    
    this.callbacks = {
        buy: { 
            success : function(o) {
                IMVU.ProductPurchaseService.inProgress = false;
                IMVU.Customer.thisPagePurchaseCallbackCount++;
                var responseObject = YAHOO.lang.JSON.parse(o.responseText);
                self.waitDialog.hide();
                
                switch (responseObject.status) {
                    case 1: // successful purchase

                        IMVU.Customer.updatePreference("InstantBuyConfirm", IMVU.Customer.InstantBuyConfirm);
                        IMVU.Customer.credits = responseObject.balance_credits;
                        IMVU.Customer.fredits = responseObject.balance_promo;
                    
                        YAHOO.util.Dom.addClass(responseObject.products, "in-inventory");
                        self.purchaseCompleteDialog.setHeader("Thank You For Your Purchase!");
                        self.purchaseCompleteDialog.cfg.queueProperty("text", "<img width=\"100\" height=\"80\" src=\"" + responseObject.image + "\"> <h3>You just purchased:<br/> " + responseObject.name + "!</h3> <p>Credits Spent: " + responseObject.total_f + "<br/>(" + responseObject.balance_total_f + " remaining)</p> <p class=\"shop-try\">To use your purchased item now, click <a href=\"imvu:PutOn?productId=" + responseObject.products + "\" onclick=\"IMVU.ProductPurchaseService.purchaseCompleteDialog.hide();\">here</a>!</p>");
                        self.purchaseCompleteDialog.cfg.queueProperty("buttons", [{ text:"OK", handler: function() { this.hide(); } }] );
                        self.purchaseCompleteDialog.render(document.body);
                        
                        self.purchaseCompleteDialog.center();
                        self.purchaseCompleteDialog.show(); 
                        
                        self.setCreditValues(responseObject.balance_credits_f, responseObject.balance_promo_f);
                        
                        YAHOO.util.Event.onAvailable(responseObject.products, function() {
                            // TODO: legacy widget code -- remove after new widget rollout
                            var productElement = YAHOO.util.Dom.get(responseObject.products);
                            
                            var buttons = YAHOO.util.Dom.getFirstChildBy(productElement, function(el) { if (el.className=="buttons" && el.tagName == "UL") return true; });
                            YAHOO.util.Dom.getElementsByClassName("icon-add-to-cart", "A", responseObject.products, function(el) { el.style.display="none"; });
                            YAHOO.util.Dom.getElementsByClassName("add_to_wishlist_link", "A", responseObject.products, function(el) { el.style.display="none"; });
                        
                            if (buttons) {
                                var alreadyOwnDiv = document.createElement("DIV");
                                alreadyOwnDiv.className="no-sales";
                                alreadyOwnDiv.innerHTML = "<span>You own this item.</span>";
                                buttons.parentNode.replaceChild(alreadyOwnDiv, buttons);
                            }
                            // remove legacy widget code
                        });
                        IMVU.ProductPurchaseService.purchaseEvent.fire();     
                        self.triggerClientInventoryRefresh();
                        if (typeof tracker != 'undefined') tracker._trackPageview('/events/catalog/conversion');
                        break;
                        
                    case 2: // not enough credits
                    
                        self.purchaseCompleteDialog.setHeader("Refill Your Credits?");
                        self.purchaseCompleteDialog.cfg.queueProperty("text", "<img width=\"100\" height=\"80\" src=\"/accountcatalog/images/c_credits.gif\"> <h3>You don't have enough credits to make this purchase.</h3> <p>Total Needed: " + responseObject.total_f + "<br/>(You currently have " + responseObject.balance_total_f + " credits.)</p> <p class=\"shop-try\"><a href=\"/store/store_us.php\" onclick=\"self.purchaseCompleteDialog.hide();\">Get more IMVU credits now!</a></p>");
                        self.purchaseCompleteDialog.cfg.queueProperty("buttons", [{ text:"Buy Credits!", handler: function() { window.location.href = "/store/store_us.php"; }, isDefault: true },
                                                                                  { text:"Cancel", handler: function() { this.hide(); } }] );
                        self.purchaseCompleteDialog.render(document.body);
                        self.purchaseCompleteDialog.show();
    
                        YAHOO.util.Dom.get("credits_real_value").innerHTML = responseObject.balance_credits_f;
                        YAHOO.util.Dom.get("credits_promo_value").innerHTML = responseObject.balance_promo_f;
                        
                        break;
                        
                    case 0: // not logged in
                    
                        self.purchaseCompleteDialog.setHeader("Not Currently Logged In");
                        self.purchaseCompleteDialog.cfg.queueProperty("text", "<h3>You are not currently logged in to IMVU. You may have been logged out.</h3> <p><a href=\"/catalog/login.php\">Click here to login again.</a></p>");
                        self.purchaseCompleteDialog.cfg.queueProperty("buttons", [{ text:"Login", handler: function() { window.location.href = "/catalog/login.php"; }, isDefault: true}] );
                        self.purchaseCompleteDialog.render(document.body);
                        self.purchaseCompleteDialog.show();
                        
                        break;
                }
                
            }, 
            
            failure : function(o) {
                IMVU.ProductPurchaseService.inProgress = false;
                self.waitDialog.hide();
                self.handleFailure();
            }
            
        },
        
        addToCart : { 
            success : function(o) {
                IMVU.ProductPurchaseService.inProgress = false;
                var responseObject = YAHOO.lang.JSON.parse(o.responseText);
                self.waitDialog.hide();
                
                IMVU.Customer.updatePreference("InstantBuyCartConfirm", IMVU.Customer.InstantBuyCartConfirm);
                        
                var cart_link = YAHOO.util.Dom.get("cart_link");
                
                if (responseObject.status == 1) {
                    if (cart_link) {
                        if (responseObject.item_count == 0) {
                            cart_link.title = "Shopping Cart (empty)";
                            YAHOO.util.Dom.removeClass("cart_link", "full");
                            YAHOO.util.Dom.addClass("cart_link", "empty");
                        } else if (responseObject.item_count == 1) {
                            cart_link.title = "Shopping Cart (1 item)";
                            YAHOO.util.Dom.removeClass("cart_link", "empty");
                            YAHOO.util.Dom.addClass("cart_link", "full");
                        } else {
                            cart_link.title = "Shopping Cart (" + responseObject.item_count + " items)";
                            YAHOO.util.Dom.removeClass("cart_link", "empty");
                            YAHOO.util.Dom.addClass("cart_link", "full");
                        }
                    }
                    IMVU.ProductPurchaseService.addToCartEvent.fire(responseObject);
                }
            }, 
            failure : function(o) {
                IMVU.ProductPurchaseService.inProgress = false;
                self.waitDialog.hide();
                self.handleFailure();
            }
        },

        addToWishlist : { 
            success : function(o) {
                IMVU.ProductPurchaseService.inProgress = false;
                var responseObject = YAHOO.lang.JSON.parse(o.responseText);
                setTimeout(function() {
                    self.waitDialog.hide();
                    if (responseObject.message == 'wishlist_full') {
                        self.purchaseCompleteDialog.setHeader("Wishlist Full");
                        self.purchaseCompleteDialog.cfg.queueProperty("text", "Your wishlist is full. To add more items to your wishlist, first remove some.");
                        self.purchaseCompleteDialog.cfg.queueProperty("buttons", [{ text:"OK", handler: function() { this.hide(); }, isDefault: true}] );
                        self.purchaseCompleteDialog.render(document.body);
                        self.purchaseCompleteDialog.show();
                    } else if (responseObject.message == 'exists') {
                        self.purchaseCompleteDialog.setHeader("Item Already in Wishlist");
                        self.purchaseCompleteDialog.cfg.queueProperty("text", "This item is already in your wishlist.");
                        self.purchaseCompleteDialog.cfg.queueProperty("buttons", [{ text:"OK", handler: function() { this.hide(); }, isDefault: true}] );
                        self.purchaseCompleteDialog.render(document.body);
                        self.purchaseCompleteDialog.show();
                    } else {
                        var wishlist_count = YAHOO.util.Dom.get("wishlist_count");
                        if (wishlist_count) {
                            wishlist_count.innerHTML = parseInt(wishlist_count.innerHTML) + 1;
                        }
                    }
                    self.addToWishlistEvent.fire(o);
                }, 500);
            },
            failure : function(o) {
                IMVU.ProductPurchaseService.inProgress = false;
                self.waitDialog.hide();
                self.handleFailure();
            }
        }
        
    };
    
    /* Buy Functions */
    
    
    this.buy = function(pid, price, name, img, trackingId, warning) {
        var buttonContainer = YAHOO.util.Dom.get("instant_get_button_" + pid);
        if (buttonContainer) {
            buttonContainer.style.visibility = "hidden";
        }
        
        YAHOO.util.Event.purgeElement("btn_purchase");
        YAHOO.util.Event.purgeElement("btn_cancel");
        
        var doPurchase = function() {
            if (IMVU.ProductPurchaseService.inProgress) return;
            self.waitDialog.setHeader("Completing your purchase...");
            self.waitDialog.render(document.body);
            self.waitDialog.show();

            var postPairs = ['products=' + pid];
            postPairs.push('trackingId=' + trackingId);
            if (typeof IMVU.CatalogController != 'undefined') {
                if (IMVU.CatalogController.activeRequest) {
                    if (IMVU.CatalogController.activeRequest.search) {
                        postPairs.push('search=' + IMVU.CatalogController.activeRequest.search);
                    }
                    if (IMVU.CatalogController.activeRequest.category) {
                        postPairs.push('category=' + IMVU.CatalogController.activeRequest.category);
                    }
                }
            }
            
            var postBody = postPairs.join('&');
            self.cn = YAHOO.util.Connect.asyncRequest('POST', '/api/service/shop/svc_catalog_purchase.php', self.callbacks.buy, postBody);
            IMVU.ProductPurchaseService.inProgress = true;
            IMVU.Customer.thisPagePurchaseCount++;
        };
        
        var clickPurchase = function() {
            self.confirmBuyDialog.hide();
            IMVU.Customer.InstantBuyConfirm = (YAHOO.util.Dom.get("cb_confirm").checked ? 0 : 1);
            doPurchase();
        };
        
        var clickCancel = function() {
            buttonContainer.style.visibility = "visible";
            IMVU.Customer.InstantBuyConfirm = (YAHOO.util.Dom.get("cb_confirm").checked ? 0 : 1);
            IMVU.Customer.updatePreference("InstantBuyConfirm", IMVU.Customer.InstantBuyConfirm);
            self.confirmBuyDialog.hide();
        };
        
        var showConfirmBuyDialog = function() {
            YAHOO.util.Event.onAvailable(["shopConfirm", "cartDialog"], function() {
                YAHOO.util.Dom.get("confirm_name").innerHTML = name;
                YAHOO.util.Dom.get("confirm_price").innerHTML = price;
                
                if (IMVU.discount) {
                    var newPrice = parseInt(price * (1 - parseFloat(IMVU.discount)));
                    var discountAmount = parseInt(price * parseFloat(IMVU.discount));
                    
                    YAHOO.util.Dom.addClass(["shopConfirm", "cartDialog"], "discounted");
                    YAHOO.util.Dom.get("confirm_discount").innerHTML = newPrice;
                    YAHOO.util.Dom.get("confirm_discount_amount").innerHTML = discountAmount;
                }
                
                YAHOO.util.Dom.get("confirm_img").src = img;
                YAHOO.util.Dom.get("confirm_balance").innerHTML = (IMVU.Customer.credits + IMVU.Customer.fredits);
                
                YAHOO.util.Dom.get("cb_confirm").checked = (! IMVU.Customer.InstantBuyConfirm);
                
                if (warning == 1) {
                    YAHOO.util.Dom.get("audio_warning").innerHTML = "Any audio in this product will be limited to 20 seconds.";
                }
            
                YAHOO.util.Event.addListener("btn_purchase", "click", clickPurchase);
                YAHOO.util.Event.addListener("btn_cancel", "click", clickCancel);   
    
                self.confirmBuyDialog.innerElement.style.display = "block";
                
                self.confirmBuyDialog.render(document.body);
                self.confirmBuyDialog.center();
                self.confirmBuyDialog.show();
            });
        };
        
        if (IMVU.Customer.InstantBuyConfirm) {
            showConfirmBuyDialog();
        } else {
            doPurchase();
        }
    };
    
    
    /* Add to Cart Functions */
    
    this.addToCart = function(pid, price, name, img) {
        var doAddToCart = function() {
            if (IMVU.ProductPurchaseService.inProgress) return;
            self.waitDialog.setHeader("Adding to your cart...");
            self.waitDialog.render(document.body);
            self.waitDialog.show();
            self.cn = YAHOO.util.Connect.asyncRequest('POST', '/api/service/shop/svc_cart.php', self.callbacks.addToCart, 'products=' + pid);
            IMVU.ProductPurchaseService.inProgress = true;
        };
         
        var clickAdd = function() {
            self.confirmAddToCartDialog.hide();
            IMVU.Customer.InstantBuyCartConfirm = (YAHOO.util.Dom.get("cb_cart_confirm").checked ? 0 : 1);
            doAddToCart();
        };
        
        var clickCancel = function() {
            IMVU.Customer.InstantBuyCartConfirm = (YAHOO.util.Dom.get("cb_cart_confirm").checked ? 0 : 1);
            //console.log("Clicked cancel... IMVU.Customer.InstantBuyCartConfirm: " + IMVU.Customer.InstantBuyCartConfirm);
            self.confirmAddToCartDialog.hide();
            IMVU.Customer.updatePreference("InstantBuyCartConfirm", IMVU.Customer.InstantBuyCartConfirm);
        };
               
        var showConfirmAddToCartDialog = function() {
            YAHOO.util.Event.purgeElement("btn_dlg_add");
            YAHOO.util.Event.purgeElement("btn_dlg_add_cancel");
        
            YAHOO.util.Event.addListener("btn_dlg_add", "click", clickAdd);
            YAHOO.util.Event.addListener("btn_dlg_add_cancel", "click", clickCancel);   
        
            self.confirmAddToCartDialog.innerElement.style.display = "block";
            self.confirmAddToCartDialog.render(document.body);
            self.confirmAddToCartDialog.show();
        };
        
        //console.log("add to cart confirm pref: " + IMVU.Customer.InstantBuyCartConfirm);
        
        if (IMVU.Customer.InstantBuyCartConfirm) {
            YAHOO.util.Dom.get("cart_name").innerHTML = name;
            YAHOO.util.Dom.get("cart_price").innerHTML = price;
            
            if (IMVU.discount) {
                var newPrice = parseInt(price * (1 - parseFloat(IMVU.discount)));
                var discountAmount = parseInt(price * parseFloat(IMVU.discount));
                
                YAHOO.util.Dom.addClass("cartDialog", "discounted");
                YAHOO.util.Dom.get("cart_discount").innerHTML = newPrice;
                YAHOO.util.Dom.get("cart_discount_amount").innerHTML = discountAmount;
            }
                
            YAHOO.util.Dom.get("cart_img").src = img;
            YAHOO.util.Dom.get("cart_balance").innerHTML = (IMVU.Customer.credits + IMVU.Customer.fredits);
            YAHOO.util.Dom.get("cb_cart_confirm").checked = (! IMVU.Customer.InstantBuyCartConfirm);
            showConfirmAddToCartDialog();
        } else {
            doAddToCart();
        }
            
    };
    
    /* Add to Wishlist Functions */
    
    this.addToWishlist = function(pid) {
        if (IMVU.ProductPurchaseService.inProgress) return;
        this.waitDialog.setHeader("Adding to your wishlist...");
        this.waitDialog.render(document.body);
        this.waitDialog.show();
        this.cn = YAHOO.util.Connect.asyncRequest('POST', '/api/service/wishlist/wishlist.php', this.callbacks.addToWishlist, 'action=add&pid=' + pid);
        IMVU.ProductPurchaseService.inProgress = true;
    };
    
    /* Inventory Refresh */
    
    this.triggerClientInventoryRefresh = function() {
        var frameUrl = '/filebox/web_inventory_refresh.swf';
        var frameId = 'web_inventory_refresh_swf';

        var frame = YAHOO.util.Dom.get(frameId);
        if (frame) {
            frame.src = frameUrl + '?r=' + Math.random();
        } else {
            frame = document.createElement('IFRAME');
            frame.id = frameId; 
            frame.width = 30;
            frame.height = 30;
            document.body.insertBefore(frame, document.body.firstChild);
            frame.src = frameUrl;
        }
    };
    
}();

YAHOO.util.Event.onDOMReady(function() {
    IMVU.ProductPurchaseService.init();
});

IMVU.ProductJSParsed = true;
