
var ctrl = new WissenController();
var wiWochentagArr = new Array("Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag");
var wiMonatArr     = new Array("Januar", "Februar", "M&auml;rz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember");

function wiHasBoCookie()
{
	var val = false;
	if (ctrl.getCookie('boSession') || (ctrl.getCookie('digasnet.cookie.loginname') && ctrl.getCookie('digasnet.cookie.passwd')))
	{
		val = true;
	} 
	return val;
}

// Suchbegriff setzen
function setFieldValue(fieldId,wort)
{
	var formFeld = document.getElementById(fieldId);
	formFeld.value = wort;
}

function wiUnquote(str)
{
	if (str && str != null)
	{
		str = str.replace(/&quot;/g, '"');
		str = str.replace(/&lt;/g, '<');
		str = str.replace(/&gt;/g, '>');

		str = str.replace(/&amp;/g, '&');
		
		return str;
	}
	else
		return '';
}

function wiChangeDate(von, bis, lid)
{
	var url = location.href;

	url = url.replace(/\&von=[^&]*/, '');
	url = url.replace(/\?von=[^&]*&/, '?');
	url = url.replace(/\?von=[^&]*/, '');

	url = url.replace(/\&bis=[^&]*/, '');
	url = url.replace(/\?bis=[^&]*&/, '?');
	url = url.replace(/\?bis=[^&]*/, '');

	url = url.replace(/\&lid=[^&]*/, '');
	url = url.replace(/\?lid=[^&]*&/, '?');
	url = url.replace(/\?lid=[^&]*/, '');

	url = url.replace(/\&pc=[^&]*/, '');
	url = url.replace(/\?pc=[^&]*&/, '?');
	url = url.replace(/\?pc=[^&]*/, '');
	
	url = url.replace(/#$/, '');
	
	if (url.indexOf('?') >= 0)
		url = url + "&";
	else
		url = url + "?";
	url = url + "von=" + von + "&bis=" + bis + "&lid=" + lid;
	location.href = url;
}

function displayDate(divId, useMonthname)
{
	var dd = $(divId);
	if (dd != null && typeof dd != 'undefined') 
	{
 		var d = new Date();
 		if (useMonthname != null && typeof useMonthname != 'undefined' && useMonthname == true)
 			var mh = wiWochentagArr[d.getDay()] + ', ' + d.getDate() + '.' + wiMonatArr[d.getMonth()] + ' ' + d.getFullYear();
 		else
 			var mh = wiWochentagArr[d.getDay()] + ', ' + d.getDate() + '.' + (d.getMonth() + 1) + '.' + d.getFullYear();
		dd.update(mh);
	}
}

// --------------------------------------------------------------------------
// BasisFunktionen
// --------------------------------------------------------------------------
function WissenController()
{
this.getCookieVal = function getCookieVal (offset)
{
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
	endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}

//  setCookie (name, val, expires, path, domain, secure)
this.setCookie = function setCookie (name,value,expires,path,domain,secure) 
{
document.cookie = name + "=" + escape (value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
}

this.getCookie = function getCookie (name) 
{
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) 
{
	var j = i + alen;
	if (document.cookie.substring(i, j) == arg)
		return this.getCookieVal (j);
	i = document.cookie.indexOf(" ", i) + 1;
	if (i == 0) break;
}
return null;
}
}

// --------------------------------------------------------------------------
// divName:     Name des Divs wo die Suchwoerter rein sollen
// fieldId:     Name des Form-Feldes "suchbegriff" - für Wiederbefuellung
// cookieName:  Name des Cookies unter dem die Historie gespeichert wird
// limit:       Maximale Anzahl an gespeicherten Suchbegriffen
// --------------------------------------------------------------------------
function W4USuchhistorie(divName,fieldId,cookieName,limit)
{
this.controller = new WissenController();
this.fieldId = fieldId;
this.divName = divName;
this.key = cookieName;
this.limit = limit;
this.sep = '@-@';

// liefert die Woerter aus dem Cookie oder leeren Array
this.getWords = function getWords()
{
var inVal = this.controller.getCookie(this.key);
var inList = new Array(0);

if (inVal)
	inList = inVal.split(this.sep);

return inList;
}

// 15 Minuten
this.getExpires = function getExpires()
{
var ablauf = new Date();
var fuenfMinuten = ablauf.getTime() + (15 * 60 * 1000); // 5 minuten
ablauf.setTime(fuenfMinuten);
return ablauf;
}

// Wort zur Suchhistorie hinzufügen
this.addWord = function addWord(wort)
{
var myWort = wort.replace(/^\s*|\s*$/g,'');
myWort =  myWort.replace(/\'/g,'')

if (myWort.length > 0)
{
this.addWordIntern(myWort);
this.updateDiv();
}
}

// intern
this.addWordIntern = function addWordIntern(wort)
{
// Woerter holen
var inList = this.getWords();

// wort an 1. pos der liste setzen
var newList = new Array(1);
newList[0] = wort;

// rest der bestehenden liste hinten ran (falls vorhanden)
var i = 0;
var len = inList.length;

for (; i < inList.length; i++)
{
if (wort == inList[i])
	continue;

if (newList.length >= this.limit)
	break;

newList.push(inList[i]);
}

// keks-zeit updaten
var ablauf = this.getExpires();

// keks neu setzen
var cVal = newList.join(this.sep);

this.controller.setCookie(this.key, cVal, ablauf);
}

// den View updaten
this.updateDiv = function updateDiv()
{
var i=0;
var wortArray = this.getWords();
var aDiv = document.getElementById(this.divName);

if (aDiv)
{
aDiv.nodeValue = '';

while (aDiv.firstChild)
{
	var Knoten = aDiv.firstChild;
	aDiv.removeChild(Knoten);
}

for (; i<wortArray.length;i++)
{
	var elem = this.generateEntry(wortArray[i])
	aDiv.appendChild(elem);
}
}
}

// Link zum Eintrag wieder ins "suchbegriff"-Feld setzen generieren
this.generateEntry = function generateEntry(wort)
{
var wortText = document.createTextNode(wort);
var myHref = document.createAttribute("href");
var myOnclick = document.createAttribute("onclick");
var aNode = document.createElement("a");
myHref.nodeValue = "#";
myOnclick.nodeValue = "Javascript:setFieldValue('" + this.fieldId + "', '" + wort + "'); document.forms['suchform'].submit(); return false;";
aNode.appendChild(wortText);
aNode.setAttributeNode(myHref);
aNode.setAttributeNode(myOnclick);
return aNode;
}
}


//----------------------------------------------------------
// FUNKTIONEN FUER DIE WISSEN VIDEOS | START
//----------------------------------------------------------

function spFlashDetectInit()
{
	if(!document.getElementById('spFlashDetectInitScript'))
	{
		var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
		var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
		var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

		if(isIE && isWin && !isOpera)
		{
			document.write('<scr'+'ipt id="spFlashDetectInitScript" type="text/vbscript">\n');
			document.write('Function spGetSwfVer(i)\n');
			document.write('on error resume next\n');
			document.write('Dim swControl, swVersion\n');
			document.write('swVersion = 0\n');
			document.write('set swControl = CreateObject("ShockwaveFlash.ShockwaveFlash." + CStr(i))\n');
			document.write('if (IsObject(swControl)) then\n');
			document.write('swVersion = swControl.GetVariable("$version")\n');
			document.write('end if\n');
			document.write('spGetSwfVer = swVersion\n');
			document.write('End Function\n');
			document.write('<\/scr'+'ipt>\n');
			document.write('\n');
		} 
		else 
		{
			document.write('<scr'+'ipt id="spFlashDetectInitScript" type="text/javascript">\n');
			document.write('function spGetSwfVer(i)\n');
			document.write('{\n');
			document.write('if (navigator.plugins != null && navigator.plugins.length > 0) {\n');
			document.write('if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {\n');
			document.write('var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";\n');
			document.write('var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;\n');
			document.write('descArray = flashDescription.split(" ");\n');
			document.write('tempArrayMajor = descArray[2].split(".");\n');
			document.write('versionMajor = tempArrayMajor[0];\n');
			document.write('versionMinor = tempArrayMajor[1];\n');
			document.write('if ( descArray[3] != "" ) {tempArrayMinor = descArray[3].split("r");} else {tempArrayMinor = descArray[4].split("r");}\n');
			document.write('versionRevision=tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;\n');
			document.write('// variable flashVer zusammensetzen -> analog zu ie\n');
			document.write('flashVer="x " + versionMajor + "," + versionMinor + "," + versionRevision;\n');
			document.write('} else {\n');
			document.write('flashVer=-1;\n');
			document.write('}\n');
			document.write('}\n');
			document.write('// MSN/WebTV 2.6 supports Flash 4\n');
			document.write('else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;\n');
			document.write('// WebTV 2.5 supports Flash 3\n');
			document.write('else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;\n');
			document.write('// older WebTV supports Flash 2\n');
			document.write('else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;\n');
			document.write('// Can\'t detect in all other cases\n');
			document.write('else {flashVer = -1;}\n');
			document.write('return flashVer;\n');
			document.write('}\n');
			document.write('<\/scr'+'ipt>\n');
			document.write('\n');
		}
	}
} 

function spFlashDetect(reqMajorVer, reqMinorVer, reqRevision) 
{
	var reqVer = parseFloat(reqMajorVer + "." + reqRevision);
	// loop backwards through the versions until we find the newest version	
	for (var i=25;i>0;i--) 
	{
		versionStr = spGetSwfVer(i);
		if (versionStr == -1 ) 
		{ 
			return false;
		} 
		else if (versionStr != 0) 
		{
			var versionArray = new Array();
			var tempArray   = versionStr.split(" ");
			var tempString  = tempArray[1];
			versionArray    = tempString .split(",");
			var versionMajor    = versionArray[0];
			var versionMinor    = versionArray[1];
			var versionRevision = versionArray[2];
			var versionString   = versionMajor + "." + versionRevision;   // 7.0r24 == 7.24
			var versionNum      = parseFloat(versionString);
			// is the major.revision >= requested major.revision AND the minor version >= requested minor
			if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) 
			{
				return true;
			} 
			else 
			{
				return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );	
			}
		}
	}
}

function loadSmallFlashVideo(videoid, divelement)
{
	var divs = divelement.getElementsByTagName('DIV');
	for (key=0; key < divs.length; key++) 
	{
		eval('_videoElement'+divs[key].className+' = divs[key]');
	}	

	if(document.getElementById)
	{
		//flashvars += '&FlashVars_JS_setOAS_timeseen_url=spOasSetTimeseenUrl&FlashVars_JS_OAS_timeseen=spOasSetCurrentTimeseen&FlashVars_JS_OAS_reminder=spOasSetReminder&FlashVars_JS_openPopup=spOpenFlashvideoPopup&FlashVars_JS_showFlashDiv=spShowHiddenFlashplayerDiv2';
		if ( spFlashDetect(8,0,0) ) 
		{
			_videoElementsmallFlashPlayerRunning.innerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + 
				 '	      codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"' + 
				 '        id="'+videoid+'"' + 
				 '        width="180"' + 
				 '        height="155">' +
				 ' 		<param name="movie" value="/wissen/files/swf/180-all-006.swf" />' +
				 '		<param name="quality" value="high" />' +
				 '		<param name="bgcolor" value="#f2f2f2" />' +
				 '		<param name="menu" value="false" />' +
				 '		<param name="allowScriptAccess" value="always" />' +
				 '		<param name="wmode" value="transparent" />' +
				 '		<param name="FlashVars" value="FlashVars_videoid='+videoid+'&FlashVars_language=de&FlashVars_allowAds=true&FlashVars_JS_openPopup=wiOpenVideo&FlashVars_JS_showFlashDiv=wiToggleCredit" />' +
				 '		<embed src="/wissen/files/swf/180-all-006.swf" ' +
				 '		       name="'+videoid+'" ' +
				 '		       width="180" ' +
				 '		       height="155" ' +
				 '		       pluginspage="http://www.macromedia.com/go/getflashplayer"' + 
				 '		       quality="high"' +
				 '		       bgcolor="#f2f2f2"' + 
				 '		       menu="false" ' +
				 '		       allowScriptAccess="always"' + 
				 '		       wmode="transparent" ' +
				 '		       FlashVars="FlashVars_videoid='+videoid+'&FlashVars_language=de&FlashVars_allowAds=true&FlashVars_JS_openPopup=wiOpenVideo&FlashVars_JS_showFlashDiv=wiToggleCredit">' +
				 '		</embed>' +
				 '	</object>';
		} 
		else 
		{
			_videoElementsmallFlashPlayerRunning.innerHTML = '<div style="width:100%;height:149px;padding:3px;background-color:#f0f0f0">' +
				 '	Der benötigte Flash Player 8 wurde nicht gefunden.<br />' +
				 '  Mögliche Ursachen:<br /><br />' +
				 '  JavaScript erkennt den Player nicht korrekt.<br />' +
				 '	<br />Der Player ist nicht vorhanden.<br />' +
				 '  <a href="http://www.macromedia.com/go/getflash/" target="_blank">Jetzt installieren<\/a>' +
				 ' <\/div>';
		}
		
		wiToggleCredit('');
	}
	
	return false;
}

function wiToggleCredit(unused)
{
	// Hack
	if ($('wiVideoDescriptionDiv') != null)
	{
		var divs = $('wiVideoDescriptionDiv').getElementsByTagName('DIV');
		for (key=0; key < divs.length; key++) 
		{
			eval('_videoElement'+divs[key].className+' = divs[key]');
		}	
	}

	_videoElementsmallFlashPlayerRunning.style.zIndex = 3;
	_videoElementsmallFlashPlayerPicCredit.style.display = 'none';
	_videoElementsmallFlashPlayerVideoCredit.style.display = 'block';
}

function wiOpenVideo(videoid)
{
	window.open('http://www.spiegel.de/video/video-'+videoid+'.html');
}

spFlashDetectInit();



//----------------------------------------------------------
// FUNKTIONEN FÜR DIE WISSEN VIDEOS | ENDE
//----------------------------------------------------------


//----------------------------------------------------------
// FUNKTIONEN FÜR DIE DOKUMENTANZEIGE | START
//----------------------------------------------------------

/*-----------------------------------------------------------
    Toggles element's display value
    Input: any number of element id's
    Output: none 
    ---------------------------------------------------------*/
function toggleDisp() {
    for (var i=0;i<arguments.length;i++){
        var d = $(arguments[i]);
        if (d.style.display == 'none')
            d.style.display = 'block';
        else
            d.style.display = 'none';
    }
}
/*-----------------------------------------------------------
    Toggles tabs - Closes any open tabs, and then opens current tab
    Input:     1.The number of the current tab
                    2.The number of tabs
                    3.(optional)The number of the tab to leave open
                    4.(optional)Pass in true or false whether or not to animate the open/close of the tabs
    Output: none 
    ---------------------------------------------------------*/
function toggleTab(num,numelems,opennum,animate) {
    if ($('wiTabContent'+num).style.display == 'none'){
        for (var i=1;i<=numelems;i++){
            if ((opennum == null) || (opennum != i)){
                var temph = 'wiTabHeader'+i;
                var h = $(temph);
                if (!h){
                    var h = $('wiTabHeaderActive');
                    h.id = temph;
                }
                var tempc = 'wiTabContent'+i;
                var c = $(tempc);
                if(c.style.display != 'none'){
                    if (animate || typeof animate == 'undefined')
                        Effect.toggle(tempc,'blind',{duration:0.5, queue:{scope:'menus', limit: 3}});
                    else
                        toggleDisp(tempc);
                }
            }
        }
        var h = $('wiTabHeader'+num);
        if (h)
            h.id = 'wiTabHeaderActive';
        h.blur();
        var c = $('wiTabContent'+num);
        c.style.marginTop = '2px';
        if (animate || typeof animate == 'undefined'){
            Effect.toggle('wiTabContent'+num,'blind',{duration:0.5, queue:{scope:'menus', position:'end', limit: 3}});
        }else{
            toggleDisp('wiTabContent'+num);
        }
    }
}

function wiShowAllCluster()
{
    var divs = document.getElementById("wiCluster").getElementsByTagName("div");
    for (var i=0;i<divs.length;i++)
    {
        var d = $(divs[i]);
        if (d.style.display == 'none')
        {
            d.style.display = 'block';
        }
    }
    document.getElementById("wiClusterShowButton").style.display = 'none';
}

//----------------------------------------------------------
// FUNKTIONEN FÜR DIE DOKUMENTANZEIGE | ENDE
//----------------------------------------------------------


/** Für die Bildliste: Großes Bild bei mouseover zeigen */
function wiShowBigPic(url, title)
{
	var bDiv = $('wiBildergalerieBigPic');
	
	bDiv.update('<img id="wiBigPig" src="'+url+'" alt="'+title+'" border="0" />' +
					 '<br />' +
					 '<span style="font-style: italic;">' + title + '</span>');
	bDiv.show();
	
	var imgHeight = $('wiBigPig').getHeight();
	if (imgHeight == 0)  // noch nicht geladen
		imgHeight = 420;
	var topValue = -40 - imgHeight;
	bDiv.style.top = topValue + 'px';
}

/** Für die Bildliste: Großes Bild bei mouseout verstecken */
function wiHideBigPic()
{
	$('wiBildergalerieBigPic').hide();
}		

//----------------------------------------------------------
// BROWSERDETECTION USW.
//----------------------------------------------------------

function getBrowserDetect() 
{
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "Unbekannter Browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "Unbekannte Version";
		this.OS = this.searchString(this.dataOS) || "Unbekanntes Betriebssystem";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ string: navigator.userAgent, subString: "Chrome", versionSearch: "Chrome/", identity: "Chrome" },
        { string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb" },
		{ string: navigator.vendor, subString: "Apple", identity: "Safari" },
		{ prop: window.opera, identity: "Opera" },
		{ string: navigator.vendor,	subString: "iCab", identity: "iCab"	},
		{ string: navigator.vendor, subString: "KDE", identity: "Konqueror" },
		{ string: navigator.userAgent, subString: "Firefox", identity: "Firefox" },
		{ string: navigator.vendor, subString: "Camino", identity: "Camino" },
		{ string: navigator.userAgent, subString: "Netscape", identity: "Netscape" }, // ab NS 6
		{ string: navigator.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE" },
		{ string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv" },
		{ string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla"	} // NS bis 4
	],
	dataOS : [
		{ string: navigator.platform, subString: "Win", identity: "Windows" },
		{ string: navigator.platform, subString: "Mac", identity: "Mac" },
		{ string: navigator.platform, subString: "Linux", identity: "Linux"	}
	]
};
BrowserDetect.init();
return BrowserDetect;
}

function isBrowserSupported()
{
	var val = false;
	var browserD = getBrowserDetect();
	var version = browserD.version;

	if (Prototype.Browser.IE && version >= 6) {
		val = true;
	}
	else if (Prototype.Browser.Opera && version >= 9.2) {
		val = true;
	}
	else if (browserD.browser == 'Firefox' && version >= 1.5) {
		val = true;
	}
    else if (browserD.browser == 'Chrome') {
        val = true;
    }
	else if (browserD.browser == 'Safari' && version >= 3) {
		val = true;
	}
	else {
		val = false;
	}
	return val;
}

// Cookies+Browerkompatibiliät prüfen
function testBrowserCookie(divId,dispMessage)
{
	var browserSupported = isBrowserSupported();
	var cookieEnabled = navigator.cookieEnabled;

	if (!cookieEnabled || !browserSupported)
	{
		m  = '<ul><li>Bitte beachten Sie:</li>';
		m1 = '<li>Einige Funktionen von SPIEGEL Wissen könnten mit Ihrem Browser nur eingeschränkt nutzbar sein, ' +
             'da ihr Browser technisch veraltet ist. Auftretende Probleme können eventuell durch einen Wechsel ' +
             'auf eine neuere Browser-Version behoben werden.</li>';
		m2 = '<li>Cookies sind in Ihrem Browser deaktiviert.</li>';

		if (!browserSupported)
			m += m1

		if (!cookieEnabled)
			m += m2;
	
		m += '</ul>'

		if (dispMessage)
			$(divId).update(m);
	}
}

//----------------------------------------------------------
// FUNKTIONEN FÜR DIE MERKLISTE | START
//----------------------------------------------------------

// TODO einlagern: merkliste.js

//----------------------------------------------------------
// FUNKTIONEN FÜR DIE MERKLISTE | ENDE
//----------------------------------------------------------


// Tooltip anzeigen
function wiShowTooltip(divId,title,content)
{
	var bDiv = $(divId);
	var myHtml = '<p class="wiTTContent">' + content + '</p>'; 
	bDiv.update(myHtml);
	bDiv.show();
}

// Tooltip weg
function wiHideTooltip(divId)
{
	$(divId).hide();
}		

