﻿/* /////////////////////////////////////////
	common.js -Common Settings
	Copyright (C) 2011 Japan Port Contents.
   ///////////////////////////////////////// */

var currentAnchor = null,
	section = null,//ページ判定
	cat = null,//cat画面判定
	hasCat = false,//既にcat用画面を開いているか
	url = location.href.replace(/\\/g,'/').replace( /.*\//, '' ),//ファイル名以降のみ抜き出す
	//初期キャッシュ
	contents = $("#contents"),
	loader = $("#loader"),
	main = $("#main"),
	aside = $("#aside"),
	maxW = 1280,//最大横幅
	asideW = aside.width(),
	queryMain = null,//メインクエリ
	querySub = null,//サブクエリ
	domain = 'http://www.japan-port.com/',
	_ua = (function(){
		return {
			ltIE6:typeof window.addEventListener == "undefined" && typeof document.documentElement.style.maxHeight == "undefined",
			ltIE7:typeof window.addEventListener == "undefined" && typeof document.querySelectorAll == "undefined",
			ltIE8:typeof window.addEventListener == "undefined" && typeof document.getElementsByClassName == "undefined",
			mobile:/android|iphone|ipad|ipod/i.test(navigator.userAgent.toLowerCase())
		}
	})();

//URL判定、ハッシュ追加
function defineHash() {
	if (url.indexOf("#") == -1) {
		if (url.length < 1) {
			document.location.hash = "index";// "japan-port.com/"の場合=>indexとみなす
		} else {
			document.location.hash = url.split(".")[0];//ファイル名だけ=>ファイル名を#後に付ける
		}
	} else if (url == "#") {
		document.location.hash = "index";//#だけ=>indexとみなす
	}
}
defineHash();
function defineSection() {
	url = location.href.replace(/\\/g,'/').replace( /.*\//, '' );//ex) index.php#main&id=2
	section = url.split("#")[1];//ex) main&id=2
	section2 = section.split("&")[1];//ex) &id=2
	section = section.split("&")[0];//ex) main
	if (section2) {
		hasCat = true;//すでにcat画面を見ている
	} else {
		hasCat = false;//まだcat画面を見ていない
	}
}
//index表示：delay()はズレが生じるため使用しない
function showIndex() {
	$("#siteLogo").fadeTo(300, 1, function(){
		main.fadeTo(400, 1, function(){
			$("#billboard").fadeIn(600, function(){
				$("#hgroup").animate( {
					left : "0",
					opacity: 1
				}, 400, 'easeOutExpo' );
			});
		});
	});
}
function showOther() {
	if (section=="news" || section=="sitemap" || section=="company" || section=="staff") {
		contents.css("margin-left","0").fadeTo(400, 1);
		loader.css("display","none");
	} else {
		contents.animate( {
			marginLeft : "0",
			opacity: 1
		}, 500, 'easeOutExpo' );
	}
}
function checkAnchor() {
	defineSection();
	defineHash();
	if (section=="index"){
		asideW = 448;
	} else {
		asideW = 300;
	}
	if (currentAnchor != document.location.hash) {//ハッシュが変わった時だけ実行
		currentAnchor = document.location.hash;
		if (!currentAnchor) {
			queryMain = "section=index";
		} else {
			var splits = currentAnchor.substring(1).split('&');
			var currentSection = splits[0];
			delete splits[0];
			queryMain = "section=" + currentSection;// + params;
			if (splits[1]) {//&cat=1など、&以降に文字が入っていたら
				var splits2 = splits[1].split('=');
				cat = splits2[1];//ex) 1
				delete splits2[0];
				querySub = "cat=" + cat;
			} else {
				querySub = null;//初期化
			}
		}
		//読み込み時サイドバーアニメーション
		if ($(window).width() > maxW) {
			var w = $(window).width()-(maxW-asideW);//maxWを超えた場合はその位置を取得してwに代入
			aside.animate( {width: w}, 300, 'easeOutExpo' );
			main.css("marginRight",w);
		} else {
			aside.animate( {width: asideW}, 300, 'easeOutExpo' );//サイドバーをアニメーションする
		}
		if (!querySub) {
			$.get("responder_main.php",queryMain, function(data) {
				if (data==false) {
					location.href = 'index.php#index';//ハッシュ以降が不正な値ならtopに戻る
				} else {
					contents.html(data);//htmlを入れる
					loader.fadeOut("100", function(){//loaderを消した後、callbackでコンテンツを出現させる
						if (section=="index") {
							loader.css("display","none");//完全に消す
							$("#billboard").css("display","none").find("#hgroup").fadeTo("fast", 0).css("left","-700px");
							showIndex();
						} else {
							main.css("display","block");
						}
						showOther();
						//再キャッシュ
						contents = $("#contents"),
						loader = $("#loader"),
						main = $("#main"),
						aside = $("#aside");
					});
				}
				//1アクセスしたとみなす
				pageTracker._trackPageview('/' + section + '.php');
			});
		} else if (querySub) {
			$.get("responder_sub.php",querySub, function(data) {
				if (data==false) {
					location.href = 'index.php#index';//ハッシュ以降が不正な値ならtopに戻る
				} else {
					contents.html(data);//htmlを入れる
					loader.fadeOut("100", function(){//loaderを消した後、callbackでコンテンツを出現させる
						main.css("display","block");
						contents.css("margin-left","0").fadeTo(400, 1);
						loader.css("display","none");
						//再キャッシュ
						contents = $("#contents"),
						loader = $("#loader"),
						main = $("#main"),
						aside = $("#aside");
					});
				}
				//1アクセスしたとみなす
				pageTracker._trackPageview('/' + section + '.php?' + querySub);
			});
		} else {
			location.href = 'index.php#index';//不正な値ならtopに戻る
		}
		if (section!="") $("body").attr("id", section);//bodyへIDを入れる
	}
}
function switchContents(tg, tg2, move, land) {
	if (!tg2) {
		$("#glovalNav").find("a").removeClass("current").css("background-color", "");
		$("#nav"+tg).find("a").addClass("current");
		function setHash(){
			loader.show();
			document.location.hash = tg;
		}
		if (section=="news" || section=="sitemap" || section=="company" || section=="staff") {
			if (tg=="news" || tg=="sitemap" || tg=="company" || tg=="staff") {
				contents.fadeTo(400, 0, function(){
					setHash();
				});
			} else {
				contents.fadeTo(400, 0, function(){
					if (!_ua.ltIE6) $(this).css("margin-left","1000px");
					setHash();
					if (tg=="index"){
						main.css("display","none");
						$("#siteLogo").fadeTo("fast", 0);
					} else {
						main.css("display","block");
						if (tg=="contact") {
							location.href = "https://server29.instantssl.co.jp/~ja18238/contact.php";
						}
					}
				});
			}
		} else {
			if (!hasCat) {
				contents.animate( {
					marginLeft : "1000",
					opacity: 0
					}, 800, 'easeInOutExpo',function() {
						if (tg=="contact") {
							location.href = "https://server29.instantssl.co.jp/~ja18238/contact.php";
							return false;
						} else if (tg=="index"){
							main.css("display","none");
							$("#siteLogo").fadeTo("fast", 0);
						} else {
							main.css("display","block");
						}
						loader.show();
						document.location.hash = tg;
					}
				);
			} else {
				contents.fadeTo(400, 0, function() {
						if (tg=="contact") {
							location.href = "https://server29.instantssl.co.jp/~ja18238/contact.php";
							return false;
						} else if (tg=="index"){
							main.css("display","none");
							$("#siteLogo").fadeTo("fast", 0);
						} else {
							main.css("display","block");
						}
						loader.show();
						document.location.hash = tg;
					}
				);
			}
		}
	} else if(tg2) {//さらに切り替え要素があった場合
		if (!hasCat) {//初めてcategory内を表示する時
			if (move == 'fade') {//既存のコンテンツをフェードで消して移動
				contents.fadeTo(400, 0, function(){
					loader.show();
					document.location.hash = tg + '&cat=' + tg2;
				});
			} else if (move == 'slide') {//既存のコンテンツをスライドで消して移動
				contents.animate( {
					marginLeft : "1000",
					opacity: 0
					}, 800, 'easeInOutExpo', function(){
						loader.show();
						document.location.hash = tg + '&cat=' + tg2;
					});
			}
		} else if(hasCat && section=='staff') {
			$("#member"+cat).fadeTo(300, 0, function(){
				loader.show();
				document.location.hash = tg + '&cat=' + tg2;
			});
		} else if(hasCat && section=='business') {
			contents.fadeTo(300, 0, function(){
				loader.show();
				document.location.hash = tg + '&cat=' + tg2;
			});
		}
	} else {
		return false;
	}
}
//#asideの横幅を合わせる
function adjustWMax(tgEle) {
	var w = $(window).width()-(maxW-asideW);
	$(tgEle).css("width",w);
	main.css("marginRight",w);
}
$(function(){
	//TOPレイアウトのチラつき防止
	$("body").attr("id","");
	$("#contents").css("display","none");

	// 必ず"ドメイン名/#～"になるようにする。ハッシュフラグメント(#!)は使用しない。
	if ( location.href != domain ) {
		var landedURL = location.href.replace(/\\/g,'/').replace( /.*\//, '' );//ex) index.php#main&id=2
		var fileName = landedURL.split("#")[0];//ex) index.php
		var section = landedURL.split("#")[1];//ex) main&id=2
		if (fileName) {
			location.href = domain + '#' + section;//ex) domain/#main&id=2
			return false;
		}
	}

	//再キャッシュ
	contents = $("#contents"),
	loader = $("#loader"),
	main = $("#main"),
	defineSection();//section定義
	if (_ua.ltIE7) $("#officeMapExp").append('<p><img src="images/common/img_map_speech-bubble.gif" id="speechBubble" alt=""></p>');

	//ページ読み込み時
	if (section=="index"){
		asideW = 448;
		main.css("display","none");
		$("#siteLogo").fadeTo("fast", 0);
		$("#contents").css("display","block");
		$("#main").fadeTo("fast", 0);
	} else if (section=="news" || section=="sitemap" || section=="company" || section=="staff") {
		contents.fadeTo("fast", 0).css("margin-left","0");
		asideW = 300;
	} else {
		asideW = 300;
		if (!_ua.ltIE6) contents.fadeTo("fast", 0).css("margin-left","1000px");
	}

	if ($(window).width() > maxW) {
		adjustWMax("#aside");
	}

	//リサイズ時
	$(window).resize(function() {
		if ($(window).width() > maxW) {
			adjustWMax("#aside");//横幅を出た時だけ実行
		} else {
			//定義横幅内の時はデフォルトCSSの定義に従う
			aside.css("width","");
			main.css("marginRight","");
		}
	});

	//mouseover fading effects
	if (!_ua.ltIE6) {
		$("#glovalNav").find("a:not(.current)").live({
			mouseenter:
				function(){
					$(this).animate({backgroundColor: '#e40077'}, 180);
				},
			mouseleave:
				function(){
					$(this).animate({backgroundColor: '#292a33'}, 180);
				}
			}
		);
	}

	// Copyright (c) 2008 George McGinley Smith All rights reserved.
	// Open source under the BSD License. 
	$.easing.easeOutExpo = function (x, t, b, c, d) {
			return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	};
	$.easing.easeInOutExpo = function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	};

	// ページTOPに戻る
	$("#pageTop").live('click', function() { $('html,body').animate({ scrollTop: 0 }, 600, 'easeOutExpo'); });

	// checkAnchor実行
	setInterval("checkAnchor()", 600);

	/* jQuery Color Animations Copyright 2007 John Resig, Released under the MIT and GPL licenses. */
	// We override the animation for all of these color styles
	
	$.each(['backgroundColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}
			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/
	function getRGB(color) {
		var result;
		if ( color && color.constructor == Array && color.length == 3 )
			return color;
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
		return colors[jQuery.trim(color).toLowerCase()];
	}
	function getColor(elem, attr) {
		var color;
		do {
			color = jQuery.curCSS(elem, attr);
			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 
			attr = "backgroundColor";
		} while ( elem = elem.parentNode );
		return getRGB(color);
	};
});

//onload時に実行
$.event.add(window, "load", function(){
	defineSection();
	$("#glovalNav").find("a").removeClass("current").css("background-color", "");
	$("#nav"+section).find("a").addClass("current");
});


