
var eco = new Object();
function ecoInit()
{
    eco = new EcoClass();
    initInputHighlightScript();
};

//GLOBAL
var StationList = new Object();
StationList.start = new Array();

//form作成クラス
var FormClass = function(){};
FormClass.prototype = {
    createElement: function( name ){ var element = document.createElement( name ); return element; },
    remove :function( idName ){ while( idName.hasChildNodes() ){ idName.removeChild( idName.lastChild ); }; },
    excute: function(){}
};

//駅検索クラス
var SearchStationClass = function(){};
SearchStationClass.prototype = {
    url: "./simulation.php",
    execute: function(stationName)
    {
        var obj = jQuery.ajax({
            dataType: "JSON",
            data: {
                "action_get_stationlist": "",
                "station": stationName
            },
            async: false,
            cache: true,
            url: this.url
        }).responseText;

        //検索結果０
        if(obj.length <= 0) {
            return 0;
        }
        eval("var list = " + obj);
        var result = new Array();
        for(var i = 0; i < list.length; i++){
            result.push(decodeURIComponent(list[i].name));
        }
        return result;
    }
};


//計算
var CalculateClass = function(){};
CalculateClass.prototype = {
    url: "./simulation.php",
    execute: function(object)
    {
        var obj = jQuery.ajax({
            dataType: "JSON",
            data: {
                "action_get_multistation_route": "",
                "dest": object.dest,
                "name1": object.name1,
                "num1": object.num1,
                "name2": object.name2,
                "num2": object.num2,
                "name3": object.name3,
                "num3": object.num3,
                "name4": object.name4,
                "num4": object.num4,
                "name5": object.name5,
                "num5": object.num5,
                "numTrips": object.numTrips,
                "numExpances": object.numExpances
            },
            async: false,
            cache: true,
            url: this.url
        }).responseText;
        if(obj.length <= 0) return 0;    //検索結果０
        eval("var result = " + obj);
        return result;
    }
};

//検索結果保持クラス
var StationListClass = function(){};
StationListClass.prototype = {
    //info: new Object(),                //dest: String 目的地, startStationList: Array(5) 出発地リスト

    getAll: function()
    {
        return StationList;
    },

    set: function(id, stationName)
    {
        "dest" == id ? this.setDest(stationName):
                       this.setStartPoint(id, stationName);
    },

    setDest: function(stationName)
    {
        StationList.dest = stationName;
    },

    setStartPoint: function(id, stationName)
    {
        if (0 == StationList.start.length){
            StationList.start.push({"id": id, "name": stationName});
        } else {
            var search = false;
            for (var i = 0; i < StationList.start.length; i++) {
                if (StationList.start[i].id == id) {
                    StationList.start[i].name = stationName;
                    break;
                }
            }
            if (i == StationList.start.length) StationList.start.push({"id": id, "name": stationName});
        }
    },

    drop: function(id)
    {
        this.info.startStationList[id] = "";
    }
};

//ecoクラス？
var EcoClass = Class.create();
EcoClass.prototype =
{
        FormClass: new FormClass(),
        SearchStationClass: new SearchStationClass(),
        StationListClass: new StationListClass(),
        CalculateClass: new CalculateClass(),

        url: "./index.php",

        //駅名検索
        search: function(
                        id    //1: start, dest: dest
                        ){
            var station = encodeURI(document.getElementById(id).value);

            if( ! station ){
                alert( "駅名を入力してください" );
                return false;
            }
            var result = SearchStationClass.prototype.execute(station);
            if (0 == result) {
                this.fault();
            } else {
                this.set(id, result);
            }
        },

        //選択した駅を目的地or出発地にセット
        set: function(
                    id,            //dest, start(5)
                    result
                    )
        {
            //検索結果数
            if (1 == result.length) {
                this.setStationName(id, result);
                this.StationListClass.set(id, result);
                if ("dest" != id)
                    this.setNumPersons(id, 1);
            } else {
                this.StationListClass.set(id, result[0]);
                this.setSelectForm(id, result);
                if ("dest" != id)
                    this.setNumPersons(id);
            }
        },

        fault: function()
        {
            alert( "該当する駅名がありません。" );
        },

        setNumPersons: function(id, focus)
        {
            var tForm = document.getElementById(id+"_numPersons");
            tForm.value = 1;
            if (1 == focus)
                tForm.focus();
        },

        setStationName: function(id, stationName)
        {
            var result = document.getElementById(id+"_result");
            this.FormClass.remove(result);
            //alert(id + "-station-col");
            var tResult = document.getElementById(id + "-station-col");
            tResult.display = "block";
            result.appendChild( document.createTextNode( stationName ) );
            result.appendChild( document.createTextNode("駅に設定しました。") );
        },

        setSelectForm: function(id, stationList)
        {
            var result = document.getElementById(id+"_result");
            this.FormClass.remove(result);

            var select = this.FormClass.createElement("select");
                select.id = "select_" + id;
                select.onchange = function(){
                    var value = EcoClass.prototype.getSelectedValue(id);
                    StationListClass.prototype.set(id, value);
                }

            var size = ( 3 < stationList.length ) ? 3 : stationList.length;
                select.size = size;

                //ie6対策のため.1 秒後に再度表示させている
                select.style.visibility = "hidden";
                setTimeout( function() {
                    select.style.visibility = "visible";
                }, 100 );

            for( var i = 0; i < stationList.length; i++ ){
                var option = this.FormClass.createElement( "option" );
                    option.value = stationList[i];
                    option.appendChild( document.createTextNode( stationList[i] ) );
                    if( 0 == i ) option.selected = 'selected';
                        select.appendChild( option );
            }
            result.appendChild( select );
            result.appendChild( document.createTextNode("駅に設定しました。") );
        },

        getSelectedValue: function(id)
        {
            var select = document.getElementById("select_"+id);
            return select.options[select.selectedIndex].value;
        },

        // 駅入力フォームへ set event
        setReturnEvent: function(){
            var ecoStationForm = document.getElementById( "eco-place" );
            ecoStationForm.onfocus = function(){
            ecoStationForm.onkeydown = function(e)
            {
                // Mozilla(Firefox, NN) and Opera
                keycode = (e != null) ? e.which : event.keyCode;
                //return
                switch( keycode ){
                    case 13:
                        if (e != null) {
                            // イベントの上位伝播を防止
                            e.preventDefault();
                            e.stopPropagation();
                            // Internet Explorer
                        } else {
                            event.returnValue = false;
                            event.cancelBubble = true;
                        }
                        EcoClass.prototype.search();
                        break;

                    default:
                        break;
                }
            }
        }},

        controlResultField: function( Boolean )
        {
            var station = document.getElementById( "station-col" );
            station.style.display = Boolean ? "block" : "none";
        },

        calculate: function()
        {
            if (this.checkValue()){
                var obj = new Object();
                obj.dest = encodeURIComponent(StationList.dest);
                var num = document.getElementById("numTrips").value;
                obj.numTrips = this.checkNumber(num) ? num : 1;
                var numExpances = document.getElementById("pExpence").value;
                obj.numExpances = this.checkNumber(numExpances) ? numExpances : 1;
                for (var i = 0; i < StationList.start.length; i++) {
                    var num = document.getElementById(StationList.start[i].id + "_numPersons").value;
                    obj['name' + (i+1)] = encodeURIComponent(StationList.start[i].name);
                    obj['num' + (i+1)] = (undefined == num || 0 == num || !this.checkNumber(num)) ? 1 : num;
                }
                var result = this.CalculateClass.execute(obj);
                this.setResult(result);
            }
        },

        /** 計算結果出力 **/
        setResult: function(result)
        {
            //月の出張回数
            var num = document.getElementById("numTrips").value;
            var numTrips = this.checkNumber(num) ? num : 1;
            var expances = document.getElementById("pExpence").value;
            var numExpances = this.checkNumber(expances) ? expances : 0;

            var fare = result.fare * numTrips * 2;
            var time = result.time * numTrips * 2;
            var co2 = result.co2 * numTrips * 2;

            //月出張費
            var mFare = document.getElementById("mFare");
            this.FormClass.remove(mFare);
            mFare.appendChild(document.createTextNode(this.numberFormat(fare)));

            //月時間
            var mTime = document.getElementById("mTime");
            this.FormClass.remove(mTime);
            mTime.appendChild(document.createTextNode(this.formatTime(time)));

            //月co2
            var mCo2 = document.getElementById("mCo2");
            this.FormClass.remove(mCo2);
            mCo2.appendChild(document.createTextNode(this.co2Format(co2)));

            //月人件費
            var mExpances = document.getElementById("mExpances");
            this.FormClass.remove(mExpances);
            mExpances.appendChild(document.createTextNode(this.expanceFormat(numExpances, time, 1)));

            //年出張費
            var yFare = document.getElementById("yFare");
            this.FormClass.remove(yFare);
            yFare.appendChild(document.createTextNode(this.numberFormat(fare * 12)));

            //年時間
            var yTime = document.getElementById("yTime");
            this.FormClass.remove(yTime);
            yTime.appendChild(document.createTextNode(this.formatTime(time * 12)));

            //年co2
            var yCo2 = document.getElementById("yCo2");
            this.FormClass.remove(yCo2);
            yCo2.appendChild(document.createTextNode(this.co2Format(co2 * 12)));

            //年人件費
            var yExpances = document.getElementById("yExpances");
            this.FormClass.remove(yExpances);
            yExpances.appendChild(document.createTextNode(this.expanceFormat(numExpances, time, 12)));
        },

        formatTime: function(time)
        {
            var string = new String();
            if (time >= 60) {
                string = Math.floor(time / 60);
                string += "時間";
                string += time % 60;
                string += "分";
            } else {
                string = time + "分";
            }
            return string;
        },

        numberFormat: function(num)
        {
              return num.toString().replace( /([0-9]+?)(?=(?:[0-9]{3})+$)/g , '$1,' );
        },

        co2Format: function(num)
        {
            if (0 == num)
              return '0 g';
            var s = new Array('g', 'Kg', 't', 'kt', 'Mt', 'Gt');
            var e = Math.floor(Math.log(num)/Math.log(1000));
            return sprintf('%.1f ' + s[e], (num / Math.pow(1000, Math.floor(e))));
        },

        expanceFormat: function(numExpances, time, y)
        {
            return '¥' + Math.floor(numExpances * (time / 60) * y);
        },

        /** 開催地と出発地を最低一つ **/
        checkValue: function()
        {
            var message = new Array();
            if (undefined == StationList.dest) {
                message.push("・「出張の目的地」の設定が済んでいません。");
            }
            if (0 == StationList.start.length) {
                message.push("・設定が済んでいない「出発地」があります。");
            }

            if (message.length > 0) {
                alert(message.join("\n"));
                return false;
            } else
                return true;
        },

        check: function()
        {
            for ( var i = 1; i <= 5; i++) {
                var start = document.getElementById('start' + i + "_result");
                if (start.value ){
                    return true;
                }
            }
            return false;
        },

        checkNumber: function(value)
        {
            return value.match(/[0-9]+/) ? true : false;
        },

        resetAll: function()
        {
            StationList.start = [];
            StationList.dest = undefined;

            var dest = document.getElementById("dest");
            dest.value="";
            var mFare = document.getElementById("mFare");
            this.FormClass.remove(mFare);
            var tDest = document.getElementById("dest_result");
            this.FormClass.remove(tDest);
            var yFare = document.getElementById("yFare");
            this.FormClass.remove(yFare);
            var numTrips = document.getElementById("numTrips");
            numTrips.value=1;
            var tResult = document.getElementById("dest-station-col");
            tResult.display = "none";
            var pExpence = document.getElementById("pExpence");
            pExpence.value="";

            for(var i = 1; i <= 5; i++){
                this.reset(i);
            }
            var mTime = document.getElementById("mTime");
            this.FormClass.remove(mTime);
            var mCo2 = document.getElementById("mCo2");
            this.FormClass.remove(mCo2);
            var mExpances = document.getElementById("mExpances");
            this.FormClass.remove(mExpances);

            var yTime = document.getElementById("yTime");
            this.FormClass.remove(yTime);
            var yCo2 = document.getElementById("yCo2");
            this.FormClass.remove(yCo2);
            var yExpances = document.getElementById("yExpances");
            this.FormClass.remove(yExpances);
        },

        reset: function(i)
        {
            var t = "start" + i;
            var tStation = document.getElementById(t);
            tStation.value = "";
            var tResult = document.getElementById(t + "-station-col");
            tResult.display = "none";
            var tResult2 = document.getElementById(t + "_result");
            this.FormClass.remove(tResult2);
            var tNum = document.getElementById(t + "_numPersons");
            tNum.value = "";
        },

        initialize: function()
        {
            this.resetAll();
        }
};

