/***************************************

   ADMIN 用 JavaScript集

****************************************/

/***********オンロードイベント  ***********/
function onLoadEvent(actionName)
{
    //actionによって実行する処理を変更
    switch(actionName){
        case 'admin_itemmanage_item_input':
            
            break;
        case 'admin_itemmanage_moreitem_input':
            star();
            $('rank').value = 3;
            break;
    }
    
}

/***********メーカ名ドロップ関連***********/
// メーカ名頭文字ドロップダウンの変更
// 引数: makerDropId  メーカ名ドロップダウンのID
function changeMakerCapital(makerCapitalDropId, makerDropId, adult)
{
    if(typeof adult =="undefined") adult = '';
    // 選択された頭文字を取得
    capital = $(makerCapitalDropId).value;
    
    // Ajaxオブジェクト生成
    new Ajax.Request('index.php', 
                        {'method': 'get', 
                         'parameters': 'action=util_dropmaker&dropid='+makerDropId+'&capital='+capital+'&adult='+adult,
                        onException: checkException,
                        onComplete: updateMakerDrop });
}

// メーカ名ロード時
// 引数: makerDropId  メーカ名ドロップダウンのID
function loadMaker(makerDropId, makerCapitalId, makerId, adult)
{
    if(typeof adult =="undefined") adult = '';
    // Ajaxオブジェクト生成
    new Ajax.Request('index.php', 
                        {'method': 'get', 
                         'parameters': 'action=util_dropmaker' +
                                       '&dropid=' + makerDropId + 
                                       '&capital=' + makerCapitalId +
                                       '&selid=' + makerId +
                                       '&adult=' + adult,
                        onException: checkException,
                        onComplete: updateMakerDrop });
}

function checkException(req,exc)
{
//    console.log('エラー!');
//    console.log(exc);
}

function updateMakerDrop(httpResponse)
{
    //返ってきた文字列を、
    //改行文字を区切りとして配列にする
    makerArray = httpResponse.responseText.split("\n");

    //最初の１行目はメーカ名ドロップのID
    makerDropId = makerArray[0];
    
    //メーカ名ドロップの中身をクリア
    var optLength = $(makerDropId).options.length;
    for(var i = 0; i < optLength; i++){
        $(makerDropId).options[i] = null;
    }
    
    // メーカ名ドロップの Length を初期化
    $(makerDropId).options.length = 0;
    
    //メーカ名ドロップの中身を設定
    selectidx = 0;
    for(var i = 1; i < makerArray.length; i++){
        //nameとvalueに分解
        nameValueArray = makerArray[i].split(",");

        //optionを設定
        $(makerDropId).options[i - 1] = new Option(nameValueArray[1], nameValueArray[0]);

        if (nameValueArray[2]=="true") selectidx = i-1;
    }
    $(makerDropId).selectedIndex = selectidx;
}


/***********レーベル名ドロップ関連***********/
// レーベル名頭文字ドロップダウンの変更
// 引数: makerDropId  レーベル名ドロップダウンのID
function changeLabel(makerDropId, labelDropId)
{
    // 選択された頭文字を取得
    maker = $(makerDropId).value;
    
    // Ajaxオブジェクト生成
    new Ajax.Request('index.php', 
                        {'method': 'get', 
                         'parameters': 'action=util_droplabel&dropid='+labelDropId+'&makercd='+maker,
                        onException: checkException,
                        onComplete: updateLabelDrop });
}

// メーカ名ロード時
// 引数: makerDropId  メーカ名ドロップダウンのID
function loadLabel(labelDropId, makercd, labelId)
{
    // Ajaxオブジェクト生成
    new Ajax.Request('index.php', 
                        {'method': 'get', 
                         'parameters': 'action=util_droplabel' +
                                       '&dropid=' + labelDropId + 
                                       '&makercd=' + makercd +
                                       '&selid=' + labelId,
                        onException: checkException,
                        onComplete: updateLabelDrop });
}

function checkException(req,exc)
{
//    console.log('エラー!');
//    console.log(exc);
}

function updateLabelDrop(httpResponse)
{
    //返ってきた文字列を、
    //改行文字を区切りとして配列にする
    labelArray = httpResponse.responseText.split("\n");

    //最初の１行目はメーカ名ドロップのID
    labelDropId = labelArray[0];
    
    //メーカ名ドロップの中身をクリア
    var optLength = $(labelDropId).options.length;
    for(var i = 0; i < optLength; i++){
        $(labelDropId).options[i] = null;
    }
    
    //メーカ名ドロップの Length を初期化
    $(labelDropId).options.length = 0;
    
    //メーカ名ドロップの中身を設定
    selectidx = 0;
    for(var i = 1; i < labelArray.length; i++){
        //nameとvalueに分解
        nameValueArray = labelArray[i].split(",");

        //optionを設定
        $(labelDropId).options[i - 1] = new Option(nameValueArray[1], nameValueArray[0]);

        if (nameValueArray[2]=="true") selectidx = i-1;
    }
    $(labelDropId).selectedIndex = selectidx;
}


/***********シリーズ名ドロップ関連***********/
// シリーズ名頭文字ドロップダウンの変更
function changeSeries(makerDropId, seriesDropId)
{
    // 選択された頭文字を取得
    makercd = $(makerDropId).value;
    
    // Ajaxオブジェクト生成
    new Ajax.Request('index.php', 
                        {'method': 'get', 
                         'parameters': 'action=util_dropseries' +
                                       '&dropid=' + seriesDropId +
                                       '&makercd=' + makercd,
                         onException: checkException,
                         onComplete: updateSeriesDrop });
}

// シリーズ名ロード時
function loadSeries(seriesDropId, makercd, seriesId)
{
    // Ajaxオブジェクト生成
    new Ajax.Request('index.php', 
                        {'method': 'get', 
                         'parameters': 'action=util_dropseries' +
                                       '&dropid=' + seriesDropId + 
                                       '&makercd=' + makercd +
                                       '&selid=' + seriesId,
                        onException: checkException,
                        onComplete: updateLabelDrop });
}

function checkException(req,exc)
{
//    console.log('エラー!');
//    console.log(exc);
}

function updateSeriesDrop(httpResponse)
{
    //返ってきた文字列を、
    //改行文字を区切りとして配列にする
    seriesArray = httpResponse.responseText.split("\n");

    //最初の１行目はシリーズ名ドロップのID
    seriesDropId = seriesArray[0];
    
    //シリーズ名ドロップの中身をクリア
    var optLength = $(seriesDropId).options.length;
    for(var i = 0; i < optLength; i++){
        $(seriesDropId).options[i] = null;
    }
    
    //シリーズ名ドロップの Length を初期化
    $(seriesDropId).options.length = 0;
    
    //シリーズ名ドロップの中身を設定
    selectidx = 0;
    for(var i = 1; i < seriesArray.length; i++){
        //nameとvalueに分解
        nameValueArray = seriesArray[i].split(",");

        //optionを設定
        $(seriesDropId).options[i - 1] = new Option(nameValueArray[1], nameValueArray[0]);

        if (nameValueArray[2]=="true") selectidx = i-1;
    }
    $(seriesDropId).selectedIndex = selectidx;
}


/***********商品構成登録関連***********/
var structureArray = new Array();
var mediaSelectId = "media_select";
var mediaSubmitField = "media_select_submit_field";
var currentSelectIdx = 0;
function initList()
{
    //オプション項目をクリア
    var optLength = $(mediaSelectId).options.length;
    for(var i = 0; i < optLength; i++){
        $(mediaSelectId).options[i] = null;
    }
    
    // オプション項目の Length を初期化
    $(mediaSelectId).options.length = 0;
    
    idx = 0;
    for(var i = 0; i < structureArray.length; i++){
        $(mediaSelectId).options[i] = new Option('構成','01');
        idx++;
    }
        
    //新規追加項目を設定
    $(mediaSelectId).options[idx] = new Option('新規','new');
    $(mediaSelectId).selectedIndex = 0;
    $(mediaSelectId).focus();
    selectList();
}

//リストを更新する
function updateList(fromList)
{

    if(!fromList){
        idx = $(mediaSelectId).selectedIndex;
    } else {
        idx = currentSelectIdx;
    }
    
    structure = new Array();

    //フォームデータを連想配列へ格納
    stIdx = 0;
/*
    structure['media_dvd']        = $F('media_dvd');
    structure['media_vhs']        = $F('media_vhs');
    structure['hinban']           = $F('hinban');
    structure['jan_code']         = $F('jan_code');
    structure['isbn_code']        = $F('isbn_code');
    structure['sale-date']        = $F('sale-date');
    structure['sell_type_sell']   = $F('sell_type_sell');
    structure['sell_type_rental'] = $F('sell_type_rental');
    structure['content_time']     = $F('content_time');
    structure['price']            = $F('price');
    structure['bikou']            = $F('bikou');
*/
    structure[stIdx++] = ($F('media_dvd')) ? "dvd" : "vhs" ;
    structure[stIdx++] = $F('hinban');
    structure[stIdx++] = $F('jan_code');
    structure[stIdx++] = $F('isbn_code');
    structure[stIdx++] = $F('sale-date');
    structure[stIdx++] = ($F('sell_type_sell')) ? "sell" : "rental";
    structure[stIdx++] = $F('content_time');
    structure[stIdx++] = $F('price');
    structure[stIdx++] = $F('bikou');
    
    if(!fromList){
        if($(mediaSelectId).options[idx].value == "new"){
            //新規追加
            //targetIndex = idx;
            //newOption = idx+1;
        } else {
            //コピーして追加
            //targetIndex = idx;
            //newOption = $(mediaSelectId).options.length - 1;
            $(mediaSelectId).selectedIndex = $(mediaSelectId).options.length - 1;
            idx = $(mediaSelectId).options.length - 1;
        }

        $(mediaSelectId).options[idx] = new Option('構成', '01');
        $(mediaSelectId).options[idx+1] = new Option('新規', 'new');
        $('addButton').value = "コピーして追加";
        $(mediaSelectId).selectedIndex = idx;
    }
    
    //配列を更新
    structureArray[idx] = structure;
    
}

function deleteList()
{
    for(var i = currentSelectIdx ;i < structureArray.length-1; i++){
        structureArray[i] = structureArray[i+1];
    }
    structureArray.pop();
    
    $(mediaSelectId).options[currentSelectIdx] = null;
    
    $(mediaSelectId).selectedIndex = currentSelectIdx;
    selectList();
}

//選択されたリストに該当するデータをフォームに入れ込む
function selectList()
{
    idx = $(mediaSelectId).selectedIndex;
 
    if($(mediaSelectId).options[idx].value == "new"){
        structure = new Array();
        
        stIdx = 0;
/*
        structure['media_dvd']        =  true;
        structure['media_vhs']        =  false;
        structure['hinban']           =  "";
        structure['jan_code']         =  "";
        structure['isbn_code']        =  "";
        structure['sale-date']        =  "";
        structure['sell_type_sell']   =  true;
        structure['sell_type_rental'] =  false;
        structure['content_time']     =  "";
        structure['price']            =  "";
        structure['bikou']            =  "";
 */
        structure[stIdx++] =  "dvd";
        structure[stIdx++] =  "";
        structure[stIdx++] =  "";
        structure[stIdx++] =  "";
        structure[stIdx++] =  "";
        structure[stIdx++] =  "sell";
        structure[stIdx++] =  "";
        structure[stIdx++] =  "";
        structure[stIdx++] =  "";
 
        $('addButton').value = "新規追加";
    } else {
        structure = structureArray[idx];
        $('addButton').value = "コピーして追加";
    }
    
    //カレントを選択行に変更
    currentSelectIdx = idx;

    //連想配列をフォームデータに格納
    //alert(structure['hinban']);
    stIdx = 0;
/*
    $('media_dvd').checked        = (structure['media_dvd']) ? true : false;
    $('media_vhs').checked        = (structure['media_vhs']) ? true : false;
    $('hinban').value             = structure['hinban'];
    $('jan_code').value           = structure['jan_code'];
    $('isbn_code').value          = structure['isbn_code'];
    $('sale-date').value          = structure['sale-date'];
    $('sell_type_sell').checked   = (structure['sell_type_sell']) ? true : false;
    $('sell_type_rental').checked = (structure['sell_type_rental']) ? true : false;
    $('content_time').value       = structure['content_time'];
    $('price').value              = structure['price'];
    $('bikou').value              = structure['bikou'];
*/
    $('media_dvd').checked        = (structure[stIdx] == "dvd") ? true : false;
    $('media_vhs').checked        = (structure[stIdx++] == "vhs") ? true : false;
    $('hinban').value             = structure[stIdx++];
    $('jan_code').value           = structure[stIdx++];
    $('isbn_code').value          = structure[stIdx++];
    $('sale-date').value          = structure[stIdx++];
    $('sell_type_sell').checked   = (structure[stIdx] == "sell") ? true : false;
    $('sell_type_rental').checked = (structure[stIdx++] == "rental") ? true : false;
    $('content_time').value       = structure[stIdx++];
    $('price').value              = structure[stIdx++];
    $('bikou').value              = structure[stIdx++];
}

function submitList()
{
    
/*
    for(var i = 0; i < structureArray.length; i++){
        structure = structureArray[i];
        media     = (structure['media_dvd'])      ? "dvd"  : "vhs";
        sell_type = (structure['sell_type_sell']) ? "sell" : "rental";
        
        $(mediaSubmitField).innerHTML += '<input type=hidden name=media value='+media+'>';
        $(mediaSubmitField).innerHTML += '<input type=hidden name=hinban value='+structure['hinban']+'>';
        $(mediaSubmitField).innerHTML += '<input type=hidden name=jan_code value='+structure['jan_code']+'>';
        $(mediaSubmitField).innerHTML += '<input type=hidden name=isbn_code value='+structure['isbn_code']+'>';
        $(mediaSubmitField).innerHTML += '<input type=hidden name=release_date value='+structure['sale-date']+'>';
        $(mediaSubmitField).innerHTML += '<input type=hidden name=sell_type value='+sell_type+'>';
        $(mediaSubmitField).innerHTML += '<input type=hidden name=content_time value='+structure['content_time']+'>';
        $(mediaSubmitField).innerHTML += '<input type=hidden name=price value='+structure['price']+'>';
        $(mediaSubmitField).innerHTML += '<input type=hidden name=bikou value='+structure['bikou']+'>';

    }
*/   
    $(mediaSubmitField).innerHTML += '<input type=hidden name=structurejson_serial value='+structureArray.toJSONString()+'>';
    
    return true;
}

/***********ランク付け***********/
function star()
{
  var stars = new Array(5);
  var rank;

  for(var i = 0 ; i < 5 ; i++){
    if(document.all){
        stars[i] = document.all("star").appendChild(document.createElement("span"));    
    }else{
        star = document.createElement("span");
        stars[i] = document.getElementById("star").appendChild(star);
    }
    stars[i].index = i;
    stars[i].onclick = function onclick(){
        rank = 0;
        for (var i in stars)
        {
            stars[i].innerHTML = i <= this.index ? '★' : '☆';
        }
        for(var i = 0; i < 5 ; i++){
            if(stars[i].innerHTML=='★');
            rank++; 
        }
        $('rank').value = rank;
    }
  }
  
  stars[Math.ceil(5 / 2) - 1].onclick();
}


/***********商品在庫入力関連***********/
var structureArray = new Array();

//リストを更新する
function addStockList()
{

    structure = new Array();

    //フォームデータを連想配列へ格納
    addIdx   = structureArray.length;
    stIdx = 0;

    structure[stIdx++] = ($('condition_new').selected) ? "新品" : "中古" ;
    structure[stIdx++] = $('price').value+'円';
    structure[stIdx++] = $('quantity').value+'個';
    if (!($('startdate').value) && !($('enddate').value)){
        structure[stIdx++] = '無し';
    } else {
        structure[stIdx++] = $('startdate').value+'～'+$('enddate').value;
    }
    structure[stIdx++] = $('description').value;
    structure[stIdx++] = $('storage').value;
    structure[stIdx] = $('supplier').value;
    
    //配列最後尾に追加
    structureArray[addIdx] = structure;
    
    updateStockList();
}

function deleteStockList(delIdx)
{
    //配列の当該位置に一つ次の要素を上書きする形で削除
    for(var i = delIdx ;i < structureArray.length; i++){
        structureArray[i] = structureArray[i+1];
    }
    //最後尾が残るのでnull化
    //structureArray[structureArray.length-1] = null;
    structureArray.pop();
    
    updateStockList();
}

function updateStockList()
{
    stocksTable = '';
    if (structureArray.length > 0){
        //テーブルの見出し部分
        stocksTable += '<table cellspacing="6">\n   <tr>\n      <th>コンディション</th>\n       <th>販売価格</th>\n     <th>数量</th>\n       <th>販売期間</th>\n     <th>商品説明</th>\n     <th>保管場所</th>\n     <th>仕入先</th>     <th></th>\n </tr>\n';
        for (var i = 0 ;i < structureArray.length; i++){
            stocksTable += '    <tr>\n';
            for (var j = 0 ;j < 7; j++){
                //テーブルの中身
                stocksTable += '        <td>'+structureArray[i][j]+'</td>\n';
            }
            stocksTable += '        <td><button onClick=\"deleteStockList('+i+'); return false;\">行削除</button></td>'
            stocksTable += '    </tr>\n';
        }
        stocksTable += '</table>';
    }
    $('stocks').innerHTML = stocksTable;
}

function submitStockList()
{
    $('stocks_submit').innerHTML += '<input type=hidden name=structureJson_serial value='+structureArray.toJSONString()+'>';
    
    return true;
}


/***********キャスト名ドロップ関連***********/
var selcastdiv = 1;

// 選択したキャスト種別の取得
function castDivSelect()
{
    selcastdiv = $('cast_div').value;
}

// キャスト名頭文字ドロップダウンの変更時
// 引数: castCapitalDropId  キャストキャピタルドロップダウンのID
// 引数: castDropId         キャストドロップダウンのID
function changeCastCapital(castCapitalDropId, castDropId)
{
    // 選択された頭文字を取得
    capital = $(castCapitalDropId).value;
    
    // Ajaxオブジェクト生成
    new Ajax.Request('index.php', 
                        {'method': 'get', 
                         'parameters': 'action=util_dropcast' + 
                                       '&dropid=' + castDropId + 
                                       '&castdiv=' + selcastdiv + 
                                       '&capital=' + capital,
                        onException: checkException,
                        onComplete: updateCastDrop });
}

// キャスト名ロード時
// 引数: castDropId     キャストドロップダウンのID
// 引数: castCapitalId  キャストキャピタルドロップダウンのID
// 引数: castdiv        キャストの区分
// 引数: castId         キャストのID
function loadCast(castDropId, castCapitalId, castdiv, castId)
{
    // Ajaxオブジェクト生成
    new Ajax.Request('index.php', 
                        {'method': 'get', 
                         'parameters': 'action=util_dropcast' +
                                       '&dropid=' + castDropId + 
                                       '&capital=' + castCapitalId +
                                       '&castdiv=' + castdiv + 
                                       '&castid=' + castId,
                        onException: checkException,
                        onComplete: updateCastDrop });
}

function checkException(req,exc)
{
//    console.log('エラー!');
//    console.log(exc);
}

function updateCastDrop(httpResponse)
{
    //返ってきた文字列を、
    //改行文字を区切りとして配列にする
    castArray = httpResponse.responseText.split("\n");

    //最初の１行目はキャスト名ドロップのID
    castDropId = castArray[0];
    
    //キャスト名ドロップの中身をクリア
    var optLength = $(castDropId).options.length;
    for(var i = 0; i < optLength; i++){
        $(castDropId).options[i] = null;
    }
    
    // キャスト名ドロップの Length を初期化
    $(castDropId).options.length = 0;

    //キャスト名ドロップの中身を設定
    selectidx = 0;
    for(var i = 1; i < castArray.length; i++){
        //nameとvalueに分解
        nameValueArray = castArray[i].split(",");

        //optionを設定
        $(castDropId).options[i - 1] = new Option(nameValueArray[1], nameValueArray[0]);

        if (nameValueArray[2]=="true") selectidx = i-1;
    }
    $(castDropId).selectedIndex = selectidx;
}


function castItemDelCheck(form, action, mode, ctcd, upct)
{
  if (confirm("本当に削除しますか？")) {
    $('ac').value = action;
    $('mde').value = mode;
    $('castcd').value = ctcd;
    $('updcnt').value = upct;
    form.submit();
  } else {
    return false;
  }
}


function castItemInsCheck(form, action, mode)
{
  if (confirm("本当に追加しますか？")) {
    $('ac').value = action;
    $('mde').value = mode;
    form.submit();
  } else {
    return false;
  }
}


/* タグ */
function clickTag(tag)
{
    if (tag!='') $('inputtag').value += ' ' + tag;
}

function deleteImgCheck(action)
{
  if (confirm("この画像を削除します。よろしいですか？")) {
    $('ac').value = action;
    return true;
  } else {
    return false;
  }
}
