/**
 *  init
 */
jQuery(document).ready(function($) {
    // init Calculator
    $("body").ajaxError(ajax_error);

    restore_calcurl();
});

/*
 *  パーツの選択
 */
var current_items = {};
var item_data_cache = {};
var queue_item_request = [];
var queue_item_num = {};
var nowloading = false;
var nowrestoring = false;

/**
 * パーツ追加
 */
function add_item(parts_type, item_id, num, checked) {
    if (!current_items[parts_type]) {
        current_items[parts_type] = {};
    }
    if (!current_items[parts_type][item_id]) {
        current_items[parts_type][item_id] = null;
        addqueue_request_parts(parts_type, item_id, num, checked);
    } else {
        update_parts_html(parts_type, item_id, true, num, checked);
    }
}

/**
 * パーツ削除
 */
function remove_item(parts_type, item_id) {
    if (!current_items[parts_type]) {
        current_items[parts_type] = [];
    }
    delete current_items[parts_type][item_id];
    update_parts_html(parts_type, item_id, false);
}

/**
 * パーツ情報の取得キューに追加
 */
function addqueue_request_parts(parts_type, item_id, num, checked) {
    if (item_data_cache[item_id]) {
        current_items[parts_type][item_id] = item_data_cache[item_id];
        update_parts_html(parts_type, item_id, num, true, checked);
    } else {
        queue_item_request.push(item_id);
        queue_item_num[item_id] = num;
        setTimeout(function(){request_parts(checked);}, 300);
    }
}

/**
 * パーツ情報の取得
 */
function request_parts(checked) {
    if (queue_item_request.length == 0) {
        return;
    }
    if (nowloading) {
        setTimeout(function(){request_parts(checked);}, 300);
        return;
    }
    nowloading = true;
    $.getJSON("search", {
        "ids[]": queue_item_request
    }, function(data){
        nowloading = false;
        for (var item_id in data) {
            var item = data[item_id];
            var num = queue_item_num[item_id];
            queue_item_request.splice(queue_item_request.indexOf(item_id), 1);
            delete queue_item_num[item_id];
            item_data_cache[item_id] = item;
            label_1: for (var parts_type in current_items) {
                for (var item_id_askey in current_items[parts_type]) {
                    if (item_id_askey == item_id) {
                        current_items[parts_type][item_id] = item;
                        update_parts_html(parts_type, item_id, true, num, checked);
                        break label_1;
                    }
                }
            }
        }
    });
}

/**
 * パーツHTML更新
 */
function update_parts_html(parts_type, item_id, addflg, num, checked) {
    if (addflg) {
        if (!$("#parts_" + item_id).get(0)) {
            var item = current_items[parts_type][item_id];
            var item_name = '';
            var item_price = 0;
            var item_price_str = '不明';
            if (item['MakerName']) {
                item_name = item['MakerName'];
            }
            if (item['ProductName']) {
                item_name += ' ' + item['ProductName'];
            }
            if (item['LowestPrice']) {
                item_price = item['LowestPrice'];
                item_price_str = add_comma(item['LowestPrice']) + "円";
            }

            var html = '<li id="parts_' + item_id + '"><div class="itemdetail"><div class="left">';
            html += '<input type="checkbox" class="parts_select" name="p' + parts_type + '" id="p_' + parts_type + '_' + item_id + '" value="' + item_id + '"';
            if (checked) {
                html += ' checked';
            }
            html += '>'
                  + '<input type="hidden" class="pricevalue" id="p_' + parts_type + '_' + item_id + '_price" value="' + item_price + '">'
                  + '<label for="p_' + parts_type + '_' + item_id + '">'
                  + '<img id="p_' + parts_type + '_' + item_id + '_image" src="' + item['ImageUrl'] + '" height="25" width="25" alt="' + item_name + '"> '
                  + item_name
                  + '</label>'
                  + ' <a id="link_' + parts_type + '_' + item_id + '" href="' + item['ItemPageUrl']  + '" title="' + item_name + '" class="selectoption" target="kakaku" onclick="frameopen(event, \'kakaku\');">詳細を見る</a>'
                  + ' <span class="item_num" id="n_' + parts_type + '_' + item_id + '">' + num + '個</span> <a id="nchange_' + parts_type + '_' + item_id + '" class="clickoption" href="javascript:void(0);" title="個数指定" class="selectoption" onclick="select_num(\'' + parts_type + '\', \'' + item_id + '\');">変更</a>'
                  + '</div>'
                  + '<div class="right">'
                  + '<span class="price" id="price_' + parts_type + '_' + item_id + '">' + item_price_str + '</span>'
                  + '</div>'
                  + '</div>'
                  + '</li>';
            $("#selectparts_" + parts_type).append(html);
            if (!$("#selectparts_" + parts_type + " input:checked").get(0)) {
                $("#selectparts_" + parts_type + " input:first-child").attr("checked", "checked");
            }
            $("#p_" + parts_type + "_" + item_id).click(update_total);
            if (parent.navi && parent.navi.select_item) {
                parent.navi.select_item(parts_type, item_id);
            }

            // タブをバックグラウンドで開く
            if (num && checked) {
                parent.kakaku.open_tab(parts_type, item_id, item['ItemPageUrl'], true);
            }
        }
    } else {
        $("#parts_" + item_id).remove();
    }
    update_total();
}

/**
 * 個数変更
 */
function select_num(parts_type, item_id) {
    var curval = parseInt($("#n_" + parts_type + "_" + item_id).text());
    var select = document.createElement("select");
    select.className = "item_num_select";
    select.id = "num_select_" + parts_type + "_" + item_id;
    var option = document.createElement("option");
    var value = 1;
    option.value = curval;
    option.innerHTML = "個数を選択";
    select.appendChild(option);
    for (var i = 0; i < 10; i++) {
        var option = document.createElement("option");
        var value = i + 1;
        option.value = value;
        option.innerHTML = value + "個";
        if (value == curval) {
            option.selected = true;
        }
        select.appendChild(option);
    }
    select.onchange = function() {
        var newval = select.options[select.selectedIndex].value;
        $("#n_" + parts_type + "_" + item_id).html(newval + "個");
        $(this).remove();
        $("#nchange_" + parts_type + "_" + item_id).show();
        update_total();
    }
    select.onblur = select.onchange;
    $("#nchange_" + parts_type + "_" + item_id).after(select);
    $("#nchange_" + parts_type + "_" + item_id).hide();
}

/**
 * 合計金額の更新
 */
function update_total() {
    calc();
    update_calcurl();
    update_copipe();
    // Finish restore
    if (nowrestoring && queue_item_request.length == 0) {
        restore_calcurl_done();
        nowrestoring = false;
    }
}

/**
 * 再計算
 */
function calc() {
    var total = 0;
    $("#calculator .parts_select").each(function(i){
        var price_obj = $("#price_" + this.id.replace(/^p_/, ""));
        var price = get_int($("#" + this.id + "_price").val());
        var num = get_int($("#n_" + this.id.replace(/^p_/, "")).text());
        if ($(this).attr("checked")) {
            total += price * num;
        }
        price_obj.text(add_comma(price * num) + "円");
        price_obj.next(".subtotal").remove();
        if (num > 1) {
            price_obj.after('<span class="subtotal">(' + add_comma(price) + "円 x " + num + ')</span>');
        }
    });
    $("#total_price").html(add_comma(total) + "円 -" + get_today());
}

/**
 * 保存用URLの更新
 */
function update_calcurl() {
    var calc_options = $("#form_calc").serialize();
    // 個数情報
    $("#calculator .parts_select").each(function(i){
        var num = get_int($("#n_" + this.id.replace(/^p_/, "")).text());
        var item_id = $(this).val();
        if (num > 1) {
            calc_options = calc_options.replace(item_id, item_id + "%2c" + num);
        }
    });
    calc_options = calc_options.replace(/=/g, "-");
    calc_options = calc_options.replace(/&/g, "_");
    var url = parent.topurl + "?calcurl=" + calc_options;
    $("#calcurl_link").attr("href", url);
    $("#calcurl_link").html("価D安自作PC(" + $("#total_price").html() + ")");
    $("#calcurl").val(url);
    $("#calcreset_link").css("display", "inline");
}

/**
 * コピペフォームの更新
 */
function update_copipe() {
    var text = "**** My 価D安自作PC ***\n";
    $("#calculator .parts_select").each(function(i){
        if (!$(this).attr("checked")) {
            return;
        }
        var parts_type = get_int(this.id.substring(2, 4));
        var parts_type_name = $("#parts_type_" + parts_type).text();
        var name = $("#" + this.id + "_image").attr('alt');
        var price = $("#price_" + this.id.replace(/^p_/, "")).text();
        var num = get_int($("#n_" + this.id.replace(/^p_/, "")).text());
        text += "・" + parts_type_name + "：" + name + " (" + price + ")";
        if (num > 1) {
            text += " x" + num;
        }
        text += "\n";
    });
    text += "------------------------------------------------\n";
    text += "合計金額：" + $("#total_price").text() + "\n";
    text += "URL：" + $("#calcurl").val() + "\n";
    text += "※金額は価格.comでの最安値です。\n";
    $("#copipe").val(text);
}

function get_today() {
    var now = new Date();
    var today = "<span class=\"today_date\">" + now.getFullYear() + "年" + (now.getMonth() + 1) + "月" + now.getDate() + "日現在</span>"
    return today;
}

/**
 * 保存用URLを元に初期化
 */
function restore_calcurl() {
    var calcurl = parent.location.href;
    if ($("#calcurl").val() != "") {
        calcurl = $("#calcurl").val();
    }
    if (!calcurl || calcurl.indexOf("=") == -1) {
        return;
    }
    calcurl = calcurl.substring(calcurl.indexOf("=") + 1);
    var options_array = calcurl.split("_");
    var all_items = {};
    for (var i = 0; i < options_array.length; i ++) {
        options_array[i] = unescape(options_array[i]);
        var matches = options_array[i].match(/^(p)(\d+)-(\d+)(,(\d+))?/);
        if (matches) {
            var param_key = matches[1];
            if (param_key == 'p') {
                nowrestoring = true;
                var num = matches[5] ? matches[5] : 1;
                add_item(matches[2], matches[3], num, true);
            }
        }
    }
}

/**
 * 保存用URLの初期化終了
 */
function restore_calcurl_done() {
    frameopen(null, "calc");
}

/**
 * 数値文字列のフォーマット
 */
function add_comma(num) {
    return num.toString().replace(/([\d]+?)(?=(?:\d{3})+$)/g, function (t) { return t+","; });
}

/**
 * 数値文字列から数値を取り出し
 */
function get_int(str) {
    return parseInt(str.replace(/[^\d]/g, ''));
}

/**
 * Array#indexOf
 */
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(object) {
        for (var i = 0, length = this.length; i < length; i++)
          if (this[i] == object) return i;
        return -1;
    }
}
