var index = new Array();

function switchLayout(l) {
	if (l=='article') {
		$('root').addClassName('article'); $('root').removeClassName('home');
	}
	if (l=='home') {
		$('root').addClassName('home'); $('root').removeClassName('article');
		$$('#contentIndex').each(function(el) { el.remove(); });
	}

	updateAdvertisingSpace();	
}

function updateAdvertisingSpace() {
	if ($('advertisingNews')) $('advertisingNews').style.height = $('news').getHeight()+'px';
	if ($('advertisingContent')) $('advertisingContent').style.height = $('content').getHeight()+'px';
}

function updateContent(tag) {
	$$('#content h1, #content h2, #content h3, #content p, #content div').each(function(el) {
		if (el.identify() != 'contentMenu') el.remove();
	});
	
	$$('#content *').each(function(el) {
		if (el.identify() != 'contentMenu') el.hide();
	});

	$$('#content #contentMenu *').each(function(el) {
		el.show();
	});


	new Ajax.Request('json/content', {parameters: {'tag':tag}, requestHeaders: {Accept: 'application/json'}, onSuccess: function(transport) { 		
		index = new Array();
		var json = transport.responseText.evalJSON();
		json.each(function(article) {createArticle(article)});
	
		createIndex();
		switchLayout('article');
	}});
}

function createParagraph(json) {
	var p;
	if (json.type=='headline') {
		p = Builder.node('h1', {id: 'paragraph_'+json.id}, json.value);
		index.push({id: 'paragraph_'+json.id, text: json.value, type: 'h1'});
	}
	if (json.type=='header2') {
		p = Builder.node('h2', {id: 'paragraph_'+json.id}, json.value);
		index.push({id: 'paragraph_'+json.id, text: json.value, type: 'h2'});
	}
	if (json.type=='header3') {
		p = Builder.node('h3', {id: 'paragraph_'+json.id}, json.value);
		index.push({id: 'paragraph_'+json.id, text: json.value, type: 'h3'});		
	}
	if (json.type=='text') {
		p = Builder.node('div', {id: 'paragraph_'+json.id, className: 'text'}, json.value);
		var text = superTextile(json.value);
try
{
		p.update(text);
}
catch(ex) {
alert(ex.message);
}
	}
	if (json.type=='link') {
		p = Builder.node('p', {id: 'paragraph_'+json.id, className: 'link'}, Builder.node('a', {href: 'go/'+json.id, target: '_blank'}, json.value));
	}
	if (json.type=='download') {
		p = Builder.node('p', {id: 'paragraph_'+json.id, className: 'download'}, Builder.node('a', {href: 'download/'+json.id}, json.value));
	}
	if (json.type=='image') {
		p = Builder.node('p', {id: 'paragraph_'+json.id, className: 'image'}, Builder.node('img', {src: 'image/paragraph/'+json.id}));
	}
	if (json.type=='slideshow') {
		p = Builder.node('p', {id: 'paragraph_'+json.id, className: 'slideshow'}, Builder.node('img', {src: 'images/blank.gif', id: 'placeholder_'+json.id}));
		loadSlideshow(json.value, p.identify(), 'placeholder_'+json.id);
	}
	if (json.type=='gallery') {
		p = Builder.node('p', {id: 'paragraph_'+json.id, className: 'gallery'}, Builder.node('img', {src: 'images/blank.gif', id: 'placeholder_'+json.id}));
		loadGallery(json.value, p.identify(), 'placeholder_'+json.id);
	}
	if (json.type=='faq') {
		p = Builder.node('div', {id: 'paragraph_'+json.id, className: 'faq'});
		loadFaq(json.value, p.identify());
	}
	
	$('content').appendChild(p);
//	if (json.type=='text') $('paragraph_'+json.id).update(superTextile(json.value));
}

function createArticle(json) {
	json.each(function(paragraph) {createParagraph(paragraph)});
}


function createIndex() {
	$$('#contentIndex').each(function(el) { el.remove(); });
	if (index.length>1) {
		var indexList = Builder.node('ul', {id: 'contentIndex'});
		index.each(function(el) {
			var e = Builder.node('li', Builder.node(el.type, Builder.node('a', {href: self.location.href.split('#')[0]+'#'+el.id}, el.text)));
			indexList.appendChild(e);
		});
	
		$('content').insert({top: indexList});
	}
}

function showSearch(container) {
	var s = Builder.node('input', {type: 'text', className: 'searchInput', id: 'searchInputArticle'});
	$(container).update(s);
	startSearch('searchInputArticle');
}

function updateNews(id) {
	new Ajax.Request('json/news', {parameters: {'news': id}, requestHeaders: {Accept: 'application/json'}, onSuccess: function(transport) {
		var json = transport.responseText.evalJSON();
		createNews(json);
		if ($('newsImage')) $('newsImage').hide();
		$('newsArtikel').show();
		updateAdvertisingSpace();
	}});
}

function closeNews() {
	$('newsArtikel').update();
}

function createNews(news) {
	$('newsArtikel').update();
	if (news.image) $('newsArtikel').appendChild(Builder.node('img', {src: 'image/news/'+news.id, id: 'newsArtikelImage'}));
	$('newsArtikel').appendChild(Builder.node('h2', news.title));
	var text = Builder.node('p', news.text);
	text.update(superTextile(news.text));
	$('newsArtikel').appendChild(text);
	if (news.gallery>0) {
		var galdiv = Builder.node('div', {id: 'newsgallery_'+news.id, className: 'gallery'}, Builder.node('img', {src: 'images/blank.gif', id: 'placeholder_'+news.id}));
		$('newsArtikel').appendChild(galdiv);
		loadGallery(news.gallery, galdiv.identify(), 'placeholder_'+news.id);
	}
}


function loadFaq(id, container) {
	new Ajax.Request('json/faq', {parameters: {'faq': id}, requestHeaders: {Accept: 'application/json'}, onSuccess: function(transport) {
		var json = transport.responseText.evalJSON();
		createFaq(json, container);
	}});
}

function createFaq(faq, container) {
	var faqList = Builder.node('dl', {className: 'faq'});
	faq.each(function(entry) {
		var q = Builder.node('dt', {id: 'question_'+entry.id, 'onclick': "$('answer_"+entry.id+"').toggle();"}, entry.question);
		faqList.appendChild(q);
		var a = Builder.node('dd', {id: 'answer_'+entry.id, style: 'display: none'});
		a.update(superTextile(entry.answer));
		faqList.appendChild(a);
	});

	$(container).insert(faqList);
}


function loadGallery(id, container, oldcontent) {
	new Ajax.Request('json/gallery', {parameters: {'gallery': id}, requestHeaders: {Accept: 'application/json'}, onSuccess: function(transport) {
		var json = transport.responseText.evalJSON();
		createGallery(json, container, oldcontent);
	}});
}

function createGallery(gallery, container, oldcontent) {
	var gal = Builder.node('ul', {className: 'gallery'});
	var i = 0;
	var id = Math.random();
	gallery.each(function(pic) {
		var p = Builder.node('li', Builder.node('a', {href: 'image/gallery/'+pic, rel: 'lightbox['+id+']'}, Builder.node('img', {src: 'image/gallery/thumbnail/'+pic})));
		gal.appendChild(p);
	});

	$(container).insert(gal);
}

function loadSlideshow(id, container, oldcontent) {
	new Ajax.Request('json/gallery', {parameters: {'gallery': id}, requestHeaders: {Accept: 'application/json'}, onSuccess: function(transport) {
		var json = transport.responseText.evalJSON();
		createSlideshow(json, container, oldcontent);
	}});
}

function createSlideshow(gallery, container, oldcontent) {
	var gal = Builder.node('ul', {id: 'slideshowList'});
	var i = 0;
	gallery.each(function(pic) {
		var p = Builder.node('li', Builder.node('img', {src: 'image/gallery/'+pic}));
		if (i++>0) p.hide();
		gal.appendChild(p);
	});

	$(container).insert(gal);

	$$('#'+container+' #slideshowList img').each(function(el) {
		Event.observe(el, 'load', function() {
			if (el.getHeight()>$(container).getHeight()) $(container).style.height = el.getHeight()+'px';
		});
	});	

	startSlideshow(container, oldcontent);
}

function startSlideshow(container, oldcontent) {
	if ($(oldcontent)) Effect.Fade($(oldcontent), {duration: 0.5});
	var periodic = new PeriodicalExecuter(function(pe) {
		var br = false;
		$$('#'+container+' li').each(function(el) {
			if (el.style.display != 'none' && !br) {
				Effect.Fade(el, {duration: 0.5, queue: {scope: 'slideChange'+container}});
				if (el.next('li', 0)) Effect.Appear(el.next('li', 0), {duration: 0.5, queue: {scope: 'slideChange'+container}});
				else Effect.Appear($$('#'+container+' li')[0], {duration: 0.5, queue: {scope: 'slideChange'+container}});
				br = true;
				var maxHeight = 0;
				$$('#'+container+' #slideshowList img').each(function(el) {if (el.getHeight()>maxHeight) maxHeight = el.getHeight()});	
				if (maxHeight>0) $(container).style.height = maxHeight+'px';
			}
		});
	}, 5);
	Event.observe(container, 'DOMNodeRemovedFromDocument', function() {periodic.stop();});
}

function startSearch(container) {
	container = $(container);
	Event.observe(container, 'keyup', function() {
		if (container.value.length>3) {
			new Ajax.Request('json/search', {parameters: {q: container.value}, requestHeaders: {Accept: 'application/json'}, onSuccess: function(transport) {
				var json = transport.responseText.evalJSON();
				if (json) createSearchResult(container, json);
				else {
					$$('.searchResultsList').each(function(el) {el.remove();});
					var resList = Builder.node('ul', {className: 'searchResultsList'});
					var item = Builder.node('li', 'Kein Ergebnis');
					resList.appendChild(item);
					container.insert({after: resList});
				}
			}});
		}
	});
	Event.observe(container, 'blur', function() {
		window.setTimeout("$$('.searchResultsList').each(function(el) {el.remove();});", 300);
	});
}

function createSearchResult(container, results) {
	$$('.searchResultsList').each(function(el) {el.remove();});

	var resList = Builder.node('ul', {className: 'searchResultsList'});
	results.each(function(r) {
		var item = Builder.node('li', Builder.node('a', {href: 'javascript:updateContent(\''+r.tag+'\')', onclick: '$(\''+container.identify()+'\').value=\'\'; $$(\'.searchResultsList\').each(function(el) {el.remove();});'}, r.title));
		resList.appendChild(item);
	});
	container.insert({after: resList});
}




/*
 * This function originally from Stuart Langridge at http://www.kryogenix.org/
 * Heavily updated by Jeff Minard at http://www.creatimation.net/
 */

function superTextile(s) {
    var r = s;
    // quick tags first
    qtags = [['\\*', 'strong'],
             ['\\?\\?', 'cite'],
             ['\\+', 'ins'],  //fixed
             ['~', 'sub'],   
             ['\\^', 'sup'], // me
             ['@', 'code']];
    for (var i=0;i<qtags.length;i++) {
        ttag = qtags[i][0]; htag = qtags[i][1];
        re = new RegExp(ttag+'\\b(.+?)\\b'+ttag,'g');
        r = r.replace(re,'<'+htag+'>'+'$1'+'</'+htag+'>');
    }
    // underscores count as part of a word, so do them separately
    re = new RegExp('\\b_(.+?)_\\b','g');
    r = r.replace(re,'<em>$1</em>');
	
	//jeff: so do dashes
    re = new RegExp('[\s\n]-(.+?)-[\s\n]','g');
    r = r.replace(re,'<del>$1</del>');

    // links
    re = new RegExp('"\\b(.+?)\\(\\b(.+?)\\b\\)":([^\\s]+)','g');
    r = r.replace(re,'<a href="$3" title="$2">$1</a>');
    re = new RegExp('"\\b(.+?)\\b":([^\\s]+)','g');
    r = r.replace(re,'<a href="$2">$1</a>');

    // images
    re = new RegExp('!\\b(.+?)\\(\\b(.+?)\\b\\)!','g');
    r = r.replace(re,'<img src="$1" alt="$2">');
    re = new RegExp('!\\b(.+?)\\b!','g');
    r = r.replace(re,'<img src="$1">');
    
    // block level formatting
	
		// Jeff's hack to show single line breaks as they should.
		// insert breaks - but you get some....stupid ones
	    re = new RegExp('(.*)\n([^#\*\n].*)','g');
	    r = r.replace(re,'$1<br />$2');
		// remove the stupid breaks.
	    re = new RegExp('\n<br />','g');
	    r = r.replace(re,'\n');

	    re = new RegExp('<br />','g');
	    r = r.replace(re,'\n');
	
    lines = r.split('\n');
    nr = '';
    intable = false;
    for (var i=0;i<lines.length;i++) {
        line = lines[i].replace(/\s*$/,'');
        changed = 0;
        if (line.search(/^\s*bq\.\s+/) != -1) { line = line.replace(/^\s*bq\.\s+/,'<blockquote>')+'</blockquote>'; changed = 1; }
		
		// jeff adds h#.
        if (line.search(/^\s*h[1-6]\.\s+/) != -1) { 
	    	re = new RegExp('h([1-6])\.(.+)','g');
	    	line = line.replace(re,'<h$1>$2</h$1>');
			changed = 1; 
		}
		
		if (line.search(/^\s*\*\s+/) != -1) { 
			line = line.replace(/^\s*\*\s+/,'<liu>') + '</liu>'; 
			changed = 1;
		} // * for bullet list; make up an liu tag to be fixed later
        if (line.search(/^\s*#\s+/) != -1) { line = line.replace(/^\s*#\s+/,'<lio>') + '</lio>'; changed = 1; } // # for numeric list; make up an lio tag to be fixed later
        if (line.search(/^\s*\|/) != -1) { 
 //       	alert(line);
//        	line = line.trim();
        	line = line.substring(1, (line.length-1));
        	line = '<tr><td>' + line.replace(/\|/g, '</td><td>') + '</td></tr>'; change = 1;
			if (!intable) line = '<table>' + line;
        	intable = true;
			changed = 1; 
        } else {
			if (intable) line = '</table>' + line;
        	intable = false;	
        }
//        if (!changed && (line.replace(/\s/g,'').length > 0)) line = '<p>'+line+'</p>';
        if (!changed) line = line + '<br/>';
        lines[i] = line + '\n';
    }
    // Second pass to do lists
    inlist = 0; 
	listtype = '';
    for (var i=0;i<lines.length;i++) {
        line = lines[i];
        if (inlist && listtype == 'ul' && !line.match(/^<liu/)) { line = '</ul>\n' + line; inlist = 0; }
        if (inlist && listtype == 'ol' && !line.match(/^<lio/)) { line = '</ol>\n' + line; inlist = 0; }
        if (!inlist && line.match(/^<liu/)) { line = '<ul>' + line; inlist = 1; listtype = 'ul'; }
        if (!inlist && line.match(/^<lio/)) { line = '<ol>' + line; inlist = 1; listtype = 'ol'; }
        lines[i] = line;
    }

    r = lines.join('\n');
	// jeff added : will correctly replace <li(o|u)> AND </li(o|u)>
    r = r.replace(/li[o|u]>/g,'li>');
    return r;
}

