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

	FOUR-SITE&ism, Initialization JavaScript Library

	                                       http://www.4site.co.jp/
	-------------------------------------------------------------

	使用方法-----------------------------------------------------

	1.画像ロールオーバー
	  ファイル名に「-out-」と「-over-」
	  例：通常のImage         indexNavi-out-01.jpg
	      オーバー時のImage   indexNavi-ovar-01.jpg
	  img要素に「 class="swap" 」をつける

	2.ストライプテーブル
	  ストライプにさせる要素（tableかul）にclass「Stripes」をつけると自動的に.oddと.evenがつきます。
	  CSSにclass「.odd(偶数)」「.even(奇数)」を作る

	3.CSSセレクタ　first-child,last-child
	  firstChildとlastChildをつける事が出来ます。
	  CSSクラス「child」の中にある最初の要素に「firstChild」　最後の要素に「lastChild」
	  CSS「.firstChild」と「.lastChild」を作る
	  注：要素が一つの場合は「.lastChild」が付きます。

	4.スムーススクロール
	  ページの中のリンク（アンカーリンク）に対して、スムース機能がつきます。
	  <a href="ジャンプ先ID（例:#pagetop）" onclick="return SmoothScroll( 'ジャンプ先ID（例:#pagetop）' );">ボタン</a>

	5.new window（小窓window）
	  汎用性がある小窓スクリプトです。
	  使用方法は下記リンクタグでOK
	  
	    <a href="#" onclick="winOpn('URL','名前',幅,高さ,'スクロール');">こっちでもOK</a>
	    <a href="JavaScript:winOpn('URL','名前',幅,高さ,'スクロール');" >こっちでもOK</a>
		URL：sample.html
		名前：indexKomado
		幅：ピクセル単位の数字
		高さ：ピクセル単位の数字
		スクロールバー：yes|no
		
		閉じるボタン：<a href="JavaScript:winCls();" >閉じるボタン</a>
		
	6.表示・非表示機能
	  onClick="toggle(IDネーム);return false;"
	  これだけ。


==========================================================================================
(c)2007 FOUR-SITE&ism Co.,Ltd ALL Rights Reserved. 
*/

/*---------- 初期呼び出し ----------*/
addEvent(window,'load',initRollovers,false);
addEvent(window,'load',StripesTable,false);
addEvent(window,'load',StripesUL,false);
addEvent(window,'load',SelectorChild,false);
addEvent(window,'load',FormFocusSet,false);
addEvent(window,'load',bannerLoad,false);



function bannerLoad() {
	var d = new Date();
try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
  try {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (e) {
    xmlhttp = false;
  }
}
  if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
    xmlhttp = new XMLHttpRequest();
  }
if (xmlhttp) {
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var disp = document.getElementById('rightBox');
disp.innerHTML = get_response_text (xmlhttp);
}
}
xmlhttp.open('GET', 'http://www.office-mayumi.co.jp/banner080901.html?time='+d.getTime());
xmlhttp.send(null);
}
}
function get_response_text ( 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;
}


/* 画像ロールオーバー
-------------------------------------------------------------------------------------------*/
function initRollovers() {
	var src1 = "-out-";    //変更前
	var src2 = "-over-";   //変更後
	if (!document.getElementById) return
	var aImages = getElementsByClass('swap');
	for (var i = 0; i < aImages.length; i++) {

			var osrc = aImages[i].getAttribute('src');
			var hsrc = osrc.replace(src1, src2);
				
			aImages[i].setAttribute('hsrc', hsrc);
			aImages[i].setAttribute('osrc', osrc);
				
			aImages[i].onmouseover = function() {
				this.setAttribute('src',this.getAttribute('hsrc'));
			}
			var matchOver = aImages[i].src;
			var matchOverNull = matchOver.match(src2);
			if (matchOverNull == null) {
			aImages[i].onmouseout = function() {
				this.setAttribute('src',this.getAttribute('osrc'));
			}
		}
	}
}



/* ストライプテーブル
-------------------------------------------------------------------------------------------*/
function StripesTable(){
	if (!document.getElementById) return
	var table = getElementsByClass('Stripes');
	for(var i = 0; i < table.length; i++){

			var tr = table[i].getElementsByTagName("tr");
			
			var thead="yes";
			for(var ii = 0; ii < tr[0].childNodes.length; ii++){
			thead = tr[0].childNodes[ii].tagName=="TD" ? "no" : "yes";
			}
		
			if(thead=="no"){
				for(var ii = 0; ii < tr.length; ii++){
				tr[ii].className += ii%2==0 ? " odd" : " even";
				}
			}
		
			else{
				for(var ii = 1; ii < tr.length; ii++){
				tr[ii].className += ii%2==1 ? " odd" : " even";
			}
		}
	}
}



/* ストライプリスト
-------------------------------------------------------------------------------------------*/
function StripesUL(){
	if (!document.getElementById) return
	var ul = getElementsByClass('Stripes');
	for(var i = 0; i < ul.length; i++){

	var li = ul[i].getElementsByTagName("li");
		
		for(var ii = 0; ii < li.length; ii++){
			li[ii].className += ii%2==0 ? " odd" : " even";
		}
	}
}



/* CSSセレクタ　first-child,last-child
-------------------------------------------------------------------------------------------*/
function SelectorChild(){
	if (!document.getElementById) return
	var AllTag = getElementsByClass('child');
	for(var i = 0; i < AllTag.length; i++){
			
// firstChild ----------------//

	if(!AllTag[i].childNodes[0]){continue;}
	if (navigator.userAgent.indexOf("Firefox") > -1){
		if(!AllTag[i].childNodes[1]){continue;}
	}
	var FirstNODE = AllTag[i].childNodes[0].nodeType;
	var FirstNodeNum = 0;
	var FirstChild = AllTag[i].childNodes[0];
	while(FirstNODE != 1){
		FirstNodeNum++;
		FirstNODE = AllTag[i].childNodes[FirstNodeNum].nodeType;
		FirstChild = AllTag[i].childNodes[FirstNodeNum];
		}
	FirstChild.className += " firstChild";
// lastChild -----------------//
	var LastNumber = AllTag[i].childNodes.length-1;
	var LastNODE = AllTag[i].childNodes[LastNumber].nodeType;
	var LastNodeNum = LastNumber;
	var LastChild = AllTag[i].childNodes[LastNumber];
	while(LastNODE != 1){
		LastNodeNum--;
		LastNODE = AllTag[i].childNodes[LastNodeNum].nodeType;
		LastChild = AllTag[i].childNodes[LastNodeNum];
		}
	var fMatch = LastChild.className;
	var fMatchNull = fMatch.match("firstChild");
	if (fMatchNull == null) {
		LastChild.className += " lastChild";
	}else{
		fMatch = fMatch.replace("firstChild", "lastChild");
		LastChild.className = fMatch;
	}
	}
}




/* スムーススクロール
-------------------------------------------------------------------------------------------*/
function SmoothScroll(targetID){
  if( !document.getElementById ) {return true;}
  var step=20;  //初速度
  var max=400;  //最高速度
  var accel=10;  //加速度
  var interval=40;  //加速インターバル
  var current_y = document.body.scrollTop || document.documentElement.scrollTop;
  var element=document.getElementById(targetID);
  if (!element){return true;}
  var target_y = 0;
  for (i = element;i.offsetParent;i=i.offsetParent ){
    target_y += i.offsetTop;
  }
  var count=0;
  if ( current_y > target_y ){ step = -(step); accel = -(accel);}
  var timerid = setInterval( function(){
    if (step<max) step += (count*accel);
    if ( Math.abs(current_y-target_y) < Math.abs(step) ){
      window.scrollTo((document.body.scrollTop || document.documentElement.scrollTop),target_y);
      clearInterval(timerid);
      return false;
    }else{
      window.scrollBy(0,step);
      current_y += step;
      count++;
    }
  },interval);
  return false;
}



/* new window（小窓window）
-------------------------------------------------------------------------------------------*/
function winOpn(url,windowname,width,height,scBars) {
 var features="location=no, menubar=no, status=yes, resizable=yes, toolbar=no";
 if (width) {
  if (window.screen.width > width)
   features+=", left="+(window.screen.width-width)/2;
  else width=window.screen.width;
  features+=", width="+width;
 }
 if (height) {
  if (window.screen.height > height)
   features+=", top="+(window.screen.height-height)/2;
  else height=window.screen.height;
  features+=", height="+height;
 }
 features+=", scrollbars="+scBars; 
 window.open(url,windowname,features);
}
function winCls(){window.close();}



/* 表示・非表示
-------------------------------------------------------------------------------------------*/
function toggle(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
}



/*---------- getElementsByClass ----------*/
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}


/*---------- addEvent ----------*/
function addEvent(elm, evType, fn, useCapture) {
 if (elm.addEventListener) {
  elm.addEventListener(evType, fn, useCapture);
   return true;
  }
 else if (elm.attachEvent) {
  var r = elm.attachEvent('on' + evType, fn);
   return r;
  }
 else {
  elm['on' + evType] = fn;
 }
}


/* 画像チェンジ
-------------------------------------------------------------------------------------------*/
function ImgChange(FileName,id){
	imgID = document.getElementById(id);
	imgSRC = imgID.getAttribute("src");
	imgSplit = imgSRC.split("/");
	imgReplace = imgSRC.replace(imgSplit[imgSplit.length-1],FileName);
	imgID.setAttribute("src", imgReplace);
}

/* ボックスの中をスクロール
-------------------------------------------------------------------------------------------*/
var SmoothScroll = {};
SmoothScroll = {
	targetScrollTop : 0,	// we're gonna make the $(parentid).scrollTop -> targetScrollTop
	dist : 0,
	timer : 0,
	count : 0,
	parentid : 0,
	lastDist : 0,
	//speedStore : [],		// for debug
	options : {},
	defaultOptions : {
		time : 1*1000,	// [ms]
		unit : 50			// [ms]
	},
	scrollTo : function( element, parent, options ){
		this.options.time = this.defaultOptions.time;
		this.options.unit = this.defaultOptions.unit;
		if( options ){
			this.options.time = ( options.time ) ? options.time : this.options.time;
			this.options.unit = ( options.unit ) ? options.unit : this.options.unit;
		}
		clearInterval( this.timer );
		this.parentid = parent;

		this.scrollTopMax = this.$(parent).scrollHeight - this.$(parent).offsetHeight + parseInt(this.$(parent).style.borderTopWidth) + parseInt(this.$(parent).style.borderBottomWidth);

		if( navigator.userAgent.match( "MSIE" ) ){
			this.targetScrollTop = ( element ) ? this.$(element).offsetTop : 0;
		}else{
			var targetOffsetTop = ( element ) ? this.$(element).offsetTop : this.$(parent).offsetTop;
			this.targetScrollTop = targetOffsetTop - this.$(parent).offsetTop;
		}
		this.targetScrollTop = ( this.targetScrollTop > this.scrollTopMax ) ? this.scrollTopMax : this.targetScrollTop;

		this.dist = this.targetScrollTop - this.$(parent).scrollTop;
		this.lastDist = 0;
		this.timer = setInterval('SmoothScroll.update()', this.options.unit );
		this.count = 0;
		//this.speedStore = [];
		this.update();
	},
	update : function(){
		var dist = this.targetScrollTop - this.$(this.parentid).scrollTop;
		var speed = 2 * dist * this.options.unit / ( this.options.time - this.options.unit * this.count );
		//this.speedStore.push( speed );
		speed = ( speed > 0 ) ? Math.ceil( speed ) : Math.floor( speed );
		if( Math.abs(dist) <= Math.abs(speed) ){
			// got there
			clearInterval( this.timer );
			this.$(this.parentid).scrollTop = this.targetScrollTop;
			return;
		}else if( this.lastDist == dist ){
			// stuck
			clearInterval( this.timer );
			this.$(this.parentid).scrollTop = this.targetScrollTop;
			return;
		}
		var scrollTop = this.$(this.parentid).scrollTop + speed;
		this.$(this.parentid).scrollTop = scrollTop;
		this.lastDist = dist;
		this.count++;
		if( this.count == this.options.time / this.options.unit ){
			// timeout
			clearInterval( this.timer );
			this.$(this.parentid).scrollTop = this.targetScrollTop;
		}
	},
	$ : function(id) {
		return document.getElementById(id);
	}
}


/* フォーム、フォーカスセット
-------------------------------------------------------------------------------------------*/
function ColorfulInput() {
   this.skip  = [];
   //"背景｜ライン"
   this.color = { 'blur': '#FFF｜#CCC', 'focus': '#F8F8F8｜#999' };

   this.set = function() {
      for (var i = 0; i < document.forms.length; i++) {
         for (var f = 0; f < document.forms[i].length; f++) {
            var elm = document.forms[i][f];
            if(!this._checkSkip(elm)) continue;

            this._setColor(elm, 'focus');
            this._setColor(elm, 'blur');
         }       
      }
   }

   this._checkSkip = function(elm) {
      for(var i in this.skip) {
         if(elm.type == this.skip[i]) return false;
      }
      return true;
   }

   this._setColor = function(elm, type) { 
      var color = this.color[type];
	  var colorAry = color.split("｜");
      var event = function() {
		  elm.style.backgroundColor = colorAry[0];
		  elm.style.borderColor = colorAry[1];
		};

      if(elm.addEventListener) {
         elm.addEventListener(type, event, false); 
      } else if(elm.attachEvent) {
         elm.attachEvent('on'+type, event); 
      } else {
         elm['on'+type] = event;
      }
   }
}
function FormFocusSet() {
   var colorful = new ColorfulInput;
   colorful.set();
   //colorful.skip = ['submit', 'textarea'];
}
