
(function( $ ){
	var P4Slides = function (element, options) {
		this.el = element;
		this.$el = $(element);		
		this.textAreas = new Array();
		this.images = new Array();
		this.paused = false;
		this.overlayImage = '';
		this.current = -1;
		this.init(options);
		this.imageMode = 'by_sequence';
		this.textMode = '';
		
		var self = this;
	}
	
	P4Slides.prototype = {
		options: {
			xml: "swfxml.phtml",
			interval: 5000,
			transitionTime: 800,
			mode: 'production',
			thumbSize: '100x100',
			transitionCallback: function(data) {
				/* default fade-out transition */
				data.currentImage.fadeOut(data.settings.transitionTime);
				data.nextImage.fadeIn(data.settings.transitionTime, function() {
					data.nextImage.addClass('active');
					
					//if ($('#'+data.container.attr('id')+' .imageSwapContainer div.imageSwapImage').length > 1 ) {
					if (data.container.find('.imageSwapContainer div.imageSwapImage').length > 1 ) {
						$(data.currentImage).remove();
					}
					inTransition = false;
					data.container.trigger('p4SlidesTransitionStop');				
				});		
			}
		},
		
		init: function(options) {
			this.options = $.extend({},this.options, options);

			// image transition
			var obj = this;

			this.$el.bind('p4SlidesTransitionStop', function() {
				obj.debug('transition Stop');
				obj.inTransition = false;
			});

			this.$el.bind('p4SlidesPause', function() {
				obj.pause();
			});

			this.$el.bind('p4SlidesPlay', function() {
				obj.play();
			});

		},
		setOptions: function(key, value){
			if (typeof key === 'object') {
				this.options = $.extend({},this.options, key);
			} else if(typeof key === 'string' && typeof value !== 'undefined') {
				this.options[key] = value;
			}
		},
		start: function() {
			//var obj = this;
			this.xmlData = $.ajax({
				type: "GET",
				url: this.options.xml,
				dataType: "xml",
				data: {'id': this.options.id},
				context: this,
				success: function(data) {
					this.parseXML(data);
				}
			});
		},
		pause: function() {
			this.paused = true;
		},
		play: function() {
			this.paused = false;
		},
		togglePause: function() {
			this.paused = (this.paused ? false : true);
			this.debug('paused', this.paused);
		},
		isPaused: function() {
			return this.paused;
		},
		next: function() {
			clearInterval(this.imageSwapper);
			this.swapImages();
			//this.imageSwapper = setInterval(this.swapper, this.options.interval);
			
			var obj = this;			
			var timerFunction = function() { obj.swapper(obj);}
			this.imageSwapper = setInterval(timerFunction, this.options.interval);
	
		/*	this.imageSwapper = setInterval(function(that) {
				that.swapper(that);
			}, this.options.interval, this);
			*/

			
		},
		previous: function() {
			clearInterval(this.imageSwapper);
			this.swapImages('prev');
			/*this.imageSwapper = setInterval(this.swapper, this.options.interval);
			this.imageSwapper = setInterval(function(that) {
				that.swapper(that);
			}, this.options.interval, this);
			*/
			
			var obj = this;			
			var timerFunction = function() { obj.swapper(obj);}
			this.imageSwapper = setInterval(timerFunction, this.options.interval);

		},
		getImages: function() {
			return this.images;
		},
		getCurrent: function() {
			return this.current;
		},
		bind: function(event, callback) {
			this.$el.bind(event, callback);
		},
		getCurrentThumb: function() {
			return $('#p4SlidesThumb_'+this.$el.attr('id')+'_'+this.current);
		},		
		parseXML: function(xml) {
			var obj = this;
			/* settings.. */
			var overlayElem = $(xml).find('overlay');
			if (overlayElem.text() != '' && overlayElem.text() != "") {
				overlayImage = $('<img src="'+overlayElem.text()+'" style="position:absolute; z-index:200; left:'+overlayElem.attr('pos_x')+'px; top:'+overlayElem.attr('pos_y')+'px"/>');
				this.$el.find('.imageSwapContainer').append(overlayImage);
			}
			
			var imageMode = $(xml).find('image_mode');
			if (imageMode.text() == 'random') {
				this.imageMode = 'random';
			}
			
			this.textMode = $(xml).find('text_mode').text();

			/* textareas */
			$(xml).find('text_areas').find('text').each(function() {
				var $areaElem = $('<div>');
				$areaElem.css({
					position: 'absolute',
					left: $(this).attr('pos_x')+'px',
					top: $(this).attr('pos_y')+'px',
					height: $(this).attr('height')+'px',
					width: $(this).attr('width')+'px',
					'font-size': $(this).attr('font-size'),
					color: '#'+$(this).attr('color')
				});
				
				$areaElem.addClass('p4SlidesTextArea');
				$areaElem.addClass('p4SlidesTextAreaName_'+$(this).attr('name'));
				
				obj.textAreas[$(this).attr('name')] = $areaElem;
			});
			/* images */
			$(xml).find('image').each(function() {
				var imageName = $(this).find('image_file').text().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
				
				var imageLink = '';
				
				if (obj.textMode == 'banner') {
					imageLink = $(this).find('image_link').text();
				}
				
				//console.log('imagelink: '+imageLink);
				
				var texts = new Array();
				$(this).find('text').each(function(){
					var text = { 
						name: $(this).attr('name'),
						text: $(this).text().replace(/^\s\s*/, '').replace(/\s\s*$/, ''),
						type: ($(this).attr('link') ? 'link' : 'text' ),
						link: $(this).attr('link')
					};
					texts[$(this).attr('name')] = text;
				});
				
				var thumbArr = imageName.split('/');
				var thumbName = 'files/'+thumbArr[1]+'/' +obj.options.thumbSize+'/'+thumbArr.pop();
				
	
				obj.images.push({
					name: imageName,
					texts: texts,
					loaded: false,
					thumbName: thumbName,
					imageLink: imageLink
	
				});
			});
			
			var removableImages = new Array();
			var firstLoaded = false;
			var imagesLoaded = 0;				
			var triggeredLoaded = false;

			this.$el.bind('p4SlidesLoaded', function() {
				obj.debug('loaded', 'images');
				obj.swapImages('0');
				
				/*obj.imageSwapper = setInterval(function(that) {
					that.swapper(that);
				}, obj.options.interval, obj);
				*/
				
				var timerFunction = function() { obj.swapper(obj);}
				obj.imageSwapper = setInterval(timerFunction, obj.options.interval);

			});
			
			$(this.images).each(function(imageIndex) {
				var imageIndex = imageIndex;
				var imageWrapper = $('<div class="imageSwapImage"></div<');
				imageWrapper.css({
					'display': 'none',
					'overflow': 'hidden',
					'position': 'absolute',
					'background-color': '#fff',
					width: '100%',
					height: '100%'
				});
				
				
				var src = this.name;
				var imageTag = $('<img/>').attr('src', this.name);
				
				var image =  imageTag.load();

				if (obj.textMode == 'banner') {					
					if (this.imageLink != "") 
					{
						var imageLink = this.imageLink;
						image.click(function() {
							window.location=imageLink;
						})
						image.css('cursor', 'pointer');
					}
				}

				
				obj.debug('image loaded', imageIndex+':'+obj.images[imageIndex].name);
				
				imageWrapper.append(image);
				obj.images[imageIndex].loaded = true;
				
				var thumbImage = $('<img/>');
				thumbImage.attr('src', obj.images[imageIndex].thumbName);
				var thumb = $('<div class="p4SlidesThumb" id="p4SlidesThumb_'+obj.$el.attr('id')+'_'+imageIndex+'"></div>');
				
				thumb.click(function() {
					clearInterval(obj.imageSwapper);
					obj.debug('imageIndex', imageIndex);
					obj.swapImages(''+imageIndex);
					/* //obj.imageSwapper = setInterval(swapper, obj.settings.interval);
					obj.imageSwapper = setInterval(function(that) {
						that.swapper(that);
					}, obj.options.interval, obj);
					*/
					
					var obj = this;			
					var timerFunction = function() { obj.swapper(obj);}
					this.imageSwapper = setInterval(timerFunction, this.options.interval);
					
				}).css({
					'position': 'absolute',
					'top': 0,
					'left': 0
				});

				thumb.append(thumbImage);
				
				$.extend(obj.images[imageIndex], {img: imageWrapper, 'thumb': thumb});
				
				if (!firstLoaded) {
					obj.$el.find('.imageSwapContainer').append(imageWrapper);
					firstLoaded = true;
					current = this.swapTo;
					obj.$el.trigger('p4SlidesChange');
					obj.swapTo++;
					
				}
				
				if (imagesLoaded == obj.images.length-1) {
					
					/*obj.$el.bind('p4SlidesLoaded', function() {
						$('#p4slides_debug').append($('<p>foo trigger</p>'));
						
					});*/
					
					if (!triggeredLoaded) {
						triggeredLoaded = true;
						obj.$el.trigger('p4SlidesLoaded');
						
					}
				}
				
				imagesLoaded++;
				

				
			});
			
			$(removableImages).each(function(i, val) {
				debug('removing', val);
				debug('images', val);
				this.images.splice(val,1);
	
			});
		},				
		swapper: function(obj) {
			if (this.paused) {
				return;
			}
			
			obj.swapImages();
		},
		swapImages: function(manual) {
			this.debug('running swap images');
			if (this.inTransition) {
				return;
			}
			
			if (this.current == parseInt(manual)) {
				return;
			}

			this.inTransition = true;
			this.$el.trigger('p4SlidesTransitionStart');
	
			var direction = 'next';

			if (this.imageMode == 'random') {
				
				var rnd;
				do { 
					rnd = Math.floor(Math.random()*(this.images.length));
					this.debug('rnd', this.swapTo+':'+rnd);
				} while (rnd == this.swapTo);
				
				this.swapTo = rnd;
				
			} else {
				/* swap to previous image */
				if (manual != 'undefined' && manual == 'prev') { 
					direction = 'prev';
		
					this.swapTo = this.swapTo-2;
					if (this.swapTo < 0 ) {
						this.swapTo = this.images.length-1
					}; 			
				} else {
					
					/* swap to image by image number */
					if (manual != undefined && manual != '' && !isNaN( parseInt( manual ))) {
						direction = (this.images.length - this.current >= this.images.length - manual ? 'next' : 'prev');
						this.swapTo = manual;
					}
						
					if (this.swapTo < 0 || this.swapTo > this.images.length-1) {this.swapTo = 0}
				
					/* loop until all the images has been pre loaded */
					while (this.images[this.swapTo].loaded == false) {
						this.swapTo++;
						if (this.swapTo < 0 || this.swapTo > this.images.length-1) {
							this.swapTo = 0
						}
					}
				}
			}
			// console.dir(images);

			this.debug('this.swapTo', this.swapTo);
			this.debug('manual', manual);
			this.current = this.swapTo;
			// Create and add new image to DOM
			$(this.images[this.swapTo].img).css({
				'display': 'none',
				'z-index': 2
				});
			
			var imageElem = this.images[this.swapTo].img;
			this.$el.find('.imageSwapContainer').append(imageElem);
			
			this.$el.find('div.imageSwapImage:last .p4SlidesTextArea').remove();
			for (i in this.textAreas) {
				//console.log('texts.length'+this.images[this.swapTo].texts.length+', i:'+i);
				if (this.textAreas[i]['processed'] == undefined) {
					var textArea = this.textAreas[i].clone();
					if(this.images[this.swapTo].texts[i]) {
					if ( this.images[this.swapTo].texts[i].link) {
						$link = $('<a/>');
							$link.attr('href', decodeURIComponent(this.images[this.swapTo].texts[i].link));
						$link.text(this.images[this.swapTo].texts[i].text);
						textArea.html($link);
					} else {
							//console.log('swapTo:'+this.swapTo+', i:'+i);
						textArea.html(this.images[this.swapTo].texts[i].text);					
					}
					}
		
					this.$el.find('div.imageSwapImage:last').append(textArea);
				}
			}	
			
			if (typeof this.options.transitionCallback == 'function') {
				var transitionData = {
					nextImage: this.$el.find("div.imageSwapImage:last"),
					currentImage: this.$el.find("div.imageSwapImage:first"),
					direction: direction,
					container: this.$el,
					settings: this.options
				};

				this.options.transitionCallback(transitionData);
			} else {
				alert('transitionCallback must be function!');
			}
	
			this.$el.trigger('p4SlidesChange');
	
			this.swapTo++;
		},		debug: function(context, msg) {
			if (this.options.mode=='dev') {
				if (typeof msg == "undefined") {
					msg = context;
					context = "undef";
				}
	
				if (typeof console != "undefined") {
					if (typeof msg == 'object') {
						if (typeof console.group != undefined) {
							console.group(context);
							console.dir(msg);
							console.groupEnd();
						} else {
							console.log("%s: %s", context, msg);
						}
					} else {
						console.log("%s: %s", context, msg);
					}
				}		
			}
		}	
	};
	
	$.fn.P4Slides = function(options) {
		return new P4Slides(this, options);
	};

})(jQuery);
