//-------------------------------------------------------------------
// AKCS
// 
// @author:Akira Narita a.k.a AkiraCS @ AKIRA's CREATIVE STUDIO
// @Version:1.0.0
//-------------------------------------------------------------------
(function(){
	//-------------------------------------------------------------------
	// AKCS
	//-------------------------------------------------------------------
	var window = this,
	AKCS = window.AKCS = {};
	AKCS.info = 
	{
		Author:"Akira Narita",
		Product:"Revolver",
		Version:"1.0.0",
		CopyRight:"Copyright (C) 2010 Akira Narita All Rights Reserved.",
		IE:!!(window.attachEvent && !window.opera),
		Opera:!!window.opera,
		WebKit:navigator.userAgent.indexOf('AppleWebKit/') > -1,
		Gecko:navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
		MobileSafari:!!navigator.userAgent.match(/Apple.*Mobile.*Safari/),
		UserOS:navigator.platform,
		XPath:!!document.evaluate,
		SelectorsAPI:!!document.querySelector,
		ElementExtensions:!!window.HTMLElement,
		SpecificElementExtensions:
		document.createElement('div')['__proto__'] &&
		document.createElement('div')['__proto__'] !==
		document.createElement('form')['__proto__'],
		ScriptFragment:'<script[^>]*>([\\S\\s]*?)<\/script>',
		JSONFilter:/^\/\*-secure-([\s\S]*)\*\/\s*$/
	};

	//-------------------------------------------------------------------
	// $
	//-------------------------------------------------------------------
	$ = function(_id)
	{
		return document.getElementById(_id);
	};
	
	//-------------------------------------------------------------------
	// getElementByClassName
	//-------------------------------------------------------------------
	getElementByClassName = function (_tagName, _className)
	{
		var tempObj = document.getElementsByTagName(_tagName);
		var returnObj = [];
	
		for(var i=0, j=0; i<tempObj.length; i++)
		{
			if(tempObj[i].className==_className)
			{
				returnObj[j] = tempObj[i];
				j++;
			}
		}
		return returnObj;
	};

	//-------------------------------------------------------------------
	// getElementsByClassName
	//-------------------------------------------------------------------
	getElementsByClassName = function (_tagNames, _className)
	{
		var returnObj = [];
		for(var c=0; c < _tagNames.length; ++c)
		{
			var tempObj = document.getElementsByTagName(_tagNames[c]);
			for(var i=0; i<tempObj.length; i++)
			{
				if(tempObj[i].className == _className)
				{
					returnObj.push(tempObj[i]);
				}
			}
		}
		return returnObj;
	}

	//-------------------------------------------------------------------
	// getCSSValue
	//-------------------------------------------------------------------
	getCSSValue = function(_obj, _prop)
	{
		if( _obj.currentStyle)
		{//IE or Opera
			return (_prop.indexOf( "-" ) != -1) ? _obj.currentStyle[_prop.camelize] : _obj.currentStyle[_prop];
		}
		else if( getComputedStyle )
		{//Mozilla or Opera or Safari
			return document.defaultView.getComputedStyle( _obj, '' ).getPropertyValue( _prop );
		}
	};

	//-------------------------------------------------------------------
	// setSize
	//-------------------------------------------------------------------
	setSize = function(_elem, _size)
	{
		_elem.style.width = _size.w + 'px';
		_elem.style.height = _size.h + 'px';
	};
	
	//-------------------------------------------------------------------
	// setPosition
	//-------------------------------------------------------------------
	setPosition = function(_elem, _pos)
	{
		_elem.style.top		= ( _pos.t ) ? _pos.t + 'px' : null;
		_elem.style.right	= ( _pos.r ) ? _pos.r + 'px' : null;
		_elem.style.bottom	= ( _pos.b ) ? _pos.b + 'px' : null;
		_elem.style.left	= ( _pos.l ) ? _pos.l + 'px' : null;
	};
	
	//-------------------------------------------------------------------
	// setDimension
	//-------------------------------------------------------------------
	setDimension = function(_elem)
	{
		_elem.Height = _elem.clientHeight;
		_elem.Width  = _elem.clientWidth;
	};
	
	//-------------------------------------------------------------------
	// getDimension
	//-------------------------------------------------------------------
	getDimension = function(_elem)
	{
		return {height:_elem.clientHeight, width:_elem.clientWidth};
	};
	
	//-------------------------------------------------------------------
	// randRange
	//-------------------------------------------------------------------
	randRange = function(_min, _max)
	{
		return Math.floor(Math.random() * (_max - _min + 1)) + _min;
	};

	//-------------------------------------------------------------------
	// addEvent
	//-------------------------------------------------------------------
	addEvent = function(_elem, _type, _func)
	{
		if(AKCS.info.IE == true) {
			_elem.attachEvent( _type, _func );
		} else {
			_elem.addEventListener( _type, _func, false );
		}
	}

	//-------------------------------------------------------------------
	// removeEvent
	//-------------------------------------------------------------------
	removeEvent = function(_elem, _type, _func, _useCapture)
	{
		if(AKCS.info.IE == true) {
			_elem.detachEvent(_type, _func);
		} else {
			_elem.removeEventListener( _type, _func, false );
		}
	}

	//-------------------------------------------------------------------
	//  addEventByElem
	//-------------------------------------------------------------------
	addEventByElem = function(_elem, _eventType, _Function)
	{
		if(AKCS.info.IE == true)
		{
			_elem.setAttribute(_eventType, new Function(_Function));
		}
		else _elem.setAttribute(_eventType, _Function);
	};
	
	//-------------------------------------------------------------------
	//  addEventById
	//-------------------------------------------------------------------
	addEventById = function(_id, _eventType, _Function)
	{
		if(AKCS.info.IE == true) $(_id).setAttribute(_eventType, new Function(_Function));
		else $(_id).setAttribute(_eventType, _Function);
	};
	
	//-------------------------------------------------------------------
	//  addEventWithTagNameAndClassName
	//-------------------------------------------------------------------
	addEventByTagNameAndClassName = function(_tag, _className, _eventType, _Function)
	{
		var tempElement = getElementByClassName(_tag, _className);

		for(var i =0; i< tempElement.length; i++)
		{
			if(AKCS.AKCS.info.IE == true)
			{
				tempElement[i].setAttribute(_eventType, new Function(_Function));
			}
			else
			{
				tempElement[i].setAttribute(_eventType, _Function);
			}
		}
	};

	//-------------------------------------------------------------------
	//  Window Scroll Y
	//-------------------------------------------------------------------
	wscrollY = function()
	{
		return (AKCS.info.IE) ? document.documentElement.scrollTop : window.scrollY;
	}

	//-------------------------------------------------------------------
	//  Mouse Position
	//-------------------------------------------------------------------
	pointerX = function(event)
	{
		var docElement = document.documentElement,
		body = document.body || { scrollLeft: 0 };
		return event.pageX || (event.clientX + (docElement.scrollLeft || body.scrollLeft) - (docElement.clientLeft || 0));
	}

	pointerY = function(event)
	{
		var docElement = document.documentElement,
		body = document.body || { scrollTop: 0 };
		return  event.pageY || (event.clientY + (docElement.scrollTop || body.scrollTop) - (docElement.clientTop || 0));
	}

	//-------------------------------------------------------------------
	//  setStyle
	//-------------------------------------------------------------------
	setStyle = function(_elem, _style)
	{
		for(var i in _style)
		{
			_elem.style[i] = _style[i];
		}
	}

	//-------------------------------------------------------------------
	//  setBGPos
	//-------------------------------------------------------------------
	setBGPos = function(_elem, _style)
	{
		_elem.style.backgroundPosition = _style;
	}

	//-------------------------------------------------------------------
	//  setBGCol
	//-------------------------------------------------------------------
	setBGCol = function(_elem, _style)
	{
		_elem.style.backgroundColor = _style;
	}
	//-------------------------------------------------------------------
	//  getScrollHeight
	//-------------------------------------------------------------------
	getScrollHeight = function()
	{
		return (document.documentElement.scrollHeight < document.documentElement.clientHeight)
		? document.documentElement.clientHeight : document.documentElement.scrollHeight;
	}
	//-------------------------------------------------------------------
	//  FormHelper
	//-------------------------------------------------------------------
/*
	FormHelper = 
	{
		iniValues:null,
		baseURL:function(_form){return _form.action;},
	
		setIniValues:function(_form)
		{
			this.iniValues =[];
			for(var i=0; i < _form.elements.length; ++i)
			{
				this.iniValues.push({target:_form.elements[i], value:_form.elements[i].value});
			}
		},
	
		setFocus:function(_self) { _self.focus(); },
		setBlur:function(_self) { _self.blur(); },
		getForm:function (_name) { return document[_name];},
		getFormElems:function(_name) { return document[_name].elements; },	
		
		setParams:function(_self)
		{
			var tempStr = _self.action + "?";
			for(var i = 0; i < _self.elements.length; ++i)
			{
				if(i==0) { tempStr += _self.elements[i].name +"="+ EscapeUTF8(_self.elements[i].value); }
				else { tempStr += "&" + _self.elements[i].name +"="+ EscapeUTF8(_self.elements[i].value); }
			}
			// window.location.href = tempStr;
		},

		debug:function(_self)
		{
			debugForm.action = "##";
		},
	
		onEventAtSearchText:function(event, _self)
		{
			switch(event.type)
			{
				case 'focus':
					if(_self.value == 'search'){_self.value = '';} break;
				case 'blur':
					if(_self.value == ''){_self.value = 'search';} break;
			}
		}
	};
*/

	//-------------------------------------------------------------------
	//  Escape and Unescape UTF8
	//-------------------------------------------------------------------
	EscapeUTF8 = function(str)
	{
		return str.replace( /[^*+.-9A-Z_a-z-]/g,function(s)
		{
			var c=s.charCodeAt(0);
			return (c<16?"%0"+c.toString(16):c<128?"%"+c.toString(16):c<2048?"%"+(c>>6|192).toString(16)+"%"+(c&63|128).toString(16):"%"+(c>>12|224).toString(16)+"%"+(c>>6&63|128).toString(16)+"%"+(c&63|128).toString(16)).toUpperCase()
			})
	};
	
	UnescapeUTF8 = function(str)
	{
		return str.replace(/%(E(0%[AB]|[1-CEF]%[89AB]|D%[89])[0-9A-F]|C[2-9A-F]|D[0-9A-F])%[89AB][0-9A-F]|%[0-7][0-9A-F]/ig,function(s){
		var c=parseInt(s.substring(1),16);
		return String.fromCharCode(c<128?c:c<224?(c&31)<<6|parseInt(s.substring(4),16)&63:((c&15)<<6|parseInt(s.substring(4),16)&63)<<6|parseInt(s.substring(7),16)&63)
		})
	};
 
	//-------------------------------------------------------------------
	//  Alpha ( Opacity )
	//-------------------------------------------------------------------
	setAlpha = function(_elem, _alphaNum)
	{
		if(AKCS.info.IE == true)
		{
			_elem.style.filter = 'alpha(opacity = ' + Math.floor(_alphaNum) + ')';
			if(!_elem.currentStyle.hasLayout)
			{
				setStyle(_elem, { zoom: 1, width:"100%", height:"100%" });
			}
		}
		else
		{
			_elem.style.opacity = Number(_alphaNum / 100);
		}
	};
	
	getAlpha = function(_elem)
	{
		if(AKCS.info.IE == true)
		{
			var tempValue = _elem.style.filter.replace('alpha(opacity = ', '');
			tempValue = tempValue.replace(')', '');
			return (tempValue=='') ? 100 : Number(tempValue);
		}
		else
		{
			return (_elem.style.opacity == "") ? 1*100 : Number(_elem.style.opacity*100);
		}
	};

	AlphaTween = 
	{
		info:'This Class is Based on ' + AKCS.info.Product + AKCS.info.Version,
		timers:[],
		max:100,
		min:30,
		duration:15,
		btn:null,
		onInit:new Function(),
		onComplete:new Function(),
		
		set:function(_tagNames, _className) // ( Array, String )
		{
			this.onComplete = function(){alert("hoge")}
			this.btn = getElementsByClassName(_tagNames, _className);
			for(var i = 0; i < this.btn.length; ++i)
			{
				this.timers.push(new Date().getTime());
				setAlpha(this.btn[i], this.max);
				if(AKCS.info.IE == true)
				{
					this.btn[i].setAttribute("onmouseover", new Function("AlphaTween.start("+i+", 'onmouseover')" ));
					this.btn[i].setAttribute("onmouseout", new Function("AlphaTween.start("+i+", 'onmouseout')" ));
				}
				else
				{
					this.btn[i].setAttribute("onmouseover", "AlphaTween.start("+i+", 'onmouseover')");
					this.btn[i].setAttribute("onmouseout", "AlphaTween.start("+i+", 'onmouseout')");
				}
			}
		}, // End set
	
		start:function(_len, _mode) // (Number, String)
		{
			clearInterval(this.timers[_len]);
			this.timers[_len] = null;
			switch(_mode)
			{
				case 'onmouseover': this.timers[_len] = setInterval("AlphaTween.over('" + _len + "')", this.duration); break;
				case 'onmouseout': this.timers[_len] = setInterval("AlphaTween.out('" + _len + "')", this.duration); break;
			}
		}, // End start
	
		over:function(_len) // (Number)
		{
			var btn = this.btn[ _len ];
			var pos = getAlpha(btn);
			if( pos < this.min)
			{
				setAlpha(btn, this.min);
				clearInterval(this.timers[_len]);
			}
			else
			{
				var _alphaNum = pos - (pos / this.duration);
				setAlpha(btn, _alphaNum);
			}
		}, // End over
		
		out:function(_len) // (Number)
		{
			var btn = this.btn[ _len ];
			var pos = getAlpha(btn);
			if( pos > this.max)
			{
				setAlpha(btn, this.max);
				clearInterval(this.timers[_len]);
			}
			else
			{
				var _alphaNum = pos + (pos / (this.duration / 2));
				setAlpha(btn, _alphaNum);
			}
		} // End out
	};
	
	//-------------------------------------------------------------------
	//  Tween
	//-------------------------------------------------------------------
	Tween = {};
		//-------------------------------------------------------------------
		//  jumpToPageTop
		//-------------------------------------------------------------------
		Tween.jumpToPageTop = function()
		{
			var pos = document.body.scrollTop || document.documentElement.scrollTop;
			window.scrollTo( 0, pos - (pos / 10) );
			if(pos > 0) window.setTimeout("Tween.jumpToPageTop()", 10);
			else return false;
		};

	//-------------------------------------------------------------------
	//  Toggle
	//-------------------------------------------------------------------
	Toggle = 
	{
		info:'This Class is Based on ' + AKCS.info.Product + AKCS.info.Version,
		Timer:0,
		status:[],
		box:null,
		btn:null,
		inner:null,
		onInit:new Function(),
		onComplete:new Function(),
		set:function()
		{
			this.box = getElementByClassName("DIV", "toggleBox");
			this.btn = getElementByClassName("SPAN", "toggleBtn");
			this.inner = getElementByClassName("TABLE", "acTbl");
			for(var i = 0; i < this.box.length; ++i)
			{
				this.status.push({isOpen:true});
				this.box[i].style.height = this.box[i].clientHeight + "px";
				if(AKCS.info.IE == true)
				{
					this.btn[i].setAttribute("onclick", new Function("Toggle.start("+i+")" ));
				}
				else
				{
					this.btn[i].setAttribute("onclick", "Toggle.start("+i+")");
				}
			}
		}, // End set

		start:function(_len)
		{
			clearInterval(this.Timer);
			this.Timer = 0;
			this.Timer = setInterval("Toggle.open('" + _len + "')", 10);
		}, // End start

		open:function(_len)
		{
			var box = this.box[ _len ];
			var inner = this.inner[ _len ];
			var pos = parseInt(box.style.height);
			if(this.status[ _len ].isOpen == true)
			{
				if( pos == 0)
				{
					this.status[ _len ].isOpen = false;
					clearInterval(this.Timer);
				}
				else
				{
					box.style.height =pos - (pos / 10) +"px";
					box.style.height = Math.max(parseInt(box.style.height), 0) + "px";
					inner.style.marginTop = parseInt(box.style.height) - inner.clientHeight + "px";
				}
			}
			else
			{
				if( pos >= inner.clientHeight)
				{
					this.status[ _len ].isOpen = true;
					clearInterval(this.Timer);
				}
				else
				{
					box.style.height = pos + Math.max(pos / 3.33, 1) + "px";
					box.style.height = Math.min(parseInt(box.style.height), inner.clientHeight) + "px";
					inner.style.marginTop = parseInt(box.style.height) - inner.clientHeight + "px";
				}
			}
		} // End open
	};

	//-------------------------------------------------------------------
	//  addLoadEvent
	//-------------------------------------------------------------------
	addLoadEvent = function(_Func)
	{
		if(window.addEventListener) window.addEventListener("load", _Func, false);
		else if(window.attachEvent) window.attachEvent("onload", _Func);
		else window.onload = _Func;
	};

	//-------------------------------------------------------------------
	//  Ajax
	//-------------------------------------------------------------------
	Ajax = {
		getTransport: function() {
			return Try.these(
				function() {return new XMLHttpRequest()},
				function() {return new ActiveXObject('Msxml2.XMLHTTP')},
				function() {return new ActiveXObject('Microsoft.XMLHTTP')}
			) || false;
		},
		activeRequestCount:0,
		urls:[],
		commands:[],
		addReq:function() { for (var i = 0, len = arguments.length; i < len; i++){ this.urls.push(arguments[i]);} },
		addCommand:function(){	for (var i = 0, len = arguments.length; i < len; i++){ this.commands.push(arguments[i]);}},
		onStateChange:function(xhr)
		{
			//$('debug').innerHTML+=xhr.readyState;
			if (xhr.readyState == 4)
			{
				//$('debug').innerHTML+= xhr.status;
				Ajax.activeRequestCount++;
				
				/*
				FireFoxのみローカルテストを行う際にクロスドメインなことをやるとうまく実行できない
				※ステータスに206が返る
				同ドメインの場合問題はないようだ


				HTTP access control - MDC
				一旦HTTPメソッドOPTIONSでApacheに問い合わせ、
				クロスドメイン通信が許可されているかを確認してからGETメソッド等で実際の通信を行なうようだ。
				
				OPTIONSでの問い合わせ時、リクエストヘッダに
				Access-Control-Request-Headers: x-requested-with
				というものが含まれるので
				
				httpd.confに
				Header append Access-Control-Allow-Origin: *
				Header append Access-Control-Allow-Headers: x-requested-with
				等と書いてやると、クロスドメイン通信を許可することができる。
				（Access-Control-Allow-Originは実際の環境にあわせてきちんと書いた方がベター）

				*/
				//if(xhr.status == 200)
				if(xhr.readyState == 4 && xhr.status == 200)
				{
					//$('debug').innerHTML=(xhr.responseText);
					// onCompleteイベントを発行する
					if(Ajax.commands[Ajax.activeRequestCount-1] != null){ Ajax.commands[Ajax.activeRequestCount-1](xhr); }
					// urlsのlengthの数だけ読み込みを実行する
					if( Ajax.activeRequestCount < Ajax.urls.length ){ Ajax.open(); }
					else
					{
						// 終了時に各オブジェクトの初期化を行う
						Ajax.urls = [];
						Ajax.commands = [];
						Ajax.activeRequestCount=0;
					}
				}
				else
				{
					Ajax.urls = [];
					Ajax.commands = [];
					Ajax.activeRequestCount=0;
				}
			}
		},
		open:function()
		{
			var xhr = this.getTransport();
			xhr.open('GET', this.urls[this.activeRequestCount], true);
			xhr.onreadystatechange = function(e){Ajax.onStateChange(xhr)};
			//xhr.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
			//xhr.setRequestHeader("Content-Type" , "text/plane");
			//xhr.onload = function(e){alert("a"+e)}
			xhr.send(null); 
		}
	};

	//-------------------------------------------------------------------
	//  Try
	//-------------------------------------------------------------------
	Try = {
		these: function() { var returnValue; for (var i = 0, len = arguments.length; i < len; i++) { var lambda = arguments[i]; try { returnValue = lambda(); break; } catch (e) { } } return returnValue; }
	};

})();

