// disable Firebug in IE
if (!window.console) window.console = { log: function() { } }

/*
 * Animation Type:
 *  - Image for setting background style property
 *  - Text for setting innerHTML
 */
var AnimationType = { Image:1,Text:2 };
	


/*
 * Annimation class
 *  - use it whenever you need fadding funcionality
 */
var AnimationClass = Class.create({
	initialize: function(cImage, data, type)
	{
		this.obj = $(cImage);
		this.data = data;
		this.type = type;
		if(this.obj && this.data!=null && this.data.length>0)
			this.init();
	},
	
	init: function(){
		this.currentIndex = 0;
		this.cloneEl = new Element("div",{"class":this.obj.className,width:this.obj.getWidth(),height:this.obj.getHeight()});			
		this.cloneEl.zIndex = parseInt(this.obj.getStyle("zIndex"))+1;
		this.cloneEl.hide();
		this.obj.parentNode.appendChild(this.cloneEl);
		
		this.setData(this.data[0],this.obj);
		this.setData(this.data[1],this.cloneEl);
	},
	
	setData: function(val,el){
		var elToSetData = el || (this.cloneEl.style.display!="none" ? this.obj : this.cloneEl);			
		if(this.type==AnimationType.Image)
			elToSetData.style.background="url('"+val+"')";
		else{				
			elToSetData.update(val);
		}
		if(el==null){
			this.cloneEl[this.cloneEl.style.display!="none"?"fade":"appear"]({ duration: 1.0 });
			if(this.type==AnimationType.Text) this.obj[this.cloneEl.style.display!="none"?"appear":"fade"]({ duration: 1.0 });
		}
	},
	
	next: function(){
		console.log("Item:%s next", this.obj.className);

		this.currentIndex++;
		if(this.currentIndex>=this.data.length) this.currentIndex=0;
		this.setData(this.data[this.currentIndex]);
	},
	
	previous: function(){
		console.log("Item:%s previous", this.obj.className);

		this.currentIndex--;
		if(this.currentIndex<0) this.currentIndex=this.data.length-1;
		this.setData(this.data[this.currentIndex]);
	},
	
	goTo: function(num){
		console.log("Item:%s goTo[%s]", this.obj.className,num);

		if(num>=0 && num < this.data.length) this.currentIndex=num;			
		this.setData(this.data[this.currentIndex]);
	},
	
	registerEvent: function(name){
		console.log("Item:%s registeringEvent:%s", this.obj.className, name);
		document.observe(name, this.onChange.bind(this));
	},
	
	onChange: function(){
		console.log("Item:%s onChange:next", this.obj.className);
		
		this.next();
	}
});



/*
 * SimpleAnimation control
 *  - use it whenever you need to fade images
 */
var SimpleAnimation = Class.create((function(){
	var eventPrefix = "simpleanimation:";
	var obj,list,intervalId,animObj,delay,isImage;
	
	var constructor = function(o,l,d){
		obj = $(o);
		list = l;
		delay = d*1000;
		if(obj && list.length>0){ 
			isImage = (animObj=obj.select(".image")[0])!=null;
			if(isImage) init();
		}
	}
	
	var init = function(){
		if(isImage) animObj = new AnimationClass(animObj, list, AnimationType.Image);
		animObj.registerEvent(eventPrefix+"change");
	}
	
	var start = function(){
		stop();
		intervalId = setInterval(onChange,delay);
	};
	
	var stop = function(){
		clearInterval(onChange,delay);
	};
	
	var onChange = function(){ document.fire(eventPrefix+"change"); };

	return {
		initialize:constructor,
		start:start
	}
}()));



/*
 * Animation control
 *  - use it whenever you need items of fadding images with some navigation options
 */
var Animation = Class.create((function(){
	var eventPrefix = "animationcontrol:";
	var items = [];
	var obj,list,settings,
	imageIndex,
	validAction,
	intervalId,autoStartIntervalId,
	cImage,cTitle,cDescription,cNavigation,cLinkbox,
	isImage,isTitle,isDescription,isNavigation,isLinkbox,
	pageLinks, pauseLink;

	var constructor = function(o,l,s){
		obj = $(o);
		list = l;
		settings = Object.extend({prev:true,next:true,goTo:true,pause:true,prevText:"<",nextText:">",pauseText:"||"},(s || {}));		
				
		if(obj && list.length>0)
		{
			isImage = (cImage=obj.select(".image")[0])!=null;
			isTitle = (cTitle=obj.select(".title")[0])!=null;
			isDescription = (cDescription=obj.select(".description")[0])!=null;
			isNavigation = (cNavigation=obj.select(".navigation")[0])!=null;
			isLinkbox = (cLinkbox=obj.select(".link")[0])!=null;
			if(isImage || isTitle || isDescription) init();
			// TODO preloadImages();
		}
	}
	
	var init = function(){
		validAction = true;
		imageIndex=0;
		if(isImage) items.push(new AnimationClass(cImage, list.pluck("img"), AnimationType.Image));
		if(isTitle) items.push(new AnimationClass(cTitle, list.pluck("title"), AnimationType.Text));
		if(isDescription) items.push(new AnimationClass(cDescription, list.pluck("description"), AnimationType.Text));
		if(isNavigation) {
			renderNavigation();
			bindNavigation();
		}
		
		// Only for belvin
		if(isLinkbox) {
		    var linkData = [];
		    for(var i=0,l=list.length;i<l;i++)
		    {
		        var linkHtml = '<a href="'+list[i]["href"]+'" title="'+list[i]["hrefTitle"]+'">'+list[i]["hrefTitle"]+'</a>';
		        linkData.push(linkHtml);
		    }	
		    items.push(new AnimationClass(cLinkbox, linkData, AnimationType.Text));
	    }		
		// End
		
		items.invoke("registerEvent",eventPrefix+"change");
	}
	
	var renderNavigation = function(){
	    if(cNavigation.innerHTML!="") return;
		var html = "";
		
		if(settings.goTo) for(var i=0,l=list.length;i<l;i++)
			html += '<a href="#" title="" name="' + (i + 1) + '" class="goTo">' + (i + 1) + '</a>';
		if(settings.prev) html+='<a href="#" title="" class="prev">'+ settings.prevText +'</a>';
		if(settings.pause) html+='<a href="#" title="" class="pause">'+ settings.pauseText +'</a>';
		if(settings.next) html+='<a href="#" title="" class="next">'+ settings.nextText +'</a>';
		
		cNavigation.update(html);
	};
	
	var bindNavigation = function(){
		cNavigation.down(".prev").observe("click", function(ev){
			ev.stop();
			previous();
		});
		
		pauseLink = cNavigation.down(".pause");
		pauseLink.observe("click", function(ev){
			ev.stop();
			pause();
		});
		
		cNavigation.down(".next").observe("click", function(ev){
			ev.stop();
			next();
		});
		
		pageLinks = cNavigation.select(".goTo");
		for(var i=0,l=pageLinks.length;i<l;i++){
			pageLinks[i].observe("click", function(ev){  
				ev.stop();
				var el = ev.findElement("a");
				goTo(ev.element(), parseInt(el.getAttribute("name")));
			});
		}
	};
	
	var selectPage = function(indx){
		pageLinks.invoke("removeClassName","selected");		
		pageLinks[indx].addClassName("selected");
	}
	
	var start = function(){
		stop();
		intervalId = setInterval(onChange,6000);
		validAction = true;
		pauseLink.className = "pause";
	};
	
	var stop = function(changeClass){
		validAction = false;
		clearTimeout(autoStartIntervalId);
		clearInterval(intervalId);
		intervalId=null;
		if (changeClass != false)
		    pauseLink.className = "play";
	};
	
	var next = function(){
		if(validAction) {
			stop(false);
			imageIndex++;
			if(imageIndex>=pageLinks.length) imageIndex=0;
			selectPage(imageIndex);
			autoStartIntervalId = setTimeout(start,2600);
			items.invoke("next");
		}		
	};
	
	var previous = function(){
		if(validAction) {
			stop(false);
			imageIndex--;
			if(imageIndex<0) imageIndex=pageLinks.length-1;
			selectPage(imageIndex);
			autoStartIntervalId = setTimeout(start,2600);
			items.invoke("previous");
		}
	};
	
	var goTo = function(el,indx){
		console.log("Test:%s",items[0].currentIndex);
		if(validAction) {			
		    stop();
		    imageIndex=indx-1;
		    selectPage(imageIndex);
			autoStartIntervalId = setTimeout(start,2600);
			items.invoke("goTo",indx-1);
		}
	};
	
	var pause = function(){
	    if(intervalId==null) start();
	    else stop();
	};
	
	var onChange = function(){ 
		imageIndex++;
		if(imageIndex>=pageLinks.length) imageIndex=0;
		selectPage(imageIndex);
		console.log("[onChange] - Next image: %s", imageIndex);
		document.fire(eventPrefix+"change");
	};

	return {
		initialize:constructor,
		start:start,
		next:next,
		previous:previous,
		goTo:goTo,
		pause:pause
	}
}()));

