(function($){
/*------------------------------------------------------------
	jQuery Plugins
------------------------------------------------------------*/
/*	Easing Plugin
------------------------------*/
$.extend( jQuery.easing, {
	def: 'easeOutQuad',
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	}
});

/*	Utility Plugin
------------------------------*/
$.extend({
	combineSuffix: function(imgpath, suffix) {
		var dot = imgpath.lastIndexOf('.');
		var suffixDot = imgpath.search(new RegExp(suffix+'ﾂ･ﾂ･.'));
		if(suffixDot != -1){
			return imgpath.substr(0, suffixDot) + suffix + imgpath.substr(dot);
		} else {
			return imgpath.substr(0, dot) + suffix + imgpath.substr(dot);
		}
	},
	parseQuery : function(query) {
		var Params = {};
		if (!query) {return Params;}// return empty object
		var Pairs = query.split(/[;&]/);
		for (var i = 0; i < Pairs.length; i++) {
			var KeyVal = Pairs[i].split('=');
			if (!KeyVal || KeyVal.length != 2) {continue;}
			var key = unescape(KeyVal[0]);
			var val = unescape(KeyVal[1]);
			val = val.replace(/\+/g, ' ');
			Params[key] = val;
		}
		return Params;
	}
});

/*	Image Hover 
------------------------------------------------------------*/
$.fn.extend({
	imgHover : function() {
		var setting = $.extend({
			suffix : '_o'
		}, $.makeArray(arguments).shift());
		this.suffix = setting.suffix;
		var _window = $(window);
		return this.each(function() {
			var imgsrc = this.src;
			var imgsrc_on = $.combineSuffix(imgsrc, setting.suffix);
			new Image().src = imgsrc_on;
			var _this = $(this).data('src', imgsrc).data('src_o', imgsrc_on).hover(
				function() { this.src = imgsrc_on; },
				function() { this.src = imgsrc; }
			);
			_window.unload(function(e){
				_this.attr('src', _this.data('src'));
			});
		});
	}
});

/*------------------------------------------------------------
	Panorama Scripts
------------------------------------------------------------*/
/*	Global Variables
------------------------------*/
var _root = '/motion_panorama/jp/';
var _hashpath = '',
	_param = {},
	_currentPanel = 0,
	_duration = 1500,
	_panelList = [],
	_panelBodyObjList = [],
	_panelPathList = [],
	_panelPosList = [],
	_bgPosList = [],
	_preloadArray = [],
	_widthBG = 800,
	_widthVP;
var $contents,
	$mpLayer,
	$mpLoadingLayer,
	$mpGlobalNav,
	$mpGlobalNavLinks,
	$mpSwitch,
	$mpSwitchBtns,
	$mpPrevBtn,
	$mpNextBtn,
	$mpPanelArea,
	$mpContents,
	$mpContentsBg;

var $mpHomeSection;

/*	Initil Style For Javascript
------------------------------*/
addCssRule(document.styleSheets[0], '#contents', 'visibility : hidden;');

if(location.hash.search(/^#.+$/i) != -1){
	var _hash = location.href.match(/#.+$/)[0];
	_hash = _hash.substr(1);
	_hashArray = _hash.split('?');
	_hashpath = _hashArray[0];
	_param = $.parseQuery(_hashArray[1]);
	_param.p = Number(_param.p);
	_currentPanel = _param.p;
}


/*	DOM Ready
------------------------------*/
$(function(){
	$('a.overLayer').colorbox({ opacity : 0.5, close :'<img width="33" height="33" src="img/shared/btn_close_01.gif" alt="Close" />', iframe : true, innerWidth :963 ,innerHeight : 436 });
	$(window).keydown(cancelTabKey);
	$(window).keypress(cancelTabKey);
	$(window).keyup(cancelTabKey);

	$('#mpContentsBg').bind('contextmenu', function(e){
		e.preventDefault();
	});

	init();
});

/*	Initialize
------------------------------*/
function init(){
	$mpGlobalNav = $('#mpGlobalNav');
	$mpGlobalNavLinks = $mpGlobalNav.find('a').each(function(index, item){
		var $this = $(this);
		$this.addClass('mpToPanel_' + index);
		_panelPathList.push($this.attr('href'));
	});
	if(_param.p){
		_panelPathList[_param.p] = _hashpath;
	}

	$mpSwitch = $('#mpSwitch');
	$mpSwitchBtns = $mpSwitch.find('a');
	$mpPrevBtn = $('#mpPrevBtn');
	$mpNextBtn = $('#mpNextBtn');
	$contents = $('#contents');
	$mpContentsBg = $('#mpContentsBg');
	$mpPanelArea = $('#mpPanelArea');
	$('.mpContents').remove();
	_widthVP = $contents.width();

	/* opening init */
	$mpLayer = $('<div id="mpLayer"></div>').appendTo($contents);
	$mpLoadingLayer = $('<div id="mpLoadingLayer"></div>').appendTo($contents);

	loadPanel();
}


/*	Load Contents Panel
------------------------------*/
function loadPanel(){
	var _code = '',
		_countList = [];
	$.each(_panelPathList, function(index, value){
		$.get(value + '?rnd=' + new Date().getTime(), function(data){
			_code += getContentsHTML(data);
			_panelBodyObjList[index] = parseBodyElem(data);
			_panelPosList[index] = _widthVP * index * -1;
			_bgPosList[index] = _widthBG * index * -1;
			_countList.push(index);

			if(_countList.length == _panelPathList.length){
				$mpPanelArea.append(_code);
				$('div.mpContents').each(function(i, item){
					$(this).attr('id', 'mpPanel_' + _countList[i]).css('left', _widthVP * _countList[i]);
				});

				loadCallBack();
			}
		}, 'html');
	});
}


/*	Panel Loaded Callback
------------------------------*/
function loadCallBack(){
	$mpContents = $('.mpContents', $mpPanelArea);
	$mpContents.each(function(index, item){
		$panel = $(this);
		var _panelNum = Number($panel.attr('id').replace('mpPanel_', ''));
		_panelList[_panelNum] = $panel;
	});
	if(_currentPanel == 0){ // Opening
		$mpHomeSection = $('#mpHomeSection').css({ 'opacity' : 0 });
	}

	/* Rollover */
	$('img.mpImgover').imgHover();

	/* png fix for IE6 */
	if(!!window.DD_belatedPNG){
		$('.pngImg', $contents).each(function(){
			window.DD_belatedPNG.fixPng(this);
		});
	}
	$('.pngFixImg', $contents).pngFix({ 'blankgif' : _root + 'img/shared/blank.gif' });

	/* resize window */
	$(window).resize(setViewport);

	/* opening start */
	$contents.css('visibility', 'visible');
	setTimeout(function(){
		openingAnimation();
	}, 4800); // loading time
}


/*	Oprning Animation
------------------------------*/
function openingAnimation(){
	var _durationOpening = 3000;
	changeBodyElem(_currentPanel);

	if(_currentPanel == 0){ // Opening
		$mpContentsBg.css({ 'backgroundPosition' : 2725 + 'px 52px' });
		$mpLoadingLayer.animate({ opacity : 0 }, 500, function(){
			$mpContentsBg.animate({ 'backgroundPosition' : '0px 52px' }, _durationOpening, 'easeOutCirc', function(){
				$mpHomeSection.animate({ 'opacity' : 1 }, 1000, function(){
					if(!!this.style.filter){
						this.style.removeAttribute("filter");
					}
					$mpLoadingLayer.remove();
					$mpLayer.hide();
					openingCallback();
				});
			});
			$mpLayer.animate({ opacity : 0 }, 1000);
		});
	} else { // Skip
		$mpContentsBg.css({ 'backgroundPosition' : _bgPosList[_currentPanel] + 'px 52px' });
		$mpLoadingLayer.animate({ opacity : 0 }, 500, function(){
			$mpPanelArea.css({ 'left' : _panelPosList[_currentPanel] });
			$mpLayer.animate({ opacity : 0 }, 1000, function(){
				$mpLoadingLayer.remove();
				$mpLayer.hide();
				openingCallback();
			});
		});
	}
}

/*	Opening Callback
------------------------------*/
function openingCallback(){
	setSwitchEvent();
	setScrollEvent();
	setSectionEvent();

	/* under construction */
	setGnavTooltip();
}


/*	Set Switch Event
------------------------------*/
function setSwitchEvent(){
	var _durationSwitch = 250;
	var _durationBg = 500;

	/* Display Switch */
	$mpSwitch.hover(
		function(){
			$mpSwitch.stop().addClass('hover');
			$mpSwitch.animate({ 'bottom' : 0 }, _durationSwitch);
		},
		function(){
			$mpSwitch.stop().removeClass('hover');
			$mpSwitch.animate({ 'bottom' : -52 }, _durationSwitch);
		}
	);
	$mpSwitch.animate({ 'bottom' : -52 }, _durationSwitch);

	
	/* Background Switch */
	$mpSwitchBtns.each(function(index, item){
		var $this = $(this);
		var _bgPath = $this.attr('href');
		_preloadArray.push(new Image());
		_preloadArray[index].src = _bgPath;

		$this.hover(
			function(){
				$this.addClass('mpHover');
			},
			function(){
				$this.removeClass('mpHover');
			}
		);
		$this.click(function(e){
			this.blur();
			if($(this).hasClass('mpActive')){ e.preventDefault(); return; }
			$mpLayer.show();
			setTimeout(function(){
				$mpSwitchBtns.removeClass('mpActive');
				$this.addClass('mpActive');
				$mpContentsBg.animate({ opacity : 0 }, _durationBg, function(){
					$mpContentsBg.css('background-image', 'url(' + _bgPath + ')');
					$mpContentsBg.animate({ opacity : 1 }, _durationBg, function(){
						$mpLayer.hide();
					});
				});
			}, 1);
			e.preventDefault();
		});
	});
}

/*	Set Scroll Event
------------------------------*/
function setScrollEvent(){
	$('a.mpPanelLink').mpScrollPanelLink();

	$.each(_panelList, function(index, item){
		$('#mpGlobalNav .mpToPanel_' + index).click(function(e){
			this.blur();
			if(_currentPanel != index){
				$.mpScrollPanel(index);
			}
			e.preventDefault();
		});
	});
	$.mpScrollPager();
}

/* Scroll Panel Event Extended */
$.fn.extend({
	mpScrollPanelLink : function() {
		var setting = $.extend({
			event : 'click'
		}, $.makeArray(arguments).shift());
		return this.bind(setting.event, function(e) {
			this.blur();
			var $this = $(this);
			var _href = $this.attr('href').replace(location.protocol + '//' + location.host + _root, '');
			var _contentsArray = _href.split('?');
			var _contentsPath = _contentsArray[0];
			var _contentsParam = $.parseQuery(_contentsArray[1]);
			_contentsParam.p = Number(_contentsParam.p);
			$.mpScrollPanel(_contentsParam.p);
			$.mpSectionLink(_contentsPath, _contentsParam.p, _contentsParam.a);

			e.preventDefault();
		});
	}
});
$.extend({
	mpScrollPanelLink : function(_href){
		_href = _href.replace(location.protocol + '//' + location.host + _root, '');
		var _contentsArray = _href.split('?');
		var _contentsPath = _contentsArray[0];
		var _contentsParam = $.parseQuery(_contentsArray[1]);
		_contentsParam.p = Number(_contentsParam.p);
		$.mpScrollPanel(_contentsParam.p);
		$.mpSectionLink(_contentsPath, _contentsParam.p, _contentsParam.a);
	},
	mpScrollPanel: function(panelNum){
		$mpLayer.show();
		setTimeout(function(){
			_currentPanel = panelNum; // CHANGE PANEL
			changeBodyElem(-1);
	
			$mpContentsBg.animate({ 'backgroundPosition' : _bgPosList[_currentPanel] + 'px 52px' }, _duration, 'easeInOutCubic');
			$mpPanelArea.animate({ 'left' : _panelPosList[_currentPanel] }, _duration, 'easeInOutCubic', function(){
				$.mpScrollPager();
				changeBodyElem(_currentPanel);
				changeHashAddress(_currentPanel, _panelPathList[_currentPanel]);
				$mpLayer.hide();
			});
		}, 1);
	},
	mpScrollPager: function() {
		var _durationPager = 250;
		$mpPrevBtn.unbind('click');
		$mpNextBtn.unbind('click');
		if(_currentPanel != 0){
			$mpPrevBtn.click(function(e){
				$.mpScrollPanel(_currentPanel-1);
				e.preventDefault();
			});
			if(Number($mpPrevBtn.css('left').replace('px', '')) != 0){
				$mpPrevBtn.animate({ 'left' : 0 }, _durationPager);
			}
		} else {
			$mpPrevBtn.animate({ 'left' : -342 }, _durationPager);
		}

		if(_currentPanel != _panelList.length-1){
			$mpNextBtn.click(function(e){
				$.mpScrollPanel(_currentPanel+1);
				e.preventDefault();
			});
			if(Number($mpNextBtn.css('right').replace('px', '')) != 0){
				$mpNextBtn.animate({ 'right' : 0 }, _durationPager);
			}
		} else {
			$mpNextBtn.animate({ 'right' : -34 }, _durationPager);
		}
	}
});


/*	Set Section Event
------------------------------*/
function setSectionEvent(){
	$('.mpContentsNav a', $mpPanelArea).mpSectionLink()
	$('a.mpLink').mpSectionLink();
}

/* Section Link Event Extended */
$.extend({
	mpSectionLink: function(path, panelNum, anchorId){
		var setting = $.extend({
			duration : 250
		}, $.makeArray(arguments).shift());

		var $panelContents = $('div.mpContents').filter('#mpPanel_' + panelNum);
		var $panelSection = $panelContents.find('div.mpSectionWrap');
		var _panelNum = $panelContents.attr('id').replace('mpPanel_', '');

		$.get(path + '?rnd=' + new Date().getTime(), function(data){
			_panelBodyObjList[_panelNum] = parseBodyElem(data);
			_panelPathList[_panelNum] = path;
			var _code = getSectionHTML(data);
			$panelSection.mpChangeContents(_code, setting.duration, anchorId);
		}, 'html');
	}
});
$.fn.extend({
	mpSectionLink : function() {
		var setting = $.extend({
			duration : 250,
			event : 'click'
		}, $.makeArray(arguments).shift());
		return this.bind(setting.event, function(e) {
			this.blur();
			var $this = $(this);
			var $panelContents = $this.parents('div.mpContents');
			var _panelNum = Number($panelContents.attr('id').replace(/^mpPanel_/, ''));
			var _contentsPath = $this.attr('href').replace(location.protocol + '//' + location.host + _root, '');

			$.mpSectionLink(_contentsPath, _panelNum);
			e.preventDefault();
		});
	},
	mpChangeContents : function(code, duration, anchorId) {
		var _this = this;
		changeBodyElem(_currentPanel);
		return _this.animate({ opacity : 0 }, duration, function(){
			_this.html(code);

			if(anchorId){
				_this.find('div.mpSection').get(0).scrollTop = _this.find('#' + anchorId).offset().top - _this.offset().top;
			}
			$('img.mpImgover', _this).imgHover();
			$('a.mpLink', _this).mpSectionLink();
			$('a.mpPanelLink', _this).mpScrollPanelLink();
			_this.animate({ opacity : 1 }, duration, function(){
				if(!!this.style.filter){
					this.style.removeAttribute("filter");
				}
				changeBodyElem(_currentPanel);
				changeHashAddress(_currentPanel, _panelPathList[_currentPanel]);
			});
		});
	}
});


/*	Set Global Navigation Tooltip
------------------------------*/
function setGnavTooltip(){
	$mpGlobalNav.find('li').each(function(){
		var $this = $(this);
		var $mpTooltip = $this.find('div.mpTooltip');
		$this.hover(
			function(){ $mpTooltip.show(); },
			function(){ $mpTooltip.hide(); }
		);
	});
}


/*	Set Viewport
------------------------------*/
function setViewport(){
	_widthVP = $contents.width();
	for(var i=0; i<_panelList.length; i++){
		_panelPosList[i] = _widthVP * i * -1;
		_panelList[i].css('left', _widthVP * i);
	}
	$mpPanelArea.css('left', _panelPosList[_currentPanel]);
}


/*	Get Panel Contents Html
------------------------------*/
function getContentsHTML(htmlString){
	var _html = htmlString.match(/<!-- #CONTENTS-START# -->([\s\S]*)<!-- #CONTENTS-END# -->/i);
	return RegExp.$1;
}

/*	Get Section Html
------------------------------*/
function getSectionHTML(htmlString){
	var _html = htmlString.match(/<!-- #SECTION-START# -->([\s\S]*)<!-- #SECTION-END# -->/i);
	return RegExp.$1;
}

/*	Ajax Html Body parse
------------------------------*/
function parseBodyElem(htmlString){
	var _obj = {};
	var _bodyLine = htmlString.match(/<body[^>]+>/i)[0].slice(1, -1);
	_bodyArray = _bodyLine.split(' ');
	_bodyArray.shift();
	$.each(_bodyArray, function(index, item){
		var _item = _bodyArray[index].split('=');
		if(_item.length == 2){
			_obj[$.trim(_item[0])] = $.trim(_item[1].slice(1, -1));
		}
	});
	return _obj
}

/*	Change Body Elem
------------------------------*/
function changeBodyElem(panelNum){
	if(panelNum != -1){
		document.body.id = _panelBodyObjList[panelNum]['id'] || '';
		document.body.className = _panelBodyObjList[panelNum]['class'] || '';
	} else {
		document.body.id = '';
		document.body.className = '';
	}
}

/*	Change Hash Address
------------------------------*/
function changeHashAddress(panelNum, url){
	if(panelNum == 0){
		location.hash = '';
	} else {
		location.hash = url + '?p=' + panelNum;
	}
}


/*	Add CSS Rule
------------------------------*/
function addCssRule(stylesheet, selector, property) {
	if(stylesheet.insertRule) {
		stylesheet.insertRule(selector + '{' + property + '}', stylesheet.cssRules.length);
	} else if(stylesheet.addRule){
		stylesheet.addRule(selector, '{' + property + '}');
	}
}

})(jQuery);


/*	CancelTabKey
------------------------------*/
function cancelTabKey(e){
	if(getkeyCode(e) == 9){
		e.preventDefault();
	}
}
function getkeyCode(e){
	if(document.all){
		return e.keyCode;
	} else if(document.getElementById) {
		return (e.keyCode)? e.keyCode: e.charCode;
	} else if(document.layers) {
		return e.which;
	}
} 
/*------------------------------------------------------------
	Open Ajax Layer
------------------------------------------------------------*/
function openAjaxLayer(url){
	$.colorbox({ opacity : 0.5, close :'<img width="33" height="33" src="img/shared/btn_close_01.gif" alt="Close" />', iframe : true, href : url, innerWidth :963 ,innerHeight : 520 });
}

/*------------------------------------------------------------
	Open 360&deg; Panorama Layer
------------------------------------------------------------*/
function open360degreeLayer(url){
	var panoramaLayer = new panorama360Layer();
	panoramaLayer.open(url);
}

function panorama360Layer(){
	this.init(arguments[0]);
}
panorama360Layer.prototype.init = function(_setting){
	this.setting = _setting;
	this.isMoving = false;
	this.postion = 0;
	this.fps = 1000 / 60;
	this.className = "panorama360Layer";
	this.id = this.className + (new Date()).getTime();
	
	// Layer
	this.layer = document.createElement("div");
	this.layer.id = this.id;
	this.layer.className = this.className;
	this.$layer = $(this.layer).css({ opacity : 0 });
	
	// Layer Inner
	this.layerInner = document.createElement("div");
	this.layerInner.className = "layerInner";
	this.$layerInner = $(this.layerInner);
	this.layer.appendChild(this.layerInner);
	
	// Layer Objects
	var _code = "";
	_code += "<div class='panorama360Logo'><span class='pngImg'>360&deg; PANORAMA</span></div>"
	_code += "<div class='panorama360Close'><span class='pngImg'>Close</span></div>"
	_code += "<div class='panorama360Left'><span class='pngImg'>to Left</span></div>"
	_code += "<div class='panorama360Right'><span class='pngImg'>to Right</span></div>"
	this.layerInner.innerHTML = _code;
	
	// Layer Image
	this.layerImage = document.createElement("div");
	this.layerImage.className = "layerImage";
	this.layerInner.appendChild(this.layerImage);
	
	// Event Asign
	this.setEvents();
}
panorama360Layer.prototype.setEvents = function(){
	var _self = this;
	this.$layer.find(".panorama360Close").click(function(e){
		_self.close();
	});
	this.$layer.find(".panorama360Left").hover(
		function(e){
			_self.startLeft();
		},
		function(e){
			_self.stopLeft();
		}
	);
	this.$layer.find(".panorama360Right").hover(
		function(e){
			_self.startRight();
		},
		function(e){
			_self.stopRight();
		}
	);
	$(window).resize(function(){
		_self.adjustHeight();
	});

};
panorama360Layer.prototype.adjustHeight = function(){
	var _height;
	var _clientHeight = document.documentElement.clientHeight || document.body.clientHeight || window.innerHeight;
	if(_clientHeight > this.$layerInnerMaxHeight) {
		this.$layer.height("100%");
		_height = this.$layerInnerMaxHeight;
	} else {
		this.$layer.height(_clientHeight);
		_height = _clientHeight;
		
	}	
	this.$layerInner.height(_height);
	this.layerInner.style.marginTop = _height / 2 * -1 + "px";
	
};
panorama360Layer.prototype.open = function(_url){
	var _self = this;
	var _img = new Image();
	_img.onload = function(){
		_self.imgWidth = _img.width;
		_self.imgHeight = _img.height;
		_self.postion = _img.width * -1;
		_self.layerImage.style.left = _self.postion + "px";
		_self.layerImage.style.height = _self.imgHeight + "px";
		_self.layerImage.style.marginTop = _self.imgHeight / 2 * -1 + "px";
		_self.layerImage.style.width = _self.imgWidth * 3 + "px";
		_self.layerImage.style.background = "url(" + _img.src + ") repeat-x";
		_self.layerImage.style.display = "block";
	};
	_img.src = _url + "?nocache=" + (new Date()).getTime();
	document.body.appendChild(this.layer);
	this.$layerInnerMaxHeight = this.$layerInner.height();
	this.adjustHeight();
	/* png fix for IE6 */
	if(!!window.DD_belatedPNG){
		$('.pngImg', this.$layer).each(function(){
			window.DD_belatedPNG.fixPng(this);
		});
	}
	this.$layer.addClass("isStop");
	this.$layer.animate({ opacity : 1 }, 250, function(){
		this.style.filter = "";
		this.style.opacity = "";
	});
}
panorama360Layer.prototype.close = function(){
	var _self = this;
	this.$layer.animate({ opacity : 0 }, 250, function(){
		_self.$layer.remove();
		_self = null;
	});
}
panorama360Layer.prototype.startLeft = function(){
	var _self = this;
	this.isMoving = true;
	this.timer = setInterval(function(){
		_self.postion += 4;
		if(_self.postion + (_self.imgWidth - _self.$layerInner.width()) >= 0){
			_self.postion = _self.postion - _self.imgWidth;
		}
		_self.layerImage.style.left = _self.postion + "px"; 
	}, this.fps);

}
panorama360Layer.prototype.stopLeft = function(){
	clearTimeout(this.timer);
	this.isMoving = false;
}
panorama360Layer.prototype.startRight = function(){
	var _self = this;
	this.isMoving = true;
	this.timer = setInterval(function(){
		_self.postion -= 4;
		if(_self.postion + _self.imgWidth * 2 <= 0){
			_self.postion = _self.postion + _self.imgWidth;
		}
		_self.layerImage.style.left = _self.postion + "px"; 
	}, this.fps);
}
panorama360Layer.prototype.stopRight = function(){
	clearTimeout(this.timer);
	this.isMoving = false;
}
