//when the dom is ready...
window.addEvent('domready', function() {
	//time to implement fancy show / hide
	Element.implement({
		//implement show
		fadeIn: function() {
			this.fade('in');
		},
		//implement hide
		fadeOut: function() {
			this.fade('out');
		},
		show: function() {
			this.setStyle('display','');
		},
		//implement hide
		hide: function() {
			this.setStyle('display','none');
		}
	});
});

// JavaScript Document
var JosefTrattner = new Class({
	Implements: [Options, Events],
	//baseUrl: 'http://localhost/clients/joseftrattner/',
	baseUrl: 'http://www.joseftrattner.at/',
	imgPath: 'img/',
	phpPath: 'php/',
	loader: 'img/loader.gif',
	defaultContent:null,
	enableLog:false,
	months:[
		'january',
		'february',
		'march',
		'april',
		'may',
		'june',
		'jule',
		'august',
		'september',
		'october',
		'november',
		'december'
	],
	menuOptions:{ // Fx.Tween
		unit:'px',	
		duration:100,
		transition:'sine:out',
		link: 'chain'
	},
	thumbOptions:{ // Fx.Tween
		unit:'px',	
		duration:250,
		transition:'sine:out',
		link: 'chain'
	},
	options:{
		thumb_width: 100,
		thumb_height: 75,
		thumb_reflection_height: .4, //%
		thumb_reflection_startopacity: .5, //%
		thumb_transition_offset: 20, //px
		link_transition_offset: 5 //px
	},
	links:[],
	thumbs:[],
    initialize: function(options){
		this.log("f() initialize");
		this.setOptions(options);
		if(options.baseUrl){ 
			this.baseurl = options.baseUrl;
		}
		this.contentDIV = $('content');
		this.menuContainer = $('menu');
		this.initMenu();
		var spy = new ScrollSpy({
			onTick: function(position){
				$('left').setStyle('top',position.y+"px");
				//console.log('SET TOP '+position.y);
			}.bind(this)
		});
    },
	menuInitialized: function(){
		var mp = this.menuContainer.getPosition();
		var ms = this.menuContainer.getSize();
		this.loaderDiv = new Element('div',{'id':'loader',
			styles:{
				'background-image':'url('+this.baseUrl+this.loader+')',
				'background-position':'0 50%',
				'background-repeat':'no-repeat',
				'position':'absolute',
				'left':mp.x+'px',
				'top':mp.y+'px',
				'width':ms.x+'px',
				'height':ms.y+'px'
			}
		}).inject(this.menuContainer,'after');
		this.loaderDiv.hide();
		if(this.defaultContent !== null)
			this.loadContent(this.defaultContent);
	},
	initMenu: function(){
		this.log("f() initMenu");
		var request = new Request({
			url: this.baseUrl+'data/menu.json',
			noCache: true,
			method: 'get',
			onSuccess: this.onMenuLoad.bind(this),
			//onComplete: this.onMenuComplete.bind(this),
			onFailure: this.onMenuLoadFailure.bind(this)
		});
		request.send({});
	},
	onMenuLoad: function(response) {
		this.log("menu.json loaded");
		var o = JSON.decode(response);
		this.buildMenu(o);
	},
	onMenuLoadFailure: function(e) {
		if(console) console.log(e);
	},
	buildMenu: function(o){
		this.log("f() buildMenu");
		var m,d;
		for(var i in o.items){
			var item = o.items[i];
			if(item.spaceabove) this.injectContentBR(this.menuContainer);
			if(item.showtitle) new Element('div',{'text':i}).inject(this.menuContainer);
			var href = 'javascript:;';
			if(item.link){
				href = item.link;
			}
			if(typeof href == "object" && typeof item.text == "object"){
				for(var j = 0;j<href.length;j++){
					d = new Element('div',{'id':'menuPointContainer'});
					m = new Element('a',{'id':item.module,'href':href[j],'text':item.text[j],'target':'_blank',
								'styles':{'padding-left':'0px'}});
					d.inject(this.menuContainer);
					m.inject(d);
					m.addEvent('mouseover', function(e) {this.toggleMenuState($(e.target));}.bind(this));
					m.addEvent('mouseout', function(e) {this.toggleMenuState($(e.target));}.bind(this));
					this.addLink(d,m);
				}
			} else {
				d = new Element('div',{'id':'menuPointContainer'});
				m = new Element('a',{'id':item.module,'href':href,'text':item.text,
								'styles':{'padding-left':'0px'}});
				d.inject(this.menuContainer);
				m.inject(d);
				m.addEvent('mouseover', function(e) {this.toggleMenuState($(e.target));}.bind(this));
				m.addEvent('mouseout', function(e) {this.toggleMenuState($(e.target));}.bind(this));
				this.addLink(d,m);
			}
			if(item.module){
				m.addEvent('click', function(e) { 
					JT.loadContent($(e.target).id); 
				}.bind(this));
			}
		}
		this.menuInitialized();
	},
	addLink: function(div,el){
		if(this.getLink(el) === null)
			this.links.push({div:div,a:el,tw:new Fx.Tween(div,this.menuOptions),toggle:0});
	},
	getLink: function(el){
		for(var i=0;i<this.links.length;i++){
			if(this.links[i].a == el) return this.links[i];
		}
		return null;
	},
	toggleMenuState: function(el){
		var l = this.getLink(el);
		if(l.toggle){
			l.tw.start('margin-left', '0');
			l.toggle = 0;
		} else {
			l.tw.start('margin-left', this.options.link_transition_offset+'px');
			l.toggle = 1;
		}
	},
	showMenu: function(){
		this.log("f() showMenu");
		//this.menuContainer.setStyles({'display':''});
		this.menuContainer.show();
		this.loaderDiv.hide();
	},
	hideMenu: function(){
		this.log("f() hideMenu");
		//this.menuContainer.setStyles({'display':'hide'}); 
		this.menuContainer.hide();
		this.loaderDiv.show();
	},
	loadContent: function (module){
		if(this.allThumbsLoaded())
		{
			this.thumbs = new Array();
			var request = new Request({
				url: this.baseUrl+'data/'+module+'.json',
				noCache: true,
				method: 'get',
				onSuccess: this.onContentLoad.bind(this),
				//onComplete: this.onMenuComplete.bind(this),
				onFailure: this.onContentLoadFailure.bind(this)
			});
			request.send({});
		}
	},
	onContentLoad: function(response) {
		var o = JSON.decode(response);
		this.injectContent(o);
	},
	onContentLoadFailure: function(e) {
		console.log(e);
		this.showMenu();
	},
	injectContentBR: function(c,cl){
		if(cl === null) cl = "";
		if(!c){
			new Element('br',{'class':cl}).inject(this.contentDIV);
		} else {
			new Element('br',{'class':cl}).inject(c);
		}
	},
	injectContent: function (o){
		this.contentDIV.set('html','');
		this.contentDIV.setStyle('overflow','');
		new Element('p',{'class':'title','text':o.title}).inject(this.contentDIV);
		var cy = 9999999999999999999; // currentYear
		var cm = 9999999999999999999; // currentMonth
		var dateContainer;
		var hasThumbs = false;
		SortIt(o.items,-1,'year',-1,'month',-1,'id');
			for(var _c = 0;_c < o.items.length;_c++)
			{
				var co = o.items[_c];
				var ti = co.title; //String
				var ye = co.year; //Number
				var mo = co.month; //Number
				var ty = co.type; //String
				var de = co.description; //String
				var im = co.images; //Array
				var _im;
					if(ye !== cy || mo !== cm)
					{
						var yemo = '';
						if(mo === "x" || mo === "")
							yemo = ye;
						else yemo = this.months[mo-1]+" "+ye;
						new Element('p',{'text':yemo}).inject(this.contentDIV);
						this.injectContentBR();
						dateContainer = new Element('div',{'class':'dateContainer'}).inject(this.contentDIV);
					}
					if(ti !== ""){
						new Element('span',{'text':ti,'class':'title'}).inject(dateContainer);
						this.injectContentBR(dateContainer);
					}
					if(de !== "" || ty == "html"){
						var desc = new Element('span',{'class':'description'}).inject(dateContainer);
						desc.set('html',de);
						this.injectContentBR(dateContainer);
					}
					cy = ye;
					cm = mo;
					if(ty == "html")
					{
						desc.load("html/"+co.html);
					}
					if(ty == "image")
					{
						if(co.folder){
							var url = this.baseUrl+this.imgPath+co.folder+"/";
							var phpurl = this.phpPath+"thumb.php?folder="+co.folder+"&img=";
						} else {
							var url = this.baseUrl+this.imgPath;
							var phpurl = this.phpPath+"thumb.php?img=";	
						}
						for(_im = 0; _im < im.length;_im++)
						{
							hasThumbs = true;
							var image = im[_im];
							var thumb = new mooThumb({
								container: dateContainer,
								file: image,
								url: url+image,
								phpurl: phpurl+image,
								parent:this
							});
							this.addThumb(thumb);
							if(_im == im.length-1)
								this.injectContentBR(dateContainer,'clearLeft');
						}
					}
					if(ty == "imagewall")
					{
						var perrow = Math.floor(im/2);
						if(co.rows) perrow = Math.floor(im/co.rows);
						var inline = 0;
						if(co.folder){
							var url = this.baseUrl+this.imgPath+co.folder+"/";
							var phpurl = this.phpPath+"thumb.php?folder="+co.folder+"&img=";
						} else {
							var url = this.baseUrl+this.imgPath;
							var phpurl = this.phpPath+"thumb.php?img=";	
						}
						for(_im = 1; _im <= im;_im++)
						{
							hasThumbs = true;
							var image = "";
							if(_im >= 100) image = ""+_im+".jpg";
							if(_im < 100) image = "0"+_im+".jpg";
							if(_im < 10) image = "00"+_im+".jpg";
							var thumb = new mooThumb({
								width:27,
								height:40,
								padding:0,
								simple:true,
								popup:true,
								container: dateContainer,
								file: image,
								url: url+image,
								phpurl: phpurl+image,
								parent:this
							});
							this.addThumb(thumb);
							if(_im == im)
								this.injectContentBR(dateContainer,'clearLeft');
							
							inline++;
							if(inline >= perrow){
								this.injectContentBR(dateContainer,'clearLeft');
								inline = 0;
							}
						}
					}
					if(ty == "object")
					{
						for(_im = 0; _im < im.length;_im++)
						{
							var object = im[_im];
							new Element('div',{'html':object}).inject(dateContainer);
							if(_im == im.length-1)
								this.injectContentBR(dateContainer);
						}
					}
					if(ty == "link")
					{
						for(_im = 0; _im < im.length;_im++)
						{
							var a = im[_im].split('}');
							var text = a[0].substr(1);
							var url = a[1];
							var e = new Element('div').inject(dateContainer);
							var object = new Element('a',{
								'href':url,
								'text':text,
								'target':'_blank'
							}).inject(e);
							if(_im == im.length-1)
								this.injectContentBR(dateContainer);
						}
					}
					if(dateContainer)
						this.injectContentBR();
			}
			if(this.thumbs.length > 0) {
				this.hideMenu();
				this.loadNextThumb();
			}
			if(!hasThumbs) this.showMenu();
	},
	addThumb: function(thumb){
		if(this.getThumb(thumb) === null)
			this.thumbs.push(thumb);
	},
	getThumb: function(thumb){
		for(var i=0;i<this.thumbs.length;i++){
			if(this.thumbs[i] == thumb) return this.thumbs[i];
		}
		return null;
	},
	loadNextThumb: function(){
		for(var i=0;i<this.thumbs.length;i++){
			var t = this.thumbs[i];
			if(!t.loaded){
				this.thumbs[i].loadThumb();
				break;
			}
		}
		if(this.allThumbsLoaded()){
			this.showMenu();	
		}
	},
	allThumbsLoaded: function(){
		var r = true;
		for(var i=0;i<this.thumbs.length;i++){
			var t = this.thumbs[i];
			if(!t.loaded){
				r = false;
				break;
			}
		}
		return r;
	},
	log: function(t){
		if(this.enableLog){
			var ap =  t+"<br/>";
			$("logger").set('html',$("logger").get('html')+ap);
		}
	}
});
