/*
  2008-02-13
  
-------------------------------------------------------------------*/

/*
・スタイルシートを読み込む
・class=fontsizeとあるものだけをピックアップ
・"fontsize"という名前のcookieを読み込み、値を取得
・Cookieの値と同じid属性値を持つスタイルシートがあれば、それをアクティブに
・無ければalternateではないものをそのままアクティブに

/*-------------------------------------------------------------------
  Array
-------------------------------------------------------------------*/

if(!Array.prototype.pop) {
	Array.prototype.pop = function() {
		if(!this.length) {
			return null;
		}
		else {
			var last = this[this.length - 1];
			--this.length;
			return last;
		}
	}
}

if(!Array.prototype.push) {
	Array.prototype.push = function() {
		for (var i = 0, n = arguments.length; i < n; i++) {
			this[this.length] = arguments[i];
		}
		return this.length;
	}
}

if(!Array.prototype.shift) {
	Array.prototype.shift = function() {
		if(!this.length) {
			return null;
		}
		else {
			this.reverse();
			var ret = this.pop();
			this.reverse();
			return ret;
		}
	}
}

if(!Array.prototype.unshift) {
	Array.prototype.unshift = function() {
		this.reverse();
		for (var i = arguments.length - 1; i >= 0; i--) {
			this.push(arguments[i]);
		}
		this.reverse();
		return this.length;
	}
}


if( !Array.prototype.forEach ){
	Array.prototype.forEach = function( callback,thisObject ){
		for(var i=0,len=this.length;i<len;i++) {
			callback.call(thisObject,this[i],i,this);
		}
	}
}

if( !Array.prototype.shuffle ){
	Array.prototype.shuffle = function() {
		var i = this.length;
		while(i)
		{
			var j = Math.floor(Math.random()*i);
			var t = this[--i];
			this[i] = this[j];
			this[j] = t;
		}
		return this;
	}
}

/*-------------------------------------------------------------------
	Set Utility
-------------------------------------------------------------------*/


function Util(){}

Util.prototype = {


	$: function(el){
		return typeof el == 'string' ? document.getElementById(el) : el;
	},

	getStyle: function(o,s){
		var res;
		try{
			if(document.defaultView && document.defaultView.getComputedStyle){
				res = document.defaultView.getComputedStyle(o, null).getPropertyValue(s);
			} else {
				if(o.currentStyle){
					var camelized = s.replace(/-([^-])/g, function(a,b){return b.toUpperCase()});
					res = o.currentStyle[camelized];
				}
			}
			return res;
		} catch(e){}
		return "";
	},

	setStyle: function( element, styles ){
		if(!element) return;
		for( var key in styles ){
			element.style[key] = styles[key];
		}
//		console.log(styles);
	},

	addClassName: function( el, className ){
		el = this.$(el);
		if( !this.hasClassName( el, className ) )
			el.className += ( el.className? " " : "" ) + className;
	},

	removeClassName: function(el, className){
		el = this.$(el);
		if(el.className == null) return;
		var newList = [];
		var curList = el.className.split(/\s+/);

		for(var i = 0; i < curList.length; i++)
			if(curList[i] != className)
				newList[newList.length] = curList[i];
				//newList.push(curList[i]);
		el.className = newList.join(" ");
	},

	hasClassName: function(el, className){
		el = this.$(el);
		if(!el.className) return false;
		return new RegExp("(^|\\s)" + className + "(\\s|$)" ).test( el.className );
	},

	foreach: function( array,callback ){
		var len = array.length;
		for(var i=0;i<len;i++){
			callback(array[i],i,array)
		}
	},

	// ret : '../..//common/'
	// デフォルトは /common/ に設定
	getCommonDirPath: function(){
		var dirName = arguments.length? arguments[0] : 'common';
		var links = document.getElementsByTagName('LINK');
		var reg = new RegExp( "(.*\/?" + dirName + "\/).+$" );
		if( links ){
			for( var i=0; i<links.length; i++ ){
				if( links[i].getAttribute("rel") && links[i].getAttribute("rel").indexOf("stylesheet") != -1 ) {
					if( links[i].href && links[i].href.match( reg ) )
						return RegExp.$1;
				}
			}
		}
		return '/'+ dirName +'/';
	},

	isContainerWith: function(el, tagName, className) {
		while (el != null)
		{
			if (el.tagName != null && el.tagName == tagName && u.hasClassName(el, className))
				return true;
			else
				el = el.parentNode;
		}
		return false;
	},

	getContainerWith: function(el, tagName, className) {
		while (el != null)
		{
			if (el.tagName != null && el.tagName == tagName && u.hasClassName(el, className))
				return el;
			else
				el = el.parentNode;
		}
		return el;
	}

}
var u = new Util();




/*-------------------------------------------------------------------
  Events
-------------------------------------------------------------------*/

var EventManager = {};

EventManager.list = [];

EventManager.removeEvent = function( obj, event, listener, useCapture ){
	useCapture = useCapture || false;
	if(obj.removeEventListener){
		obj.removeEventListener( event, listener, useCapture );
	} else if(obj.detachEvent){
		obj.detachEvent( "on"+event, listener );
	} else {
		//delete obj['on'+event];
	}
};

EventManager.addEvent = function( obj, event, listener, useCapture ){
	//EventManager.list.push(arguments);
	EventManager.list[EventManager.list.length] = arguments;
	useCapture = useCapture || false;
	if(obj.addEventListener){
		obj.addEventListener( event, listener, useCapture );
	} else if(obj.attachEvent){
		obj.attachEvent( "on"+event, listener );
	} else {
		var exists = obj['on'+event];
		obj['on'+event] = (exists)?
			function(){
				exists();
				listener();
			} : function() {
				listener();
			};
	}
};


/*-------------------------------------------------------------------
  StyleSwitcher
-------------------------------------------------------------------*/


function StyleSwitcher( className, defaultId ){
	if(!className) return;
	this.className = className;
	this.defaultId = defaultId || '';
	this.stylesheets = [];
	this.cookieName = 'style-' + className;
	this.init();
}

StyleSwitcher.prototype = {

	getActiveStyleSheetId: function(){
		var currentId = "";
		for( var i=0; i<this.stylesheets.length; i++ ){
			if( !this.stylesheets[i].disabled ){
				currentId = this.stylesheets[i].getAttribute("id");
				return currentId;
			}
		}
		return false;
	},

	setActiveStyleSheet: function(id){
		for( var i=0; i<this.stylesheets.length; i++ ){
			if( this.stylesheets[i].getAttribute("id") == id ){
				this.createCookie( this.cookieName, id, 365 );
				this.stylesheets[i].disabled = true;
				this.stylesheets[i].disabled = false;
			}
			else{
				this.stylesheets[i].disabled = true;
			}
		}
	},


	createCookie: function(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	},


	readCookie: function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	},


	init: function(){
		var links = document.getElementsByTagName("LINK");
		if( !links ) return;

		for( var i=0; i<links.length; i++ ){
			if( links[i].getAttribute("rel") && links[i].getAttribute("rel").match(/stylesheet/i) ) {
				if( u.hasClassName(links[i], this.className) && links[i].getAttribute("id") ){
					this.stylesheets.push(links[i]);
				}
			}
		}

		var c = this.readCookie(this.cookieName);
		var id = c? c : (this.defaultId? this.defaultId : null );
		if(id) this.setActiveStyleSheet(id);

		// event
		var _this = this;
		EventManager.addEvent(window, 'unload', function(){
			var id = _this.getActiveStyleSheetId();
			if(id)
				_this.createCookie( _this.cookieName, id, 365 );
			//else
			//	_this.createCookie( _this.cookieName, links[0].getAttribute("id"), 365 );
		}, false);
	}
}



/*
  
  
-------------------------------------------------------------------*/

function FontSizeSelector( param ){
	this.className = "";
	this.buttons   = [];
	this.buttonTitle = {};
	this.displayBlockId = "";
	this.roi = null;

	for( var i in param ){
		this[i] = param[i];
	}

	if( this.className && this.buttons.length ){
		this.switcher = new StyleSwitcher( this.className );
		if( this.displayBlockId )
			this.display( this.displayBlockId );
	}
}


FontSizeSelector.prototype = {

	init: function( roiObject ){
		var activeStyleSheetId = '';
		var val = this.switcher.readCookie(this.switcher.cookieName);
		if( val ) {
			activeStyleSheetId = val;
		}
		else{
			var links = document.getElementsByTagName("LINK");
			if( !links ) return;
			for( var i=0; i<links.length; i++ ){
				var rel = links[i].getAttribute("rel");
				if( rel && rel.match(/stylesheet/i) && links[i].getAttribute("id") ) {
					if( !rel.match(/alternate/i) ){
						activeStyleSheetId = links[i].getAttribute("id")
					}
					else if( rel.match(/alternate/i) && links[i].disabled == false ){ // for IE
						links[i].disabled = true;
					}
				}
			}
		}
		if(!activeStyleSheetId) return;

		var _this = this;
		var i = 0;
		this.roi = roiObject;
		u.foreach( this.buttons, function( btn ){
			var el = u.$(btn.buttonId);
			if( btn.linkId == activeStyleSheetId ){
				if( _this.roi ){
					u.foreach( _this.roi.buttons, function( fsbtn ){
						if( fsbtn.id == btn.buttonId )
							_this.roi.activate( fsbtn, _this.roi.aSuffix );
					} );
				}
				if( el && btn.label )
					el.alt = el.title = _this.getButtonTitle(  btn.label, "current" );
			}
			else {
				if( el && btn.label )
					el.alt = el.title = _this.getButtonTitle(  btn.label, "default" );
			}
			i++;
		} );
	},

	display: function( id ){
		if( id )
			document.write('<style type="text/css" media="screen,projection,tv">#'+ id +' {display: block !important;}</style>');
	},

	getButtonTitle: function( label, type ){
		var reg = /%%label%%/i;
		var t = this.buttonTitle;
		if(t && t[type]){
			return t[type].replace( reg, label );
		}
		return label;
	},

	setFontSize: function( size ){
		var _this = this;
		u.foreach( this.buttons, function( btn ){
			if( u.$( btn.buttonId ) ){
				var el = u.$( btn.buttonId );
				if( btn.size == size ){
					_this.switcher.setActiveStyleSheet( btn.linkId );
					if(_this.roi) _this.roi.activate( u.$(btn.buttonId) );
					if( btn.label )
						el.alt = el.title = _this.getButtonTitle(  btn.label, "current" );
				}
				else {
					if(_this.roi) _this.roi.deactivate( u.$(btn.buttonId) );
					if( btn.label )
						el.alt = el.title = _this.getButtonTitle(  btn.label, "default" );
				}
			}
		} );
	}

};


/*-------------------------------------------------------------------
  init
-------------------------------------------------------------------*/
var FONTSIZE_SELECTOR_ENABLED = true;

var fsSelector;

if( FONTSIZE_SELECTOR_ENABLED ){

	fsSelector = new FontSizeSelector({
		className        : "fontsize",
		buttons :  [
			{
				size     : "small",
				buttonId : "fsbutton-small",
				linkId   : "fontsize-small",
				label    : ""
			},
			{
				size     : "medium",
				buttonId : "fsbutton-medium",
				linkId   : "fontsize-medium",
				label    : ""
			},
			{
				size     : "large",
				buttonId : "fsbutton-large",
				linkId   : "fontsize-large",
				label    : ""
			}
		],
		buttonTitle : {
			"default"    : "",
			"current"    : ""
		},
		displayBlockId   : ""
	});


	EventManager.addEvent( window, 'load', function(){
		var roi = new RolloverImages('rollover-fsbutton','on', 'on');
		fsSelector.init( roi );
	}, false );

}


