if (typeof console == 'undefined')
	var console = {log:function(mixed){window.alert(mixed);}};

$(document).ready(function()
{

    // Any fields that dont have a value should be filled with their
    // placeholder.
    $('.has-placeholder').each(function()
    {
        if (!$(this).attr('value'))
            $(this).attr('value', $(this).attr('placeholder'));
    });

    // On focus clear a field's value if it is the placeholder.
    $('.has-placeholder').focus(function()
    {
        if ($(this).attr('value') != $(this).attr('placeholder'))
            return;
        $(this).attr('value', '');
    });

    // On blur fill the field with its placeholder value if it has been left
    // blank.
    $('.has-placeholder').blur(function()
    {
        if ($(this).attr('value'))
            return;
        $(this).attr('value', $(this).attr('placeholder'));
    });

    $('.select-multiple').each(function()
    {

        var id = $(this).attr('id');

        var fakeInput = '<input class="mr-fakeinput input-text" id="mr-' + id + '" readonly="readonly" />';

        var popup = '<ul class="mr-popup" id="mr-' + id + '-popup"></ul>';

        $(this).parent().append(fakeInput);
        $(this).parent().append(popup);

        $(this).children().each(function()
        {

            var id = $(this).parent().attr('id');

            var value = $(this).attr('value');
            var check = ($(this).attr('selected')) ? 'checked' : 'unchecked';

            $('#mr-' + id + '-popup').append('<li tabindex="0" onclick="selectMultipleToggle(this);" class="' + check + '" ref="' + value + '">' + $(this).attr('value') + '</li>');

        });

    });



	$('div.has-select-range').each(function()
	{

        var id = $(this).attr('id');

        var fakeInput = '<input class="rr-fakeinput input-text" id="rr-' + id + '" readonly="readonly" />';

		var popup = '<div class="rr-popup" id="rr-' + id + '-popup">'
			+ '<dl id="rr-' + id + '-min"><dt>Minimum</dt></dl>'
			+ '<dl id="rr-' + id + '-max"><dt>Maximum</dt></dl>'
			+ '</div>';

        $(this).append(fakeInput);
		$(this).append(popup);

		if ($(this).attr('placeholder'))
			$('#rr-' + id).val($(this).attr('placeholder'));

		$(this).find('select.select-range-min option').each(function()
		{

            var id = $(this).parent().parent().attr('id');

            var value = $(this).attr('value');
            var check = ($(this).attr('selected')) ? 'checked' : 'unchecked';

            $('#rr-' + id + '-min').append('<dd onclick="selectRangeChange(this, \'min\');" class="' + check + '" ref="' + value + '">' + $(this).text() + '</li>');

		});

		$(this).find('select.select-range-max option').each(function()
		{

            var id = $(this).parent().parent().attr('id');

            var value = $(this).attr('value');
            var check = ($(this).attr('selected')) ? 'checked' : 'unchecked';

            $('#rr-' + id + '-max').append('<dd onclick="selectRangeChange(this, \'max\');" class="' + check + '" ref="' + value + '">' + $(this).text() + '</li>');

		});

		selectRangeChange(id);

	});



    $('form').submit(function()
    {

		$('input').each(function()
		{
			var input = $(this);
			if (input.attr('value') == input.attr('placeholder'))
				input.attr('value', '');
		});

    });

    if ($('#search #map-canvas').length)
    {

        var latlons = {latTop:-90, latBottom:0, lngLeft:150, lngRight:0};

		var myOptions = {
			zoom:						5,
			center:						new google.maps.LatLng(properties[0].lat, properties[0].lng),
			scrollwheel:				true,
			mapTypeControl:				false,
			mapTypeId:					google.maps.MapTypeId.TERRAIN,
			navigationControlOptions:	{position: google.maps.ControlPosition.TOP_RIGHT}
		};

        var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);

        var markers = [];

        for (var i = 0; i < properties.length; i++)
        {

            // latitude is vertical!
            // Detect bounds, set after initialization.
            if (properties[i].lat < latlons.latBottom)
                latlons.latBottom = properties[i].lat;

            if (properties[i].lat > latlons.latTop)
                latlons.latTop = properties[i].lat;

            if (properties[i].lng < latlons.lngLeft)
                latlons.lngLeft = properties[i].lng;

            if (properties[i].lng > latlons.lngRight)
                latlons.lngRight = properties[i].lng;

			var id = properties[i].id;

            var latlng    = new google.maps.LatLng(properties[i].lat, properties[i].lng);
            markers[id]    = new google.maps.Marker(
            {
                position: latlng,
                icon:     '/images/map/map-marker-single.png'
            });

            markers[id].id = id;

			google.maps.event.addListener(markers[id], 'mouseover', function(event)
			{
				this.setIcon('/mp/img/map-marker-single-highlight.png');
/*
				$('#p-' + this.id).animate({'background-color': '#EEEEEE'}, 200, function()
				{
					$(this).animate({'background-color': '#FFFFFF'}, 2000);
				});
*/
				$('#p-' + this.id).css('background-color', '#EEE');

			});

			google.maps.event.addListener(markers[id], 'mouseout', function(event)
			{
				$('#p-' + this.id).css('background-color', '#FFF');
				this.setIcon('/images/map/map-marker-single.png');
			});

			google.maps.event.addListener(markers[id], 'click', function(event)
			{
				window.location = $('#p-' + this.id).find('a').attr('href');
			});

    		markers[id].setMap(map);

    	}

        // Center the map around all the markers/clusters
        map.fitBounds(new google.maps.LatLngBounds(
            new google.maps.LatLng(latlons.latBottom, latlons.lngLeft),
            new google.maps.LatLng(latlons.latTop,    latlons.lngRight)
            ));

    }

	$('#results div.propinfo').mouseenter(function()
	{
		markers[$(this).attr('id').substr(2)].setIcon('/mp/img/map-marker-single-highlight.png');
	});

	$('#results div.propinfo').mouseleave(function()
	{
		markers[$(this).attr('id').substr(2)].setIcon('/images/map/map-marker-single.png');
	});

	if ($('#propinfo-gallery').length)
	{

		//Get our elements for faster access and set overlay width
		var div = $('#propinfo-gallery-thumbs');
		var ul  = $('#propinfo-gallery-thumbs ul');
		// unordered list's left margin
		var ulPadding = 0;

		//Get menu width
		var divWidth = div.width();

		//Remove scrollbars
		div.css({overflow: 'hidden'});

		//Find last image container
		var lastLi = ul.find('li:last-child');

		div.mouseenter(function(e)
		{
//console.log('test');
			//As images are loaded ul width increases,
			//so we recalculate it each time
			div.animating = true;

			var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;

			var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
//			div.scrollLeft(left);
//console.log(left);
//console.log(div.scrollLeft());
//console.log(Math.abs(div.scrollLeft() - left));
			div.animate({scrollLeft: left + 'px'}, Math.abs(div.scrollLeft() - left) * 2, function()
			{
//console.log('finished initial animation');
				div.mousein = true;
			});

		});

		div.mouseleave(function()
		{
//console.log('mouse out set mousein to false');
			div.mousein = false;
		});

		//When user move mouse over menu
		div.mousemove(function(e)
		{

			if (!div.mousein)
				return;

			//As images are loaded ul width increases,
			//so we recalculate it each time
			var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;

			var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
			div.scrollLeft(left);

		});

	}

	// Change thumb
	$('#propinfo-gallery-thumbs a').click(doThumbnail);

	/**
	 * Swap gallery and slideshow images for the file the thumbnail's link is
	 * pointing to.
	 *
	 * @returns bool FALSE
	 */
	function doThumbnail()
	{

		hideContactForm();

		var image = $(this).attr('href').replace(/-lrg/, '-xlrg');

		$('#propinfo-gallery').css('background-image', 'url(' + $(this).attr('href') + ')');

		return false;

	};

	if (!$('#propinfo-floorplan img').length)
		$('#a-floorplan').css({display:'none'});

	$("#propinfo-floorplan").miniZoomPan(
		{
			sW: 466,//508
			//sH: 406,//493
			sH: 453,
			lW: 800,
			lH: 600,
			frameWidth: 1,
			frameColor: '#CCC'
		});

});



function selectMultipleToggle(toggler)
{

    toggler = $(toggler);
    var idBase = $(toggler).parent().attr('id').match(/mr-(.+)-popup/)[1];

    if (toggler.attr('class') == 'unchecked')
    {
        $('#' + idBase + ' option[value=' + toggler.attr('ref') + ']').attr('selected', 'selected');
        toggler.attr('class', 'checked');
    }
    else
    {
        $('#' + idBase + ' option[value=' + toggler.attr('ref') + ']').removeAttr('selected');
        toggler.attr('class', 'unchecked');
    }

    var selected = $('#' + idBase).val();
    if (selected)
        $('#mr-' + idBase).attr('value', $('#' + idBase).val().join(', '));
    else
        $('#mr-' + idBase).attr('value', '');

};



function selectRangeChange(toggler, type)
{

	if (typeof toggler == 'object')
	{

	    toggler = $(toggler);
		var val = toggler.attr('ref');

		var id  = toggler.parent().parent().attr('id').match(/rr-(.+)-popup/)[1];

		$('#' + id + '-' + type).val(val);

	}
	else
	{
		// for initialization you may simply pass the base id
		var id  = toggler;
	}

	var min = $('#' + id + '-min').val();
	var max = $('#' + id + '-max').val();

	if (max && min > max)
	{
		var tmp = min;
		min = max;
		max = tmp;
	}

	var minLabel = $('#' + id + '-min option[value=' + min + ']').text();

	if (max && min && $('#' + id + '-min option[value=' + min + ']').attr('short'))
		var minLabel = $('#' + id + '-min option[value=' + min + ']').attr('short');

	var maxLabel = $('#' + id + '-min option[value=' + max + ']').text();

	if (min && min == max)
		var text = minLabel;
	else if (min && max)
		var text = minLabel + ' to ' + maxLabel;
	else if (max)
		var text = 'Up to ' + maxLabel;
	else if (min)
		var text = minLabel + ' or more';
	else
		var text = $('#' + id).attr('placeholder') ? $('#' + id).attr('placeholder') : '';

    $('#rr-' + id).attr('value', text);

	if (typeof toggler == 'object')
	{
		$('#rr-' + id + '-' + type + ' dd').attr('class', 'unchecked');
		toggler.attr('class', 'checked');
	}
	else
	{
		// set min and max checked
	}

};



function hideAllPanels()
{

	$('#propinfo-gallery').hide();
	$('#propinfo-floorplan').hide();
	$('#map-canvas').hide();
	hideContactForm();

}



function initializePropertyMap()
{

	hideAllPanels();
	$('#map-canvas').show();


	var lat = $('#map-canvas').attr('lat');
	var lng = $('#map-canvas').attr('lng');

	var latlng = new google.maps.LatLng(lat, lng);

	var myOptions = {
		zoom:						15,
		center:						latlng,
		scrollwheel:				true,
		mapTypeId:					google.maps.MapTypeId.TERRAIN
	};

	var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);

	if ($('#map-canvas').attr('showmarker') != '0')
		var marker = new google.maps.Marker({
			position:	latlng, 
			map:		map,
			icon:		'/images/map/map-marker-single.png'
		});

};



function showImages()
{

	hideAllPanels();
	$('#propinfo-gallery').show();

};



function showFloorplan()
{

	hideAllPanels();
	$("#propinfo-floorplan").show();

};



function contactForm(url)
{

	hideAllPanels();
	$('#propinfo-gallery').show();

	$('#prop-form').show().load(url, contactFormCaptureSubmit);

	return false;

};



function contactFormCaptureSubmit()
{

	$('#prop-form form').submit(submitContactForm);

};



function submitContactForm()
{

	$('#prop-form .input-submit').attr('disabled', 'disabled');

	var form = $(this);

	form.parent().load(
		form.attr('action'),
		form.serializeArray(),
		contactFormCaptureSubmit
		);

	return false;

};



function hideContactForm()
{

	$('#prop-form').text('').hide();

};

