﻿/// <reference path="jquery-1.4.4.js" />

(function ($4)
{

	function WdScroller( theSelector )
	{
		var self = this,
			_scroller = $( theSelector ),
			_scrollerContent = $( '.wd-scrollerContent', _scroller ),
			_btnTobble = $( ".wd-toggle", _scroller );

		$.extend(self,
		{
			next: function ()
			{
				if( _scrollerContent.data("scrollable") )
					_scrollerContent.scrollable().next();
			},

			prev: function ()
			{
				if( _scrollerContent.data("scrollable") )
					_scrollerContent.scrollable().prev();
			},

			toggle: function ()
			{
				if( _scrollerContent.data("scrollable") )
				{
					if( _btnTobble.hasClass( "wd-pause" ) )					
					{
						_btnTobble.addClass( "wd-play" ).removeClass( "wd-pause" );
						_scrollerContent.scrollable().stop();
					}
					else
					{
						_btnTobble.addClass("wd-pause").removeClass("wd-play");
						_scrollerContent.scrollable().next().play();
					}
				}
			}
		});

		// Attach the scroller to the element
		_scroller.data( "wdScroller", this );

		// Bind the events
		$( ".wd-next", _scroller).click( this.next );
		$( ".wd-prev", _scroller ).click( this.prev );
		_btnTobble.click( this.toggle );

		// Show the loading message while performing the AJAX operation
		_scrollerContent.loadmask( "Loading...", 200 );

		$.ajax
		(
			{
					url: _scroller.data( "wdUrl" )
				,	cache: false
				,	dataType: "json"
				,	success: function( theResponse )
					{
						// Populate with the response
						$.each
						(	theResponse,
							function( theIndex, theTip )
							{
								$( ".wd-items", _scrollerContent ).append
								(	$( "<div class='wd-item'></div>" )
									.append( $( "<div class='wd-title wd-marron'></div>" ).html( theTip.Title ) )
									.append( $( "<div class='wd-html wd-gray'></div>" ).html( theTip.Html ) )
								)
							}
						);

						// Hide the loading message
						_scrollerContent.unloadmask();

						// Setup the scrollable
						_scrollerContent.scrollable( { items: ".wd-items", circular: true } ).autoscroll( { interval:10000, autopause:false, autoplay:_btnTobble.hasClass( "wd-pause" ) } );
					}
				,	error: function( theXmlRequest, theError, theException )
					{
						_scrollerContent
							.html( '<div class="wd-error">An error occurred while communicating with the server.</div>' )
							.unloadmask();
					}
				}
		);

	};

	$.fn.wdScroller = function ()
	{
		var theScroller = this.data( "wdScroller" );
		if( theScroller )
			return theScroller;

		this.each
		(	function ()
			{
				theScroller = new WdScroller( this );
			}
		);

		return theScroller;
	};

})(jQuery);
