(function($) {
	var pluginName = "slideShow";

	$.fn[pluginName] = function(config) {
		var defaults = {
			hostName : 'http://gakkai.macc.jp',
			url : 'slideShow.jsp',
			imageList : [],
			duration : 15 * 1000,
			transitionDuration : 4 * 1000,
			width: '800px',
			height: '326px'
		}; 
		var opts = $.extend( defaults , config);

		$(this).css( {
			position:'relative',
			width: opts.width,
			height: opts.height,
			margin:'0px',
			padding:'0px',
			'margin-left':'auto',
			'margin-right':'auto',
			'background-color':'#EEE',
			color:'#AAA'
		});
		$(this).html('<div style="padding:8px;font-weight:bold;font-size:12px;font-family:arial">LOADING...</div>');

		var elements = this;
		/** IMAGE LIST INIT */
		var initImages = function ( imageList ) {
			for( var i = 0 ; i < imageList.length ; i++ ) {
				var visible = ';visibility:hidden';
				if( i == (imageList.length-1) ) visible = ';visibility:visible';
				var imgName = '<img src="' + opts.hostName + imageList[i] + '" style="position:absolute;left:0px;top:0px;z-index:' + (i+1) + visible + '" />';
				$(elements).append( imgName );
/*				var newImg = new Image();
				newImg.src = imageList[i];
				$(newImg).css({position:'absolute',left:'0px',top:'0px','z-index':(i+1)});
				$(elements).append( newImg ); */
			}
		}
		/** TIMER FUNCTION */
		var divId = '#' + $(this).attr('id');
		var tmFunc = function() {
			$( divId + ' img').each( function() {
				$(this).css( 'visibility' , 'visible' );
				if( $(this).css('z-index') == opts.imageList.length) {
					$(this).animate( {opacity:0} , opts.transitionDuration , function() {
						$( divId + ' img').each( function() {
							var zIdx = $(this).css('z-index');
							if( zIdx == opts.imageList.length ) {
								$(this).css( 'z-index' , 1);
								$(this).css( 'opacity' , 100 );
							} else {
								$(this).css( 'z-index' , parseInt(zIdx) + 1 );
							}
						});
					});
				}
			});
			setTimeout( tmFunc , opts.duration);
		}
		/**
		 * imageのリストを指定するか、imageのリストを返すJSONPおSERVICE URLを指定する
		 */
		if( opts.imageList.length == 0 ) {
			var ret = jQuery.ajax({
				url: opts.hostName + "/" + opts.url ,
				dataType : 'jsonp',
				type : 'GET',
				complete : function() {
				} ,
				success : function(data,status) {
					if( status == 'success' ) {
						opts.imageList = data;
						initImages( data );
						setTimeout( tmFunc , opts.duration );
					} else {
						alert("ERROR OCCURED!");
					}
				} ,
				error : function( req , status , ex ) {
					alert(ex);
				}
			});
		} else {
			initImages( opts.imageList );
			setTimeout( tmFunc , opts.duration );
		}
		return this;
	};
})(jQuery);
