﻿var FLASH_UNAVAILABLE = 603;
var STREET_VIEW_DATA_UNAVAILABLE = 600;
var icon = new GIcon();
icon.image = "http://www.google.com/mapfiles/marker.png";
icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
icon.iconSize = new GSize(20, 34);
icon.shadowSize = new GSize(37, 34);
icon.iconAnchor = new GPoint(10, 34);

var localSearch = new GlocalSearch();

// ====== Create a Client Geocoder ======
var geo = new GClientGeocoder();

// ====== Array for decoding the failure codes ======
var reasons = [];
reasons[G_GEO_SUCCESS] = "Success";
reasons[G_GEO_MISSING_ADDRESS] = "Missing Address: The address was either missing or had no value.";
reasons[G_GEO_UNKNOWN_ADDRESS] = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
reasons[G_GEO_UNAVAILABLE_ADDRESS] = "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_BAD_KEY] = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
reasons[G_GEO_TOO_MANY_QUERIES] = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
reasons[G_GEO_SERVER_ERROR] = "Server error: The geocoding request could not be successfully processed.";

// ====== Create a Client Geocoder ======
var gdir = new GDirections(null);

function SetPostCode(givenPostCode) {
    var search = givenPostCode;
    // take a copy and convert to upper case
    var s = search.toUpperCase();
    // Replace punctuation and whitepsace by a single space
    s = s.replace(/\W+/g, " ");
    // Remove and trailing leading spaces
    s = s.replace(/^ /, "");
    s = s.replace(/ $/, "");
    // Perform the check
    var match = s.match(/^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$/);
    if (match) {
        // It is a UK Postcode, so call GDirections on the reformatted search string 
        showPostcode(s);
    }
}

// ====== Using GDirections to process a UK postcode ======
function showPostcode(search) {
    // Call GDirections
    gdir.loadFromWaypoints([search, search], { getPolyline: true });
    // Wait for the reply to come back
    GEvent.addListener(gdir, "load", function() {
        var poly = gdir.getPolyline();
        var point = poly.getVertex(0);
        
        

        var map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        
        var marker = new GMarker(point);
        map.addOverlay(marker);
        try {
            var latlngbounds = new GLatLngBounds();
            var cordinates;
            cordinates = point.toString();
            cordinates = cordinates.replace("(", "").replace(")", "").replace(" ", "");
            latlngbounds.extend(cordinates);
        }
        catch (err) { }
        // centre the map on the result
        map.setCenter(point, 16);
        map.checkResize();

    });
}

function usePointFromPostcode(postcode, callbackFunction) {
    localSearch.setSearchCompleteCallback(null,
            function() {
                if (localSearch.results[0]) {
                    var resultLat = localSearch.results[0].lat;
                    var resultLng = localSearch.results[0].lng;
                    var point = new GLatLng(resultLat, resultLng);
                    callbackFunction(point);                    
                }
                else {
                    alert("Postcode not found!");
                }
            });
    localSearch.execute(postcode + ", UK");
}

function setStreetView(point) {
    var cordinates;
    cordinates = point.toString(); ;
    cordinates = cordinates.replace("(", "").replace(")", "").replace(" ", "");

    var xAndy = cordinates.split(",");
    
    var fenwayPark = new GLatLng(xAndy[0], xAndy[1]);
    panoramaOptions = { latlng: fenwayPark };
    myPano = new GStreetviewPanorama(document.getElementById("streetView"), panoramaOptions);
    GEvent.addListener(myPano, "error", handleNoFlash);
}

function handleNoFlash(errorCode) {
    if (errorCode == FLASH_UNAVAILABLE) {
        alert("Error: Flash doesn't appear to be supported by your browser");
        return;
    }

    if (errorCode == STREET_VIEW_DATA_UNAVAILABLE) {
        var elem = document.getElementById("streetViewTab");
        
        if (elem != null) {
            elem.style.display = 'none';
        }
    }    
}

function createMarker(latlng, property_title, image_url, number_of_bedrooms, number_of_reception, property_url, price) {
    var marker = new GMarker(latlng);
    GEvent.addListener(marker, "click", function() {
        try {
            var html = "<table width='300px' cellpadding='0' cellspacing='0'><tr><td width='138px'><img src='" + image_url + "' alt='" + property_title + "' style='width:138px;height:106px;'></td>" + "<td><div class='contentStyle07b' style='padding-left:20px;'><a href='#' onclick='" + property_url + "'>" + property_title + "</a><q style='text-align:left;'>" + price + "</q><div class='col04'><ul><li class='item00'>" + number_of_bedrooms + "</li><li class='item01'>" + number_of_reception + "</li></ul></div></div></td></table>";
            marker.openInfoWindowHtml(html);
        }
        catch (err) { alert(err); }
    });
    return marker;
}

