Location = function () {
    var success = false;
    this.init = function (info) {
        var t = this;
        if (typeof google !== 'undefined') {
        if (google.loader.ClientLocation != null) {
            var country = google.loader.ClientLocation.address.country_code;
            var region = google.loader.ClientLocation.address.region;
            if (country == 'GB') country = 'UK';
            weatherApp.country = country;
            weatherApp.region = region;
        }
        }

        if (t.is_latlong(info)) {
            t.splitLatLong(info);
            $(document).trigger("location.found");
            return;
        }

        if (info != '') {
            var words = info.trim().split(' ');
            if ((words.length == 1) && (-1 == info.indexOf(','))) {
              info = info + ', ' +weatherApp.country;
            } else {
              if ((words.length > 1) && (-1 == info.indexOf(','))) {
                var p = info.lastIndexOf(' ');
                info = info.substr(0,p)+','+info.substr(p);
              }
            }
            if (t.is_address(info)) {
                t.getLatLong(info);
                return;
            }
        } else {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(

                function (position) {

                    // Did we get the position correctly?
                    // alert (position.coords.latitude);
                    // To see everything available in the position.coords array:
                    //for (key in position.coords) {alert(key)}
                    weatherApp.coords = position.coords;
                    var latLong = position.coords.latitude + ', ' + position.coords.longitude;
                    t.getAddress(latLong);
                },
                // next function is the error callback


                function (error) {
                    var msg;
                    switch (error.code) {
                    case error.TIMEOUT:
                        msg = 'Timeout';
                        break;
                    case error.POSITION_UNAVAILABLE:
                        msg = 'Position unavailable';
                        break;
                    case error.PERMISSION_DENIED:
                        msg = 'Permission denied';
                        break;
                    case error.UNKNOWN_ERROR:
                        msg = 'Unknown error';
                        break;
                    }
                    alert(msg + ' when trying to find your location so using defaults.');
                    weatherApp.coords = weatherApp.defaultCoords;
                    $(document).trigger("location.found");
                });

            }
            else { // finish the error checking if the client is not compliant with the spec
                alert("Can't find you, using Southampton, UK instead.");
                weatherApp.coords = weatherApp.defaultCoords;
                $(document).trigger("location.found");
            }

          return;
        }

        $.post("Maps/getinfo.php", {
            p: info,
            c: weatherApp.country
        }, function (html) {
            var html = html.trim();
            var latlong = '';
            this.location = '';
            if (html.length > 0) {
                if (html.substr(0, 1) == '@') {
                    var address = html.substr(1);
                    t.getLatLong(address);
                    return;
                }
                var p = html.indexOf("=");

                if (p != -1) {
                    latlong = html.substr(0, p);
                    this.location = html.substr(p + 1);
                }
            }
            if (latlong == '') {
                var Lat = '';
                if (google.loader.ClientLocation != null) {
                    Lat = google.loader.ClientLocation.latitude;
                    var Long = google.loader.ClientLocation.longitude;
                }
                if (Lat == '') {
                    alert('No location data found. Setting default...');
                    weatherApp.coords = weatherApp.defaultCoords;
                } else {
                    t.splitLatLong(Lat + ',' + Long);
                }

            } else {
                t.splitLatLong(latlong);
            }
            $(document).trigger("location.found");
        }, "html");
    }

    this.is_postcode = function (info) {
        var c = 0;

        if (info.length < 5) return false;
        if (info.length > 8) return false;

        for (var i = 0; i < info.length; i++) {
            var cx = info.substr(i, 1);
            cx = cx.toUpperCase();
            if (cx == ' ') c++;
            if (0 > 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '.indexOf(cx)) return false;
        }

        cx = (info.substr(0, 1)).toUpperCase();
        if (0 > 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(cx)) return false;

        if (c > 1) return false;
        return true;
    }

    this.is_latlong = function (info) {
        var p = 0;
        var c = 0;
        for (var i = 0; i < info.length; i++) {
            if (0 > ('0123456789-., '.indexOf(info.substr(i, 1)))) return false;
            if (info.substr(i, 1) == '.') p++;
            if (info.substr(i, 1) == ',') c++;
        }
        if (p == 0) return false;
        if (p > 2) return false;
        if (c > 1) return false;
        if ((c == 1) && (p != 2)) return false;
        return true;
    }

    this.is_address = function (info) {
        info = trim(info);
        if (info.substr(0, 1) == '@') return false;
        var c = 0;
        for (var i = 0; i < info.length; i++) {
            if (info.substr(i, 1) == ' ') c++;
            if (info.substr(i, 1) == ',') c++;
        }
        var p = info.indexOf(' ');
        if (p == 1) {
            var cx = info.substr(0, 1).toUpperCase();
            if ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(cx) > -1) return false;
        }
        if (c < 2) return false;
        return true;
    }

    this.getLatLong = function (address) {
        var t = this;
        var geocoder = new google.maps.Geocoder();
        if (geocoder) {
            geocoder.geocode({
                'address': address
            }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    weatherApp.coords.latitude = results[0].geometry.location.lat();
                    weatherApp.coords.longitude = results[0].geometry.location.lng();
                    t.getAddress(weatherApp.coords.latitude + ',' + weatherApp.coords.longitude);
                } else {
                    alert("Geocode for '" + address + "' was not successful for the following reason: " + status);
                    weatherApp.coords = weatherApp.defaultCoords;
                    $(document).trigger("location.found");
                }
            });
        }
    }

    this.splitLatLong = function (latlong) {
        var t = this;
        var p = latlong.indexOf(',');
        weatherApp.coords.latitude = latlong.substr(0, p).trim();
        weatherApp.coords.longitude = latlong.substr(p + 1).trim();
    }

    this.getAddress = function (latlong) {
        var geocoder = new google.maps.Geocoder();
        if (geocoder) {
            var latlngStr = latlong.split(",", 2);
            var glat = parseFloat(latlngStr[0]);
            var glng = parseFloat(latlngStr[1]);
            var latlng = new google.maps.LatLng(glat, glng);
            geocoder.geocode({
                'latLng': latlng
            }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    weatherApp.address = results[0].formatted_address;

                } else {
                    alert("Geocode for '" + latlong + "' was not successful for the following reason: " + status);
                }
                weatherApp.myLocation = latlong;
                $(document).trigger("location.found");
            });
        }
    }
}

