/**=========================================

 filename:  utils.js
 create:    2009/
 copyright: 

=========================================**/
(function(){
//---------------------------------------------------------------------------------------------------------------------utils名前空間
var utils = function (){}
var MEMBERS = utils.prototype;

//---------------------------------------------------------------------------------------------------------------------ボタン関係
/**
 * ロールオーバー機能を付加
 * @idName(imgタグのやつで)
 * @offImg
 * @onImg
 * 
 * 
 */
MEMBERS.addRollActionById = function( idName )
{
	if( $('#' + idName).size() == 0 ) return;
	
	var img = this.getImg( idName );
	if( !img ) return;
	
	var onoffPass = MEMBERS.getImgSrc(img);
	var onImg = onoffPass[ 0 ];
	var offImg = onoffPass[ 1 ];
	this.addRollAction( img, onImg, offImg );
}

/**
 * 指定classをもつ要素を一括してロールオーバー設定
 * @className
 * imgタグのクラスでも一つ上の要素のクラスでもok
 */
MEMBERS.addRollActionByClass = function( className )
{
	$( "." + className).each(function()
	{
		if( $(this).size() > 0 )
		{
			
			var img = '';
			
			if ($(this).is('img'))
			{
				var img = $(this);
			}else 
			if ($(this).children('img').is('img'))//直下にimgがあれば（複数無理）
			{
				var img = $(this).children('img');
			}
				
			if(img != '')
			{
				var onoffPass = MEMBERS.getImgSrc(img);
				var onImg = onoffPass[ 0 ];
				var offImg = onoffPass[ 1 ];
				
				//機能設定
				MEMBERS.addRollAction( img, onImg, offImg );
			}
		}
	});
}

/**
 * ロールオーバー機能を付加
 * @idName
 */
MEMBERS.removeRollActionById = function( idName )
{
	var img = this.getImg( idName );
	if( !img ) return;
	this.removeRollAction( img );
}
MEMBERS.removeRollAction = function( img )
{
	img.unbind( "mouseout" );
	img.unbind( "mouseover" );
	if(img.parent() && img.parent().get(0).tagName == "A" )//一つ上の要素がa
	{
		img.parent().unbind( "focus" );
		img.parent().unbind( "blur" );
	}
	if(img.parent() && img.parent().get(0).tagName == "INPUT" )//一つ上の要素がInput
	{
		img.parent().unbind( "focus" );
		img.parent().unbind( "blur" );
	}
}



//---------------------------------------------------------------------------------------------------------------------テキストサイズ変更
/**
 * 大中小のボタン
 * cookie使用　txResizeBtnCond1 txResizeBtnCond2 txResizeBtnCond3
 */
MEMBERS.textSizeBtnAction = function()
{
	MEMBERS.initTextSize();
	
	//ボタンが無ければリサイズのみして終わり
	if( $("#textResizeBtn1").size() == 0 ) return;
	
	var img;
	var baseName;
	var btnIds = [ 'textResizeBtn1', 'textResizeBtn2', 'textResizeBtn3' ];
	var i,m=3;
	for( i=0; i<3; i++ )
	{
		if( $.cookie( 'txResizeBtnCond' + i ) != 'Active' )
		{
			img = window.utils.getImg( btnIds[ i ] );
			baseName = img.attr( "src" ).substring( 0, img.attr( "src" ).lastIndexOf( "/" ) );
		}
	}
	var imgNames = [ baseName + "/btn_fontsize_s", baseName + "/btn_fontsize_m", baseName + "/btn_fontsize_l" ];
	
	var i;
	var m=btnIds.length;
	for( i=1; i<=m; i++ )
	{
		MEMBERS.removeRollActionById( btnIds[i-1] );
		if( $.cookie( 'txResizeBtnCond' + i ) == 'Active' )
		{
			//ロールオーバー画像を設定するだけ
			img = window.utils.getImg( btnIds[ i-1 ] );
			img.attr({src: imgNames[ i-1 ] + "_active.gif" });
		}else
		//if( $.cookie( 'txResizeBtnCond' + i ) == 'unActive' )
		{
			img = window.utils.getImg( btnIds[ i-1 ] );
			img.attr({src: imgNames[ i-1 ] + ".gif" });
			
			//ロール処理
			MEMBERS.addRollActionById(btnIds[i-1]);
			$("#" + btnIds[i-1]).click(setTextSize);
			
		}
	}
}
/**
 * cookieの情報からbodyのスタイル変更
 * 
 */
function setTextSize()
{
	$.cookie( 'txResizeBtnCond1', 'unActive',  {  path:'/', expires: 7 });
	$.cookie( 'txResizeBtnCond2', 'unActive',  {  path:'/' , expires: 7 } );
	$.cookie( 'txResizeBtnCond3', 'unActive',  {  path:'/' , expires: 7 } );
	
	var id = $( this ).attr( 'id' );
	var size = id.substr( id.length-1, 1 );
	switch(size)
	{
		case '1' :
			$('body').css('font-size', '10px');
			if( $('#footer').size() > 0 ) $('#footer').css('font-size', '13px');
			$.cookie( 'txResizeBtnCond1', 'Active', { path:"/" , expires: 7 } );
			MEMBERS.textSizeBtnAction();
		break;
		case '2' :
			$('body').css('font-size', '13px');
			if( $('#footer').size() > 0 ) $('#footer').css('font-size', '13px');
			$.cookie( 'txResizeBtnCond2', 'Active', { path:"/" , expires: 7 } );
			MEMBERS.textSizeBtnAction();
		break;
		case '3' :
			$('body').css('font-size', '16px');
			if( $('#footer').size() > 0 ) $('#footer').css('font-size', '13px');
			$.cookie( 'txResizeBtnCond3', 'Active', { path:"/" , expires: 7 } );
			MEMBERS.textSizeBtnAction();
		break;
	}
}

MEMBERS.initTextSize = function()
{
	for( i=1; i<=3; i++ )
	{
		if( $.cookie( 'txResizeBtnCond' + i ) == "Active" )
		{
			switch(i)
			{
				case 1 :
					$('body').css('font-size', '10px');
					if( $('#footer').size() > 0 ) $('#footer').css('font-size', '13px');
				break;
				case 2 :
					$('body').css('font-size', '13px');
					if( $('#footer').size() > 0 ) $('#footer').css('font-size', '13px');
				break;
				case 3 :
					$('body').css('font-size', '16px');
					if( $('#footer').size() > 0 ) $('#footer').css('font-size', '13px');
				break;
			}
			//break;
		}
	}
}

//---------------------------------------------------------------------------------------------------------------------ピックアップボタン
/**
 * おススメProgramのスケジュール取得
 * ピックアップ プログラム部分
 */
var selecteBtns;
var otherBtns;
MEMBERS.setId = function()
{
	selecteBtns = $( ".selectedProgramSchedule" );
	otherBtns = $( ".otherProgramSchedule" );
	
	var i,m;
	m = selecteBtns.length;
	for( i=0; i<m; i++ )
	{
		MEMBERS[ "loadedFlagSelect" + i ] = false;
		$( selecteBtns[i] ).attr( "selectBtnId", i );
		
	}
	m = otherBtns.length;
	for( i=0; i<m; i++ )
	{
		MEMBERS[ "loadedFlagOther" + i ] = false;
		$( otherBtns[i] ).attr( "otherBtnId", i );
	}
}

/*

MEMBERS.selectedProgramScheduleOpen = function(_this)
{
	var id = $( _this ).attr( "selectBtnId" );
	alert( id );
	
	MEMBERS.getSchedule( MEMBERS[ "loadedFlagSelect" + id ], top_assigned_obj.selectedProgramIds[ parseInt( id ) ] , _this);
	
}
MEMBERS.otherProgramScheduleOpen = function(_this)
{
	var id = $( _this ).attr( "otherbtnid" );
	alert( id );
	MEMBERS.getSchedule( MEMBERS[ "loadedFlagOther" + id ], top_assigned_obj.selectedProgramIdsAcc[ parseInt( id ) ] , _this);
}

*/






MEMBERS.showProgramSchedule = function(opt)
{
	opt = opt || {};

	// Shadowboxに表示する
	if (opt.target && opt.target == "Shadowbox") {
		opt.target = "program-schedule-" + (new Date()).getTime();
	    Shadowbox.open({
	        content:    '<div id="' + opt.target  + '"></div>',
	        player:     "html",
	        title:      opt.title || "スケジュール",
			height:     "500",
			width:		"400",
			options: {
				//autoDimensions: true,
				//overlayColor: "#000000",
				//overlayOpacity: 1,
				//fadeDuration: 0.1,
				//resizeDuration: 0.1,
	            onFinish: function(){
	    			opt.target = "#" + opt.target;
	    			showProgramSchedule(opt);
	    		},
				onOpen : function(){ },
				onClose : function(){ }
	    	}
	    });
	    return;
	}

	var target   = $(opt.target || '#shadowBoxContent');
	var schedule = new TipProgramSchedule();

	// 読込み開始
	schedule.onPreLoad = function()
	{
		target.html("スケジュール検索中");
	}

	// 読込み完了
	schedule.onLoad = function(result) {
		var rows = result.data;
		var html = "";
		if (!rows || rows.length < 1) {
			html = "該当スケジュールはありません";
		} else {
			html = '<div class="tip-program-schedule" style="margin: 15px 5% 0pt;"><table>';
			//html += '<tr><th>年月日</th><th>時刻</th><th>プログラム名</th><th>インストラクタ</th></tr>';
			for (var i in rows) {
				
				var scheduleDate = new Date( rows[ i ].date.replace(/-/g,"/") );
				dateStr =  MEMBERS.keta(scheduleDate.getMonth()+1, 2)
					+ "/" + MEMBERS.keta(scheduleDate.getDate(), 2);
				html += Hx.template('<tr><th>' + dateStr + '</th><td>[$start_time]～[$end_time]</td><td>[$program_name]</td></tr>', rows[i]);
			}
			html += '</table></div>';
		}

		target.html(html);
	}

	// 検索パラメータ
	schedule.request.shop_id = opt.shop_id || "";
	schedule.request.lc_code = opt.lc_code || "";
	schedule.request.date    = opt.date    || "now";
	schedule.load();
}

// table
/*
var schedule = "<table>";
for( var i in response.data )
{
	var scheduleData = response.data[i];
	var txt = scheduleData.date.replace(/-/g,"/");
	var scheduleDate = new Date( txt );
	var scheduleDateString = scheduleDate.getFullYear().toString().substr(2)
							+ "/" + MEMBERS.keta(scheduleDate.getMonth()+1, 2)
							+ "/" + MEMBERS.keta(scheduleDate.getDate(), 2);
	schedule += "<tr><th>"+scheduleDateString+"</th><td>"+scheduleData.start_time+"～"+scheduleData.end_time+"</td></tr>";
}
schedule += "</table>";*/







//---------------------------------------------------------------------------------------------------------------------アコーディオン
MEMBERS.sectionBtns = [];
MEMBERS.tabs = [];
MEMBERS.tabsCond = [  ];
var collection = {};
var animationParam = {height:"toggle" /*, opacity:"toggle"*/};
var animating = false;
MEMBERS.setAcordionAnimation = function()
{
	/**
	 * タグ構造
	 * ボタン　↓
	 * < otherProgram1 ～ X > 
	 * < accordionBtn >
	 * < accordionAnime >
	 * 
	 * sections1~X = 
	 * [
	 * 		[ btn1, content1, height ,unActive, 送信ボタン,loadedFlag, 送信用コード ] ,	//1カテゴリ
	 * 		[ btn2, content2, height ,unActive, 送信ボタン,loadedFlag, 送信用コード ] ,	//1カテゴリ
	 * 		[ btn3, content3, height ,unActive, 送信ボタン,loadedFlag, 送信用コード ]		//1カテゴリ
	 * ]
	 * 
	 */
	var programIdsAccIndex = 0;
	var i;
	var m;
	var index = 1;
	while ($("#otherProgram" + index).size() > 0)
	{
		//otherProgramごとのsection配列を作成
		MEMBERS[ "sections" + index ] = [];
		
		var otherSchedulebtns		= $("#otherProgram" + index).find( ".otherProgramSchedule" );
		var btns					= $("#otherProgram" + index).find( ".accordionBtn" );
		var contents				= $("#otherProgram" + index).find( ".accordionAnime" );
		var selectedProgramIdsAcc	= top_assigned_obj.selectedProgramIdsAcc;
		
		m = btns.length;
		for( i=0; i<m; i++ )
		{
			//section配列内部作成
			$( btns[ i ] ).attr( "btnIndex", index + "" + i );	//各ボタンでの参照用にid追加
			$( otherSchedulebtns[ i ] ).attr( "otherScheduleIndex", index + "" + i );
			
			var set = [];
			set.push( btns[ i ] );								//ボタン
			set.push( contents[ i ] );							//コンテンツ
			set.push( $( contents[ i ] ).css( "height" ));		//それぞれのコンテンツのheight(未使用)
			set.push( "unActive" );								//各アコーディオンの状態
			set.push( otherSchedulebtns[ i ] );					//ロード開始ボタン
			set.push( false );									//loadedFlag
			set.push( selectedProgramIdsAcc[ programIdsAccIndex + i ] );				//送信用Id
			
			MEMBERS[ "sections" + index ].push( set );
			
			//click
			$( contents[ i ] ).css( "display", "none" );
			$( btns[ i ] ).click(function(){ toggleAnimation( this );});
			
		}
		
		//微妙
		programIdsAccIndex += m;
		index ++;
	}
}
var toggleAnimation = function( btn )
{
	if( animating ) return false;
	animating = true;
	
	var sectionId = $(btn).attr( "btnIndex" ).substring( 0, 1 );
	var setId = $(btn).attr( "btnIndex" ).substring( 1,2 );
	var mySection = MEMBERS[ "sections" + sectionId ];	//自身が属しているセクション
	var set = mySection[ setId ];						//自身が属しているセット
	
	var j, n;
	n = mySection.length;
	for( j=0 ; j<n; j++ )
	{
		//自分自身ならば開く、開いていれば閉じる
		if( j == setId )
		{
			$( set[ 1 ] ).animate( animationParam, {complete:function()
				{
					set[ 3 ] = ( set[ 3 ] == "active" ) ? "unActive" : "active";
					animating = false;
				}
			});
		}else
		//他は全て消す
		{
			if( mySection[ j ][ 3 ] == "active" )
			{
				$( mySection[ j ][ 1 ] ).animate( animationParam );
			}
			mySection[ j ][ 3 ] = "unActive";
		}
	}
}
/*
var scheduleClick = function( scheduleBtn )
{
	var sectionId = $(scheduleBtn).attr( "otherScheduleIndex" ).substring( 0, 1 );
	var setId = $(scheduleBtn).attr( "otherScheduleIndex" ).substring( 1,2 );
	var mySection = MEMBERS[ "sections" + sectionId ];	//自身が属しているセクション
	var set = mySection[ setId ];						//自身が属しているセット
	
	MEMBERS.getSchedule( set[5], set[6] );
}*/
MEMBERS.getSchedule = function ( loadedFlag, lc_code, _this )
{
	//alert( loadedFlag );
	/*
	//値渡し？
	if( loadedFlag )
	{
		loadedFlag = true;
		$( "#shadowBoxContent" ).replaceWith( collection[ "" + lc_code ] );
		return;
	}
	*/
	
	var apiURL = /* TESTURL */ "/shop_info/SHP001/api/get-schedule";
	var request = {
		"lc_code" : lc_code,
		"date"    : "now"
	};
	
	//alert( lc_code );
	
	var parameter =
	{
		async  : true,
		cache  : false,
		timeout: 30 * 1000,
		type   : "GET",
		dataType: "jsonp",
		data   : request,
		url    : apiURL,
		success: function( response )
		{
			scheduleCallBack( response, lc_code, _this );
		},
		error:function( XMLHttpRequest, textStatus, errorThrown )
		{
			alert( "error" );
		}
	}
	
	$.ajax( parameter );
}
function scheduleCallBack( response, lc_code )
{
	//title
	var scheduleWindow = $( "<div>" + top_assigned_obj.shopName + " 実地スケジュール" + "</div>" ).css( "margin-top","15px" );
	
	// table
	var schedule = "<table>";
	for( var i in response.data )
	{
		var scheduleData = response.data[i];
		var txt = scheduleData.date.replace(/-/g,"/");
		var scheduleDate = new Date( txt );
		var scheduleDateString = scheduleDate.getFullYear().toString().substr(2)
								+ "/" + MEMBERS.keta(scheduleDate.getMonth()+1, 2)
								+ "/" + MEMBERS.keta(scheduleDate.getDate(), 2);
		schedule += "<tr><th>"+scheduleDateString+"</th><td>"+scheduleData.start_time+"～"+scheduleData.end_time+"</td></tr>";
	}
	schedule += "</table>";
	scheduleWindow.append( schedule );
	
	$( "#shadowBoxContent" ).find( "div" ).replaceWith( scheduleWindow );
	collection[ "" + lc_code ] = scheduleWindow;
	
}

/**
 * getSchedule用桁ぞろえ
 */
MEMBERS.keta = function( value, ketaCount )
{
	var str = ""+value;
	while( str.length < ketaCount )
	{
		str = "0" + str;
	}
	return str;
}

//---------------------------------------------------------------------------------------------------------------------共通
/**
 * imgにロールアクションを設定
 * @img
 * @onImg
 * @offImg
 * 
 */
MEMBERS.addRollAction = function( img, onImg, offImg )
{
	this.preLoadImg( [ onImg, offImg ] );
	
	img.mouseover( function(){ img.attr({src: onImg});});
	img.mouseout( function(){ img.attr({src: offImg});});
	
	if(img.parent() && img.parent().get(0).tagName == "A" )//一つ上の要素がa
	{
		img.parent().focus( function(){ img.attr({src: onImg});});
		img.parent().blur( function(){ img.attr({src: offImg});});
	}
	if(img.parent() && img.parent().get(0).tagName == "INPUT" )//一つ上の要素がInput
	{
		img.parent().focus( function(){ img.attr({src: onImg});});
		img.parent().blur( function(){ img.attr({src: offImg});});
	}
}
/**
 * imgのon、offの両方の画像パスを取得
 * @img
 */
MEMBERS.getImgSrc = function( img )
{
	//指定クラスの持つイメージの名前を取得
	var offImg = img.attr("src");
	//その名前からon画像の名前を作成
	var str = offImg;
	var imgName = str.substring( 0, str.lastIndexOf( "." ) );//str.split( "." )[0];
	var imgType = str.split( "." )[ str.split( "." ).length-1 ];
	
	imgName += "_on";
	onImg = imgName + "." + imgType;
	
	
	return [ onImg, offImg ];
}
/**
 * 
 * @idName
 */
MEMBERS.getImg = function( idName )
{
	var element = $('#' + idName);
	if( element )return element;
	else return false;
}

/**
 * ロールオーバー用の画像をあらかじめロード
 * 
 */
MEMBERS.preLoadImg = function( arr )
{
	var arr = arr;
	
	var i,m=arr.length;
	for (i = 0; i < m; i++)
	{
		var img = new Image();
		img.src = arr[ i ];
	}
}




















/*
var wheelEnabled = true;
MEMBERS.wheel = function (event)
{
	var delta = 0;
	if (!event)// For IE.
	{
		event = window.event;
	}
	if (event.wheelDelta)// IE/Opera.
	{ 
		delta = event.wheelDelta/120;
		if (window.opera)
		{
			delta = -delta;
		}else
		if (event.detail)// Mozilla case.
		{ 
			delta = -event.detail / 3;
		}
	}
	if( !wheelEnabled )
	{
		if (event.preventDefault)
		{
			event.preventDefault();
		}
		event.returnValue = false;
	}
}
if (window.addEventListener) window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel;
*/





window.utils = new utils();
//---------------------------------------------------------------------------------------------------------------------utils名前空間
})();
