/**
 * @author mtanaka
 */

var GoogleDirectionsServiceRequest = Class.create();

GoogleDirectionsServiceRequest.prototype = {
	
	routeline: null, // ルートのオーバレイオブジェクト． GPolyline
	distance: null, // ルートの距離 double?
	duration: null, // 所要時間 duration
	bShown: false, // ルート表示中フラグ
	bRequestCompleted: false, // Ajaxリクエストの完了フラグ
	mapHandler: null, // Google mapsのハンドラ GmapHandler
	manager: null, // リクエストを管理するオブジェクト GeoInfoManager
	
	query: null,
	directions: null, // ルート検索のオブジェクト GDirections

	/**
	 * Ajaxリクエストを生成
	 * @param {Object} params
	 * 	params.indexStart ルート開始点のインデックス
	 *  params.indexEnd ルート終了点のインデックス
	 *  params.mapHandler Google mapsのハンドラ GmapHandler
	 *  params.manager リクエストを管理するオブジェクト GeoInfoManager
	 */
	initialize: function(params) {	
		
		this.mapHandler = params.map;
		this.manager = params.manager;

		var map = this.mapHandler.getMap();
	
		this.bRequestCompleted = false;

		// ルートをリクエスト	
		this.query = "from: " + params.start + " to: " + params.end;
		this.manager.notifyRouteRequestIssued();
		this.createRequest();
	},

		
	createRequest: function() {
			this.directions = new GDirections(null, null);
			GEvent.bind(this.directions, "load", this, this.complete);
			GEvent.bind(this.directions, "error", this, this.requestError);
			this.directions.load(this.query, { locale: "ja_JP", getPolyline: true } );
	},

	requestError :function() {		
		setTimeout(this.createRequest.bind(this), 3000);
	},

	/**
	 * GDirections.loadに設定するコールバック関数
	 * 
	 * 下記を設定
	 * this.arrayLines: 表示ライン
	 * this.bRequestCompleted: リクエスト完了
	 * this.manager.decrementRequest(): リクエスト数をデクリメント
	 * 
	 * @param {Object} httpObj
	 */ 
	complete : function(){ 
	
		this.routeline = this.directions.getPolyline();
		this.distance = this.directions.getDistance().meters;
		this.duration = this.directions.getDuration().seconds;
	
		this.mapHandler.addRoute(this.routeline);

		this.bRequestCompleted = true;
		this.manager.notifyRouteRequestCompleted();
	},
	
	gerRouteline: function() {
		return this.routeline;
	},
	
	/**
	 * 経路の距離を返す．
	 * @return (double) 距離．Ajaxリクエストが未完了ならnull.
	 */
	getDistance: function() {
		if(!this.bRequestCompleted) return null;
		return this.distance;
	},
	
	/**
	 * マップ上に経路を表示
	 */
/*	show: function() {
		if (!this.bShown && this.bRequestCompleted) {
//			this.mapHandler.showRoute(this.routeline);
			this.mapHandler.getMap().addOverlay(this.routeline);

			this.bShown = true;
		}
	},
*/
	/**
	 * マップ上の経路を非表示に
	 */
/*	hide: function() {
		if (this.bShown) {
//			this.mapHandler.hideRoute(this.routeline);
			this.mapHandler.getMap().removeOverlay(this.routeline);

			this.bShown = false;
		}
	},
*/	
	// key1=value1&key2=value2形式のパラメータを得る．
	toRequestParam: function(objParam) {
		return $H(objParam).toQueryString();
	}
	
};

