/**
 * 
 * common.js
 * 
 * @require prototype.js
 * @require scriptaculous.js
 * @require urchin.js
 * 
 */


/**
 * 初期化設定ハンドラ．
 */
var init; // 必要ならコントローラー内で設定する初期化
Event.observe(window, "load", commonInit);


/**
 * 初期化．
 */
function commonInit(){
	// GoogleAnalytics
	track();
	// 検索ボックスの設定
	setSearchBox();
	// 画像のhover切替設定
	setImageAction();
	// 商品
	setItemDataAction();
	// サイドバーの開閉設定
	setAccordionMenu();
	// カレンダー設定
	setCalendar();
	// カスタムの初期化設定があれば実行
	if(init && typeof(init) == "function"){
		init();
	}
}

/**
 * 検索ボックスの初期設定．
 */
function setSearchBox(){
	var e = $("search").word;
	e.defaultValue = "キーワードを入力してください";
	e.defaultColor = e.style.color;
	e.value = e.defaultValue;
	e.onfocus = function(){
		if(this.value == this.defaultValue){ this.value = ""; this.style.color = "#333333";}
	}
	e.onblur = function(){
		if(this.value == ""){ this.value = this.defaultValue; this.style.color = this.defaultColor;}
	}
	$("search").onsubmit = function(){
		if(e.value == e.defaultValue || e.value == ""){
			return false;
		}else{
			return true;	
		}
	}
}

/**
 * 画像のhover設定．
 */
function setImageAction(){
	var images = new Array();
	var hoverImages = new Array();
	var tmp1 = document.getElementsByTagName("img");
	var tmp2 = document.getElementsByTagName("input"); 
	var l1 = tmp1.length;
	var l2 = tmp2.length;
	var e = new RegExp("hover", "i");
	var r = new RegExp("(.+)(\\.)(.+)", "i");
	for(var i=0; i<l1; i++){
		var t = tmp1[i];
		if(t.className && t.className.match(e)){
			images.push(t);
		}
	}
	for(var i=0; i<l2; i++){
		var t = tmp2[i];
		if(t.src && t.className && t.className.match(e)){
			images.push(t);
		}
	}
	var l = images.length;
	for(var i=0; i<l; i++){
		var t = images[i];
		t.url1 = t.src;
		t.url2 = t.src.replace(r, "$1_on.$3");
		t.onmouseover = function(){
			this.src = this.url2;	
		}
		t.onmouseout = function(){
			this.src = this.url1;	
		}
		hoverImages.push(t.url2);
	}
	preloadImages(hoverImages);
}

/**
 * 画像の先読み
 * @param images 先読みさせたい画像パスを格納する配列
 */
function preloadImages(images){
	var d = document;
	d.imageHolder = new Array();
	var l = images.length;
	for(var i=0; i<l; i++){
		d.imageHolder[i] = new Image();
		d.imageHolder[i].src = images[i];
	}
}

/**
 * 商品情報のスタイル設定．
 */
function setItemDataAction(){
	var tmp = document.getElementsByTagName("dl");
	var l = tmp.length;
	var r1 = new RegExp("itemData", "i");
	var r2 = new RegExp("saleState2|saleState4", "i");
	for(var i=0; i<l; i++){
		var e = tmp[i];
		if(e.className && e.className.match(r1)){
			e.url = e.getElementsByTagName("a")[0].href;
			e.onclick = function(){ 
				location.href= this.url;
			}
			e.onmouseover = function(){
				this.style.borderColor = "#9f9f9f";
				this.style.backgroundColor = "#f9f9f9";
			}
			e.onmouseout = function(){
				this.style.borderColor = "#c8c8c8";	
				this.style.backgroundColor = "#ffffff";
			}
		}
	}
}

/**
 * サイドバーのアコーディオン設定．
 */
function setAccordionMenu(){
	$("acmh1").onclick = function(){ Effect.toggle("acmc1", 'blind');}
	$("acmh2").onclick = function(){ Effect.toggle("acmc2", 'blind');}
	$("acmh1").style.cursor = $("acmh2").style.cursor = "pointer";
}

/**
 * サイドバーのツールチップ設定．
 */
function setSidebarTooltip(){
	var sidebar = $("sidebar");
	var tooltip = $("tooltip");
	// tooltipに動的にプロパティを追加
	tooltip.enabled = false;
	tooltip.disabledTimer = 0;
	tooltip.appear = function(){
		if(!this.enabled){
			this.style.display = "block";
			this.enabled = true;
		}
		clearTimeout(this.disabledTimer);
	}
	tooltip.disappear = function(){
		if(this.enabled){
			this.disabledTimer = setTimeout(this.disappear2, 300);
		}
	}
	tooltip.disappear2 = function(){
		tooltip.style.display = "none";
		tooltip.enabled = false;
	}
	tooltip.setMsg = function(msg, width){
		tooltip.innerHTML = msg;
		tooltip.style.width = width + "px";
	}
	tooltip.setPos = function(mouseX, mouseY){
		if(!this.enabled){ return;}
		mouseX = mouseX <= 850 ? mouseX: 850;
		tooltip.style.left = (mouseX - (tooltip.style.width.replace(/px/, "") / 2)) + "px";
		tooltip.style.top  = (mouseY + 22) + "px";
	}
	// イベントハンドラ
	function mouseOverHandler(e){
		if(!Event.element){return;} // 読込待ち
		var t = Event.element(e);
		tooltip.appear();
		tooltip.setMsg(t.subtext, t.subtextWidth);
		tooltip.setPos(Event.pointerX(e), Event.pointerY(e));
	}
	function mouseOutHandler(e){
		tooltip.disappear();
	}
	function mouseMoveHandler(e){
		if(!Event.element){return;} // 読込待ち
		tooltip.setPos(Event.pointerX(e), Event.pointerY(e));
	}
	// 設定
	var links = sidebar.getElementsByTagName("a");
	var len = links.length;
	for(var i=0; i<len; i++){
		var e = links[i];
		if(e.title){
			e.subtext = e.title;
			e.subtextWidth = Math.floor(getTextWidth(e.title, 5.5, 11));
			e.title = "";
			Event.observe(e, "mouseover", mouseOverHandler);
			Event.observe(e, "mousemove", mouseMoveHandler);
			Event.observe(e, "mouseout", mouseOutHandler);
		}
	}
}

/**
 * カレンダーの設定．
 */
function setCalendar(){
	var t = $("calendarController");
	var c = $("currentMonth");
	var n = $("nextMonth");
	t.onclick = function(){
		var m = c.style.display == "none";
		if(m){
			c.style.display = "block";
			n.style.display = "none";
			t.innerHTML = "&gt; 次の月";
		}else{
			c.style.display = "none";
			n.style.display = "block";
			t.innerHTML = "&lt; 前の月";
		}
		return false;
	}
}

/**
 * GoogleAnalyticsの実行．
 */
function track(){
	_uacct = "UA-2512123-1";
	urchinTracker();
}


/**
 * ＱＲコードの拡大．
 */
function showLargeQR(url){
	var w = window.open(url, "QR", "width=250, height=250, toolbar=no, scrollbars=yes, resizable=yes");
	w.focus();
}


/**
 * フォーム要素の見栄えの設定．
 * 基本的に設定しているCSSでカバーできない箇所を設定します．
 * @param form フォーム要素
 */
function setFormStyle(form){
	
	// テキスト入力要素のフォーカス時のスタイル
	var setTextFocusStyle = function(){
		this.style.background = "#FBFDFF";
	}
	var setTextBlurStyle = function(){
		this.style.background = "#FFFFFF";
	}
	
	// ボタンスタイルクラス、幅指定
	var setButtonWidth = function(e){
		if(e.tagName == "INPUT"){
			e.style.width = (26 + e.value.length * 11) + "px";
		}else if(e.tagName == "BUTTON"){
			var w = e.getElementsByTagName("img")[0].width + 4;
			e.style.width = w + "px";
		}
	}
	
	// <input>タグに対する設定、テキストインプトのみに設定する（古いブラウザ対策）
	var formElements = form.getElementsByTagName("input");
	var l = formElements.length;
	for(i=0; i<l; i++){
		var e = formElements[i];
		if(e.type == "text" || e.type == "password"){
			// CSSスタイル
			e.style.height = "18px";
			e.style.padding = "2px 1px 1px 7px";
			e.style.border = "solid 1px #bbbbbb";
			// フォーカス時の挙動を追加設定
			e.onfocus = setTextFocusStyle;
			e.onblur = setTextBlurStyle;
		}
	}
	
	// <textarea>タグの設定
	var formElements = form.getElementsByTagName("textarea");
	var l = formElements.length;
	for(i=0; i<l; i++){
		e = formElements[i]
		e.style.imeMode = "active";
		e.onfocus = setTextFocusStyle;
		e.onblur = setTextBlurStyle;
	}
	
	// <button>タグの設定
	var formElements = form.getElementsByTagName("button");
	var l = formElements.length;
	for(i=0; i<l; i++){
		var e = formElements[i];
		setButtonWidth(e);
	}
}


/**
 * IMEの設定（IE限定）．
 * @param form フォーム要素
 * @param elementName フォーム内の目的要素の名前（複数の引数が可能）
 */
function setIMEActive(form, elementName){
	for(var i=1; i<arguments.length; i++){
		var tgt = form[arguments[i]];
		if(tgt){
			tgt.style.imeMode = "active";
		}
	}
}
function setIMEInactive(form, elementName){
	for(var i=1; i<arguments.length; i++){
		var tgt = form[arguments[i]];
		if(tgt){
			tgt.style.imeMode = "inactive";
		}
	}
}


/**
 * ページトップへの遷移．
 */
function toPageTop(){
	window.scrollTo(0, 0);
}


/**
 * 文字列のバイト長を求めます．
 * @param str 対象文字
 * @return シングルバイトで何バイトに相当するか
 */
function getStringByteLength(str){
	var byteLength = 0;
	var len = str.length;
	while(len--){
		var charCode = str.substr(len, 1).charCodeAt(0);
		byteLength += isSingleByteString(charCode) ? 1: 2;
	}
	return byteLength;
}

/**
 * シングルバイト文字かどうかを返します．
 * @param str 対象文字
 * @return シングルバイトなら true、マルチバイトなら false
 */
function checkCharCodeRange(str, minCharCodeRange, maxCharCodeRange){
	var len = str.length;
	while(len--){
		var charCode = str.substr(len, 1).charCodeAt(0);
		if (charCode < minCharCodeRange || charCode > maxCharCodeRange){
			return false;
			break;
		}
	}
	return true;
}

/**
 * シングルバイト文字かどうかを返します．
 * @param str 対象文字
 * @return シングルバイトなら true、マルチバイトなら false
 */
function isSingleByteString(str){
	return (checkCharCodeRange(str, 0x00, 0x7f) || checkCharCodeRange(str, 0xff61, 0xff9f)) ? true : false;
}

/**
 * 文字列のバイト長にあわせたテキスト長さを求めます．
 * @param str 対象文字
 * @param singleByteWidth 幅
 * @param multiByteWidth 幅
 * @return 幅（ピクセル）
 */
function getTextWidth(str, sbWidth, mbWidth){
	var width = 0;
	var len = str.length;
	while(len--){
		var char = str.substr(len, 1);
		width += isSingleByteString(char) ? sbWidth: mbWidth;
	}
	return width;
}


