$(document).ready(function(){
    hideDetail();
    $("#zip").blur(function(){
        if (IsPostId($("#zip").val())) {
            $.getJSON("modules/city/city.php", {
                zip: $("#zip").val()
            }, function(data){
                if (data.city.length > 0) {
                    selectState(data.city[0].abbrev);
                    selectSuburb(data.city);
                }
                else {
                    $("#postcodeMessage").remove();
                    $("#zip").parent().append("<div id=\"postcodeMessage\">您输入的4位 邮政编码不存在！请重新输入...</div>")
                    $("#zip").css("color", "red");
                }
            });
        }
        else {
            $("#postcodeMessage").remove();
            $("#zip").parent().append("<div id=\"postcodeMessage\">您输入的不是4位 邮政编码！请重新输入...</div>")
            $("#zip").css("color", "red");
        }
    });
    $("#city").livequery('change', function(){
        $("#address").focus();
    })
    $("#zip").focus(function(){
        hideDetail();
    })
});

function selectState(state){
    $("#state").parent().show();
    $("#state > option").map(function(){
        if ($(this).attr("name") == state) {
            $(this).attr("selected", "selected");
        }
    })
}

function selectSuburb(city){
    $("#city").parent().show();
    if (city.length > 1) {
        var output = '<select id="city" class="required" name="city">';
        output += '<option value="">请选择您所在的Suburb</option>';
        for (i = 0; i < city.length; i++) {
            output += '<option value="' + city[i].suburb + '">' + city[i].suburb + '</option>';
        }
        output += '</select>';
        $("#city").replaceWith(output);
        $("#city").focus();
    }
    else {
        $("#city").replaceWith('<input type="text" size="35" value="" id="city" name="city" class="required"/>')
        $("#city").val(city[0].suburb);
        $("#address").focus();
    }
    $("#postcodeMessage").remove();
    $("#zip").css("color", "black");
}

function hideDetail(){
    $("#state").parent().hide();
    $("#city").parent().hide();
}

function getZip(){
    var zip = $("#zip").val();
    return zip;
}

// Check postcode is 4 digital number
function IsPostId(str){
    var reg = /^\d{4}$/;
    return reg.test(str);
}
