/**
 * common.js
 * @description	全ページ共通JS
 * @update		12.02.02
 * @author		utix
 * @version 	1.0
 * @link		http://www.utix.co.jp/
 * 
 */

var pageMain, navi;
(function($, window, undefined) {
//------------------------------------------------------------
// PAGE MAIN CLASS
//------------------------------------------------------------
	$.PageMain = function(){
		this.searchText = 'Search...';
		this.searchFocusBG = '#EEE';
		this.facebookCYR = '<iframe src="//www.facebook.com/plugins/likebox.php?locale=en_US&href=http%3A%2F%2Fwww.facebook.com%2Fcybird.recruiting.jp&amp;width=187&amp;height=330&amp;colorscheme=light&amp;show_faces=true&amp;border_color=%23FFF&amp;stream=false&amp;header=false&amp;appId=228166370543875" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:187px; height:306px;" allowTransparency="true"></iframe>';
		this.facebookCY = '<iframe src="//www.facebook.com/plugins/likebox.php?locale=en_US&href=http%3A%2F%2Fwww.facebook.com%2Fcybird.co.jp&amp;width=187&amp;height=330&amp;colorscheme=light&amp;show_faces=true&amp;border_color=%23FFF&amp;stream=false&amp;header=false&amp;appId=228166370543875" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:187px; height:293px;" allowTransparency="true"></iframe>';
		this.uri = {};
	};
	$.PageMain.prototype = {
	
	//------------------------------
	// ページ初期化
	//------------------------------
		initialize:function(){
			//loader アニメーション
			var frameList = [], i, self = this;
			for(i =0; i<48; i++){ frameList[i] = '-'+i*80+'px 0px'; };
			$('#loader span').set({opacity:0}).to(200, {opacity:1, delay:1000, onComplete:function(){
				$('#loader span').to(2000, {frame:'24', frameList:frameList, repeat:999});
			}});
			if(SimpleUI.browser.lteIE7) $('#loading span').fixPng();
			
			//現在位置指定
			this.uri = this.getURI(location.href)
        	var pathname = this.uri.pathname, mainCategory = '/'+pathname.split('/')[1]+'/';
			mainCategory = mainCategory.replace('index.html', '');
			this.uri.pathname = pathname = pathname.replace('index.html', '');
			if(mainCategory == '//'){
				$('#gnHome a').addClass('current');
			}else if(mainCategory == '/investor/'){
				$('#gnCompany a').addClass('current');
				$('#categoryNav li a:eq(5)').addClass('current');
			}else if(mainCategory != '//' && mainCategory != 'investor'){
				$('#globalNav li a[href$="'+mainCategory+'"]').addClass('current');
				$('#categoryNav li a[href$="'+pathname +'"]').addClass('current');
			};
			this.initalizeNav();
			if($('body').prop('id') != 'home') $('#pageContainer').append('<div id="pageCover" style="width:'+$('#pageContainer').width()+'px; height:'+$('#pageContainer').height()+'px; position:absolute; top:0; left:0; background:#FFF;"></div>');
		},
	
	//------------------------------
	// ナビゲーション初期化
	//------------------------------
		initalizeNav:function(){
			
			//ナビゲーション
			$('#globalNav a, #categoryNav a').each(function(i, val){
				if($(this).prop('target') != '_blank' && this.href.indexOf(location.href) == -1){
					$(this).click(function(e){ pageMain.linkTo(this.href); return false; });
				};
			});
			if(this.uri.pathname == '/service/'){
				$('#categoryNav .cn-mobile a').click(function(e){ pageMain.pageTo(this.hash); return false; });
			};
			
			//ページ内リンク
			$('#page a[href^=#]').click(function(e){ pageMain.pageTo(this.hash); return false; });
			$('.pageTop a').click(function(e){ pageMain.pageTo(this.hash); return false; });
			
			//ポップアップ
			$('.popup').click(function(){ var win = window.open(this.href, "popup", (this.rel)? this.rel : '').focus(); return false; });
			
			//検索フォーム
			$('#subNav input').val(pageMain.searchText).css({color:'#999'})
				.focus(function(){
					if(this.value == pageMain.searchText) $(this).val('');
					$(this).to(200, {color:'#000', backgroundColor:pageMain.searchFocusBG, 
						 	borderTopColor:pageMain.searchFocusBG,borderBottomColor:pageMain.searchFocusBG,borderLeftColor:pageMain.searchFocusBG,borderRightColor:pageMain.searchFocusBG }
					);
					$('#searchInput').set({backgroundColor:'#FFF'})
					$('#searchInput').to(200, {width:'300px', backgroundColor:pageMain.searchFocusBG});
				})
				.blur(function(){
					$(this).to(200, {backgroundColor:'#FFF', borderTopColor:'#FFF', borderBottomColor:'#FFF', borderLeftColor:'#FFF', borderRightColor:'#FFF'});
					$('#searchInput').to(200, {width:'180px', backgroundColor:'#FFF'});
					if(this.value == ''){
						$(this).val(pageMain.searchText).css({color:'#999'});
					};
					if(this.value != pageMain.searchText){
						$(this).css({color:'#000'});
					};
			});
		},
	
	//------------------------------
	// シェアリンク初期化
	//------------------------------
		initalizeShare:function(){
			$('body').append('<div id="share" style="visibility:hidden"></div>');
			var shareLink ="", url = document.URL.toString(), title = document.title, count = false, countStr;
			/*
			$('meta[ property="og:url"]').prop('content', url);
			$('meta[ property="og:title"]').prop('content', title);
			*/
			shareLink += '<div><ul>';
			countStr = (count)? '450px' : '71px';
			shareLink += '<li class="facebook"><span><iframe src="//www.facebook.com/plugins/like.php?href=' + this.utf8Encode(url) + '&amp;send=false&amp;layout=button_count&amp;width=450&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:' + countStr + '; height:21px;" allowTransparency="true"></iframe></span></li>';
			
			countStr = (count)? 'horizontal' : 'none';
			shareLink += '<li class="twitter"><span><a href="http://twitter.com/share" class="twitter-share-button" data-url="' + url + '" data-text="' + title + '" data-count="' + countStr + '" data-lang="ja">ツイート</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></span></li>';
			countStr = (count)? 'true' : 'false';
			if(!SimpleUI.browser.lteIE7) {
				shareLink += '<li class="google"><span><scr' + 'ipt src="http://apis.google.com/js/plusone.js">{lang: \'ja\'}</scr' + 'ipt><div class="g-plusone" data-size="medium" data-count="' + countStr + '" data-href="' + url + '"></div></span></li>';
			}
			shareLink += '</div></ul>';
			//$(window).load(function(){});
			$('#share').append(shareLink);
			
			var shareBtn = $('#share div');
			var sharePoint = -85;
			if(!SimpleUI.browser.touch){
				$('#share').bind('mouseover', function(){
					shareBtn.css({height:'140px'});
					shareBtn.to(1000, {right:'0px', ease:Motion.easing.easeOutQuint});
				}).bind('mouseout', function(){
					shareBtn.to(400, {right:sharePoint +'px', delay:500});
				})
			}else{
				$('#shareBtn').bind('click', function(){
					shareBtn.css({height:'140px'});
					if(shareBtn.css('right') != '0px'){
						shareBtn.to(200, {right:'0px', ease:Motion.easing.easeOutQuint});
					}else{
						shareBtn.to(200, {right:sharePoint +'px'});
					}
				})
			};
			$('#share div').css({height:'0px'}).to(400, {height:'140px',  ease:Motion.easing.easeOutSine});
			$('#share').css({visibility:'visible'});
			shareBtn.css({right:sharePoint +'px'});
			if(SimpleUI.browser.lteIE7) SimpleUI('#share').iePosFix({top:'120px', right:(SimpleUI.browser.lteIE6)? '-25px' : '0px'});
		},
	
	//------------------------------
	// ロード完了
	//------------------------------
		onLoad:function(){
			if(SimpleUI.browser.lteIE7) $('#loading span').fixPng();
			//ローダ
			$('#loader span').to(100, {opacity:0});
			$('#loader').to(200, {opacity:0, delay:100, onComplete:function(){ $('#loader').css({height:'1px'}); }});
			if(document.URL.toString().indexOf('cybird') != -1 && $('body').prop('id') != 'contact' && $('body').prop('id') != 'search' && $('body').prop('id') != 'other') setTimeout(function(){pageMain.initalizeShare();}, 1800);
			setTimeout(function(){ window.scrollTo(0,0); }, 100);
			setTimeout(function(){ window.scrollTo(0,0); }, 400);
			var hash = window.location.hash;
			if(/#/i.test(hash)) {
				setTimeout(function(){window.scrollTo(0,0); pageMain.pageTo(hash);}, 1000);
			};
			this.pageStart();
		},
	
	//------------------------------
	// ページ表示開始
	//------------------------------
		pageStart:function(){
			
			if($('body').prop('id') == 'home'){
				//ソーシャル関連
				$('#facebookCYR').append(this.facebookCYR);
				$('#facebookCY').append(this.facebookCY);
				
				//MAIN AREA
				new $.slideContents();
				
			}else if($('body').prop('id') != 'home' && $('#categoryTitle').length == 1){
				//ホーム以外 ヘッダ有り
				var titileW = $('#categoryTitle h1').width()+'px',
					pageW = $('#pageContainer').width()+'px',
					pageH = $('#pageContainer').height()+'px';
				$('#categoryTitle h1').set({width:'0px'});
				$('#categoryTitle h1').setTo(300, {width:'0px'}, {width:titileW, ease:Motion.easing.easeOutQuart, delay:500});
				$('#categoryTitlePlus')
					.set({opacity:0})
					.to(500, {opacity:1, delay:1000, ease:Motion.easing.easeOutSine});
				$('#pageCover').height(pageH);
				$('#pageCover').to(500, {opacity:0, delay:1000, onComplete:function(){
					$('#pageCover')[0].parentNode.removeChild($('#pageCover')[0]);
					$('#pageCover').remove();
				}});
			}else{
				$('#pageCover').height(pageH);
				//ホーム以外 ヘッダ無し
				$('#pageCover').to(200, {opacity:0, onComplete:function(){
					$('#pageCover')[0].parentNode.removeChild($('#pageCover')[0]);
					$('#pageCover').remove();
				}});
			};
			$('#main, #contents').css({visibility:'visible'});
		},
	
	
	//------------------------------
	// サイト内リンク
	//------------------------------
		linkTo:function(url){
			$('#loader').css({height:'100%'}).to(300, {opacity:1, delay:100, onComplete:function(){location.href = url; }});
		},
	
	
	//------------------------------
	// サイト内リンク
	//------------------------------
		pageTo:function(hash){
			if(!$(hash) || hash == '') return false;
			var currentY = document.documentElement.scrollTop || document.body.scrollTop,
				targetY = $(hash).offset().top,
				maxY =  $(document).height() - $(window).height(), dist;
			if(targetY > maxY) targetY = maxY;
			dist = parseInt((currentY - targetY)*.005 +500, 10);
			dist = (dist < 0)? -dist : dist;
			$(window).to(dist, {scrollTop:targetY+'px', ease:Motion.easing.easeInOutCubic, onComplete:function(){
				window.location.hash = (hash != '#pageTop')? hash : '';
			}});
		},
	
	
	//------------------------------
	// URL解析
	//------------------------------
		getURI:function(url){
			var matches = /^(((([^:\/#\?]+:)?(?:\/\/((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?]+)(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/.exec(url);
			var components = /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/.exec(url);
			// RFC3986
			// http://www.studyinghttp.net/cgi-bin/rfc.cgi?3986
			// directory
			// hrefNoHash
			// directory
			if(matches) {
				results = {
					href: matches[0] || "",
					hrefNoHash: matches[1] || "",
					hrefNoSearch: matches[2] || "",
					domain: matches[3] || "",
					protocol: matches[4] || "",
					authority: matches[5] || "",
					username: matches[7] || "",
					password: matches[8] || "",
					host: matches[9] || "",
					hostname: matches[10] || "",
					port: matches[11] || "",
					pathname: matches[12] || "",
					directory: matches[13] || "",
					filename: matches[14] || "",
					search: matches[15] || "",
					hash: matches[16] || ""
				};
			}
			return results;
		},
	
	
	//------------------------------
	// UTF8エンコード
	//------------------------------
		utf8Encode:function(str){
			str = str.replace(/\r\n/g,"\n");
			var result = "", i, len = str.length, current;
			for (i = 0; i < len; i++) {  
				current = str.charCodeAt(i);
				if (current < 128) {
					result += String.fromCharCode(current);
				} else if((current > 127) && (current < 2048)) {
					result += String.fromCharCode((current >> 6) | 192);
					result += String.fromCharCode((current & 63) | 128);
				} else {
					result += String.fromCharCode((current >> 12) | 224);
					result += String.fromCharCode(((current >> 6) & 63) | 128);
					result += String.fromCharCode((current & 63) | 128);
				}
			}
			return escape(result);  
		}
	};
	
//------------------------------------------------------------
// SLIDE CONTENTS CLASS
//------------------------------------------------------------
	var slideOption = {
		selector		 : '.slide',
		currentClass	 : 'current',
		navSelector		 : '.slideNav a',
		nextSelector		 : '.next',
		prevSelector		 : '.prev'
	};
	$.slideContents = function(elem, param){
		this.slide;
		this.nav;
		this.option = slideOption;
		this.contentsList = [ ];
		this.currentNum;
		this.timer;
		var option = slideOption;
		if(!elem) elem = slideOption.selector;
		if(param) option = $.extend({}, option, param || {});
		this.initialize(elem, option);
	};
	$.slideContents.prototype = {
		
		initialize:function(elem, option){
			var self = this;
			this.slide = $(elem);
			this.nav = this.slide.find(option.navSelector);
			this.nav.each(function(i, val){
				$(this.hash).set({opacity:0});
				self.contentsList.push([this.hash, $(this).get(0)]);
				$(this).click(function(){
					self.onChange(this.hash);
					return false;
				});
			});
			this.slide.append('<a href="#" class="next"><span></span></a><a href="#" class="prev"><span></span></a>');
			this.slide.find(option.nextSelector).click(function(){
				self.onNext();
				return false;
			}).find('span').set({opacity:0});
			this.slide.find(option.prevSelector).click(function(){
				self.onPrev();
				return false;
			}).find('span').set({opacity:0});
			this.slide.find(option.nextSelector+','+option.prevSelector).hover(
				function(){$(this).find('span').to(200, {opacity:1});},
				function(){$(this).find('span').to(200, {opacity:0});}
			);
			this.onChange(this.contentsList[0][0]);
		},
		
		onChange:function(hash){
			var i , len = this.contentsList.length, target, nav, h1, p, h1W, pW;
			for(i = 0; i<len; i++){
				target = $(this.contentsList[i][0]);
				nav = $(this.contentsList[i][1]);
				if(hash == this.contentsList[i][0]){
					target.to(700, {opacity:1}).css({zIndex:20});
					nav.addClass(this.option.currentClass);
					nav.css({backgroundPosition:'0 -30px'});
					this.currentNum = i;
				}else if(nav.hasClass(this.option.currentClass)){
					target.to(500, {opacity:0}).css({zIndex:1});
					nav.removeClass(this.option.currentClass);
					nav.css({backgroundPosition:'0 0'});
				};
			};
			this.onTimerStart();
		},
		
		onNext:function(){
			if(this.currentNum != this.contentsList.length-1){
				this.onChange(this.contentsList[this.currentNum+1][0]);
			}else{
				this.onChange(this.contentsList[0][0]);
			};
		},
		
		onPrev:function(){
			if(this.currentNum != 0){
				this.onChange(this.contentsList[this.currentNum-1][0]);
			}else{
				this.onChange(this.contentsList[this.contentsList.length-1][0]);
			};
		},
		
		onTimerStart:function(){
			var self = this;
			clearTimeout(this.timer);
			this.timer = setTimeout(function(){self.onNext()}, 4000);
		}
	};
	
	
//------------------------------------------------------------
// REGISTER
//------------------------------------------------------------
	pageMain = new $.PageMain();
	$(function() {
		$('#main, #contents').css({visibility:'hidden'});
		pageMain.initialize();
	});
	$(window).load(function(){
		pageMain.onLoad();
	});
	$(window).unload(function() {
		$('#main, #contents').css({visibility:'visible'});
		$('#main, #contents').set({opacity:1});
	});
	
})(jQuery, window);
try { document.execCommand('BackgroundImageCache', false, true); }catch(e){};
