/**
 * Feature Listing JQuery Plugin
 *	usage: used on any page with the feature listing widget
 *	dependencies: jQuery, WebsiteManager.js
 */
(function() {
	var featureListingAjaxRequest = null;
	var nextRun = null;
	var listingCache = null; //This is the json object that hold all of our data.
	var listingCacheIndex = null; //Current listing being displayed from the listing cache.
	var refreshTimeout = null; //Timeout in millisecond.

	/** This function stops and frees everything used by the featured listing widget
	  *
	  */
	$.finalizeFeatureListingWidget = function() {
		// prevent the script from running again
		if(this.nextRun != null)
			clearTimeout(this.nextRun);
		
		// clear the content (we do this becuase if we drag the feature listing out again we
		// want to run the $.initializeFeatureListingWidget that is in the content. This step
		// is only necessary for widgets that require javascript initialize functions to be run
		// after drag)
		$('#featureListingWidget').parent().children(".widgetHeader, .widgetContent").remove();
		
		//Clear the cache and the position.
		this.listingCache = null;
		this.listingCacheIndex = null;
	}

	/** This function initializes the listings search page.
	  *
	  * @param identifier the SystemInfo.RPM_WIDGET_FEATURE_LISTING
	  */
	$.initializeFeatureListingWidget = function(identifier) {
		this.listingCacheIndex = 0; //Current listing being displayed from the listing cache.
		this.refreshTimeout = 20000; //Timeout in millisecond.

		// register this widget with the widget manager (if necessary)
		if(typeof(websiteManager) != "undefined")
			websiteManager.widgetManager.removeWidgetCallbacks[identifier] = function(){$.finalizeFeatureListingWidget()};
		
		// get the feature listing
		$.getFeatureListing();
	}

	/** get Feature Listing
	  *
	  */
	$.getFeatureListing = function(){
		// get self
		var self = this; //So that we can refer to this 'this' in the ajax call which is in a diff context and has a diff 'this'

		// abort any pending requests
		if(this.featureListingAjaxRequest){
			this.featureListingAjaxRequest.abort();
		}

		// If our listingCache is empty let's grab the data.
		if(self.listingCache == null) {
			self.listingCacheIndex = 0; //Index gets re-initialized every time that we load listings from the server, technically should only happen once.

			this.featureListingAjaxRequest = $.ajax({
				type: "GET",
				url: "listings",
				data: "pathway=6&loadFeatureListing=true",
				dataType: "json",
				error: function(data, error){
					//alert("Error: featureListingWidget(): " + error + " " + data);
				},
				success: function(data){
					self.listingCache = data;
					self.listingCacheIndex = 0; //Reset the index.
					$.postFeaturedListing(); //Post the next listing from the listings cache.
				},
				complete: function (XMLHttpRequest, textStatus) {
				}
			});
		} else { //We already have listing data just post the next one.
			$.postFeaturedListing();
		}
	}
	
	 /**
	  * Generates the HTML and posts the featured listing.
	  * It takes it's data out of the listingCache. If that is not filled out it will not do anything.
	  */
	$.postFeaturedListing = function(){
		var self = this;

		//Quit right away if we don't have our stuff.
		if(self.listingCache == null || self.listingCache.rows == null || self.listingCache.rows.length == 0) {
			//This replaces the calls in the old feature_listing_widget_summary.jsp file.
			
			//If we're in the back office.
			if(self.listingCache.back_office == 1) {	
				//Show the error message.
				$('#featureListingWidget').fadeOut("slow", function(){
					$('#featureListingWidget').html("No Listings Available.  Please ensure your agent and brokerage ID(s) have been entered correctly in the Agents/Assistants area of the Account Manager. Alternatively your Featured Listings Widget settings in the Website Manager may be too restrictive.");
					$('#featureListingWidget').fadeIn("slow");
				});
				
				$.finalizeFeatureListingWidget();
			} else { //Front office.
				$('#featureListingWidget').fadeOut("slow", function(){
					$("#featureListingModule").parent().css("display", "none"); //Hide the entire featured listing widget if we don't have any featured listings.
					$.finalizeFeatureListingWidget();
				});
			}

			return;
		}
		
		//If the index is past the end of the cache reset it to the beggining.
		if(self.listingCacheIndex >= self.listingCache.rows.length) { self.listingCacheIndex = 0; }
		
		//Generate the HTML to be used.
		var htmlToUse = '';
		var htmlToUse = htmlToUse + '<div class="listingPrice">'+self.listingCache.rows[self.listingCacheIndex].list_price+'</div>';
   
		var htmlToUse = htmlToUse + '<div class="listingPhotoContainer">';
		var htmlToUse = htmlToUse + '   <a href="listing_detail-'+self.listingCache.rows[self.listingCacheIndex].list_num+'.html">';
		var htmlToUse = htmlToUse + '       <img src="'+self.listingCache.rows[self.listingCacheIndex].photo_link+'" class="listingPhoto" /></a><br />';
		var htmlToUse = htmlToUse + '   </a>';
		var htmlToUse = htmlToUse + '</div>';
    
		var htmlToUse = htmlToUse + '<div style="width:100%;float:left;text-align:center;padding-top:5px;"><b>'+self.listingCache.rows[self.listingCacheIndex].addrs+'</b></div>';
    
		var htmlToUse = htmlToUse + '<div style="width:26%;float:left;text-align:right;">'+self.listingCache.rows[self.listingCacheIndex].feat1_label+':</div>';
		var htmlToUse = htmlToUse + '<div style="width:24%;float:left;text-align:left;text-indent:5px">'+self.listingCache.rows[self.listingCacheIndex].feat1_value+'</div>';
 
		var htmlToUse = htmlToUse + '<div style="width:26%;float:left;text-align:right;">'+self.listingCache.rows[self.listingCacheIndex].feat2_label+':</div>';
		var htmlToUse = htmlToUse + '<div style="width:24%;float:left;text-align:left;text-indent:5px">'+self.listingCache.rows[self.listingCacheIndex].feat2_value+'</div>';

		var htmlToUse = htmlToUse + '<div style="width:100%;float:left;text-align:center;padding-top:5px;"><a href="listing_detail-'+self.listingCache.rows[self.listingCacheIndex].list_num+'.html">More Details</a></div>';

		//Update the data.
		$('#featureListingWidget').fadeOut("slow", function(){
			$('#featureListingWidget').html(htmlToUse);
			$('#featureListingWidget').fadeIn("slow");
		});
		
		//The listing cache is in random order so grabbing the next will get us the next random one.
		self.listingCacheIndex++;
				
		//Finally rebind the timer to get it to keep scrolling.
		self.nextRun = setTimeout("$.getFeatureListing()", self.refreshTimeout);
	}
	
})();