﻿// fixed/scroll Navigation
function switchPositioning() {
    var h = document.viewport.getHeight();
    var t = $('pageTop');
    if (t != null) {
        if (h < MIN_HEIGHT_FIXED_NAV) {
            t.removeClassName('fixed');
        }
        else {
            t.addClassName('fixed');
        }
    }
}

// scrolling
var Weiterlesen = Class.create({

	initialize: function()
	{
		// all size values in pixels
		this.MaximalTopOffsetActive = 120; // maximally tolerated top offset of active element in list
		this.MinimalUpperMargin = 0; // when header not fixed
		this.MinimalHeightFixedHeader = MIN_HEIGHT_FIXED_NAV; // minimal viewport height for fixed header
		this.UpperSujetHeight = 0; // upper sujet height, set by MAS
		this.LowerSujetHeight = 0; // lower sujet height including margin, set by MAS

		this.pageTop = $('pageTop');
		this.weiterLesen = $('weiterLesen');
		this.weiterLesenScroll = $('weiterLesenScroll');

		if (PageProperties.isEnhanced == true) {
			this.reposition();
			this.showWeiterlesenActive();
			this.weiterLesen.style.bottom = '43px';
		}
		else if ($('objectContent').hasClassName('fullwidth'))
		{
			this.weiterLesen.style.top = (parseInt(this.weiterLesen.style.top) + $('objectContent').getHeight()) + 'px';
		}
	},

	reposition: function()
	{
		// minimal and maximal upper margin
		var min = this.MinimalUpperMargin;
		var max = this.pageTop.getHeight();

		if (this.MinimalHeightFixedHeader <= document.viewport.getHeight())
		{
			min = max;
		}
		max += this.UpperSujetHeight;
		if ($('objectContent').hasClassName('fullwidth'))
		{
			max += $('objectContent').getHeight();
		}
		// calculated margin
		var calc = max - document.viewport.getScrollOffsets().top;

		if (calc < min)
		{
			calc = min;
		}
		calc += 8;
		if (PageProperties.isAdRessort) calc += 20;

		// adjust positions via styles
		this.weiterLesen.setStyle({ top: calc + 'px' });
		this.weiterLesenScroll.setStyle({ bottom: this.LowerSujetHeight + 'px' });
	},

	setUpperSujetHeight: function(ush)
	{
		this.UpperSujetHeight = ush;
		this.reposition();
	},

	setLowerSujetHeight: function(lsh)
	{
		this.LowerSujetHeight = lsh;
		this.reposition();
	},

	showWeiterlesenActive: function()
	{
		// guarantee visibility of active element in list, if exists
		var actObj = this.weiterLesenScroll.down('ul li.active');
		if (actObj)
		{
			var actTop = actObj.positionedOffset().top;
			if (actTop > this.MaximalTopOffsetActive) {
				// scroll down
				this.weiterLesenScroll.scrollTop = actTop - this.MaximalTopOffsetActive;
			}
			else if (actTop < this.weiterLesenScroll.scrollTop)
			{
				// scroll up
				this.weiterLesenScroll.scrollTop = actTop;
			}
		}
	}
});

// Navigation
var Navigation = Class.create({
	initialize: function(elt)
	{
		this.element = $(elt);
		this.delayID = 0;
		this.resetID = 0;

		this.items = {};
		this.activeItems = new Array();

		var homeLink = this.element.down('a');
		homeLink.observe('mouseover', this.onMouseOver.bind(this));
		homeLink.observe('mouseout', this.onMouseOut.bind(this));

		this.element.select('div > ul > li').each(function(channel)
		{
			new NavChannel(channel, this);
		} .bind(this));
		this.activeInit = this.activeItems;
	},

	onMouseOver: function() { this.mouseOver(this, this.showAll.bind(this)); },
	onMouseOut: function() { this.mouseOut(this) },

	showAll: function()
	{
		this.element.select('li').each(function(e) { e.removeClassName('active'); });
	},

	activate: function(pathArray)
	{
		var activeNew = new Array();
		$A(pathArray).each(function(pathEntry)
		{
			try
			{
				var entryName = pathEntry.n.toLowerCase();
				var menuItem = this.items['nav_' + entryName];
				if (menuItem) activeNew.push(menuItem);
			} catch (e) { }
		} .bind(this));
		if (activeNew.size() == 0)
		{
			activeNew = this.activeInit;
		}
		this.activeItems = activeNew;
		this.reset();
	},

	reset: function()
	{
		this.showAll();
		var line1 = $('navLine1');
		var line2 = $('navLine2');
		if (!line1.hasClassName('active')) line1.addClassName('active');
		if (line2.hasClassName('active')) line2.removeClassName('active');
		this.activeItems.each(function(item)
		{
			item.activate();
		});
	},

	mouseOver: function(menuItem, action)
	{
		window.clearTimeout(this.resetID);
		window.clearTimeout(this.delayID);
		if (action) this.delayID = action.delay(0.333);
	},

	mouseOut: function(menuItem)
	{
		window.clearTimeout(this.delayID);
		this.resetID = this.reset.bind(this).delay(1);
	}
});

var NavChannel = Class.create({
    initialize: function(elt, nav)
    {
        this.element = $(elt);
        this.nav = nav;
        this.id = this.element.id.toLowerCase();
        nav.items[this.id] = this;
        if (this.isActive()) nav.activeItems.push(this);

        var channelLink = this.element.down('a');
        if (channelLink) {
            channelLink.observe('mouseover', this.onMouseOver.bind(this));
            channelLink.observe('mouseout', this.onMouseOut.bind(this));
        }

        var ressortUL = this.element.down('ul');
        if (ressortUL) ressortUL.childElements().each(function(ressort) {
            new NavRessort(ressort, nav);
        });
    },

    activate: function()
    {
        var line = this.element.up('div');
        line.siblings().each(function(e) { e.removeClassName('active'); });
        line.addClassName('active');
        this.highlight();
        this.element.select('li').each(function(e) { e.removeClassName('active'); });
    },

    highlight: function()
    {
        this.element.siblings().each(function(e) { e.removeClassName('active'); });
        this.element.addClassName('active');
    },

    isActive: function()
    {
        return this.element.hasClassName('active');
    },

    isLineActive: function()
    {
        return this.element.up('div').hasClassName('active');
    },

    onMouseOver: function()
    {
        this.nav.mouseOver(this, (this.isLineActive()) ? this.highlight.bind(this) : null);
    },

    onMouseOut: function()
    {
        this.nav.mouseOut(this);
    }
});

var NavRessort = Class.create({
    initialize: function(elt, nav)
    {
        this.element = $(elt);
        if (this.element.hasClassName('nav_empty')) return;
        this.nav = nav;
        this.id = this.element.id.toLowerCase();
        nav.items[this.id] = this;
        if (this.isActive()) nav.activeItems.push(this);

        this.element.down('a').observe('mouseover', this.onMouseOver.bind(this));
        this.element.down('a').observe('mouseout', this.onMouseOut.bind(this));
    },

    activate: function()
    {
        this.element.siblings().each(function(e) { e.removeClassName('active'); });
        this.element.addClassName('active');
    },

    isActive: function()
    {
        return this.element.hasClassName('active');
    },

    onMouseOver: function()
    {
        this.nav.mouseOver(this);
    },

    onMouseOut: function()
    {
        this.nav.mouseOut(this);
    }
});

// Toolbar Setup
function setupToolbar()
{
	var dv = PageProperties.version.detected;
	if (dv == 'text' || dv == 'mobil')
	{
		$('TBMobileButton').setAttribute('href',
			'http://' + dv + '.' + PageProperties.Host + '/permanent');
	}
	if (top == self && is_ipad)
	{
		var nodes = $('toolbarMenu').select('li.entry a.button');
		nodes.each(
			function(node)
			{
				node.addEventListener('click',
					function(event)
					{
						var nodes = $('toolbarMenu').select('li.entry');
						var node = event.target.up('li.entry');
						var hovered = node.hasClassName('hover');
						nodes.invoke('removeClassName', 'hover');
						if (!hovered) node.addClassName('hover');
						event.stop();
					},
					true
				);
			}
		);
	}
}

// Pfad zum aktuellen Kontext
var BreadCrumbs = Class.create({
    initialize: function(element, maxWidth) {
        this.element = element;
        this.maxWidth = maxWidth;
    },
    adjust: function() {
        var crumbs = this.element.select('.breadCrumb').slice(0, -2);
        while (this.element.getWidth() > this.maxWidth && crumbs.length > 0) {
            crumbs.pop().hide();
        }
    }
});

function readCookie(name)
{
	var nameEQ = name + '=';
	var ca = document.cookie.split(';');
	for (var i = 0, l = ca.length; i < l; i++)
	{
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
}

function getUserPreferences()
{
	if (!PageProperties) return;
	
	var detected  = null;
	var preferred = null;
	
	if (document.cookie)
	{
		var pairs = readCookie('MGUID').split('&');
		for (var i = 0, l = pairs.length; i < l; i++)
		{
			var p = pairs[i].split('=');
			var n = p[0];
			var v = p[1];
			if (n == 'DetectedVersion') detected = v.toLowerCase();
			if (n == 'Version') preferred = v.toLowerCase();
		}
	}
	PageProperties.version = {
		'detected': detected,
		'preferred': preferred
	};
}
getUserPreferences();

// gathering the username and communityname by forcing the backend to get it from the database not from the cookie.
function refreshUserInfo()
{
	if (!$('toolbarProfile')) return;
	getUserInfo(['refreshUserInfo=1']);
}

// gathering the weather-data by forcing the backend to get it from the database not from the cookie.
function refreshWeatherInfo()
{
	if (!$('toolbarProfile')) return;
	getUserInfo(['refreshWeatherInfo=1']);
}

// gathering the username and communityname.
function updateUserInfo()
{
	if (!$('toolbarProfile')) return;
	getUserInfo();
}

// requesting the userinformation from the backend; from cookie or from database.
function getUserInfo()
{
	var params = arguments[0] || [];
	if ($('TBLogin'))
	{
		$('TBUser').hide();
		new Ajax.Request('/ajax/bottomnavinfo.ashx',
			{ method: 'get'
			, parameters: params.join('&')
			, onComplete: writeUserInfo
		});
	}
}

// writes the username and communityname in the toolbar if the user is logged in.
function writeUserInfo(transport)
{
	var data = transport.responseJSON;
	if (data && (data.FirstName || data.LastName)) {
		$('TBFirstName').innerHTML = data.FirstName;
		$('TBLastName').innerHTML = data.LastName;
		$('toolbarProfile').removeClassName('anonymous');
	}
	$('TBUser').show();
	
	if (data && data.WeatherImgName) {
		var wetter = $('wetterWidget');
		if (wetter) {
		    wetter.down('.bild').update('<img src="/img/cont/wetter/fcicons/' + data.WeatherImgName + '-small.gif" alt="' + data.WeatherImgDesc + '" title="' + data.WeatherImgDesc + '">');
			wetter.down('.stadt').update(data.WeatherCity);
			wetter.down('.temp').update(data.WeatherTemp + '°');
			wetter.show();
			if (wetter.cumulativeOffset().left < (breadCrumbs.element.getWidth() + breadCrumbs.element.cumulativeOffset().left + 17))
				wetter.hide();
		}
	}
}

Event.observe(document, 'dom:loaded', updateUserInfo);

function logout()
{
	if (confirm("Wollen Sie sich abmelden?"))
	{
		var url = "/ajax/bottomnavinfo.ashx?type=logout";
		var cb = new Ajax.Request(url, { method: 'get',
			onComplete: function(transport)
			{
				var status = transport.responseJSON;
				if (status && status.Status && status.Status == "ok")
				{
					//User hat sich erfolgreich ausgeloggt
					$('toolbarProfile').addClassName('anonymous');
				}
			}
		});
	}
}


// Spezial-Funktionen
function hasGuidCookie() 
{
    return document.cookie.indexOf('UGUID') != -1;
}

function validateSearch(element)
{
	var v = element.value.strip();
	if (v[0] == '*')
	{
		v = v.substring(1);
		element.value = v;
	}
	if (v.length <= 2) 
	{
		alert('Bitte geben Sie einen Suchbegriff mit einer Länge von mindestens 3 Zeichen an.');
		return false;
	}
	return true;
}

// FlashWrite (ist auch in MAS.js definiert!)
/*
Schreibt Flash-Object- und Embed-Tags so, dass trotz MS-ActiveX-Lizenz nur ein Klick nötig ist

oParentElement    DOM-Objekt, in das die Flash-Einbettung geschrieben wird
iWidth            Breite
iHeight           Höhe
sBanner           URL der Flash-Animation
sFlash            Flash-Parameter (Liste von Name-Wert-Paaren)
sClickTag         Name des Flash-Parameters zur Übergabe der Ziel-URL
sURLclick         Ziel-URL
sCounterURL       Optionale URL des Zählpixels; kann den symbolischen Wert %%RAND%% enthalten, der dann durch einen Zeitstempel ersetzt wird
*/
function FlashWrite(oParentElement, iWidth, iHeight, sBanner, sFlash, sClickTag, sURLclick, sCounterURL) {
    var i;
    var sClickAppend = '';
    if (sClickTag && sURLclick) { if (sBanner.indexOf('?') > -1) { sClickAppend = '&' } else { sClickAppend = '?' } sClickAppend += sClickTag + '=' + escape(sURLclick); }
    var sRet = '<object id="flashbanner" name="flashbanner" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="' + iWidth + '" height="' + iHeight + '" VIEWASTEXT style="z-index: 1">';
    sRet += '<param name="movie" value="' + sBanner + sClickAppend + '">';
    for (i = 0; i < sFlash.length; i++) { sRet += '<param name="' + sFlash[i][0] + '" value="' + sFlash[i][1] + '">'; }
    sRet += '<embed type="application/x-shockwave-flash" src="' + sBanner + sClickAppend + '" ';
    for (i = 0; i < sFlash.length; i++) { sRet += sFlash[i][0] + '="' + sFlash[i][1] + '" '; }
    sRet += 'width="' + iWidth + '" height="' + iHeight + '" /><\/object>';
    if (sCounterURL) { if (sCounterURL.indexOf('%%RAND%%') > -1) { sCounterURL = sCounterURL.replace(/%%RAND%%/, (new Date()).getTime()) } sRet += '<img style="position: relative; top: -1px" src="' + sCounterURL + '" />' }
    oParentElement.innerHTML = sRet;
}

// picture popup link: intermediate steps towards applications
// (C) Robert Knienider, 2009
var PicturePopup = Class.create({

	// recount in caller and show popup
	open: function(type, imageObject)
	{
		this.count(type, '/Picturepopup');
		return this.show(imageObject);
	},

	// recount in calling page with changed type
	count: function(sType, sType2)
	{
		// scripted counters exist?
		var oIVW = $('ivw');
		if (oIVW && window.timestamp)
		{
			// recount all
			var timestamp2 = (new Date()).getTime();
			var iCP = oIVW.getElementsBySelector('img').length;
			var oCP;
			for (var i = 0; i < iCP; i++)
			{
				oCP = oIVW.down('img', i);
				oCP.src = oCP.src.replace(timestamp, timestamp2).replace(sType, sType2);
			}
		}
	},

	// show popup
	show: function(object)
	{
		// "o" defines default object
		var o = { 'path': '', 'name': 'zoom', 'width': 100, 'height': 100, 'title': '', 'credits': '' };
		Object.extend(o, object);
		var sTitle = o.title.stripTags().substr(0, 100);
		if (sTitle == '')
		{
			sTitle = 'derStandard.at';
		}
		var params = 'width=' + o.width + ',height=' + o.height + ',innerwidth=' + o.width + ',innerheight=' + o.height + ',resizable=yes,scrollbars=no,top=0,left=0';
		var zoom = window.open('', 'zoom_' + o.name, params);
		with (zoom.document)
		{
			open();
			write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">');
			write('<html><head><title>' + sTitle + '</title></head>');
			write('<body style="margin:0;padding:0;background:#000000;text-align:center;">');
			write('<img style="margin:0 auto;width:100%;" src="' + o.path + '" title="' + o.credits + '" alt="">');
			write('</body></html>');
			close();
		}
		if (window.focus) zoom.focus();
		return false;
	}

});

function launchTV(location)
{
	tvKiosk = window.open(location, 'derStandardTV', 'width=980,height=700,resizable=yes,top=0,left=0');
	tvKiosk.focus();
}
function launchRadio(location)
{
	radioKiosk = window.open(location, 'CtrlWindow', 'toolbar=no,menubar=no,location=no,scrollbars=no,resizable=no,width=577,height=151');
	radioKiosk.focus();
} 

// opens a popup-window
function popupwin(page, width, height, noscroll)
{
	popup = window.open(page, 'popupwin', 'toolbar=no,menubar=no,scrollbars=' + (noscroll ? 'no' : 'yes') + ',resizable=yes,' + 'width=' + width + ',height=' + height + ',left=100,top=160');
	if (popup != null) {
		popup.focus();
	}
}

// decode an encoded emailadress and make a mailto: link
function MailTo(Name, EncodedMail)
{
	var decoded = "";
	if (EncodedMail != '') {
		for (var i = 0; i < EncodedMail.length; i += 2) {
			if (i + 1 == EncodedMail.length) {
				decoded += EncodedMail.charAt(i);
			} else {
				decoded += EncodedMail.charAt(i + 1) + EncodedMail.charAt(i);
			}
		}
		decoded = '@' + decoded.replace(/\?/g, '.');
	}
	location.href = "mailto:" + Name + decoded;
}

// Shift key is pressed or not
var modifierKey = false;

//Scrollhandler for SPACE KEY_UP and KEY_DOWN events
function scrollOnePage(e)
{
	var keyCode = e.keyCode; // key pressed
	
	if (keyCode == 16)
	{
		modifierKey = true;
	}
	
	var focusOn = Event.element(e).tagName; // the name of the element in focus, when the event was triggered
	var bFixedView = $('pageTop').hasClassName('fixed'); // true if the page is shown with fixed pageTop (navigation) and toolbar (bottomnav)

	// only act if no inputfield is in focus and the page is viewed in enhanced mode with fixed pageTop and toolbar
	if (focusOn != 'INPUT' && focusOn != 'TEXTAREA' && focusOn != 'OBJECT' && focusOn != 'EMBED' && PageProperties.isEnhanced && bFixedView)
	{
		if (Prototype.Browser.Opera) return; // do nothing for Opera
		
		// Only set variables if needed for scrolling
		if (keyCode == 32 || keyCode == Event.KEY_PAGEDOWN || keyCode == Event.KEY_PAGEUP)
		{
			var intTopOffset = $('pageTop').getHeight();									// height of the fixed top element
			var intBottomOffset = $('toolbar').getHeight();									// height of the fixed bottom element
			var intViewPortHeight = document.viewport.getHeight();							// current height of the viewport
			var intScrollOffset = document.viewport.getScrollOffsets().top;					// current scroll position of the document
			var intScrollRange = intViewPortHeight - (intTopOffset + intBottomOffset) - 30;	// number of pixels to scroll the page
			e.stop(); // stop Event
		}

		if ((keyCode == 32 && !modifierKey) || keyCode == Event.KEY_PAGEDOWN) // scroll down when SPACE or PAGEDOWN was pressed
		{
			window.scrollTo(0,intScrollOffset + intScrollRange);
		}
		else if ((keyCode == 32 && modifierKey) || keyCode == Event.KEY_PAGEUP) // scroll up when PAGEUP was pressed
		{
			window.scrollTo(0, intScrollOffset - intScrollRange);
		}
	}
}

// reset modifierKey (shift key) Flag
function resetModifierKey(e)
{
	if (e.keyCode == 16)
	{
		modifierKey = false;
	}
}

//method is used in embedhtml objects to display stellenmarkt announcements
function insertStellenmarktAdIntoPage(feedNumber) 
{
	//get content from url
	var stellenMarktAdDiv = $('StellenmarktAd');

	if (!stellenMarktAdDiv)
		//if no div with id="StellenmarktAd" is here, replace with content can not be done
		return;

	new Ajax.Request('/anzeiger/derjob/skys/cbox/frameless.aspx',
			{ method: 'get'
			, parameters: { feed: feedNumber, 'var': 2 }
			, onFailure: function() {
				//remove div that should be replaced by the ad
				stellenMarktAdDiv.remove();
			}
			, onSuccess: function(response) {
				//replace div with ad
				stellenMarktAdDiv.replace(response.responseText);
			}
			});
}

//get stock exchange chart html snippets via ajax request and write them into the given element
function writeStockExchangeCharts(oElement, sRequestUrl, arrInstrumentIds, sSeriesColor, sGradientColor)
{
	var chartRequest = new Ajax.Updater(oElement, sRequestUrl, {
		method: 'POST',
		contentType: 'application/json',
		postBody: Object.toJSON({ 'InstrumentIds': arrInstrumentIds, 'seriesColor': sSeriesColor, 'gradient': sGradientColor })
	});
}