/** 
   ****************************
     Geolocation library
     Language Jobs Ltd
     Devis Lucato 2009
   ****************************
*/

var geo_validator_timer_1 = 0
var geo_waiting_for_validation = true
var geo_addressischanged = false

var geo_last_validated = ''

var entered_country
var entered_postcode
var entered_city

var ie6 = ($.browser.msie && $.browser.version.substring(0,1) == '6')

// *****************************************************************************************

function user_changed_address(changed_field) {
        tmp_addresstovalidate = get_address_to_validate()
        if ( tmp_addresstovalidate != '' && tmp_addresstovalidate != geo_last_validated ) {
                if ( changed_field == 'country' && entered_postcode == '' && entered_city == '' ) {
                        hide_guessed_address()
                        set_postcode_label()
                        // wait for postal code or city
                } else {
                        geo_start_waiting_for_validation()
                        hide_guessed_address()
                        set_postcode_label()
                        geo_validate_address()
                }
        }
        geo_validator_timer_1 = 0
}

function initialize_geolocator() {
        geo_start_waiting_for_validation()
        hide_guessed_address()
        
        $('#country_of_residence').change(function () {
                if ( geo_validator_timer_1 == 0 ) {
                        geo_validator_timer_1 = 1
                        user_changed_address('country')
                }
        })
        
        $('#postcode').change(function () {
                if ( geo_validator_timer_1 == 0 ) {
                        geo_validator_timer_1 = 1
                        user_changed_address('postcode')
                }
        })
        
        $('#city').change(function () {
                if ( geo_validator_timer_1 == 0 ) {
                        geo_validator_timer_1 = 1
                        user_changed_address('city')
                }
        })
        
        $('#postcode').bind('keyup',function () {
                geo_start_waiting_for_validation()
        })
        
        $('#city').bind('keyup',function () {
                geo_start_waiting_for_validation()
        })
        
        $('#overridepostcode').change(function () {
                if ( $('#overridepostcode').is(':checked') ) {
                        $('#postcode').val('')
                        $('#postcode').attr('disabled',true)
                        geo_validate_address()
                } else {
                        $('#postcode').attr('disabled',false)
                }
        })
        set_postcode_label()
        geo_stop_waiting_for_validation()
}

function geolocation_onload() {
        initialize_geolocator()
        geo_validate_address()
}

// *****************************************************************************************

function strtrim(str) {
        /* Thanks http://blog.stevenlevithan.com/archives/faster-trim-javascript */
        var     str = str.replace(/^\s\s*/, ''),
                ws = /\s/,
                i = str.length;
        while (ws.test(str.charAt(--i)));
        return str.slice(0, i + 1);
}
function clean_string(string_text) {
        string_text = string_text.replace('\n','')
        string_text = string_text.replace('\r','')
        string_text = string_text.replace('\t','')
        return string_text
}

// *****************************************************************************************

function get_address_to_validate() {
        
        $('#postcode').val(strtrim($('#postcode').val()))
        $('#city').val(strtrim($('#city').val()))
        entered_country = $('#country_of_residence').children("[@selected]").attr('iso_code')
        entered_postcode = $('#postcode').val()
        entered_city = $('#city').val()
        
        if ( typeof( entered_country ) == "undefined" ) entered_country = ''
        if ( typeof( entered_postcode ) == "undefined" ) entered_postcode = ''
        if ( typeof( entered_city ) == "undefined" ) entered_city = ''
        
        entered_country = clean_string(entered_country)
        entered_postcode = clean_string(entered_postcode)
        entered_city = clean_string(entered_city)
        
        result = ''
        if ( entered_postcode != '' ) {
                if ( entered_city != '' ) {
                        result = entered_postcode+", "+entered_city+", "+entered_country
                } else {
                        result = entered_postcode+", "+entered_country
                }
        } else {
                if ( entered_city != '' ) {
                        result = entered_city+", "+entered_country
                } else {
                        result = entered_country
                }
        }
        
        return result
}

function validate_postcode() {
        entered_country = $('#country_of_residence').children("[@selected]").attr('iso_code')
        entered_postcode = $('#postcode').val()
        return ($('#overridepostcode').is(':checked') || lj_postcode_validation(entered_country,entered_postcode,'validate'))
}

function geo_validate_address() {
        mark_address_as_notchecked()

        tmp_addresstovalidate = get_address_to_validate()
        
        postcode_validation_passed = validate_postcode()
        
        if ( postcode_validation_passed ) {
                if ( entered_country != '' ) {
                        $.getJSON("/geolocation.php?gc=" + entered_country + "&gt=" + entered_city + "&gp=" + entered_postcode,
                                function(data){
                                        getAddressServerSide(data)
                                }
                        );
                        geo_last_validated = tmp_addresstovalidate
                }
        } else {
                geo_stop_waiting_for_validation()
                mark_postcode_as_wrong()
        }
}

function getAddressServerSide(data) {
        if (data != null) {
                if (!data.error) {
                        mark_address_as_correct()
                        set_guessed_address(data.detail)
                        show_guessed_address()
                        geo_stop_waiting_for_validation()
                } else {
                        mark_address_as_wrong('Y')
                        hide_guessed_address()
                        geo_stop_waiting_for_validation()
                }
        } else {
                mark_address_as_wrong('Y')
                hide_guessed_address()
                geo_stop_waiting_for_validation()
        }
}

// *****************************************************************************************

function mark_address_as_notchecked() {
        if ( !ie6 ) {
                $(".address_warn_ico").removeClass('correct_address_ico')
                $(".address_warn_ico").removeClass('wrong_address_ico')
        }
}
function mark_address_as_wrong(isPostcodeFormatCorrect) {
        $('#validaddress').val('N')
        if ( entered_postcode != '' ) {
                if ( !ie6 ) {
                        $("#postcode_warn_ico").addClass('wrong_address_ico')
                }
                if ( isPostcodeFormatCorrect == 'Y' ) {
                        show_postcode_override_option()
                }
        }
        if ( entered_city != '' ) {
                if ( !ie6 ) {
                        $("#city_warn_ico").addClass('wrong_address_ico')
                }
                $('#validcity').val('N')
        } else {
                $('#validcity').val('Y')
        }
}
function mark_postcode_as_wrong() {
        $('#validaddress').val('N')
        if ( entered_postcode != '' ) {
                if ( !ie6 ) {
                        $("#postcode_warn_ico").addClass('wrong_address_ico')
                }
        }
}
function mark_address_as_correct() {
        $('#validaddress').val('N')
        if ( entered_postcode != '' ) {
                if ( !ie6 ) {
                        $("#postcode_warn_ico").addClass('correct_address_ico')
                }
                hide_postcode_override_option()
                $('#validaddress').val('Y')
        } else {
                if ( entered_city != '' ) {
                        if ( !ie6 ) {
                                $("#city_warn_ico").addClass('correct_address_ico')
                        }
                        $('#validcity').val('Y')
                }
        }
}

function show_guessed_address() {
        $('#guessed_address_container').show()
}
function hide_guessed_address() {
        //$('#guessed_address_container').hide()
        $("#guessed_address").empty()
        $("#guessed_address").append('...')
        
}
function set_guessed_address(address_text) {
        $("#guessed_address").empty()
        $("#guessed_address").append(address_text)
}
function show_postcode_override_option() {
        $('#postcode_override_form').show()
}
function hide_postcode_override_option() {
        $('#postcode_override_form').hide()
}

function set_address_geolocation(lat,lng) {
        $('#latitude').val(lat)
        $('#longitude').val(lng)
}
function set_postcode_label() {
        entered_country = $('#country_of_residence').children("[@selected]").attr('iso_code')
        suggest_postcode_format(entered_country)
        postcode_setting = $('#country_of_residence').children("[@selected]").attr('postcode')
        if ( postcode_setting == 'Y' ) {
                $('#label_postcode_if_available').hide();
                $('#label_postcode').show();
                if ( $('#overridepostcode').is(':checked') ) {
                        show_postcode_override_option()
                        $('#postcode').attr('disabled',true)
                } else {
                        hide_postcode_override_option()
                        $('#postcode').attr('disabled',false)
                }
        } else {
                $('#label_postcode').hide();
                $('#label_postcode_if_available').show();
                show_postcode_override_option()
        }
}
function suggest_postcode_format(entered_country) {
        $('#postcode_format').empty()
        jsvar_postcode_format = lj_postcode_format(entered_country)
        if ( jsvar_postcode_format != '' ) {
                jsvar_postcode_format = '&nbsp; ['+jsvar_postcode_format+']'
        }
        $('#postcode_format').append(jsvar_postcode_format)
}

// *****************************************************************************************

function geo_start_waiting_for_validation() {
        geo_waiting_for_validation = true
}
function geo_stop_waiting_for_validation() {
        geo_waiting_for_validation = false
}
function set_null_geolocation() {
        set_address_geolocation(999,999)
}