//
// TAG REMOVAL & UNDO
//

// click on [x] (remove) tag callback
function remove_tag_click(obj) {
    // using time in millisecond to ID the tag being removed
    var date = new Date()
    id = date.getTime()
    $(obj).parent()
    .replaceWith('<span id="' + id +'">...</span>')
    href = $(obj).attr("href")
    if (href.indexOf('http://') < 0)
        href = 'http://' + location.host + href;
    $.get(href, {type : "ajax"},
    function(data) {
        $("span[id=" + id +"]").html(data)
        ajaxify_undo(id)
    })
}

// ajaxy undo tag removal
function ajaxify_undo(id) {
    $("span[id=" + id + "] a.undo")
    .click(function(event) {
        undo_tag_click(id)
        stop(event)
    })
}

// undo click re-tag callback
function undo_tag_click(id) {
    href = $("span[id=" + id + "] a.undo")[0].href
    $("span[id=" + id +"]").replaceWith('<span id="' + id +'">...</span>')
    $.get(href, {type: "ajax"},
    function(data) {
        $("span[id=" + id +"]").replaceWith(data)
        remove_tag()
    })
}

function remove_tag() {
    $.each($("a[href*=remove/tag]"),
    function() {
        $(this)
        .click(function(event) {
            remove_tag_click(this)
            stop(event)
        })
    })
}

//
// TAG FORM
//

// action tag-form
function tag(form) {
    dict = { tags : $("form[name=" + form + "] input[name=tags]")[0].value,
             book : $("form[name=" + form + "] input[name=book]")[0].value,
             type : "ajax"}
    // deal with first tag addition i.e. minimize not there
    minimize = $("form[name=" + form + "]").siblings("span.minimize")
    // if not first tag pluralize (better than testing if necessary?)
    if (minimize.length) {
        minimize.text('tags:').after('<span name="in_progress">...</span>')
    } else {
        formobj =  $("form[name=" + form + "]")
        formobj
        .parent()
        .siblings("div.tags")
        .attr("style", "width:100%")
        .html('<span class="minimize">tag:</span><span name="in_progress">...</span>')
        formobj.clone(true)
        .prependTo(formobj.parent().siblings("div.tags"))
        .end().remove()
    }
    $.post("/tag", dict,
    function(data) {
        $("span[name=in_progress]").replaceWith(data)
        remove_tag()
    })
    $("form[name=" + form + "] input[name=tags]")[0].value = ''
}

function tag_form() {
    $.each($("form[name*=tag-form]"),
    function() {
        $(this).attr("action","javascript:tag('" + this.name + "');")
    })
}

//
// SEARCH FORM - (QUICK) ADD BOOK
//

// ajax get to add book with isbn ... it's about closure baby!!!!
// i.e. making the $.get callback aware of the RELEVANT isbn
function add(isbn) {
    $("div.book:first")
    .before(
        '<div class="book pending"><strong>' + isbn + '</strong> ...</div>'
    )
    $("div.book.pending").not(".round").corner().addClass("round")
    //window.scroll(0,0)
    $.get('http://'+ location.host + '/add/' + isbn, {type : 'ajax'},
    function(data) {
        $("div.book:contains(" + isbn +"):not(div.book.pending)")
        .remove()
        $("div.book.pending:contains(" + isbn +")").replaceWith(data)
        $("div.book.failure").not(".round").corner().addClass("round")
        new_book()
        // in case can't find ISBN => add manually
        manual_add()
    })
}

// standard search ... without the _ -> endless loop?
function _search(query) {
    window.location.replace('/search?query=' + encodeURIComponent(query))
}

// Command LIne pre-processing :P
function cli() {
    query = $("input[name=query]").attr("value")
    if (typeof(query) == 'undefined') query = '';
    if (query[0] == '+') {
        add(query.slice(1).replace('*','X'))
        $("input[name=query]").attr("value", "")
    } else {
        _search(query)
    }
}

function search_form() {
    /* $("button[id=search-button]")
    .click(function(event) {
        search_click(event)
    }) */
    $("form[name=search-form]")
    .attr("action", "javascript:cli();")
}

//
// SLIDEBAR ISBN ADD
//

// the action
function isbn_add_action() {
    isbn = $("input[name=isbn]").attr("value")
    add(isbn)
    $("input[name=isbn]").attr("value", "")
}

// ajaxifying the isbn add
function isbn_add() {
    $("form[name=add-form]")
    .attr("action", "javascript:isbn_add_action()")
}

//
// ADD MANUAL
//

function manual_add() {
    $("a[href*=/add/manual]")
    .click(function() {
        $(this).parent("div.book.failure").remove()
        // only one manual add form at a time possible
        if ($("div.book.pending.manual").length == 0) {
            $("div.book:first")
            .before(
                '<div class="book pending manual">...</div>'
            )
            $("div.book.pending.manual").not(".round").corner().addClass("round")
        }
        $.get('http://' + location.host + $(this).attr("href"),
        {type: 'ajax'},
        function(data) {
            $("div.book.pending.manual").html(data).corner()
            $("div.book.pending.manual input[name=title]").focus()

            //cancel add manual
            $("div.book > a[href*=/cancel]")
            .click(function() {
                $(this).parents("div.book").remove()
                return false
            })
        })
        return false
    })
}

//
// EDIT BOOK DESC
//

// closure on which

function edit(which) {
    href = $(which).attr("href")
    // it's the invitation do write a description that has been clicked on
    if ($(which).parents(".zoom_loading").length > 0) {
        which = $(which).parents("div.book").children("a[href*=/edit]").get(0)
    }
    $(which).hide().siblings().not(".jquery-corner").hide()
    $(which).parents("div.book").append('<div class="edit_book loading">...<div>')
    $.get('http://' + location.host + href,
    {type : 'ajax'},
    function(data) {
        $("div.edit_book.loading").remove()
        $(which).parents("div.book")
        .append(data)
        .addClass("pending")

        remove_book()

        // cancel edit
        $("div.book > a[href*=/cancel]")
        .click(function(event) {
            $(this).parents("div.book").removeClass('pending')
            .children(":hidden").not(".zoom_loading").show()
            $(this).parents("div.book")
            .children(".edit_book").remove()
            stop(event)
        })
    })
}

function edit_book() {
    $("a[href*=/edit/book]")
    .unbind('click')
    .click(function() {
        edit(this)
        return false
    })
}

//
// BOOK REMOVAL & UNDO
//

function undo_remove_book(id) {
    $("div.book.removed[id=" + id + "]").corner()
    $("div.book.removed[id=" + id + "] a")
    .click(function(event) {
        $.get(this.href, {type : "ajax"},
        function(data) {
            $("div.book.removed[id=" + id + "]")
            .replaceWith(data)
            new_book()
        })
        stop(event)
    })
}

function remove_book_click(obj) {
    $.get(obj.href, {type : 'ajax'},
    function (data) {
        var date = new Date()
        id = date.getTime()
        $(obj).parent()
        .replaceWith('<div class="book removed" id="' + id + '">' + data + '</div>')
        undo_remove_book(id)
    })
}

function remove_book() {
    $("a[href*=/remove/book/]")
    .unbind()
    .click(function(event) {
        remove_book_click(this)
        stop(event)
    })
}

//
// RIVERFLOW
//

// return true if scroll down to a point where next page should be called
function flow() {
    // IE sucks !!!!
    var scrollTop = window.pageYOffset || document.documentElement.scrollTop
    // using var to force local scope
    var riverflow = $("#riverflow").get(0).offsetTop
    var foot = $("#footer").get(0).offsetTop
    // 2/3 down
    if (scrollTop > riverflow * (2/3))
        return true
    // riverflow reaching footer ...
    if (scrollTop + foot > (2/3) * riverflow)
        return true
    // opera has its problems too
    if ((foot == 0) && (scrollTop > riverflow * (1/2)))
        return true
    return false
}

// to be called everytime (a) new book(s) are added to the DOM for event
// handling
function new_book() {
    remove_book()
    remove_tag()
    tag_form()
    book_hover()
}

function riverflow() {
    $(window)
    .scroll(function () {
        $("a#less-books").remove()
        riverflow = $("#riverflow")
        if (riverflow.length && flow()) {
            more = $("a#more-books").get(0)
            if (typeof(more) != 'undefined') {
                url = $(more).attr("href")
                $(more).replaceWith("...")
                $.get(url, {type : "ajax"},
                function (data) {
                    riverflow.replaceWith(data)
                    new_book()
                })
            }
        }
    })
}

//
// ZOOM BOOK
//

function zoom_click(target) {
    if (target.children("form[name=edit-book-form]").length > 0) return;
    zoom_loading = target.children('.zoom_loading')
    if (zoom_loading.length > 0) {
        zoom_loading.toggle()
        return
    }
    $.get('http://'+ location.host + target.find(".title > a").attr("href"),
        {type : 'ajax'},
        function(data) {
            target.children('.zoom_loading').html(data)
            // attaching the ajax edit click event
            edit_book()
        })
    target.append('<div class="zoom_loading"><strong>...</strong></div>')
}

$(document).ready(function(){

    remove_tag()
    tag_form()
    search_form()
    remove_book()
    riverflow()
    isbn_add()
    manual_add()
    edit_book()

})
