var TVS = null;
var embed = false;
var oldquery = null;
function handlePageLoad() 
{
        TVS = new TruveoVideoSearch('1x1jhj64466mi12ia');
	TVS.showRelatedItems = 1;
        TVS.attachEvent('onload', 'handleVSLoad();');
        TVS.attachEvent('onupdate', 'handleUpdate();');
        TVS.initialize();
}
function handleVSLoad() 
{
        TVS.getVideos('tag:Urlaub');
}

function getVideos(query, start) { 

	document.getElementById('result').innerHTML = '<img src="./img/ajax.gif" alt="Loading...">';
	embed = false;
	query += ',tag:Urlaub'
	if (arguments.length < 1) { TVS.getVideos(query); }
	else if (arguments.length < 2) { TVS.getVideos(query); }
	else { TVS.getVideos(query, start); }
}

function getVideosByCategory(category) {
	if (category.toLowerCase() == 'all') { 
		var query = TVS.query;
		if (oldquery){query=oldquery;}
		query = query.replace(/\s?category:"[^"]*"/gi, "");
		query = query.replace(/\s?category:\S*/gi, "");
		getVideos(query); 
	}
	else 
	{ 
		var query = TVS.query;
		var theRegExp = new RegExp('\\s?category:"\\s*'+VSUTIL.escapeRegExp(category)+'\\s*"', "gi");
		query = query.replace(theRegExp, "");
		theRegExp = new RegExp('\\s?category:'+VSUTIL.escapeRegExp(category), "gi");
		query = query.replace(theRegExp, "");
		getVideos(query + ' category:"' + category + '"'); 
	}
}
function sortBy(sortOption) { getVideos(TVS.query.replace(/\s?sort:\S*/gi, "") + " sort:" + sortOption);}

function filterType(type) { 
    if (oldquery) { TVS.query = oldquery;}
    var query = TVS.query.replace(/\s?type:\S*/gi, "");
    if (type == 'all') { getVideos(query); }
        else { getVideos(query + " type:" + type); }
}

function getCategories(CategorySet)
{
    var charLimit = 16;
    divcategories =  document.getElementById('categories')
    divcategories.innerHTML = '<div><a href="javascript:getVideosByCategory(\'all\'); void(0);">Alle Kategorien</a></div>';
    if (("totalResultsReturned" in CategorySet) && (CategorySet.totalResultsReturned > 0)) 
    {
	for (var i=0; i < CategorySet.totalResultsReturned; i++) 
	{
	    var categoryName = CategorySet.Category[i].name;
	    var categoryCount = CategorySet.Category[i].count;
	    divcategories.innerHTML += '<div><a href="javascript:getVideosByCategory(\''+VSUTIL.escapeHTMLString(categoryName)+'\'); void(0);">'+VSUTIL.escapeHTML(VSUTIL.truncateString(categoryName, charLimit))+' ('+categoryCount+')</a></div>';

	}
    }											
}	    

function playVideo(videoUrl, id) {
	embed = true;
	oldquery = TVS.query;
//    	window.open(videoUrl, '', 'width=800,height=800,location=no,menubar=no,resizable=yes,scrollbars=yes');
	TVS.getVideos(id,0);
}
    
function handleUpdate() {
	document.getElementById('categories').innerHTML = '';
	getCategories(TVS.CategorySet);
	if (embed)
	{
	    html = TVS.VideoSet.Video[0].videoPlayerEmbedTag;
	    html = '<h3>' + TVS.VideoSet.Video[0].title + '</h3><hr /><br />' + html;
	    html += '<div><br /><a href="javascript:getVideos(oldquery);void(0);" style="font-size:16px;text-decoration:underline;">zur&uuml;ck</a></div>';
	    divembed =  document.getElementById('embed')
	    divembed.innerHTML = '<div style="padding-left:10px;">' + html + '</div>';
	    divembed.style.display = "block";
	    document.getElementById('result').innerHTML = '';
	    document.getElementById('pagebar').innerHTML = '';
	    return;
	}
	divpagebar = document.getElementById('pagebar');
	divpagebar.innerHTML = "";
	document.getElementById('embed').display ="non";
	res = document.getElementById('result');
	res.innerHTML = "";
	pos = TVS.VideoSet.firstResultPosition;
	posend = eval(pos) + 10;
	document.getElementById('embed').innerHTML = "";
	j = 0;
	pageshtml = "";
	pos = eval(pos);
	for (var i=pos-40;i<TVS.VideoSet.totalResultsAvailable;i=i+10)
	{
	    if((i % 10 == 0) && (i > 0))
	    {
		j++;
		if (j >= 10){ break;}
		if (i==pos) { thispage = 'style="font-size:14px;text-decoration: underline;"';} else{ thispage='';}
		pageshtml += '<a href="#" class="nextpage"' + thispage + 'onclick="getVideos(TVS.query,' + i +');">'+ eval(i)/10 + '</a>';	    
		if (j < 9){pageshtml += "|";}
	    }
	}
	
        divpagebar.innerHTML += '<div><div style="float:left;"><h3>Videos:</h3>' + pos + " bis " + posend + " von " + TVS.VideoSet.totalResultsAvailable + "</div>";
	divpagebar.innerHTML += '<div style="float:right;"><h3>&nbsp;</h3>' + pageshtml + '</div></div><div style="clear:both;"></div><hr><br />';
        var colorow = '';
        for (var i=0; i < TVS.VideoSet.totalResultsReturned; i++) 
	{
	    var theVideo = TVS.VideoSet.Video[i];

	    if (i%2==0){colorrow=' class="secondrow"';} else { colorrow=' ';}
		
	    date = 'Hinzugef&uuml;gt: ' + VSUTIL.getShortDateString(TVS.VideoSet.Video[i].dateFound);
	    runtime = 'Laufzeit : ' + VSUTIL.getRuntimeString(TVS.VideoSet.Video[i].runtime);
	    extrainfo = '<div class="extrainfo">' + date + ' | ' + runtime + '</div>';
	    url = '<a href="javascript:playVideo(\''+theVideo.visdeoPlayerEmbedTag+'\','+theVideo.id+');void(0);"><img src="'+theVideo.thumbnailUrl+'" class="thumbnail" alt="click to play video"/></a>';

	    html = '<br /><div'+colorrow+'><div style="float:left;padding:5px;" id="resultvideo'+i+'">' + url + '</div><div id="resultTitle'+i+'" style="float:left;padding:3px;width:480px;"><div class="title"><a href="javascript:playVideo(\''+theVideo.visdeoPlayerEmbedTag+'\','+theVideo.id+');void(0);">' + theVideo.title + '</a></div>'+extrainfo;
	    html += '<div id="resultDescr'+i+'">' + theVideo.description + '</div></div>';
	    html += '<div style="clear:left;"></div>';
	    res.innerHTML += html;
        }	
}
var VSUtilities = function() {
this.getShortDateString = function(dateFound) {
		var theDate = new Date(dateFound);
		var now = new Date();
		var elapsedTime = now.getTime() - theDate.getTime();
		var seconds = Math.round(elapsedTime/1000);
		if (seconds < 60) { return("vor " + seconds+" Sekunde"+(seconds==1?'':'n')); }
		var minutes = Math.round(elapsedTime/(1000*60));
		if (minutes < 60) { return("vor " + minutes+" Minute"+(minutes==1?'':'n')); }	
		var hours = Math.round(elapsedTime/(1000*60*60));	
		if (hours < 24) { return("vor " + hours+" Stunde"+(hours==1?'':'n')); }
		var days = Math.round(elapsedTime/(1000*60*60*24));
		if (days < 30) { return("vor " + days+" Tag"+(days==1?'':'en')); }	
		var months = Math.round(elapsedTime/(1000*60*60*24*30));
		if (months < 12) { return("vor " + months+" Monat"+(months==1?'':'en')); }	
		var years = Math.round(elapsedTime/(1000*60*60*24*30*12));
		return("vor " + years+" Jahr"+(years==1?'':'en'));
	}
this.getRuntimeString = function(runtime) {
		var totalSeconds = parseInt(runtime);
		var minutes = Math.floor(totalSeconds/60);
		var seconds = totalSeconds - (minutes * 60);
		return(minutes+"min "+seconds+"sek");
    }
this.escapeHTML = function(string) {
		var newstr = string.replace(/&/g,"&amp;");
		newstr = newstr.replace(/</g,"&lt;");
		newstr = newstr.replace(/>/g,"&gt;");
		newstr = newstr.replace(/'/g,"&#039;");
		newstr = newstr.replace(/"/g,"&quot;");
		return(newstr);
	}
							
this.escapeHTMLString = function(string) {
		var newstr = string.replace(/&/g,"&amp;");
		newstr = newstr.replace(/</g,"&lt;");
		newstr = newstr.replace(/>/g,"&gt;");
		newstr = newstr.replace(/'/g,"\\&#039;");
		newstr = newstr.replace(/"/g,"\\&quot;");
		return(newstr);		
	}
this.truncateString = function(string, maxChar) {
		if (string && (string.length > maxChar)) {
		var index = string.indexOf(";", maxChar);
		if ((index >= 0) && ((index - maxChar) < 10)) { maxChar = index+1; }
		return(string.substr(0, maxChar)+'...');
		}
		else { return(string); }
	}
this.escapeRegExp = function(string) {
		var newstr = string.replace(/\^/g,"\^");
		newstr = newstr.replace(/\$/g,"\$");
		newstr = newstr.replace(/\./g,"\.");
		newstr = newstr.replace(/\*/g,"\*");
		newstr = newstr.replace(/\+/g,"\+");
		newstr = newstr.replace(/\?/g,"\?");
		newstr = newstr.replace(/\=/g,"\=");
		newstr = newstr.replace(/\!/g,"\!");
		newstr = newstr.replace(/\:/g,"\:");
		newstr = newstr.replace(/\|/g,"\|");
		newstr = newstr.replace(/\\/g,"\\");
		newstr = newstr.replace(/\//g,"\/");
		newstr = newstr.replace(/\(/g,"\(");
		newstr = newstr.replace(/\)/g,"\)");
		newstr = newstr.replace(/\[/g,"\[");
		newstr = newstr.replace(/\]/g,"\]");
		newstr = newstr.replace(/\{/g,"\{");
		newstr = newstr.replace(/\}/g,"\}");
		return(newstr);		
	}
}

VSUTIL = new VSUtilities();


