( function( $ ) {

    // plugin definition
    $.fn.overlabel = function( options ) {

        // build main options before element iteration
        var opts = $.extend( {}, $.fn.overlabel.defaults, options );

        var selection = this.filter( 'label[for]' ).map( function() {

            var label = $( this );
            var id = label.attr( 'for' );
            var field = document.getElementById( id );

            if ( !field ) return;

            // build element specific options
            var o = $.meta ? $.extend( {}, opts, label.data() ) : opts;

            label.addClass( o.label_class );

            var hide_label = function() { label.css( o.hide_css ) };
            var show_label = function() { this.value || label.css( o.show_css ) };

            $( field )
                 .parent().addClass( o.wrapper_class ).end()
                 .focus( hide_label ).blur( show_label ).each( hide_label ).each( show_label );

            return this;

        } );

        return opts.filter ? selection : selection.end();
    };

    // publicly accessible defaults
    $.fn.overlabel.defaults = {

        label_class:   'overlabel-apply',
        wrapper_class: 'overlabel-wrapper',
        hide_css:      { 'text-indent': '-10000px' },
        show_css:      { 'text-indent': '0px', 'cursor': 'text' },
        filter:        false

    };

} )( jQuery );

function autoFill(id){
    var title=$(id).attr('title');
    $(id).addClass("readonly").attr({ value: title }).focus(function(){
        if($(id).val()==title){
            $(id).val("").removeClass("readonly");
        }
    }).blur(function(){
        if($(id).val()==""){
            $(id).addClass("readonly").val(title);
        }
    });
}

function login() {
    $("#login").click(
        function() {
            $(".overlay").show();
            $(".sign-in").show();
        }
    );
    $(".sign-in .close").click(
        function() {
            $(".overlay").hide();
            $(".sign-in").hide();
        }
    );
}
function buttons() {
    $(".collection li").hover(
        function() {
            $(this).children('.buttons').show();
        },
        function() {
            $(this).children('.buttons').hide();
        }
    );
    $(".collection li div.buttons div").hover(
        function() {$(this).addClass('active')},
        function() {$(this).removeClass('active')}
    );
}

function bindComments() {
    $('.comment input.button').unbind('click');
    $('.comment input.button').click(function() {
        $(this).unbind('click');
        var form = $(this).parents('form');
        var txt = form.children('textarea').val();
        var blk = $(this).parents('div.comments');
        if (!txt && !$(this).parents('div.comment add-form')) {
            blk = $(this).parents('div.comment');
        }
        blk.load(form.attr('action'), {'submit': 1, 'comment': txt, 'library': (($(this).parents('div.comment.add-form').length == 0) && "1") | ""}, function() {
            bindComments();
        });
    });
}

function editComment(toy_id, comment_id) {
    $('ul#comments-'+toy_id+' form.addcomment').parents('li').remove();
    $('#comment-'+comment_id).load('/toy/' + toy_id + '/comment/' + comment_id + '/');
    return false;
}

function deleteComment(toy_id, comment_id) {
    if (confirm('Really delete?')) {
        $('#comments-'+toy_id).load('/toy/' + toy_id + '/comment/' + comment_id + '/?delete=1');
    }
    return false;
}

$ (
    function () {
        $("label.overlabel").overlabel();
        login();
        buttons();
        if (window.location.hash == 'login' | window.location.pathname == '/login/') {
            $("#login").click();
            $(".sign-in .close").remove();
        }
        $('fieldset.second input').change(function() { return selectToyType(); });
        $('fieldset.second input').bind('keyup', function() { selectToyType(); });
        if ($('.upload-toy.step1').length > 0) {
            $('fieldset.second').hide();
            $('fieldset.second input.hide').parent().hide();
        } else {
            $('fieldset.second').show();
            $('fieldset.second input.hide').parent().hide();
            selectToyType(true);
        }

        /*
        $('div.collection ul li').hide();
        $('div.collection ul li a img').load(function() {
            var li = $(this).parents('li');
            li.parents('ul').queue(function () {
                var li_queue = this;
                li.fadeIn('fast', function() {
                    $(li_queue).dequeue();
                });
            });

        });
        */

        bindComments();

        if ($("#tags").length > 0) {
            $("#tags .columns dd li a.edit").click(function() {
                $(".overlay").show();
                $(".popup").show();
                $('#edit_form').attr('action', this.rel);
                $('#id_tag_type').val($(".popup .select li.active").attr('id').replace('tagtype_', ''));
                $('#id_tag_name').val($(this).text());
                return false;
            });

            $("#tags .columns dd li a.delete").click(function() {
                return confirm('Are you sure to delete it?');
            });

            $(".popup .close").click(
                function() {
                    $(".overlay").hide();
                    $(".popup").hide();
                    return(false);
                }
            );
            $(".popup .select li").click(
                function() {
                    $(this).parent().parent().toggleClass("closed");
                    $('#id_tag_type').val(this.id.replace('tagtype_', ''));
                    $(".popup .select li").removeClass('active');
                    $(this).addClass('active');
                    return(false);
                }
            );
            $(".popup .select .icon").click(
                function() {
                    $(this).parent().toggleClass("closed");
                    return(false);
                }
            );
        }
    }
);

// ============================================================

function openClose(obj)
    {
    obj = obj.parentNode.parentNode;
    obj.className = obj.className == 'open' ? 'close' : 'open';
    }

//============================================================

function ajax(text)
    {
    var src = '/ajax/'+text+'/?x='+(Math.floor(Math.random()*10000000));
    if (window.XMLHttpRequest)
        var r = new XMLHttpRequest();
    else
        var r = new ActiveXObject('Microsoft.XMLHTTP');
    r.open('GET', src, false);
    r.send(null);
    return r.responseText;
    }

function havewant(obj, tId, type)
    {
    var r = ajax(type+'/'+tId);
    if (r == 'ok')
        {
        var li = obj.parentNode.parentNode;
        li.removeChild(obj.parentNode);
        var n = document.createElement('div');
        n.className = 'mark '+type+' ie6-png';
        n.innerHTML = '<div></div>';
        li.appendChild(n);
        }
    else
        location.href = r;
    }

function have(obj, tId)
    {
    havewant(obj, tId, 'have');
    }

function want(obj, tId)
    {
    havewant(obj, tId, 'want');
    }

//============================================================

function g(obj)
    { return document.getElementById(obj); }

function upComplete(id, url)
    {
    g('first').innerHTML = ''
        +'<p class="image"><a class="delete" href="/upload/delete/?id='+id+'">Delete this image</a><img src="'+url+'" alt="" style="max-width: 390px;" /></p>'
        +'<div class="buttons"><div class="have" onclick="have(this, '+id+')">I have this toy</div><div class="want" onclick="want(this, '+id+')">I want this toy</div></div>'
        +'<p>It’s easy to add new toys to The Library. Just upload a picture and share your knowledge about the toy. The more information you can provide, the better. When you tag a toy with an artist or series, Rotocasted uses this for searching and sorting. Please be accurate! If you don’t know something (for instance, “quantity produced”), it is best to leave it blank.</p>';
    g('id').value = id;
    $('.button.save').show();
    $('.upload-toy').removeClass('step1');
    $('fieldset.second').show();
    selectToyType();
    }

function u(obj)
    {
    var v = obj.parentNode.parentNode.getElementsByTagName('input')[0];
    v.value = obj.innerHTML;
    v.focus();
    selectToyType();
    }

function setupAutocompletes(url) {
    $('fieldset.second input.text.autocomplete').each(function() {
        $(this).autocomplete(
            url,
            {
                delay:10,
                minChars:2,
                matchSubset:0,
                matchContains:0,
                cacheLength:10,
                extraParams:{type: $(this).attr('name')},
                loadingClass:'ac_loading',
                resultsClass:'ac_results',
                autoFill:false
            }
        );
    });
}

function checkFormSubmit() {
    if ($('#submit').css('display') == 'none' | $('.ac_results:visible').children().length != 0) {
        return false;
    }
    return true;
}

function selectToyType(load) {
    $('fieldset.second input').parent().show();

    if ($('#type').val()) {
        $('li.step2_1').show();
        if ($('#platform').val() || $('#miniseries').val() || $('#type').val() != 'Mini figure') {
            $('li.step2_2').show();
        } else {
            $('li.step2_2').hide();
        }
    } else {
        $('li.step2_1').hide();
        $('li.step2_2').hide();
    }

    if ($('#type').val() == 'Designer toy') {
        if (load) $('.designertoy-hide').val('');
        $('.designertoy-hide').parent().hide();
    }
    if ($('#type').val() == 'Plush') {
        if (load) $('.plush-hide').val('');
        $('.plush-hide').parent().hide();
    }
    if ($('#type').val() == 'Mini figure') {
        if ($('#platform').val()) {
            if (load) $('.platform-mini-hide').val('');
            $('.platform-mini-hide').parent().hide();
        } else if ($('#miniseries').val()) {
            if (load) $('.serial-mini-hide').val('');
            $('.serial-mini-hide').parent().hide();
        } else {
            if (load) $('.mini-hide').val('');
            $('.mini-hide').parent().hide();
        }
    }
    if ($('#type').val() == 'Capsule') {
        if (load) $('.capsule-hide').val('');
        $('.capsule-hide').parent().hide();
    }
}






