/**
 * @author daco
 */

function c(text) {
	return;
	if(document.all) { //document.all
		var db = document.body;
		if (!db) {return;}
		
		var ttt = new Element('span');
		ttt.setStyle({color:'#000', fontSize:'9px'});
		text = ''+text;
		ttt.update(text + '><br />');
		$('btNav').insert(ttt);
		
	} else {
		console.log(text);
	}
}

function IEVersion(){
	var _n=navigator,_w=window,_d=document;
	var version="NA";
	var na=_n.userAgent;
	var ieDocMode="NA";
	var ie8BrowserMode="NA";
	// Look for msie and make sure its not opera in disguise
	if(/msie/i.test(na) && (!_w.opera)){
		// also check for spoofers by checking known IE objects
		if(_w.attachEvent && _w.ActiveXObject){		
			// Get version displayed in UA although if its IE 8 running in 7 or compat mode it will appear as 7
			version = (na.match( /.+ie\s([\d.]+)/i ) || [])[1];
			// Its IE 8 pretending to be IE 7 or in compat mode		
			if(parseInt(version)==7){				
				// documentMode is only supported in IE 8 so we know if its here its really IE 8
				if(_d.documentMode){
					version = 8; //reset? change if you need to
					// IE in Compat mode will mention Trident in the useragent
					if(/trident\/\d/i.test(na)){
						ie8BrowserMode = "Compat Mode";
					// if it doesn't then its running in IE 7 mode
					}else{
						ie8BrowserMode = "IE 7 Mode";
					}
				}
			}else if(parseInt(version)==8){
				// IE 8 will always have documentMode available
				if(_d.documentMode){ ie8BrowserMode = "IE 8 Mode";}
			}
			// If we are in IE 8 (any mode) or previous versions of IE we check for the documentMode or compatMode for pre 8 versions			
			ieDocMode = (_d.documentMode) ? _d.documentMode : (_d.compatMode && _d.compatMode=="CSS1Compat") ? 7 : 5;//default to quirks mode IE5				   			
		}
	}
				 
	return {
		"UserAgent" : na,
		"Version" : version,
		"BrowserMode" : ie8BrowserMode,
		"DocMode": ieDocMode
	};		
}



// Add mouse wheel support to prototype
Object.extend(Event, {
        wheel:function (event) {
                var delta = 0;
                if (!event) event = window.event;
                if (event.wheelDelta) {
                        delta = event.wheelDelta/120;
                        if (window.opera) delta = -delta;
                } else if (event.detail) { delta = -event.detail/3;}
                return delta; //Safari Round
        }
});


/*
 * Base class with handy mixins.
 * 
 */

LazzoBaseClass = Class.create ({
	
	initialize: function(){
		
		if ($('bio')) {
			this.__initDomLoaded();
		} else {
			document.observe('dom:loaded', this.__initDomLoaded.bind(this));
		} 
		
		if (this._init) {
			this._init();
		}

	},
	
	/*
	 * Always perform this one.
	 * Calls _initDomLoaded on extended class if defined.
	 */
	__initDomLoaded: function(){
		
		var bionode					= $('bio');
		var mainnode				= $('main');
		var imageCol 				= $('imageCol');
		
		this.httphost				= mainnode.readAttribute('httphost');
		this.contextpath			= mainnode.readAttribute('contextpath');
		
		this.editmode				= mainnode.hasClassName('editmode');
		this.locale					= mainnode.readAttribute('locale');
		this.path					= mainnode.readAttribute('path');
		this.isNews					= this.path.match(/generic\/portfolios\/news/);
		
		this.userRoleIsAdmin		= false;
		
		if (bionode) {
			this.directory_id		= bionode.readAttribute('directory_id');
			if (bionode.readAttribute('userrole') && bionode.readAttribute('userrole') == 'admin') {
				this.userRoleIsAdmin= true;		
			}
		}
		
		if (this._initDomLoaded) {
			this._initDomLoaded();	
		}
		
	},

	_fireEvent: function(eventname, m){
		
		// http://blog.thinkature.com/index.php/2006/11/26/escaping-the-javascript-call-stack-with-settimeout/
		var memo = (m)? m:{};
		var f = function(){document.fire('custom:'+eventname, memo);};
		f.defer();
			
	},
	
	_observe: function(eventname, func) {
		
		document.observe('custom:'+eventname, func);
		
	},
	
	_stopObserving: function(eventname, func) {
		
		document.stopObserving('custom:'+eventname, func);
		
	},
	
	/*
	 * Different from _initDomLoaded. This one must be called specificaly in extended class with function as argument.
	 * This way we prevent a whole lot of unnecessary observers
	 */
	_onWindowResizeCall: function(func) {
		
		Event.observe(document.onresize ? document : window, "resize", func);
	
	}
	
});




Object.extend(Function.prototype, {

  executeOnDomLoaded: function() {
    var __method = this;
    document.observe('dom:loaded', function() {return __method.apply(__method);});
	return this;
  }

});

Object.extend(Function.prototype, {

  executeOnWindowResize: function() {
    var __method = this;
	Event.observe(document.onresize ? document : window, "resize", function() {return __method.apply(__method);});
	return this;  
  }

});

// obsolete?
ComicHouse.defaults = {
	minViewportHeight:690
};



ComicHouse.modalDialogButton = Class.create ({
	
	initialize: function() {
		this.locale = $('main').readAttribute('locale');
		switch (this.locale) {
		
			case 'ne':
				this.y = 0;
			break;
			case 'en':
				this.y = -96;
			break;
			case 'de':
				this.y = -192;
			break;
			case 'fr':
				this.y = -288;
			break;
			
		}
		
	},
	create: function(type, callback){
		this.callback = callback;
		this.button = new Element('div', {className:'button_' + type}).setStyle({backgroundPosition:'0 '+this.y+'px'});
		this.button.observe('mouseover', this._mouseover.bind(this)); this.button.observe('mouseout', this._mouseout.bind(this)); this.button.observe('mousedown', this._mousedown.bind(this)); this.button.observe('click', this._mouseclick.bind(this));
	},
	get: function(){
		return this.button;
	},
	_mouseover: function(){
		var ypos = this.y - 48;
		this.button.setStyle({backgroundPosition:'0 ' + ypos + 'px'});
	},
	_mouseout: function(){
		this.button.setStyle({backgroundPosition:'0 ' + this.y + 'px'});
	},
	_mousedown: function(){
		var ypos = this.y - 24;
		this.button.setStyle({backgroundPosition:'0 ' + ypos + 'px'});
	},
	_mouseclick: function(){
		this.callback();
		Dialogs.close();
	}
});


ComicHouse.modalDialog = function (text, buttons) {
	
	// blur any inputfield. Dont know why this goes wrong for IE.
	if (!Prototype.Browser.IE) {
		$$('input, textarea').invoke('blur');
	}
	
	var dialogBody = new Element('div', {id:'dialog-content-wrapper'});
	
	var dialogContent = new Element('div', {id:'dialog-content-text'}).update(text);
	dialogBody.insert(dialogContent); 
	
	var buttonsLength = buttons.length; 
	
	buttons.each(function(button, index){
		
		var buttonElement = button.get();
		if (buttonsLength == 1) {
			buttonElement.setStyle({left:'146px'});
		}
		if (buttonsLength == 2) {
			if (index==0) {
				buttonElement.setStyle({left:'100px'});
			}
			if (index==1) {
				buttonElement.setStyle({right:'100px'});
			}
		}
		
		dialogContent.insert(buttonElement);

	});
	
	var bottom = new Element('div', {id:'dialog-ch-bottom'}); dialogBody.insert(bottom); 

	var locale = $('main').readAttribute('locale');
	
	switch (locale) {
	
		case 'ne':
			var title = 'attentie';
		break;
		case 'en':
			var title = 'attention';
		break;
		case 'de':
			var title = 'achtung';
		break;
		case 'fr':
			var title = 'attention';
		break;
		
	}
	
	// insert modal dialog
	var dialog = new Dialog({
		title:title,
		content:dialogBody,
		width:350,
		height:135,
		padding:0,
		height: 'auto',
		opacity: .5,
		background:['#000', 'transparent'],
		close:{
			link:false,
			overlay:false,
			esc:false
		}
	});
	
	ComicHouse.quicktimeMovie.hide();
	
	dialog.open();
	
	return false;	
	
};




ComicHouse.PreviewPane = Class.create ({
	
	initialize: function(element) {
		
		this.element = element;
		
		if (Prototype.Browser.IE) {
			this.verticalOffset = -5;	
		} else {
			this.verticalOffset = -7;
		}
		
		this.pane = new Element('div', {className:'previewpane'}).hide();
		this.element.insert({top:this.pane});

		this._createImageNodes();
		
		var blur = new Element('div', {className:'previewpaneblur'});
		this.pane.insert(blur);
		
		this.pointer = new Element('div', {className:'previewpanepointer'});
		this.pane.insert(this.pointer);
		
		['one','two','three'].each(function(element, index){
			var node = new Element('div', {className:'previewpanecount '+element}).update(index+1);
			this.pane.insert(node);	
		}.bind(this));
		
		this.count = new Element('div', {className:'previewpanecount'});
		this.pane.insert(this.count);
		
		this.pane.observe('click', this._doClick.bind(this));

	},
	
	_doClick: function(){
		
		if (this.href) {
			location.href = this.href;
		}
		
	},
	
	_createImageNodes: function(){
		
		this.images = $R(0,3).map(function(nr, index){
			var img = new Element('img', {className:'previewimage'+index});
			this.pane.insert(img);	
			return img;
		}, this);
		
	},
	
	show: function(element){
		
		this.pane.show();
		
		var selectedElement = this.element.down('.selected');
		if (selectedElement)
			selectedElement.setStyle({color:'#B11A3B'}).removeClassName('selected');
		element.setStyle({color:'#fff'}).addClassName('selected');
		
	},
	
	showClickedPointer: function(){
		
		this.pointer.addClassName('clicked');
		
	},

	hideClickedPointer: function(){
		
		this.pointer.removeClassName('clicked');
		
	},
	
	hide: function(){
		
		this.pane.hide();
		var selectedElement = this.element.down('.selected');
		if (selectedElement)
			selectedElement.setStyle({color:'#B11A3B'}).removeClassName('selected');
		
	},
	
	position: function(/*int*/ top){
		
		this.pane.setStyle({top:top + this.verticalOffset + 'px'});
		
	},
	
	fill: function(/*array*/ images){
		
		images.each(function(src, index){
			
			this.images[index].src = src;
			
		}, this);
		
	},
	
	setHref: function(href){
		
		this.href = href;
				
	},
	
	setCount: function(count){
		
		this.count.update('4 [...'+count+']');
		
	}

});



ComicHouse.AuthorNavigation = Class.create ({
	
	initialize: function(suffix, index) {

		this.suffix = suffix;
		this.index = index;
		this.activePage = null;
		
		this.path = $('main').readAttribute('path');
		this._init();
		Event.observe(document.onresize ? document : window, "resize", this._checkHeightAndResize.bind(this));  
	
		ComicHouse.authorNavigationHelper.register(this);
	
	},
	
	_init: function(){

		this.navElement = $('portfoliodropdown' + this.suffix);
		this.portfoliodropdown_content = $('portfoliodropdown'+this.suffix+'_content');
		
		this.previewPane = new ComicHouse.PreviewPane(this.navElement);
		
		this.scrollbar = new ComicHouse.Scrollblock(this.portfoliodropdown_content, 
			{
				callback:this.previewPane.hide.bind(this.previewPane),
				leftAlign: true,
				customClassName: 'previewpane',
			 	offsetBy:{left:15,top:0},
				offsetTopImageBy:{left:3,top:0},
				offsetBottomImageBy:{left:0,top:0}
				
			 });

		this.navElement.select('a').
			invoke('observe', 'custom:doactivepage', this._doActivePage.bind(this)).
			invoke('observe', 'mouseover', this._doMouseOver.bind(this)).
			invoke('observe', 'mousedown', this._doMouseDown.bind(this)).
			invoke('observe', 'mouseup', this._doMouseUp.bind(this)).
			invoke('fire', 'custom:doactivepage');

		this._insertInfoLink();

		this.obscurer		= new Element('div', {className:'portfoliodropdown_obscurer'}).hide();
		this.obscurerLeft	= new Element('div', {className:'portfoliodropdown_obscurer-left'}).hide();
		this.obscurerRight	= new Element('div', {className:'portfoliodropdown_obscurer-right'}).hide();

		$('main').insert({bottom:this.obscurer});
		$('main').insert({after:this.obscurerLeft});
		$('main').insert({after:this.obscurerRight});
		
		$(document.body).observe('click', this._hideAndResetTopNavigation.bind(this));

	},
	
	_insertInfoLink: function() {
		var link = $('illustration-'+this.suffix+'-information');
		this.navElement.insert(link);
		link.show();
	},
	
	_hideAndResetTopNavigation: function(evt){
		var element = evt.element(); 
		if (element.hasClassName('portfoliodropdown_obscurer') || element.hasClassName('portfoliodropdown_obscurer-left') || element.hasClassName('portfoliodropdown_obscurer-right') || element.up().tagName=='HTML') {
			
			ComicHouse.topnavigation.shutAllDown();
			this.hide();
		
		}
		
	},
	
	_centerAlign: function(){
		
		if (this.scrollbar.hasScrollBar()) {
			this.portfoliodropdown_content.setStyle({left:0});
		} else {
			this.portfoliodropdown_content.setStyle({left:'-11px'});
		}
		
	},

	_doActivePage: function(evt) {
		
		if (!this.path) {return;}
		
		var element = evt.element();
		var href = element.readAttribute('href');
		
		var regex = new RegExp('/'+this.path+'/');
		
		if (href.match(regex)) {
			this.activePage = element;
			element.addClassName('activepage');
						
		}

	},

	_doMouseOver: function(evt){
		
		var element = evt.element();
		var activepage = element.hasClassName('activepage');
		if (activepage) {return;}
		
		var images = element.readAttribute('preview').evalJSON();
		var href = element.readAttribute('href');
		var count = element.readAttribute('count');
		
		var top = element.offsetTop - this.scrollbar.getScrollTop();
		this.previewPane.fill(images);
		this.previewPane.setHref(href);
		this.previewPane.setCount(count);
		this.previewPane.position(top);
		this.previewPane.show(element);

	},
	
	_doMouseDown: function(evt){
		
		var element = evt.element();
		var activepage = element.hasClassName('activepage');
		if (activepage) {return;}
		
		this.previewPane.showClickedPointer(element);
		
	},

	_doMouseUp: function(evt){
		
		var element = evt.element();
		var activepage = element.hasClassName('activepage');
		if (activepage) {return;}
		
		this.previewPane.hideClickedPointer(element);
		
		//this.navElement.select('a.activepage').invoke('removeClassName', 'activepage');
		
	},
	
	_checkHeightAndResize: function(){
		
		var bottomOffset = 300;
		
		var dupNode = this.portfoliodropdown_content.cloneNode(true);
		dupNode.writeAttribute('id', 'portfoliodropdown'+this.suffix+'_content_duplicate');
		$('main').insert(dupNode);
		dupNode.setStyle({height: 'auto'});		// measure real height
		
		var navElementHeight = dupNode.getHeight() + bottomOffset;
		
		var viewportHeight = document.viewport.getHeight();

		if (navElementHeight >= viewportHeight) {
			
			this.portfoliodropdown_content.setStyle({height:viewportHeight-bottomOffset+'px'});
			
		} else {
			
			this.portfoliodropdown_content.setStyle({height:'auto'});
			
		}

		dupNode.remove();
		
		if (this.navElement.visible()) {
			this.scrollbar.reset();		
			this._centerAlign();		
			this.previewPane.hide();
		}
		
	},
	
	_showIselects: function() {
		
		if (this._iselectsDone) {return;}
		
		var iselectSessionValues = ComicHouse.iselect.getSessionDirectoryIds();
		this.navElement.select('a').each(function(element){
			
			var directoryid = element.readAttribute('directoryid');
			
			if (iselectSessionValues.include(directoryid)) {
				element.update('√ '+ element.innerHTML);
			}
			
			
		});
		
		this._iselectsDone = true;
		
	},
	
	show: function() {

		this._showIselects();	

		ComicHouse.quicktimeMovie.hide();		
		ComicHouse.authorNavigationHelper.hideAll(this);
		
		ComicHouse.topnavigation.partiallyHideForAuthorNav(this.index);
		$(document.body).addClassName('iefix');
		this.obscurer.setOpacity(.85).show();
		this.obscurerLeft.setOpacity(.85).show();
		this.obscurerRight.setOpacity(.85).show();
		
		this._checkHeightAndResize();
		this.navElement.show();
		
		this.scrollbar.reset();
		// scroll activepage into view
		if (this.activePage) {
			this.scrollbar.setValueBy(this.activePage.offsetTop);
		}
		
		this._centerAlign();
		
	},
	
	// this is the same as hide method, but since we want show quicktime to call once, does not include hide quicktime.
	hideAll: function() {
		
		$(document.body).removeClassName('iefix');
		this.obscurer.fade({from:.85, to:0, duration:.4});
		this.obscurerLeft.fade({from:.85, to:0, duration:.4});
		this.obscurerRight.fade({from:.85, to:0, duration:.4});
		this.previewPane.hide();
		this.navElement.hide();
		
		
	},
	
	hide: function() {
		
		$(document.body).removeClassName('iefix');
		this.obscurer.fade({from:.85, to:0, duration:.4});
		this.obscurerLeft.fade({from:.85, to:0, duration:.4});
		this.obscurerRight.fade({from:.85, to:0, duration:.4});
		
		this.previewPane.hide();
		this.navElement.hide();
		
		ComicHouse.quicktimeMovie.show();
		
		ComicHouse.topnavigation.undoPartiallyHideForAuthorNav();
		
	}
	
});


ComicHouse.AuthorNavigationHelper = Class.create ({

	initialize: function(){
		this.authorNavs = [];
	},
	
	register: function(authornav){
		this.authorNavs.push(authornav);
	},
	
	hideAll: function(callingobj){
		this.authorNavs.each(function(obj){
			if (callingobj!=obj) {
				obj.hideAll();
			}
		});
	}

});
ComicHouse.authorNavigationHelper = new ComicHouse.AuthorNavigationHelper();


ComicHouse.QuicktimeMovie = Class.create ({

	insert: function(url) {
	
	    this.options = Object.extend({
      		qtvr:false,
      		looped:'false',
      		x:450,
      		y:350
		}, arguments[1] || { });
	    
		var controller		= (this.options.qtvr)? 'false':'true';
	    var loop			= this.options.looped;
	    
		// really strange bug in IE8 (others unknown) where the controller would not show the seccond time the movie loads.
		// cache=false didn't do the trick, this one does!
		var d = new Date();
		var t = d.getTime();
		url += '?'+t;
		
		// 'postdomevents', 'true'
		// Did not work crossbrowser.
		var html = QT_WriteOBJECT(url, this.options.x, this.options.y + 15, '', 'emb#NAME', 'chquicktimemovie', 'emb#id', 'chquicktimemovieembed', 'obj#id', 'chquicktimemovie', 'obj#name', 'chquicktimemovie', 'AUTOPLAY', 'true', 'SCALE', '1', 'CONTROLLER', controller, 'LOOP', loop, 'ALIGN', 'middle', 'enablejavascript', 'True', 'bgcolor', 'white');

		ComicHouse.artCanvas.updateWithQT(html, this.options.y + 15);

        if ( document.addEventListener ) {
        	qtmovie = $('chquicktimemovieembed');
        }
        else {
            // IE
        	qtmovie = document.getElementById('chquicktimemovie');
		};
		qtmovie = $(qtmovie);

		if (this.options.qtvr) {
			var art = $('art');
			var qtvrimage = new Element('img', {src:'images/quicktime/qvr_bar.gif', id:'qtvr-bar'});
			art.insert(new Element('br'));
			art.insert(qtvrimage);
		}
		
		this.embed = qtmovie;

	},
	
	remove: function(){
		if (this.embed) {
			this.embed = null;
		}
	},
	
	show: function(){
		if (!this.embed) {return;}
		try {
			this.embed.Play();
			
		} catch (e) {}	
		ComicHouse.artCanvas.show();
	},
	
	hide: function(){
		if (!this.embed) {return;}
		try {
			this.embed.Stop();
			
		} catch (e) {}
		ComicHouse.artCanvas.hide();
	}

});
ComicHouse.quicktimeMovie = new ComicHouse.QuicktimeMovie();

/* --------------- Move trits to left 50% if viewport is too small, and other tweaks --------------- */
ComicHouse.moveTritsToLeft = function() {
	var editmode = $('main').hasClassName('editmode');
	if (editmode) {
		var switchWidth = 792;	
		if (document.viewport.getWidth() < switchWidth) {
			$(document.body).addClassName('smallport-editmode');
		} else {
			$(document.body).removeClassName('smallport-editmode');
		}
	} else {
		var switchWidth = 900;
		if (document.viewport.getWidth() < switchWidth) {
			$(document.body).addClassName('smallport');
		} else {
			$(document.body).removeClassName('smallport');
		}
	}
};
ComicHouse.moveTritsToLeft.executeOnDomLoaded();
ComicHouse.moveTritsToLeft.executeOnWindowResize();
/* --------------- Move trits to left 50% in viewport is too small --------------- */



/* --------------- Langswitch background animation --------------- */
Effect.MoveBackground = Class.create(Effect.Base, {
  initialize: function(element) {
  	
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);

    var options = Object.extend({
      from: -62,
      to:   -53
    }, arguments[1] || { });
    this.start(options);
  },
  setup: function(){
  	this.element.setStyle({backgroundPosition:'-62px'});
  },
  update: function(position) {
    this.element.setStyle({backgroundPosition:'0 '+position+'px'});
  }
});

(function(){	
	$$('#langSwitches a').each(function(node){
		node.observe('mouseout', function(){
			if (this.effect && this.effect.state != 'finished') {
				return;
			}
			this.effect = new Effect.MoveBackground(node, {duration:.5});
		});
	});
}).executeOnDomLoaded();
/* --------------- /end Langswitch background animation --------------- */

/* --------------- Let the logo play along --------------- */
(function(){	
	var comichouseHeader	= $('comichouse-header');
	var topnavigationHome	= $('topnavigation_home');
	var trits				= $('trits');
	if (comichouseHeader && topnavigationHome){
		comichouseHeader.observe('mouseover', function(){
			topnavigationHome.addClassName('hover');
			if (trits)
				trits.addClassName('hover');
		});
		comichouseHeader.observe('mouseout', function(){
			topnavigationHome.removeClassName('hover');
			if (trits)
				trits.removeClassName('hover');
		});
		comichouseHeader.observe('click', function(){
			location.href = topnavigationHome.readAttribute('href'); 
		});
		topnavigationHome.observe('mouseover', function(){
			if (trits)
				trits.addClassName('hover');
		});
		topnavigationHome.observe('mouseout', function(){
			if (trits)
				trits.removeClassName('hover');
		});
	}
	
}).executeOnDomLoaded();
/* --------------- / Let the logo play along --------------- */


/* --------------- Staticportfolio paging --------------- */
(function(){	

	var pager = $('main').down('.staticportfolio');
	if (pager){
		pagernodes = pager.select('a');
		
		var nav = function(node, index){
			
			pagernodes.invoke('removeClassName','selected');
			node.addClassName('selected');
			var showThisContentNode = $('main').down('.staticportfolio_content', index); 
			$('main').select('.staticportfolio_content').invoke('hide');
			
			// fixed with table-cell css technique
			//var height = showThisContentNode.getHeight();
			//var mt = Math.round(-(height / 2) + 35);
			//$('bio').setStyle({marginTop:mt+'px'});
			
			showThisContentNode.show();
			
		};
		
		pagernodes.each(function(node, index){
			node.observe('click', function(){nav(node, index);});
		});
		
		//center pager
		var width = pager.getWidth();
		
		var leftwidth = ((633 - width) / 2) + 4;
		pager.setStyle({left:leftwidth+'px'});
		pager.setStyle({visibility:'visible'});
	}
	
}).executeOnDomLoaded();
/* --------------- /end Staticportfolio paging --------------- */

/* --------------- Move secret_login_link --------------- */
(function(){	
	var linkelement = $('hidden_login_link');
	if (linkelement) {
		var href = linkelement.readAttribute('href');
		linkelement.remove();
		var element = new Element('a', {href:href, id:'hidden_login_link'});
		$(document.body).insert(element);
	}
	
}).executeOnDomLoaded();
/* --------------- /end Move secret_login_link --------------- */




/* --------------- IE link outline fix --------------- */
(function(){	

	if (Prototype.Browser.IE) {
		var blur = function(){this.blur();};
		$$('a').invoke('observe', 'focus', blur);
	}
	
}).executeOnDomLoaded();
/* --------------- /end IE link outline fix --------------- */


/* --------------- Home hover recent --------------- */
(function(){	
	
	if ($('homeTextLeft') && $('homeTextRight')) {

		// show rows if it fits.
		var setheight = function(){
			var h = document.viewport.getHeight();
			h -= 470;
			h = (Math.round(h / 70) * 4);
			if (h < 8) h = 8;
			$$('#home > #homeTextLeft + .latest-additions a').invoke('setStyle',{display:'none'});
			$$('#home > #homeTextRight + .latest-additions a').invoke('setStyle',{display:'none'});
			$$('#home > #homeTextLeft + .latest-additions a').each(function(node, i) {
				if ((i+1) > h) {throw $break;}; node.setStyle({display:'block'});
			});
			$$('#home > #homeTextRight + .latest-additions a').each(function(node, i) {
				if ((i+1) > h) {throw $break;}; node.setStyle({display:'block'});
			});
		};
		setheight();
		Event.observe(document.onresize ? document : window, "resize", setheight);
		// End show rows if it fits.
		
		var latestadditionsglow			= new Element('div', {id:'latest-additions-glow'});
		var latestadditionstextbox		= new Element('div', {id:'latest-additions-text-box'});
		var latestadditionstextboxtop	= new Element('div', {id:'latest-additions-text-box-top'});
		var fx							= null;
		$$('.latest-additions a').each(function(node){
			
			var mouseenter = function() {
				latestadditionstextbox.stopObserving();
				latestadditionstextbox.observe('mouseenter', mouseleave);
				latestadditionstextbox.update(ComicHouse.descriptionFormatter.formatForDisplay(node.down('span').innerHTML));
				
				node.insert(latestadditionsglow);
				node.insert(latestadditionstextbox.hide());
				latestadditionstextbox.insert(latestadditionstextboxtop);
				node.down('img', 1).setStyle({width:'64px',height:'64px'});
				if (fx && fx.cancel) {fx.cancel();}
				fx = Effect.Appear(latestadditionstextbox, {duration:.3, delay:.25});
			};

			

			var mouseleave = function() {  
				latestadditionstextboxtop.remove();
				latestadditionsglow.remove();
				latestadditionstextbox.remove();
				node.down('img', 1).setStyle({width:'0px',height:'0px'});
			};
			
			node.observe('mouseenter', mouseenter);
			node.observe('mouseleave', mouseleave);
			
		});
		
	}
	
}).executeOnDomLoaded();
/* --------------- /end  Home hover recent  --------------- */






/* --------------- Popup balloon link-intercept --------------- */
(function(){	
	
	var mainnav = $('mainnavigation');
	
	if (!mainnav) {return;}
	
	var intercept_links		= [mainnav.down('a', 2), mainnav.down('a', 3)];
	var intercept_balloon	= new Element('div', {id:'navigation-balloon-1'});
	
	// the close function
	var close = function(evt){
		
		var bc = $('balloon-container');
		
		if (!bc) {return;}
		
		var element = evt.element();
		
		var x = evt.pointerX(); // - $('main').offsetLeft;
		var y = evt.pointerY(); // - ($('main').offsetHeight - bc.offsetTop);
		
		var xRange = {min:132, max:670};
		var yRange = {min:15, max:548};

		if ( (x < xRange.min || x > xRange.max) || (y < yRange.min || y > yRange.max) ) {
			$('balloon-container').fade({duration:.3, afterFinish: function(){$('navigation-balloon-1').update(''); $('balloon-container').remove.defer();}});
			//$('navigation-balloon-1').update.delay(.3, '');
			ComicHouse.quicktimeMovie.show();
			mainnav.select('a').invoke('removeClassName', 'balloon');
		}
	};
	
	$(document.body).observe('click', close);
	
	intercept_links.each (
	
			function(link, index) {
				link.observe('click', function(evt) {
					// stop the browser from following the link
					evt.stop();
					var element				= evt.element();
					
					var open = function(evt) {
						
						link.addClassName('balloon');
						
						// stop qt movie playing
						ComicHouse.quicktimeMovie.hide();
						
						var elementPos			= {left:element.offsetLeft, width:element.offsetWidth};
						
						var href				= element.readAttribute('href');
						var balloon_container	= new Element('div', {id:'balloon-container'});
						var north				= new Element('div', {id:'balloon-north'});

						var balloon				= intercept_balloon;
						
						balloon_container.insert(north);
						balloon_container.insert(balloon);
						var beam = new Element('div', {id:'balloon-beam'}).setStyle({top:element.offsetTop-120+'px'});
						$('main').insert({after:balloon_container});
						balloon_container.insert(beam);
						
						new Ajax.Request(href, {
							
							onSuccess: function(response) {
								var htmlString = response.responseText;
								
								var container = new Element('div');
								container.update(htmlString);
								
								var snippet = container.down('#staticpage');
								balloon.update(snippet);
								
							}
							
						});
						
					};
					
					// already a popup
					if ($('balloon-container')) {
						close(evt);
						open.delay(.5, evt);
					} else {
						open(evt);
					}

					
				});
			}
	
	);
	
}).executeOnDomLoaded();
/* --------------- /end Popup balloon link-intercept --------------- */




ComicHouse.ArtCanvas = Class.create(LazzoBaseClass, {
 	
	_init: function(){
		this.showcopyright = false;
		this._isReady = true;
		this._observe('wirescrollbars', this._initDependableLoaded.bind(this));
		this._observe('sliderinterface-showing', this._watchForSliderShowing.bind(this));
		this._observe('sliderinterface-hiding', this._watchForSliderHiding.bind(this));
		
		this._onWindowResizeCall(function(){
			if (this.horizontalScrollBar && !this.isMovie && this.editmode) {
				this._killScrollbar();
				this._setImageScrollbars();				
			}
			this._verticalAlign();
		}.bind(this));
	},
	
	_initDependableLoaded: function() {

		// there are pages without trits. for instance the webtour.
		if (!$('trits')) {
			return;	
		}
	
		if (!$('art')) {
			var art = new Element('div', {id:'art'});
			$('main').insert({after: art});
		}
		if (!$('bio')) {
			var bio = new Element('div', {id:'bio'});
			$('main').insert({top: bio});
		}
	
		this.art = $('art');
		this.artworkloader	= new Element('img', {id:'artworkloader', src:'nav/klok.gif', width:'300', height:'300'}).hide();
		$('main').insert(this.artworkloader);
		
		this._fireEvent('artcanvas');

		// deeplink support		
		if (this.art.hasClassName('deeplinked')) {
			
			if (this.art.down('img')) {
				var f = function(){this.art.setStyle({left:'20px'});this._fireEvent('desk-image-loaded');this.h = $('art').getHeight();this._verticalAlign();}.bind(this);
				//f.delay(2);
			} else {
				
				var f = function(){this.art.setStyle({left:'20px'});this.h = $('art').getHeight();this._verticalAlign();}.bind(this);
				//f.delay(2);
				
			}
			
		}
		
	},
	
	verticalAlign: function () {
		this.h = this.getHeight();
		if (this._isReady) {
			this._verticalAlign();
		}
	},
	
	_verticalAlign: function() {
		
		var h = this.h;
		if ($('edittextinput')) {
			h += $('edittextinput').getHeight(); 
		}
		var topAndBottomNavigationsHeight = (this.editmode)? 200:285;
		var availableHeight = document.viewport.getHeight() - topAndBottomNavigationsHeight;
		if (h > availableHeight) {
			$(document.body).addClassName('lowport');
		} else {
			$(document.body).removeClassName('lowport');	
		}
		if (this.art) {
			var m = -(h / 2) + 50;
			this.art.setStyle({marginTop:m+'px'});
			// avoid flicker.
			var f = function(){
				this.art.setStyle({visibility:'visible'});
				this._fireEvent('artcanvas-altered-height');
			}.bind(this);
			f.delay(.3);
		}

	},

	_setImageScrollbars: function() {

		var h = 0;
		var ti = setInterval(function() {

			var currH = $('art').getHeight();
			if (currH == h && currH > 20) {
				
				clearInterval(ti);
				this._killScrollbar();
				
				if (this.isMovie) {
					return;
				}
				
				this.horizontalScrollBar = new ComicHouse.ScrollblockH($('art'), {offsetBy:{left:180,top:2}});
				this._isReady = true;
								
			} else {
				h = currH;
			}
						
		}.bind(this), 50);
		
		this._isReady = true;
			
	},
	
	_killScrollbar: function() {
		if (this.horizontalScrollBar) {
			this.horizontalScrollBar.kill();
			this.horizontalScrollBar = null;
		}
	},
	
	_updateWithLoadedImage: function(){
		
		var h = this.art.down('img').getHeight();
		this.h = h;
		this._isReady = true;
		
		var artworkdescription = $('artwork_description');
		if (artworkdescription) {
			var formattedString	= ComicHouse.descriptionFormatter.formatForDisplay(artworkdescription.innerHTML);
			artworkdescription.update(formattedString);
			this.h += artworkdescription.getHeight(); 
		}
		this._verticalAlign();
		if (this.editmode) 
			this._setImageScrollbars();
	},
	
	getHeight: function() {
		
		return this.art.getHeight();
		
	},
	
	updateWithQT: function(html, h){
		
		this.art.update(html);
		this.h = h;
		this._isReady = true;
	},

	updateWithSWF: function(html, w, h, artworkid){
		this.art.update(html);
		this.h = h;
		this._isReady = true;
		
		this._fireEvent('artcanvas-updated-with-swf', {height:h, artworkid:artworkid});
		
	},
	
	updateWithSWFFLVNode: function(node, h){
		
		this.art.update(node);
		this.h = h;
		this._isReady = true;
	},
	
	insertSlider: function(slider, curtainleft, curtainright) {
		
		$('artwork_description').insert({before:slider});
		
		this.art.insert({bottom:curtainleft});
		this.art.insert({bottom:curtainright});
	},
	_watchForSliderShowing: function() {
		this.h += 50;
		this._verticalAlign();
	},
	_watchForSliderHiding: function() {
		this.h -= 50;
		this._verticalAlign();		
	},	
	
	/*
	 * Format the artwork description text and update to the new height.
	 */
	setArtworkDescription: function(string){
		
		var formattedString		= ComicHouse.descriptionFormatter.formatForDisplay(string);
		var node				= new Element('div', {id:'artwork_description'}).update(formattedString);
		this.art.insert(node);
		var height				= node.getHeight();
		this.h					+= height;
	
		this._verticalAlign.bind(this).defer();
	},
	
	show: function(){
		this.art.show();
	},
	
	hide: function(){
		this.art.hide();
	},

	/*
	 * Best to call this method before doing anything with this class.
	 * By using this test, other classes can make sure that their UI depicts ready or not status.
	 */
	isReady: function(){
		return this._isReady; 
		
	},
	
	/*
	 * Clear art (art.update())
	 * Set art height auto
	 * Call this before the set method.
	 */
	load: function(){
		this._isReady = false;
		this.art.removeAttribute('class');
		
		this.art.update().setStyle({visibility:'hidden'});
		this.artworkloader.show();
		// some modules perform a hack, this is to make sure everything updates well
		$$('#artwork_description').invoke('remove');
		this._fireEvent('artcanvas-isloading');

	},

	/*
	 * Clear art (art.update())
	 * Set art height 0
	 */
	clear: function() {
				
		this.art.update().setStyle({visibility:'hidden'});

		// some modules perform a hack, this is to make sure everything updates well
		$$('#artwork_description').invoke('remove');

	},


	/*
	 * Check new height and set
	 */	
	set: function(mimetypehr, showcopyright) {
		
		this.art.removeAttribute('class');
		this.mimetypehr		= mimetypehr;
		this.isMovie		= (mimetypehr == 'flv' || mimetypehr == 'mp4' || mimetypehr == 'video');
				
		this.showcopyright	= (typeof showcopyright == 'undefined')? true:showcopyright;

		this._isReady = false;
		
		if (!this.showcopyright && this.art.down('img') && !this.art.down('img').readAttribute('animated')) {
			
			//(this.editmode)? this.art.setStyle({left:'148px'}):this.art.setStyle({left:'20px'});
			this.art.addClassName('image');
			
			this.art.down('img').observe('load', function() {
				this._isReady = true;
				this._fireEvent('desk-image-loaded');
				//$$('#artwork_description').invoke('addClassName', {left:'68px'});
				//if (!this.editmode) $$('#artwork_description').invoke('setStyle', {left:'68px'});
			}.bind(this));
		
		} else {
			this.art.addClassName('animated');
			//(this.editmode)? this.art.setStyle({left:'270px'}):this.art.setStyle({left:'220px'});
			this._isReady = true;
			//$$('#artwork_description').invoke('setStyle', {left:'0px'});
		}
		
		this.artworkloader.hide();
		this.art.show();
		
		if (!this.isMovie) {
			this.art.down('img').observe('load', this._updateWithLoadedImage.bind(this));
		}
		
	}

});
ComicHouse.artCanvas = new ComicHouse.ArtCanvas();

/*
 * Method for displaying images on canvas
 * Observe's the desk-image-loaded event.
 * Check these usecases:
 * - Description text
 * - Animation
 * - Popup dialog
 * - Other templates like static, iselect and deeplink
 * - Behaviour in the editor
 * 
 * TODO: 
 * - [fixed] On imageload, at least in IE, a viewport scrollbar shows briefly
 * - [fixed] Update dragClass to use scrollLeft.
 * - [fixed] IE8 miniscroll interface does not show after secondary click.
 * - [fixed] Check in IE
 * - [fixed] Deeplink to serie item
 */

ComicHouse.ImageScroll = Class.create(LazzoBaseClass, {
	
	_init: function() {
		this.srcimage				= null;
		this.sliderinterface		= {};
		this.wheeleventattached		= false;
		this._observe('desk-image-loaded', this._imageLoaded.bind(this));
		this._onWindowResizeCall(this._calculateAndSet.bind(this));
	
		this.dragClass 				= Class.create(Control.Slider, {
			
			setValue: function(sliderValue, handleIdx){
			    if (!this.active) {
			      this.activeHandleIdx = handleIdx || 0;
			      this.activeHandle    = this.handles[this.activeHandleIdx];
			    }
			    
			    handleIdx = handleIdx || this.activeHandleIdx || 0;

			    sliderValue = this.getNearestValue(sliderValue);
			    			    
			    this.values[handleIdx] = sliderValue;
			    
			    this.value = this.values[0];

			    //if (!this.dragging || !this.event) this.updateFinished();
		  },
		   
		  startDrag: function(event) {
			    if (Event.isLeftClick(event)) {
			      if (!this.disabled){
			        this.active = true;
			        
			        var handle = Event.element(event);
			        var pointer  = [Event.pointerX(event), Event.pointerY(event)];
			        var track = handle;
			        if (track==this.track) {
			          var offsets  = Position.cumulativeOffset(this.track); 
			          this.event = event;
			          
			          this.setValue(this.translateToValue( 
			           (this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
			          ));
			          var offsets  = Position.cumulativeOffset(this.activeHandle);
			          this.offsetX = (pointer[0] - offsets[0]);
			          this.offsetY = (pointer[1] - offsets[1]);
			        } else {
			          // find the handle (prevents issues with Safari)
			          while((this.handles.indexOf(handle) == -1) && handle.parentNode) 
			            handle = handle.parentNode;
			            
			          if (this.handles.indexOf(handle)!=-1) {
			            this.activeHandle    = handle;
			            this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
			            this.updateStyles();
			            
			            var offsets  = Position.cumulativeOffset(this.activeHandle);
			            // use the scrollLeft instead of offset.
			            this.offsetX = (pointer[0] + this.activeHandle.up().scrollLeft);
			            this.offsetY = (pointer[1] - offsets[1]);
			          }
			        }
			      }
			      Event.stop(event);
			    }
			  },
		  
		  getNearestValue: function(value){
		    if (this.allowedValues){
		      if (value >= this.allowedValues.max()) return(this.allowedValues.max());
		      if (value <= this.allowedValues.min()) return(this.allowedValues.min());
		      
		      var offset = Math.abs(this.allowedValues[0] - value);
		      var newValue = this.allowedValues[0];
		      this.allowedValues.each( function(v) {
		        var currentOffset = Math.abs(v - value);
		        if (currentOffset <= offset){
		          newValue = v;
		          offset = currentOffset;
		        } 
		      });
		      return newValue;
		    }
		    if (value > this.range.end) return this.range.end;
		    if (value < this.range.start) return this.range.start;
		    return value;
		  }
		
		});
		
	},
	/*
	 * If desk image loaded, continue loading the sliderinterface.
	 */
	_imageLoaded: function() {
		
		if (this.editmode) {return;}
		
		// NOTE: I removed the interface loaded check: IE8 bug. Now, the interface is reinitialized every time.
		this._initInterface();
		
		// create scrollcanvas once
		if (!this.canvas) {
			this.canvas		= new Element('div', {id:'imagescroll'});
		}
		
		// attach wheel event once
		if (!this.wheeleventattached) {
			Event.observe(this.sliderinterface.track, 'mousewheel', this.sliderinterface.setValueByEventValue.bind(this));
			Event.observe(this.sliderinterface.track, 'DOMMouseScroll', this.sliderinterface.setValueByEventValue.bind(this));
			Event.observe(this.canvas, 'mousewheel', this.sliderinterface.setValueByEventValue.bind(this));
			Event.observe(this.canvas, 'DOMMouseScroll', this.sliderinterface.setValueByEventValue.bind(this));
			this.wheeleventattached = true;
		}
				
		// clear the canvas
		this.canvas.select('*').invoke('remove');
		
		this.srcimage	= $('art').down('img');
		this.srcimage.wrap(this.canvas);

		// the image drag function
		if (this.dragging) {
			this.dragging.dispose();
		}
		this.dragging	= new this.dragClass(this.srcimage, this.canvas, {
			axis:'horizontal',
			onSlide: function(value){
				this.sliderinterface.setValue(value);
			}.bind(this)}
		 );
		// end the image drag function
		
		this.imagewidth		= this.srcimage.offsetWidth;
		this.imageheight	= this.srcimage.offsetHeight;
		
		// hide copyright notice
		this.canvas.setStyle({left:'0px', height:this.imageheight-23+'px'});
		
		this._calculateAndSet();

		this.sliderinterface.setImage(this.srcimage);
		this.sliderinterface.setSliderWidth(this.canvas.offsetWidth); 
		
		this.sliderinterface.setCallback(this._slide.bind(this));
	},
	
	/*
	 * (Re)calculate canvas width.
	 * Set image marginLeft.
	 * Show or hide sliderinterface.
	 */
	_calculateAndSet: function() {
		
		if (!this.canvas) {return;}
		
		// reset scrolledOffset
		if (this.canvas.scrollLeft) this.canvas.scrollLeft = 0;
		
		// calculate canvas width
		var canvasWidth	= this.canvas.offsetWidth;
		
		var f = this.sliderinterface.setSliderWidth.bind(this);
		f.defer(canvasWidth);
		
		if (((canvasWidth - this.imagewidth) > 0) && ((canvasWidth - this.imagewidth) < 138)) {
			//$('art').setStyle({background:'green'});
			this.canvas.removeClassName('scrollable');
			this.srcimage.setStyle({marginLeft:canvasWidth - this.imagewidth+'px'});
			this.sliderinterface.hide();
		} else {
			if (this.imagewidth < canvasWidth) {
				//$('art').setStyle({background:'red'});
				this.canvas.removeClassName('scrollable');
				this.srcimage.setStyle({marginLeft:'138px'});
				this.sliderinterface.hide();
			} else {
				//$('art').setStyle({background:'gray'});
				this.canvas.addClassName('scrollable');
				this.srcimage.setStyle({marginLeft:'0px'});
				this.sliderinterface.show();
			}
		}
		
	},
	
	_slide: function(value) {
		var l = (this.canvas.scrollWidth - this.canvas.offsetWidth) * value;
		this.canvas.scrollLeft = l;
		
		if (value<=0.01) {this.sliderinterface.curtainleft.hide();} else {this.sliderinterface.curtainleft.show();}
		if (value>=0.99) {this.sliderinterface.curtainright.hide();} else {this.sliderinterface.curtainright.show();}
	},
	
	/*
	 * Creates interface (once) like this: 
	 * <div back>
	 * 	<img miniimage />
	 * 	<div slider></div>
	 * </div>
	 * With a few methods.
	 */
	_initInterface: function() {
		var self = this;
		this.sliderinterface.isShowing		= false;
		this.sliderinterface._dragValue		= 0;
		this.sliderinterface.track			= new Element('div', {id:'imagescroll-track'}).hide();
		this.sliderinterface.miniimage		= new Element('img', {id:'imagescroll-miniimage'});
		this.sliderinterface.slider			= new Element('div', {id:'imagescroll-slider'});
		this.sliderinterface.curtainleft	= new Element('div', {id:'imagescroll-curtainleft'}).hide();
		this.sliderinterface.curtainright	= new Element('div', {id:'imagescroll-curtainright'}).hide();

		this.sliderinterface.show			= function(){
			if (self.sliderinterface.isShowing) {return;}
			self.sliderinterface.isShowing = true;
			self.sliderinterface.track.show();
			self.sliderinterface.curtainleft.hide();
			self.sliderinterface.curtainright.show();
			self._fireEvent('sliderinterface-showing');
		};
		this.sliderinterface.hide			= function(){
			if (!self.sliderinterface.isShowing) {return;}
			self.sliderinterface.isShowing = false;
			self.sliderinterface.track.hide();
			self.sliderinterface.curtainleft.hide();
			self.sliderinterface.curtainright.hide();
			self._fireEvent('sliderinterface-hiding');
		};
		
		// insert all in dom tree
		this.sliderinterface.track.insert(this.sliderinterface.miniimage);
		this.sliderinterface.track.insert(this.sliderinterface.slider);
		this.sliderinterface.leftshadow = new Element('div', {id:'imagescroll-leftshadow'});
		this.sliderinterface.rightshadow = new Element('div', {id:'imagescroll-rightshadow'});
		this.sliderinterface.slider.insert(this.sliderinterface.leftshadow);
		this.sliderinterface.slider.insert(this.sliderinterface.rightshadow);

		/*
		 * Init function, attaching Slide();
		 */
		this.sliderinterface.initSlider			= function(){

			if (self.sliderobject) {
				self.sliderobject.dispose();
			} 
			self.sliderobject = new Control.Slider(self.sliderinterface.slider, self.sliderinterface.track, {
				axis:'horizontal',
				onSlide: function(value){
					self.sliderinterface.callback(value);
				},
				onChange: function(value){
					self.sliderinterface.callback(value);
				}}
			 );
			
		};
		
		/*
		 * set value by scrollwheel
		 */
		this.sliderinterface.setValueByEventValue 	= function (event) {
			var scroll_amount = Event.wheel(event);
			var deltaWidth = this.canvas.scrollWidth - this.canvas.offsetWidth;
			self.sliderobject.setValueBy(-scroll_amount/(deltaWidth/15));
		},
		
		/*
		 * Set value by dragging
		 */
		this.sliderinterface.setValue				= function(value){
			
			self.sliderobject.setValue(value);
		};
		
		/*
		 * Called once per image
		 */
		this.sliderinterface.setImage				= function(image){
			ComicHouse.artCanvas.insertSlider(self.sliderinterface.track, self.sliderinterface.curtainleft, self.sliderinterface.curtainright);
			self.sliderinterface.ratio = (43 / image.getHeight()); 
			
			self.sliderinterface.miniimage.src = image.src;
			var width = self.sliderinterface.ratio * image.getWidth();
			self.sliderinterface.miniimage.setStyle({width:width+'px'});  
			self.sliderinterface.track.setStyle({width:width+'px'});
		};
		/*
		 * Call after setImage, sets handle width on init and after viewport resize
		 */
		this.sliderinterface.setSliderWidth			= function(canvaswidth){
			var borderWidth	= 8;
			var w			= self.sliderinterface.ratio * canvaswidth; 
			
			self.sliderinterface.slider.setStyle({width:w-borderWidth+'px'});
			self.sliderinterface.leftshadow.setStyle({right:w-(borderWidth/2)+'px'});
			self.sliderinterface.rightshadow.setStyle({left:w+-(borderWidth/2)+'px'});
			
			self.sliderinterface.initSlider();
			
		};
				
		/*
		 * The callback function, called onslide
		 */
		this.sliderinterface.setCallback			= function(callback){
			self.sliderinterface.callback = callback;
		};
		
	}
	
});
new ComicHouse.ImageScroll();




ComicHouse.descriptionFormatter = {
	
	labels: ComicHouse.localizedText.credit_labels,
	
	keys: ['titel', 'regisseur', 'producent', 'animator', 'modeling', 'characterontwerp', 'bureau', 'creatie', 'klant/merk'],
	
	unformatted: null,
	
	_preformat: function(string) {
		
		var locale = $('main').readAttribute('locale');
		var translations = new Hash(ComicHouse.localizedText.mini_dictionary_json); 
		
		translations.each(function(token) {
			
			var key = token[0];
			var val = token[1];
			
			reg = new RegExp('\\[:' + key + ':\\]', "gm");
			
			string = string.replace(reg, val);
			
		});
		
		return string;
			
	},
	
	formatForDisplay: function(string) {
		
		// Enables [:xxx:] formats to be substituted.
	
		string = this._preformat(string);
	
		this.unformatted	= string;

		var creditlist		= false;
		var labels			= this.labels;
		var tableHTML		= '<table id="credits">';
		
		this.keys.each(function(label, index) {
			
			var regex = new RegExp('&lt;' + label + '&gt;(.*)&lt;\/' + label + '&gt;', 'i');
			
			if (string.match(regex)) {
				var value			= string.match(regex)[1];
				
				if (label == 'titel') {
				
					value = '<strong>' + value + '</strong>';
				
				}
				
				var translatedLabel	= labels[index];
				tableHTML += '<tr label="'+label+'"><td class="credits_label">'+translatedLabel+':</td><td class="credits_value">'+value+'</td></tr>';
				creditlist = true;
			}
			
		});

		if (creditlist) {
			
			tableHTML += '</table>';			
			return tableHTML;
			
		} else {
			
			return this.unformatted;
			
		}

	},
	
	getMask: function() {
		var s = '';
		this.labels.each(function(label) {
			s += "&lt;"+label+"&gt;editme&lt;/"+label+"&gt;<br>";
		});
		return s;
	},
	
	getUnformatted: function(){		
		return this.unformatted;
	}
	
};

// jw player callback
// function playerReady(obj) {};
ComicHouse.LandingFlash  = Class.create(LazzoBaseClass, {
	insert: function(flv, replacenode) {
		
		var f = function() {
		
			var contextpath = '/'+this.contextpath;
			var flashvars = {
					file: contextpath + flv,
					logo: contextpath+'mediaplayer/skin/comichouse/blanklogo.png',
					repeat:"always",
					screencolor:'#ffffff',
					icons:false,
					type:'video',
					bufferlength:5,
					repeat:'always',
					width:400,
					height:150,
					controlbar:'none',
					autostart:true
			};
			var params = {
					wmode:'opaque',
					scale: "noscale",
					controlbar:'none',
					allowscriptaccess:'always',
					allowfullscreen:'false'
			};
			var attributes = {
					id: "landingflash",
					name: "landingflash"
			};		
			swfobject.embedSWF(contextpath+'mediaplayer/skin/comichouse/CHPlayer.swf', replacenode, "400", "150", "10.0.0", contextpath+'mediaplayer/skin/comichouse/expressInstall.swf', flashvars, params, attributes);
			if ($(replacenode)) 
				$(replacenode).addClassName('color');
		}.bind(this);
		
		f.defer();
	}
});


