function callTranslator(field, translator_command) {
    var t = document.getElementById('id_' + field + '_it').value;
    t = escape(t);
    if (t.length > 2000) {
        var i = 0;
        while (t.length - i * 2000 > 2000) {
            var s = t.substr(i * 2000, 2000);
            if (i == 0) { window.open('/translate_it/firstpart/yahoo?txt=' + s, '_blank'); }
            else { window.open('/translate_it/part/yahoo?txt=' + s, '_blank'); }
            i++;
        }
        var s = t.substr(i * 2000, t.length - i * 2000);
        window.open('/translate_it/lastpart/' + translator_command + '?txt=' + s, '_blank');
    }
    else { window.open('/translate_it/full/' + translator_command + '?txt=' + t, '_blank'); }
}

function trim(s){
    return s.replace(/^\s+|\s+$/g,"");
} 


/* jquery */

function update_totals () {
    $("#cart_total_price").load('/get-cart-total-price/'); //ajax
    return true;
}

function update_menu_cart_list() {
    var language = $("#session_language").attr('value');
    if (!language) language = 'en';
    $("#mc_list").load('/get-menu-cart-html/' + language); //ajax
    return true;
}

function toggle_image(this_id) { // presente in product_box.html
    var thumbnail = $("#" + this_id).children(":first-child").attr('src');
    var type = this_id.split('_')[0]; // 'i' o 'ic'
    var id = this_id.split('_')[2];
    var n = $("#" + this_id + " span.thumbnail_n").html();
    var target = '';
    var el = $("#" + this_id);
    while (el.parent()) {
        el = el.parent();
        if (el.hasClass('pb_itemmodels')) {
            target = "#pb_photo_box_" + el.attr('id').replace('pb_itemmodels_', '');
            break;
        }
        if (el.hasClass('product_box')) {
            target = "#pb_photo_box_" + el.attr('id');
            break;
        }
    }
    //alert('this_id: ' + this_id + ' type: ' + type + ' id: ' + id + ' n: ' + n + ' target: ' + target + ' thumbnail: ' + thumbnail);
    $(".thumbnail_small").removeClass('thumbnail_small_active');
    if (type != "ic") {
        $("#" + this_id).addClass('thumbnail_small_active');
        $(target + " .photo").addClass('nodisplay');
        $(target + " .photo").removeClass('photo');
        $(target + " #pb_photo_" + id + "_" + n).addClass('photo');
        $(target + " #pb_photo_" + id + "_" + n).removeClass('nodisplay');
        
        if (!$(target).is(':visible')) { $(target).slideDown(200); }
    }
    //var thumbnail_n = parseInt($("#" + this_id).children(":first-child img").attr('alt').replace('thumbnail_', ''));
    //if (thumbnail_n >= 4) $('#product_list').scrollTo($(target), 300, {}); /* http://plugins.jquery.com/project/ScrollTo - scrolling al box foto */
}


function get_email_text() { // presente in product_box
    var text = '';
    var total_price = 0.0;
    var total_qty = 0;
    $(".mc_item_body").children(".mc_itemcode").each(
        function() {
            var code_item_id = $(this).attr('id').replace('mc_itemcode_', '');
            var code = code_item_id.split('_')[0];
            var item_id = code_item_id.split('_')[1];
            var item_name = $("#mc_item_header_bare_" + item_id + " a").html();
            var qty = parseInt(trim($("#mc_input_qty_" + code + "_" + item_id).attr('value')));
            var price = parseFloat(trim($("#mc_unit_price_" + code + "_" + item_id).html()).substring(4));
            text += item_name + " - " + code + " (" + qty + ")\n";
            total_price += qty * price;
            total_qty += qty;
        }
    );
    total_price = total_price.toFixed(2);
    return text;
}


function checkContainerOverflow(container, scroller, focus_container, focus_target, up_arrow, down_arrow) {
    // controlla se il contenuto del container va fuori
    var h = 0;
    var container_height = $(container).height();
    var inner_height = $(scroller).height();
    //alert('scroller: ' + scroller + ', inner_height: ' + inner_height + ', container: ' + container + ', container_height: ' + container_height);
    if(inner_height > container_height) {
        /* comparsa delle frecce di scroll */
        $(down_arrow).show();
    }
    return true;
}


function checkBoxesOverflow(container, scroller, focus_target) {
    // controlla se dentro al container ci sono box troppo grandi per essere visualizzati
    // in caso mette le barre di scrolling al container
    if (container.indexOf('#') != 0) container = '#' + container;
    if (scroller.indexOf('#') != 0) scroller = '#' + scroller;
    if (focus_target.indexOf('.') == 0) focus_target = focus_target.substr(1);
    var overflow = false;
    var container_height = $(container).height();
    var h = 0;
    var measured = ''; // debug
    $(scroller).children().each(
        function() {
            if ($(this).hasClass(focus_target)) {
                //alert(measured); // debug
                h = $(this).height();
                //measured = $(this).attr('id') + ': ' + h + ' + '; // debug
            }
            else {
                h += $(this).height();
                //measured += $(this).attr('id') + ': ' + h + ' + '; // debug
            }
            if (h > container_height) {
                overflow = true;
            }
        }
    );
    return overflow;
}


function scrollSeek(from, to, direction, container) {
    // scrolla in su o in giù finché non incontra l'elemento bersaglio o arriva in cima/fondo
    // from = elemento di focus corrente, to = classe destinazione, se omesso scroll fino in cima/fondo, direction <1 indietro >1 avanti
    var result = null;
    var h = 0;
    if (from.indexOf('#') == 0) from = from.substr(1);
    var next = $('#' + from);
    if (to.indexOf('.') == 0) to = to.substr(1);
    do {
        var el = next;
        if (direction <= 0) next = el.prev();
        else next = el.next();
        h += el.height();
        //alert('ID: ' + next.attr('id') + ' CLASS: ' + next.attr('class') + ' TO: ' + to + ' LENGTH: ' + next.length);
    } while (next.length > 0 && (el.attr('class') != to || el.attr('id') == from));
    if (el.attr('id') != from) {
        result = el.attr('id');
    }
    //alert('el ID: ' + el.attr('id') + ' el CLASS: ' + el.attr('class') + ' TO: ' + to + ' next LENGTH: ' + next.length + ' next ID: ' + next.attr('id') + ' RESULT: ' + result);
    return {element: result, height: h};
}


function noMoreScrolling(from, direction) {
    // controlla se esiste un prossimo elemento bersaglio, altrimenti siamo in cima/fondo
    if (from.indexOf('#') != 0) from = '#' + from;
    var el = $(from);
    if (direction > 0) next = el.prev();
    else next = el.next();
    if (next.length <= 0 || !next.attr('id')) return true;
    return false;
}


function scrollDown(container, scroller, focus_container, focus_target, up_arrow, down_arrow) {
    //alert('container: ' + container + ' scroller: ' + scroller + ' focus_container: ' + focus_container  + ' focus_target: ' +  focus_target + ' up_arrow: ' + up_arrow + ' down_arrow: ' + down_arrow);
    $(up_arrow).show();
    var focus_on = $(focus_container).html();
    var last = $(scroller + " " + focus_target + ":last").attr('id');
    if (focus_on != last) {
        var s = scrollSeek(focus_on, focus_target, 1, focus_container);
        var el = s.element;
        var h = s.height;
        var container_height = $(container).height();
        //alert('FOCUS_ON:' + focus_on + ', LAST:' + last + ', GOING TO: ' + el + ' H: ' + h + ' CONTAINER_HEIGHT: ' + container_height);
        if (el) {
            var h = -1; // disabilito quasta funzione
            if (h > container_height) {
                $(container).scrollTo('+=' + container_height + 'px', 400, {axis:'y'});
            }
            else {
                var y = $('#' + el).offset().top; // misura la posizione verticale dell'elemento sotto focus, prima dello scrolling
                $(container).scrollTo($('#' + el), 400, {axis:'y', onAfter:function(){
                    // controlla se il box ha fisicamente scrollato in basso (confrontando la posizione di el prima dello scrolling con quella dopo lo scrolling), se no blocca lo scrolling perché non siamo sull'ultimo elemento ma siamo già in fondo allo scroller
                    if (y == $('#' + el).offset().top) {
                        scrollUp(container, scroller, focus_container, focus_target, up_arrow, down_arrow);
                        $(down_arrow).hide();
                    }
                } });
                focus_on = el;
                $(focus_container).html(focus_on);
            }
        }
        else $(down_arrow).hide();
    }
    if (focus_on == last) {
        $(down_arrow).hide();
    }
    return true;
}


function scrollUp(container, scroller, focus_container, focus_target, up_arrow, down_arrow) {
    $(down_arrow).show();
    var focus_on = $(focus_container).html();
    var first = $(scroller + " " + focus_target + ":first").attr('id');
    var s = scrollSeek(focus_on, focus_target, -1, focus_container);
    var el = s.element;
    var h = s.height;
    //alert('FOCUS_ON:' + focus_on + ', FIRST:' + first + ', GOING TO: ' + el);
    if (el) {
        $(container).scrollTo($('#' + el), 400, {axis:'y'});
        focus_on = el;
        $(focus_container).html(focus_on);
    }
    else $(up_arrow).hide();
    if (noMoreScrolling(focus_on, -1)) $(up_arrow).hide();
    return true;
}


function highlightButton(el) {
    var c = $(this).attr('class');
    $(this).addClass(c + '_hi');
    el.children(".tag_left").css('color', '#333');
    el.children(".tag_right").addClass('tag_right_hi');
    return true;
}


function deHighlightButton(el) {
    var c = $(this).attr('class');
    $(this).removeClass(c + '_hi');
    el.children(".tag_left").css('color', '#fff');
    el.children(".tag_right").removeClass('tag_right_hi');
    return true;
}



$(document).ready(function() {
    /* http://www.thefutureoftheweb.com/blog/detect-ie6-in-javascript */
    var is_ie6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
    var is_ie = /*@cc_on!@*/false;
    if (is_ie6) {
        var ext = 'gif';
    } else {
        var ext = 'png'; 
    }
    
    /* aggiornamento del menu cart in alto a sisnistra */
    update_menu_cart_list()
    
    $("#nav_language_it").hover(
        function() {
            $("#flag_icon_it").removeClass('flag_it');
            $("#flag_icon_it").addClass('flag_it_hi');
            $("#nav_language_it .text").addClass('text_hi');
        },
        function() {
            $("#flag_icon_it").removeClass('flag_it_hi');
            $("#flag_icon_it").addClass('flag_it');
            $("#nav_language_it .text").removeClass('text_hi');
    });
    $("#nav_language_en").hover(
        function() {
            $("#flag_icon_en").removeClass('flag_en');
            $("#flag_icon_en").addClass('flag_en_hi');
            $("#nav_language_en .text").addClass('text_hi');
        },
        function() {
            $("#flag_icon_en").removeClass('flag_en_hi');
            $("#flag_icon_en").addClass('flag_en');
            $("#nav_language_en .text").removeClass('text_hi');
    });
    /*
    $("#nav_language_it").livequery('click',
        function() {
            $("#nav_language_it .text").load('/change-language/it'); // ajax
            window.location.reload();
    });
    $("#nav_language_en").livequery('click',
        function() {
            $("#nav_language_en .text").load('/change-language/en'); // ajax
            window.location.reload();
    });
    */
    $("#nav_login").click(
        function() {
            if($("#login_box").is(':visible')) {
                $("#login_box").slideUp(200);
            } else {
                $("#login_box").slideDown(200);
            }
            
    });
    
    $("#input_login_username").keypress(
        function(event) {
            if (event.which == 13) {
                $("#login_form").submit();
            }
        }
    );
    $("#input_login_password").keypress(
        function(event) {
            if (event.which == 13) {
                $("#login_form").submit();
            }
        }
    );
    
    $(".mc_item_add").hover(
        function() { highlightButton($(this)); },
        function() { deHighlightButton($(this)); }
    );
    $(".mc_item_remove").hover(
        function() { highlightButton($(this)); },
        function() { deHighlightButton($(this)); }
    );
    $(".mc_item_cancel").hover(
        function() { highlightButton($(this)); },
        function() { deHighlightButton($(this)); }
    );
    $(".mc_item_proceed").hover(
        function() { highlightButton($(this)); },
        function() { deHighlightButton($(this)); }
    );
    $(".mc_item_accept").hover(
        function() { highlightButton($(this)); },
        function() { deHighlightButton($(this)); }
    );
    $(".mc_item_back").hover(
        function() { highlightButton($(this)); },
        function() { deHighlightButton($(this)); }
    );
    $(".mc_item_reset").hover(
        function() { highlightButton($(this)); },
        function() { deHighlightButton($(this)); }
    );
    $(".pb_item_add").hover(
        function() { highlightButton($(this)); },
        function() { deHighlightButton($(this)); }
    );
    $(".pb_item_remove").hover(
        function() { highlightButton($(this)); },
        function() { deHighlightButton($(this)); }
    );
    $(".mc_item_ops_buy_more").hover(
        function() { highlightButton($(this)); },
        function() { deHighlightButton($(this)); }
    );
    $(".mc_item_ops_delete").hover(
        function() { highlightButton($(this)); },
        function() { deHighlightButton($(this)); }
    );
    
    /* comparsa/scomparsa menu cart espanso */
    function toggle_menu_cart() {
        if ($("#armpit").hasClass('short_armpit')) {
            /* espandi */
            $(".content_element").hide();
            $("#frameleft").hide()
            //$("#menu_cart_frameleftshadow").hide()
            $("#armpit").addClass('long_armpit');
            $("#armpit").removeClass('short_armpit');
            $("#menu_cart_foot").addClass('long_foot');
            $("#menu_cart_foot").removeClass('short_foot');
            $("#menu_cart_container").addClass('long_container');
            $("#menu_cart_container").removeClass('short_container');
            $("#menu_cart_frameleftcorner").show();
            $(".cart_spacer").show();
            $("#cart_proceed").show();
            $("#menu_cart_extended").slideDown(400);
            $("#open_cart").hide();
            //$("#mc_closer").show();
        } else {
            /* contrai */
            //$("#mc_closer").hide();
            $("#menu_cart_extended").hide();
            $(".cart_spacer").hide();
            $("#cart_proceed").hide();
            $("#menu_cart_frameleftcorner").hide();
            $("#menu_cart_container").addClass('short_container');
            $("#menu_cart_container").removeClass('long_container');
            $("#menu_cart_foot").addClass('short_foot');
            $("#menu_cart_foot").removeClass('long_foot');
            $("#armpit").addClass('short_armpit');
            $("#armpit").removeClass('long_armpit');
            //$("#menu_cart_frameleftshadow").show()
            $("#frameleft").show();
            $(".content_element").slideDown(400);
            $("#open_cart").show();
        }
    }
    if ($("#shopping_cart").length <= 0) { /* se non siamo nella pagina shopping_cart (cioè #shopping_cart non esiste)*/
        $("#cart_icon").click(          /* consento l'apertura del menu cart */
            function() {
                toggle_menu_cart();
        });
        $("#cart_icon").hover(
            function() {
                $("#open_cart a").addClass("highlighted");
            },
            function() {
                $("#open_cart a").removeClass("highlighted");
        });
        $("#open_cart").click(
            function() {
                toggle_menu_cart();
        });
        $("#cart_spacer_1").click(
            function() {
                toggle_menu_cart();
        });
    }
    
    /* cart form submit */
    $("#cart_proceed").click(
        function() {
            // disabilito gli input con valore a 0 altrimenti il POST potrebbe essere troppo lungo
            $(".mc_input_qty").each(
                function() {
                if (parseInt($(this).attr('value')) == 0) $(this).attr('disabled', 'disabled');
            });
            $("#menu_cart_form").submit();
    });
    
    /* menu prodotti, espansione categorie */
    /*
    $(".cat_header").livequery('click',
        function() {
            var category = $(this).attr('id').replace('cat_header_', '');
            $(".cat").slideUp(200);
            if($("#cat_" + category).is(':visible')) {
                $("#cat_" + category).slideUp(200);
            } else {
                $("#product_list").html('<div class="page_loading"></div>');
                $("#cat_" + category).slideDown(200);
                var url = $(this).attr('name'); // chiamata ajax per riempire il box product_list con i prodotti relativi alla categoria cliccata
                $("#product_list").load('/get-category-product-boxes/' + url); // ajax
                //$(".product_list_cat").hide();
                //$("#product_list_cat_" + category).show();
            }
        }
    );
    */
    
    /* box prodotto, bottone aggiunta oggetto al carrello */
    function update_item(code, item_id, price, qty) {
        //alert('(update_item) code:' + code + ', item_id: ' + item_id + ', price: ' + price + ', qty: ' + qty);
        var total_price = price * qty;
        var language = $("#session_language").attr('value');
        $("#pb_item_qty_" + code + "_" + item_id).html(qty);
        $("#pb_cart_qty_" + code + "_" + item_id).html(qty);
        if (qty == 1) {
            if (language == 'it') $("#pb_item_text_" + code + "_" + item_id).html("oggetto");
            else $("#pb_item_text_" + code + "_" + item_id).html("item");
        }
        else {
            if (language == 'it') $("#pb_item_text_" + code + "_" + item_id).html("oggetti");
            else $("#pb_item_text_" + code + "_" + item_id).html("items");
        }
        var total_item_qty = 0; // numero di sottoprodotti che stanno sotto questo header
        var total_qty = update_totals(); // numero totale di sottoprodotti
        //alert('(update_item) code: ' + code + ', item_id: ' + item_id +  ', qty: ' + qty +  ', price: ' + price + ', total_item_qty: ' + total_item_qty,  ', total_qty: ' + total_qty );
        if (qty == 0) {
            $("#pb_item_remove_" + code + "_" + item_id).hide();
            $("#pb_item_resume_" + code + "_" + item_id).hide();
            if (total_qty == 0) {
                if($("#cart_icon").hasClass("cart_full")) {
                    $("#cart_icon").addClass("cart_empty");
                    $("#cart_icon").removeClass("cart_full");
                }
            } else {
                if($("#cart_icon").hasClass("cart_empty")) {
                    $("#cart_icon").addClass("cart_full");
                    $("#cart_icon").removeClass("cart_empty");
                }
            }
        } else {
            $("#pb_item_remove_" + code + "_" + item_id).show();
            $("#pb_item_resume_" + code + "_" + item_id).show();
            if($("#cart_icon").hasClass("cart_empty")) {
                $("#cart_icon").addClass("cart_full");
                $("#cart_icon").removeClass("cart_empty");
            }
        }
    }
    /* http://docs.jquery.com/Frequently_Asked_Questions#Why_do_my_events_stop_working_after_an_AJAX_request.3F */
    $(".pb_item_add").livequery('click',
        function() {
            var code_item_id = $(this).attr('id').replace('pb_item_add_', '');
            var code = code_item_id.split('_')[0];
            var item_id = code_item_id.split('_')[1];
            var price = parseFloat(trim($("#pb_price_" + code + "_" + item_id).html().replace('€ ', '')));
            var qty = parseInt($("#pb_cart_qty_" + code + "_" + item_id).html());
            if (!qty) qty = 0;
            qty++;
            //alert('(pb_item_add) code: ' + code + ', item_id: ' + item_id + ', qty: ' + qty +  ', price: ' + price);
            $("#cart_resume_right").html('<div class="cart_tag_loading"></div>');
            $("#cart_resume_right").load('/add-item/' + code + '/' + item_id); // ajax
            update_menu_cart_list();
            update_item(code, item_id, price, qty)
            update_totals();
        }
    );
    /* box prodotto, bottone rimozione oggetto dal carrello */
    $(".pb_item_remove").livequery('click',
        function() {
            var code_item_id = $(this).attr('id').replace('pb_item_remove_', '');
            var code = code_item_id.split('_')[0];
            var item_id = code_item_id.split('_')[1];
            var price = parseFloat(trim($("#pb_price_" + code + "_" + item_id).html()).replace('€ ', ''));
            var qty = parseInt($("#pb_cart_qty_" + code + "_" + item_id).html());
            if (!qty) qty = 0;
            qty--;
            if (qty < 0) qty = 0;
            //alert('(pb_item_remove) code: ' + code + ', item_id: ' + item_id + ', qty: ' + qty +  ', price: ' + price);
            $("#cart_resume_right").html('<img src="/kt_media/images/loading6.gif" alt="loading..." />');
            $("#cart_resume_right").load('/remove-item/' + code + '/' + item_id); // ajax
            update_menu_cart_list();
            update_item(code, item_id, price, qty)
            update_totals();
        }
    );
    /* menu carrello, aggiornamento totali, quando si preme enter nell'input o quando l'input perde il fuoco */
    $(".mc_input_qty").keypress(
        function(event) {
            if (event.which == 13) {
                var code_item_id = $(this).attr('id').replace('mc_input_qty_', '');
                var code = code_item_id.split('_')[0];
                var item_id = code_item_id.split('_')[1];
                var price = parseFloat(trim($("#mc_unit_price_" + code + "_" + item_id).html()).replace('x € ', ''));
                var qty = parseInt(trim($("#mc_input_qty_" + code + "_" + item_id).attr('value')));
                if (!qty) qty = 0;
                if (qty < 0) qty = 0;
                //alert('(mc_input_qty enter) code: ' + code + ', item_id: ' + item_id + ', qty: ' + qty +  ', price: ' + price);
                $("#cart_resume_right").html('<img src="/kt_media/images/loading6.gif" alt="loading..." />');
                $("#cart_resume_right").load('/update-item-qty/' + code + '/' + item_id + '/' + qty);
                update_item(code, item_id, price, qty)
                update_totals();
            }
        }
    );
    $(".mc_input_qty").blur(
        function() {
            var code_item_id = $(this).attr('id').replace('mc_input_qty_', '');
            var code = code_item_id.split('_')[0];
            var item_id = code_item_id.split('_')[1];
            var price = parseFloat(trim($("#mc_unit_price_" + code + "_" + item_id).html()).replace('x € ', ''));
            var qty = parseInt(trim($("#mc_input_qty_" + code + "_" + item_id).attr('value')));
            if (!qty) qty = 0;
            if (qty < 0) qty = 0;
            //alert('(mc_input_qty blur) code: ' + code + ', item_id: ' + item_id + ', qty: ' + qty +  ', price: ' + price);
            $("#cart_resume_right").load('/update-item-qty/' + code + '/' + item_id + '/' + qty);
            update_item(code, item_id, price, qty)
            update_totals();
        }
    );
    
    /* prodotto box, click thumbnails immagini, cambio foto */
    $(".thumbnail_small").click(
        function() {
            var id = $(this).attr('id');
            toggle_image(id);
        }
    );
    
    /* prodotto box, click immagine, apertura foto */
    /*$(".pb_photo_box .photo img").click(
        function() {
            var photo_path = $(this).attr('src');
            var i = photo_path.split("/").length;
            var photo_name = photo_path.split("/")[i-1]
            window.open('/image/' + photo_name, '_blank');
        }
    );*/
    
    /* shopping_cart, shopping_summary, buy more oggetto dal carrello */
    $(".mc_item_ops_buy_more").click(
        function() {
            $where = $(this).attr('name');
            window.open($where, '_self');
        }
    );
    /* shopping_cart, shopping_summary, delete oggetto dal carrello */
    $(".mc_item_ops_delete").click(
        function() {
            var code_item_id = $(this).attr('id').replace('mc_item_ops_delete_', '');
            var code = code_item_id.split('_')[0];
            var item_id = code_item_id.split('_')[1];
            $("#mc_item_ops_1_" + code + "_" + item_id).hide();
            $("#mc_item_ops_2_" + code + "_" + item_id).show();
        }
    );
    $(".confirm_delete").livequery('click',
        function() {
            var code_item_id = $(this).attr('id').replace('confirm_delete_', '');
            var code = code_item_id.split('_')[0];
            var item_id = code_item_id.split('_')[1];
            window.open('/shopping_cart/remove/' + item_id + '_' + code, '_self');
            /*
            $("#mc_item_ops_" + code + "_" + item_id).load('/update-item-qty/' + code + '/' + item_id + '/0');
            $("#mc_row_" + code + "_" + item_id).slideUp(100);
            //window.open('/shopping_cart/', '_self'); // non funziona bene con ajax
            */
        }
    );
    $(".no_confirm_delete").click(
        function() {
            var code_item_id = $(this).attr('id').replace('no_confirm_delete_', '');
            var code = code_item_id.split('_')[0];
            var item_id = code_item_id.split('_')[1];
            $("#mc_item_ops_2_" + code + "_" + item_id).hide();
            $("#mc_item_ops_1_" + code + "_" + item_id).show();
        }
    );
    
    /* shopping_cart bottoni conferma */
    $("#mc_item_back_confirm").click(
        function() {
            window.open('/products/', '_self');
        }
    );
    $("#mc_item_accept_confirm").click(
        function() {
            window.open('/shopping_cart/expedition_address/', '_self');
        }
    );
    function same_as_delivery_address() {
        if($("#same_as_delivery_address_chk").is(':checked')) {
            // importa dati da delivery address e disabilita campi
            $("#id_billing_first_name").attr('value', $("#id_delivery_first_name").attr('value'));
            $("#id_billing_first_name").attr('readonly', 'readonly');
            $("#id_billing_first_name").addClass('readonly');
            $("#id_billing_last_name").attr('value', $("#id_delivery_last_name").attr('value'));
            $("#id_billing_last_name").attr('readonly', 'readonly');
            $("#id_billing_last_name").addClass('readonly');
            $("#id_billing_address").attr('value', $("#id_delivery_address").attr('value'));
            $("#id_billing_address").attr('readonly', 'readonly');
            $("#id_billing_address").addClass('readonly');
            $("#id_billing_city").attr('value', $("#id_delivery_city").attr('value'));
            $("#id_billing_city").attr('readonly', 'readonly');
            $("#id_billing_city").addClass('readonly');
            $("#id_billing_postcode").attr('value', $("#id_delivery_postcode").attr('value'));
            $("#id_billing_postcode").attr('readonly', 'readonly');
            $("#id_billing_postcode").addClass('readonly');
            $("#id_billing_country").attr('value', $("#id_delivery_country").attr('value'));
            $("#id_billing_country").attr('readonly', 'readonly');
            $("#id_billing_country").addClass('readonly');
            $("#same_as_delivery_address_chk").attr('value', '1');
            return true;
        } else {
            // riabilita campi
            $("#id_billing_first_name").attr('readonly', '');
            $("#id_billing_first_name").removeClass('readonly');
            $("#id_billing_last_name").attr('readonly', '');
            $("#id_billing_last_name").removeClass('readonly');
            $("#id_billing_address").attr('readonly', '');
            $("#id_billing_address").removeClass('readonly');
            $("#id_billing_city").attr('readonly', '');
            $("#id_billing_city").removeClass('readonly');
            $("#id_billing_postcode").attr('readonly', '');
            $("#id_billing_postcode").removeClass('readonly');
            $("#id_billing_country").attr('readonly', '');
            $("#id_billing_country").removeClass('readonly');
            $("#same_as_delivery_address_chk").attr('value', '0');
            return false;
        }
    }
    if($("#same_as_delivery_address_chk").length > 0) {
        if($("#same_as_delivery_address_chk").is(':checked')) same_as_delivery_address();
    }
    $("#same_as_delivery_address_chk").click(
        function() {
            same_as_delivery_address();
        }
    );
    $("#expedition_address_submit_btn").click(
        function() {
            if ($("#same_as_delivery_address_chk").attr("checked")) same_as_delivery_address();
            if ($("#accept_privacy_checkbox").attr("checked")) {
                document.ExpeditionAddressForm.submit();
            } else {
                $("div#privacy_message").show();
            }
        }
    );
    $("#expedition_address_reset_btn").click(
        function() {
            $("#billing_address_form input").attr('value', '');
            $("#billing_address_form textarea").html('');
            $("#billing_address_form select").val('');
            $("#billing_address_form #id_first_name").focus();
            $("#delivery_address_form input").attr('value', '');
            $("#delivery_address_form textarea").html('');
            $("#delivery_address_form select").val('');
        }
    );
    $("#expedition_address_back_btn").click(
        function() {
            window.open('/shopping_cart/', '_self');
        }
    );
    $("#mc_item_back_order").click(
        function() {
            window.open('/shopping_cart/expedition_address/', '_self');
        }
    );
    if($("#delivery_service_summary").length > 0) {
        if($("#delivery_service_summary .price").html() == '') {
            $("#delivery_service_summary .note_1").show();
        }
    }
    $("#place_order_action").attr('value', ''); /* reset in caso di reload pagina */
    $("#mc_item_cancel_order").click(
        function() {
            $("#place_order_action").attr('value', 'cancel');
            document.PlaceOrderForm.submit();
        }
    );
    $("#mc_item_accept_order").click(
        function() {
            $("#place_order_action").attr('value', 'place');
            document.PlaceOrderForm.submit();
        }
    );
    $("#payment_method_paypal").click(
        function() {
            if($("#bank_data").is(':visible')) {
                $("#bank_data").hide();
            }
        }
    );
    $("#paypal_form_submit_btn").click(
        function() {
            $("#email_send_result").load(escape('/email-order-summary/paypal')); // ajax
        }
    );
    $("#payment_method_bank_transfer").click(
        function() {
            if(!$("#bank_data").is(':visible')) {
                $("#bank_data").show()
                $("#email_send_result").load(escape('/email-order-summary/bank')); // ajax
            }
        }
    );
    
    /* overflow scrolling */
    /* news */
    if ($("#news_title").length > 0) {
        // news box
        /*
        var newsbox_container = "#home_box_2";
        var newsbox_scroller = "#home_scroller";
        var newsbox_focus_container = "#news_focus";
        var newsbox_focus_target = ".news_top_border";
        var newsbox_up_arrow = ".home_top_border .scroll_up_arrow";
        var newsbox_down_arrow = ".home_bottom_border .scroll_down_arrow";
        
        checkContainerOverflow(newsbox_container, newsbox_scroller, newsbox_focus_container, newsbox_focus_target, newsbox_up_arrow, newsbox_down_arrow);
        
        if (checkBoxesOverflow(newsbox_container, newsbox_scroller, newsbox_focus_target)) {
            $(newsbox_container).css('overflow', 'auto');
            //$(newsbox_up_arrow).hide();
            //$(newsbox_down_arrow).hide();
        }
        
        // scroll news in basso
        $(newsbox_down_arrow).click(
            function() {
                scrollDown(newsbox_container, newsbox_scroller, newsbox_focus_container, newsbox_focus_target, newsbox_up_arrow, newsbox_down_arrow);
            }
        );
        
        $(newsbox_down_arrow).mousedown(function(){
            $(this).addClass('scroll_down_arrow_click');
        }).mouseup(function(){
            $(this).removeClass('scroll_down_arrow_click');
        });
        
        // scroll news in alto
        $(newsbox_up_arrow).click(
            function() {
                scrollUp(newsbox_container, newsbox_scroller, newsbox_focus_container, newsbox_focus_target, newsbox_up_arrow, newsbox_down_arrow);
            }
        );
        
        $(newsbox_up_arrow).mousedown(function(){
            $(this).addClass('scroll_up_arrow_click');
        }).mouseup(function(){
            $(this).removeClass('scroll_up_arrow_click');
        });
        */
        
        // news menu
        var newsmenu_container = "#home_menu"; // box esterno lista news con altezza fissa
        var newsmenu_scroller = "#home_menu_body"; // box interno lista news con altezza non definita
        var newsmenu_focus_container = "#newsmenu_focus"; // contenitore elemento con focus corrente no-display
        var newsmenu_focus_target = ".nav_news_top"; // classe di elementi bersaglio dei focus
        var newsmenu_up_arrow = ".m_top_border .m_scroll_up_arrow"; // freccia in alto
        var newsmenu_down_arrow = ".m_bottom_border .m_scroll_down_arrow"; // freccia in basso
        
        checkContainerOverflow(newsmenu_container, newsmenu_scroller, newsmenu_focus_container, newsmenu_focus_target, newsmenu_up_arrow, newsmenu_down_arrow);
        
        // scroll news in basso
        $(newsmenu_down_arrow).click(
            function() {
                scrollDown(newsmenu_container, newsmenu_scroller, newsmenu_focus_container, newsmenu_focus_target, newsmenu_up_arrow, newsmenu_down_arrow);
            }
        );
        
        $(newsmenu_down_arrow).mousedown(function(){
            $(this).addClass('scroll_down_arrow_click');
        }).mouseup(function(){
            $(this).removeClass('scroll_down_arrow_click');
        });

        
        // scroll news in alto
        $(newsmenu_up_arrow).click(
            function() {
                scrollUp(newsmenu_container, newsmenu_scroller, newsmenu_focus_container, newsmenu_focus_target, newsmenu_up_arrow, newsmenu_down_arrow);
            }
        );
        
        $(newsmenu_up_arrow).mousedown(function(){
            $(this).addClass('scroll_up_arrow_click');
        }).mouseup(function(){
            $(this).removeClass('scroll_up_arrow_click');
        });
    }
    
    /* prodotti */
    if ($("#product_list").length > 0) {
        // products box
        /*
        var productsbox_container = "#product_list";
        var productsbox_scroller = "#product_list_scroller";
        var productsbox_focus_container = "#product_list_focus";
        var productsbox_focus_target = ".pb_top_border";
        var productsbox_up_arrow = ".product_list_top_border .scroll_up_arrow";
        var productsbox_down_arrow = ".product_list_bottom_border .scroll_down_arrow";
        
        checkContainerOverflow(productsbox_container, productsbox_scroller, productsbox_focus_container, productsbox_focus_target, productsbox_up_arrow, productsbox_down_arrow);
        
        if (checkBoxesOverflow(productsbox_container, productsbox_scroller, productsbox_focus_target)) {
            $(productsbox_container).css('overflow', 'auto');
            //$(productsbox_up_arrow).hide();
            //$(productsbox_down_arrow).hide();
        }
        
        // scroll prodotti in basso
        $(productsbox_down_arrow).click(
            function() {
                scrollDown(productsbox_container, productsbox_scroller, productsbox_focus_container, productsbox_focus_target, productsbox_up_arrow, productsbox_down_arrow);
            }
        );
        
        $(productsbox_down_arrow).mousedown(function(){
            $(this).addClass('scroll_down_arrow_click');
        }).mouseup(function(){
            $(this).removeClass('scroll_down_arrow_click');
        });

        
        // scroll prodotti in alto
        $(productsbox_up_arrow).click(
            function() {
                scrollUp(productsbox_container, productsbox_scroller, productsbox_focus_container, productsbox_focus_target, productsbox_up_arrow, productsbox_down_arrow);
            }
        );
        
        $(productsbox_up_arrow).mousedown(function(){
            $(this).addClass('scroll_up_arrow_click');
        }).mouseup(function(){
            $(this).removeClass('scroll_up_arrow_click');
        });
        */
        
        // products menu
        var productsmenu_container = "#product_menu";
        var productsmenu_scroller = "#product_menu_scroller";
        var productsmenu_focus_container = "#product_menu_focus";
        var productsmenu_focus_target = ".nav_categories_top";
        var productsmenu_up_arrow = ".m_top_border .m_scroll_up_arrow";
        var productsmenu_down_arrow = ".m_bottom_border .m_scroll_down_arrow";
        
        checkContainerOverflow(productsmenu_container, productsmenu_scroller, productsmenu_focus_container, productsmenu_focus_target, productsmenu_up_arrow, productsmenu_down_arrow);
        
        // scroll prodotti in basso
        $(productsmenu_down_arrow).click(
            function() {
                scrollDown(productsmenu_container, productsmenu_scroller, productsmenu_focus_container, productsmenu_focus_target, productsmenu_up_arrow, productsmenu_down_arrow);
            }
        );
        
        $(productsmenu_down_arrow).mousedown(function(){
            $(this).addClass('scroll_down_arrow_click');
        }).mouseup(function(){
            $(this).removeClass('scroll_down_arrow_click');
        });

        
        // scroll prodotti in alto
        $(productsmenu_up_arrow).click(
            function() {
                scrollUp(productsmenu_container, productsmenu_scroller, productsmenu_focus_container, productsmenu_focus_target, productsmenu_up_arrow, productsmenu_down_arrow);
            }
        );
        
        $(productsmenu_up_arrow).mousedown(function(){
            $(this).addClass('scroll_up_arrow_click');
        }).mouseup(function(){
            $(this).removeClass('scroll_up_arrow_click');
        });
    }
    
    /* gallery */
    if ($("#gallery_box").length > 0) {
        
    }
    
});
