jQuery(document).ready(function() {

    var markers = [];
    var markersFlat = [];
    var markerGroups = { "byron-bay": [], "ballina": [], "lennox": [], "suffolk-park": [] };

    var areaFilter;
    var bedroomsFilter;
    var bathroomsFilter;

    var currentProperty; // ID of the current property

	var mapCenter = new GLatLng(-28.65593719213315, 153.61714767456055);

    if (GBrowserIsCompatible()) {

        var map = new GMap2(document.getElementById("map"));
        map.setCenter(mapCenter, 14);
        map.addControl(new GSmallMapControl());
        map.setMapType(G_SATELLITE_MAP);
		
		
        // position the map		
        var bounds = null;
        var bounds = map.getBounds();
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();
        var lngSpan = northEast.lng() - southWest.lng();
        var latSpan = northEast.lat() - southWest.lat();

        function reCenter() {
            var windowWidth = $(window).width();
            var windowHeight = $(window).height();
            var sidebarWidth = $('#masthead').width();
            var newCenterx = (windowWidth - 500) / 2;
            var newCentery = windowHeight / 2;

            var newCenter = new GPoint(newCenterx, newCentery);
            map.setCenter(map.fromContainerPixelToLatLng(newCenter), 14);
        }

        reCenter();

        // on unload
        $(window).unload(function() { GUnload(); });

    }


    GDownloadUrl("/xml/markerdata.xml.aspx", function(data) {
        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
            var id = markers[i].getAttribute("id");
            var name = markers[i].getAttribute("name");
            var address = markers[i].getAttribute("address");
			var web = markers[i].getAttribute("web");
            var area = markers[i].getAttribute("area");
            var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                    parseFloat(markers[i].getAttribute("lng")));
            var marker = createMarker(id, point, name, address, area, web);
            map.addOverlay(marker);
        }
    });
	
	
$('.markerLink').live("click", function() {
		//alert('!');
		var property = $(this).attr('href');
		property = property.substring(1,property.length); 
		openPropertyPage(property);
		return false;
       });

	

    function createMarker(id, point, name, address, area, web) {
        var marker = new GMarker(point, { title: name });
        marker.point = point;
        marker.name = name;
        marker.address = address;
		marker.web = web;
        markerGroups[area].push(marker);
        markersFlat.push(marker);
        markers[id] = marker;
        var html = "<a style='color:#000;' href='#"+id+"' class='markerLink'>" + name + "</a><br />"+address + "<br/><a style='color:#000;border-bottom:1px #000 solid' href='" + web + "'  target='_blank'>" + web + "</a>";
        GEvent.addListener(marker, 'click', function() {
            marker.openInfoWindowHtml(html);
            selectResult($('#' + id));
            // scroll result table
            //$('#firstPanel').scrollTo('#' + id, 500);
            // go back to first panel
			//$('#panels').animate({left:"0"},'fast');
			openPropertyPage(id);

        });
        return marker;
    }



    // result selection

    function selectResult(tr) {
        $('#results tr').removeClass("selected");
        $(tr).addClass("selected");
    }


    // Select property
    $('#results tr').each(function(r) {
        var id = $(this).attr('id');
        $(this).click(function() {
            id = $(this).attr('id');
            map.closeInfoWindow();
            selectResult($(this));
            showMarker(id);
        });
        $(this).find('a').click(function() {
            showMarker(id);
            openPropertyPage(id);
        })
    })


    // Adjust scrolling panels (.panel) height	

    function adjustColumnHeight() {
        $('#maincontent .panel').each(function() {
            $(this).css('height', $(window).height() - $('#masthead').height() - $('#footer').height() - $('#filterBar').height());
        })
    }

    $(window).resize(function() {
        adjustColumnHeight();
    })




    // On load filter


    function filterProperties(areaFilter, bedroomsFilter, bathroomsFilter) {
        $("#results tr").hide();
        // close current info window
        map.closeInfoWindow();
        //alert(areaFilter+",  "+bedroomsFilter+",  "+bathroomsFilter);


        $('#filter li').removeClass('current');
        $("#area-" + areaFilter).addClass("current");

        var properties = $("#results tr." + areaFilter);
        /*if (bedroomsFilter > 0 && bathroomsFilter > 0) {
        //alert('bedrooms and bathrooms');
        $("#bedrooms option[value=" + bedroomsFilter + "]").attr("selected", true);
        $("#bathrooms option[value=" + bathroomsFilter + "]").attr("selected", true);
        properties.siblings(".bedrooms-" + bedroomsFilter).siblings(".bathrooms-" + bathroomsFilter).show();
        }
        else */
        if (bedroomsFilter == 0 && bathroomsFilter > 0) {
            //alert('Bathrooms');
            $("#bathrooms option[value=" + bathroomsFilter + "]").attr("selected", true);
            //properties.siblings(".bathrooms-" + bathroomsFilter).show();
            
            var bathrooms = jQuery("#results tr.bathrooms-" + bathroomsFilter).each(function() {
                if (jQuery(this).hasClass(areaFilter)) {
                    jQuery(this).show();
                }
            });
            //bathrooms.show();
        }
        else if (bedroomsFilter > 0 && bathroomsFilter == 0) {
            //alert('Bedrooms');
            $("#bedrooms option[value=" + bedroomsFilter + "]").attr("selected", true);
            //var bedrooms = properties.siblings(".bedrooms-" + bedroomsFilter );
            var bedrooms = jQuery("#results tr.bedrooms-" + bedroomsFilter).each(function() {
                if (jQuery(this).hasClass(areaFilter)) {
                    //alert('good');
                    jQuery(this).show();
                }
            });
            //debugger;
            //bedrooms.show();
        }
        else {
            //alert('area only');
            properties.show();
        }



        if (!(markerGroups[areaFilter] === undefined) && !(markerGroups[areaFilter][0] === undefined)) {
	        filterGroup(areaFilter);
            map.panTo(markerGroups[areaFilter][0].point);
			//map.panTo(mapCenter);
        }

		/* NEW */
		else
        {
			filterGroup('all');
			map.panTo(mapCenter);
        }

    }




    // Filter

    $('#filter li a').each(function(f) {
        $(this).click(function() {
            //var hash = window.location.hash;
            var href = $(this).attr('href');
            if (href.indexOf('#') > 0)
            // here I haven't figured out how to use the $.query.get() plugin yet.
            // This would allow us to have a proper URL for a combination of filters.
            {
                var hash = href.substring(href.indexOf('#'));
                areaFilter = hash.substr(6);
            }
            bedroomsFilter = $("#bedrooms option:selected").attr("value");
            bathroomsFilter = $("#bathrooms option:selected").attr("value");
            filterProperties(areaFilter, bedroomsFilter, bathroomsFilter);
        })
    })





    $('#bedrooms').change(function() {
        bedroomsFilter = $("#bedrooms option:selected").attr("value");
        bathroomsFilter = $("#bathrooms option:selected").attr("value");
        filterProperties(areaFilter, bedroomsFilter, bathroomsFilter);
    })

    $('#bathrooms').change(function() {
        bedroomsFilter = $("#bedrooms option:selected").attr("value");
        bathroomsFilter = $("#bathrooms option:selected").attr("value");
        filterProperties(areaFilter, bedroomsFilter, bathroomsFilter);
    })


    function toggleGroup(area) {
        for (var i = 0; i < markerGroups[area].length; i++) {
            var marker = markerGroups[area][i];
            if (marker.isHidden()) {
                marker.show();
            } else {
                marker.hide();
            }
        }
    }



    function filterGroup(area) {
        for (var i = 0; i < markersFlat.length; i++) {
            markersFlat[i].hide();
        }

        if (area == "all") //hack
        {
            /*for (var r = 0; r < markerGroups.length; r++) {
                for (var j = 0; j < markerGroups[r].length; j++) {
                    markerGroups[r][j].show();
                }
            }*/
            
		/* NEW */
        for (var i = 0; i < markersFlat.length; i++) {
            markersFlat[i].show();
        }

        } else {
            for (var j = 0; j < markerGroups[area].length; j++) {
                markerGroups[area][j].show();
            }
        }
    }


    //

    function showMarker(id) {
        var marker = markers[id];
        var html = "<a style='color:#000;' href='#"+id+"' class='markerLink'>" + markers[id].name + "</a><br />"+markers[id].address+ "<br/><a style='color:#000;border-bottom:1px #000 solid' href='" + markers[id].web + "'  target='_blank'>" + markers[id].web + "</a>";
		
        marker.openInfoWindowHtml(html);
    }



    // Open property page on second panel

    function openPropertyPage(id) {
    	//alert(id);
        currentProperty = id;
        $('#secondPanel div').text = "";
        $('#secondPanel div').load('property.aspx?id=' + id, function() {
            $('#panels').animate({ left: "-100%" }, 'fast');
            $('#property_images ul').cycle({
                speed: 1000,
                timeout: 0,
                next: '#property_images #next_image'
            });
        }
)
    };


    function enquiry(id) {
        //alert(markers[id].name);



        $('#object').text(" about " + markers[id].name);
        $('#objectinput').val(markers[id].name);
        $('.message').hide();
        $('#panels').animate({ left: "-200%" }, 'fast');


    };

    $('#actions a.enquiry').live("click", function() {
        enquiry(currentProperty);
    });

    // Enquiry form

    $('#submitinput').click(function() {
        $('#loading').fadeIn("slow");
    });

    $('#contact-form').ajaxForm(function(data) {
        if (data == 1) {
            $('#success').fadeIn("slow");
            $('#bademail').fadeOut("slow");
            $('#contact-form').resetForm();
            $('#contact-form').fadeOut("slow");
            $('#loading').fadeOut("slow");
        }
        else if (data == 2) {
            $('#badserver').fadeIn("slow");
            $('#loading').fadeOut("slow");
        }
        else if (data == 3) {
            $('#bademail').fadeIn("slow");
            $('#email').css("background-color", "#990000");
            $('#email').focus();
            $('#loading').fadeOut("slow");
        }
    });



    $('#back a').click(function() {
        $('#panels').animate({ left: "0" }, 'fast');
    })

    $('#backtoproperty a').click(function() {
        $('#panels').animate({ left: "-100%" }, 'fast');
    })



    $('#nav a').click(function() {
        var href = $(this).attr('href');
        openContentPage(href);
        return false;
    })

    function init() {

        adjustColumnHeight();

        areaFilter = $.query.get('area');
        bedroomsFilter = $.query.get('bedrooms');
        bathroomsFilter = $.query.get('bathrooms');

        if (areaFilter == "") {
            areaFilter = "all";
        }
        if (bedroomsFilter == "") {
            bedroomsFilter = 0;
        }
        if (bathroomsFilter == "") {
            bathroomsFilter = 0;
        }

        //alert(areaFilter+",  "+bedroomsFilter+",  "+bathroomsFilter);
        filterProperties(areaFilter, bedroomsFilter, bathroomsFilter);

    }

    init();







    //property enquiry form
    function enquiry(id) {
        //alert(markers[id].name);
        $('#object').text(" about " + markers[id].name);
        $('#objectinput').val(markers[id].name);
        $('#subjectinput').val('Enquiry on property ' + markers[id].name);
        $('.message').hide();
        $('#panels').animate({ left: "-200%" }, 'fast');

        jQuery('.nsp').hide();
        jQuery('#submitinput').click(function() {
            jQuery('#loading').fadeIn("slow");
            jQuery.ajax({
                url: '/_code/SendPropertyEnquiry.ashx?id=' + id,
                type: 'post',
                dataType: 'json',
                data: jQuery('#contact-form').serializeArray(),
                success: function(data, textStatus) {
                    //jQuery('#contact-form').html(data.message);
                    jQuery('#loading').hide();
                    alert(data.message);


                },
                error: function() {
                    alert('Your form cannot be sent at this time. Please make sure you have entered all fields correctly and try again.');
                },
                complete: function() {
                    jQuery('#loading').hide();
                    jQuery('#enquiryForm :input').val('');
                    //alert('here');
                }
            });
        });
    };

})


