/*
 * This file is part of EC-CUBE
 *
 * Copyright(c) 2000-2007 LOCKON CO.,LTD. All Rights Reserved.
 *
 * http://www.lockon.co.jp/
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
// 親ウィンドウの存在確認.
function fnIsopener() {
    var ua = navigator.userAgent;
    if( !!window.opener ) {
        if( ua.indexOf('MSIE 4')!=-1 && ua.indexOf('Win')!=-1 ) {
            return !window.opener.closed;
        } else {
            return typeof window.opener.document == 'object';
        }
    } else {
        return false;
    }
}

// 郵便番号入力呼び出し.
function fnCallAddress(php_url, tagname1, tagname2, input1, input2) {
    zip1 = document.form1[tagname1].value;
    zip2 = document.form1[tagname2].value;

    if(zip1.length == 3 && zip2.length == 4) {
        url = php_url + "?zip1=" + zip1 + "&zip2=" + zip2 + "&input1=" + input1 + "&input2=" + input2;
        window.open(url,"nomenu","width=500,height=350,scrollbars=yes,resizable=yes,toolbar=no,location=no,directories=no,status=no");
    } else {
        alert("郵便番号を正しく入力して下さい。");
    }
}

// 郵便番号から検索した住所を渡す.
function fnPutAddress(input1, input2) {
    // 親ウィンドウの存在確認。.
    if(fnIsopener()) {
        if(document.form1['state'].value != "") {
            // 項目に値を入力する.
            state_id = document.form1['state'].value;
            town = document.form1['city'].value + document.form1['town'].value;
            window.opener.document.form1[input1].selectedIndex = state_id;
            window.opener.document.form1[input2].value = town;
        }
    } else {
        window.close();
    }
}

function fnOpenNoMenu(URL) {
    window.open(URL,"nomenu","scrollbars=yes,resizable=yes,toolbar=no,location=no,directories=no,status=no");
}

function fnOpenWindow(URL,name,width,height) {
    window.open(URL,name,"width="+width+",height="+height+",scrollbars=yes,resizable=no,toolbar=no,location=no,directories=no,status=no");
}

function fnSetFocus(name) {
    if(document.form1[name]) {
        document.form1[name].focus();
    }
}

// セレクトボックスに項目を割り当てる.
function fnSetSelect(name1, name2, val) {
    sele1 = document.form1[name1];
    sele2 = document.form1[name2];

    if(sele1 && sele2) {
        index=sele1.selectedIndex;

        // セレクトボックスのクリア
        count=sele2.options.length
        for(i = count; i >= 0; i--) {
            sele2.options[i]=null;
        }

        // セレクトボックスに値を割り当てる。
        len = lists[index].length
        for(i = 0; i < len; i++) {
            sele2.options[i]=new Option(lists[index][i], vals[index][i]);
            if(val != "" && vals[index][i] == val) {
                sele2.options[i].selected = true;
            }
        }
    }
}

// Enterキー入力をキャンセルする。(IEに対応)
function fnCancelEnter()
{
    if (gCssUA.indexOf("WIN") != -1 && gCssUA.indexOf("MSIE") != -1) {
        if (window.event.keyCode == 13)
        {
            return false;
        }
    }
    return true;
}

// モードとキーを指定してSUBMITを行う。
function fnModeSubmit(mode, keyname, keyid) {
    switch(mode) {
    case 'error_coupon':
        alert('選択したクーポンタイプは重複して登録できません');
        return;
        break;
    case 'delete_coupon':
        if(!window.confirm('削除して宜しいですか？')){
            return;
        }
        break;
    case 'delete_category':
        if(!window.confirm('選択したカテゴリとカテゴリ内のすべてのカテゴリを削除します')){
            return;
        }
        break;
    case 'delete':
        if(!window.confirm('削除しても宜しいですか？')){
            return;
        }
        break;
    case 'confirm':
        if(!window.confirm('登録しても宜しいですか')){
            return;
        }
        break;
    case 'delete_all':
        if(!window.confirm('検索結果をすべて削除しても宜しいですか')){
            return;
        }
        break;
    default:
        break;
    }
    document.form1['mode'].value = mode;
    if(keyname != "" && keyid != "") {
        document.form1[keyname].value = keyid;
    }
    document.form1.submit();
}

function fnFormModeSubmit(form, mode, keyname, keyid) {
    switch(mode) {
    case 'delete_coupon_user':
        if(!window.confirm('削除して宜しいですか？')){
            return;
        }
        break;
    case 'delete':
        if(!window.confirm('一度削除したデータは、元に戻せません。\n削除しても宜しいですか？')){
            return;
        }
        break;
    case 'confirm':
        if(!window.confirm('登録しても宜しいですか')){
            return;
        }
        break;
    case 'regist':
        if(!window.confirm('登録しても宜しいですか')){
            return;
        }
        break;
    default:
        break;
    }
    document.forms[form]['mode'].value = mode;
    if(keyname != "" && keyid != "") {
        document.forms[form][keyname].value = keyid;
    }
    document.forms[form].submit();
}

function fnSetFormSubmit(form, key, val) {
    document.forms[form][key].value = val;
    document.forms[form].submit();
    return false;
}

function fnSetFormVal(form, key, val) {
    document.forms[form][key].value = val;
}

function fnChangeAction(url) {
    document.form1.action = url;
}

// ページナビで使用する。
function fnNaviPage(pageno) {
    document.form1['pageno'].value = pageno;
    document.form1.submit();
}

function fnSearchPageNavi(pageno) {
    document.form1['pageno'].value = pageno;
    document.form1['mode'].value = 'search';
    document.form1.submit();
    }

    function fnSubmit(){
    document.form1.submit();
}

// ポイント入力制限。
function fnCheckInputPoint() {
    if(document.form1['point_check']) {
        list = new Array(
                        'use_point'
                        );

        if(!document.form1['point_check'][0].checked) {
            color = "#dddddd";
            flag = true;
        } else {
            color = "";
            flag = false;
        }

        len = list.length
        for(i = 0; i < len; i++) {
            if(document.form1[list[i]]) {
                document.form1[list[i]].disabled = flag;
                document.form1[list[i]].style.backgroundColor = color;
            }
        }
    }
}

// 別のお届け先入力制限。
function fnCheckInputDeliv() {
    if(!document.form1) {
        return;
    }
    if(document.form1['deliv_check']) {
        list = new Array(
                        'deliv_name01',
                        'deliv_name02',
                        'deliv_kana01',
                        'deliv_kana02',
                        'deliv_pref',
                        'deliv_zip01',
                        'deliv_zip02',
                        'deliv_addr01',
                        'deliv_addr02',
                        'deliv_tel01',
                        'deliv_tel02',
                        'deliv_tel03'
                        );

        if(!document.form1['deliv_check'].checked) {
            fnChangeDisabled(list, '#dddddd');
        } else {
            fnChangeDisabled(list, '');
        }
    }
}


// 購入時会員登録入力制限。
function fnCheckInputMember() {
    if(document.form1['member_check']) {
        list = new Array(
                        'password',
                        'password_confirm',
                        'reminder',
                        'reminder_answer'
                        );

        if(!document.form1['member_check'].checked) {
            fnChangeDisabled(list, '#dddddd');
        } else {
            fnChangeDisabled(list, '');
        }
    }
}

// 最初に設定されていた色を保存しておく。
var g_savecolor = new Array();

function fnChangeDisabled(list, color) {
    len = list.length;

    for(i = 0; i < len; i++) {
        if(document.form1[list[i]]) {
            if(color == "") {
                // 有効にする。
                document.form1[list[i]].disabled = false;
                document.form1[list[i]].style.backgroundColor = g_savecolor[list[i]];
            } else {
                // 無効にする。
                document.form1[list[i]].disabled = true;
                g_savecolor[list[i]] = document.form1[list[i]].style.backgroundColor;
                document.form1[list[i]].style.backgroundColor = color;//"#f0f0f0";
            }
        }
    }
}


// ログイン時の入力チェック
function fnCheckLogin(formname) {
    var lstitem = new Array();

    if(formname == 'login_mypage'){
        lstitem[0] = 'mypage_login_email';
        lstitem[1] = 'mypage_login_pass';
    }else{
        lstitem[0] = 'login_email';
        lstitem[1] = 'login_pass';
    }
    var max = lstitem.length;
    var errflg = false;
    var cnt = 0;

    //　必須項目のチェック
    for(cnt = 0; cnt < max; cnt++) {
        if(document.forms[formname][lstitem[cnt]].value == "") {
            errflg = true;
            break;
        }
    }

    // 必須項目が入力されていない場合
    if(errflg == true) {
        alert('メールアドレス/パスワードを入力して下さい。');
        return false;
    }else{
        jsonLogin();
        return true;
    }
}

// 時間の計測.
function fnPassTime(){
    end_time = new Date();
    time = end_time.getTime() - start_time.getTime();
    alert((time/1000));
}
start_time = new Date();

//親ウィンドウのページを変更する.
function fnUpdateParent(url) {
    // 親ウィンドウの存在確認
    if(fnIsopener()) {
        window.opener.location.href = url;
    } else {
        window.close();
    }
}

//特定のキーをSUBMITする.
function fnKeySubmit(keyname, keyid) {
    if(keyname != "" && keyid != "") {
        document.form1[keyname].value = keyid;
    }
    document.form1.submit();
}

//文字数をカウントする。
//引数1：フォーム名称
//引数2：文字数カウント対象
//引数3：カウント結果格納対象
function fnCharCount(form,sch,cnt) {
    document.forms[form][cnt].value= document.forms[form][sch].value.length;
}


// テキストエリアのサイズを変更する.
function ChangeSize(button, TextArea, Max, Min, row_tmp){

    if(TextArea.rows <= Min){
        TextArea.rows=Max; button.value="小さくする"; row_tmp.value=Max;
    }else{
        TextArea.rows =Min; button.value="大きくする"; row_tmp.value=Min;
    }
}

//Add favorite
function add_favorite(Url,customer_id,product_id,id,imgLoad,messages){
    if(id!=''){
        $("#"+imgLoad).show();
        $("#"+id).hide();
    }

    $.ajax({type: "POST",
        url: Url+"json/wishlist.php",
        data: "customer_id="+customer_id+"&product_id="+product_id+"&mode=add_favorite",
        success:
        function(msg){
            if(id!=''){
                $("#"+imgLoad).hide();
                if(messages != "fav_gray"){
                    document.getElementById(id).innerHTML=messages;
                    $("#"+id).show();
                }else{
                    $('#fav_gray').show();
                }
            }
        }
    });
}
function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57

    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 0 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;

    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function explode( delimiter, string, limit ) {
    // http://kevin.vanzonneveld.net
    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']

    var emptyArray = { 0: '' };

    // third argument is not required
    if ( arguments.length < 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
    {
        return null;
    }

    if ( delimiter === ''
        || delimiter === false
        || delimiter === null )
    {
        return false;
    }

    if ( typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object' )
    {
        return emptyArray;
    }

    if ( delimiter === true ) {
        delimiter = '1';
    }

    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

var CheckSubmitSend = true;
function fnCheckSubmit(msg) {

    if(CheckSubmitSend) {
        CheckSubmitSend = false;
        return true;
    } else {
        alert(msg);
        return false;
    }
}
function is_numeric( mixed_var ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: David
    // *     example 1: is_numeric(186.31);
    // *     returns 1: true
    // *     example 2: is_numeric('Kevin van Zonneveld');
    // *     returns 2: false
    // *     example 3: is_numeric('+186.31e2');
    // *     returns 3: true

    return !isNaN( mixed_var );
}

function check_stock(name,id,unit,stock,stock_unlimited,sale_limit,sale_unlimited,quantity_min,quantity_max){
	var err_flg = false;
	if(stock_unlimited != 1 && sale_unlimited != 1 ){
        if(sale_limit < stock){
            if(unit > sale_limit){
                document.getElementById(id).value=sale_limit;
                alert("恐れ入りますが「（"+name+"）」のご購入は、おひとり様"+sale_limit+"個までとなっております。"+sale_limit+"個までのご購入でお願いいたします。");
                err_flg = true;
            }
        }else{
            if(unit > stock){
                document.getElementById(id).value=stock;
                alert("ご要望の商品数量が、当店の在庫数を超えています。誠に申し訳ございませんが、"+stock+"個までのご購入でお願いいたします。");
                err_flg = true;
            }
        }
    }else{
        if( stock_unlimited != 1 && unit > stock){
            document.getElementById(id).value=stock;
            alert("ご要望の商品数量が、当店の在庫数を超えています。誠に申し訳ございませんが、"+stock+"個までのご購入でお願いいたします。");
            err_flg = true;
        }
        if(sale_unlimited != 1 && unit > sale_limit ){
            document.getElementById(id).value=sale_limit;
            alert("恐れ入りますが「（"+name+"）」のご購入は、おひとり様"+sale_limit+"個までとなっております。"+sale_limit+"個までのご購入でお願いいたします。");
            err_flg = true;
        }
    }
    if (err_flg === false){
    	if(unit > quantity_max){
            document.getElementById(id).value=quantity_max;
        }else if(unit < quantity_min){
            document.getElementById(id).value=quantity_min;
        }
    }

    if (document.getElementById("pre_"+id)){
        if (document.getElementById("pre_"+id).innerHTML != undefined && document.getElementById("pre_"+id).innerHTML != null ) {
            document.getElementById("pre_"+id).innerHTML = document.getElementById(id).value;
        }else if(document.getElementById("pre_"+id).value != undefined && document.getElementById("pre_"+id).value != null ) {
            document.getElementById("pre_"+id).value = document.getElementById(id).value;
        }
    }
}

function check_stock_ajax(url,id,product_id,unit,name,stock,stock_unlimited,sale_limit,sale_unlimited,quantity_min,quantity_max){
//    $("#"+id).hide();
//    $("#loading_"+id).show();
    $.ajax({type: "POST",
        url: url+"json/Calculate_Price.php",
        data: "unit="+unit+"&id="+id+"&product_id="+product_id+"&mode=check_stock",
        timeout: 5000,
        success:
        function(str_data){
            arr_data=explode(",",str_data);
            if(arr_data[0]!="false"){
                if (document.getElementById("pre_"+id)){
                    if (document.getElementById("pre_"+id).innerHTML != undefined && document.getElementById("pre_"+id).innerHTML != null ) {
                        document.getElementById("pre_"+id).innerHTML = arr_data[1];
                    }else if(document.getElementById("pre_"+id).value != undefined && document.getElementById("pre_"+id).value != null ) {
                        document.getElementById("pre_"+id).value = arr_data[1];
                    }
                }
                document.getElementById(id).value=arr_data[1];
                alert(arr_data[0]);
            } else {
                if (document.getElementById("pre_"+id)){
                    if (document.getElementById("pre_"+id).innerHTML != undefined && document.getElementById("pre_"+id).innerHTML != null ) {
                        document.getElementById("pre_"+id).innerHTML = unit;
                    }else if(document.getElementById("pre_"+id).value != undefined && document.getElementById("pre_"+id).value != null ) {
                        document.getElementById("pre_"+id).value = unit;
                    }
                }
            }
//            $("#loading_"+id).hide();
//            $("#"+id).show();
        },
        error:
        function(XMLHttpRequest, status, errorThrown){
            // 引数がある場合、JS側で在庫のチェックをする
        	if ((typeof name) != "undefined" ){
                check_stock(name,id,unit,stock,stock_unlimited,sale_limit,sale_unlimited,quantity_min,quantity_max);

        	} else {
            	// 前の選択個数を取得して、個数リストに設定
                if (document.getElementById("pre_"+id)){
                    if (document.getElementById("pre_"+id).innerHTML != undefined && document.getElementById("pre_"+id).innerHTML != null ) {
                    	pre_qu = document.getElementById("pre_"+id).innerHTML;
                    }else if(document.getElementById("pre_"+id).value != undefined && document.getElementById("pre_"+id).value != null ) {
                    	pre_qu = document.getElementById("pre_"+id).value;
                    }
                    document.getElementById(id).value =pre_qu;
                    alert("サーバの応答が遅いため、在庫チェック処理をキャンセルしました。個数を変更前の値に戻したため、再度変更してください。" );
                }
            }
//            $("#loading_"+id).hide();
//            $("#"+id).show();
        }
    });

}
// 半角数字を全角数字に変換
function f2h(value) {
    var char1 = new Array("１","２","３","４","５","６","７","８","９","０");
    var char2 = new Array(1,2,3,4,5,6,7,8,9,0);
    var count;

    while(value.match(/[０-９]/)){         //入力データに全角数字がある場合
        for(count = 0; count < char1.length; count++){
            //入力データを全角数字から半角数字に置換する
            value = value.replace(char1[count], char2[count]);
        }
    }
    return value;
}

// 数値を返す（Null、空文字列、数値に変換できない場合0を返す）
function cnum(val){
    if (!val){
        return 0;
    } else if (val.length == 0) {
        return 0;
    } else if (!is_numeric){
        return 0;
    } else {
        return parseInt(val);
    }
}

//有効な日時かを返す
function checkDate(year, month, day) {
    var dt = new Date(year, month - 1, day);
    if(dt == null || dt.getFullYear() != year || dt.getMonth() + 1 != month || dt.getDate() != day) {
        return false;
    }
    return true;
}


