//Yamoodow 1.0 - (c) 2009 Christian Opitz, Netzelf - http://netzelf.de - Released under the MIT License
var yamoodow = new Class({
	Implements: [Options,Events],
	options: {
		opener:null,
		title:'',
		buildTabs:true,
		width: 795,
		height: 404,
		overlayOpacity: 0.8,
		overlayFadeDuration: 400,
		windowFadeDuration: 400,
		lang: {
  		loading: 'Loading...',
  		loaded: 'Ready',
  		failure: 'Error: ',
  		httpCodes: {
        '404':'page not found',
        '403':'forbidden'
      }
    },
		cssPrefix: 'ymd',
		cache: true
	},
	initialize: function(tabs, options) {
		this.setOptions(options);
		this.tabs = tabs;
		
		this.overlay = new Element('div', {id: this.options.cssPrefix+'Overlay', events: {click: this.closeWin.bind(this)}});
		this.win = new Element('div', {id: this.options.cssPrefix+'Window', styles: {width: this.options.width, display: 'none'}});
		
		this.fxOverlay = new Fx.Tween(this.overlay, {property: "opacity", duration: this.options.overlayFadeDuration}).set(0);
		this.fxWindow = new Fx.Tween(this.win, {property: "opacity", duration: this.options.windowFadeDuration}).set(0);
		this.title = new Element('div', {id:this.options.cssPrefix+'Title', 'text': this.options.title}).adopt(
					 new Element('div', {id:this.options.cssPrefix+'CloseLabel',events:{click:this.closeWin.bind(this)}}));
		this.head  = new Element('div', {'class':this.options.cssPrefix+'RightCorner'}).adopt(
		titleWrap  = new Element('div', {'class':this.options.cssPrefix+'LeftCorner'})).inject(this.win);
		this.title.inject(titleWrap);
				
		if (this.tabs && this.options.buildTabs) {
			//Build Navi
			this.nav = new Element('ul',{styles:{'margin':0,'padding':0}}).inject(new Element('div', {'id':this.options.cssPrefix+'Navi'}).inject(this.win));
			this.tabs.each(function(tab,i){
				this.tabs[i].li = new Element('li', {
					'text':tab.text,
					'events': { 
						'click': this.load.bind(this,i)
				}}).inject(this.nav)
			}.bind(this));
		}
		
		this.bottom    = new Element('div', {'id':this.options.cssPrefix+'Bottom'}).adopt(
						         new Element('div', {'class':this.options.cssPrefix+'RightCorner'}).adopt(
		statusWrap     = new Element('div', {'class':this.options.cssPrefix+'LeftCorner'})));
		this.statusBar = new Element('div', {'class': this.options.cssPrefix+'StatusBar'}).inject(statusWrap);
		
		window.addEvent('domready',function(){
      $(document.body).adopt(this.overlay, this.win);
			this.contentHeight = this.options.height - this.win.getSize().y;
			this.containerWrap = new Element('div', {'id': this.options.cssPrefix+'ContainerWrap'}).setStyle('height',this.contentHeight).inject(this.win);
			this.container = new Element('div', {'class': this.options.cssPrefix+'Content',styles:{overflow:'auto',height:'100%'}}).inject(this.containerWrap);
			this.bottom.inject(this.win);
			
			if (this.options.opener) {
  			this.options.opener.removeEvent('click');
  			this.options.opener.removeProperty('href');
  			this.options.opener.addEvent('click', this.openWin.bind(this));
  		}
		}.bind(this));
		
		this.active = -1;
		this.cache = [];
		
		return this;
	},
	openWin: function() {
		compatibleOverlay = Browser.Engine.trident4 || (this.overlay.currentStyle && (this.overlay.currentStyle.position != "fixed"));
		if (compatibleOverlay) this.overlay.style.position = "absolute";
		this.win.setStyle('display','');
    this.fxOverlay.set(0).start(this.options.overlayOpacity).chain(function(){ this.fxWindow.start(1); }.bind(this));
		this.position();
		this.overlaySetup(1);

		if (this.active == -1) {
			this.active = 0;
			this.load(0);
		}
	},
	closeWin: function() {
		this.fxWindow.start(0).chain(function(){
			this.fxOverlay.cancel().chain(this.overlaySetup.bind(this,0)).start(0);
		}.bind(this));
	},
	position: function() {
		var scroll = window.getScroll(), size = window.getSize();
		this.win.setStyles({"left": scroll.x + (size.x / 2) - (this.options.width / 2),'top': scroll.y + (size.y / 2) - (this.options.height / 2)});
		$$(this.center, this.bottomContainer).setStyle("left", scroll.x + (size.x / 2));
		if (compatibleOverlay) this.overlay.setStyles({left: scroll.x, top: scroll.y, width: size.x, height: size.y});
	},
	overlaySetup: function(open) {
		["object", Browser.Engine.trident4 ? "select" : "embed"].forEach(function(tag) {
			Array.forEach(document.getElementsByTagName(tag), function(el) {
				if (open) el._slimbox = el.style.visibility;
				el.style.visibility = open ? "hidden" : el._slimbox;
			});
		});

		this.overlay.setStyle('display', open ? "" : "none");

		var fn = open ? "addEvent" : "removeEvent";
		window[fn]("scroll", this.position.bind(this))[fn]("resize", this.position.bind(this));
	},
	/* if second argument is set to true, cache of this tab is emptyed and tab gets reloaded */
	load: function(i) {
		if (this.options.buildTabs) {
      this.tabs[this.active].li.removeClass(this.options.cssPrefix+'Active');
  		this.tabs[i].li.addClass(this.options.cssPrefix+'Active');
		}
		this.toCache = this.active;
		this.active = i;
		if (!arguments[1]) {
			if (this.getCache()) return;
		} else this.cacheClear(this.active);
		this.tabs[this.active].status = null;
		if (this.tabs[i].iframe) this.loadIframe(); else this.loadAjax();
	},
	/* arguments:
	None (clear Statusbar immediately) or Text(optional), Add loading class (optional, bool), delay till message disappears (optional), Event (optional) */
	triggerStatus: function() {
		this.statusBar.set('html',arguments[0] || '');
		$clear(this.statusTimer);
		if (arguments[1]) this.statusBar.addClass(this.options.cssPrefix+'Loading'); else this.statusBar.removeClass(this.options.cssPrefix+'Loading');
		if (arguments[2]) this.statusTimer = this.triggerStatus.delay(arguments[2]*1000,this);
		if (arguments[3]) this.fireEvent(arguments[3],[$merge({container:this.container},this.tabs[this.active]),this.active]);
	},
	loadIframe: function(){
		this.triggerStatus(this.options.lang.loading,1,0,'load');
		this.writeCache();
		this.container.setStyle('overflow','visible');
		this.iframe = new IFrame({
			src: this.tabs[this.active].url,
			styles: {
				width:this.options.width,
				height:this.contentHeight,
				border:'none'
			},
			events: { load: this.triggerStatus.bind(this,[this.options.lang.loaded,0,3,'success']) }
		}).inject(this.container.empty());
	},
	loadAjax: function(){
		this.triggerStatus(this.options.lang.loading,1,0,'load');
		this.writeCache();
    this.container.setStyle('overflow','auto');  
		new Request.HTML({
			url:this.tabs[this.active].url,
			update:	this.container,
			onSuccess: this.triggerStatus.bind(this,[this.options.lang.loaded,0,3,'success']),
			onFailure: function(xhr){
        this.tabs[this.active].status = xhr.status;
        this.triggerStatus(this.options.lang.failure+this.options.lang.httpCodes[xhr.status],0,0,'failure'); }.bind(this)
		}).get();
	},
	writeCache: function() {
		if (!this.options.cache) return;
		this.cache[this.toCache] = this.container.setStyle('display','none');
		this.container = new Element('div', {'class': this.options.cssPrefix+'Content',styles:{overflow:'auto',height:'100%'}}).inject(this.containerWrap);
	},
	getCache: function() {
		if (!this.options.cache || !this.cache[this.active]) return false;
		this.cache[this.toCache] = this.container.setStyle('display','none');
		this.container = this.cache[this.active].setStyle('display','');
		return true;
	},
	cacheClear: function(i) {
		if (!this.options.cache) return;
		if (this.cache[this.active]) {
			this.cache[this.active].destroy();
			this.cache[this.active] = 0;
		}
	}
});