var customIcon = new GIcon();
customIcon.image = "/Content/2009/images/googleMaps/pointer.png";
customIcon.shadow = "/Content/2009/images/googleMaps/shadow.png";
customIcon.iconSize = new GSize(32, 32);
customIcon.shadowSize = new GSize(49, 32);
customIcon.iconAnchor = new GPoint(16, 24);
customIcon.infoWindowAnchor = new GPoint(16, 16);

var clientCode = true;
var prevAccuracy = -1;

// Address class
function Address(streetAddress, friendlyName, latLng) {
    this.friendlyName = friendlyName;
    this.streetAddress = streetAddress;
    this.latLng = latLng;
}

function Initialize() {
    $('[id$=_ImageButton1]').click(GetZipFromAddress);
    if (GBrowserIsCompatible()) {
        setTimeout(function () {
        var geoCoder = new GClientGeocoder();
        if (geoCoder) {
            $(addresses).each(
				function(index, address) {
				    address.streetAddress = address.streetAddress.replace(/\bSPACE\b/, 'SUITE').replace(/\bSPC\b/, 'STE');
				}
			);

            $(addresses).each(
				function(index, address) {
				    var point;
				    if (address.latLng) {
				    var split = address.latLng.split(',');
				        point = new GLatLng(split[0], split[1]);
				    }
				    SetLatLngForAddress(address, point);
				}
			);
        }

        if (addresses.length > 0) {
            MapAddresses();
        }
        else {
            SetDefaultMap();
        }
        }, 100);
    }
}

function SetDefaultMap() {
    var zoom = false;
    var map = GetMap(zoom);
    //map.setCenter(new GLatLng(59.5, -98.5), 3);
    //map.setCenter(new GLatLng(39.50, -98.35), 3);
    map.setCenter(defaultLatLng, 3);
    map.clearOverlays();
}

function SetLatLngForAddress(address, latLng) {
    address.googleCallbackComplete = true;

    if (latLng) {
        address.latLng = latLng;
    }
    else {
        address.latLng = undefined;
    }
}

function MapAddresses() {
    var addressesWithLatLng = [];
    $(addresses).each(
		function(index, address) {
		    if (address.latLng) {
		        addressesWithLatLng.push(address);
		    }
		}
	);

    if (addressesWithLatLng.length == 0) {
        SetDefaultMap();
        return;
    }

    var bounds = new GLatLngBounds(addressesWithLatLng[0].latLng, addressesWithLatLng[0].latLng);

    $(addressesWithLatLng).each(
		function(index, address) {
		    if (address.latLng) {
		        bounds.extend(address.latLng);
		    }
		}
	);

    var zoom = true;
    var map = GetMap(zoom);
    map.clearOverlays();
    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds) - 1);

    $(addressesWithLatLng).each(
		function(index, address) {
		    if (address.latLng) {
		        var marker = new GMarker(address.latLng, { icon: customIcon });

		        GEvent.addListener(marker, "click", function() {
		            marker.openInfoWindowHtml(address.friendlyName);
		        });

		        map.addOverlay(marker);
		        if (addressesWithLatLng.length == 1) {
		            marker.openInfoWindowHtml(address.friendlyName);
		        }
		    }
		}
	);
}

function GetMap(zoom) {
    var map = new GMap2(document.getElementById("map_canvas"));
    map.addControl(new GMapTypeControl());
    if (zoom) {
        map.addControl(new GSmallMapControl());
    }
    else {
        map.disableDoubleClickZoom();
    }
    return map;
}

function ShowStoreLocation(itemIndex) {
    var zoom = true;
    var map = GetMap(zoom);
    var geocoder = new GClientGeocoder();

    if (geocoder) {
        var point = addresses[itemIndex].latLng;
        if (point) {
            map.setCenter(point, 13);
            var marker = new GMarker(point, { icon: customIcon });
            map.addOverlay(marker);
            marker.openInfoWindowHtml(addresses[itemIndex].friendlyName);
            window.scrollTo(0, 0);
        }
        else {
            SetDefaultMap();
            //alert('We\'re sorry, this location cannot be mapped.');
            $('#map_canvas').hide();
        }
    }


}

function ShowNewStoreLocation(streetAddress, friendlyName, latLng) {
    var itemIndex = AddAddress(streetAddress, friendlyName, latLng);
    Initialize();
    ShowStoreLocation(itemIndex);
}

function AddAddress(streetAddress, friendlyName, latLng) {
    var rtrn = -1;
    if (addresses) {
        addresses.push(new Address(streetAddress, friendlyName, latLng));
        rtrn = addresses.length - 1;
    }
    return rtrn;
}

function GetZipFromAddress() {
    if ((clientCode == true) && notZipCode($('[id$=_genericlocation]').val()) && isValidAddress($('[id$=_genericlocation]').val())) {
        prevAccuracy = -1;
        GeoCodeAddress($('[id$=_genericlocation]').val());
        return false;
    }
    else {
        return true;
    }
}

function GeoCodeAddress(address) {
    try {
        var postalCode = null;
        var curAccuracy = -1;
        var geoCoder = new GClientGeocoder();
        var i = 0;
        if (geoCoder) {
            geoCoder.getLocations(address, function(result) {
                if (result.Status.code == G_GEO_SUCCESS) {
                    //data with accuracy level > 4 will have zip codes
                    for (i = 0; i < result.Placemark.length; i++) {
                        var placemark = result.Placemark[i];

                        postalCode = GetPropertyValue(placemark, "AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber");

                        if (postalCode == null) {
                            postalCode = GetPropertyValue(placemark, "AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber");
                        }

                        if (postalCode == null) {
                            postalCode = GetPropertyValue(placemark, "AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.DependentLocality.PostalCode.PostalCodeNumber");
                        }

                        if (postalCode == null) {
                            var plAddr = placemark.address.replace(/\,/g, '');
                            var plAddressParts = plAddr.split(' ');
                            if (plAddressParts.length > 3 && IsZipValid(plAddressParts[plAddressParts.length - 2])) {
                                postalCode = plAddressParts[plAddressParts.length - 2];
                            }
                        }

                        if (postalCode != null) {
                            break;
                        }

                        curAccuracy = result.Placemark[0].AddressDetails.Accuracy;
                    }

                    if (postalCode != null) {
                        $('[id$=_genericlocation]').val(postalCode);
                        GeoCodingComplete();
                    }
                    else if (curAccuracy > prevAccuracy) {
                        prevAccuracy = curAccuracy;
                        GeoCodeAddress(result.Placemark[0].Point.coordinates[1] + ',' + result.Placemark[0].Point.coordinates[0]);
                    }
                    else {
                        GeoCodingComplete();
                    }
                }
                else {
                    GeoCodingComplete();
                }
            });
        }
    }
    catch (err) {
        GeoCodingComplete();
    }
}

function IsZipValid(val) {
    var rgxZip = /^\d{5}$|^\d{5}-\d{4}$/;
    return rgxZip.test(val);
}


function GetPropertyValue(obj, property) {
    property = property.split(".");
    for (i in property) {
        var key = property[i];
        if (obj[key] == null)
            return null;
        obj = obj[key];
    }
    return obj;
}

function notZipCode(zipcode) {
    if (typeof parseInt(zipcode) == 'number' && zipcode.toString().length == 5) {
        return false;
    }
    else {
        return true;
    }
}

function isValidAddress(address) {
    var regEx = /^[a-zA-Z\s\.]+,[\s]?[a-zA-Z\s]+$|^\d{5}(-\d{4})?$/;
    return regEx.test(address)
}

function GeoCodingComplete() {
    clientCode = false;
    $('[id$=_ImageButton1]').click();
}

$(document).ready(Initialize);
$(window).unload(GUnload);


