dojo.require('dojo.number');
dojo.require('dojo.currency');
dojo.require('dojo.string');

dojo.declare("com.foreclosureagency.RenderController",null,  {

	LISTINGS_PER_PAGE: 50,
	MAX_PAGES: 40,
	lastListings: null,
	totalCount: 0, // not all the listings are downloaded, track here the downloaded ones
	listingsVisible:false, // track when this panel is visible so that we can update it
	currentPage: null,
	updateImagesTimeout: null, // used to display the images in a second phase after the screen has been updated
	sortField: 'minBid',
	sortDescending: true,
    headerDesc: [
                      ['24%', 'Property', null],
                      ['18%', 'Address', "address"],
                      ['10%', 'Zip', "zip"],
                      ['13%','Price',"minBid"],
                      ['10%','Sq Ft',"size"],
                      ['10%','Bed',"bathrooms"],
                      ['10%','Bath',"bedrooms"]
             ],
     sortSelectChanged: function(select) {
         var criteria = select.options[select.selectedIndex].value.split("_");
         if  ( criteria && criteria.length && criteria.length == 2 ) {
             var descending = (criteria[1] == "down");
             this.sortBy(criteria[0],descending);
         }
         
     },
     sortBy: function(field,descending) {
		this.sortField = field;
		this.sortDescending = descending;
		if ( this.lastListings !== null ) {
			this.lastListings.sort(function(a,b){
				/* comment the following to make the spotlight stick at the top */
				if ( field == 'spotlight' ) {                
    				if ( a.markerType == 'best' ) {
    					return -1;
    				}
    				if ( b.markerType == 'best' ) {
    					return 1;
    				}
				}
				var sortField = field;
				// in the spotlight algorithm first sort on photos
				if ( field == 'spotlight') {
					if ( a.photoURL && !b.photoURL ) {
						return -1;
					}
					if ( !a.photoURL && b.photoURL ) {
						return 1;
					}
					// either both have pictures or none have pictures, sort on the price
					sortField = 'minBid';
				}
				/* end of code make the spotlight stick */
				if ( !a.hasOwnProperty(sortField)) {
					return descending?-1:1;
				}
				if ( !b.hasOwnProperty(sortField)) {
					return 0;
				}
				if ( descending ) {
					return ( a[sortField] > b[sortField] ) ? -1 : 1;
				} else {
					return ( a[sortField] < b[sortField] ) ? -1 : 1;
				}
			});
			this.renderPage(1);
		}
	 },
             
	/**
	 * Generate the PDF for the current listings.
	 * This function uses a form to be able to inject the return through the browser save mechanism.
	 */
	generatePdf : function() {
		var form = document.forms.listingPdf;
		for ( var i=0;i<this.lastListings.length;i++) {
			var aListing = this.lastListings[i];
			var inp = document.createElement('input');
			inp.type = 'hidden';
			inp.name = 'listingIds';
			inp.value = aListing.id;
			form.appendChild(inp);
		}
		form.submit();
	},
	
	init : function() {
		dojo.subscribe("mapSubPane", this,  function(panel){
			if ( panel == "listingPane") {
				if ( this.listingsVisible ) {return;} 
				this.listingsVisible=true; 
				this.updateListings();
			} else {
				this.listingsVisible = false;
			}
		});
		dojo.subscribe( "filterChanged", this, this.updateListings );
	},	
	
	updateListings: function(page) {
		if ( this.listingsVisible ) {
			var listings = searchControl.listings;
			if ( !listings ) {
				return;
			}
			this.totalCount = searchControl.clustered.numListings;
			var displayed = this.renderListings(listings,page);
		}
	},	
	
	/**
	 * Save a new set of listings and render the given page.
	 * If no page is passed in assume this is the first time display and sort the data.
	 *  Returns the rendered listings.
	 */
    renderListings : function(listings,page) {
		// save listings for pagination, if necessary
		this.lastListings = listings;
		if ( typeof(page) == "undefined" ) {
			//c_onsole.log("first time display, sort listings by spotlight algorithm");
			this.sortBy( "spotlight", true );
			page = 1;
		}
		return this.renderPage( page );
	},
	
	fetchGoogleMapImage : function ( listing, div, onClick ) {
	    var map = new GMap2(div);
	    var latlng = new GLatLng(listing.lat, listing.lon );
	    map.setCenter( latlng,13);
	    map.setMapType(G_SATELLITE_MAP);
	    map.setZoom(map.getCurrentMapType().getMaximumResolution()-1);
	    GEvent.addListener(map,'click', onClick );
	    var marker = new GMarker( latlng, {icon: mapControl.getIcon(listing.markerType)} );
	    map.addOverlay(marker);                    	
	},
	
	fetchVirtualEarthMapImage : function ( listing, divName, onClick ) {
	    var latlng = new VELatLong(listing.lat, listing.lon);
	    var map = new VEMap(divName);
	    map.HideDashboard();
	    map.HideScalebar();
	    map.LoadMap(latlng, 17);
        // switch to birds eye if available
        map.AttachEvent("onobliqueenter", function (){
            if(map.IsBirdseyeAvailable()) {
               map.SetBirdseyeScene(latlng);
            }
         });
        map.AttachEvent('onclick', onClick );
	    //
	    //var marker = new GMarker( latlng, {icon: mapControl.getIcon(listing.markerType)} );
	    //map.addOverlay(marker);                    	
	},
	
	updateImages : function(displayed) {
        // Look for listing that need pictures, and use google to draw them
		Public.progressIndicator.show();
        var enterTime = new Date().getTime();
        var i = 0;
        var that = this;
        dojo.forEach( displayed, function(aListing) {

            if( (!aListing.photoURL || dojo.string.trim(aListing.photoURL) === "") && i < 100)
            {
                i++;
                var mapTarget = dojo.byId("listing_"+aListing.id);
                //var mapTarget = dojo.byId("foobar");
                if(mapTarget) {
                	if ( RENDER.useVirtualEarth ) {
                		that.fetchVirtualEarthMapImage( aListing, "listing_"+aListing.id, function() { mapControl.showDetail(aListing.id, aListing.entityType);} );
                	} else {
                		that.fetchGoogleMapImage( aListing, mapTarget, function() { mapControl.showDetail(aListing.id, aListing.entityType);} );
                	}
                }
            }
        });
        if ( RENDER.showStatistics ) {
            enterTime = new Date().getTime()-enterTime;
        	GLog.write("updateImages TIME: " + enterTime );
        }
		Public.progressIndicator.hide();
        
	},
	
	showMessage: function(msg) {
		 var listingPane = dojo.byId("listingPaneContent");
		 listingPane.innerHTML = msg;
	},
	
	doCalcPayment: function(amount) {
        var term = 30;
        var rate = 0.06 / 12;
        var m = term * 12;
        m = Math.pow(1+rate,m);
        var payment = amount  * (rate*m)/(m-1);
        var result = Math.round(payment);
        return result;
	},
	
	renderListingRow: function(aListing,isEven,index) {
        var aRow = [];
        var i=0;
        aRow[i++] = '<div class="listing ';
        aRow[i++] = isEven?"even":"odd";
        aRow[i++] = '">';
        if(aListing.photoURL && aListing.photoURL !== "")
        {
            aRow[i++] = "<img style='' src='";
            aRow[i++] = aListing.photoURL;
            aRow[i++] = "' width='160' height='120'  valign='middle' ";
            aRow[i++] = " onclick=\"mapControl.showDetail(";
            aRow[i++] = aListing.id;
            aRow[i++] = ",'";
            aRow[i++] = aListing.entityType;
            aRow[i++] = "')\"";
            aRow[i++] = " alt='House Listing' />";
            
            
            // add a second image
            aRow[i++] = "<img alt='Satellite View' class='entity-type-overlay' src='/web/images/map/";
            if ( aListing.entityType == "Listing" ) {
            	if ( aListing.saleType == "pre" ) {
            		aRow[i++] = "housex-orange.png'>";        		
            	} else {
            		aRow[i++] = "housex-red.png'>";
            	}
            } else {
            	aRow[i++] = "housex.png'>";
            }
            
        }        
        aRow[i++] = '<div class="address-bar"><a href="##">';
	    aRow[i++] = '<table cellpadding="0" cellspacing="0" border="0"><tr><td class="bar-left"></td><td class="main">';
	    aRow[i++] = '<h3>';
        if( RENDER.address === null ) {
            aRow[i++] = aListing.address;
            aRow[i++] = "<strong> ";
            aRow[i++] = aListing.city;
            aRow[i++] = ",";
            aRow[i++] = aListing.state;
            aRow[i++] = " ";
            aRow[i++] = aListing.zip;
            aRow[i++] = "</span>";
        } else {
        	aRow[i++] = "<a href='registration.do'>";
        	aRow[i++] = RENDER.address;
            aRow[i++] = "</a><br>";
        }	    
	    aRow[i++] = '</h3></td><td class="bar-right"></td></tr></table></a></div>';
	    aRow[i++] = '<div class="property-info"><h4>';
        if ( aListing.minBid ) {
        	aRow[i++] = "$";
        	aRow[i++] = dojo.number.format(aListing.minBid);
        } else {
        	if( aListing.entityType == "Auction" ) {
        		aRow[i++] = "Auction price N/A";
        	} else {
        		aRow[i++] = "Price not listed";
        	}
        }
	    
	    aRow[i++] ='</h4>';
	    aRow[i++]='<h5>';
	    if( aListing.bedrooms ) {
    	    aRow[i++] = aListing.bedrooms;
    	    aRow[i++] = ' Bed / ';
        }
        if ( aListing.bathrooms ) {
    	    aRow[i++] = aListing.bathrooms;
    	    aRow[i++]=' Bath <strong style="color:#9a9a9a; margin:2px;">|</strong> ';
	    }
	    if ( aListing.size ) {
    	    aRow[i++]=  aListing.size;
    	    aRow[i++]=' Sq Ft <strong style="color:#9a9a9a; margin:2px;">|</strong> ';
	    }
	    if ( aListing.minBid ) {
    	    aRow[i++] = '$';
    	    aRow[i++] = dojo.number.format(this.doCalcPayment(aListing.minBid*0.8));
    	    aRow[i++] = '/mo @ 6.0%';
        }
	    
	    aRow[i++] = '</h5>';
	    aRow[i++] = '</div>';
	    aRow[i++] = '<div><table style="height: 30px; position: absolute; width: 200px; left: 194px; top: 85px; font-size: 9px; text-align: left; font-weight: bold;">';
	    aRow[i++] = '<tr><td>';
	    aRow[i++] = '<a href="##" onclick="renderControl.showDetail(';
        aRow[i++] = aListing.id;
        aRow[i++] = ", \'";
        aRow[i++] = aListing.entityType;
	    aRow[i++] = '\');return false;">More Details</a>';	    
	    aRow[i++] = '</td><td>';
	    aRow[i++] = '<a href="http://www.google.com/maps?daddr=';
	    aRow[i++] = aListing.zip;
	    aRow[i++] = '&saddr=';
	    aRow[i++] = aListing.address;
	    aRow[i++] = '&f=d" target="_directions">Driving Directions</a>';
	    aRow[i++] = '</td></tr>';
	    aRow[i++] = '</table></div>';
	    aRow[i++] = '<div><table style="cellpadding:0; cellspacing:0; border:1px solid #dddddd; height:80px; position:relative; width: 165px; left: 450px; top:54px; font-size:9px; text-align:left; font-weight:bold;">';
	    if ( aListing.companyToShow ) {
		    aRow[i++] = '<tr class="even">';
		    aRow[i++] = '<td class="label" style="width:5px; text-align:left; font-weight:normal; padding-left:2px">Company:</td>';
		    aRow[i++] = '<td class="stat" style="text-align:left; font-weight:bold; padding-left:2px">';
		    aRow[i++] = aListing.companyToShow.substring(0,18);
		    aRow[i++] = '<td>';
		    aRow[i++] = '</tr>';
	    }
	    if ( aListing.contactPhoneToShow ) {
		    aRow[i++] = '<tr class="even">';
		    aRow[i++] = '<td class="label" style="width:5px; text-align:left; font-weight:normal; padding-left:2px">Phone:</td>';
		    aRow[i++] = '<td class="stat" style="text-align:left; font-weight:bold; padding-left:2px">';
		    aRow[i++] = aListing.contactPhoneToShow.substring(0,18);
		    aRow[i++] = '<td>';
		    aRow[i++] = '</tr>';
	    }
	    if ( aListing.contactToShow ) {
		    aRow[i++] = '<tr class="even">';
		    aRow[i++] = '<td class="label" style="width:5px; text-align:left; font-weight:normal; padding-left:2px">Contact:</td>';
		    aRow[i++] = '<td class="stat" style="text-align:left; font-weight:bold; padding-left:2px">';
		    aRow[i++] = aListing.contactToShow.substring(0,18);
		    aRow[i++] = '<td>';
		    aRow[i++] = '</tr>';
	    }
	    if ( aListing.email ) {
	    	aRow[i++] = '<tr class="even">';
		    aRow[i++] = '<td class="label" style="width:5px; text-align:left; font-weight:normal; padding-left:2px">Email:</td>';
		    aRow[i++] = '<td class="stat" style="text-align:left; font-weight:bold; padding-left:2px">';
		    aRow[i++] = aListing.email.substring(0,18);
		    aRow[i++] = '<td>';
		    aRow[i++] = '</tr>';
	    }
	    aRow[i++] = '</table></div>';
	    aRow[i++] = '</div><div id="spacer" style="height:15px;">&nbsp;</div>';
	    
	    return aRow.join('');
	},
	
	showDetail: function( listingId, entityType ) {
	    mapControl.showDetail(listingId,entityType);
	},
   
    /**
     *
     * @param aListing
     * @param isEven
     */
    renderListingRowOld : function(aListing, isEven, index) {

        var aRow = [];
        var i=0;
        
        aRow[i++] = "<tr class='";
        aRow[i++] = (isEven ? "listingRowEven" : "listingRowOdd");
        aRow[i++] = "'>";
        aRow[i++] = "<td class='listingrowCell' ><div style='position:relative; width:120px; height:120px;' id='listing_";
        aRow[i++] = aListing.id;
        aRow[i++] = "' >";
        if(aListing.photoURL && aListing.photoURL !== "")
        {
            aRow[i++] = "<img style='float: left; display: inline; position: relative;' src='";
            aRow[i++] = aListing.photoURL;
            aRow[i++] = "' width='160' height='120'  valign='middle' ";
            aRow[i++] = " onclick=\"mapControl.showDetail(";
            aRow[i++] = aListing.id;
            aRow[i++] = ",'";
            aRow[i++] = aListing.entityType;
            aRow[i++] = "')\"";
            aRow[i++] = "/>";
            
            
            // add a second image
            aRow[i++] = "<img alt='Satellite View' style='float:left;margin-top: -25px; margin:left: 5px; position: relative; display:inline;height: 19px; width: 19px;' src='/web/images/map/";
            if ( aListing.entityType == "Listing" ) {
            	if ( aListing.saleType == "pre" ) {
            		aRow[i++] = "housex-orange.png'>";        		
            	} else {
            		aRow[i++] = "housex-red.png'>";
            	}
            } else {
            	aRow[i++] = "housex.png'>";
            }
            
        }
        aRow[i++] = "</div></td>";
        aRow[i++] = "<td class='listingrowCell' >";
        if( RENDER.address === null ) {
            aRow[i++] = aListing.address;
            aRow[i++] = "<br>";
            aRow[i++] = aListing.city;
            aRow[i++] = ",";
            aRow[i++] = aListing.state;
            aRow[i++] = " ";
        } else {
        	aRow[i++] = "<a href='registration.do'>";
        	aRow[i++] = RENDER.address;
            aRow[i++] = "</a><br>";
        }
        aRow[i++] = aListing.zip;
        aRow[i++] = "<br>";
        aRow[i++] = "</td>";
        aRow[i++] = "<td  align='center' class='listingrowCell' >";
        aRow[i++] = aListing.zip;
        aRow[i++] = "</td>";
        aRow[i++] = "<td align='center' class='listingrowCell' >";
        if ( aListing.minBid ) {
        	aRow[i++] = "$";
        	aRow[i++] = dojo.number.format(aListing.minBid);
        } else {
        	if( aListing.entityType == "Auction" ) {
        		aRow[i++] = "Auction price N/A";
        	} else {
        		aRow[i++] = "Price not listed";
        	}
        }
        aRow[i++] = "</td>";
        aRow[i++] = "<td  align='center' class='listingrowCell' >";
        aRow[i++] = aListing.size;
        aRow[i++] = "</td> <td  align='center' class='listingrowCell' >";
        aRow[i++] = aListing.bedrooms;
        aRow[i++] = "</td> <td  align='center' class='listingrowCell' >";
        aRow[i++] = aListing.bathrooms;
        aRow[i++] = "</td> <td class='listingrowCell' ><a href='#' onclick='mapControl.showDetail(";
        aRow[i++] = aListing.id;
        aRow[i++] = ", \"";
        aRow[i++] = aListing.entityType;
        aRow[i++] = "\"); return false;' >More Details</a> </td>";
        aRow[i++] = "</tr>";

        //console.debug(aRow.join(''));
        return aRow.join('');
    }

});

/**
 * Render the listings for the given page.
 * Returns the rendered listings.
 */
com.foreclosureagency.RenderController.prototype.renderPage = function(page) {
	var enterTime = new Date().getTime();
	var listings = this.lastListings;
    var listingPane = dojo.byId("listingPaneContent");
    var completeListing = [];
    i = 0;
    this.currentPage = page;

    var pageControl = [];
    if ( listings.length > this.LISTINGS_PER_PAGE ) {
		document.getElementById('label-01').style.display='block';
		document.getElementById('label-02').style.display='block';
    	var pages = listings.length/this.LISTINGS_PER_PAGE;
    	if ( pages > this.MAX_PAGES ) {
    		pages = this.MAX_PAGES;
    	}
    	for ( var pi=0;pi<pages;pi++) {
    		pageControl[i++] = " ";
    		var pageLink = pi+1;
    		if ( pageLink != page ) {
    			pageControl[i++] = "<a href='##' onclick='renderControl.renderPage(";
    			pageControl[i++] =  pageLink;
    			pageControl[i++] =  ")'>";
    			pageControl[i++] = pageLink;
    			pageControl[i++] = "</a>";
    		} else {
    			pageControl[i++]= pageLink;
    		}
    	}
    }
    
    i=0;
    
    var url = window.location.toString();

    var listingStart = (page-1)*this.LISTINGS_PER_PAGE;
    var displayed = listings.slice( listingStart, listingStart+this.LISTINGS_PER_PAGE);
    var me = this;
    dojo.forEach( displayed, function(aListing, index) {
    	completeListing[i++] = me.renderListingRow(aListing, ( index % 2 === 0), index );
    } );

    listingPane.innerHTML = completeListing.join('');
    var pageControlAll = pageControl.join(""); pageControl = null;
    dojo.query("#listingPane .counter").forEach(function(a){
        a.innerHTML=pageControlAll;
    });
    
    if ( RENDER.showStatistics ) {
        enterTime = new Date().getTime()-enterTime;
    	GLog.write("renderPage TIME: " + enterTime );
    }
    
    var that = this;
    if ( this.updateImagesTimeout ) {
    	clearTimeout( this.updateImagesTimeout );
    }
    this.updateImagesTimeout = setTimeout(function(){that.updateImages(displayed);},200);
    return displayed;
};



var renderControl = new com.foreclosureagency.RenderController();

dojo.addOnLoad(function(){
	renderControl.init();
	if ( GeoLib.isPanelActivated('listings')) {
		searchControl.selectSubTab("listingPane");
		renderControl.listingsVisible=true; 
		searchControl.addOnLoad( function(){searchControl.doSearch();} );
		
	}
});

