/*
* lm 1.3
* Automatic functions for webpages
* Require:
*  jquery.js
*  frame.css
*  content_font.css
*
* Copyright: (c) 2008 ludicmind.net
**************************************/

// Initialization
$.lm = {
	init: function() {
		for (func in $.lm) {
			if ($.lm[func].init)
				$.lm[func].init();
		}
	}
};

$(document).ready(function(){
	$.lm.init();
	$("input#next").bind("click", checkProduct);
	$("input#confirm").bind("click", checkAddress);
	$("input#send").bind("click", checkConfirm);
	$("input#backToAddress").bind("click", function(){
		$('form')[0].action = 'input';
	});
	$("input.name").bind("click", function(){
		this.select();
	});
	$("input[name='shipping']").bind("click", shipAddress);
	if($("input[name='shipping']:checked").val() == 1){
		$("dl#shippingInfo").addClass("disable");
		$("dl#shippingInfo input").attr("disabled","disabled");
		$("dl#shippingInfo select").attr("disabled","disabled");
	}
	if($("input[name='shipping']:checked").val() == 2){
		$("input#pay1").attr("checked", "checked");
		$("input#pay2").attr("disabled", "disabled");
		$("label[for='pay2']").addClass("disabled");
	}
	$("input#inputAddr").bind("click", inputAddress);
	$("input#ship_inputAddr").bind("click", inputShipAddress);
	$("a#rules").bind("click", function(){
		showRules();
		return false;
	});
});


// Sales Policy
function showRules(){
	$("div#body").append("<div id='salesBlockContainer'></div>");
	$("select").css("visibility", "hidden");
	$("div#salesBlockContainer").load("/sales.html", function(){
		$("a.salesClose").bind("click",function(){
			$("div#salesBlockContainer").remove();
			$("select").css("visibility", "visible");
			return false;
		});
	});

}

//Form Check
function checkProduct(){
	if(($("input[name='items[]']:checked").length == 0)) {
		showError("商品を選択してください");
		return false;
	} else {
		$(this).after("<input type='hidden' name='submit' value='次へ' />");
	}

}

//Check total price

function checkAddress(){
	var mailRegExp = new RegExp("^[a-z0-9\._%-]+@[a-z0-9\.-]+\.[a-z]{2,4}$", "i");
	mail1Check = $("input[name='mail1']").val().search(mailRegExp);

	$("input").removeClass("error");
	$("select").removeClass("error");

	if($("input[name='name1']").val() == "" || $("input[name='name1']").val() == "姓" || $("input[name='name2']").val() == "" || $("input[name='name2']").val() == "名") {
		showError("お名前を入力してください");
		$("input[name='name1']").addClass("error");
		$("input[name='name2']").addClass("error");
		return false;
	} else if($("input[name='kana1']").val() == "" || $("input[name='kana1']").val() == "セイ" || $("input[name='kana2']").val() == "" || $("input[name='kana2']").val() == "メイ") {
		showError("フリガナを入力してください");
		$("input[name='kana1']").addClass("error");
		$("input[name='kana2']").addClass("error");
		return false;
	} else if($("input[name='mail1']").val() == "") {
		showError("E-mailを入力してください");
		$("input[name='mail1']").addClass("error");
		return false;
	} else if(mail1Check < 0) {
		showError("メールアドレスの形式が正しくありません");
		$("input[name='mail1']").addClass("error");
		return false;
	} else if($("input[name='mail1']").val() != $("input[name='mail2']").val()) {
		showError("2つのメールアドレスが一致しません");
		$("input[name='mail1']").addClass("error");
		$("input[name='mail2']").addClass("error");
		return false;
	} else if($("input[name='zip1']").val() == "" || $("input[name='zip2']").val() == "") {
		showError("郵便番号を入力してください");
		$("input[name='zip1']").addClass("error");
		$("input[name='zip2']").addClass("error");
		return false;
	} else if($("select[name='prefecture']").val() == "") {
		showError("都道府県を選択してください");
		return false;
	} else if($("input[name='address1']").val() == "") {
		showError("市区町村を入力してください");
		$("input[name='address1']").addClass("error");
		return false;
	} else if($("input[name='address2']").val() == "") {
		showError("番地を入力してください");
		$("input[name='address2']").addClass("error");
		return false;
	} else if($("input[name='tel1']").val() == "" || $("input[name='tel2']").val() == "" || $("input[name='tel3']").val() == "") {
		showError("電話番号を入力してください");
		$("input[name='tel1']").addClass("error");
		$("input[name='tel2']").addClass("error");
		$("input[name='tel3']").addClass("error");
		return false;
	} else if($("input[name='shipping']:checked").length != 1) {
		showError("ご配送先を選択してください");
		return false;
	} else if($("input[name='shipping']:checked").val() == 2 && ($("input[name='ship_name1']").val() == "" || $("input[name='ship_name1']").val() == "姓" || $("input[name='ship_name2']").val() == "" || $("input[name='ship_name2']").val() == "名")) {
		showError("配送先のお名前を入力してください");
		$("input[name='ship_name1']").addClass("error");
		$("input[name='ship_name2']").addClass("error");
		return false;
	} else if($("input[name='shipping']:checked").val() == 2 && ($("input[name='ship_kana1']").val() == "" || $("input[name='ship_kana1']").val() == "セイ" || $("input[name='ship_kana2']").val() == "" || $("input[name='ship_kana2']").val() == "メイ")) {
		showError("配送先のフリガナを入力してください");
		$("input[name='ship_kana1']").addClass("error");
		$("input[name='ship_kana2']").addClass("error");
		return false;
	} else if($("input[name='shipping']:checked").val() == 2 && ($("input[name='ship_zip1']").val() == "" || $("input[name='ship_zip2']").val() == "")) {
		showError("配送先の郵便番号を入力してください");
		$("input[name='ship_zip1']").addClass("error");
		$("input[name='ship_zip2']").addClass("error");
		return false;
	} else if($("input[name='shipping']:checked").val() == 2 && $("select[name='ship_prefecture']").val() == "") {
		showError("配送先の都道府県を選択してください");
		return false;
	} else if($("input[name='shipping']:checked").val() == 2 && $("input[name='ship_address1']").val() == "") {
		showError("配送先の市区町村を入力してください");
		$("input[name='ship_address1']").addClass("error");
		return false;
	} else if($("input[name='shipping']:checked").val() == 2 && $("input[name='ship_address2']").val() == "") {
		showError("配送先の番地を入力してください");
		$("input[name='ship_address2']").addClass("error");
		return false;
	} else if($("input[name='pay']:checked").length != 1) {
		showError("お支払い方法を選択してください");
		return false;
	} else {
		$(this).after("<input type='hidden' name='submit' value='確認' />");
	}
}

function shipAddress(){
	if($("input[name='shipping']:checked").val() == 1){
		$("dl#shippingInfo").addClass("disable");
		$("dl#shippingInfo input").attr("disabled","disabled");
		$("dl#shippingInfo select").attr("disabled","disabled");
		$("input#pay2").attr("disabled", "");
		$("label[for='pay2']").removeClass("disabled");
	} else {
		$("dl#shippingInfo").removeClass("disable");
		$("dl#shippingInfo input").attr("disabled","");
		$("dl#shippingInfo select").attr("disabled","");
		$("input#pay1").attr("checked", "checked");
		$("input#pay2").attr("disabled", "disabled");
		$("label[for='pay2']").addClass("disabled");
	}
}

function checkConfirm(){
	if($("input#confirm_check:checked").length != 1) {
		showError("内容を確認後、「上記の内容で注文する」にチェックを付けてください");
		return false;
	} else {
		$(this).after("<input type='hidden' name='submit' value='注文' />");
	}
}


// Auto input address
function inputAddress(){
	if($("input#zip1").val() == "" || $("input#zip2").val() == ""){
		showError("郵便番号を入力してください");
		return false;
	}
	if($("input#zip1").val().length != 3 || $("input#zip2").val().length != 4){
		showError("正しい桁数の郵便番号を入力してください");
		return false;
	}
	zip = convertNum($("input#zip1").val());
	zip2 = convertNum($("input#zip2").val());
	zip = zip.toString() + zip2.toString();
	if(isNaN(zip)){
		showError("郵便番号には数字を入力してください");
		return false;
	}

	$.ajax({
		type: "GET",
		url: "http://zip.ricollab.jp/" + zip + ".json",
		dataType: "jsonp",
		complete: function(XMLHttpRequest, textStatus){
			
		},
		success: function(data, status){
			$("select[name='prefecture'] option").each(function(){
				if($(this).attr("value") == data.address.prefecture){
					$(this).attr("selected", "selected");
				}
			});
			$("input#address1").attr("value", data.address.city+data.address.town);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert("error");
		}
	});
}

function inputShipAddress(){
	if($("input#ship_zip1").val() == "" || $("input#ship_zip2").val() == ""){
		showError("郵便番号を入力してください");
		return false;
	}
	if($("input#ship_zip1").val().length != 3 || $("input#ship_zip2").val().length != 4){
		showError("正しい桁数の郵便番号を入力してください");
		return false;
	}
	zip = convertNum($("input#ship_zip1").val());
	zip2 = convertNum($("input#ship_zip2").val());
	zip = zip.toString() + zip2.toString();
	if(isNaN(zip)){
		showError("郵便番号には数字を入力してください");
		return false;
	}
	$.ajax({
		type: "GET",
		url: "http://zip.ricollab.jp/" + zip + ".json",
		dataType: "jsonp",
		complete: function(XMLHttpRequest, textStatus){
			
		},
		success: function(data, status){
			$("select[name='ship_prefecture'] option").each(function(){
				if($(this).attr("value") == data.address.prefecture){
					$(this).attr("selected", "selected");
				}
			});
			$("input#ship_address1").attr("value", data.address.city+data.address.town);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert("error");
		}
	});
}

function convertNum(num){
	han = "0123456789.,-+";
	zen = "０１２３４５６７８９．，－＋";
	str = "";
	for (i=0; i<num.length; i++) {
		c = num.charAt(i);
		n = zen.indexOf(c,0);
		if (n >= 0) c = han.charAt(n);
		str += c;
	}
	return str;
}
// Image hover
$.lm.hover = {
	init: function() {
		$('.hover')
			.bind('mouseover', this.enter)
			.bind('mouseout', this.exit)
			.bind('focus', this.enter)
			.bind('blur', this.exit)
			.each(this.preload);
	},

	preload: function() {
		this.preloaded = new Image;
		this.preloaded.src = this.src.replace(/^(.+)(\.[a-z]+)$/, "$1_o$2");
	},

	enter: function() {
		if (!this.src.match(/^(.+)_o(\.[a-z]+)$/) && !this.src.match(/^(.+)_a(\.[a-z]+)$/)){
			this.src = this.src.replace(/^(.+)(\.[a-z]+)$/, "$1_o$2");
		}
	},

	exit: function() {
		if (this.src.match(/^(.+)_o(\.[a-z]+)$/)){
			this.src = this.src.replace(/^(.+)_o(\.[a-z]+)$/, "$1$2");
		} else {
			this.src = this.src.replace(/^(.+)_a(\.[a-z]+)$/, "$1$2");
		}
	}
};


// Opacity Change hover
$.lm.oHover = {
	init: function() {
		$('.oHover')
			.live('mouseover', this.enter)
			.live('mouseout', this.exit)
			.live('focus', this.enter)
			.live('blur', this.exit);
	},

	enter: function() {
		$(this).animate({opacity: 0.7}, 200);
	},

	exit: function() {
		$(this).animate({opacity: 1}, 200);
	}
};


// Add "first-child" class to all elements in #content
$.lm.firstChild = {
	init: function() {
		var ua = window.navigator;
		if (ua.appName == "Microsoft Internet Explorer" && ua.appVersion.indexOf("MSIE 7.0") == -1) {
			$("#content *:first-child").addClass("first-child");
		}
	}
};


// Add "nolink" class to Heading without a[href]
$.lm.noLink = {
	init: function() {
		$("a:not([href])").parent("h2").addClass("nolink");
		$("a:not([href])").parent("h3").addClass("nolink");
		$("a:not([href])").parent("h4").addClass("nolink");
	}
};


// Mouse hover on input[type='image']
$.lm.inputHover = {

	init: function() {
		$('input[type="image"]')
			.bind('mouseover', this.enter)
			.bind('mouseout', this.exit)
			.each(this.preload);
	},

	preload: function() {
		this.preloaded = new Image;
		this.preloaded.src = this.src.replace(/^(.+)(\.[a-z]+)$/, "$1_o$2");
	},

	enter: function() {
		this.src = this.src.replace(/^(.+)(\.[a-z]+)$/, "$1_o$2");
	},

	exit: function() {
		this.src = this.src.replace(/^(.+)_o(\.[a-z]+)$/, "$1$2");
	}
};


// Navigation Submenu
$.lm.submenu = {
	init: function() {
		var toggle = function(direction, display) {
			return function() {
				var self = this;
				var ul = $(this).children("ul").eq(0);
				if( ul.css("display") == display && !self["block" + direction] ) {
					self["block" + direction] = true;
					ul["slide" + direction]("fast", function() {
						self["block" + direction] = false;
					});
				}
			};
		}
		$("li.hasSubmenu").hover(toggle("Down", "none"), toggle("Up", "block"));
		$("li.hasSubmenu ul").hide();
	}
};


// Replace "abbr" with "acronym" (only IE6)
$.lm.changeAbbr = {
	init: function() {
		var ua = window.navigator;
		if (ua.appName == "Microsoft Internet Explorer" && ua.appVersion.indexOf("MSIE 7.0") == -1) {
			var abbrs = document.getElementsByTagName('abbr');
			for (var i = 0; i < abbrs.length; i++) {
				var oldAbbr = abbrs.item(i);
				var newAbbr = document.createElement('abbr');
				newAbbr.title = oldAbbr.title;
				oldAbbr.parentNode.insertBefore(newAbbr, oldAbbr);
				while (oldAbbr.nextSibling.nodeName != '/ABBR') {
					newAbbr.appendChild(oldAbbr.nextSibling);
				}
				oldAbbr.parentNode.removeChild(oldAbbr.nextSibling);
				oldAbbr.parentNode.removeChild(oldAbbr);
			}
		}
	}
};


// Menu List Add Class "first" and "last" - use to ul
(function($) {
	jQuery.fn.addClassFL = function(colNum) {
		return this.children("li").each(function(i){
			if (i % colNum == 0){
				$(this).addClass("first");
			}
			if (i % colNum == colNum - 1){
				$(this).addClass("last");
			}
		});
	};
})(jQuery);


// Menu List Add Class "first" and "last" - use to div
(function($) {
	jQuery.fn.addDivClassFL = function(colNum) {
		return this.children("div").each(function(i){
			if (i % colNum == 0){
				$(this).addClass("first");
			}
			if (i % colNum == colNum - 1){
				$(this).addClass("last");
			}
		});
	};
})(jQuery);

// Error Message
function showError(message){
	var innerWidth = $.browser.msie ? document.documentElement.clientWidth : window.innerWidth;
	var innerHeight = $.browser.msie ? document.documentElement.clientHeight : window.innerHeight;
	var winWidth = innerWidth > document.body.offsetWidth ? innerWidth : document.body.offsetWidth;
	var winHeight = innerHeight > document.body.offsetHeight ? innerHeight : document.body.offsetHeight;
	var pageOffset = $.browser.msie ? document.documentElement.scrollTop : window.pageYOffset;

	$("body").append("<div id='filter' style='position: absolute; top: 0; left: 0; width: 100%; height: " + winHeight + "px; background-color: #FFFFFF; opacity: 0.7; filter: alpha(opacity=70)'></div>");
	$("body").append("<p id='error' style='position: absolute; top: " + (pageOffset + (innerHeight - 50) / 2) + "px; left:" + (innerWidth - 495) / 2 + "px'>" + message + "</p>");
	setTimeout("hideError()", 4000);
}

function hideError(){
	$("#filter").fadeOut("slow", function(){
		$("#filter").remove();
	});
	$("#error").fadeOut("slow", function(){
		$("#error").remove();
	});
}

// Cookie
function getExpDate(days, hours, minutes){
	var expDate = new Date();
	if(typeof days == "number" && typeof hours == "number" && typeof minutes == "number"){
		expDate.setDate(expDate.getDate() + parseInt(days));
		expDate.setHours(expDate.getHours() + parseInt(hours));
		expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
		return expDate.toGMTString();
	}
}

function getCookieVal(offset){
	var endstr = document.cookie.indexOf(";", offset);
	if(endstr == -1) {
		endstr = document.cookie.length;
	}
	return unescape(document.cookie.substring(offset, endstr));
}

function getCookie(name){
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while(i < clen){
		var j = i + alen;
		if(document.cookie.substring(i, j) == arg){
			return getCookieVal(j);
		}
		i = document.cookie.indexOf(" ", i) + 1;
		if(i == 0) break;
	}
	return "";
}

function setCookie(name, value, expires, path, domain, secure){
	document.cookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
}

function deleteCookie(name, path, domain) {
	if(getCookie(name)){
		document.cookie = name + "=" +
			((path) ? "; path=" + path : "") +
			((domain) ? "; domain=" + domain : "") +
			"; expires=Thu, 01-0Jan-70 00:00:01 GMT";
	}
}

function string2Array(str){
	var arr = new Array();
	if(str.charAt(0) == ","){
		str = str.substring(1);
	}
	if(str.charAt(str.length - 1) == ","){
		str = str.substring(0, str.length - 2);
	}
	str = str.replace(" ","");
	var flag = 0;
	while(flag == 0){
		if(str.indexOf(",") != -1){
			arr.push(str.substring(0, str.indexOf(",")));
			str = str.substring(str.indexOf(",") + 1);
		} else {
			arr.push(str);
			flag = 1;
		}
	}
	return arr;
}

function array2String(arr){
	var str = "";
	var flag = 0;
	for(i in arr){
		if(flag != 0){
			str += ",";
		} else {
			flag = 1;
		}
		str += arr[i];
	}
	return str;
}

