/*
	フラッシュの表示領域サイズの調整
		・ロード終了タイミングで加工だと遅すぎる？
	　　表示→加工→調整で
		・独自ドメインにも対応、jsonpで
	
*/
var flashResize={
	FILE_PHP:"getFlashSize.php",ifsizeset:false,ifloaded:false,fired:false,
	initialize:function(_common_image_dir,clinicid){
		/* jsのパスからphpのパスを取得 */
		var sc=document.getElementsByTagName("script");
		if(!sc.length) return false;
		for(var i=0,L=sc.length;i<L;i++){
			var srcVar=sc[i].getAttribute("src");
			if(!srcVar) continue;
			var reg=new RegExp(/^(.*)tabReader.js$/);
			
			if(reg.exec(srcVar)==null) continue;
			var path   = RegExp.$1;
			break;
		}
		if(!path) return false;
		
		
		/* jsonpセット */
		var a=[],c=0;
		a[c++]="<script type='text/javascript' src='";
		a[c++]=path;
		a[c++]=this.FILE_PHP;
		a[c++]="?_common_image_dir=";
		a[c++]=_common_image_dir;
		a[c++]="&clinicid=";
		a[c++]=clinicid;
		a[c++]="'><\/script>";
		document.write(a.join(""));
		
		Event.observe(document,"dom:loaded",this.load.bind(this),false);
	},
	/* jsonpで呼び出される関数 */
	setSize:function(obj){
		if(!obj.width || !obj.height) return false;
		this.resizeParam=obj;
		this.ifsizeset=true;
		
		if(this.fired) {
			return false;
		} else {
			if(this.ifloaded){
				this.fired=true;
				this.resize();
			}
		}
	},
	load:function(){
		/* フラッシュのエレメントを特定 */
		var objs = $A($("topimage").getElementsByTagName("object"));
		var embs = $A($("topimage").getElementsByTagName("embed"));
		if(objs.length>0)  this.objElem=objs[0];
		if(embs.length>0)  this.embedElem=embs[0];
		//alert(objs.length);alert(embs.length);
		
		this.ifloaded=true;
		if(this.fired) {
			return false;
		} else {
			if(this.ifsizeset){
				this.fired=true;
				this.resize();
			}
		}
	},
	resize:function(){
		var obj= this.resizeParam
		
		if(this.objElem){
			this.objElem.setAttribute("width",obj.width);
			this.objElem.setAttribute("height",obj.height);
		}
		if(this.embedElem){
			this.embedElem.setAttribute("width",obj.width);
			this.embedElem.setAttribute("height",obj.height);
		}
	}
}

function Tabs(array,options){
	
	//Definition
	this.tabtop="tab_head"; 					//Tab-container's id
	this.cont="tab_body";					//Contents-container's id
	//this.image_path="../common/";				//Path to Tabs
	this.image_path="/web/testid/common/";				//Path to Tabs
	this.image_rollover="";				//Postposition of roll-over 
	this.image_current="_c";					//Postposition of current 
	this.image_ext=".gif";					//Extension of images
	this.cont_postfix="_contents";			//postfix of  target area's id 
	this.old_tabname="";
	
	//Customize
	this.skip=true;							//If true,skip effect at first time
	this.duration=0.3; 						//Duration of Fading and Appearing effect 
	this.zindex=50;						//Base value of tab's z-index
	this.fadeto=0.1;
	
	//Properties
	this.current="";
	this.targ="";
	
	this.tab_ids=array;
	if(options){
		for(var prop in options){
			this[prop]=	options[prop];
		}
	}
	
	//Functions
	this.load=function(){
		if(!$(this.tabtop)) return false;
		for(i=0,L=this.tab_ids.length;i<L;i++){
			var id=this.tab_ids[i];

			//Put A tag
			var tab=document.createElement("a");
			$(this.tabtop).appendChild(tab);
			//Set Attribute
			tab.className=id;
			tab.setAttribute("id",id);
			tab.setAttribute("href","javascript:void(0)");
			//Set click event observing 
			Event.observe(tab,"click",this.click.bind(this),false);
			
		}

		//Choose default tab
		this.current=this.tab_ids[0];
		
		this.click(this.tab_ids[0]);
	}
	this.click=function(e){
		id=(typeof e=="string") ? e:Event.element(e).id;//Adapt for both id-name and event
		if(!$(id)) return false;
		
		this.old_tabname=this.current;
		
		//tab change
		setTimeout(function(){
			$(this.current).className	= this.current;
			$(id).className				= id+this.image_current;
			this.current=id;
		}.bind(this),1);
		
		//tab contents change
		this.targ=id;
		if(this.skip){
			this.appear();
		} else {
			new Effect.Fade(this.cont,{duration:this.duration,to:this.fadeto,afterFinish:this.appear.bind(this)});
			
		}
		
	}
	this.appear=function(){
 	  try{

		$(this.old_tabname+this.cont_postfix).style.display="none";
		$(this.targ+this.cont_postfix).style.display="block";
		this.old_tabname=this.targ;
		

		if(this.skip){
			$(this.cont).style.display="block";
			this.skip=false;
		} else {
			new Effect.Appear(this.cont,{duration:this.duration});
		}
	  }catch(e){}
		
		
	}
	this.setstyle=function(){		//output Stylesheet		
		
		var zindex=this.zindex;
		var folder=this.image_path;
		var ext=this.image_ext;
		var rollover=this.image_rollover;
		var current=this.image_current;

		var styleTextSet=[];
		for(i=0,L=this.tab_ids.length;i<L;i++){
			var id=this.tab_ids[i];
			
			
			var cont =this.cont;
			styleTextSet.push(
				["a."+id ," background-image:url("+folder+id+ext+"); z-index:"+(zindex-i)],
				["a."+id+current,"background-image:url("+folder+id+current+ext+"); z-index:"+(zindex+50)],
				["div#"+cont,"z-index:"+(zindex+25)]
			);
			
		}
		return styleTextSet;
	}
	/*this.preload=function(){
		//Preload of current and rollover image
		for(i=0,L=this.tab_ids.length;i<L;i++){
			
			(new Image()).src=this.image_path+this.tab_ids[i]+this.image_rollover+this.image_ext;
			(new Image()).src=this.image_path+this.tab_ids[i]+this.image_current+this.image_ext;
		}
	}*/
	
	var styleObj=document.styleSheets[document.styleSheets.length-1];
	var styletexts=this.setstyle();
	setCSS(styleObj,styletexts);
	
	this.load();
}

function OV(obj){
	switch(typeof obj){
		case "undefined":
		case "boolean":
		case "number":
		case "string":
			var out=obj;
			break;
		default:
			var ar=[];var c=0;
			for(var prop in obj){
				ar[c++]="key:";
				ar[c++]=prop;
				ar[c++]="; value:";
				ar[c++]=obj[prop];
				ar[c++]="\n";
			}
			var out=ar.join("");
	}
	return out;
}

var blogReader=Class.create();
blogReader.prototype={
	/* プロパティ */
	/*URL:"/blog/index.php",
	RSS:"/blog/xml-rss2.php",*/
	CLASS_SHOWALL:"link_right",
	ID_SHOWALL_LINK_PREFIX:"blogReader_showall",
	CLASS_SINGLEWRAPPER:"blogReader_singleContainer",
	TEXT_SHOWALL:"全て見る",
	TEXT_SHOWALL_CLOSE:"戻る",
	
	/* デフォルト */
	targetID:"blog_wrapper",
	overWrite:true,
	mode:"all",
	max:null,
	
	clickEvents:{},
	initialize:function(httpObj,option){
		if(typeof option=="object"){
			for(var prop in option){
				this[prop]=option[prop];
			}
		}
		
		if(!$(this.targetID)){
			document.write("<div id='"+this.targetID+"'><\/div>");
		}
		this.targetObj=$(this.targetID);
		this.maxoriginal=this.max
		
		this.ID_SHOWALL_LINK=this.ID_SHOWALL_LINK_PREFIX+this.targetID;
		
		this.httpObj=httpObj;
		this.loadResult()
			
	},
	loadResult:function(){
		var httpObj=this.httpObj;
		switch(this.mode){
			default:
			case "all":
				this.targetObj.innerHTML=httpObj.responseText;
				break;
			case "rss":
			
				var a=[],c=0;
				a[c++]="<ul>";
				
				var xml=httpObj.responseXML;
				var items=$A(xml.getElementsByTagName("entry"));
				
				if(this.max==null){
					var L=items.length;
				} else {
					if(this.max > items.length){
						var L=items.length;
					} else {
						var L=this.max;
					}
				}
				
				for(var i=0;i<L;i++){
					var link ="";
					var text ="";
					var date ="2009.04.01";
					for(var j=0 ,jL=items[i].childNodes.length;j<jL;j++){
						var child=items[i].childNodes[j];
						switch(child.tagName){
							case "title":
								if(child.firstChild) var text=child.firstChild.nodeValue;
								break;
							case "link":
								//if(child.firstChild) var link=child.firstChild.nodeValue;
								var href=child.getAttribute("href");
								if(href) var link=href;
								break;
							case "published":
								if(child.firstChild) var date=(child.firstChild.nodeValue).substr(0,10).replace(/-/g,".");
								break;
						}
					}
					a[c++]="<li><a href='"+link+"' target='_blank'>"+date+"..."+text+"</a></li>";
				}
				/* make "showAll" */
				//if(this.max!=null  && items.length > this.max){
				if(items.length > this.max){
					if(this.max==null){
						var text=this.TEXT_SHOWALL_CLOSE
						this.ifshowAllopened=true;
					} else {
						var text=this.TEXT_SHOWALL+"("+items.length+"件)";
						this.ifshowAllopened=false;
					}
					a[c++]="<li class='";
					a[c++]=this.CLASS_SHOWALL;
					a[c++]="'><a id='";
					a[c++]=this.ID_SHOWALL_LINK;
					a[c++]="'>";
					a[c++]=text;
					a[c++]="</a></li>";
				}
				
				a[c++]="</ul><div style='clear:both;font-size:1px;line-height:1;height:1px;'></div>";
				this.targetObj.innerHTML=a.join("");

				if($(this.ID_SHOWALL_LINK)){
					if(typeof this.onShowAll!="undefined"){
						Event.observe($(this.ID_SHOWALL_LINK),"click",this.onShowAll.bind(this),false);
					} else {
						Event.observe($(this.ID_SHOWALL_LINK),"click",this.toggleShowAll.bind(this),false);
					}
				}

				//this.mode="all";	
				break;
		}
		
		if(this.overWrite)	this.linkOverWrite();
	},
	linkOverWrite:function(){

		var atags=$A(this.targetObj.getElementsByTagName("a"));
		this.atags_status={};
		atags.each(this.linkOverWrite_iterator.bind(this));
		
	},
	linkOverWrite_iterator:function(atag){
		this.clickEvents[atag]=this.click.bind(this);
		
		//Event.observe(atag,"click",function(e){e.preventDefault();},false);
		Event.observe(atag,"click",this.clickEvents[atag],false);
		this.atags_status[atag]={
			status:"empty",containerElement:""
		}
	},
	click:function(e){
		var atag=Event.element(e);
		if(!atag.href) return null;
		
		e.preventDefault();
		
		switch(this.atags_status[atag].status){
			case "moving":
				break;
			case "opened":
				this.atags_status[atag].status="moving";
				this.closeSingle(atag);
				break;
				
			case "closed":
				this.atags_status[atag].status="moving";
				this.openSingle(atag);
				break;
			default:
			case "empty":
				this.atags_status[atag].status="moving";
				this.loadSingle(atag);
				break;
		}
		
		
	},
	closeSingle:function(atag){
		var containerElement=this.atags_status[atag].containerElement;
		if(!containerElement )  return false;
		
		var afterFunc=function(){
			this.atags_status[atag].status="closed";
		}.bind(this);
		new Effect.BlindUp(containerElement,{
			duration:0.4,
			afterFinish:afterFunc
		});
	},
	openSingle:function(atag){
		var containerElement=this.atags_status[atag].containerElement;
		if(!containerElement)  return false;
		
		var afterFunc=function(){
			this.atags_status[atag].status="opened";
		}.bind(this);
		new Effect.BlindDown(containerElement,{
			duration:0.4,
			afterFinish:afterFunc
		});
	},
	loadSingle:function(atag){
		var divObj=document.createElement("div")
		//divObj.className=this.CLASS_SINGLEWRAPPER;
		divObj.style.display="none";
		atag.parentNode.appendChild(divObj);
		this.atags_status[atag].containerElement=divObj
		
		this.atag=atag;
		var afterFunc=function(httpObj){
			this.atags_status[this.atag].containerElement.innerHTML=httpObj.responseText;
			this.openSingle(this.atag)
		}.bind(this)
		
		var opt={
			method:"get",
			onComplete:afterFunc
		}
		new Ajax.Request(atag.href,opt);
	},
	toggleShowAll:function(){
		if(this.ifshowAllopened){
			this.max=this.maxoriginal;
		} else {
			this.max=null;
		}
		this.ifshowAllopened=(!this.ifshowAllopened);
		
		var effect_option1={
			duration:0.3,
			to:0.1,
			queue:{
				scope:"changeShow",
				position: 'front'
			},
			afterFinish:this.loadResult.bind(this)
		}
		var effect_option2={
			duration:0.5,
			from:0.1,
			queue:{
				scope:"changeShow",
				position: 'end'
			}
		}
		new Effect.Fade(this.targetObj,effect_option1);
		new Effect.Appear(this.targetObj,effect_option2)
		
	}
}

function setCSS(styleObj,styletexts){
  try{
	if (document.all) {
	  var styleTextSet=function(set,key){
		 // alert(key);
		styleObj.addRule(set[0], set[1]);
	  }
	} else {
	  var styleTextSet=function(set,key){
		 // alert(key);
		styleObj.insertRule(set[0] + "{" + set[1] + "}", styleObj.cssRules.length);
	  }
	  
	}
	styletexts.each(styleTextSet);
  }catch(e){alert(OV(e))}
}

var tryAjax =Class.create();
tryAjax.prototype={
	//insArray:{},
	initialize:function(url,id){
	  try{
		this.id=id;
		var opts={
			method:"get",
//			parameters:"?blogid="+id,
			onSuccess:this.loadSuccess.bind(this),
			onFailure:this.loadFailure.bind(this)
		}
		var ajaxIns=new Ajax.Request(url,opts);
		
		/*this.loading=true;
		this.timoutID=setTimeout(function(){
			if(this.loading)
		}.bind(this),10000);*/
		//this.insArray[id] = ajaxIns;
	  }catch(e){alert(OV(e))}
	},
	// レスあり、かつblogidが有効
	loadSuccess:function(_httpObj){
		tabReaderObj.loadedcount++;
		tabReaderObj.httpObjs[this.id]=_httpObj;
		if(_httpObj.responseText!=tabReaderObj.errorText){
			tabReaderObj.valids[this.id]=1;
		} else {
			tabReaderObj.valids[this.id]=0;
		}
		var xml=_httpObj.responseXML;
		if(xml===null) {
			this.loadFailure()
		} else {
			var items=$A(xml.getElementsByTagName("entry"));
			if(!items.length){
				tabReaderObj.valids[this.id]=0;
			}
			
			tabReaderObj.finishCheck();
		}
	},
	// レスがない（リンク切れ）
	loadFailure:function(){
		tabReaderObj.loadedcount++;
		tabReaderObj.valids[this.id]=0;
		tabReaderObj.finishCheck();
	}
}

var tabReaderObj={
	
  initialize:function(_newsID,_blogID,_common_image_dir,clinicid){
	/*
		プロパティ
	*/
	//this.RSS_URL="/blog/xml-rss2.php";
	this.RSS_URL="../blog/###/atom.xml";
	this.POSTFIX_NEWS="news";
	this.errorText="error";
	this.common_image_dir=_common_image_dir
	this.indicatorSrc="../common_image/indicator.gif";
	this.clinicid=clinicid;
	
	//this.ids=[];
	this.tabarray={};
	this.valids={};
	this.httpObjs={};
	this.tabcount=0;
	this.loadedcount=0;
	this.if_tab_started=false;
	/*
		メソッド用意
	*/
	// loading表示
	this.tabloader={
		start:function(){
			var a=[],c=0;
			a[c++]="<img src='";
			a[c++]=tabReaderObj.indicatorSrc;
			a[c++]="' id='tabloaderImage' />";
			document.write(a.join(""));
			
			
			
		},
		stop:function(){
			if($("tabloaderImage")) $("tabloaderImage").style.display="none";
		}
	}
	// タブを表示せず終了
	this.emptyEnd=function(){
		this.tabloader.stop();
	}
	// タブを表示
	this.tabStart=function(tabarray){
		if(this.if_tab_started) return false;
		this.if_tab_started=true;
		this.tabloader.stop();

		/*var a=[],c=0;
		a[c++]="#main{background-color:#00F;}.blogReader_singleContainer{background:url(";
		a[c++]=this.indicatorSrc;
		a[c++]=") right top no-repeat;}.link_right{float:right;}.link_right a{cursor:pointer;}#tab_info_contents h2,#tab_blog_contents h2{font-size:110%;font-weight:bold;padding-left:0px;}";
		a[c++]="#tab_info_contents div.contentitem,#tab_blog_contents div.contentitem{display:none}";
		a[c++]="#tab_info_contents div.contentbody,#tab_blog_contents div.contentbody{ padding-left:1em;}";
		a[c++]="#tab_head{ height:32px;}#tab_head a{ width:114px; height:32px ; background-position:0 0; background-repeat:no-repeat; display:block; position:relative; float:left; cursor:pointer}";*/
		/*var styleObj=document.createElement("style");
		document.body.appendChild(styleObj);
		if(styleObj.styleSheet){
			styleObj.styleSheet.cssText = a.join("");
		} else {
			styleObj.appendChild(document.createTextNode(a.join("")));
		}*/
		
		var styleObj=document.styleSheets[document.styleSheets.length-1];
		var indicatorSrc=this.indicatorSrc;
		var styletexts=[		
			//[".blogReader_singleContainer","background:url("+indicatorSrc+") right top no-repeat;"],
			[".link_right","float:right;"],
			[".link_right a","cursor:pointer;"],
			//["#tab_blog_contents","display:none;"],
			["#tab_info_contents h2","font-size:110%;font-weight:bold;padding-left:0px;"],
			["#tab_blog_contents h2","font-size:110%;font-weight:bold;padding-left:0px;"],
			["#tab_info_contents div.contentitem","display:none;"],
			["#tab_blog_contents div.contentitem","display:none;"],
			["#tab_info_contents div.contentbody"," padding-left:1em;"],
			["#tab_blog_contents div.contentbody"," padding-left:1em;"],
			["#tab_head","height:32px;"],
			["#tab_head a","width:114px; height:32px ; background-position:0 0; background-repeat:no-repeat; display:block; position:relative; float:left; cursor:pointer;"],
			
			["#tab_bodytop","background:url(../common_image/tab_back.gif) no-repeat left top; height:10px; font-size:1px;"],
			//["#tab_body","background:url(../common_image/tab_back.gif) repeat-y left -20px; padding:0 5px 5px 5px;"]
			["#tab_body","background:url(../common_image/tab_body.gif) repeat-y left top; padding:0 5px 5px 5px;"]
		];
		setCSS(styleObj,styletexts)

		var a=[],c=0;
		a[c++]="<div id='tab'>";
		a[c++]="	<div id='tab_head'><\/div>";
		a[c++]="	<div id='tab_bodytop'><\/div>";
		a[c++]="	<div id='tab_body'>";
		a[c++]="		<div id='tab_info_contents'><\/div>";
		a[c++]="		<div id='tab_blog_contents' style='display:none'><\/div>";
		a[c++]="	<\/div>";
		a[c++]="	<div id='tab_foot'><\/div>";
		a[c++]="<\/div>";
		new Insertion.Top($("main"),a.join(""));
		
		var tab_names=[];
		for(var id in tabarray){
		//for(var id=0,L=tabarray.length;id<L;id++){
			if(tabarray[id]=="tab_info"){
				new blogReader(this.httpObjs[id],{mode:"rss",targetID:"tab_info_contents",overWrite:true,max:3});
				tab_names[0]="tab_info";
			} else if(tabarray[id]=="tab_blog"){
				new blogReader(this.httpObjs[id],{
					mode:"rss",targetID:"tab_blog_contents",overWrite:false,max:3,TEXT_SHOWALL:"ブログ一覧へ",
					onShowAll:function(){
						var xml=this.httpObj.responseXML;
						var items=$A(xml.getElementsByTagName("link"));
						if(items.length>0) {
							var url=items[0].getAttribute("href");
							if(url!=null) location.href=url;
						}

					}
				});
				tab_names[1]="tab_blog";
			}
		}
		if(typeof tab_names[0]=="undefined"){ 
			tab_names[0]=tab_names[1];
			delete tab_names[1]
		}
		new Tabs(tab_names,{image_path:this.common_image_dir});
	}
	this.addTab=function(id,tabname){
		//this.ids.push(id);
		//this.tabarray.push(tabname);
		this.tabarray[id]=tabname;
		this.tabcount++;
		this.valids[id]=0;
		
	}

	
	// 全タブのロード終了チェック
	this.finishCheck=function(){
		if(this.loadedcount!=this.tabcount) return false;

		//var tabarray =this.tabarray;
		//for(var id=0,L=this.valids.length;id<L;id++){
		for(var id in this.valids){
			if(!this.valids[id])  {
				//delete this.ids[id];
				delete this.tabarray[id];
				delete this.httpObjs[id];
				this.tabcount--;
			}
		}
		
		if(this.tabcount>0){
			
			
			this.tabStart(this.tabarray);
		} else {
			this.emptyEnd()
		}
	}
	
	
	/*
		メイン処理
	*/
	//ローディング表示開始
	
	
	//引値からプロパティをセット
	if(_newsID!==true && _blogID!==true) {
		return false;
	} else {
		this.tabloader.start();
		
		if(_newsID===true) {
			//var newsID=Number(_newsID);
			this.addTab(0,"tab_info");
			//通信をこころみる
			var URL= this.RSS_URL.replace(/###/,clinicid+this.POSTFIX_NEWS);
			new tryAjax(URL,0)
		}
		if(_blogID===true) {
			//var blogID=Number(_blogID);
			this.addTab(1,"tab_blog");
			//通信をこころみる
			var URL= this.RSS_URL.replace(/###/,clinicid)	
			new tryAjax(URL,1);
		}
		/*var styleObj=document.createElement("link");
		styleObj.setAttribute("rel","stylesheet");
		styleObj.setAttribute("type","text/css");*/
		var styleObj=document.createElement("stlye");
		document.getElementsByTagName("head")[0].appendChild(styleObj);
		this.styleObj=styleObj;
	}
	
  }
}


var tabReader=function(_newsID,_blogID,_common_image_dir,clinicid){
	/*
		Flash領域の最適化
	*/
	flashResize.initialize(_common_image_dir,clinicid);
	
	(new Image()).src=_common_image_dir+"tab_info.gif";
	(new Image()).src=_common_image_dir+"tab_info_c.gif";
	(new Image()).src=_common_image_dir+"tab_blog.gif";
	(new Image()).src=_common_image_dir+"tab_blog_c.gif";
	
	tabReaderObj.initialize(_newsID,_blogID,_common_image_dir,clinicid);
	
}