//変数pageを各htmlより取得
/*******************************
Setting
*******************************/
//for ie6 pageTopBtn
var pageTop_ie6=$.xGetWindowSize().height-40;

/*******************************
Execution
*******************************/
$(function(){
	//初期スクロール
	xScroll();
	//ページトップボタン配置
	xPageTop(true);
	//ページスクロール
	$("a",".scroll").xScroll();
	$("a#pagetop").xScroll();
	//ウィンドウリサイズイベント
	$(window).bind("resize",xWindowResize);
	//ドロップダウンメニュー
	$.xDropEffect();
	//画像拡大
	$(".noias_viewer").xImgLarger();
	//外部リンクを別ウィンドウで
	$(".link_blank").attr("target","_blank");
	//google map
	$("#link_gmap").attr("href","http://maps.google.co.jp/maps?q=%E5%B2%90%E9%98%9C%E7%9C%8C%E5%B2%90%E9%98%9C%E5%B8%82%E5%AF%BA%E5%B3%B6%E7%94%BA1-5-1&lr=lang_ja&oe=utf-8&client=firefox-a&ie=UTF8&split=0&gl=jp&ei=AGzUSdKiGMGfkQW7u9iCDw&ll=35.415626,136.752799&spn=0.001941,0.004069&z=19");
	//最新のお知らせの文字数制限
	xNewPostLink(12);
	//swf埋め込み
	if(page=="beginners3") swfobject.embedSWF("/wp-content/swf/beginners.swf","beginners_player","612","430","8","/wp-content/swf/expressInstall.swf",{},{"wmode":"transparent"},{});
	//サイドメニューロールオーバー
	xSideOver();
	//image clip
	xImageClip();
	//メールアドレスの挿入
	xMailAdd();
	//blog　post背景調整
	$("div.post_seam:eq(0)","div#main").hide();
	//コレクションページ
	if(page=="collection"){
		xSSLRedirect();//SSLへリダイレクト
		xCollectionMenu();//コレクションメニューの挿入
		xCollectionResult();//コレクション検索結果を挿入(ページャー部)
		xCollectionThumb();//リストページサムネイルのロールオーバー
		xCollectionSelect();//詳細ページリストボックス操作
		xInCart();//カートへ追加
		xSideCart();//サイドメニューカートの移動
	}
	//コレクションページ
	if(page=="cart"){
		xSSLRedirect();
		xCart();//カート内挙動
	}
	
	if(page=="contact") xSSLRedirect();
	
	
	if(page=="404") xFooterHeight();
	
	//sideの高さ調節
	xElementSize();
	//
	xAnalytics()
});
/*******************************
Function
*******************************/
//メールアドレスの挿入
function xMailAdd(){
	$("a.mailadd").attr("href","mailto:contact@pu-pi.com").text("contact@pu-pi.com");
}
//初期スクロール
function xScroll(){
	var target=window.location.href.split("#")[1];
	if(target){
		document.documentElement.scrollTop=0;
		var nTop=$("#"+target).offset().top-250||0;
		$(($.browser.opera)?"html":"html,body").animate({scrollTop:nTop},1000,'swing');
	}
}

//ページトップボタン配置
function xPageTop(init,position){
	var target=$("#container");
	var position_obj=target.offset();
	var left=pageTopLeft=position_obj.left+(target.width())-15;
	var pagetop=$("#pagetop");
	if(init){
		pagetop.css("display","block").animate({opacity:0.7},0).hover(function(){$(this).animate({opacity:1},0)},function(){$(this).animate({opacity:0.7},0)});
	}
	if(position) return (document.body.scrollTop)+pageTop_ie6;
	else pagetop.css("left",left),pageTop_ie6=$.xGetWindowSize().height-40;
}

//
function xElementSize(){
	var side_el=$("#side");
	var main_el=$("#main");
	var container_el=$("#container");
	var nSideH=side_el.height();
	if(main_el.height()<nSideH) main_el.height(nSideH);
	else side_el.height(container_el.height());
}

//window Resize
function xWindowResize(){
	xPageTop(false);
	if(page=="404") xFooterHeight();
}

//最新のお知らせの文字数制限
function xNewPostLink(limit){
	$.each($("li a","div#newpost"),function(){
		var sText=$(this).text();
		if(sText.length>limit) $(this).text(sText.substr(0,limit)+"…");
	});
}

//サイドメニューのロールオーバー
function xSideOver(){
	var target_el=$("a","div#page_menu");
	target_el.attr("title","");
	$.each(
		target_el,
		function(){
			if("side_"+page==$(this).attr("id")){
				var n=$(this).text().length;
				if(n<4) $(this).addClass("page_menu_over1");
				else if(n==4) $(this).addClass("page_menu_over2");
				else if(n==5) $(this).addClass("page_menu_over3");
				else if(n==6) $(this).addClass("page_menu_over4");
				else if(n==7) $(this).addClass("page_menu_over5");
				else $(this).addClass("page_menu_over6");
			}
		}
	);
	target_el.hover(
		function(){
			var n=$(this).text().length;
			if("side_"+page==$(this).attr("id")) $(this).addClass("page_menu_over0");
			else if(n<4) $(this).addClass("page_menu_over1");
			else if(n==4) $(this).addClass("page_menu_over2");
			else if(n==5) $(this).addClass("page_menu_over3");
			else if(n==6) $(this).addClass("page_menu_over4");
			else if(n==7) $(this).addClass("page_menu_over5");
			else $(this).addClass("page_menu_over6");
		},
		function(){
			if("side_"+page!=$(this).attr("id")) $(this).removeClass();
		}
	)
}

//画像上のclip効果
function xImageClip(){
	if($.browser.msie&&$.browser.version<7) return 0;
	else{
		var target_el=$("#clip");
		if(target_el.attr("src")){
			var plus=($.browser.msie)?120:110;
			$("#main").prepend("<img id='clip_img' />");
			$("#clip_img").css({
				position:"absolute",
				top:target_el.offset().top-plus,
				left:"576px"
			}).
			attr("src","/wp-content/themes/pu-pi/images/share/clip.png");
		}
	}
}

//コレクションメニューの挿入
function xCollectionMenu(){
	$("#collectionCaution").remove();
	$("#collectionCaution2").remove();
	$("#collectionMenu").appendTo("#page_menu").show(); 
	//検索実行
	$("button","#collectionMenu").click(function(){
		window.location.href=xGetSSL()+"/collection/?"+$("form","#collectionMenu").serialize();
		return false;
	});
}

//コレクション検索結果を挿入(ページャー部)
function xCollectionResult(){
	var result_array=[];
	var myText="";
	var myValue="";
	var parentName="";
	$.each($("option:selected","#collectionMenu"),function(){
		this_el=$(this);
		if(this_el.val()!="0"){
			myText=this_el.text();
			myValue=this_el.val();
			parentName=this_el.parent().attr("name");
			result_array.push("<a href='"+xGetSSL()+"/collection/?"+parentName+"="+myValue+"' title='"+this_el.text()+"の一覧を見る'>"+this_el.text()+"</a>");
		}
	});
	result_txt=result_array.join(" + ");
	$("div.collection_pager_content","div#article_content").html(result_txt);
}

//リストページサムネイルのロールオーバー&クリック
function xCollectionThumb(){
	target_el=$("div.article_img_box");
	target_el.hover(
		function(){
			var top=($.browser.msie&&$.browser.version<7)?"-151px":"-148px";
			$("img.list_swatch",this).parent().animate({top:top,left:"0"},330);
			$(this).parent().css("backgroundColor","#eee");
		},
		function(){
			$("img.list_swatch",this).parent().animate({top:"-148px",left:"148px"},180);
			$(this).parent().css("backgroundColor","#fff");
		}
	);
	target_el.click(
		function(){
			window.location.href=$("a",this).attr("href");
		}
	);
}

//詳細ページリストボックス操作
function xCollectionSelect(){
	if($("div#article_one").text()){
		$("#choose_size").change(function(){
			var target_el=$("select#choose_lot");
			if($(this).val()){
				$.get(xGetSSL()+"/wp-content/themes/pu-pi/shop/",{lot_id:$(this).attr("lot_id"),cnt_type:$(this).val()},
					function(data){
						target_el.empty();
						var select="<option value='' selected='selected'>数量を選択</option>";
					 	for(var i=1;i<=data;i++) select+="<option value='"+i+"'>"+i+" 本</option>";
					 	target_el.removeAttr("disabled");
					 	target_el.append(select);
					}
				);
			}else{
				target_el.attr("disabled","disabled").val(0);
			}
		})
	}
}

//カートへ追加(サイドカート)
function xInCart(){
	/*************************
	cookie書式
		ID:サイズ:数量
	**************************/
	$("button#cart_btn").click(function(){
		var sep1="\t";
		var sep2=":";
		var cookie=$.cookie('pu-pi');
		var id=$("select#choose_size").attr("lot_id");
		var size=$("select#choose_size").val();
		var value=$("select#choose_lot").val();
		//サイズ・数量が選択されている
		if(id&&value){
			//cookie情報がある
			if(cookie){
				var cookie_array=cookie.split(sep1);
				for(var i=0;i<cookie_array.length;i++){
					cookie_array[i]=cookie_array[i].split(sep2);
					//登録済み商品
					if(cookie_array[i][0]==id&&cookie_array[i][1]==size){
						var conflict=true;
						cookie_array[i][2]=value;
					}
				}
				//cookie保存
				if(conflict){
					for(var i=0;i<cookie_array.length;i++) cookie_array[i]=cookie_array[i].join(sep2);
					cookie=cookie_array.join(sep1);
					xSaveCookie("pu-pi",cookie);
				}
				else xSaveCookie("pu-pi",cookie+sep1+id+sep2+size+sep2+value);
			}
			//cookie情報がない
			else xSaveCookie("pu-pi",id+sep2+size+sep2+value);
			//カートへ移動
			window.location.href=xGetSSL()+'/cart/';
		}
		//サイズ・数量が選択されていない
		else{
			alert("サイズ・数量を選択してください。");
		}
	});
}

//サイドメニューカートの移動
function xSideCart(){
	var target_el=$("ul#cart_in_article");
	if(target_el.html()){
		$("ul","div#side_cart").remove();
		$("ul#cart_in_article").appendTo("div#side_cart").show();
	}
	//カートへ移動
	$("button","ul#cart_in_article").click(function(){
		window.location.href=xGetSSL()+"/cart/";
	});
}

/*******************************
cart.php
********************************/
function xCart(){
	var article_cookie=$.cookie("pu-pi");
	var pay_select=$("select","tr#pay_row");
	var post_select=$("select","tr#post_row");
	//買い物を続ける
	$("#back_btn").click(function(){window.location.href=xGetSSL()+"/collection/"});
	if(article_cookie){
		//単品削除
		$("a.delete_btn").click(function(){
			//cookie更新
			var this_el=$(this);
			if(window.confirm("【No."+this_el.attr("sling_title")+"】を削除します")) xReCart(this_el.attr("article_id"),this_el.attr("article_size"));
		});
		//商品セレクトボックス育成
		var total_lot=0;
		var chg_array=[];
		$.each($("select","div#cart_content table tr.article_row"),function(){
			var this_el=$(this);
			var option_el="";
			var max_lot=this_el.attr("max_lot");
			var select_lot=this_el.attr("select_lot");
			var selected="";
			total_lot+=Number(select_lot);
			for(var i=0;i<=max_lot;i++){
				if(select_lot==i) selected="selected='selected'";
				option_el+="<option value='"+i+"' "+selected+">"+i+"</option>";
				selected="";
			}
			this_el.append(option_el);
			this_el.change(function(){
				//cookie更新
				xReCart(this_el.attr("article_id"),this_el.attr("article_size"),this_el.val(),true);
				//ラッピングセレクトボックス更新
				xRePkg();
				//再計算
				xCartCalculate();
			});
		});
		//レジへ進む
		$("#regi_btn").click(function(){
			//selectBoxの値をcookieに追加(在庫数変動対策)
			if(xReCookie()) window.location.href=xGetSSL()+"/regi/";
		});
		//カートを空にする
		$("#clear_btn").removeAttr("disabled").click(function(){
			if(window.confirm("カートを空にします。")){
				xSaveCookie("pu-pi",null);
				xSaveCookie("pkg",null);
				xSaveCookie("post",null);
				xSaveCookie("pay",null);
				window.location.reload();
			}
		});
		//ラッピングセレクトボックス育成
		xRePkg();
		//配送セレクトボックス
		post_select.change(function(){
			var post_select=$(this);
			$.get(xGetSSL()+"/wp-content/themes/pu-pi/shop/",{pref_id:$(this).val()},function(data){
				//cookie更新
				xSaveCookie("post",post_select.val());
				$("td.option_total","tr#post_row").html(number_format(data,true));
				//再計算
				xCartCalculate();
			});
		});
		//支払い手数料
		pay_select.change(function(){
			//cookie更新
			var value=$(this).val();
			var target_el=$("td.option_total","tr#pay_row");
			xSaveCookie("pay",value);
			if(value!=1) target_el.html("&yen;0");
			xCartCalculate();
		});
		xCartCalculate();
	}
}

//ラッピングセレクトメニュー育成
function xRePkg(){
	//登録商品総数の設定
	var total_lot=0;
	$.each($("select","div#cart_content table tr.article_row"),function(){total_lot+=Number($(this).val())});
	//選択値の設定
	var current_lot=0;
	if($.cookie("pkg")>total_lot){
		current_lot=total_lot;
		$.cookie("pkg",current_lot,{expires:7,path:xGetSSL()+"/"});
	}else{
		current_lot=($.cookie("pkg")||0);
	}
	//反映
	var option_el="";
	var selected="";
	for(var i=0;i<=total_lot;i++){
		if(current_lot==i) selected="selected='selected'";
		option_el+="<option value='"+i+"' "+selected+">"+i+"</option>";
		selected="";
	}
	var this_el=$("select","div#cart_content table tr#pkg_row");
	this_el.empty().append(option_el).change(function(){xSaveCookie("pkg",$(this).val());xCartCalculate();});
	xSaveCookie("pkg",this_el.val());
	
	return total_lot;
}

//レジ直前にセレクトボックスを再集計(商品情報のみ)
function xReCookie(){
	/*************************
	cookie書式
		ID:サイズ:数量
	**************************/
	var cookie="";
	var sep1="\t";
	var sep2=":";
	var i=0;
	$.each($("select","div#cart_content table tr.article_row"),function(){
		var this_el=$(this);
		if(i>0) cookie+=sep1;
		cookie+=this_el.attr("article_id")+sep2+this_el.attr("article_size")+sep2+this_el.val();
		i++;
	});
	//cookie再登録
	xSaveCookie("pu-pi",cookie);
	return true;
}


//セレクトボックスによるCookie更新(id,size,更新or削除)
function xReCart(id,size,value,b){
	/*************************
	cookie書式
		ID:サイズ:数量
	**************************/
	var sep1="\t";
	var sep2=":";
	var cookie=$.cookie('pu-pi');
	var cookie_array=cookie.split(sep1);
	var pool_array=[]
	for(var i=0;i<cookie_array.length;i++){
		pool_array[i]=cookie_array[i].split(sep2);
		//登録済み商品 or 削除対象
		if(pool_array[i][0]==id&&pool_array[i][1]==size){
			var conflict=true;
			var conflictNo=i;
			pool_array[i][2]=value;
		}
	}
	//削除
	if(!b) pool_array.splice(conflictNo,1);
	//cookie保存
	if(conflict){
		cookie_array=[];
		for(var i=0;i<pool_array.length;i++) cookie_array[i]=pool_array[i].join(sep2);
		cookie=cookie_array.join(sep1);
		xSaveCookie("pu-pi",cookie);
	}
	else xSaveCookie("pu-pi",cookie+sep1+id+sep2+size+sep2+value);
	//削除した場合はリロード
	if(!b) window.location.reload();
}


//cart集計
function xCartCalculate(){
	var price_array=[];
	var lot_array=[];
	var i=0;
	var total1=0;
	var total2=0;
	//商品単価
	$.each($("td.article_price","div#cart_content table"),function(){price_array[i]=number_format($(this).text(),false);i++;});
	i=0;
	//数量
	$.each($("select","div#cart_content table tbody"),function(){lot_array[i]=$(this).val();i++;});
	i=0;
	//小計
	$.each($("td.article_total","div#cart_content table"),function(){
		var kari_total=price_array[i]*lot_array[i];
		total1+=kari_total;
		$(this).html(number_format(kari_total,true));
		i++;
	});
	//代引き手数料の再計算後に実行
	if($("select","tr#pay_row").val()==1){
		var target_el=$("td.option_total","tr#pay_row");
		$.get(xGetSSL()+"/wp-content/themes/pu-pi/shop/",{charge_cost:total1},function(data){
			target_el.html(number_format(data,true));
			//配送料・支払い手数料
			$.each($("td.option_total","div#cart_content table"),function(){total2+=Number(number_format($(this).text(),false));});
			//商品合計
			$("#total1").html(number_format(total1,true));
			//総合計
			$("#total2").html(number_format(total1+total2,true));
			//レジボタンの状態
			xCheckRegiBtn();
		});
	}
	//代引き手数料が選択されていない
	else{
		//配送料・支払い手数料
		$.each($("td.option_total","div#cart_content table"),function(){total2+=Number(number_format($(this).text(),false));});
		//商品合計
		$("#total1").html(number_format(total1,true));
		//総合計
		$("#total2").html(number_format(total1+total2,true));
		//レジボタンの状態
		xCheckRegiBtn();
	}
}

function xCheckRegiBtn(){
	var regi_btn=$("#regi_btn");
	var regi_flg=Boolean(
		Number($("select","tr#post_row").val())&&
		Number($("select","tr#pay_row").val())&&
		Number(number_format($("#total1").text(),false))
	);
	if(regi_flg) regi_btn.removeAttr("disabled");
	else regi_btn.attr("disabled","disabled");
}

//通貨記号・3桁カンマ区切り(第2引数で、カンマ挿入・解除を指定)
function number_format(str,b) {
	if(b){
		var num = new String(str).replace(/,/g, "");
		while(num != (num = num.replace(/^(-?\d+)(\d{3})/, "$1,$2")));
		return "&yen;"+num;
	}else{
		str=str.replace(/,/g,"");
		return str.substring(1,str.length);
	}
}


//cookie保存
function xSaveCookie(name,value){
	$.cookie(name,value,{expires:7,path:"/pu-pi.com/"});
}

//SSLURL
function xGetSSL(){
	var url=window.location.href;
	if(!url.match("pu-pi.noias")){
		return "https://ss2.xrea.com/pu-pi.com";
	}
}

function xSSLRedirect(){
	var url=window.location.href;
	if(url.match("http:")&&!url.match("pu-pi.noias")){
		location.href=url.replace("http://pu-pi.com",xGetSSL());
	}
}


function xFooterHeight(){
	var target_el=$("#footer");
	var h=$.xGetWindowSize().height;
	var top=target_el.offset().top;
	var p=($.browser.msie)?0:60;
	if(h>808) target_el.height(h-top-p);
}

function xAnalytics(){
	try {
		_uacct = "UA-472370-16";
		urchinTracker();
	}catch(err){}
}