
/**
 * 指定した文字数で文字を切る
 */
function cutWord(str, wordCount){

    var addWord = "...";
    var limit = wordCount - addWord.length
    
    if (str.length > limit) {
    
        return str.substr(0, limit) + addWord;
    }
    else {
    
        return str;
    }
}

/**
 * 指定した文字列を指定した文字数ごとに区切る
 * @param {Object} str
 * @param {Object} figureCount
 */
function addFigure(str, figureCount){
    var figureWord = ",";
    var num = new String(str).replace(new RegExp(figureWord, "g"), "");
    var reg = new RegExp("^(-?\\d+)(\\d{" + figureCount + "})");
    while (num != (num = num.replace(reg, "$1" + figureWord + "$2"))) 
        ;
    return num;
}

function showItem(target, options){
    //$("div.itemBox_inner",target).css("display","block");
    var inner = $("div.itemBox_inner", target);
    $(inner).hide();
    inner.setTemplateElement("templete_item", null, {
        filter_data: false
    });
    inner.processTemplate(options.item);
    
    
    
    
    var imageURL = options.item.ImageUrl;
    var linkURL = options.item.ItemPageUrl;
    var img = new Image();
    
    $(img).load(function(){
        $(target).css("background-image", "none");
        $("div.productImage", inner).append(this);
        $(this).wrap('<a href="' + linkURL + '"></a>');
        $(inner).fadeIn(1000);
    }).attr('src', imageURL)
    
    $(target).hover(function(){
        $(this).addClass("boxhover");
    }, function(){
        $(this).removeClass("boxhover");
    });
    $(target).click(function(){
        location.href = linkURL;
    });
}

//1画面に表示するアイテム数
var MAX_VIEW_ITEMS = 100;
//１回に取得できるアイテム数
var MAX_PAGE_ITEM = 20;


//現在のページ数（取得した回数）
var current_page = 0;
//検索キーワード
var searchKeyword = "";
//検索結果
var searchResultItems = [];


function startSearch(){
	$("#no_result").hide();
    $("#searchingBox").show();
    $("#result").hide();
    $("#resultItems").hide();
    
    $("#resultItems").empty();
    current_page = 0;
    searchResultItems = [];
    search();
}

function endSearch(){
    //console.log(result);
    $("#searchingBox").hide();
    $("#result").show();
    $("#resultItems").show();
    
    var items = $.map(searchResultItems, function(n, i){
        var item = n;
        //商品名（省略用）
        item.productNameS = cutWord(n.ProductName, 40);
        //item.productNameS = cutWord("ああああああああああああああああああああああああああああああああああああああああ", 40);
        //Star Rating
        item.scoreStar = (n.TotalScoreAve) ? Math.round(n.TotalScoreAve) : 0;
        //価格
        item.enPrice = (n.LowestPrice) ? "￥" + addFigure(n.LowestPrice, 3) : null;
        //ランキング
        //item.PvRanking= (n.PvRanking)? n.PvRanking : "ランク外A" ;
        
        return item;
    });
    
    
    $.each(items, function(i, val){
        var itemBox = $('<div class="itemBox"></div>');
        itemBox.append('<div class="itemBox_inner"></div>');
        
        $("#resultItems").append(itemBox);
        
        var options = {};
        itemBox.lazyaction({
            action: showItem,
            options: {
                item: val
            }
        });
        
    });
    
    
    
    
    
    
    
    
    
    //     var temp = "";
    //    temp += "-------------------------" + "<br />";
    //   jQuery.each(result.Item[0], function(i, val){
    //  	 temp += "[ " + i + " ] " + val + "<br />";
    //   });
    //   $('#trace').html(temp);
}

function search(){

    $.ajax({
        url: "http://pipes.yahoo.com/pipes/pipe.run",
        data: {
            ApiKey: "18e1df1b7387543cc580ebe9c55294a1",
            HitNum: MAX_PAGE_ITEM,
            Keyword: searchKeyword,
            //価格コムのページ数は１から始まる
            PageNum: current_page + 1,
            _id: "d3acf57a65838085f97700e9ce5c0eb2",
            _render: "json"
        },
        dataType: 'jsonp',
        jsonp: '_callback',
        complete: function(){
            //通信終了時の処理
        },
        success: function(data, status){
            //通信が成功した場合の処理 (JSONPのコールバック関数はこれが呼ばれます)
            onSuccessSearchItem(data);
        }
    });
    
}



function onSuccessSearchItem(data){

    var result = data.value.items[0];
    
    if (result.NumOfResult) {
    
    
    
        searchResultItems = searchResultItems.concat(result.Item);
        current_page++;
        if (MAX_PAGE_ITEM * current_page < Math.min(result.NumOfResult, MAX_VIEW_ITEMS)) {
            search();
        }
        else {
            endSearch();
        }
        
        
        
        var html = "";
        html += searchKeyword + "を検索した結果" + result.NumOfResult + "件中1～" + searchResultItems.length + "件目を表示";
        $('#result_inner').html(html);
    }else{
		
		 $("#searchingBox").hide();
		 $("#no_result").show();
		 $("#no_result").html(searchKeyword + "は、みつかりません。");
	}
    
}


/**
 * PageLoad function
 * This function is called when:
 * 1. after calling $.historyInit();
 * 2. after calling $.historyLoad();
 * 3. after pushing "Go Back" button of a browser
 *
 * @param {Object} hash
 */
function pageload(hash){
    // alert("pageload: " + hash);
    // hash doesn't contain the first # character.
    if (hash) {
        // restore ajax loaded state
        if ($.browser.msie) {
            // jquery's $.load() function does't work when hash include special characters like aao.
            //hash = encodeURIComponent(hash);
        }
        $('#input_keyword').val(hash);
        
        searchKeyword = hash;
        startSearch();
    }
    else {
        // start page
        //何もしない
    }
}

/**
 * 検索する
 */
function sendSearch(){
    //$('#trace').html();
    var keyword = $('#input_keyword').val();
    keyword = $.trim(keyword);
    if ("" == keyword) {
        return;
    }
    else {
        searchKeyword = keyword;
    }
    
    var hash = searchKeyword;
    hash = hash.replace(/^.*#/, '');
    // moves to a new page. 
    // pageload is called at once. 
    // hash don't contain "#", "?"
    $.historyLoad(hash);
    
}

$(document).ready(function(){
    // Initialize history plugin.
    // The callback is called at once by present location.hash. 
    $.historyInit(pageload, "index.html");
    
    
    
    $('#input_keyword').keypress(function(e){
    
        if (e.which == 13) {
            sendSearch();
        }
    });
    
    
    $('#button_search').click(function(){
    
        sendSearch();
    });
});










