/*
$(document).ready(function () {
    $("#map").css({
        height: 500,
        width: 600
    });
    var myLatLng = new google.maps.LatLng(17.74033553, 83.25067267);
    MYMAP.init('#map', myLatLng, 11);

    $("#showmarkers").click(function (e) {
        MYMAP.placeMarkers('markers.xml');
    });
});
*/

// jQuery onLoad
$(function() {
	function setEqualHeight() {
		var maxHeight = 0;
		var $max;
		$("#content > .column").each(function() {
			var $this = $(this);
			var height = $this.height();
			if (height > maxHeight) {
				maxHeight = height;
				$max = $this;
			}
		}).not($max).css("min-height", maxHeight);
	}
	// setEqualHeight();

	$("a[rel='external']").click(function(event) {
		window.open($(this).attr("href"));
		event.preventDefault();
	});

	$("a.email").text(function() {
		return $(this).text() + "@qualifiedproperties.com";
	}).attr("href", function() {
		return "mailto:" + $(this).text();
	});

	if (0 < $(".validate").length) {
		$("label.required").append(" <em>*</em>");

		$.getScript("/s/js/jquery.validate.min.js", function() { 
			$("form").validate();
		});
	}

	var $listingImage = $("div.listing-image");
	if (1 == $listingImage.length) {
		$("ul.gallery li img").hover(
			function() { 
				var src = $(this).attr("src").replace("?115", "");
				$listingImage.children("a").attr("href", src + "?850").children("img").attr("src", src + "?350");
			}, 
			function() { /* out */ }
		);
	}

	$(".colorbox").colorbox();
});

// Google Maps v3 APIs
var loadMaps = function () {
    var map = document.getElementById("map") || null;
    if (null == map || !map) {
        return;
    }

    if ("function" === typeof loadMaps.beforeLoadCallback) {
        loadMaps.beforeLoadCallback(map);
    }

    function mapsLoaded() {
        var houston = new google.maps.LatLng(29.76317, -95.362587);
        var latlng = new google.maps.LatLng(29.663667, -95.173016);

        var myOptions = {
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: false,
            navigationControl: true,
            navigationControlOptions: google.maps.NavigationControlStyle.SMALL,
            zoom: "undefined" != typeof loadMaps.zoom ? loadMaps.zoom : 11
        };
        var gmap = new google.maps.Map(map, myOptions);

        MYMAP.map = gmap;
        MYMAP.bounds = new google.maps.LatLngBounds();
        MYMAP.geocoder = new google.maps.Geocoder(); 

        if ("function" === typeof loadMaps.afterLoadCallback) {
            loadMaps.afterLoadCallback(gmap);
        }

        if ("undefined" == typeof loadMaps.marker) {
            loadMaps.marker = {
                title: "Get Driving Directions",
                click: function (gmap, marker) {
                    // infowindow.open(gmap, marker);
                }
            };
        }

        var mapLoad = google.maps.event.addListener(gmap, "tilesloaded", function () {
            $(map).addClass("gmap");
            google.maps.event.removeListener(mapLoad);
        });

        var icon = new google.maps.MarkerImage(
			"/s/img/fox.png",
			new google.maps.Size(24, 25),
      			new google.maps.Point(0, 0),    // origin  
			new google.maps.Point(12, 12)   // anchor
		);

        var marker = new google.maps.Marker({
            position: latlng,
            icon: icon,
            map: gmap,
            title: loadMaps.marker.title
        });

        google.maps.event.addListener(marker, "click", function () {
            loadMaps.marker.click(gmap, marker);
        });

        MYMAP.placeMarkers("/markers.ashx");
    }

    google.load("maps", "3.4", { "callback": mapsLoaded, "other_params": "sensor=false" });
    $(window).unload(function () { if ("undefined" != typeof GUnload) GUnload(); });
}

// Load Google Maps when ready
if ("undefined" !== typeof google) {
	google.setOnLoadCallback(function() {
		loadMaps();
	});
}

function updatePropertyLocation(propertyGuid, latitude, longitude) {
    var jsonText = JSON.stringify({ propertyGuid: propertyGuid, latitude: latitude, longitude: longitude });
    $.ajax({
        url: "/listings/default.aspx/UpdatePropertyLocation",
        data: jsonText,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
}

var MYMAP = {
    map: null,
    bounds: null,
    geocoder: null,
    infoWindows: null
}

/*
MYMAP.init = function (selector, latLng, zoom) {
    var myOptions = {
        zoom: zoom,
        center: latLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    this.map = new google.maps.Map($(selector)[0], myOptions);
    this.bounds = new google.maps.LatLngBounds();
}
*/

function showAddress(data) {
	if (!data)
		return;

    MYMAP.geocoder.geocode({ "address": data.address }, function (results, status) {
        if (status != google.maps.GeocoderStatus.OK) {
            return;
        }

        var lat = results[0].geometry.location.lat();
        var lng = results[0].geometry.location.lng();
        var point = new google.maps.LatLng(lat, lng);

        showPoint(point, data);
        updatePropertyLocation(data.guid, lat, lng);
    });
}

function showPoint(point, data) {
    if (!point) {
        // alert(address + " not found");
        return;
    }

    var marker = new google.maps.Marker({
        icon: "http://labs.google.com/ridefinder/images/mm_20_" + ( 'L' == data.type ? "green" : "blue" ) + ".png",
        position: point,
        map: MYMAP.map
    });

    var html = '<strong>' + data.name + '</strong><br />[ <a href="' + data.url + '">View Listing</a> ]';
    google.maps.event.addListener(marker, 'click', function () {
        MYMAP.infoWindow.close();
        MYMAP.infoWindow.setContent(html);
        MYMAP.infoWindow.open(MYMAP.map, marker);
    });

    // extend the bounds to include the new point
    // MYMAP.bounds.extend(point);
}

MYMAP.placeMarkers = function (filename) {
    MYMAP.infoWindow = new google.maps.InfoWindow();
    $.get(filename, function (xml) {
        /*
        $(xml).find("marker").each(function () {

            var guid = $(this).find('guid').text();
            var name = $(this).find('name').text();
            var url = $(this).find('url').text();
            var type = $(this).find('type').text();
            var address = $(this).find('address').text();
            var description = $(this).find('description').text();
        */

        jQuery.each(__markers, function () {
            var guid = this.guid;
            var name = this.name;
            var url = this.url;
            var type = this.type;
            var address = this.address;

            // create a new LatLng point for the marker
            var lat = this.lat || 0;
            var lng = this.lng || 0;
            var point = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));

            var data = {
                guid: guid,
                type: type,
                name: name,
                address: address,
                url: url,
                lat: lat,
                lng: lng
            };

            if (lat && lng && point) {
                showPoint(point, data);
            }
            else {
                showAddress(data);
            }
        });
    });
}
