window.addEvent('domready',add_events);

function add_events()
{

    $('id_zone_achat_shipment_info').style.display = 'none';
    $('id_zone_achat_option').style.display = 'block';
    $('id_zone_achat_rassurance').style.display = 'block';
    //$('detail_model_description').style.height = '160px';

    var to_hide = $$('.hide_when_js');
    to_hide.each( function(elmt){
        elmt.style.display="none";
    } );

    var to_display = $$('.hide_when_no_js');
    to_display.each( function(elmt){
        elmt.style.display="block";
    } );

    $('_hidden_article_id').disabled;

    $('cart_add').addEvent( 'submit' , ajax_submit_cart.bindWithEvent($('cart_add')) );

    if($('id_btn_remove_quantity') && $('id_btn_add_quantity'))
    {
        $('id_btn_remove_quantity').addEvent('click', removeOneQuantity.bindWithEvent($('id_btn_remove_quantity')));
        $('id_btn_add_quantity').addEvent('click', addOneQuantity.bindWithEvent($('id_btn_add_quantity')));
    }

    info_maintenance();

    new Tips($$('.maintenance_icone'));

    $$('.article_color_choice').each( function(elmt){
            elmt.addEvent('click',update_article.bindWithEvent(elmt));
    } );

    $$('.article_color_choice_not_available').each( function(elmt){
            elmt.addEvent('click',update_article.bindWithEvent(elmt));
    } );

    $$('.filter_quantity').each( function(elmt){
            elmt.addEvent('click', function(e) {
                e = new Event(e);
                e.preventDefault();
                filter_quantity(e.target);    
            });
    } );
    // initialize with the one with 'hlsize' class
    if($$('.hlsize').length != 0) {
        filter_quantity($$('.hlsize')[0]);
    }
    
    $$('.filter_quantity_not_available').each( function(elmt){
            elmt.addEvent('click', function(e) {
                e = new Event(e);
                e.preventDefault();
                filter_quantity_not_available(e.target);
            });
    } );

    $$('.switch_image').each( function(elmt){
        //elmt.addEvent('click', changeImage.bindWithEvent(elmt));
        elmt.addEvent('click', update_article_from_thumb.bindWithEvent(elmt));
    } );

    $('id_first_tab_zone_achat').addEvent('click', switch_tab_zone_achat.bindWithEvent($('id_first_tab_zone_achat')));
    $('id_second_tab_zone_achat').addEvent('click', switch_tab_zone_achat.bindWithEvent($('id_second_tab_zone_achat')));

    if ($('detail_model_description') && $('detail_model_description').getSize().scrollSize.y > 160)
    {
        $('read-whole-description').setText('Lire la suite…');
        $('read-whole-description').addEvent('click', show_text.bindWithEvent($('read-whole-description')));
    }

    $$('.bottom_tab').each( function(elmt){
            elmt.addEvent('click',switch_bottom_tabs.bindWithEvent(elmt));
    } );

    // sliders
    slider_af83();
}

function slider_af83() {

    if($('slider_items_thumbs'))
    {
        var sliderPhoto = new sliderAF83(
                'slider_items_thumbs',
                'horizontal',
                {
                    previousButton:'previous_items_thumbs',
                    nextButton:'next_items_thumbs',
                    itemClassName:'switch_image',
                    nbItems:4,
                    unitSize:67
        });
        
        var selected = $$('#slider_items_thumbs .highlight-thumb')[0];
        var data = Json.evaluate(selected.getAttribute('rel'));
        sliderPhoto.goToPosition(data.position);
    }

    var sliderOtherCreator = new sliderAF83(
            'slider_items_other_creator',
            'horizontal',
            {
                previousButton:'previous_items_other_creator',
                nextButton:'next_items_other_creator',
                itemClassName:'item_other_creator',
                nbItems:4,
                unitSize:180
    });

    var sliderOtherLike = new sliderAF83(
            'slider_items_other_like',
            'horizontal',
            {
                previousButton:'previous_items_other_like',
                nextButton:'next_items_other_like',
                itemClassName:'item_other_like',
                nbItems:4,
                unitSize:180
    });

}
/*
function hide_text(e)
{
    $('detail_model_description').style.height = '160px';
}
*/

function show_text(e)
{
    e = new Event(e);
    $('detail_model_description').style.height = 'auto';
	$('detail_model_description').style.maxHeight = '400px';
    $('container-read-whole-description').style.display = 'none';
    e.preventDefault();
}

function switch_bottom_tabs(e)
{
    var reg = new RegExp("[_]+", "g");
    e = new Event(e);
    var href = e.target.getAttribute('href');
    var arr_href = href.split(reg);
    var tabs = new Array();
    tabs[0] = '1';
    tabs[1] = '2';
    tabs[2] = '3';
    tabs[3] = '4';

    var choice = $(e.target);

    $('bottom_tab_' + arr_href[4]).addClass('bottom_tab_current');
    $('id_zone_bottom_header').getElements('li')[arr_href[4] -1].addClass('current_tab');
    $('id_zone_bottom_tabs_' + arr_href[4]).style.display = 'block';

    for(t = 0; t <= 3; t++)
    {
        if(arr_href[4] != tabs[t])
        {
            $('bottom_tab_' + tabs[t]).removeClass('bottom_tab_current');
            $('id_zone_bottom_header').getElements('li')[tabs[t] - 1].removeClass('current_tab');
            $('id_zone_bottom_tabs_' + tabs[t]).style.display = 'none';
        }
    }


    e.preventDefault();
}

function info_maintenance()
{
    var icone_set = $$('.maintenance_icone');
    var html = '<ul>';

    icone_set.each(function(e)
            {
            html = html + '<li>' + e.getAttribute('alt').charAt(0).toUpperCase() + e.getAttribute('alt').substr(1).toLowerCase() + '</li>';
            }
            );
    html= html + '</ul>';

    icone_set.each(function(e){e.setAttribute('title','Conseils d’entretien::'+html)});
}

function ajax_submit_cart(e)
{
    if($$('.filter_quantity').length == 1)
    {
        var reg = new RegExp("[_]+", "g");
        var id_str = $$('.filter_quantity')[0].id;
        var stock_id = id_str.split(reg)[1];

        $('id_stock_id').setProperty('value', stock_id);
    }

    if(this.stock_id.value != '')
    {
        var Expression = new RegExp("^((http://)?[^/]*)(.*)$");
        var old_action = this.action;
        var matches = Expression.exec(this.action);
        this.action = matches[1]+"/ajax"+matches[3];

        this.send({
            onComplete: go_to_cart
        });
        /*
        this.action = old_action;
        var shop=e.target.shop_id.value;
        var html = "Article ajouté à votre panier<br /><a href='/cart/' class='grownlBigButton'>Commander</a><br /><a href='/shop/"+shop+"' class='grownlButton'>Continuer mes achats</a><br /><br />";
        myGrowl = Growl.Bezel({
        	title: '',
        	text: html,
        	image: '/images/growl/ajax_loader_shop.gif',
        	duration: null
        });
        */
    }
    else
    {

        myGrowl = Growl.Bezel({
        	title: '',
        	text: 'Merci de choisir une taille',
        	image: '/images/growl/ajax_loader_warning.gif',
        	duration: 2
        });
    }

    return correctSubmitHandler(e);
}

function go_to_cart()
{
    window.location = "/cart/show";
}

function update_minicart()
{
    url = "/ajax/cart/minicart/";
    var myAjax = new Ajax(url, {
        method: 'get',
        update: $('shopping_cart_full'),
        evalScripts: true
    }).request();
}

function filter_quantity_not_available(elmt)
{
    elmt.target.style.outline = 'none';
}

function filter_quantity(elmt)
{
    var limit = 5;
    var reg = new RegExp("[_]+", "g");
    
    var id = elmt.getAttribute('id');
    var arr_q = id.split(reg);
    $('id_stock_id').value = arr_q[1];
    var quantity = arr_q[2];
    $$('.filter_quantity').each(function(elmt){elmt.removeClass('hlsize')});
    elmt.addClass('hlsize');
    (quantity < 5) ? limit = quantity : limit = 5;
    if($('id_max_quantity')) {
        $('id_max_quantity').value = limit;
    }

    if(quantity == 0) {
        $('display_stock').innerHTML = '<span class="stock_label">Stock&nbsp;: <span id="status_stock">épuisé</span></span>';
        $('id_zone_achat_datail_quantite').style.display = "none";
        return;
    }

    if(quantity > 3)
        {
            $('display_stock').innerHTML = '<span class="stock_label">Stock&nbsp;: <span id="status_stock">' + quantity + ' pièces</span></span>';
        }
        else if(quantity > 0 && quantity <= 3)
            {
                // <span class="stock_label_warn">Stock&nbsp;: <span id="status_stock">plus que 1 pièce</span></span> Vite, j’en profite&nbsp;!
                if(quantity == 1)
                    {
                        $('display_stock').innerHTML = '<span class="stock_label_warn">Stock&nbsp;: <span id="status_stock">plus que 1 pièce</span></span> Vite, j’en profite&nbsp;!';
                        if($('quantity_only_one'))
                            {
                                $('quantity_only_one').style.display = 'block';
                            }
/*
if($('id_quantity'))
{
$('id_quantity').style.display = 'none';
                $('id_btn_remove_quantity').style.visibility = 'hidden';
                $('id_btn_add_quantity').style.visibility = 'hidden';
            }*/
        }
        else
        {
            $('display_stock').innerHTML = '<span class="stock_label_warn">Stock&nbsp;: <span id="status_stock">plus que ' + quantity + ' pièces</span></span> Vite, j’en profite&nbsp;!';
            if($('quantity_only_one'))
            {
                $('quantity_only_one').style.display = 'none';
            }
            if($('id_quantity')) {
                $('id_quantity').style.display = 'block';
            }
            if($('id_btn_add_quantity')) {
                $('id_btn_add_quantity').style.visibility = 'visible';
            }
        }
    }

}

function update_article(e)
{
    container = $('detail_model');
    var reg = new RegExp("[_]+", "g");
    e = new Event(e);
    var id = e.target.getAttribute('id');
    var arr_id = id.split(reg);
    var article_id = arr_id[3];

    var selected_img = 1;

    var switch_image = $$('.switch_image');
    for(var i = 0; i < switch_image.length; i++)
    {
            if(switch_image[i].getProperty('rel') == 'show_article_' + article_id)
            {
                selected_img = switch_image[i].id.split(reg)[2];
                break;
            }
    }

    url = "/ajax/model/detail/" + $('_model_id').value +"/?article_id="+article_id + '&selected_img=' + selected_img;
    var myAjax = new Ajax(url, {
        method: 'get',
        update: container ,
        evalScripts: true,
        onComplete: function(){
            add_events();
            home_rassurance_check_tool_tips();
            /*alternate_slider();*/
            MOOdalBox.init();
            Slimbox.scanPage();
        }
    });
    myAjax.request();
    e.preventDefault();
}

function update_article_from_thumb(e)
{
    container = $('detail_model');
    var reg = new RegExp("[_]+", "g");
    e = new Event(e);
    
    var data = Json.evaluate(e.target.getAttribute('rel'));

    url = "/ajax/model/detail/" + $('_model_id').value +"/?article_id="+data.article_id +'&selected_img=' + data.image_key;
    var myAjax = new Ajax(url, {
        method: 'get',
        update: container ,
        evalScripts: true,
        onComplete: function(){
            add_events();
            home_rassurance_check_tool_tips()
            /*alternate_slider();*/
            MOOdalBox.init();
            Slimbox.scanPage();
        }
    });
    myAjax.request();
    e.preventDefault();
}

function switch_tab_zone_achat(e)
{
    e = new Event(e);
    var tab_id = e.target.getAttribute('id');

    var first  = $('id_first_tab_zone_achat');
    var second = $('id_second_tab_zone_achat');

    if(tab_id == 'id_first_tab_zone_achat')
    {
        first.addClass('achat_tab_current');
        $('id_zone_tabs_achat').getElements('li')[0].addClass('current_tab');
        $('id_zone_tabs_achat').getElements('li')[0].removeClass('current_tab_no');
        second.removeClass('achat_tab_current');
        $('id_zone_tabs_achat').getElements('li')[1].removeClass('current_tab');
        $('id_zone_tabs_achat').getElements('li')[1].addClass('current_tab_no');
        $('id_zone_achat_shipment_info').style.display = 'none';
        $('id_zone_achat_option').style.display = 'block';
        $('id_zone_achat_rassurance').style.display = 'block';
    }
    else
    {
        first.removeClass('achat_tab_current');
        $('id_zone_tabs_achat').getElements('li')[0].removeClass('current_tab');
        $('id_zone_tabs_achat').getElements('li')[0].addClass('current_tab_no');
        second.addClass('achat_tab_current');
        $('id_zone_tabs_achat').getElements('li')[1].addClass('current_tab');
        $('id_zone_tabs_achat').getElements('li')[1].removeClass('current_tab_no');
        $('id_zone_achat_shipment_info').style.display = 'block';
        $('id_zone_achat_option').style.display = 'none';
        $('id_zone_achat_rassurance').style.display = 'none';
    }

    e.preventDefault();
}
function changeImage(e)
{
    var visible_photo = $$('.visible_photo');
    var visible_zoom  = $$('.visible_zoom');

    visible_photo.each( function(elmt){
        elmt.className = 'hidden_photo';
    } );

    visible_zoom.each( function(elmt){
        elmt.className = 'hidden_zoom';
    } );

    var Expression = new RegExp("^thumb_img_([1-9]*)$");
    var matches = Expression.exec(this.id);
    $('big_img_'+matches[1]).className = 'visible_photo';

    var set_thumbs = $$('.switch_image');
    set_thumbs.each( function(elmt){
        elmt.removeClass('highlight-thumb');
    } );
    if($('thumb_img_'+matches[1])) {
        $('thumb_img_'+matches[1]).addClass('highlight-thumb');
    }
    if($('image_label_zoom_'+matches[1])) {
        $('image_label_zoom_'+matches[1]).className = 'visible_zoom';
    }
    return correctSubmitHandler(e);
}

function addOneQuantity()
{
    send_qty = $('send_quantity');
    q = $('id_quantity');

    if(parseInt(q.value) < getMaxQuantity() && parseInt(q.value) + 1 != getMaxQuantity())
    {
        q.value = parseInt(q.value) + 1;
    }
    else
    {
        q.value = getMaxQuantity();
    }
    send_qty.value = q.value;
    hideShowBtnQuantity(q.value);
}

function removeOneQuantity()
{
    q = $('id_quantity');

    if(parseInt(q.value) > 1)
    {
        q.value = parseInt(q.value) - 1;
    }
    else
    {
        q.value = 1;
    }

    hideShowBtnQuantity(q.value);
}

function hideShowBtnQuantity(newValue)
{
    if(getMaxQuantity() == 1)
    {
        document.getElementById('id_btn_add_quantity').style.visibility = 'hidden';
        document.getElementById('id_btn_remove_quantity').style.visibility = 'hidden';
    }
    else
    {
        if(newValue < getMaxQuantity() && newValue > 1)
        {
            document.getElementById('id_btn_remove_quantity').style.visibility = 'visible';
            document.getElementById('id_btn_add_quantity').style.visibility = 'visible';
        }
        else
        {
            if(newValue == getMaxQuantity())
            {
                document.getElementById('id_btn_remove_quantity').style.visibility = 'visible';
                document.getElementById('id_btn_add_quantity').style.visibility = 'hidden';
            }

            if(newValue == 1)
            {
                document.getElementById('id_btn_remove_quantity').style.visibility = 'hidden';
                document.getElementById('id_btn_add_quantity').style.visibility = 'visible';
            }
        }
    }
}

function getMaxQuantity()
{
    return parseInt(document.getElementById('id_max_quantity').value);
}


