var RFlow = {
    version: '2007-04-11',
    lastQuery: '',
    hits: 10,

    // 現在のページID
    current : '',

    // ローカルDBにキャッシュを保存する
    saveItem :function(query, json) {
        if (!LocalDB.enable) return false;

        var now = new Date();
        var yy = now.getYear();
        var mm = now.getMonth() + 1;
        var dd = now.getDate();
        var h  = now.getHours();
        var m  = now.getMinutes();
        var s  = now.getSeconds();
        if (yy < 2000) { yy += 1900; }
        if (mm < 10) { mm = "0" + mm; }
        if (dd < 10) { dd = "0" + dd; }
        if (h < 10) { h = "0" + h; }
        if (m < 10) { m = "0" + m; }
        if (s < 10) { s = "0" + s; }
        var updated = yy + "-" + mm + "-" + dd + ' ' + h + ':'+ m + ':' + s;
        var insertData = {
            'url' : query,
            'hash': SHA1(query),
            'body': json,
            'updated': updated
        };
        LocalDB.save('items', insertData, {'conditions' : ['hash = ?', [insertData.hash]]});
        return true;
    },
    // 古いデータを削除する
    clearItems :function(){
        if (!LocalDB.enable) return false;
        var now = new Date();
        now.setTime(now.getTime() - (1000*60*60*24*3)); //3日前
        var yy = now.getYear();
        var mm = now.getMonth() + 1;
        var dd = now.getDate();
        var h  = now.getHours();
        var m  = now.getMinutes();
        var s  = now.getSeconds();
        if (yy < 2000) { yy += 1900; }
        if (mm < 10) { mm = "0" + mm; }
        if (dd < 10) { dd = "0" + dd; }
        if (h < 10) { h = "0" + h; }
        if (m < 10) { m = "0" + m; }
        if (s < 10) { s = "0" + s; }
        var expires = yy + "-" + mm + "-" + dd + ' ' + h + ':'+ m + ':' + s;
        LocalDB.remove('items', {'conditions': [' updated < ? ', [expires]]});
    },

    // コールバック関数
    genreSearch : function(json) {
        var self = this;
        if (0 < json.Body.GenreSearch.child.length) {
            $.each(json.Body.GenreSearch.child, function(index, data) {
                if ($('#list_genre_' + data.genreId).length == 0) {
                    var li = $(document.createElement('li'));
                    li.attr('id', 'list_genre_' + data.genreId);
                    var a = $(document.createElement('a'));
                    a.attr('href', '#genre_' + data.genreId);
                    a.text(data.genreName);
                    li.append(a);
                    $('#' + self.current).append(li);

                    // ジャンルを取得
                    $(a).click(function(e) {
                        //self.current = e.target.href.split('#')[1];
                        RFlow.getByAPI({'api':'GenreSearch', 'current':e.target.href.split('#')[1], 'genreId': data.genreId});
                    });
                }

                // 初めて取得するリストの場合はあらかじめ追加しておく
                if ($('#genre_' + data.genreId).length == 0) {
                    var next_ul = $(document.createElement('ul'));
                    next_ul.attr('id', 'genre_' + data.genreId);
                    next_ul.attr('title', data.genreName);
                    $('body').append(next_ul);
                }
            });
        } else {
            var genreId = self.current.split('_')[1];
            RFlow.getByAPI({'api':'ItemSearch', 'current':self.current, 'genreId': genreId});
        }
    },
    itemSearch : function(json) {
        var self = this; $('#' + self.current).addClass('coverflowable');
        if (0 < $('#' + self.current + '>li.nextItems').length) $('#' + self.current + '>li.nextItems').remove();
        if (0 == $('#' + self.current + '>li').length) {
            $('#' + self.current).html('<li class="group">商品一覧</li><li class="iphoneInfo">ここでiPhoneを横にすると、大きい商品画像を見ながら選択できます。</li>');
        }

        $.each(json.Body.ItemSearch.Items.Item, function(index, data) {
            if ($('#list_item_' + data.itemCode).length == 0) {
                var li = $(document.createElement('li'));
                li.attr('id', 'list_item_' + data.itemCode);
                var a = $(document.createElement('a'));
                a.attr('href', '#item_' + data.itemCode);
                a.html('<div class="listedImage"><img src="' + data.smallImageUrl + '"></div><span class="listedName">' + h(data.itemName) + '</span><div class="clear"></div>');
                li.append(a);
                $('#' + self.current).append(li);
            }

            // 初めて取得するリストの場合はあらかじめ追加しておく
            if ($('#item_' + data.itemCode).length == 0) {
                var div = $(document.createElement('div'));
                div.attr('id', 'item_' + data.itemCode);
                div.attr('title', data.itemName);
                div.addClass('itemDetail');
                div.addClass('panel');

                var html = '';
                html += '<h2>' + h(data.itemName) + '</h2>';
                html += '<div class="leftBox"><img class="itemImage" src="' + data.mediumImageUrl + '"></div>';

                html += '<div class="rightBox">';
                html += '<div class="price">' + data.itemPrice + '円</div>';
                html += '<div class="reviewAverage">レビュー平均:' + data.reviewAverage + '</div>';
                html += '<div class="reviewCount">レビュー件数:' + data.reviewCount + '</div>';
                //html += '<a class="shopLink" href="' + data.shopUrl + '">' + h(data.shopName) + '</a>';
                html += '</div>';
                html += '<a class="purchaseLink" href="' + data.affiliateUrl + '" target="_blunk">販売ページへ</a>';

                html += '<div class="caption">' + h(data.itemCaption).replace(/.(■)/g,"<br />$1" ) + '</div>';
                div.html(html);
                $('body').append(div);
            }
        });

        // 次のページ
        if ($('#' + self.current + '>li.nextItems').length == 0) {
            var page = parseInt(json.Body.ItemSearch.page);
            if (page < parseInt(json.Body.ItemSearch.pageCount)) {
                var li = $(document.createElement('li'));
                li.addClass('nextItems');
                li.html('<div>次の' + RFlow.hits + '件を表示</div>');
                li.one('click', function(e) {
                    li.addClass('progress');
                    RFlow.getByAPI({'api':'ItemSearch', 'current':self.current, 'genreId': self.current.split('_')[1], 'page':page+1});
                });
                $('#' + self.current).append(li);
            }
        }
    },
    itemCodeSearch : function(json) {
    },
    catalogSearch : function(json) {
    },

    // API名を指定して取得
    getByAPI : function(options, callBack) {
        var self = this;
        var params = {};
        self.current = options.current;
        params.version = this.version;

        switch (options.api) {
        case 'GenreSearch':
            params.operation = options.api;
            params.genreId = options.genreId || 0;
            //params.genreInformationFlag = options.genreInformationFlag || 1;
            callBack = callBack || function(json) { self.genreSearch(json) };
            break;
        case 'ItemSearch':
            params.operation = options.api;
            params.genreId = options.genreId || 0;
            params.hits = options.hits || RFlow.hits;
            params.page = options.page || 1;
            //params.genreInformationFlag = options.genreInformationFlag || 1;
            //params.carrier = options.carrier || 1;
            params.imageFlag = options.imageFlag || 1;
            callBack = callBack || function(json) { self.itemSearch(json) };
            break;
        case 'ItemCodeSearch':
            params.operation = options.api;
            callBack = callBack || function(json) { self.itemCodeSearch(json) };
            break;
        case 'CatalogSearch':
            params.operation = options.api;
            callBack = callBack || function(json) { self.catalogSearch(json) };
            break;
        default:
            return;
            break;
        }
        var params_array = [];
        $.each(params, function(i, data) { params_array.push(i + '=' + data) });
        var query = 'get_json.rb?' + params_array.join('&');

        var now = new Date();
        now.setTime(now.getTime() - (1000*60*60*24*3)); //3日前
        var yy = now.getYear();
        var mm = now.getMonth() + 1;
        var dd = now.getDate();
        var h  = now.getHours();
        var m  = now.getMinutes();
        var s  = now.getSeconds();
        if (yy < 2000) { yy += 1900; }
        if (mm < 10) { mm = "0" + mm; }
        if (dd < 10) { dd = "0" + dd; }
        if (h < 10) { h = "0" + h; }
        if (m < 10) { m = "0" + m; }
        if (s < 10) { s = "0" + s; }
        var expires = yy + "-" + mm + "-" + dd + ' ' + h + ':'+ m + ':' + s;
        // キャッシュがあればキャッシュを使用
        LocalDB.find('items', {'conditions': ['hash = ? and ? < updated', [SHA1(query), expires]], 'callback':function(items) {
            // キャッシュがあればキャッシュを使用
            if (0 < items.length) {
                callBack(eval('('+items[0].body+')'));
            // キャッシュがなければ、新たに取得する
            } else {
                $.get(query, '', function(json) {
                    json_data = eval('('+json+')');
                    if (json_data.Header.Status == 'Success') {
                        //json文字列をキャッシュとしてローカルDBに保存する
                        RFlow.saveItem(query, json);

                        // コールバックメソッドを実行
                        callBack(json_data);
                        //eval('self.' + jsonp);
                    } else {
                        alert(json_data.Header.StatusMsg);
                    }
                });
            }
        }});
        this.lastQuery = query;
    },
    addFlowItems: function(json) {
        var self = this;
        var page = parseInt(json.Body.ItemSearch.page);

//        if (0 < $('#coverFlow>ul.coverFlow>li.nextItems').length) $('#coverFlow>ul.coverFlow>li.nextItems').remove();

        $.each(json.Body.ItemSearch.Items.Item, function(index, data) {
            var li = $(document.createElement('li'));
            li.click(function(e) {
                if (window.confirm("購入画面を開きますか？")) {
                    window.open(data.affiliateUrl, "_blank");
                }
            });
            li.html('<img src="' + data.mediumImageUrl + '" alt="' + h(data.itemName) + '" />');
//            li.css('-webkit-transform', 'scale(1) translateX(480px) rotateY(-90deg)');
            $('#coverFlow>ul.coverFlow').append(li);
        });

//        $('#coverFlow>ul.coverFlow').append($(html));

        // 次のページ
        if ($('#coverFlow>ul.coverFlow>li.nextItems').length == 0) {
            var page = parseInt(json.Body.ItemSearch.page);
            if (page < parseInt(json.Body.ItemSearch.pageCount)) {
                var next_li = $(document.createElement('li'));
                next_li.addClass('nextItems');
                next_li.html('<div>次の' + RFlow.hits + '件</div>');
                next_li.one('click', function(e) {
                    RFlow.getByAPI({'api':'ItemSearch', 'current':self.current, 'genreId': self.current.split('_')[1], 'page':page+1}, function(json) {
                        $('#coverFlow>ul.coverFlow>li.nextItems').remove();
                        self.addFlowItems(json);
                        $('#coverFlow>ul.coverFlow>li').eq(CoverFlow.selectedItem).addClass('center');

                        var ul = $('#coverFlow>ul.coverFlow').get(0);
                        CoverFlow.initItem(ul);
                        CoverFlow.start(ul);
                    });
                });
                $('#coverFlow>ul.coverFlow').append(next_li);
            }
        }
    },
    initFlow: function() {
        var self = this;
        if ($('body>ul[selected=true]').filter('.coverflowable').size() == 1) {
            $('div.toolbar').hide(0);
            $('body').css('background-color', '#000');
            //$('#' + this.current).hide(0);
            $('#' + this.current).attr('selected', '');

            var genreId = this.current.split('_')[1];
            RFlow.getByAPI({'api':'ItemSearch', 'current':self.current, 'genreId': genreId}, function(json){

                var html = '';
                html += '<ul class="coverFlow">';
                html += '</ul>';
                html += '<div id="flowItemName">';
                html += '</div>';
                $('#coverFlow').html(html);
                self.addFlowItems(json);

                $('#coverFlow').attr('selected', 'true');
                //location.href = location.href.split('#')[0] + '#coverFlow';
                scrollTo(0, 1);
                $('#coverFlow>ul').coverFlow({
                    'nameLabel' : 'flowItemName',
                    'leftButton' :'leftButton',
                    'rightButton' :'rightButton'
                });
            });
        }
    },
    finishFlow: function() {
        var self = this;
        if ($('body>div[selected=true]').filter('#coverFlow').size() == 1) {
            $('body').css('background-color', '#fff');
            $('#coverFlow').attr('selected', '');
            $('#coverFlow').html('');
            $('div.toolbar').show(0);
            $('#' + self.current).attr('selected', 'true');
            CoverFlow.clean();
        }
    },
    dummy : 'dummy'
}

// jQuery 拡張
jQuery.fn.extend({
    coverFlow: function(options) {
        CoverFlow.init(options);

        var self=this;
        return this.each(function(i, ul) {
//            jQuery(ul).append(jQuery(html));

            CoverFlow.initItem(ul);
            CoverFlow.start(ul);

            var x = 0;
            var dx = 0;
            jQuery(document.body).unbind("touchstart");
//            jQuery(document.body).unbind("touchmove");
            var touchStartEvent = function(e) {
                e = event;
                dx = x = e.touches[i].pageX;
                if (x < 120) {
                    CoverFlow.moveLeft(ul);
                    CoverFlow.start(ul);
                }
                if (360 < x) {
                    CoverFlow.moveRight(ul);
                    CoverFlow.start(ul);
                }
                var label = jQuery('#' + CoverFlow.nameLabel);
                label.text('');
                label.text(jQuery('li.center>img', ul).eq(0).attr('alt'));
            }

//            var touchMoveEvent = function(e) {
//                e = event;
//                dx = e.touches[i].pageX;
//                var d = dx - x;
//                if (30 < Math.abs(d)) {
//                    x = dx;
//                    (d < 0) ? CoverFlow.moveLeft(ul) : CoverFlow.moveRight(ul);
//                    CoverFlow.start(ul);
//                }
//            }
            jQuery(document.body).bind("touchstart", touchStartEvent);
//            jQuery(document.body).bind("touchmove", touchStartEvent);
        });
    }
});
var CoverFlow = {
    selectedItem : 0,
    scrollLeft : 0,
    interval : 0,
    items : 0,
    init : function(options) {
        this.selectedItem = this.selectedItem || 0;
        this.scrollLeft = this.scrollLeft || -140;
        this.interval = this.interval || 40;
        this.items = this.items || 10;
        this.nameLabel = options.nameLabel || '';
        this.touch = options.touch || function(){};
    },
    clean : function() {
        this.selectedItem = 0;
        this.scrollLeft = 0;
        this.interval = 0;
        this.items = 0;
    },
    swipe : function() {},
    moveLeft : function(ul) {
        if (0 < CoverFlow.selectedItem) {
            CoverFlow.scrollLeft -= CoverFlow.interval;
            jQuery('>li', ul).eq(CoverFlow.selectedItem).addClass('right').removeClass('center');
            jQuery('>li', ul).eq(--CoverFlow.selectedItem).addClass('center').removeClass('left');
        }
    },
    moveRight : function(ul) {
        if (CoverFlow.selectedItem < CoverFlow.items-1) {
            CoverFlow.scrollLeft += CoverFlow.interval;
            jQuery('>li', ul).eq(CoverFlow.selectedItem).addClass('left').removeClass('center');
            jQuery('>li', ul).eq(++CoverFlow.selectedItem).addClass('center').removeClass('right');
        }
    },
    initItem : function(ul) {
        CoverFlow.items = jQuery('>li', ul).size();
        if (!jQuery('>li', ul).hasClass('center')) jQuery('>li:first', ul).addClass('center');
        var nextSide = 'left';
        jQuery('>li', ul).each(function(j, li) {
            if (jQuery(li).hasClass('center')) {
                CoverFlow.selectedItem = j;
                nextSide = 'right';
            } else {
                jQuery(li).addClass(nextSide);
            }
        });
        jQuery('#' + CoverFlow.nameLabel).text(jQuery('li.center>img', ul).eq(0).attr('alt'));
    },
    start : function(ul) {
        jQuery('>li', ul).each(function(j, li) {
            li.style.display = (j < CoverFlow.selectedItem -5 || CoverFlow.selectedItem + 5 < j) ? 'none' : 'block';
            if (jQuery(li).hasClass('left')) {
                li.style.webkitTransform = 'scale(1) translateX(' + ((j * CoverFlow.interval) - CoverFlow.scrollLeft - 100) + 'px) rotateY(90deg)';
            } else if(jQuery(li).hasClass('right')) {
                li.style.webkitTransform = 'scale(1) translateX(' + ((j * CoverFlow.interval) - CoverFlow.scrollLeft + 100) + 'px) rotateY(-90deg)';
            } else if(jQuery(li).hasClass('center')) {
                li.style.webkitTransform = 'scale(1.5) translateX(' + ((j * CoverFlow.interval) - CoverFlow.scrollLeft - 45) + 'px) rotateY(0deg)';
            }
        });
    }
}

var h = function(str) {
    return str.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

$(function() {
    LocalDB.init();
    $('#to_ichiba_home').click(function(e) {
        var current = e.target.href.split('#')[1];
        RFlow.getByAPI({'api':'GenreSearch', 'current':current});
    });
    $('body').bind('orientationchange', function() {
        if (window.orientation == 90 || window.orientation == -90) {
            RFlow.initFlow();
        } else {
            RFlow.finishFlow();
        }
    });
    RFlow.clearItems();

//    $('#searchButton').click(function() {
//        if ($('#coverFlow>ul').size() == 1) {
//            RFlow.finishFlow();
//        } else {
//            RFlow.initFlow();
//        }
//    });
});
