

/*****************************************************
 * 関数
 ****************************************************/

/**
 *  ページ遷移
 *
 * @param string link 遷移先名
 */
function nextPage(link) {
    var frm = new postRequest();
    frm.add('page', link);
    frm.submit();
}

function nextComparePage(link) {
    var frm = new postRequest();
    frm.add('page', link);
    frm.add('compare', 1);
    frm.submit();
}

/*****************************************************
 * CLASS
 ****************************************************/

/**
 *  ページ遷移class
 *
 */
function postRequest() {
    this.frmObject = document.createElement("form");
    this.frmObject.method = "post";

    /**
     *  hidden form 追加
     *
     * @param string elementname  フォーム名
     * @param mixed  elementvalue 値
     */
    this.add = function(elementname, elementvalue)
    {
       var input    = document.createElement("input");
	   input.type   = "hidden";
	   input.name   = elementname;
	   input.value  = elementvalue;
       this.frmObject.appendChild(input);
    };
    
    /**
     * submit
     *  特定のフレームに対してpostしたい場合はフレーム名を引数にする
     *
     * @param string targetFrame フレーム名
     */
    this.submit = function(targetFrame)
    {
        try {
            if (targetFrame) { this.frmObject.target = targetFrame; }
        } catch(e) { }
      
        try {
            this.frmObject.action = 'index.php';
            document.body.appendChild(this.frmObject);
            this.frmObject.submit();
            return true;
        } catch(e) {
            return false;
        }
    };
}

/**
 *  運動メニュー変更によるページ遷移
 *
 * @param string no メニューキーNo
 */
function chgExercise(no) {
    var frm = new postRequest();
    frm.add('page', 'Exercise');
    frm.add('exerciseMenu', no);
    frm.submit();
}





/**
 *  AJAX 共通関数
 *
 * @param array posts post値配列
 * @param function funcSuccess 成功時に実行する関数
 * @param function funcFailure 失敗時に実行する関数
 */
function ajaxRequest(posts, funcSuccess, funcFailure) {

    posts['ajax'] = 'on';
    new Ajax.Request('index.php', {method    : 'post',
                                   postBody  : $H(posts).toQueryString(),
                                   onSuccess : function(httpObj) {
                                                   if (typeof funcSuccess == 'function') { funcSuccess(httpObj); }
                                               },
                                   onFailure : function(httpObj) {
                                                   if (typeof funcFailure == 'function') { funcFailure(httpObj); }
                                               }
                                  });
}


/**
 *  PhysionSuperClass
 *
 */
function PhysionBase()
{
    /**
     *  デバッグフラグ
     */
    this.dbgFlag = false;

    /**
     *  デバッグdiv id
     */
    this.debugDivId = 'debug';


    /**
     *  パスワード長 最小
     */
    this.passwordShortLimit = 4;
    /**
     *  パスワード長 最大
     */
    this.passwordLongLimit  = 10;

    /**
     *  初期化
     *
     * @param  object obj ChildClass
     * @return void
     */
    this.init = function(obj)
    {
        if (this.dbgFlag) {
            window.onload = function(){ obj.appendDebugDiv(); }
        }
    };

    /**
     *  デバッグ用div追加
     *
     * @return void
     */
    this.appendDebugDiv = function()
    {
        var bodyNode = document.getElementsByTagName('body')[0];
        var divNode  = document.createElement('div');
        divNode.id = this.debugDivId;
        divNode.className = 'debug';
        var btnNode = document.createElement('input');
        btnNode.type = 'button';
        btnNode.value = 'clear';
        try {
            btnNode.attachEvent('onclick', this.clearDebug);
        } catch(e) { 
            //btnNode.onclick = function() { this.clearDebug); }
        }
        bodyNode.appendChild(btnNode);
        bodyNode.appendChild(divNode);
    };

    this.clearDebug = function()
    {
        document.getElementById('debug').innerHTML = '';
    };

    this.debug = function(str)
    {
        if (this.dbgFlag == false) { return 1; }
        var divDebug = document.getElementById(this.debugDivId);
        var divNode  = document.createElement('div');
        divNode.appendChild(document.createTextNode(str));
        divDebug.appendChild(divNode);
    };

    /**
     *  AJAX 共通関数
     *
     * @param object    obj         呼び出し元object
     * @param array     posts       post値配列
     * @param function  funcSuccess 成功時に実行する関数
     * @param function  funcFailure 失敗時に実行する関数
     */
    this.ajaxRequest = function(obj, posts, funcSuccess, funcFailure)
    {
        //this.debug('start ajax');
        posts['ajax'] = 'on';
        new Ajax.Request('index.php', {method    : 'post',
                                       postBody  : $H(posts).toQueryString(),
                                       onSuccess : function(httpObj) {
//                                                       obj.debug(httpObj.responseText);
                                                       if (typeof funcSuccess == 'function') { funcSuccess(obj, httpObj); }
                                                   },
                                       onFailure : function(httpObj) {
                                                       if (typeof funcFailure == 'function') { funcFailure(httpObj); }
                                                   }
                                      });
    };

    /**
     *  数値チェック
     *
     * @param  string name フォーム名
     * @return boolean
     */
    this.validateNumeric = function(name)
    {
        if (isNaN(document.getElementsByName(name)[0].value)) {
            document.getElementsByName(name)[0].focus();
            alert('数値を入力してください');
            return false;
        }
        return true;
    };

    /**
     *  自然数チェック
     *
     * @param  string  name         フォーム名
     * @param  boolean disableAlert true:自動的にアラートを表示しない
     * @return boolean
     */
    this.validateNaturalNumber = function(name, disableAlert)
    {
        if (!document.getElementsByName(name)[0].value.match(/^\d+$/)) {
            document.getElementsByName(name)[0].focus();
            if (!disableAlert) {
                alert('数値を入力してください');
            }
            return false;
        }
        return true;
    };

    /**
     *  限界値チェック
     *
     * @param  string  name     フォーム名
     * @param  numeric value    閾値
     * @param  integer vector   0:上限, 1:下限
     * @param  integer boundary 0:以上下,1:より上下
     */
    this.validateLimit = function(name, value, vector, boundary)
    {
        var form = document.getElementsByName(name)[0];
        var formValue = Number(form.value);
        switch (vector) {
            case 0: //上限
                switch (boundary) {
                    case 0:
                        if (formValue <= value) {
                            //
                        } else {
                            form.focus();
                            alert(value + '以下で入力してください'); 
                            return false;
                        }
                        break;

                    case 1:
                        if (formValue < value) {
                            //
                        } else {
                            form.focus();
                            alert(value + '未満で入力してください'); 
                            return false;
                        }
                        break;

                    default:
                        break;
                }
                break;

            case 1: //下限
                switch (boundary) {
                    case 0:
                        if (formValue >= value) {
                            //
                        } else {
                            form.focus();
                            alert(value + '以上で入力してください'); 
                            return false;
                        }
                        break;

                    case 1:
                        if (formValue > value) {
                            //
                        } else {
                            form.focus();
                            alert(value + 'より上の値を入力してください'); 
                            return false;
                        }
                        break;

                    default:
                        break;
                }
                break;

            default:
                break;
        }
        return true;
    };

    /**
     *  日付チェック
     *
     * @param  string name フォーム名
     * @return boolean
     */
    this.validateDate = function(name)
    {
        if (document.getElementsByName(name)[0].value.match(/^$/)) {
            return true;
        }
        if (!document.getElementsByName(name)[0].value.match(/^(\d{4})(\d{2})(\d{2})$/)) {
            document.getElementsByName(name)[0].focus();
            alert('日付を正しく入力してください');
            return false;
        }
        var yearValue   = RegExp.$1;
        var monthValue  = RegExp.$2 - 1;
        var dayValue    = RegExp.$3;
        var date = new Date(yearValue, monthValue, dayValue);
        if (date.getFullYear() == yearValue && date.getMonth() == monthValue && date.getDate() == dayValue) {
            return true;
        }
        document.getElementsByName(name)[0].focus();
        alert('日付を正しく入力してください');
        return false;
    };

    /**
     *  文字列長チェック
     *
     * @param  string  name   エレメント名
     * @param  integer length 長さ上限
     * @param  integer length 長さ下限
     * @return boolean
     */
    this.validateLength = function()
    {
        if (arguments.length == 3) {
            if (document.getElementsByName(arguments[0])[0].value.length > arguments[1] || document.getElementsByName(arguments[0])[0].value.length < arguments[2]) {
                document.getElementsByName(arguments[0])[0].focus();
                this.alert(arguments[2] + '文字以上、' + arguments[1] + '文字以内で指定してください');
                return false;
            }
        } else {
            if (document.getElementsByName(arguments[0])[0].value.length > arguments[1]) {
                document.getElementsByName(arguments[0])[0].focus();
                this.alert(arguments[1] + '文字以内で指定してください');
                return false;
            }
        }
        return true;
    };


    /**
     *  数値を,区切り
     *
     * @param  string str
     * @return string
     */
    this.numberFormat = function(str)
    {
      var num = new String(str).replace(/,/g, "");
      while (num != (num = num.replace(/^(-?\d+)(\d{3})/, "$1,$2")));
      return num;
    };

}

/**
 *  ユーザ情報管理クラス
 *
 */
function UserInfoClass()
{

    this.userName;
    this.password;

    this.page;


    this.init = function()
    {
        this.userName = null;
        this.password = null;
    };

    this.setPage = function(page)
    {
        this.page = page;
    };
    this.getPage = function()
    {
        return this.page;
    };

    /**
     *  更新
     */
    this.update = function()
    {
        // 初期化
        this.init();
        // validate
        if (!this.validate()) {
            return false;
        }
        // update
        var posts = {page:'EditUser', action:'update', name:this.userName};
        if ($('birth_month')) {
            var birthMonth = $('birth_month').options[$('birth_month').selectedIndex].value;
            posts['birthMonth'] = birthMonth;
        }
        if ($('birth_day')) {
            var birthDay   = $('birth_day').options[$('birth_day').selectedIndex].value;
            posts['birthDay'] = birthDay;
        }
        if ($('gym_user_id')) {
            var gymid = $('gym_user_id').value;
            posts['gym_user_id'] = gymid;
        }
        if (this.password != null) {
            posts['password'] = this.password;
        }
        posts['athlete_flag'] = this.getRadioValue('athlete_flag');

        var funcSuccess = function(obj, httpObj) {
            var xml = httpObj.responseXML;
            var messages = xml.getElementsByTagName('message');
            for (var i = 0, iCnt = messages.length; i < iCnt; i++) {
                alert(messages[i].firstChild.nodeValue);
                return 1;
            }
            if (confirm('更新完了しました。' + "\n" + '画面を更新しますか？')) {
                nextPage(UserInfoClass.getPage());
            } else {
                $('closeIcon').click();
            }
        };
        var funcFailure = function(obj) {
            $('debug').innerHTML = obj.responseText;
        };

        this.ajaxRequest(this, posts, funcSuccess, funcFailure);
    };

    this.getRadioValue = function(name)
    {
        var radio = document.getElementsByName(name);
        for (var i = 0, iCnt = radio.length; i < iCnt; i++) {
            if (radio[i].checked == true) {
                return radio[i].value;
            }
        }
        return null;
    };

    /**
     *  validate 
     *
     * @return boolean
     */
    this.validate = function()
    {
        // 名前チェック
        var name = 'user_name';
        if (!this.validateLength(name, 255)) {
            return false;
        }
        this.userName = document.getElementsByName(name)[0].value;
        // パスワードチェック
        name = 'password1';
        if (document.getElementsByName(name)[0].value != document.getElementsByName('password2')[0].value) {
            document.getElementsByName(name)[0].focus();
            alert('パスワードが一致しません');
            return false;
        }
        if (document.getElementsByName(name)[0].value.length != 0) {
            if (!this.validateLimit(name, this.passwordLongLimit, this.passwordShortLimit)) {
                return false;
            }
            this.password = document.getElementsByName(name)[0].value;
        }
        return true;
    };

    /**
     *  window close
     */
    this.close = function()
    {
    };
}


