$().ready(function() {
	$id = null;
	$status = null;
				 
	function update() {
		$path = "http://www.libertypark.com/homes-and-homesites/listings/saved";
		
		if ($('#listings input[name=status]').val() == 0) {
			$('#listings .saved-popup').show();
			return;
		}

		$email = $('#listings .saved-popup').find('input[name=email]').val();

		$.ajax({
			type: 'POST',
			url: 'http://www.libertypark.com/homes-and-homesites/listings/saved/update',
			data: 'id=' + $id + '&email=' + $email + '&status=' + $status,
			success: function($data){
				$('#listings .saved-popup').hide();
				if ($id != null) alert("The listing has been " + ($status ? "saved" : "deleted") + ".");
				if (!$status) document.location = $path;
			}
		 });
	}

	$('.print').click(function() { window.print(); });

	$('#listings .saved-popup .close').click(function() {
		$('#listings .saved-popup').hide();												  
	});
	$('#listings .saved-popup form').submit(function() {
		$input = $('#listings .saved-popup form input[name=email]');
		$input.focus(function() {
			if ($(this).val() == 'Please enter your email') $(this).val('');
		});

		if (!jQuery.email($input.val())) {
			$input.val('Please enter your email');
		}
		else {
			$('#listings input[name=status]').val('1');
			update();
		}

		return false;															 
	});

	$('.save-listing, .delete-listing').click(function() {
		$id = $(this).closest('li').find('input[name=id]').val();	
		if (isNaN($id)) $id = $('#listings input[name=id]').val();

		$status = ($(this).hasClass('save-listing') ? 1 : 0);
		update();
	});

	$('#listings .detail .gallery').gallery({ change: function($event, $index) {
		$data = JSON.parse($('#listings .detail .gallery textarea').val());
		$buttons = $('#listings .detail .gallery a.lightbox');
		$buttons.attr('href', $data[$index - 1]);
		$buttons.lightBox();																			  
	} });
	
	$('#listings .detail .gallery-thumbnails').scrollable();
	
	var $buttons;
	var i = 1;

	$buttons = $('#listings .detail .gallery-thumbnails ul li a');
	$buttons.each(function() {
		this.index = i;
		i++;
	});
	$buttons.mouseover(function() {
		$('#listings .detail .gallery').gallery('change', this.index);
	});
	$buttons.lightBox();

	$button = $('#navigation ul li').eq(2).find('ul a').eq(4);
	$button.attr('href', 'javascript:void(0)');
	$button.click(function() { update(); });

	if (String(document.location).split('/').pop() == 'saved' && $('#listings input[name=status]').val() == 0) $('#listings .saved-popup').show();
});
