var can_validate_after_post = false;
var loginIntervalID = null;
var old_zip_url = null;

function trim(stringToTrim) {
	return stringToTrim.replace(/^\/+|\/+$/g,"");
}

$j(document).ready(function(){
   $j('select#register_form_county').change(function(){
       $j('select#register_form_city').html('');
       $j('select#register_form_village').html('');
       $j.get('/feeds/cities/'+$j('select#register_form_county').val(), null, function(data){
            $j('select#register_form_city').html(data);
            if ($j('input#city').val()) {
                $j('select#register_form_city').val($j('input#city').val());
                $j('select#register_form_city').change();
                $j('input#city').val('');
            } else {
                can_validate_after_post = true;
                validate_after_post_register_form();
            }
       }, 'html');
   });

   $j('select#register_form_city').change(function(){
       $j('select#register_form_village').html('');
       $j.get('/feeds/villages/'+$j('select#register_form_city').val(), null, function(data){
            $j('select#register_form_village').html(data);
            if ($j('input#village').val()) {
                $j('select#register_form_village').val($j('input#village').val());
                $j('input#village').val('');
                can_validate_after_post = true;
                validate_after_post_register_form();
            }
       }, 'html');
   });

    validate_after_post_register_form();

    $j('a#find_zip_code').click(function(){
        clearInterval( loginIntervalID );
        loginIntervalID = setInterval ("CheckPopupClose()", 500);
    });


});

function CheckPopupClose() {
    if ( window.location.hash == "#close-pp" ) {
        window.location.hash = "close-pp-old";
        clearInterval( loginIntervalID );
        $j('a.pp_close').click();
    }
    return false;
}

$j(document).ready(function(){
    $j('select#register_form_county,select#register_form_city,select#register_form_village').change(function(){
        updateZipCodeLink();
    });
});

function updateZipCodeLink() {
    var county_id = parseInt($j('select#register_form_county').val());
    var city_id = parseInt($j('select#register_form_city').val());
    var village_id = parseInt($j('select#register_form_village').val());

    if (county_id == NaN) county_id = 0;
    if (city_id == NaN) city_id = 0;
    if (village_id == NaN) village_id = 0;
    if (old_zip_url == null) {
        old_zip_url = $j('a#find_zip_code').attr('href');
    }

    var url = '/'+trim('zip-codes/'+county_id+'/'+city_id+'/'+village_id);
    var new_zip_url = old_zip_url.replace('/zip-codes', url);
    $j('a#find_zip_code').attr('href', new_zip_url);
}