var other_books = {
    element: '',
    line_left: 3,
    book_html: '',
    use_line_count: function () {
        this.line_left--;
        if ( this.line_left == 2 ) {
            return 'start';
        }
        else if ( this.line_left == 0 ) {
            this.line_left = 3;
            return 'end';
        }
        return this.line_left;
    },
    put_books: function (data) {
        var current_line_status = this.use_line_count();

        if (current_line_status == 'start') {
            var book_html = '<div class="line">' + this.make_new_book(data) + '</div>';
	    this.element.append(book_html);
        }
	else {
            var book_html = this.make_new_book(data);
	    this.element.children('.line:last-child').prepend(book_html);
        }

    },
    make_new_book: function (data) {
        var html = '<div class="new-book">'
        + '  <h4>' + data['title'] + '</h4>'
        + '  <p class="figure"><img src="' + data['images']['small'] + '" width="40" height="60" alt="" /></p>'
        + '  <div class="caption">'
        + '    <p class="data"><strong>' + data['price'] + '円（税込）</strong></p>'
        + '    <p>' + data['description'] + '</p>'
        + '    <ul>'
        + '      <li><a href="' +  data['permalink'] + '" target="_blank"><img src="/design/pcjp/images/authors/buyAmazon.jpg" width="135" height="27" alt="アマゾンで購入する" /></a></li>'
        + '    </ul>'
        + '  </div>'
        + '</div>';

        return html;
    },
    put_line_head: function () {
        return '<div class="line">';
    }
};

function get_amazon_book (identifier) {
     $.ajax({
         url : "http://api.d21.co.jp/amazon/url",
         dataType : "jsonp",
         data : "url=" + identifier,
         jsonp : "jsoncallback",
         success : function (json) {
             other_books.put_books(json);
         },
         error : function(){
             alert('error');
         }
     });
};
 
function replace_other_book () {
    other_books.element = $('#other_books');
    var urllist = other_books.element.text();
    other_books.element.html('');

    urllist = urllist.split(/\n/);

    /*
    $.each(urllist, function () {
        var value = this.replace(/\s/g, '');
        if ( value ) {
            get_amazon_book(value);
        }
    });
    */
    for ( var i = 0; i < urllist.length; i++ ) {
        var url = urllist[i].replace(/\s/g, '');
        if ( url ) {
            get_amazon_book(url);
        }
    }
};


$(document).ready( function () { replace_other_book() } );


