

var ajaxCartExist = typeof(ajaxCart) != 'undefined'; 

var giftlistAjaxCart = {};


ajaxCart.prototype = ajaxCart;

var ajaxCartOverrideButtonsInThePage = ajaxCart.overrideButtonsInThePage;

ajaxCart.prototype.overrideButtonsInThePage = function(){
    //for every 'add' buttons...
    
    if(typeof(overrideGiftListButtonsInThePage) != 'undefined') overrideGiftListButtonsInThePage();
    ajaxCartOverrideButtonsInThePage(); 
    //for product page 'add' button...
    //$('body#giftlist_product p#add_to_cart').attr('id', 'giftlist_add_to_cart'); 
    $('body#giftlist_product p#add_to_cart input').unbind('click').click(function(){
        ajaxCart.addToGiftlist($('#product_page_product_id').val(), $('#product_page_giftlist_product_id').val(), $('#idCombination').val(), true, null, $('#quantity_wanted').val(), null);
        return false;
    }); 
   
    if(typeof(giftlist_products) != 'undefined' && giftlist_products.length > 0){
        $('body#giftlist .ajax_add_to_cart_button').each(function(index){
                var idProduct =  $(this).attr('rel').replace('ajax_id_product_', ''); 
                for ( var i in giftlist_products){ 
                    if(parseInt(idProduct) == giftlist_products[i]['id_product'] && !giftlist_products[i]['done'] ){
                        giftlist_products[i]['done'] = true;
                        $(this).attr('href',$(this).attr('href')+'&id_giftlist_product='+giftlist_products[i]['id_giftlist_product']+'&id_product_attribute='+giftlist_products[i]['id_product_attribute']);
                        $(this).attr('rel_giftlist',giftlist_products[i]['id_giftlist_product']).attr('rel_giftlist_attribute',giftlist_products[i]['id_product_attribute']);
                        break;
                    }    
                }    
        }).unbind('click').click(function(){
            var idProduct =  $(this).attr('rel').replace('ajax_id_product_', '');
            var idGiftlistProduct =  $(this).attr('rel_giftlist').replace('ajax_id_giftlist_product_', '');
            var idCombinaison = $(this).attr('rel_giftlist_attribute').replace('ajax_id_giftlist_product_attribute_', '');
            ajaxCart.addToGiftlist(idProduct,idGiftlistProduct, idCombinaison, false, this);
            return false;
        });
    }     
         
    
        
    
};

ajaxCart.prototype.addToGiftlist = function(idProduct,idGiftlistProduct , idCombination, addedFromProductPage, callerElement, quantity, whishlist){
        if (addedFromProductPage && !checkCustomizations())
        {
            alert(fieldRequired);
            return ;
        }
        //disabled the button when adding to do not double add if user double click
        if (addedFromProductPage)
        {
            $('body#giftlist_product p#add_to_cart input').attr('disabled', 'disabled').removeClass('exclusive').addClass('exclusive_disabled');
            $('.filled').removeClass('filled');
        }
        else
            $('.ajax_add_to_cart_button').attr('disabled', 'disabled');
        
        if ($('#cart_block #cart_block_list').hasClass('collapsed'))
            this.expand();
        //send the ajax request to the server
        $.ajax({
            type: 'POST',
            url: baseDir + 'cart.php',
            async: true,
            cache: false,
            dataType : "json",
            data: 'add=1&ajax=true&qty=' + ((quantity && quantity != null) ? quantity : '1') + '&id_product=' + idProduct + '&id_giftlist_product='+idGiftlistProduct+'&token=' + static_token + ( (parseInt(idCombination) && idCombination != null) ? '&ipa=' + parseInt(idCombination): ''),
            success: function(jsonData)
            {
                // add appliance to whishlist module
                if (whishlist && !jsonData.errors)
                    WishlistAddProductCart(whishlist[0], idProduct, idCombination, whishlist[1]);
                    
                // add the picture to the cart
                var $element = $(callerElement).parent().parent().find('a.product_image img,a.product_img_link img');
                if (!$element.length)
                    $element = $('#bigpic');
                var $picture = $element.clone();
                var pictureOffsetOriginal = $element.offset();
                $picture.css({'position': 'absolute', 'top': pictureOffsetOriginal.top, 'left': pictureOffsetOriginal.left});
                var pictureOffset = $picture.offset();
                var cartBlockOffset = $('#cart_block').offset();

                $picture.appendTo('body');
                $picture.css({ 'position': 'absolute', 'top': $picture.css('top'), 'left': $picture.css('left') });
                
                $picture.animate({ 'width': $element.attr('width')*0.66, 'height': $element.attr('height')*0.66, 'opacity': 0.2, 'top': cartBlockOffset.top + 30, 'left': cartBlockOffset.left + 15 }, 1000).fadeOut(100, function() {
                    ajaxCart.updateCart(jsonData);
                    //reactive the button when adding has finished
                    if (addedFromProductPage)
                        $('body#giftlist_product p#add_to_cart input').removeAttr('disabled').addClass('exclusive').removeClass('exclusive_disabled');
                    else
                        $('.ajax_add_to_cart_button').removeAttr('disabled'); 
                });                 
               // });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) 
            {
                alert("TECHNICAL ERROR: unable to add the product.\n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
                //reactive the button when adding has finished
                if (addedFromProductPage)
                    $('body#giftlist_product p#add_to_cart input').removeAttr('disabled').addClass('exclusive').removeClass('exclusive_disabled');
                else
                    $('.ajax_add_to_cart_button').removeAttr('disabled');
            }
        });
    };
    
ajaxCart.prototype.hideOldProducts = function(jsonData) {
        //delete an eventually removed product of the displayed cart (only if cart is not empty!)
        if($('#cart_block #cart_block_list dl.products').length > 0)
        {
            var removedProductIds = Array();
            var removedProductId = null;
            var removedProductData = null;
            var removedProductDomId = null;
            //look for a product to delete...
            $('#cart_block_list dl.products dt').each(function(){
                //retrieve idProduct and idCombination from the displayed product in the block cart
                var domIdProduct = $(this).attr('id');
                var firstCut =  domIdProduct.replace('cart_block_product_', '');
                var ids = firstCut.split('_');

                //try to know if the current product is still in the new list
                var stayInTheCart = false;
                for (aProduct in jsonData.products)
                {
                    //we've called the variable aProduct because IE6 bug if this variable is called product
                    //if product has attributes
                    if (jsonData.products[aProduct]['id'] == ids[0] && (!ids[1] || jsonData.products[aProduct]['idCombination'] == ids[1]))
                    {
                        stayInTheCart = true;
                        // update the product customization display (when the product is still in the cart)
                        ajaxCart.hideOldProductCustomizations(jsonData.products[aProduct], domIdProduct);
                    }
                }
                //remove product if it's no more in the cart
                if(!stayInTheCart)
                {
                    removedProductIds.push($(this).attr('id'));
                    //return false; // Regarding that the customer can only remove products one by one, we break the loop
                }
            });
            
            //if there is removed products, delete them from the displayed block cart
            if (removedProductIds.length > 0 )
            {
                for ( var i=0, len=removedProductIds.length; i<len; ++i ){
                    removedProductId = removedProductIds[i];
                
                    var firstCut =  removedProductId.replace('cart_block_product_', '');
                    var ids = firstCut.split('_');

                    $('#'+removedProductId).addClass('strike').fadeTo('slow', 0, function(){
                        $(this).slideUp('slow', function(){
                            $(this).remove();
                            //if the cart is now empty, show the 'no product in the cart' message
                            if($('#cart_block dl.products dt').length == 0)
                            {
                                $('p#cart_block_no_products:hidden').slideDown('fast');
                                $('div#cart_block dl.products').remove();
                            }
                        });
                    });
                    $('dd#cart_block_combination_of_' + ids[0] + (ids[1] ? '_'+ids[1] : '') ).fadeTo('fast', 0, function(){
                        $(this).slideUp('fast', function(){
                            $(this).remove();
                        });
                    });
                }
            }
            
        }
    };    

   

//when document is loaded...
$(document).ready(function(){

   
   
   
    if($('body#order input#addressesAreEquals') != null && typeof(isDeliveredToListOwner) != 'undefined' && isDeliveredToListOwner){ 
        
        //remove delivery choice tags and set hidden inputs for forum submit
        $('input#addressesAreEquals').parent().html('');         
        $('p.address_delivery').html('<input type="checkbox" id="addressesAreEquals" /><input type="hidden" name="id_address_delivery" value="'+deliveryToOwnerAdressId+'" /><select id="id_address_delivery"><option value="'+deliveryToOwnerAdressId+'"/></select>').hide(0);
        $('select#id_address_delivery').val(deliveryToOwnerAdressId);
        //display the invoice address choice
        $('p#address_invoice_form').show(0);
        
        //call the updateAddressesDisplay before removing the list owner delivery address
        updateAddressesDisplay();
        
        //hide the update link of the delivery address
        $('#address_delivery li.address_update').hide(0); 
        
        //remove the list owner delivery address from JS lists
        for (i in addresses)
        {
            if(i == deliveryToOwnerAdressId){
                delete addresses[i];
            }
        }
        //in version < 1.4.1.0, addresses_values doesn't exist
        if(typeof(addresses_values) != 'undefined')
        {    
            for (i in addresses_values)
            {
                if(i == deliveryToOwnerAdressId){
                    delete addresses_values[i];
                }
            }
        }
        
        //remove the list owner delivery address from the invoice select
        $("select#id_address_invoice option[value='"+deliveryToOwnerAdressId+"']").remove();
        updateAddressDisplay('invoice');
           
        //change the binding of change event from the invoice choice, need only to update the invoice address now   
        $('select#id_address_invoice').attr('onchange','').bind('change',function(){
           updateAddressDisplay('invoice'); 
        });
    } 
    
    
});









