var zip_add1;
var zip_add2;

function getAddress(fname, compName, add1, add2)
{
	var zip1 = document.forms[fname].elements[compName + "_1"].value;
	var zip2 = document.forms[fname].elements[compName + "_2"].value;

	if (zip1.length == 3 && checkIsNumber(zip1))
	{
		if (zip2.length == 4 && checkIsNumber(zip2))
		{
			zipcode = zip1 + zip2;
		}
		else
		{
			zipcode = zip1;
		}

		zip_add1 = add1;
		zip_add2 = add2;

		var url = '/address';
		var pars = 'zipcode=' + zipcode;

		$.get(url, pars, showAddress);
	}
	else
	{
		alert("入力された郵便番号が不正です。");
	}
}

function showAddress(message, status)
{
	var response = message;
	if (response != "" && response.indexOf("ERROR") == -1)
	{
		var address = response.split(":");

		if (zip_add1 !="")
		{
			var prefecture = document.getElementById(zip_add1);
			var count = prefecture.options.length;

			for (var i = 0; i < count; i++)
			{
				if (prefecture.options[i].value == address[0])
				{
					prefecture.selectedIndex = i;
					break;
				}
			}
		}

		if (zip_add2 != "")
		{
			document.getElementById(zip_add2).value = address[1];
		}
	}
	else
	{
		alert("入力された郵便番号が不正です。住所が見つかりません。");
	}

}

function checkIsNumber(value){
    return (value.match(/[0-9]+/g) == value);
  }

