(function ($) {
    $.widget("ui.ListingSlideshow", {
        options: {
            userID: -1,
            mlsGroup: "",
            cirrusUrl: "",
            interval: 7,
            layout: "vertical",
            serviceUrl: ""
        },
        _create: function () {
            if (!this._optionsValid())
                return;

            var self = this;
            var elem = $(this.element);
            var svcUrl;

            //if a custom service url is not specified, use the default Featured Listing Service.
            (this.options.serviceUrl == "") ?
                svcUrl = "http://listingsearch.1parkplace.com/ListingSearch.JsonListingService.svc/featuredListings/" + this.options.userID + "/" + this.options.mlsGroup
                : svcUrl = this.options.serviceUrl;
				
            //We only want to provide a style sheet link if they are not using a Custom Layout
            if (this.options.layout.toLowerCase() != "custom") {
                (this.options.layout.toLowerCase() == "vertical") ?
                $("head").append("<link rel='Stylesheet' type='text/css' id='ssCss' href='http://tools.1parkplace.com/Widgets/ListingSlideshow/Vertical.css' />") :
                $("head").append("<link rel='Stylesheet' type='text/css' id='ssCss' href='http://tools.1parkplace.com/Widgets/ListingSlideshow/Horizontal.css' />");
            }
			
            //Get the user's featured listings.
			$.ajax(
			{
				type: 'GET',
				url: svcUrl,
				cache: false,
				dataType: 'jsonp',
				success: function(data, status, req) {
					if (data != null)
					{
						self.element.data("listings", data.GetFeaturedListingsResult); //store listings so we can access from other functions
						//If there is more than 1 listing, bind the events to pause the slideshow when the cursor is over the listing.
						if (data.GetFeaturedListingsResult.length > 1)
							elem.hover($.proxy(self._pause, self), $.proxy(self._play, self));

						self._setTemplate();
						self.element.data("index", 0);  //set index to point to 1st listing
						self._display(); //display 1st listing
						self._play();
					}
				},
				error: function(xhr, status, error) {
                    alert("no results");
                    $(self.element).html("<p>There was an error processing the request.</p><span style=\"color: #F00;\">Details: "+xhr.responseText+" "+status+"</span>");
				}
			});
        },
		_onLoad: function() { },
		
        //Ensures the required parameters are supplied.
        _optionsValid: function () {
            if (this.options.userID === -1 && this.options.serviceUrl == "") {
                $(this.element).html('<div style="color: Red">The "userID" parameter must be specified!</div>');
                return false;
            }

            if (this.options.cirrusUrl === "") {
                $(this.element).html('<div style="color: Red">The "cirrusUrl" parameter must be specified!</div>');
                return false;
            }
            
            if (this.options.mlsID === "") {
            	$(this.element).html('<div style="color: Red">The "mlsID" parameter must be specified!</div>');
                return false;
            }

            return true;
        },
        _setTemplate: function () {
            var self = this;
            var elem = $(this.element);
            //If a non-default template is specified, apply it.
			elem.html('<div class="ssThumbnailContainer">' +
							'<img class="ssThumbnail" />' +
						'</div>' +
						'<div class="ssInfo">' +
							'<div class="ssPrimaryInfo"> ' +
								'<div class="ssPrice"></div>' +
								'<div class="ssStreet"></div>' +
								'<div class="ssCityStateZip"></div>' +
							'</div>' +
							'<div class="ssSecondaryInfo">' +
								'<div class="ssMlsNumber"></div>' +
								'<span class="ssBeds"></span><span class="ssBaths"></span>' +
								'<div class="ssSqft"></div>' +
								'<div class="ssLotSize"></div>' +
							'</div>' +
						'</div>');
        },
        //Plays the slideshow.
        _play: function () {
            var listings = this.element.data("listings");
            //If there's more than 1 listing, play the slideshow it it's not already playing
            if (listings.length > 1 && !this.element.data("slideshow")) {
                var ss = setInterval($.proxy(this._next, this),
                    this.options.interval * 1000
                );

                this.element.data("slideshow", ss);  //store handle to slideshow
            }
        },
        //Displays the next listing.
        _next: function () {
            var listings = this.element.data("listings");
            var i = this.element.data("index");
            (i < listings.length - 1) ?
                this.element.data("index", ++i) :  //if not at the last listing, go to next listing
                this.element.data("index", 0);  //if at the last listing, go back to first listing

            this._display();
        },
        //Pauses the slideshow
        _pause: function () {
            var ss = this.element.data("slideshow");
            if (ss) {
                clearInterval(ss);
                this.element.data("slideshow", null);
            }
        },
        //Displays the listing the index is currently pointing to.
        _display: function (index) {
            var listings = this.element.data("listings");
            var i = this.element.data("index");
            var self = this;
            self._bindListing(listings[i]);

            //Preload the thumbnail of the next listing so is displays instantly.
            if (i + 1 < listings.length && listings[i + 1].Thumbnail != "") {
                var thumb = new Image();
                thumb.src = listings[i + 1].Thumbnail;
            }
        },
        _bindListing: function (listing) {
            var self = this;
            var elem = $(this.element);
            elem.find("img.ssThumbnail").attr("src", listing.Thumbnail);
            elem.find("div.ssThumbnail").css("background", "url(" + listing.Thumbnail + ")");
            elem.find(".ssPrice").html(listing.Price);
            elem.find(".ssStreet").html(listing.Street);
            elem.find(".ssCityStateZip").html(listing.CityStateZip);
            elem.find(".ssMlsNumber").html("<label>MLS#</label> " + listing.MlsNumber);
            
            if (listing.Beds > 0)
            {
                elem.find(".ssBeds").html("<label>Beds:</label> " + listing.Beds);
                elem.find(".ssBeds").show();
            }    
            else
            	elem.find(".ssBeds").hide();
            	
            if (listing.Baths !== "")
            {
            	elem.find(".ssBaths").html("<label>Baths:</label> " + listing.Baths);
                elem.find(".ssBaths").show();
            }
            else
            	elem.find(".ssBaths").hide();
                
            if (listing.Sqft > 0)
            {
                elem.find(".ssSqft").html("<label>Sqft:</label> " + listing.Sqft);
                elem.find(".ssSqft").show();
            }
	    else
	    	elem.find(".ssSqft").hide();
	    	
            if (listing.LotSize !== "")
            {
                elem.find(".ssLotSize").html("<label>Lot Size:</label> " + listing.LotSize);
                elem.find(".ssLotSize").show();
            }
            else
                elem.find(".ssLotSize").hide(); 
                
            var redirectUrl = self.options.cirrusUrl;

            //append appropriate character to query string
            (redirectUrl.indexOf("?") == -1) ? redirectUrl += "?" : redirectUrl += "&";
            
            //add the service ID so Cirrus can verify
            redirectUrl += "cirrusServiceID=223&listingID=";
            
            elem.click(function () { window.location = redirectUrl + listing.MlsNumber; });
        }
    });
})(jQuery);
