$(document).ready(function(){
    $('#is_duplicate').click(function(){$('#duplicate').slideToggle('fast')});

    // Searchbox stuff...
    var searchbox = $('#logo form input[type=text], #footer input[type=text]');
    var def_search_str = '34G, Freya, Dcup, etc...';

    // Onlsy set the suggestion text if the searchbox is empty
    if (searchbox.val() == "") {
        searchbox.addClass('inactive');
        searchbox.val(def_search_str);
    }

    // Searches for default string are searches for empty string
    $('#logo form input[type=submit]').click(function(){
        if (searchbox.val() == def_search_str) {
            searchbox.val('');
        }
        return true;
    });
    searchbox.focus(function(){
        $(this).removeClass('inactive');
        if ($(this).val() == def_search_str) {
            $(this).val('');
        }
    });
    searchbox.blur(function(){
        var res = $(this).val();
        if (res == '') {
            $(this).addClass('inactive')
            $(this).val(def_search_str);
        } else if (res == def_search_str) {
            $(this).addClass('inactive')
        }
    });

    // Tabs activation
    var $steps = $('.tab-step');
    $steps.not('.active').hide();
    var $tabs = $('#steps a, a.next, .prev:not(.link)');
    var do_tab = function(e, hash){
        if (hash == undefined) {
            hash = this.rel;
        }
        hash = hash.split('?')[0];
        $active_class = $('#steps a[rel^=' + hash + ']');
        if ($active_class.length != 0) {
            $tabs.removeClass('active');
            $steps.hide().filter(hash).show();
            $active_class.addClass('active');
        }
        return false;
    }
    $tabs.click(do_tab);
    hash = window.location.hash;
    if (hash){
        do_tab(1, hash);
    }

    // Blinking messages
    $('ul.message').fadeOut('slow', function(){
        var $this = $(this);
        $this.fadeIn('slow', function(){
            setTimeout(function(){
                $this.slideUp('slow');
            }, 4000);
        });
    });

    var $oidlogin = $('#topbar-openid');
    var $uplogin = $('#topbar-username');
    $('.topbar-switch').click(function(){
        $oidlogin.slideToggle();
        $uplogin.slideToggle();
        return false;
    });

    $('#size-detail .compare a.ready').click(function(){
        $(this).load(this.href);
        return false;
    });

    $('#feedback-link a').click(function(){
        $(this.parentNode).children('form').animate({width: 'toggle'});
        return false;
    });

    // Lightbox
    apply_lightbox($('.lightbox'));
    // Convert to inches 
    convert_inches();

    show_units_help();

    // Js fallback
    $('.hide-no-js').removeClass('hide-no-js');
    $('.show-no-js').remove();

});

var PREF_UNITS_ENDPOINT = '/profile/units/';

function convert_inches() {
    var CM = 0, IN = 1;
    var UNITS_TEXT = ['Cm.', 'In.'];

    var link = $('#convert-inches, #measurements-unit, .convert-inches, .measurements-unit');
    var table = $('table.measurements');
    var unit = $('#measurements-unit, .measurements-unit');
    var $label = $('#convert-inches, .convert-inches');

    var get_units = function(){
        if(unit.html() == UNITS_TEXT[CM]) return CM;
        return IN;
    };

    var pos = table.position();
    if (pos) { // In the case there's no table, there's no pos

        $('table.switch-units thead').hover(function(){
            // Recalculate position, it may have moved :P
            var pos = table.position();
            $label.css({
                top: pos.top,
                left: pos.left + parseInt(table.width())
            });
            $label.fadeIn();
        }, function(){
            $label.fadeOut('slow');
        });

        link.click(function(){
            var units = get_units();
            var RATIO = 2.54, text = UNITS_TEXT[1], link_text = 'Switch to Centimeters';

            if (units == IN) {
                RATIO = 1.0/RATIO;
                text = UNITS_TEXT[0];
                link_text = 'Switch to Inches';
            }

            unit.html(text);
            $label.html(link_text);
            $('table.measurements tbody tr td').each(function(){
                val = parseFloat($(this).html());
                $(this).html((val/RATIO).toFixed(1));
            });
            // Setting to units - 1 to get the "other" units, the one
            // that are different from the currently set (the clicked one)
            $.post(PREF_UNITS_ENDPOINT, {units: Math.abs(units -1)});
            return false;
        });
    }
}

function apply_lightbox(node){
    node.lightBox({
        fixedNavigation:true,
        imageLoading: MEDIA_URL + 'images/lightbox-ico-loading.gif',
        imageBtnClose: MEDIA_URL + 'images/lightbox-btn-close.gif',
        imageBtnPrev: MEDIA_URL + 'images/lightbox-btn-prev.gif',
        imageBtnNext: MEDIA_URL + 'images/lightbox-btn-next.gif',
        imageBlank: MEDIA_URL + 'images/lightbox-blank.gif'
    });
    return node;
}


function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; }

function show_units_help(){
    clicked = readCookie('show_units_help');
    if (!clicked) {
        $('<img/>').attr('src', MEDIA_URL + 'images/icon-close.png')
            .appendTo(
                $('<a href="#" title="Dismiss"></a>').appendTo(
                    $('<div></div>').addClass('units-help')
                    .text('Mouse over the units label to switch between centimeters and inches')
                    .insertBefore('table.show-units-help')
                    .width($('#measurements-unit').fadeOut(function(){
                        $(this).fadeIn(function(){
                            $(this).fadeOut(function(){
                                $(this).fadeIn();
                            });
                        });
                    }).parent().width())
                ).click(function(){
                        $('.units-help').fadeOut(function(){
                            $(this).remove();
                            createCookie('show_units_help', 1);
                            })
                        return false;
                        })
            );
    }
}
