/* ================================================================ *
    ajaxzip2.js ---- ADDRAjax Ajaxによる住所ドリルダウン検索
    + ナース用検索プルダウンの初期設定

    Copyright (c) 2006-2007 Kawasaki Yusuke <u-suke [at] kawa.net>
    http://www.kawa.net/works/ajax/ajaxzip2/ajaxzip2.html

    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use,
    copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following
    conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.


	※　以下の部分をナースの星用に改造しています。
	　・地区表示の削除
	　・都道府県は県名でなく都道府県IDを返す
	　・一定の都道府県しか市区町村を返さない
	　・市区町村multipul対応
	　・
	　・
* ================================================================ */

ADDRAjax = function (fpref,fcity,fservice,ftype) {
    if ( fpref ) this.form_pref = fpref;
    if ( fcity ) this.form_city = fcity;
    if ( fservice ) this.form_service = fservice;
    if ( ftype ) this.form_type = ftype;
};
ADDRAjax.VERSION = '2.11';

// デフォルト値
ADDRAjax.prototype.JSONDATA = 'js/ajaxzip2/data';
ADDRAjax.prototype.URL_SUFFIX = '';
ADDRAjax.prototype.form_pref = 'pref';
ADDRAjax.prototype.form_city = 'city[]';
ADDRAjax.prototype.form_service = 'service[]';
ADDRAjax.prototype.form_type = 'types[]';
ADDRAjax.prototype.onChange = function(pref,city){};

// 都道府県名の一覧
ADDRAjax.prototype.PREF_MAP = [
    null,       '北海道',   '青森県',   '岩手県',   '宮城県',
    '秋田県',   '山形県',   '福島県',   '茨城県',   '栃木県',
    '群馬県',   '埼玉県',   '千葉県',   '東京都',   '神奈川県',
    '新潟県',   '富山県',   '石川県',   '福井県',   '山梨県',
    '長野県',   '岐阜県',   '静岡県',   '愛知県',   '三重県',
    '滋賀県',   '京都府',   '大阪府',   '兵庫県',   '奈良県',
    '和歌山県', '鳥取県',   '島根県',   '岡山県',   '広島県',
    '山口県',   '徳島県',   '香川県',   '愛媛県',   '高知県',
    '福岡県',   '佐賀県',   '長崎県',   '熊本県',   '大分県',
    '宮崎県',   '鹿児島県', '沖縄県'
];

// 市区町村を表示する都道府県ID
ADDRAjax.prototype.CITY_DISPLAY_PREF = new Array ('11','12','13','14','23','26','27');

// キャッシュ格納用
ADDRAjax.prototype.JSON_CACHE = [];


ADDRAjax.prototype.SERVICE_OPT = [
    null,  '病院', 'クリニック', '介護関連施設', '訪問看護・入浴', 'デイサービス', 'その他'
];

ADDRAjax.prototype.TYPE_OPT = [
    null,  '常勤（正社員）', '非常勤（パート）', '紹介予定派遣', '派遣社員'
];

// 都道府県名→都道府県IDの逆変換表
new function(){
    var rev = {};
    var map = ADDRAjax.prototype.PREF_MAP;
    for( var i=0; i<map.length; i++ ) {
        if ( ! map[i] ) continue;
        rev[map[i]] = i;
    }
    ADDRAjax.prototype.PREF_REV = rev;
};

// 初期化
ADDRAjax.prototype.init = function () {
    // フォームの各変数を検索
    var apref = document.getElementsByName( this.form_pref );
    var acity = document.getElementsByName( this.form_city );
    var asrvc = document.getElementsByName( this.form_service );
    var atype = document.getElementsByName( this.form_type );
    if ( ! apref ) return;
    if ( ! acity ) return;
    if ( ! asrvc ) return;
    if ( ! atype ) return;

    // フォームの各変数を確認
    this.elem_pref = apref[0];
    this.elem_city = acity[0];
    this.elem_srvc = asrvc[0];
    this.elem_type = atype[0];
    if ( ! this.elem_pref ) return;
    if ( ! this.elem_city ) return;
    if ( ! this.elem_srvc ) return;
    if ( ! this.elem_type ) return;

    // 初回に1度だけ使用するコールバック関数
    this.onceAfterPref    = null;
    this.onceAfterCity    = null;
    this.onceAfterService = null;
    this.onceAfterType    = null;

    // 都道府県名のプルダウンを初期化
    this.initSelectList( this.elem_pref, this.PREF_MAP );
    this.initSelectList( this.elem_srvc, this.SERVICE_OPT );
    this.initSelectList( this.elem_type, this.TYPE_OPT );
    this.initSelectList( this.elem_city, [] );

    // イベントハンドラの登録
    var __this = this;
    if ( window.Event && Event.observe ) {
        Event.observe( this.elem_pref, 'change', function(){__this.onChangePref();} );
    }
    else if ( window.jQuery ) {
        jQuery( this.elem_pref ).bind( 'change', function(){__this.onChangePref();} );
    }
};

// プルダウンの初期化
ADDRAjax.prototype.initSelectList = function ( elem, list, defval ) {
    var opts = elem.options;

    for( var i=opts.length; i>0; i-- ) {
        if ( ! opts[i] ) continue;
        opts[i].parentNode.removeChild( opts[i] );
    }
    if ( list.length ) {
        elem.disabled = false;
    } else {
        elem.disabled = true;
    }
    for( var i=0; i<list.length; i++ ) {
        var str = list[i];
        if ( ! str ) continue;
        if ( typeof(str) == 'object' ) str = str[1];
        var eopt = document.createElement( 'option' );
        elem.appendChild( eopt );
        eopt.text  = str;

        if( elem.name != this.form_city ){
	        eopt.value = i;
		}else{
			eopt.value = i+1;
		}
		if(defval instanceof Array){
			for( var z=0; z<defval.length; z++ ){
				if( eopt.value == defval[z] ){
					eopt.selected = true;
				}
			}
		}else{
	        if ( str == defval ) eopt.selected = true;
		}
    }
}





// プルダウンの値を取得する
ADDRAjax.prototype.getSelectValue = function (elem) {
    var opts = elem.options;
    if ( ! opts ) return;
    for( var i=0; i<opts.length; i++ ) {
        if ( opts[i].selected ) return opts[i].value;
    }
};
ADDRAjax.prototype.getPrefValue = function () {
    return this.getSelectValue( this.elem_pref );
};
ADDRAjax.prototype.getCityValue = function () {
    return this.getSelectValue( this.elem_city );
};

// プルダウンの値を選択する
ADDRAjax.prototype.setSelectValue = function (elem,values) {
    if ( ! elem ) return;
    var opts = elem.options;
    if ( ! opts ) return;

    for( var i=0; i<opts.length; i++ ) {
        opts[i].selected = false;
    }

    for( var i=0; i<opts.length; i++ ) {
		if(values instanceof Array){
			for( var z=0; z<values.length; z++ ){
				if( isNaN(opts[i].value) ){
					if( opts[i].value == values[z] ){
						opts[i].selected = true;
						break;
					}
				}else{
					if( opts[i].value == eval(values[z]) ){
						opts[i].selected = true;
						break;
					}
				}
			}
		}else{
	        if ( opts[i].value == values ) {
    	        opts[i].selected = true;
    	    }
		}
    }
};

// Safariの文字化け防止
ADDRAjax.prototype.getResponseText = function ( req ) {
    var text = req.responseText;
    if ( navigator.appVersion.indexOf('KHTML') > -1 ) {
        var esc = escape( text );
        if ( esc.indexOf('%u') < 0 && esc.indexOf('%') > -1 ) {
            text = decodeURIComponent( esc );
        }
    }
    return text;
};

// 都道府県の選択時に呼ばれるイベント
ADDRAjax.prototype.onChangePref = function () {
    var vpref = this.getPrefValue();
    var __this = this;

    var prefcb = function (data){
        if( __this.onceAfterPref ){
            __this.onceAfterPref( vpref, '' );
            __this.onceAfterPref = null;
        }else if( __this.onChange ){
            __this.onChange( vpref, '' );
        }
    }

	if( !vpref ) {
    	__this.initSelectList( __this.elem_city, [] );
        window.setTimeout( prefcb, 1 );
        return;
    }

    var prefid = vpref;
    if ( !prefid ) return;

    var flag = 0;
    for( i=0; i<this.CITY_DISPLAY_PREF.length; i++ ){
    	if( this.CITY_DISPLAY_PREF[i] == prefid ){
    		flag = 1;
    		break;
    	}
    }
    if( flag != 1 ){
    	__this.initSelectList( __this.elem_city, [] );
        window.setTimeout( prefcb, 1 );
        return;
    }

    var updateCityList = function (data) {
        __this.initSelectList( __this.elem_city, data[2] );
        window.setTimeout( prefcb, 1 );
    };

    var data = this.JSON_CACHE[prefid];
    if ( data ) return updateCityList( data );

    // JSONファイル名を決定する
    var pref2 = ''+prefid;
    if ( pref2.length < 2 ) pref2 = '0' + pref2;
    var url = this.JSONDATA+'/pref-'+pref2+'.json'+this.URL_SUFFIX;

	if(url.onerror){
        this.initSelectList( this.elem_city, [] );
        window.setTimeout( prefcb, 1 );
        return;
	}

    if ( window.Ajax && Ajax.Request ) {
        // JSONファイル受信後のコールバック関数（Prototype.JS用）
        var recv_prototype = function (req) {
            if ( ! req ) return;
            if ( ! req.responseText ) return;
            var json = __this.getResponseText( req );
            data = eval('('+json+')');
            __this.JSON_CACHE[prefid] = data;
            updateCityList( data );
        };
        var opt = {
            method: 'GET',
            asynchronous: true,
            onComplete: recv_prototype
        };
        new Ajax.Request( url, opt );
    }
    else if ( window.jQuery ) {
        // JSONファイル受信後のコールバック関数（jQuery用）
        var recv_jquery = function (data) {
            __this.JSON_CACHE[prefid] = data;
            updateCityList( data );
        };

        jQuery.getJSON( url, recv_jquery );
    }
};

// 指定地域に移動する
ADDRAjax.prototype.setAddress = function (pref,city,service,types) {

    if ( pref ) {
        var __this = this;
        if ( city ) {
            this.onceAfterPref = function () {
                __this.setSelectValue( __this.elem_city, city );
            };
        }
        var func = function () {
            __this.setSelectValue( __this.elem_pref, pref );
            __this.onChangePref();
        };
        window.setTimeout( func, 1 );
    }
    if(service) {
        var __this = this;
        var func = function () {
            __this.setSelectValue( __this.elem_srvc, service );
        };
        window.setTimeout( func, 1 );
    }
    if(types) {
        var __this = this;
        var func = function () {
            __this.setSelectValue( __this.elem_type, types );
        };
        window.setTimeout( func, 1 );
    }
};



