/**
 * Agence Soon
 *
 * NOTICE OF LICENSE
 *
 *
 * @copyright  Copyright (c) 2010 Agence Soon (http://www.agence-soon.fr)
 * @author Hervé Guétin (herve.guetin@gmail.com)
 */

/* Fix validation W3C pour AutosearchComplete */
function w3cFix() {
    var html = '<div class="search-autocomplete" id="myContainer" style="top:' + (posSC.top + $('myInput').getHeight() + 3) +'px; left:' + posSC.left + 'px"></div>';
    document.body.appendChild(div_to_replace);
    
    return html;
}

$j(document).ready(function($) {
    
    $('html, body').animate({scrollTop:0}, 0);

    /* Popin informations */
    $('a#popin_informations_trigger').fancybox({
        'padding': 0,
        'overlayColor' : '#000'
    });
    $('a#popin_informations_trigger').trigger('click');

    /* Alertes nouveautés (Newproductsalert) */
    $('#newproductsalert_subscribe_container').hide();
    $('a#newproductsalert_trigger').fancybox({
        'padding': 0,
        'autoDimensions': false,
        'width': 380,
        'height': 190,
        'scrolling'   : 'no',        
        'overlayColor' : '#000'
    });
    $('#newproductsalert_errors').css('visibility', 'hidden');
    var submitNewProductsAlert = function() {
        //var url = $('#domain_url').attr('value') + 'newproductsalert/index/subscribe/email/' + $('#newproductsalert').attr('value');
        var url = '/newproductsalert/index/subscribe/email/' + $('#newproductsalert').attr('value');
        $.ajax({
            url: url,
            success: function(data) {
                if($(data).find(':input').length != 0) {
                    $('#newproductsalert_errors').html(data);
                    $('#newproductsalert_errors').css('visibility', 'visible');
                }
                else {
                    $('#newproductsalert_subscribe').html(data);
                }

            }
        });
    }
    $('#submit_newproductsalert').click(function() {
        submitNewProductsAlert();
    })
    
    /* Newsletter // Voir aussi js/soon/newsletterajax.js */
    $('.block-subscribe').hide();
    $('#newsletter_trigger, #newsletter_close').click(function() {
        $('.block-subscribe').slideToggle('fast');
        $('.header .friends-referral').toggle();
    })

    /* Mini cart */
    $('#cart_items').hide();
    $('#cart_items_trigger').click(function() {
        $('#cart_items').slideToggle('fast');
    })

    /* Top Navigation // Megadropdown */
    var ie7Fix = 300; /* Valeur arbitraire fixée empiriquement */
    
    var getColumns = function (storeId) {
        var storeColumnAssoc = new Array(0, 4, 4, 4, 2, 2, 2); // l'index correspond au store id
        return storeColumnAssoc[storeId];
        
    }
    
    var generateMegadropdown = function() {
        $('#megadropdown .subdiv').each(function() {
            if($(this).height() > $('.subdiv-container').height() + ie7Fix) {
                $(this).columnize({
                    columns : getColumns($('#megadropdown #store_id').attr('value')),
                    lastNeverTallest : true
                });
                /* On change la marge du premier titre */
                $('#megadropdown .column').each(function() {
                    $(this).find('.level1:first').css('margin-top', '10px');
                })
            }
            else {
                $(this).css('float', 'left').css('margin-right', '15px');
                /* On change la marge du premier titre */
                $(this).find('.level1:first').css('margin-top', '10px');
            }
        })

        /* On déplace le block CMS après la dernière colonne */
        $('#megadropdown .subdiv-container').each(function() {
            $('#' + $(this).attr('id') + ' .subdiv .last').after($('#' + $(this).attr('id') + ' .subdiv-cms'));
        })

        $('#megadropdown ul.level0').css('position', 'absolute').css('z-index', '100');
        $('.megadropdown-container').css('visibility', 'visible');

        $('#megadropdown > li > ul').hide();
        $('#megadropdown > li').hover(
            function() {
                $('#megadropdown ul.level0').css('visibility', 'visible');
                $('#megadropdown > li > ul').hide();
                $(this).children('ul').show();
                
			/* On déplace le dropdown pour certaines catégories */
			$('#megadropdown .init-level').each(function() {
				var liLeftPosition = $(this).parent().position().left;
				var levelWidth = $(this).width();
				console.log(liLeftPosition + '//' + levelWidth);
				if(levelWidth < liLeftPosition) {
					$(this).css('left', liLeftPosition);
				}
			});                   
                
            },
            function() {
                $(this).children('ul').delay(100).fadeOut(150);
            }
            );

        $('#megadropdown li.level1 a').hover(
            function() {
                $(this).addClass('over');
            /*Cufon.replace($(this), {
                fontFamily: 'ArialBold'
            });*/
            
            },
            function() {
                $(this).removeClass('over');
            /*Cufon.replace($(this), {
                fontFamily: 'ArialBold'
            });*/
            });       
    }
    generateMegadropdown();

    /* Home */
    if($('#home_new_count').attr('value') > 4) {
        $('.home-new').scrollable({
            'speed': 1000,
            'circular': true
        });        
    }
    if($('#home_bestsellers_count').attr('value') > 4) {
        $('.home-bestsellers').scrollable({
            'speed': 1000,
            'circular': true
        });        
    }

    var switchHomeList = function(el) {
        var containerId = $(el).attr('id').split('_')[1];
        $('.home-list-container').hide().removeClass('active');
        $('.home-list-title').removeClass('active');
        $('#home_' + containerId + '_container').show().addClass('active');
        $('#home_' + containerId + '_title').addClass('active');
        Cufon.replace('.home-list-title h3', {
            fontFamily: 'ArialBold'
        });
    }

    var switchHomeListTitle = function(el, status) {
        var containerId = $(el).attr('id').split('_')[1];
        $('.home-list-title').removeClass('active');
        if(status == true) {
            $('#home_' + containerId + '_title').addClass('active');
        }
        $('#home_' + $('.home-list-container.active').attr('id').split('_')[1] + '_title').addClass('active');
        Cufon.replace('.home-list-title h3', {
            fontFamily: 'ArialBold'
        });
    }

    var initHomeLists = function() {
        if($('.home-list-title').size() > 1) {
            $('.home-list-title:last').insertBefore('.home-list-title:first')
        }
        $('<div class="home-list-titles"></div>').insertBefore('.home-list-title:first');
        $('.home-list-title').each(function() {
            $(this).appendTo('.home-list-titles');
        })
        $('.home-list-title:last').addClass('last');
        switchHomeList($('.home-list-title:first'));
    }

    if($('.home-list-title').size() > 0) {
        initHomeLists();
    }

    $('.home-list-title').click(function() {
        switchHomeList($(this));
    })

    $('.home-list-title').hover(function() {
        switchHomeListTitle($(this), true);
    },
    function() {
        switchHomeListTitle($(this), false);
    })



    /* Catégories */
    $('.big-image-product').hide();
    $('.available-sizes-container').hide();
    $('.available-sizes').css({
        opacity: 0.9
    });
    $('.product-trigger').hover(function() {
        var currentId = $(this).attr('id').split('_')[3];
        $('#big_image_category').stop(true, true).fadeOut();
        $('#big_image_product_' + currentId).stop(true, true).fadeIn();

        $('.available-sizes-container').hide();
        $('#available_sizes_' + currentId).show();


        $(this).mousemove(function(e) {
            $('#available_sizes_' + currentId).css('left', e.clientX + 20).css('top', e.clientY + 20);
        })
    },
    function() {
        $('.big-image-product').stop(true, true).delay(500).fadeOut();
        $('#big_image_category').stop(true, true).fadeIn();

        $('.available-sizes-container').hide();
    }
    );

    $('#description_details').hide();
    $('#description_details_trigger').click(function() {
        $('#description_details').slideToggle();
    })
    
    $('.products-grid .price-percent').each(function() {
        var top = $(this).parent().parent().find('.image-container').outerHeight() - 40 + 'px'; // 40 = 30px de hauteur du block + 10px de marge de l'image
        var percentHtml = '<span>' + $('.price', this).html() + '</span>';
        $(this).css('top', top);
        $(this).append(percentHtml);
        $('.price', this).remove();
    })

    /* Alertes produits */
    var displayProductAlert = function(url) {
        $.ajax({
            url: url,
            success: function(data) {
                $('#productalert_container').html(data);
            }
        });
    }
    $('.productalert-subscribe-trigger').click(function() {
        var url = $(this).attr('href');
        displayProductAlert(url);
    })
    
    $('.productalert-subscribe-trigger').fancybox({
        'padding': 0,
        'overlayColor' : '#000',
        'onComplete' : function() {
            Cufon.replace('.productalert-subscribe h3', {
                fontFamily: 'GeorgiaBoldItalic'
            });
        }
    });

    /* Options produits */
    $('.product-options dd').hide();
    var liIdArray, productOptionInfo = new Array();
    var getProductOptionInfo = function(el) {
        liIdArray = el.split('-');
        productOptionInfo['attribute'] = liIdArray[1];
        productOptionInfo['optionIndex'] = liIdArray[2];
        return productOptionInfo;
    }
    $('.associated-products-options .available').click(function() {
        var productOptionInfo = getProductOptionInfo($(this).attr('id'));
        document.getElementById(productOptionInfo['attribute']).selectedIndex = productOptionInfo['optionIndex'];
        if($(this).hasClass('option-active')) {
            document.getElementById(productOptionInfo['attribute']).selectedIndex = 0;
            $('.associated-products-options .option').removeClass('option-active').addClass('option-inactive');
            return;
        }
        $('.associated-products-options .option').removeClass('option-active').addClass('option-inactive');
        $(this).removeClass('option-inactive').addClass('option-active');
    })

    $('.associated-products-options li.option').tooltip({
        onShow: function() {
            $('.fulfillment-arrow').show();
        }
    });
    $('.associated-products-options .option').hover(function() {
        var position = $(this).position();
        $('.fulfillment-arrow').css('left', position.left + 10);
        $('.fulfillment-available .fulfillment-content').css('left', position.left);
    })

    /* Guide des tailles */
    $('#size_chart_container').hide();
    $('a.size_chart_trigger').fancybox({
        'padding': 0,
        'overlayColor' : '#000'
    });

    /* Switch addThis */
    var switchAddThis = function() {
        var addthisImg = $('#addthis_image').attr('value');
        $('.product-view .addthis img').attr('src', addthisImg);
    }
    switchAddThis();

    /* More views thumbs */
    $('.moreviews-thumb').click(function() {
        $('.moreviews-thumb').removeClass('thumb-active').addClass('thumb-inactive');
        $(this).removeClass('thumb-inactive').addClass('thumb-active');
    })
    $('#thumb_1').removeClass('thumb-inactive').addClass('thumb-active');

    /* Video
     *
     * --> On cache le bouton video au survol du zoom pour éviter le mouseout
     * Chercher videoTriggerShow et videoTriggerHide dans js/mogalupa/mogazoom/cloud-zoom.1.0.2.min.js
     *
     * */
    var srcImg = $('#video_img').attr('value');
    var hoverImg = $('#video_hover_img').attr('value');
    $('.video-trigger').hover(function() {
        $('.video-trigger img').attr('src', hoverImg);
    },
    function() {
        $('.video-trigger img').attr('src', srcImg);
    })
    
    $('#video_container').hide();
    $('a#video_trigger').fancybox({
        'padding': 0,
        'overlayColor' : '#000'
    });

    /* Dernier produit ajouté au panier (Last Cart Product) */
    $('.last-cart-product-container, a#last_cart_product_trigger').hide();
    $('a#last_cart_product_trigger').fancybox({
        'padding': 0,
        'overlayColor' : '#000'
    });
    $('a#last_cart_product_trigger').trigger('click');

    if($('.last-cart-product #is_bundle').size() > 0) { // On cache le prix pour les silhouettes car le prix est 0.00€
        $('.last-cart-product .price-box').hide();
    }

    /* Silhouettes */
    $('.looks-list .price-from .title').hover(function() {
        $(this).addClass('over');
        Cufon.replace($(this), {
            fontFamily: 'GeorgiaBoldItalic'
        });
    },
    function() {
        $(this).removeClass('over');
        Cufon.replace($(this), {
            fontFamily: 'GeorgiaBoldItalic'
        });
    })

    $('.looks-list, .looks-carousel').scrollable({
        'speed': 2000
    });

    var liSelectionIdArray, selectionOptionInfo = new Array();
    var getSelectionOptionInfo = function(el) {
        liSelectionIdArray = el.split('-');
        selectionOptionInfo['bundleOption'] = liSelectionIdArray[3];
        selectionOptionInfo['optionIndex'] = liSelectionIdArray[4];
        return selectionOptionInfo;
    }

    var reloadPriceBundle = function(el) {
        bundle.changeSelection(el); // cf. skin/frontend/base/default/js/bundle.js
    }
    
    var checkBundlePrice = function() {
        var optionsCount = $('.bundle-selection-container').size();
        var selectedOptionsCount = $('.option-active').size();
        if(optionsCount == selectedOptionsCount && $('#bundle_price_flag').html() == 1) {
            return true;
        }
        else {
            return false;
        }
        
    }

    $('.bundle-products-options .available').click(function() {
        var productOptionInfo = getSelectionOptionInfo($(this).attr('id'));
        document.getElementById('bundle-option-' + productOptionInfo['bundleOption']).selectedIndex = productOptionInfo['optionIndex'];
        document.getElementById('bundle-option-' + productOptionInfo['bundleOption'] + '-qty-input').value = 1;
        /*document.getElementById('checkbox-bundle-option-' + productOptionInfo['bundleOption']).checked = 1;
        document.getElementById('checkbox-bundle-option-' + productOptionInfo['bundleOption']).disabled = false;*/
        if($(this).hasClass('option-active')) {
            document.getElementById('bundle-option-' + productOptionInfo['bundleOption']).selectedIndex = 0;
            $('#bundle-products-options-' + productOptionInfo['bundleOption'] + ' .option').removeClass('option-active').addClass('option-inactive');
            if(checkBundlePrice() == true) {
                $('.price-box').hide();                
                $('.price-box.price-bundle').show();
            }
            else {
                $('.price-box').show();                
                $('.price-box.price-bundle').hide();
            }
            reloadPriceBundle(document.getElementById('bundle-option-' + productOptionInfo['bundleOption']));
            Cufon.replace('.price-box', {
                fontFamily: 'GeorgiaBoldItalic'
            });
            return;
        }
        $('#bundle-products-options-' + productOptionInfo['bundleOption'] + ' .option').removeClass('option-active').addClass('option-inactive');
        $(this).removeClass('option-inactive').addClass('option-active');
        if(checkBundlePrice() == true) {
            $('.price-box').hide();            
            $('.price-box.price-bundle').show();
        }
        else {
            $('.price-box').show();            
            $('.price-box.price-bundle').hide();
        }
        
        reloadPriceBundle(document.getElementById('bundle-option-' + productOptionInfo['bundleOption']));
        Cufon.replace('.price-box', {
            fontFamily: 'GeorgiaBoldItalic'
        });
    })

    /*$('.bundle-option-checkbox').click(function () {
        var productOptionInfo = getSelectionOptionInfo($(this).attr('id'));
        document.getElementById('bundle-option-' + productOptionInfo['bundleOption']).selectedIndex = 0;
        document.getElementById('bundle-option-' + productOptionInfo['bundleOption'] + '-qty-input').value = 0;
        document.getElementById('checkbox-bundle-option-' + productOptionInfo['bundleOption']).disabled = true;
        $('#bundle-products-options-' + productOptionInfo['bundleOption'] + ' .option').removeClass('option-active').addClass('option-inactive');
        reloadPriceBundle(document.getElementById('bundle-option-' + productOptionInfo['bundleOption']));
        Cufon.replace('.price-box', {
            fontFamily: 'GeorgiaBoldItalic'
        });
    })*/

    $('.bundle-product .product-shop .additional').appendTo('.product-img-box');

    /* Cart */
    var isCustomerBalanceChecked = false;
    if($('#cart_use_customer_balance').attr('checked') == true) {
        isCustomerBalanceChecked = true;
    }

    $('#cart_use_customer_balance').click(function() {
        var removeCreditUrl = $('#remove_credit_url').val();
        var applyCreditUrl = $('#apply_credit_url').val();
        var action = applyCreditUrl;
        if(isCustomerBalanceChecked == true) {
            action = removeCreditUrl;
        }
        window.location.href = action;
    })

    var inputData = function(el) {
        var inputData = new Array();
        inputData['input_id'] = 'cart_qty_' + $(el).attr('id').split('_')[2];
        inputData['current_value'] = Number($('#' + inputData['input_id']).val());
        return inputData;
    }
    $('.cart-table .qty-inc').click(function() {
        var el = inputData($(this));
        $('#' + el.input_id).val(el.current_value + 1);
    })
    $('.cart-table .qty-dec').click(function() {
        var el = inputData($(this));
        if(el.current_value > 1) {
            $('#' + el.input_id).val(el.current_value - 1);
        }
    })

    $('a#cart_loyalty_trigger').fancybox({
        'padding': 0,
        'overlayColor' : '#000'
    });    


    /* Cufonizer */
    var cufonizer = function() {

        var arial = new Array('a.level-top', /*'li.level1 a', */'.block-title', '.block-sibling-cat a', '.last-cart-product .title', '.cart .cart-collaterals .left span.title', '.home-list-title', '.cms-home .weekly-look .discover');
        for(i=0;i<arial.length;i++) {
            $(arial[i]).addClass('cufonized').addClass('arialbold');
        }

        var georgiabolditalic = new Array('.block-viewed .price', '.products-grid .price', '.product-view .product-name h1', '.product-view .price', '.product-view .short-description', '.btn-cart', '.size-advice', '.last-cart-product .price', '.price-from .title', '.price-from .price', '.bundle-product .product-options h3', '.cart-table .td-subtotal', '.cart .totals table .tr-grandtotal .amount', '.cart .totals table .tr-grandtotal-incltaxes .amount', '.cart .block-crosssell .price', '.home-list .price', '.account-login h2', '.my-account .box-account .box-head h2', '.my-account .box-account .box-title h3', '.my-account .amount', '.my-wishlist .price', '.cms-page-view .page-title h1');
        for(i=0;i<georgiabolditalic.length;i++) {
            $(georgiabolditalic[i]).addClass('cufonized').addClass('georgiabolditalic');
        }

        Cufon.now();
        Cufon.replace('.arialbold', {
            fontFamily: 'ArialBold'
        });
        Cufon.replace('.georgiabolditalic', {
            fontFamily: 'GeorgiaBoldItalic'
        });
    }
    cufonizer();
})

