/*****************************************************************************
 * iSAS.js - iSAS Javascript Interface.
 *
 * Copyright(c) 2006,2007 NEC System Technologies, Ltd. All rights reserved.
 * No reproduction of this program without permission.
 *
 * Version 1.00, 2006/12/14  necst miso.
 * Version 1.01, 2007/01/16  necst miso.  WMPイベントハンドラを追加
 * Version 1.02, 2007/03/09  necst miso.  初回呼び出し時のcookie取得処理を追加
 *
 *****************************************************************************/
var val_cm_id;

//var iSAS_Debug	= true;
var iSAS_RequestBaseUrl	= 'http://dsal.er.cyberwing.co.jp/hserver/';	//CMリクエスト用ベースURL
var iSAS_Keywords	= 'site|area|al|fn|kn|ln|ma|sg';	//CMリクエストパラメータ名のリスト
var iSAS_CM		= null;
var iSAS_Loading	= false;
var iSAS_Interval	= 100;
var iSAS_TimerId	= 9999;
var iSAS_Timer;
var iSAS_TimerCount;
var iSAS_TrackingImage	= null;
var iSAS_IF_Element	= null;
var iSAS_CB		= { onCMLoad : null, onCMStop : null };
var iSAS_LoadImage	= false;
var iSAS_LoadImageUrl	= 'http://dsal.er.cyberwing.co.jp/iserver/site=NIF_dummy/area=main/';	//cookie取得用リクエストURL

//WMPイベント処理用
var iSAS_EH_Element = null;
var iSAS_EH_Attribute =
{
	scritpID	: 'iSAS_EventHandler'
,	playerID	: 'wmp'
,	scriptUrl	: 'http://ak.dr.cyberwing.co.jp/scripts/iSAS/nftstream/iSAS_WmpEventHandler.js'
,	scriptLang	: 'Javascript'
,	eventType	: 'playStateChange( wmp_state )'
};

var CmRequest, CmEvent;		//パラメータ退避用

//AdManagerへ広告要求を行う
function iSAS_CM_LOAD( request, event )
{
	//応答待ちの場合は何もしない
	if ( iSAS_Loading )
	{
		return;
	}

	iSAS_Loading = true;

	//iSAS_cm_load_mainのパラメータ(img.onloadでパラメータが渡せないのでここで変数に退避しておく)
	CmRequest = request;
	CmEvent = event;

	//cookie取得のためのダミーリクエストを発行（初回のみ）
	if ( !iSAS_LoadImage )
	{
		iSAS_LoadImage	= true;
		var img		= new Image();
		img.src		= iSAS_LoadImageUrl;
		img.onload	= iSAS_cm_load_main;	//imageのロードが終わったらCMのロードへ
		img.onerror	= iSAS_cm_load_main;	//imageのロードが失敗してもCMのロードへ(cookieないけど。。)
	}

	//２回目以降はそのままCMのロードへ
	else
	{
		iSAS_cm_load_main();
	}

	return;
}

//表示回数のカウントアップ
function iSAS_CM_TRACK()
{
	if ( typeof iSAS_CM.param.playaction == 'undefined' )
	{
		//iSAS_debug_alert('no playaction!');
		return false;
	}

	//iSAS_debug_alert( iSAS_CM.param.playaction );

	//既にAdManagerへリクエストを送信している場合は無効
	if ( iSAS_CM.tracked )
	{
		return false;
	}

	//AdManagerへリクエストを送信
	iSAS_CM.tracked = true;
	iSAS_TrackingImage = new Image();
	iSAS_TrackingImage.src = iSAS_CM.param.playaction;

	return true;
}


/**********************************************************
 * private method.
 **********************************************************/

function iSAS_cm_load_main()
{
	//初期化
	val_cm_id	= '';
	iSAS_Timer	= CmEvent.Timeout || 10000;
	iSAS_TimerCount	= 0;
	iSAS_TimerId	= -1;
	iSAS_CB.onCMLoad = ( typeof( CmEvent.onCMLoad ) == 'function' )?  CmEvent.onCMLoad : null;
	iSAS_CB.onCMStop = ( typeof( CmEvent.onCMStop ) == 'function' )?  CmEvent.onCMStop : null;

	//広告管理用オブジェクトの生成と初期化
	iSAS_CM			= new Object();
	iSAS_CM.ready		= false;
	iSAS_CM.timedout	= false;
	iSAS_CM.tracked		= false;
	iSAS_CM.request		= iSAS_build_request( CmRequest );	//広告要求URLの生成
	iSAS_CM.param		= null;

	//イベントハンドラを追加（初回呼び出し時のみ）
	if ( !iSAS_EH_Element )
	{
		iSAS_EH_Attribute.playerID = CmEvent.PlayerID;

		iSAS_EH_Element = document.createElement("script");
		iSAS_EH_Element.setAttribute('id', iSAS_EH_Attribute.scriptID );
		iSAS_EH_Element.setAttribute('htmlFor', iSAS_EH_Attribute.playerID );
		iSAS_EH_Element.setAttribute('src', iSAS_EH_Attribute.scriptUrl );
		iSAS_EH_Element.setAttribute('event', iSAS_EH_Attribute.eventType );
		iSAS_EH_Element.setAttribute('language', iSAS_EH_Attribute.scriptLang );
		document.body.appendChild( iSAS_EH_Element );
	}

	//２回目以降の呼び出しではPlayerIDのみチェックして変わっていたら設定する
	else if ( iSAS_EH_Attribute.playerID != CmEvent.PlayerID )
	{
		iSAS_EH_Attribute.playerID = CmEvent.PlayerID;
		document.getElementById( iSAS_EH_Attribute.scriptID ).htmlFor = iSAS_EH_Attribute.playerID;
	}

	if( iSAS_IF_Element )
	{
		document.body.removeChild( iSAS_IF_Element );	//前回のCMのElementを削除する
	}

	//AdManagerへリクエストを送信
	iSAS_IF_Element = document.createElement("script");
	iSAS_IF_Element.setAttribute('type', 'text/javascript');
	iSAS_IF_Element.setAttribute('src', iSAS_CM.request );
	document.body.appendChild( iSAS_IF_Element );

	//AdManagerからの応答待ち
	iSAS_check_response();
}

function iSAS_debug_alert( msg )
{
	if ( iSAS_DEBUG )
	{
		alert( msg );
	}

	return;
}

//AdManagerへのリクエストURLの組み立て
function iSAS_build_request( CmRequest )
{
	var request_url = iSAS_RequestBaseUrl;
	for ( m in CmRequest )
	{
		//無効なパラメータは無視
		if ( !m.match('^(' + iSAS_Keywords + ')$') ||  CmRequest[m].match('[^A-Za-z0-9_]'))
		{
			continue;
		}

		request_url += ( m + '=' + CmRequest[m] + '/' );
	}

	//cache busting.
	var d = new Date();
	var n = '' + d.getTime() + Math.round( Math.random() * 100000000 );
	request_url += ( 'acc_random=' + n + '/' );

	return request_url;
}

//AdManagerからの応答チェック
function iSAS_is_ready()
{
	//val_cm_idがセットされていれば応答あり！
	return ( typeof( iSAS_CM ) == 'object'  &&  val_cm_id != '' )?  true : false;
}

//AdManagerからの応答後の処理
function iSAS_post_load ( bStat )
{
	//ステータス設定
	iSAS_CM.ready = bStat;

	//応答待ちフラグ解除
	iSAS_Loading = false;

	//コールバック関数が指定されている場合は呼び出す
	if ( typeof( iSAS_CB.onCMLoad ) == 'function' )
	{
		iSAS_CB.onCMLoad( iSAS_CM );
	}
}

//AdManagerからの応答チェック
function iSAS_check_response()
{
	if ( typeof( iSAS_CM ) != 'object' )
	{
		return;
	}

	//タイマクリア
	clearInterval( iSAS_TimerId );

	//応答済みの場合
	if ( iSAS_is_ready())
	{
		iSAS_set_params();
		iSAS_post_load( true );
	}

	//タイムアウトの場合
	else if (( iSAS_TimerCount * iSAS_Interval ) > iSAS_Timer )
	{
//iSAS_debug_alert('timeout: n=' + nTimerCount + '  i=' + nInterval + '  t=' + nTimer );

		//タイムアウト後に広告情報が戻された場合を考慮して要素を削除する
		document.body.removeChild( iSAS_IF_Element );
		iSAS_IF_Element = null;
		iSAS_CM.timedout = true;
		iSAS_post_load( false );
	}

	//未応答の場合
	else
	{
		//タイマセット
		iSAS_TimerId = setInterval('iSAS_check_response()', iSAS_Interval );
		iSAS_TimerCount++;
	}
}


//Admanagerから返された広告情報をオブジェクトに設定する
function iSAS_set_params()
{
	//オブジェクト生成
	var param = new Object();

	//メンバ変数
	param.cm_id		= val_cm_id;			//広告ID
	param.cm_name		= val_cm_name;			//動画タイトル
	param.cm_file_seq1	= val_cm_file_seq1;		//1固定（標準画質）
	param.cm_file_quality1	= val_cm_file_quality1;		//1固定（標準画質）
	param.cm_file_asx_url1	= val_cm_file_asx_url1;		//動画URL（標準画質）
	param.cm_file_wmv_url1	= val_cm_file_wmv_url1;		//動画URL（標準画質）
	param.cm_file_seq2	= val_cm_file_seq2;		//2固定（高画質）
	param.cm_file_quality2	= val_cm_file_quality2;		//2固定（高画質）
	param.cm_file_asx_url2	= val_cm_file_asx_url2;		//動画URL（高画質）
	param.cm_file_wmv_url2	= val_cm_file_wmv_url2;		//動画URL（高画質）
	param.cm_file_seq3	= val_cm_file_seq3;		//3固定（超高画質）
	param.cm_file_quality3	= val_cm_file_quality3;		//3固定（超高画質）
	param.cm_file_asx_url3	= val_cm_file_asx_url3;		//動画URL（超高画質）
	param.cm_file_wmv_url3	= val_cm_file_wmv_url3;		//動画URL（超高画質）
	param.cm_txtlink	= val_cm_txtlink;		//テキスト広告クリックURL
	param.cm_txttitle	= val_cm_txttitle;		//テキスト広告文字列
	param.cm_primg		= val_cm_primg;			//バナーURL
	param.cm_primgalt	= val_cm_primgalt;		//バナーALT文字列
	param.cm_prlink		= val_cm_prlink;		//バナークリックURL
	param.cm_linktarget	= val_cm_linktarget;		//リンクターゲット
	param.playaction	= val_playaction;		//トラッキングURL

	iSAS_CM.param = param;
	return true;
}


//動画終了時の処理（プレイヤーのイベントハンドラから呼び出される）
function iSAS_onStopMovie()
{
	if ( typeof( iSAS_CB.onCMStop ) == 'function' )
	{
		iSAS_CB.onCMStop();
	}
}

//動画開始時の処理（プレイヤーのイベントハンドラから呼び出される）
function iSAS_onStartMovie()
{
	iSAS_CM_TRACK();		//imp数のインクリメント
}

/* iSAS.js */






