/**
 * 親ブロックの幅が770px以外でもレイアウトが
 * 崩れないようにサイズを調整します。
 */
//(function () {
//    var container = $("script:last").parents("div:first");
//    container.ready(function () {
//        var innerBlock = $("div.inner", container);
//        $("div.infoContents", innerBlock).width(innerBlock.width() - $("div.photoContents", innerBlock).width());
//        var infoColmnWidth = innerBlock.width() - 410;
//        var dataColmnWidth = innerBlock.width() - 500;
//        $("div.box01 ul.spec li p span.data", innerBlock).width(dataColmnWidth);
//        var type3 = $("div.box01 input.type03", innerBlock);
//        console.log(type3.outerWidth({margin:true}));
//        if (infoColmnWidth < type3.outerWidth({margin:true})) {
//            type3.outerWidth(infoColmnWidth);
//        }
//        console.log([innerBlock.width(), infoColmnWidth, dataColmnWidth]);
//    });
//})();

var arrStockNum = new Array();
var arrStockFg = new Array();
var strStockNum;
var strStockFg;
var strVariationGoodsId;
var strVariation1;
var strVariation2;
var strVariation3;
var strVariationFg;
var intNo;
window.onload = function() {
    if (document.getElementById("hidVariationFg")) {
        jQuery("#itemDetail01 .photoContents .mainPhoto p.photo").each( function() {
            var thumb = jQuery(this).find("img");
            var imgWidth = thumb.width()/2;
            var thisPadding = (190-imgWidth);
            jQuery("#itemDetail01 #wrap").css({marginLeft:thisPadding});
        });

        strVariationFg = getValue("hidVariationFg");
        if (strVariationFg >= "1") {
            strVariationGoodsId = "";
            strVariation1 = "";
            if (strVariationFg >= "2") {
                strVariation2 = "";
                if (strVariationFg == "3") {
                    strVariation3 = "";
                }
            }
        }

        jQuery("a[rel^='gallery']").prettyPhoto({
            animationSpeed:"fast",
            allow_resize:false,
            overlay_gallery:true,
            autoplay_slideshow: false
        });
        jQuery("a[rel^='prettyPhoto']").prettyPhoto({
            animationSpeed:"fast",
            show_title:false,
            allow_resize:false,
            modal: true,
            overlay_gallery: false,
            showcallback: function() {
                jQuery("a.close").click( function() {
                    jQuery.prettyPhoto.close();
                    return false;
                });
                jQuery(".pp_content").jqTransform();
            }
        });
    }

    //購入数量のテキストボックスにキーイベント付加(購入数量欄でのEnter押下対応
    $("#txtBuyNum").keypress(
        function(e){
            return app_enterByNum(e);
        }
    );

    //購入数量を持つFormをsubmit禁止にする(購入数量欄でのEnter押下対応
    $("#goodsItemVeiwForm").submit(function(e){return false;});

    //購入数量からフォーカスが外れた時に、前0除外と全角数字を半角数字に変換する処理をバインド
    $("#txtBuyNum").blur(
        function(e){
            setValue("txtBuyNum", zeroShift(zenToHan(getValue("txtBuyNum"))));
            return true;
        }
    );

};

//Powered By Yahoo ロゴ表示
$(document).ready(function(){
    var strUrl = getHost() + "/common/yahooshopping/getlogo/";
    $.get(strUrl,app_showYahooLogo);
});

function app_showYahooLogo(data){
    if(data != null && data != ""){
        $("#page_block3").find('div:first').before(data);
    }
}

function app_showStockNum() {
}

//レビュー表示
function app_showGoodsReviewView() {
    var strUrl = getHost() + "/app/goodsReviewView/index/GoodsId/" + getValue("hidGoodsId");
    window.open(strUrl);
}

//ブログ表示
function app_showGoodsBlog(strHashtag, strMessage) {
    var strUrl = "http://twitter.com/intent/tweet?hashtags="+strHashtag+"&text="+strMessage+" "+$("#hidUrl").val();
    window.open(strUrl);
}

//この商品について問い合わせる
function app_showInqForm() {
    var strUrl = getHost() + "/app/goodsInquiryEdit/index";
    ajaxRequest(strUrl, {"hidGoodsId": getValue("hidGoodsId"), "hidGoodsCode": getValue("hidGoodsCode"), "hidGoodsName":getValue("hidGoodsName")
    }, showInqFormCallback);
}

function showInqFormCallback(data) {
     $("#inqFormDialog").remove();
     jQuery(document.createElement('div')).html(data.html).attr("id","inqFormDialog").appendTo('body').hide();
     var title = data.Title;
     JdialogForUrl('inqFormDialog',title,'900','900',1);
}

//友達にメールですすめる
function app_showTellFriend() {
    var strUrl = getHost() + "/app/Goodsintroduceedit/index";
    ajaxRequest(strUrl, {"hidGoodsId": getValue("hidGoodsId"), "hidGoodsCode": getValue("hidGoodsCode"), "hidGoodsName":getValue("hidGoodsName")}, showTellFriendCallback);
}

//友達に教える
function showTellFriendCallback(data) {
    $("#tellFirendDialog").remove();
    jQuery(document.createElement('div')).html(data.html).attr("id","tellFirendDialog").attr("align","left").appendTo('body').hide();
    var title = data.Title;
    JdialogForUrl('tellFirendDialog',title,'750','600',1);
}

//この商品のURLを携帯に送る
function app_showSendMobileForm() {
    var strUrl = getHost() + "/app/mailToMobileEdit/index";
    ajaxRequest(strUrl, {"hidGoodsId": getValue("hidGoodsId"), "hidGoodsCode": getValue("hidGoodsCode"), "hidGoodsName":getValue("hidGoodsName")}, showSendMobileCallback);
}

//この商品のURLを携帯に送るcallback
function showSendMobileCallback(data) {
    $("#sendMobileDialog").remove();
    jQuery(document.createElement('div')).html(data.html).attr("id","sendMobileDialog").appendTo('body').hide();
    initSelectable("selMobileDomain", null,"120px");
    var title = data.Title;
    JdialogForUrl('sendMobileDialog',title,'900','900',1);
}

//再入荷通知
function app_showRearrivalNoticeEdit() {
    app_clearErrorMsg();
    var arrMessage = new Array();
    var arrMsg = new Array();
    //var strUrl = getHost() + "/app/rearrivalNoticeEdit/index/GoodsId/" + getValue("hidGoodsId");
    var strUrl = getHost() + "/app/rearrivalNoticeEdit/index";
    var $blnFlag = true;
    if (!document.getElementById("hidRearrivalFg")) {
        if (strVariationFg != "0" && strVariationGoodsId == "") {
            if((getValue("hidSumStockFg") == 1 && getValue("hidStockFg") == 1)
                || (getValue("hidStockFg") == 0 && getValue("hidStockNum") != 0)) {
                arrMessage[0] = getMessage("ERR-100718");
                app_setErrorMsg(arrMessage);
                return;
            }

            if (strVariation1 == "" || strVariation1 == null) {
                arrMessage[0] = getMessage("ERR-100715");
                app_setErrorMsg(arrMessage);
                return;
            } else {
                if (strVariationFg >= "2" && strVariation2 == "") {
                    arrMessage[0] = getMessage("ERR-100715");
                    app_setErrorMsg(arrMessage);
                    return;
                } else if (strVariationFg == "3" && strVariation3 == "") {
                    arrMessage[0] = getMessage("ERR-100715");
                    app_setErrorMsg(arrMessage);
                    return;
                }

            }
        } else {
            if (getValue("hidSumStockFg") == "0") {
                if (strStockFg == "0") {
                    if (strStockNum == "0" || strStockNum == "×") {
                        $blnFlag = false;
                    } else {
                        if (getValue("hidLimitFg") == "1" && parseInt(getValue("hidLimitMin")) > parseInt(arrStockNum[intNo].replace(/,/g,""))) {
                            $blnFlag = false;
                        }
                    }
                }
            } else {
                if (getValue("hidStockFg") == "0" && getValue("hidStockNum") == "0") {
                    $blnFlag = false;
                } else {
                    if (getValue("hidLimitFg") == "1" && parseInt(getValue("hidLimitMin")) > parseInt(getValue("hidStockNum").replace(/,/g,""))) {
                        $blnFlag = false;
                    }
                }
            }
        }
    } else {
        $blnFlag = false;
    }
    if ($blnFlag) {
        var arrMessage = new Array();
        strMessage = getMessage("ERR-100718");
        if (strVariationFg != "0") {
            arrMessage[0] = getValue("app_EC0067_VariationUnion");
        } else {
            arrMessage[0] = "";
        }
        arrMessage[0] = String.format(strMessage, arrMessage[0]);
        app_setErrorMsg(arrMessage);
        return;
    }
    ajaxRequest(strUrl, {"GoodsId"                    : getValue("hidGoodsId"),
                         "VariationGoodsId"           : strVariationGoodsId},
                         showRearrivalNoticeCallback);
    /*
    if (strVariationFg != "0") {
        strUrl = strUrl + "/VariationGoodsId/" + strVariationGoodsId;
    }
    showDialog(strUrl, "-1", "-1", "950px", "750px","yes", "no", "no", "yes");
    */
}

// 再入荷通知のコールバック
function showRearrivalNoticeCallback(data) {
    $("#rearrivalNotice").remove();
    jQuery(document.createElement('div')).html(data.html).attr("id","rearrivalNotice").attr("align","left").appendTo('body').hide();
    var title = data.Title;
    JdialogForUrl('rearrivalNotice',title,'950','910',1);
}

//カートに入れる
function app_cart() {
    app_clearErrorMsg();
    var strUrl = getHost() + "/app/goodsItemsView/cart";

    if (app_dataCheck()) {
        if (strVariationFg != "0") {
            setValue("hidVariationGoodsId", strVariationGoodsId);
        }

        ajaxRequest(strUrl, {
            "hidVariationGoodsId"   : getValue("hidVariationGoodsId"),
            "hidGoodsId"            : getValue("hidGoodsId"),
            "txtBuyNum"             : getValue("txtBuyNum"),
            "hidVariationFg"        : getValue("hidVariationFg"),
            "hidVariationGoodsId"   : getValue("hidVariationGoodsId"),
            "hidVariation1Name"     : getValue("hidVariation1Name"),
            "selVariation1"         : getValue("selVariation1"),
            "hidVariation2Name"     : getValue("hidVariation2Name"),
            "selVariation2"         : getValue("selVariation2"),
            "hidVariation3Name"     : getValue("hidVariation3Name"),
            "selVariation3"         : getValue("selVariation3"),
            "hidMemo1"              : getValue("hidMemo1"),
            "txtMemo1"              : getValue("txtMemo1"),
            "Memo1"                 : getValue("Memo1"),
            "hidMemo2"              : getValue("hidMemo2"),
            "txtMemo2"              : getValue("txtMemo2"),
            "Memo2"                 : getValue("Memo2"),
            "hidMemo3"              : getValue("hidMemo3"),
            "txtMemo3"              : getValue("txtMemo3"),
            "Memo3"                 : getValue("Memo3"),
            "hidGoodsName"          : getValue("hidGoodsName"),
            "hidStockNum"           : getValue("hidStockNum")
        }, appCartCallback);
    }
}

//カートに入れるcallback
function appCartCallback(data) {
    if (null != data && data.msg == "success") {
        $("#TokenKey").val(data.TokenKey);
        $("#GoodsInfo").val(data.strGoodsInfo);
        document.cartForm.action = data.strCartUrl;
        document.cartForm.submit();
    } else if(null != data && data.msg != "success") {
        var goodsName = getValue("hidGoodsName");
        for(var i = 0; i < data.msg.length; i++){
            if(data.msg[i].match("の購入数は、") && !data.msg[i].match(goodsName)){
                data.msg[i] = data.msg[i].replace("ERR-", "");
                data.msg[i] = goodsName + data.msg[i];
             }
        }
        app_setErrorMsg(data.msg);
    } else {
        return;
    }
}

//カートに入れる時のデータチェック
function app_dataCheck() {
    var arrMsg = new Array();
    var arrLabel = new Array();
    var arrMessage = new Array();
    var strMessage = "";
    var TEXT_MAX = 128;
    var BUY_MAX = 99999;
    var blnChkContinue = true;

    //購入数量の値から前の0を除外し全角数字を半角に変換
    setValue("txtBuyNum", zeroShift(zenToHan(getValue("txtBuyNum"))));

    if (document.getElementById("txtMemo1")) {
        updateTrim("txtMemo1");
        arrLabel = chkMaxLength("txtMemo1", TEXT_MAX);
        if (!arrLabel[0]) {
            strMessage = getMessage(arrLabel[1]);
            arrMessage[0] = getValue("hidMemo1");
            arrMsg[arrMsg.length] = String.format(strMessage, arrMessage[0], TEXT_MAX);
        }
    }
    if (document.getElementById("txtMemo2")) {
        updateTrim("txtMemo2");
        arrLabel = chkMaxLength("txtMemo2", TEXT_MAX);
        if (!arrLabel[0]) {
            strMessage = getMessage(arrLabel[1]);
            arrMessage[0] = getValue("hidMemo2");
            arrMsg[arrMsg.length] = String.format(strMessage, arrMessage[0], TEXT_MAX);
        }
    }
    if (document.getElementById("txtMemo3")) {
        updateTrim("txtMemo3");
        arrLabel = chkMaxLength("txtMemo3", TEXT_MAX);
        if (!arrLabel[0]) {
            strMessage = getMessage(arrLabel[1]);
            arrMessage[0] = getValue("hidMemo3");
            arrMsg[arrMsg.length] = String.format(strMessage, arrMessage[0], TEXT_MAX);
        }
    }
    if (strVariationFg != "0" && strVariationGoodsId == "") {
        if (strVariation1 == "") {
            strMessage = getMessage("ERR-100715");
            arrMessage[0] = getValue("hidVariation1Name");
            arrMsg[arrMsg.length] = String.format(strMessage, arrMessage[0]);
        } else {
            if (strVariationFg >= "2" && strVariation2 == "") {
                strMessage = getMessage("ERR-100715");
                arrMessage[0] = getValue("hidVariation2Name");
                arrMsg[arrMsg.length] = String.format(strMessage, arrMessage[0]);
            } else if (strVariationFg == "3" && strVariation3 == "") {
                strMessage = getMessage("ERR-100715");
                arrMessage[0] = getValue("hidVariation3Name");
                arrMsg[arrMsg.length] = String.format(strMessage, arrMessage[0]);
            }
        }
    }
    updateTrim("txtBuyNum");
    arrLabel = chkBlank("txtBuyNum");
    if (!arrLabel[0]) {
        strMessage = getMessage(arrLabel[1]);
        arrMessage[0] = getLabel("app_EC0067_Purchase");
        arrMsg[arrMsg.length] = String.format(strMessage, arrMessage[0]);
        blnChkContinue = false;
    } else {
        arrLabel = chkInt("txtBuyNum");
        if (!arrLabel[0]) {
            strMessage = getMessage("ERR-100009");
            arrMessage[0] = getLabel("app_EC0067_Purchase");
            arrMsg[arrMsg.length] = String.format(strMessage, arrMessage[0]);
            blnChkContinue = false;
        }
    }
    if (arrMsg.length > 0) {
        app_setErrorMsg(arrMsg);
        return false;
    } else {
        return true;
    }
}

//非ログイン時のカートに入れる エラーメッセージ
function nologin_cart() {
    var arrMsg = new Array();
    arrMsg[0] = getMessage("ERR-100808");
    app_setErrorMsg(arrMsg);
    return false;
}

//エラーメッセージ表示
function app_setErrorMsg(arrMsg) {
    window.location="#msgTop";
    app_clearErrorMsg();
    setErrorMsg(arrMsg, 600, "errorMsgDiv");
    document.getElementById("errorMsgBox").style.display = "block";
}

//エラーメッセージ欄クリア
function app_clearErrorMsg() {
    document.getElementById("errorMsgBox").style.display = "none";
    setInnerHTML("errorMsgDiv", "");
}

//購入数欄でenterキー押下時
function app_enterByNum(e){
  //キーコードチェック
  if(e.keyCode == 13){
      //enterキーならカートに入れるボタンの処理を呼ぶ
      app_cart();
  }
  return true;
}


////////////////////////////////////////////////////////////////////////////////
/// バリエーション関連クラス
////////////////////////////////////////////////////////////////////////////////
/**
 * バリエーションのオプション状態クラス
 */
function RookOptionStatus() {
    this.firstOptionId;
    this.secondOptionId;
    this.thirdOptionId;
};

/** Setter */
RookOptionStatus.prototype.set = function (props) {
    for (var key in props) this[key] = props[key];
    return this;
};

/** Clear */
RookOptionStatus.prototype.clear = function () {
    this.firstOptionId = "";
    this.secondOptionId = "";
    this.thirdOptionId = "";
    return this;
};

/**
 * 前回読み込んだ時のパラメータと比較して、再度読み込みが必要か
 * 判断します。
 */
RookOptionStatus.prototype.isRead = function (props) {
    var count = 0;
    for (var key in props) {
        /// 自分にあるものだけチェック
        if (!this[key] || this[key] == "") continue;
        count++;
        /// 変わったので読みにいかなければ…
        if (this[key] != props[key]) return true;
    }
    if (count <= 0) return true;
    return false;
};

/**
 * 連想配列を「=」と「&」で繋いだ文字列にして返します。
 * @param map 連想配列
 * @returns 「=」と「&」で繋いだ文字列
 */
function toQueryStrings(map) {
    var qs = [];
    for (var key in map) qs.push(key + "=" + map[key]);
    return qs.join("&");
}

/**
 * バリエーションのオプション選択クラス
 */
function RookOptionSelector() {
    this.goodsId;
    this.variationGoodsId;
    this.firstOptionId;
    this.secondOptionId;
    this.thirdOptionId;
    this.isExec;
    this.data;
    this.firstSelector;
    this.secondSelector;
    this.thirdSelector;
    this.variationCount;///バリエーション種類数
    this.stockIndicator;

    /// 前回のパラメータ
    this.readStatus = new RookOptionStatus();
    /// 価格とか在庫数
    this.information = new RookGoodsInformation();
    /// 最初に表示したときの値
    this.defaultInformation;
    /// 表示チェック
    this.checkDisp = {
            sale: false,
            member: false,
            market: false,
            stock: false
    };
}

/**
 * オプションをいくつ選択するとデータを読みにいくか
 * 例）
 * たとえば「3」だとバリ１＆バリ２＆バリ３を全部指定した時
 * バリ１＆バリ２しか登録していない場合はバリ１＆バリ２を指定した時
 * バリ１しか登録していない場合はバリ１を指定した時
 */
RookOptionSelector.VARIATION_COUNT = 1;

/** 簡易Setter */
RookOptionSelector.prototype.set = function (props) {
    for (var key in props) this[key] = props[key];
    return this;
};

/**
 * セレクタの値を読み取ってパラメータを作成します。
 */
RookOptionSelector.prototype.setParameter = function () {
    var count = 0;
    var keys = ["firstOptionId", "secondOptionId", "thirdOptionId"];
    var checkMap = {};/// チェック用
    /// 値が有効か（NULL＆空文字チェック）
    for (var i = 0, ilen = keys.length; i < ilen; i++) {
        if (this[keys[i]] && this[keys[i]] != "") {
            checkMap[keys[i]] = this[keys[i]];
            count++;
        }
    }
    /// 何一つなければ元の値に戻すために
    /// データクリア、読み込み情報クリア
    if (count <= this.variationCount - 1) {
        this.data["data"] = [];
        this.readStatus.clear();
        this.getInformetion();
        return null;
    }
    /// パラメータ作成
    var parameterMap = {};
    var mapCount = 0;
    for (var i = 0, ilen = keys.length; i < ilen; i++) {
    	/// NULL＆空文字チェック
        if (!this.readStatus[keys[i]] || this.readStatus[keys[i]] == "") continue;
        /// 現在データの状態（条件）と選択値を比較
        if (this.readStatus[keys[i]] == checkMap[keys[i]]) {
            parameterMap[keys[i]] = checkMap[keys[i]];
            mapCount++;
            if (mapCount >= this.variationCount)
                return parameterMap;
        }
    }
    if (mapCount < this.variationCount) {
        for (var i = 0, ilen = keys.length; i < ilen; i++) {
            if (!parameterMap[keys[i]] && checkMap[keys[i]]) {
                parameterMap[keys[i]] = checkMap[keys[i]]
                mapCount++;
                if (mapCount >= this.variationCount)
                    return parameterMap;
            }
        }
    }
    return parameterMap;
};

/**
 * 非同期でバリエーションのデータを取得します。
 * 第一オプション単位でデータを取得します。
 */
RookOptionSelector.prototype.getData = function () {
//    if (!this.isExec) return;

    var parameterMap = this.setParameter();

    /// オプション数が足りない
    if (!parameterMap) return;

    if (!this.readStatus.isRead(parameterMap)) {
        this.getInformetion();
        return;
    }
    this.readStatus.clear();
    this.readStatus.set(parameterMap);

    var that = this;
    parameterMap["goodsId"] = this.goodsId;
    ajaxRequest(
//        getHost() + "/page/stockList/detail?" + toQueryStrings(parameterMap),
        getHost() + "/page/stockList/detail",
        parameterMap,
        function (data) {
            that.data = data;
            that.stockIndicator = RookOptionSelector.getStockIndicator(data["isMark"]);
            that.getInformetion();
//console.log("LENGTH: " + data.data.length);
        }
    );
};

/**
 * 初期化処理
 * ・イベントハンドラ
 * ・表示要素のチェック
 * ・各価格の初期値を保存
 */
RookOptionSelector.prototype.initialize = function () {
    this.bindHandlers();

    if (this.variationCount > RookOptionSelector.VARIATION_COUNT)
        this.variationCount = RookOptionSelector.VARIATION_COUNT;

    this.checkDisp.sale   = jQuery("#spnSalesPrice1" ).size() > 0;
    this.checkDisp.member = jQuery("#spnMemberPrice1").size() > 0;
    this.checkDisp.market = jQuery("#spnMarketPrice1").size() > 0;
    this.checkDisp.stock  = jQuery("#spnStockButton1").size() > 0;

    /// 一つでもtrueなら実行
    this.isExec = this.checkDisp.sale
               || this.checkDisp.member
               || this.checkDisp.market
               || this.checkDisp.stock;

    this.defaultInformation = new RookGoodsInformation().set({
        count             : 0,
        salePrice         : removePriceFormat(jQuery("#spnSalesPrice1  span.price").text()),
        higherSalePrice   : removePriceFormat(jQuery("#spnSalesPrice2  span.price").text()),
        memberPrice       : removePriceFormat(jQuery("#spnMemberPrice1 span.price").text()),
        higherMemberPrice : removePriceFormat(jQuery("#spnMemberPrice2 span.price").text()),
        marketPrice       : removePriceFormat(jQuery("#spnMarketPrice1 span.price").text()),
        higherMarketPrice : removePriceFormat(jQuery("#spnMarketPrice2 span.price").text()),
        hasAlwaysStock    : false,
        stockNumber       : -1,
        checkDisp         : this.checkDisp
    });
    this.information.set({checkDisp : this.checkDisp});
//    console.log(this.defaultInformation);
};

/**
 * セレクタにイベントハンドラを登録します。
 */
RookOptionSelector.prototype.bindHandlers = function () {
    var that = this;
    var count = 0;
    if (jQuery(this.firstSelector).size() > 0) {
        jQuery(this.firstSelector).change(function (evt) {
            that.firstOptionId = this.value;
            strVariation1 = this.value;//元からある関数向け
            that.getData();
        });
        count++;
    }
    if (jQuery(this.secondSelector).size() > 0) {
        jQuery(this.secondSelector).change(function (evt) {
            that.secondOptionId = this.value;
            strVariation2 = this.value;//元からある関数向け
            that.getData();
        });
        count++;
    }
    if (jQuery(this.thirdSelector).size() > 0) {
        jQuery(this.thirdSelector).change(function (evt) {
            that.thirdOptionId = this.value;
            strVariation3 = this.value;//元からある関数向け
            that.getData();
        });
        count++;
    }
    this.variationCount = count;
};

/**
 * 各価格と在庫数を取得します。
 */
RookOptionSelector.prototype.getInformetion = function () {
    if (this.data.data.length > 0) {
        this.information.setInformetion(
                this.data.data, this.firstOptionId, this.secondOptionId, this.thirdOptionId);
    } else {
        this.information.set(this.defaultInformation);
    }
    this.dispInformation();
    return this;
};

/**
 * 各価格と在庫数を表示します。
 * 表示されている要素をチェックして書き込みます。
 */
RookOptionSelector.prototype.dispInformation = function () {
    if (this.checkDisp.sale) {
        jQuery("#spnSalesPrice1 span.price" ).text(
                toPriceFormat(this.information.salePrice));
        if (this.information.higherSalePrice >= 0) {
            jQuery("#spnSalesPrice2 span.price" ).text(
                    toPriceFormat(this.information.higherSalePrice));
            jQuery("#spnSalesPrice2" ).show();
        } else {
            jQuery("#spnSalesPrice2" ).hide();
        }
    }

    if (this.checkDisp.member) {
        jQuery("#spnMemberPrice1 span.price").text(
                toPriceFormat(this.information.memberPrice));
        if (this.information.higherMemberPrice >= 0) {
            jQuery("#spnMemberPrice2 span.price").text(
                    toPriceFormat(this.information.higherMemberPrice));
            jQuery("#spnMemberPrice2").show();
        } else {
            jQuery("#spnMemberPrice2").hide();
        }
    }

    if (this.checkDisp.market) {
        jQuery("#spnMarketPrice1 span.price").text(
                toPriceFormat(this.information.marketPrice));
        if (this.information.higherMarketPrice >= 0) {
            jQuery("#spnMarketPrice2 span.price").text(
                    toPriceFormat(this.information.higherMarketPrice));
            jQuery("#spnMarketPrice2").show();
        } else {
            jQuery("#spnMarketPrice2").hide();
        }
    }

    strStockNum = this.information.stockNumber;
    strStockFg = this.information.hasAlwaysStock ? "1" : "0";
    if (this.checkDisp.stock) {
        var stockNumber = this.stockIndicator.indicate(this.information);
        if (this.information.hasAlwaysStock || this.information.stockNumber > 0) {
            jQuery("#pCart").show();
            jQuery("#imgNoStock").hide();
        } else if (this.information.stockNumber == 0) {
            jQuery("#pCart").hide();
            jQuery("#imgNoStock").show();
        } else {
            jQuery("#pCart").show();
            jQuery("#imgNoStock").hide();
            stockNumber = "";
        }
        jQuery("#spnStockButton1").text(stockNumber);
    }

    if (this.information.count == 1) {
        strVariationGoodsId = this.information.variationGoodsId;
    } else {
        strVariationGoodsId = "";
    }
//console.log(this);
};

/**
 * シンプルファクトリ
 */
RookOptionSelector.getStockIndicator = function (isMark, lowLimitNumber) {
    if (isMark) {
        return new RookDetailStockMarkIndicator(lowLimitNumber);
    } else {
        return new RookDetailStockNumberIndicator(lowLimitNumber);
    }
    return null;
};

////////////////////////////////////////////////////////////////////////////////
/// 各価格と在庫数のクラス
/**
 * 各価格と在庫数のクラス
 */
function RookGoodsInformation() {
    this.count;
    this.variationGoodsId;
    this.salePrice;
    this.higherSalePrice;
    this.memberPrice;
    this.higherMemberPrice;
    this.marketPrice;
    this.higherMarketPrice;
    this.hasAlwaysStock;
    this.stockNumber;
    this.noticeStockNumber;
    this.checkDisp;
}

/** 簡易Setter */
RookGoodsInformation.prototype.set = function (props) {
    for (var key in props) {
        this[key] = props[key];
    }
    return this;
};

/**
 * データから各価格の最低値、最高値、在庫数などをセットします。
 */
RookGoodsInformation.prototype.setInformetion = function (data, op1, op2, op3) {
//    console.log([data.length, op1, op2, op3]);
    this.count = 0
    this.salePrice = Number.MAX_VALUE;
    this.higherSalePrice = -1;
    this.memberPrice = Number.MAX_VALUE;
    this.higherMemberPrice = -1;
    this.marketPrice = Number.MAX_VALUE;
    this.higherMarketPrice = -1;
    this.hasAlwaysStock = false;
    this.stockNumber = -1;
    this.noticeStockNumber = -1;
    /// 各オプションIDの有無で条件関数を取得する。
    var isTarget = this.getCondition(op1, op2, op3);
    for (var i = 0, ilen = data.length; i < ilen ;i++) {
        var d = data[i];
        if (isTarget(d)) {
            if (this.checkDisp.sale) {
                var sale = parseInt(d.SALE_PRICE, 10);
                if (this.salePrice > sale)           this.salePrice         = sale;
                if (this.higherSalePrice < sale)     this.higherSalePrice   = sale;
            }
            if (this.checkDisp.member) {
                var member = parseInt(d.MEMBER_PRICE, 10);
                if (this.memberPrice > member)       this.memberPrice       = member;
                if (this.higherMemberPrice < member) this.higherMemberPrice = member;
            }
            if (this.checkDisp.market) {
                var market = parseInt(d.MARKET_PRICE, 10);
                if (this.marketPrice > market)       this.marketPrice       = market;
                if (this.higherMarketPrice < market) this.higherMarketPrice = market;
            }
            if (this.checkDisp.stock) {
                if (d.ALWAYS_STOCK_FG == "1") {
                    this.hasAlwaysStock = true;
                } else {
                    var stock = parseInt(d.STOCK_NUM, 10);
                    if (this.stockNumber < stock) this.stockNumber = stock;
                }
            }
            if (this.count == 0) {
                this.variationGoodsId = d.VARIATION_GOODS_ID;
                this.noticeStockNumber = d.NOTICE_STOCK_NUM;
            }
            this.count++;
        }
    }
    /// 最低と最高が同じなら最高を表示しないように目印をつける
    if (this.marketPrice == this.higherMarketPrice) this.higherMarketPrice = -1;
    if (this.memberPrice == this.higherMemberPrice) this.higherMemberPrice = -1;
    if (this.salePrice == this.higherSalePrice) this.higherSalePrice = -1;

    return this;
};

/**
 * データ検索の条件関数（クロージャ）を返します。
 * 各オプションIDの有無で条件が変わります。
 */
RookGoodsInformation.prototype.getCondition = function (op1, op2, op3) {
    if (op1) {
        if (op2) {
            if (op3) {
                return function (d) {return op1 == d.VARIATION1_OPTION_ID && op2 == d.VARIATION2_OPTION_ID && op3 == d.VARIATION3_OPTION_ID;};
            } else {
                return function (d) {return op1 == d.VARIATION1_OPTION_ID && op2 == d.VARIATION2_OPTION_ID;};
            }
        } else {
            if (op3) {
                return function (d) {return op1 == d.VARIATION1_OPTION_ID && op3 == d.VARIATION3_OPTION_ID;};
            } else {
                return function (d) {return op1 == d.VARIATION1_OPTION_ID;};
            }
        }
    } else {
        if (op2) {
            if (op3) {
                return function (d) {return op2 == d.VARIATION2_OPTION_ID && op3 == d.VARIATION3_OPTION_ID;};
            } else {
                return function (d) {return op2 == d.VARIATION2_OPTION_ID;};
            }
        } else {
            if (op3) {
                return function (d) {return op3 == d.VARIATION3_OPTION_ID;};
            } else {
                return function (d) {return true;};
            }
        }
    }
    return function (d) {return false;};
};

////////////////////////////////////////////////////////////////////////////////
/// 在庫数表示クラス
////////////////////////////////////////////////////////////////////////////////
/** インターフェース */
function RookDetailStockIndicator() {}
/** 在庫数や在庫の状況を表示します */
RookDetailStockIndicator.prototype.indicate = function (sn) {return -1};
////////////////////////////////////////////////////////////////////////////////
/**
* 基本的に数値を表示します。
*/
function RookDetailStockNumberIndicator() {
  this.base = RookDetailStockIndicator;
}
RookDetailStockNumberIndicator.prototype = new RookDetailStockIndicator;
RookDetailStockNumberIndicator.ALWAYS_HAS_STOCK   = "在庫あり";
RookDetailStockNumberIndicator.prototype.indicate = function (sn) {
    if (sn.hasAlwaysStock) return RookDetailStockNumberIndicator.ALWAYS_HAS_STOCK;
    if (sn.count > 1) {///まだ商品が一つに定まっていない
        if (sn.stockNumber <= 0) return "0";
        return RookDetailStockNumberIndicator.ALWAYS_HAS_STOCK;
    }
    return toPriceFormat(sn.stockNumber);
};
////////////////////////////////////////////////////////////////////////////////
/**
* マークを表示します。
*/
function RookDetailStockMarkIndicator() {
  this.base = RookDetailStockIndicator;
}
RookDetailStockMarkIndicator.prototype = new RookDetailStockIndicator;
RookDetailStockMarkIndicator.MANY_STOCK_MARK = "○";
RookDetailStockMarkIndicator.FEW_STOCK_MARK  = "△";
RookDetailStockMarkIndicator.NO_STOCK_MARK   = "×";
RookDetailStockMarkIndicator.prototype.indicate = function (sn) {
    if (sn.hasAlwaysStock) return RookDetailStockMarkIndicator.MANY_STOCK_MARK;
    if (sn.count > 1) {///まだ商品が一つに定まっていない
        if (sn.stockNumber <= 0) return RookDetailStockMarkIndicator.NO_STOCK_MARK;
        return RookDetailStockMarkIndicator.MANY_STOCK_MARK;
    }
    if (sn.stockNumber <= 0) return RookDetailStockMarkIndicator.NO_STOCK_MARK;
    if (sn.stockNumber <= sn.noticeStockNumber) return RookDetailStockMarkIndicator.FEW_STOCK_MARK;
    return RookDetailStockMarkIndicator.MANY_STOCK_MARK;
};

////////////////////////////////////////////////////////////////////////////////
/// ユーティリティ関数
/**
 * 三桁ごとにカンマを挿入します。
 * @param strValue 数値に見える文字列
 * @returns 価格（金額）文字列
 */
function toPriceFormat(strValue) {
    var num = new String(new Number(strValue)).replace(/,/g, "");
    while (num != (num = num.replace(/^(-?\d+)(\d{3})/, "$1,$2")));
    return num;
};
/**
 * カンマを削除します
 * @param strValue 価格（金額）に見える文字列
 * @returns 数値
 */
function removePriceFormat(strValue) {
    var num = new String(strValue).replace(/,/g, "");
    return parseInt(num, 10);
};

/**
 * 処理開始
 */
$(document).ready(function () {
    new RookOptionSelector().set({
        goodsId: document.getElementById("hidGoodsId").value,
        firstSelector: "#selVariation1",
        secondSelector: "#selVariation2",
        thirdSelector: "#selVariation3"
    }).initialize();
});


