﻿var patternList = {
    //-------------------------------------------------------------------------
    // contenct block
    '\\[\\['    :    '<div class="content_block">',
    '\\]\\]'    :    '</div>',
    //-------------------------------------------------------------------------
    // paragraphs
    '==R>'  :      '<p class="hyphenate" style="text-align:right">',
    '==C>'  :      '<p class="hyphenate" style="text-align:center">',
    '==L>'  :      '<p class="hyphenate" style="text-align:left">',
    '==>'   :      '<p class="hyphenate">',
    '<=='   :      '</p> ',
    '==FN>'    :    '<p class="footnote hyphenate">',
    //-------------------------------------------------------------------------
    // general formatting
    '~'        :    '&shy;',
    '__'    :    '<br/>',
    '---'    :    '<hr/>',
    '(>|\\s|^)\\*([^\\*]+)\\*(<|\\s|$)'    :    '$1<em>$2</em>$3',
    '(>|\\s|^)_([^_]+)_(<|\\s|$)'        :    '$1<cite>$2</cite>$3',
    //-------------------------------------------------------------------------
    // images
    '\\(image_?([^\\s_]*)\\)\\(([^\\s\\)]*)\\)'    : '<img class="$1" src="$2" />',
    '\\(labelled_image_?([^\\s]*)\\)\\(([^\\s\\)]*)\\)\\(([^\\)]*)\\)' : '<div class="labelled $1"><img class="labelled_$1" src="$2" />$3</div>',
    '\\(gallery_image\\)\\(([^\\s\\)]*)\\)\\(([^\\)]*)\\)'    : '<a href="$2"><img class="thumbnail" src="$1" /></a>',
    // ----------------------------------------------------------------------------
    // hyperlinks
    // workaround for labelled image links
    '\\((<div class=\"labelled.*)(<img.*>)(.*)(</div>)\\)\\->\\(([^\\s\\(\\)]+)\\)'    :    '$1<a href="$5">$2$3</a>$4',
    // regular hyperlinks
    '\\(flag_(.{2})\\)\\->\\(([^\\s\\(\\)]+)\\)'    :    '<a href="$2"><img src="./images/flag_$1_small.gif" /></a>',
    '\\(text_(.{2})\\)\\->\\(([^\\s\\(\\)]+)\\)'    :    '<a class="label" id="text_$1" href="$2">text_$1</a>',
    '\\(photo\\)\\->\\(([^\\s\\(\\)]+)\\)'            :    '<a href="$1"><img src="./images/photo.gif" /></a>',
    '\\(scale\\)\\(([^\\s\\(\\)]+)\\)'                 :   '<img src="./images/$1.gif"/>',
    '\\(label\\)\\(([^\\s\\(\\)]+)\\)'                 :   '<span class="label" id="$1">$1</span>',
    '\\(([^\\(\\)]+)\\)\\->\\(([^\\s\\(\\)]+)\\)'     :     '<a href="$2">$1</a>',
    '\\(([^\\(\\)]+)\\)\\^\\(([^\\s\\(\\)]+)\\)'    :    '<a href="$2" target="_blank">$1</a>',
    // ----------------------------------------------------------------------------
    // headers
    '^(\\s*)(=){1}([^=].*[^=])(=){1}(\\s*)$'    :    '<h1>$3</h1>',
    '^(\\s*)(=){2}([^=].*[^=])(=){2}(\\s*)$'     :     '<h2>$3</h2>',
    '^(\\s*)(=){3}([^=].*[^=])(=){3}(\\s*)$'     :     '<h3>$3</h3>',
    '^(\\s*)(=){4}([^=].*[^=])(=){4}(\\s*)$'     :     '<h4>$3</h4>'
};

function convertToHTML(content) {
	//-----------------------------------------------------------------
	// converts markup text to html
    var regexp;
    var content2;
    for (var i in patternList) {
        content2=content;
        do {
            regexp = new RegExp(i, 'gm');
            content=content2;
            content2=content.replace(regexp, patternList[i]);
        } while (content2 !=content);
    }
    return content2;
}

function makeLanguageListFlags(data) {
    var languageList = $.grep(new Array(data.hu, data.en, data.de, data.ru, data.es) ,function(n,i){ return(n); });
    var languageListFlags = "";
    for (var l in languageList) {
        languageListFlags += " (flag_"+languageList[l]+")->(#article="+data.cikk_szam+";lang="+languageList[l]+";)";
    }
    return languageListFlags;
}

function makeTitle(data, linked, in_list) {
	var title = "";	
	title = linked ?  '<a href="#article=' + data.cikk_szam +';">' + data.cim + '</a>' : data.cim;
	title += 
		makeLanguageListFlags(data) +
		(data.kepek > 0 ? ' <a href="#gallery='+data.cikk_szam+';"><img src="./images/photo.gif" /></a>' : ' ') +
		(data.meretarany ? ' <img src="./images/'+ data.meretarany +'.gif"/>' : ' ');
	title = in_list ? title + '<br/>\n' : "<h1>" + title +"</h1>\n";
	return title;	
}

$(function() {
	// initialize google analytics
    if (typeof(_gat) !== "undefined") {
        pageTracker = _gat._getTracker("UA-5428359-1");
    }
    else {
        pageTracker = false;
    }
	
	var siteLang = '';
	var loadedContentType = '';
	var	loadedContent = '';
	var loadedContentLang = '';
	var allLabels = '';
	
	var displayedContent = {
		title: "",
		gallery: "",
		text: "",
		links: "",
		info: ""		
	};	
	
	//-----------------------------------------------------------------
	// loading labels
	$.ajax({
		url: './php/get_labels.php',
		async: false,
		dataType: 'json',
		success: function (labels) {
			allLabels = labels;
		}
	});		
	
	// hashchange event
	$(window).hashchange( function(){	
		var hash = "";
		var params = {};		
		var splitHash = function(hash) {
			var paramsTemp = hash.split(";");
			var splitParam;
			for (var i in paramsTemp) {
				splitParam = paramsTemp[i].split("=");
				params[splitParam[0]] = splitParam[1];
			}		
			return params;
		}
		
		var content = '';
		var contentType = '';
		var contentLang = '';
		var contentChanged = '';
		var contentLangChanged = '';
		var contentTypeChanged = '';
		var labels = '';
				
		var articleData = '';
		var languageList = '';
		var languageListText = '';
		
		var articleImages = [];
		var embeddedImages = '';
		var articleRelated = '';
		var list = '';

		//-----------------------------------------------------------------
		// parse hash
		hash = location.hash;
		
        // remove leading # as well trailing ; if present
		hashregexp = new RegExp('^#(.*[^;]);?$', 'gm');
        hash = hash.replace(hashregexp, '$1');

		// extract params from hash
		params = splitHash(hash);
		
		//-----------------------------------------------------------------
		// setting site language
		if (siteLang === '' || params.setlang) {
			if (params.setlang) {				
				siteLang = params.setlang;				
			}
			else {
				//- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
				//browser/user language detection				
				siteLang = params.setlang?params.setlang:params.lang?params.lang:navigator.language?navigator.language:"hu";
				
				//- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
				// matching language strings
				siteLang = siteLang.match(/hu/)?"hu":(siteLang.match(/de/)?"de":(siteLang.match(/ru/)?"ru":"en"));				
			}		

			//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
			// language indicator flag
			$('a.active_language').removeClass('active_language');
			$('#lang_'+siteLang).addClass('active_language');	
		}	
		
		labels = allLabels[siteLang];
		// setting content language
		contentLang = params.lang?params.lang:siteLang;
		
		// setting content type
		contentType = params.article?"article":params.gallery?"gallery":params.list?"list":params.forum?"forum":loadedContentType?loadedContentType:"list";
		content = params[contentType]?params[contentType]:loadedContent?loadedContent:"updates";
		
		//-----------------------------------------------------------------
		// determining whether content shall be loaded or not
		contentChanged = (content === loadedContent)?false:true;
		contentLangChanged = (contentLang === loadedContentLang)?false:true;
		contentTypeChanged = (contentType === loadedContentType)?false:true;
		
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
		// track page view				
		if (pageTracker && (contentChanged || contentTypeChanged)) {
				pageTracker._trackPageview(contentType === "forum" ? "/forum" : "/"+contentType+"/"+content);	
		}
		
		//-----------------------------------------------------------------
		// load content
		if (contentChanged || contentLangChanged) {
			// empty containers
			var displayedContent = {
				title: "",
				gallery: "",
				text: "",
				links: "",
				info: ""
			};			
			
			// article or category lists			
			// get just the list
			if (contentType === "list") {
				$.ajax({
					url: './php/get_data.php?type=' + contentType+ '&content=' + content + '&language=' + contentLang,
					async: false,
					dataType: 'json',
					success: function (data) {
						list = data;
					}
				});
				if (content === "updates") {
					displayedContent.title = "";
					for (var i in list) {
						if (list[i].tipus === "hir") {
							displayedContent.title += makeTitle(list[i]);
						}
						else {
							displayedContent.title += makeTitle(list[i], 'linked');
						}
						displayedContent.title += '<p class="hyphenate"><i>' + list[i].datum + "</i> - " + list[i].szoveg + "</p>\n";
					}
				}
				else if (content === "categories") {
					displayedContent.title = '<h1 class="label" id="articles">articles</h1>';
					displayedContent.text = "";
					for (var i in list) {
						displayedContent.text += '<h3>(<span class="label" id="'+ list[i].kategoria + '">'+list[i].kategoria+'</span>)->(#list='+ list[i].kategoria +';) <span class="additional">(' + list[i].cikkek_szama + ')</span> </h3>';
					}
				}
				else if (content === "links") {
					displayedContent.title = '<h1 class="label" id="links">links</h1>';
					displayedContent.text = list[0].cikk_szoveg;
				}
				else if (content === "rules") {
					displayedContent.title = '<h1 class="label" id="rules">rules</h1>';
					displayedContent.text = list[0].cikk_szoveg;
				}
				else {
					displayedContent.title = '<h1 class="label" id="'+content+'">'+content+'</h1>';
					displayedContent.text = "==>";
					for (var i in list) {
						if (content === "battle_reports" || content == "armies") {
							if (!list[i-1] || (list[i].korszak != list[i-1].korszak)) {
								displayedContent.text += '<h3 class="label" id="' + list[i].korszak + '">' + list[i].korszak + '</h3>\n==>';
							}
						}
						else {
							if (content === "events" ){
								if (!list[i-1] || (list[i].datum.substr(0, 4) != list[i-1].datum.substr(0, 4))) {
									displayedContent.text += '<h3>' + list[i].datum.substr(0, 4) + '</h3>\n==>';
								}
							}
						}
						//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
						// composing content
						displayedContent.text += makeTitle(list[i], 'linked', 'in_list');
					}
					displayedContent.text += '<==';
				}
			}
			// forum
			// dont get anything
			else if (contentType === "forum") {
				//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
				// inserting content
				displayedContent.title = '<h1 class="label" id="forum"></h1>';
				displayedContent.text = '<iframe id="forum_container" src="forum" scrolling="no"/>';
			}
			// articles
			else if (contentType === "article" || contentType === "gallery"){	
				//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
				// get article data
				$.ajax({
					url: './php/get_data.php?type=article&content=' + content + '&language=' + contentLang,
					async: false,
					dataType: 'json',
					success: function (data) {
						articleData = data[0];
					}
				});
				//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
				// get gallery, if needed
				if (articleData.kepek > 0) {
					$.ajax({
						url: './php/get_data.php?type=gallery&content=' + content + '&language=' + contentLang,
						async: false,
						dataType: 'json',
						success: function (images) {
							for (var i in images) {
								articleImages[i] = '<a href="articles/'+images[i].cikk_szam+"/images/"+images[i].kep+'"><img class="thumbnail" src="articles/' +images[i].cikk_szam+"/thumbnails/"+images[i].miniatur + '" \></a>';
							}
						}
					});
				}
				//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
				// get related links
				$.ajax({
					url: './php/get_data.php?type=related&content=' + content + '&language=' + contentLang,
					async: false,
					dataType: 'json',
					success: function (data) {
						articleRelated = data;
					}
				});
				
				//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -				
				// compose content	
				
				//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
				// making article language list for default text
				languageList = $.grep(new Array(articleData.hu, articleData.en, articleData.de, articleData.ru) ,function(n,i){ return(n); });                                
				languageListText = "";
				var i = 0;
				for (var l in languageList) {					
					switch(i) {
						case 0:
							break;
						case languageList.length-1:
							languageListText += " "+labels['et'];
							break;
						default:
							languageListText += ", ";
							break;
					}					
					languageListText += " (text_"+languageList[l]+")->(#article="+articleData.cikk_szam+";lang="+languageList[l]+";)";
					i++;
				}

				if (languageListText.length == 0) {
					contentType = "gallery";
				}

				//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
				// title
				displayedContent.title = makeTitle(articleData);				
				
				//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
				// artcicle text
                displayedContent.text = languageListText.length !== 0 ? articleData.cikk_szoveg : "";				
				
				//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
				// replace language links in default text
				regexp = new RegExp('\\(language_links\\)', 'gm');
				displayedContent.text = displayedContent.text.replace(regexp, languageListText);			
				
				//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
				// replace in-line gallery blocks with images
				regexp = new RegExp('\\(gallery_block\\s(\\d\\d?)-(\\d\\d?)\\)', 'm');

				matchResult = displayedContent.text.match(regexp);
				while (matchResult) {
					embeddedImages = '';
					for (var i = matchResult[1]-1; i<=matchResult[2]-1; i++) {
						embeddedImages += articleImages[i];
					}
					displayedContent.text = displayedContent.text.replace(regexp, embeddedImages);
					matchResult = displayedContent.text.match(regexp);
				}				
				
				//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
				// make gallery
				for (i in articleImages) {
					displayedContent.gallery += articleImages[i];
				}
				
				//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
				// composing article info block
				if (articleData.szerzo || articleData.foto ||  articleData.modellezte) {
					
					if (articleData.modellezte) {
						articleData.modellezte_label = '';
						articleData.modellezte_list = articleData.modellezte.split(',');					
						for (var i in articleData.modellezte_list) {
							if (articleData.modellezte_list.hasOwnProperty(i)) {
								articleData.modellezte_label += "(label)("+articleData.modellezte_list[i]+"), ";
							}							
						}
						articleData.modellezte_label = articleData.modellezte_label.replace(/,\s*$/, '');
					}
					if (articleData.szerzo !== articleData.foto && articleData.szerzo !== articleData.modellezte && articleData.foto !== articleData.modellezte) {
						displayedContent.info = articleData.szerzo?"(label)(text): (label)("+articleData.szerzo+")":"";
						displayedContent.info += articleData.foto?"__(label)(photos): (label)("+articleData.foto+")":"";
						displayedContent.info += (articleData.modellezte_label)?"__(label)(figures):" + articleData.modellezte_label :"";

					}
					else if (articleData.szerzo === articleData.foto && articleData.szerzo == articleData.modellezte) {
							displayedContent.info = "(label)("+articleData.szerzo+")";
					}
					else {
						if (articleData.szerzo === articleData.foto) {
							displayedContent.info = articleData.szerzo?"(label)(text_and_photos): (label)("+articleData.szerzo+")":"";
							displayedContent.info += (articleData.modellezte_label)?"__(label)(figures): "+articleData.modellezte_label:"";
						}
						if (articleData.foto === articleData.modellezte) {
							displayedContent.info = articleData.szerzo?"(label)(text): (label)("+articleData.szerzo+")":"";
							displayedContent.info += (articleData.modellezte_label)?"__(label)(photos_and_figures): "+articleData.modellezte_label:"";
						}
						if (articleData.szerzo === articleData.modellezte) {
							displayedContent.info = articleData.szerzo?"(label)(text_and_figures): (label)("+articleData.szerzo+")":"";
							displayedContent.info += articleData.foto?"__(label)(photos): (label)("+articleData.foto+")":"";
						}
					}
					displayedContent.info = "==R>" + displayedContent.info +"<==";
				}

				//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
				// related links
				if (articleRelated.length > 0) {
					displayedContent.links = '<h2 class="label" id="related_articles">related_articles</h1>';
				
					for (var i in articleRelated) {
						//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
						// making article language lists
						var languageList = $.grep(new Array(articleRelated[i].hu, articleRelated[i].en, articleRelated[i].de, articleRelated[i].ru, articleRelated[i].es) ,function(n,i){ return(n); });
						var languageListFlags = "";
						for (var l in languageList) {
							languageListFlags += " (flag_"+languageList[l]+")->(#article="+articleRelated[i].cikk_szam+";lang="+languageList[l]+";)";
						}

						if (!articleRelated[i-1] || (articleRelated[i].kategoria != articleRelated[i-1].kategoria)) {
							displayedContent.links += '<h3 class="label" id="' + articleRelated[i].kategoria + '">' + articleRelated[i].kategoria + '</h3>\n==>';
						}

						//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
						// composing content
						displayedContent.links += makeTitle(articleRelated[i], 'linked', 'in_list');
					}	
				}
			}			
		}
		
		//-----------------------------------------------------------------
		// display content depending on type		
		// fill and display used blocks, empty and hide unused
		for (block in displayedContent) {
			$('#'+block+'_container').html(convertToHTML(displayedContent[block]));
			if (displayedContent[block] === "") {
				$('#'+block+'_container').toggle(false);
			}
			else {
				$('#'+block+'_container').toggle(true);
			}
		}

		if (contentType == "article") {
			$('#text_container').toggle(true);
			$('#gallery_container').toggle(false);
		}
		else if(contentType == "gallery") {
			$('#text_container').toggle(false);
			$('#gallery_container').toggle(true);
		}
		else if (contentType == "forum") {
			$('#forum_container').iframeAutoHeight();
		}
		
		//-----------------------------------------------------------------
		// replace labels
		$('.label').each(function(){
			$(this).html(labels[$(this).attr('id')]);
		});
		
		//-----------------------------------------------------------------
		// hyphenate content
		// setting language for hyphenation
		$('html').attr('lang', contentLang);
		//if (contentLang === 'hu') {
			//HyphenatorExtendedHungarian.run();
		//}
		//else {
			if (contentLang !== 'en'){
				Hyphenator.run();
			}
		//}
		
		//-----------------------------------------------------------------
		// lightbox init
		$('#jquery-lightbox').remove();
		$('#jquery-overlay').fadeOut("slow", function() { $('#jquery-overlay').remove(); });
		// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
		$('embed, object, select').css({ 'visibility' : 'visible' });		
		
		var lb = $(displayedContent.gallery);
		lb.lightBox({
			overlayBgColor: 'rgb(111,68,138)',
			overlayOpacity: 0.9,
			imageBtnClose: 'images/close.jpg',
			imageBtnPrev: 'images/prev.jpg',
			imageBtnNext: 'images/next.jpg',
			imageLoading: 'images/loading.gif',
			txtImage: '',
			txtOf: '/'
		});
		$('.thumbnail').parent('a[target!="_blank"]').click(function() {
			lb.filter('a[href="' + $(this).attr('href') + '"]').click();
			return false;
		});		
		
		//-----------------------------------------------------------------
		// store loaded content		
		loadedContentType = contentType;
		loadedContent = content;		
		loadedContentLang = contentLang;	

	});

    if (window.location.hash === '') {
        window.location.hash = "#list=updates;";
    }
	else {
		$(window).hashchange();
	}

});
