var ListingViewer = new Singleton(function($) {
	var container = $('<div class="listing_viewer"/>');

    this.dependencies = {
        stylesheets: {
            listing_viewer: '/stylesheets/listing_viewer.css'
        },
        javascripts: {
            'jQuery.fn.cycle': '/javascripts/jquery/jquery.cycle.js'
        }
    };
    
	this.methods({
		ready: function() {
			this.loadIEStyles();
			this.createDialog();
			this.afterInitialize();
		},
		afterInitialize: function() {
			// 	Default to nothing
		},
		afterLoad: function() {
			// 	Default to nothing
		},
		requestListing: function(listing_id_or_url) {
			container.dialog('open');
			ListingViewer.loadListing(listing_id_or_url);
		},
		loadListing: function(listing_id_or_url) {
			container.find('.listing').html('<div class="loading"></div>');
			var url;
			if (isNaN(listing_id_or_url)) { url = listing_id_or_url; }
			else { url = '/searches/listings/' + listing_id_or_url; }
			$.get(url, function(html) { ListingViewer.setListing(html); });
		},
		loadIEStyles: function() {
			if ($.browser.msie) {
				if ($.browser.version <= 6) {
					$('<link type="text/css" rel="stylesheet" media="screen" href="/stylesheets/searches/common.ie6.css" />').appendTo('head');
				}
				else {
					$('<link type="text/css" rel="stylesheet" media="screen" href="/stylesheets/searches/common.ie7.css" />').appendTo('head');
				}
			}
		},
		setListing: function(html) {
			container.html(html);
			container.find('.basic_info').after('<ul class="thumbnails"/>');
			container.find('.photos').cycle({
			    fx:     'fade',
			    speed:  'slow',
			    timeout: 0,
			    pager:  container.find('.thumbnails'),

			    // callback fn that creates a thumbnail to use as pager anchor 
			    pagerAnchorBuilder: function(idx, slide) {
					var img = $(slide).find('img');
					return '<li><a href="#"><img src="' + img.attr("src") + '" width="50" height="50" /></a></li>';
			    }
			});
			
			container.find('img').error(function() {	
				$(this).attr('src', '/images/listings/nopic.png');
			});

			// Buttons
			container.find('.secondary_links a.print').click(function() {
				var print_window = window.open($(this).attr('href'));
				print_window.onload = function() {
					print_window.print();
					print_window.close();
				};
				return false;
			});
			this.afterLoad();
		},
		currentListing: function() {
			return container.find('span.listing_id').text();
		},
		getContainer: function() {
			return container;
		},
		createDialog: function() {
			container.dialog({
				modal: true,
				bgiframe: true,
				title: 'Property Overview',
				resizable: false,
				autoOpen: false,
				height: 550,
				width: 800
			});
		}
	});
});
