/* -------------------------------------------

	* 共通関数実行
	* init
	
------------------------------------------- */
$(function () {

	/* for IE6 background image flicker */
	if (jQuery.browser.msie && jQuery.browser.version == 6) {
		try {
			document.execCommand("BackgroundImageCache", false, true);
		} catch (err) {}
	}
	
	/* FloatImage */
	$("#info .image").not(".no").FloatImage();
	$("#info .imageBox").not(".no").FloatImage();
	
	/* popup */
	$(".popup").popup();

	/* SmoothScroll */
	$().SmoothScroll();

	/* Rollover */
	new RolloverImages("rollover", "on");

	/* adjustHeight */
	var fSWatcher = new fontSizeWatcher();
	if(!$(CLASS_TARGET_ELEMENTS).length == 0) fSWatcher.start();
	$( CLASS_TARGET_ELEMENTS ).initAdjustHeight();
	
});

/* -------------------------------------------

	* 共通関数定義
	* @function
	
------------------------------------------- */
(function ($) {
	
	/* ---------------------
		adjustHeight Setup
	--------------------- */
	/* 並列するカラムの高さをあわせる際に指定するclass */
	CLASS_TARGET_ELEMENTS = ".menuColWrap, .col2Wrap, .imageCol02, .imageCol03, .imageColRental, .contactWrap, .imageBlock03 .thumbnail";
	
	/* CLASS_TARGET_ELEMENTS内でボックスの高さを合わせる際に指定する要素 */
	CLASS_TARGET_FIGURE_ELEMENTS = ".inner, .imageColRental .image, .caption, .contactWrap .col, .contactWrap .col dl dl dt, .thumbnail li";

	fontSizeWatcher = function(){
		this.elm = $('<div id="fontSizeWatcher">&nbsp;</div>').css({
			display: 'block',
			visibility: 'hidden',
			position: 'absolute',
			padding: '0',
			top: '0'
		});
		if(!$(CLASS_TARGET_ELEMENTS).length == 0) this.elm.appendTo('body');
		this.lastHeight = this.elm.height(); //.offsetHeight
	}
	
	fontSizeWatcher.prototype = {
		elm: null,
		lastHeight: 0,
		timer: null,
		test: function(){
			if( this.elm.height() !== this.lastHeight ){
				this.lastHeight = this.elm.height();
				this.elm.trigger("fontSizeChange");
			}
		},
		start: function(){
			var that = this;
			this.timer = setInterval( function(){that.test()}, 200 );
		},
		toString: function(){ return "fontSizeWatcher" }
	}

	/* 並列カラムの高さあわせ */
	$.fn.adjustHeight = function(){
		
		var contentsWidth = $('div#contents').width();
		var targetColumn = this.find("> *");	
		//高さをを合わせる対象のBox数
		//var targetNum = targetColumn.length;
		
		/* コンテンツ幅による振り分け */
		if(contentsWidth > 620){
			var targetNum = Math.floor(860 / targetColumn.width());
		} else {
			var targetNum = Math.floor(620 / targetColumn.width());
		}
		
		/* カラムが2つ以上ない場合は無視 */
		if(targetNum < 2) {
			return;
		}
	
		var ROW_MAX_HEIGHT, HEADING_MAX_HEIGHT, ELEMENTS;
		
		targetColumn.each( function(i) {
			ROW_MAX_HEIGHT = 0;
			HEADING_MAX_HEIGHT = 0;
			
			/* タイトル高さ合わせ */
			for( var j=0; j<targetNum && i*targetNum+j < targetColumn.length; j++ ){
				ELEMENTS = $(CLASS_TARGET_FIGURE_ELEMENTS,targetColumn.get(i*targetNum+j));
				HEADING_MAX_HEIGHT = Math.max( ELEMENTS.css("height","auto").height(), HEADING_MAX_HEIGHT );
			}
			for( var j=0; j<targetNum && i*targetNum+j < targetColumn.length; j++ ){
				ELEMENTS = $(CLASS_TARGET_FIGURE_ELEMENTS,targetColumn.get(i*targetNum+j));
				ELEMENTS.height(HEADING_MAX_HEIGHT);
			}
			
			/* 直下のBOXの高さ合わせ */
			for( var j=0; j<targetNum && i*targetNum+j < targetColumn.length; j++ ){
				ELEMENTS = $(targetColumn.get(i*targetNum+j));
				ROW_MAX_HEIGHT = Math.max( ELEMENTS.css("height","auto").height(), ROW_MAX_HEIGHT );
			}
			for( var j=0; j<targetNum && i*targetNum+j < targetColumn.length; j++ ){
				ELEMENTS = $(targetColumn.get(i*targetNum+j));
				ELEMENTS.height(ROW_MAX_HEIGHT);
			}
		});
		return this;
	}

	/* 並列カラムの高さあわせ初期化 */
	$.fn.initAdjustHeight = function(){
		return this.each(function(){
			var that = $(this);
			$("#fontSizeWatcher").bind("fontSizeChange",function(){that.adjustHeight()});
			$(this).adjustHeight();
		});
	}
	
	/* ------------------------------------------
		FloatImage Setup
	------------------------------------------ */
	$.fn.FloatImage = function () {
		$(this).each(function() {
				var w = $("img", this).width() + 2;
				$(this).css("width",w);
				
				/* 回り込みの際に、block要素がある場合 */
				var width_all = $(this).parent().width();
				var target = $(this).siblings(".widthFix");
				target.css("width",width_all - w -15);
		});
	};
	
	/* ------------------------------------------
		Popup Setup
	------------------------------------------ */
	$.fn.popup = function (op) {
		settings = {
			height: 600, // 高さ設定
			width: 700, // 幅設定
			toolbar: 0, // ツールバー 1 (YES) or 0 (NO)
			scrollbars: 1, // スクロールバー 1 (YES) or 0 (NO)
			status: 0, // ステータスバー 1 (YES) or 0 (NO)
			resizable: 1, // リサイズ 1 (YES) or 0 (NO)
			left:0, // ポジション（left）
			top:0, // ポジション（top）
			center: 1 // 中央表示 1 (YES) or 0 (NO)
		};
		
		if (settings.center == 1) {
			settings.top = (screen.height - settings.height) / 2;
			settings.left = (screen.width - settings.width) / 2;
		}
		
		$.extend(settings,op || {});
		
		return this.each(function () {
	
			parameters = "height=" + settings.height + ",width=" + settings.width + ",toolbar=" + settings.toolbar + ",scrollbars=" + settings.scrollbars + ",status=" + settings.status + ",resizable=" + settings.resizable + ",left=" + settings.left + ",screenX=" + settings.left + ",top=" + settings.top + ",screenY=" + settings.top;
	
			$(this).bind("click", function () {
				var name = "POPUP";
				winObj = window.open(this.href, name, parameters);
				winObj.focus();
				return false;
			});
		});
	};
	
	/* ------------------------------------------
		ol list
	------------------------------------------ */
	/* OL見栄え調整 */
	$.fn.dressOL = function(){
		return this.each( function(){
			$(this).addClass("dressed")
		})
	}

	/**
	 * 初期表示処理
	 */
	$(document).ready( function(){

		/* OL.numberList01の粉飾 */
		$("ol.numberList01").dressOL();

	});

	/**
	 * JS読み込み時処理
	 */

	/* CSSチラつき対応 */
	try {
		document.execCommand('BackgroundImageCache', false, true);
	} catch( myEx ) {}
	
	/* ------------------------------------------
		SmoothScroll Setup
	------------------------------------------ */
	$.fn.SmoothScroll = function (options) {

		var scroller = (function () {
			var c = $.extend({
				easing: 100,
				step: 30,
				fps: 60,
				fragment: ""
			}, options);

			c.ms = Math.floor(1000 / c.fps);
			var timerId;
			var param = {
				stepCount: 0,
				startY: 0,
				endY: 0,
				lastY: 0
			};

			function move() {
				if (param.stepCount == c.step) {
					// scroll end
					setFragment(param.fragment);

					window.scrollTo(getCurrentX(), param.endY);
				} else if (param.lastY == getCurrentY()) {
					// scroll
					param.stepCount++;
					window.scrollTo(getCurrentX(), getEasingY());
					param.lastY = getEasingY();
					timerId = setTimeout(move, c.ms);
				} else {
					// error	
					if (getCurrentY() + getViewportHeight() == getDocumentHeight()) {
						setFragment(param.fragment);
					}
				}
			}

			function setFragment(fragment) {
				location.href = location.href.split("#")[0] + fragment;
			}

			function getEasingY() {
				return Math.floor(getEasing(param.startY, param.endY, param.stepCount, c.step, c.easing));
			}

			function getEasing(start, end, stepCount, step, easing) {
				var s = stepCount / step;
				return (end - start) * (s + easing / (100 * Math.PI) * Math.sin(Math.PI * s)) + start;
			}

			function targetOffsetTop(target) {
				return target.offset().top;
			}
			return {
				set: function (options) {
					this.stop();
					if (options.startY == undefined) options.startY = getCurrentY();
					param = $.extend(param, options);
					param.lastY = param.startY;
					param.fragment = options.fragment;
					timerId = setTimeout(move, c.ms);
				},
				stop: function () {
					clearTimeout(timerId);
					param.stepCount = 0;
				}
			};
		})();

		function getCurrentY() {
			return document.body.scrollTop || document.documentElement.scrollTop;
		}

		function getCurrentX() {
			return document.body.scrollLeft || document.documentElement.scrollLeft;
		}

		function getDocumentHeight() {
			return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement.scrollHeight : document.body.scrollHeight;
		}

		function getViewportHeight() {
			return (!$.browser.safari && !$.browser.opera) ? document.documentElement.clientHeight || document.body.clientHeight || document.body.scrollHeight : window.innerHeight;
		}
		// init
		$("a[href^=#], area[href^=#]").not("a[href=#], area[href=#], a.no-scroll, area.no-scroll").click(function () {

			var fragment = $(this).attr("href");
			var target = $(fragment);
			if (target.length == 0) target = $("a[name=" + fragment + "]");

			if (target.length) {
				scroller.set({
					endY: ((getDocumentHeight() - target.offset().top)) < getViewportHeight() ? getDocumentHeight() - getViewportHeight() : target.offset().top,
					fragment: fragment,
					_target: target
				});

				return false;
			}
		});
	}

})(jQuery)

/* ------------------------------------------
  Rollover Setup
------------------------------------------ */

function RolloverImages(className, onSuffix, aSuffix) {
	this.init(className, onSuffix, aSuffix);
}

RolloverImages.prototype = {

	init: function (className, onSuffix, aSuffix) {
		if (!document.getElementById || !document.images || !className) return;

		// 
		this.targetClassName = className;
		this.onSuffix = onSuffix;
		this.aSuffix = aSuffix;
		//this.mdSuffix = mdSuffix;
		this.buttons = [];

		// 
		var _this = this;
		var imgs = [];
		var inputs = [];
		var rolloverObj = [];

		var selectors = ["img." + this.targetClassName, "input." + this.targetClassName];

		$(selectors.join(", ")).each(function (i) {
			var el = $(this);
			rolloverObj.push(this);
		});

		$.each(rolloverObj, function (i) {
			_this.registButton(this);
		});
		this.preloadImages();
	},


	registButton: function (el) {
		var _this = this;
		var btn = new Object();
		btn.src = el.src;
		btn.filetype = btn.src.substring(btn.src.lastIndexOf("."));
		btn.basename = btn.src.substring(0, btn.src.length - btn.filetype.length);
		btn.onsrc = btn.basename + this.onSuffix + btn.filetype;

		el.offsrc = btn.src;
		el.onsrc = btn.onsrc;
		el.lock = false;
		if (this.aSuffix) {
			btn.activesrc = btn.basename + this.aSuffix + btn.filetype;
			el.activesrc = btn.activesrc;
		}

		this.buttons.push(el);

		if (!this.aSuffix) {
			$(el).bind("mouseover", function () {
				_this.swapImage(el, "on");
			});
			$(el).bind("mouseout", function () {
				_this.swapImage(el, "off");
			});
			if (el.parentNode && el.parentNode.tagName == "A") {
				var p = el.parentNode;
				$(p).bind("focus", function () {
					_this.swapImage(el, "on");
				});
				$(p).bind("blur", function () {
					_this.swapImage(el, "off");
				});
			}
		} else {
			$(el).bind("mouseover", function () {
				if (!el.lock) _this.swapImage(el, "on");
			});
			$(el).bind("mouseout", function () {
				if (!el.lock) _this.swapImage(el, "off");
			});
			$(el).bind("mouseup", function () {
				$(_this.buttons).each(function (i) {
					_this.deactivate(this)
				});
				_this.activate(el);
			});

			if (el.parentNode && el.parentNode.tagName == "A") {
				var p = el.parentNode;
				$(p).bind("focus", function () {
					if (!el.lock) _this.swapImage(el, "on");
				});
				$(p).bind("blur", function () {
					if (!el.lock) _this.swapImage(el, "off");
				});

				$(p).bind("keypress", function (e) {
					if (jQuery.browser.msie || (!jQuery.browser.msie && e.keyCode == 13)) {
						//Event.stop(e);
						$(_this.buttons).each(function (i) {
							_this.deactivate(this)
						});
						_this.activate(el);
					}
				});
			}

		}
	},

	preloadImages: function () {
		var ret = [];
		for (var i = 0; i < this.buttons.length; i++) {
			(new Image()).src = this.buttons[i].onsrc;
			ret[ret.length] = this.buttons[i].onsrc;
			if (this.buttons[i].activesrc) {
				(new Image()).src = this.buttons[i].activesrc;
				ret[ret.length] = this.buttons[i].activesrc;
			}
		}
	},

	swapImage: function (obj, status) {
		if (!obj || !obj[status + "src"]) return;
		if (!obj.lock) obj.src = obj[status + "src"];
	},

	activate: function (el) {
		this.swapImage(el, "active");
		this.lock(el);
	},

	deactivate: function (el) {
		this.unlock(el);
		this.swapImage(el, "off");
	},

	lock: function (obj) {
		if (obj.lock == "undefined") return;
		if (!obj.lock) obj.lock = true;
	},

	unlock: function (obj) {
		if (obj.lock == "undefined") return;
		if (obj.lock) obj.lock = false;
	}

}
