/* -------------------------------------------------

global.js v1.4
Script writen by KEI TSUZURAHARA.
Created: 1 Aug 2007
Last modified: 11 Dec 2007

**対象ブラウザ**
Win: IE6.x / IE7.x / Firefox2.x / Opera9.x / Netscape7.x
Mac: Firefox2.x / Safari2.x / Opera9.x / Netscape7.x

**バージョン遍歴**
v1.4 - 11 Dec 2007
・ページスクロールの最大幅での動きを修正

v1.3 - 29 Nov 2007
・カテゴリの選択にるセレクトボックスの同期を改修
・商品比較ページのチェックボックスの選択を追加

v1.2 - 4 Nov 2007
・ページスクロールを改良（ページ内アンカーを自動スクロール）

v1.1 - 17 Oct 2007
・ページスクロールを追加
・リセットボタンの初期化処理を追加
・カテゴリのリストをjson化

v1.0 - 2 Oct 2007
・ナビゲーションのアニメーションを改良
・マウスオーバーのイベントをJSで割当

v0.1 - 1 Aug 2007
・プロトタイプ作成

------------------------------------------------- */

/*@cc_on _d=document;eval('var document=_d')@*/

var motion = false;
var gNaviOn = false;
var lNaviOn = false;
var intervalID = null;

// HTMLロード後に実行する初期化コード
$(function(){
	
	//IE6で疑似クラスhoverを有効
	if (getBrowser() == "ie") {
		$("button").hover(
			function(){
				var xpos = $(this).css("background-position-x");
				$(this).css({"background-position":xpos +" 100%", "cursor":"pointer"});
			},
			function(){
				var xpos = $(this).css("background-position-x");
				$(this).css({"background-position":xpos + " 0", "cursor":"default"});
			}
		);
	}

	//アンカースクロール
	$('a[@href^="#"]').click(
		function(e){
			var id = getAnchor($(this).attr("href"));
			if(document.getElementById(id)){
				var pos = $("#"+id).offset();
				scrollPage.cancel(e);
				scrollPage.setScroll(pos.top);
			}
		}
	);
	
	var url = window.location.href;
	
	//直リンクのアンカースクロール
	/*
	if(url.indexOf("#") != -1){
		var id = getAnchor(url);
		if(document.getElementById(id)){
			var pos = $("#"+id).offset();
			scrollPage.cancel(e);
			window.scrollTo(0, 0);
			scrollPage.setScroll(pos.top);
		}
	}
	*/

	//シューズ検索オプションの開閉設定
	if(url.indexOf("/product/") == -1){
		$("#shoesoption").hide();
	} else if(url.indexOf("/product/") != -1){
		if(document.getElementById("brandlist") || document.getElementById("typelist")){
			$("#shoesoption").hide();
		}
	}
	
	//ブランド選択、タイプ選択プルダウンの出し分け
	var cat = $("input[@name=category_cd]").val();
	if(cat == "m"){
		cat = "mens";
	} else if(cat == "w"){
		cat = "womens";
	} else if(cat == "k") {
		cat = "kids";
	}
	checkCategory(cat);

	//シューズ検索オプションボタンのイベント
	$("#shoesoption_open a").click(function(){
		slideToggle('shoesoption');
	});

	//ブックマークボタンのイベント
	$("#bookmark a").click(
		function(e){
			scrollPage.cancel(e);
			bookmark(this.id);
		}
	);
	
	//Safari2.0.3以下用文字化け対策
	(function(){
		// the garble control for safari (XMLHttpRequest#responseText)
		var func01 = function(text){
			var esc = escape( text );
			if( esc.indexOf("%u") < 0 && esc.indexOf("%") > -1 ){
				text = decodeURIComponent( esc );
			}
			return text;
		};
	
		// For jQuery.js
		if(window.jQuery != undefined){
			if(navigator.appVersion.indexOf("KHTML") > -1 ){ // for safari
				var _httpData=window.jQuery.httpData;
				window.jQuery.httpData=function(r, type){
					try{
						var ct = r.getResponseHeader("content-type");
						var data = !type && ct && ct.indexOf("xml") >= 0;
						data = type == "xml" || data ? r.responseXML : func01(r.responseText);
	
						// If the type is "script", eval it in global context
						if ( type == "script" )
						jQuery.globalEval( data );
	
						// Get the JavaScript object, if JSON is used.
						if ( type == "json" )
						eval( "data = " + data );
	
						// evaluate scripts within html
						if ( type == "html" )
						jQuery("<div>").html(data).evalScripts();
	
						return data;
					}catch(e){
						return _httpData.apply(this. arguments);
					}
				};
			}
	}
	})();
	
});

//ブラウザ判別
function getBrowser() {
	var ua = navigator.userAgent;
	if(ua.indexOf("Safari") > -1) return "safari";
	if(ua.indexOf("Opera") > -1) return "opera";
	if(ua.indexOf("Firefox") > -1) return "firefox";
	if(ua.indexOf("Gecko") > -1) return "mozilla";
	if(ua.indexOf("MSIE") > -1) return "ie";
	if(ua.indexOf("Mozilla") > -1) return "netscape";
}

//アンカー名取得
function getAnchor(anc) {
	var a_id = anc.split("#");
	var id = a_id[1];
	return id;
}

//レイヤーの開閉
function slideToggle(obj) {
	$("#"+obj).slideToggle(800);
}

	
//ランキング表示の切り替え
function swapRank(obj) {
	if (!motion){
		motion = true;
		if(obj == "mens"){
			$("#rank_womens").hide();
			$("#rank_kids").hide();
			$("#rank_tab").css({backgroundPosition:"0 0"});
		} else if(obj == "womens"){
			$("#rank_mens").hide();
			$("#rank_kids").hide();
			$("#rank_tab").css({backgroundPosition:"0 50%"});
		} else if(obj == "kids"){
			$("#rank_mens").hide();
			$("#rank_womens").hide();
			$("#rank_tab").css({backgroundPosition:"0 100%"});
		}
		$("#rank_"+obj+":hidden").fadeIn("slow",function(){
			motion = false;
		});
	}
}

//検索プルダウンの切り替え
function checkCategory(cat) {
	var hasBrand = false;
	var hasScene = false;
	var select_brand = $("select[@name=brand_cd]").val();
	var select_scene = $("select[@name=scene_cd]").val();
	$.getJSON("/js/json/brand_"+cat+".json",
		function(json){
			$("select[@name=brand_cd] > option").remove();
			$.each(json.feed,function(i) {
				if(this.data == select_brand){
					hasBrand = true;
				}
				$("select[@name=brand_cd]").append("<option value='" + this.data + "'>" + this.label + "</option>");
			});
			if(hasBrand){
				$("select[@name=brand_cd]").val(select_brand);
			} else {
				$("select[@name=brand_cd]").val("");
			}
		}
	);
	$.getJSON("/js/json/scene_"+cat+".json",
		function(json){
			$("select[@name=scene_cd] > option").remove();
			$.each(json.feed,function(i) {
				if(this.data == select_scene){
					hasScene = true;
				}
				$("select[@name=scene_cd]").append("<option value='" + this.data + "'>" + this.label + "</option>");
			});
			if(hasScene){
				$("select[@name=scene_cd]").val(select_scene);
			} else {
				$("select[@name=scene_cd]").val("");
			}
		}
	);
	
}

//ショップ検索ブランド選択判定
function checkShopBrand(query){
	if(query.shop_brand.value == "") {
		alert("ブランドを選択してください");
		return false;
	} else {
		return true;
	}
}

//シューズ検索フォームクリア
function resetShoesSearch(){
	$("#form_shoessearch input[type=radio]").each(function(){this.checked = false});
	$("select[@name=price_min]").val("");
	$("select[@name=price_max]").val("");
	$("select[@name=size_cd]").val("");
	$("select[@name='a_width_cd[]']").val("");
	$("select[@name='a_base_color_cd[]']").val("");
	$("select[@name='a_function_cd[]']").val("");
	$.getJSON("/js/json/brand_mens.json",
		function(json){
			$("select[@name=brand_cd] > option").remove();
			$.each(json.feed,function(i) {
				$("select[@name=brand_cd]").append("<option value='" + this.data + "'>" + this.label + "</option>");
			});
			$("select[@name=brand_cd]").val("");
		}
	);
	$.getJSON("/js/json/scene_mens.json",
		function(json){
			$("select[@name=scene_cd] > option").remove();
			$.each(json.feed,function(i) {
				$("select[@name=scene_cd]").append("<option value='" + this.data + "'>" + this.label + "</option>");
			});
			$("select[@name=scene_cd]").val("");
		}
	);
	$("#form_shoessearch input[@id=shoes_mens]").attr("checked", "checked");
}

//フォームの送信
function sendForm (obj){
	var action = $("#form_" + obj).attr("action");
	var formdata = $("#form_" + obj + " input:text, #form_" + obj + " input:hidden, #form_" + obj + " input:radio, #form_" + obj + " input:checkbox, #form_" + obj + " textarea, #form_" + obj + " select").serialize();
	$.post(action,formdata,
		function(response){
			$("#form_" + obj + " .form_body").html(response).css({margin:"280px 0"}).css({fontSize:"1.2em"});
			$("#form_" + obj + " .btns").hide();
		}
	);
}

//ブックマーク登録
function bookmark(isp){
	var url = encodeURIComponent(window.location.href);
	var title = encodeURIComponent(document.title);
	switch(isp) {
		case "yahoo":
			var site = "http://bookmarks.yahoo.co.jp/bookmarklet/showpopup?";
			var link = site + "t=" + title + "&u=" + url + "&opener=bm&ei=UTF-8"; break;
		case "google":
			var site = "http://www.google.com/bookmarks/mark?";
			var link = site + "op=edit&bkmk=" + url + "&title=" + title; break;
		case "hatena":
			var site = "http://b.hatena.ne.jp/append?";
			var link = site + url; break;
		case "delicious":
			var site = "http://del.icio.us/post?";
			var link = site + "url=" + url + "&title=" + title; break;
		case "livedoor":
			var site = "http://clip.livedoor.com/redirect?";
			var link = site + "link=" + url + "&title=" + title; break;
		case "technorati":
			var site = "http://technorati.com/faves?";
			var link = site + "add=" + url + "&title=" + title; break;
		case "nifty":
			var site = "http://clip.nifty.com/create?";
			var link = site + "url=" + url + "&title=" + title; break;
		case "buzzurl":
			var site = "http://buzzurl.jp/config/add/confirm?";
			var link = site + "url=" + url + "&title=" + title; break;
		case "saaf":
			var site = "http://bm.saaf.jp/bm/add?";
			var link = site + "url=" + url; break;
	}
	window.open(link,'_blank');
	pageTracker._trackPageview(link);
}

//表示領域取得
function winSize(){
	var size = [];
	if(getBrowser() == "safari"){
		size.h = window.innerHeight;
		size.w = window.innerWidth;
	} else {
		size.h = document.documentElement.clientHeight || document.body.clientHeight || window.innerHeight;
		size.w = document.documentElement.clientWidth || document.body.clientWidth || window.innerWidth;
	}
	return size;
}

//スクロール
var scrollPage = {
	//スクロール位置
	yPos:function(){
		var y = document.body.scrollTop  || document.documentElement.scrollTop;
		return y;
	},
	//スクロール最大位置
	maxPos:function(){
		var docH = $(document).height();
		var winsize = winSize();
		var maxH = docH - winsize.h;
		return maxH;
	},
	//スクロール
	doScroll:function(){
		var scrollY = scrollPage.yPos();
		var toY = scrollPage.toY;
		scrollY += Math.floor((toY-scrollY)/10);
		window.scrollTo(0, scrollY);
		switch (scrollPage.mode) {
			case "up":
				if(scrollY <= toY){
					clearTimeout(scrollPage.interval);
					return false;
				} else {
					scrollPage.interval = setTimeout("scrollPage.doScroll()", 10);
				}
				break;
			case "down":
				if(scrollY >= toY-10){
					clearTimeout(scrollPage.interval);
					return false;
				} else {
					scrollPage.interval = setTimeout("scrollPage.doScroll()", 10);
				}
				if(scrollY >= scrollPage.maxPos()-10){
					clearTimeout(scrollPage.interval);
					return false;
				}
				break;
		}
	},
	//スクロール方向設定
	setScroll:function(toY){
		if(toY == null) {
			this.toY = 0;
		} else if(toY >= scrollPage.maxPos()) {
			this.toY = scrollPage.maxPos();
		} else {
			this.toY = toY;
		}
		var scrollY = scrollPage.yPos();
		if(scrollY >= this.toY) {
			this.mode = "up";
		} else {
			this.mode = "down";
		}
		scrollPage.doScroll();
	},
	//キャンセル
	cancel:function(e){
		if (window.event) {
			window.event.cancelBubble = true
			window.event.returnValue = false
		}
		if (e.preventDefault && e.stopPropagation) {
			 e.preventDefault()
			 e.stopPropagation()
		}
	},
	//初期化
	init:function(e){
		if (window.event) {
			window.event.cancelBubble = true
			window.event.returnValue = false
		}
		if (e.preventDefault && e.stopPropagation) {
			 e.preventDefault()
			 e.stopPropagation()
		}
	}
}
