/**
 *  Collection of Utility Classes and Functions.
 *  
 *  @author Boris Searles
 *  @author Alexander Farkas
 */

if(typeof g_windowWidth == 'undefined' || typeof g_windowHeight == 'undefined'){
	var g_windowWidth = ($.browser.msie && parseInt($.browser.version) <= 6) ? 1010 : 1014;
	var g_windowHeight = ($.browser.msie && parseInt($.browser.version) <= 6) ? 694 : 698;
}

/**
 *  CurrentAsset Object contains all relavant data for 
 *  the current asset. It is initialized in the AjaxControl::handleSuccess()
 *  method.
 */
function CurrentAsset() 
{
	this.requestUrl = null;
	this.url = null;
	this.flashXml = null;
	this.id = null;
	this.type = null;
	this.displayType = null;
	this.title = null;
	this.height = null;
	this.width = null;
	this.separatorUrl = null;
	this.separatorAltUrl = null;
	
	this.isSet = function() {
		return this.requestUrl ? true: false;
	};
	this.reset = function() {
		this.requestUrl = null;
		this.url = null;
		this.flashXml = null;
		this.id = null;
		this.type = null;
		this.displayType = null;
		this.title = null;
		this.height = null;
		this.width = null;
		this.separatorUrl = null;
		this.separatorAltUrl = null;
	};
	this.getClone = function() {
	    var clone = new CurrentAsset();
		clone.requestUrl = this.requestUrl;
		clone.url = this.url;
		clone.flashXml = this.flashXml;
		clone.id = this.id;
		clone.type = this.type;
		clone.displayType = this.displayType;
		clone.title = this.title;
		clone.height = this.height;
		clone.width = this.width;
		clone.separatorUrl = this.separatorUrl;
		clone.separatorAltUrl = this.separatorAltUrl;
		return clone;
	};
}


/**
 *  Method checks cookies containing user's video preferences,
 *  currently only video format and bandwidth.
 */
function readCookies() 
{   
    var pp = $.cookie('zdfmt_pp'); // video plugin (qtp, wmp)
    if( pp ) {
        g_mediaPlayer.plugin = pp;
    }

    var bw = $.cookie('zdfmt_bw'); // video bandwidth (isdn, dsl1000, dsl2000)
    if( bw ) {
        g_mediaPlayer.bandwidth = bw;
    }
}
 

/**
 *  Method sets video preference cookies (player plugin and bandwidth))
 *  @param {string} plugin either "wmp" or "qtp"
 *  @param {string} bandwidth either "isdn", "dsl1000", or "dsl2000"
 */
function setCookies(plugin, bandwidth)
{
    if(plugin !== null) {
        $.cookie('zdfmt_pp', plugin, {expires: 30});
    }
    if(bandwidth !== null) {
        $.cookie('zdfmt_bw', bandwidth, {expires: 30});
    }
}


/**
 *  @return {number} timestamp in milliseconds
 */
function getTimestamp() 
{
	var dateObj = new Date();
    return dateObj.getTime();  
}
function g_requestLoxPix(s){
	if(!s) return;
	var p = new Image();
	p.src = s;
};

/**
 *  Checks if specified plugin installed, iterates through plugin array searching
 *  for passed plugin name - if found it will abort and return full name of found plugin.
 *  @param {string} Name of plugin to check for
 *  @return {boolean/string} name of found plugin or false if not found
 */
function detectPlugin() {
    // allow for multiple checks in a single pass
    var daPlugins = arguments;
    // consider pluginFound to be false until proven true
    var pluginFound = false;
    // if plugins array is there and not fake
    if (navigator.plugins && navigator.plugins.length > 0) {
		var pluginsArrayLength = navigator.plugins.length;
		// for each plugin...
		for (pluginsArrayCounter=0; pluginsArrayCounter < pluginsArrayLength; pluginsArrayCounter++ ) {
		    // loop through all desired names and check each against the current plugin name
		    var numFound = 0;
			    for(namesCounter=0; namesCounter < daPlugins.length; namesCounter++) {
				// if desired plugin name is found in either plugin name or description
					if( (navigator.plugins[pluginsArrayCounter].name.indexOf(daPlugins[namesCounter]) >= 0) || 
					    (navigator.plugins[pluginsArrayCounter].description.indexOf(daPlugins[namesCounter]) >= 0) ) {
					    // this name was found
					    numFound++;
						var nameOfPlugin = navigator.plugins[pluginsArrayCounter].name;
					}   
			    }
		    // now that we have checked all the required names against this one plugin,
		    // if the number we found matches the total number provided then we were successful
		    if(numFound == daPlugins.length) {
				pluginFound = nameOfPlugin;
				// if we've found the plugin, we can stop looking through at the rest of the plugins
				break;
		    }
		}
    }
    return pluginFound;
}


/**
 *  VBScript used for plugin detection in IE (used for quicktime detection).
 */ 
if ($.browser.msie && (navigator.userAgent.indexOf('Win') != -1)) {
  
	document.writeln('<script language="VBscript">');

    document.writeln('\'do a one-time test for a version of VBScript that can handle this code');
    document.writeln('detectableWithVB = False');
    document.writeln('If ScriptEngineMajorVersion >= 2 then');
    document.writeln('  detectableWithVB = True');
    document.writeln('End If');

    document.writeln('\'this next function will detect most plugins');
    document.writeln('Function detectActiveXControl(activeXControlName)');
    document.writeln('  on error resume next');
    document.writeln('  detectActiveXControl = False');
    document.writeln('  If detectableWithVB Then');
    document.writeln('     detectActiveXControl = IsObject(CreateObject(activeXControlName))');
    document.writeln('  End If');
    document.writeln('End Function');

    document.writeln('\'and the following function handles QuickTime');
    document.writeln('Function detectQuickTimeActiveXControl()');
    document.writeln('  on error resume next');
    document.writeln('  detectQuickTimeActiveXControl = False');
    document.writeln('  If detectableWithVB Then');
    document.writeln('    detectQuickTimeActiveXControl = False');
    document.writeln('    hasQuickTimeChecker = false');
    document.writeln('    Set hasQuickTimeChecker = CreateObject("QuickTimeCheckObject.QuickTimeCheck.1")');
    document.writeln('    If IsObject(hasQuickTimeChecker) Then');
    document.writeln('      If hasQuickTimeChecker.IsQuickTimeAvailable(0) Then ');
    document.writeln('        detectQuickTimeActiveXControl = True');
    document.writeln('      End If');
    document.writeln('    End If');
    document.writeln('  End If');
    document.writeln('End Function');

    document.writeln('</scr' + 'ipt>');
}


(function($) {
	$.extend({
		zdfMovie: {
			hide: function(){
				var $vContainer = $("#video-container");
				var videoPlugin = $('#mediaplayer').attr('class');
				if(videoPlugin && g_mediaPlayer.isPluginAvailable(videoPlugin) && (g_mediaPlayer.isReady(true) || g_mediaPlayer.isReady()))
					g_mediaPlayer.stop(videoPlugin);
				if($vContainer.exists()){
					window.setTimeout(function(){
						if(g_Safari3){
							if(videoPlugin && g_mediaPlayer.isPluginAvailable(videoPlugin) && (g_mediaPlayer.isReady(true) || g_mediaPlayer.isReady()))
								g_mediaPlayer.stop(videoPlugin);
							$('#mediaplayer').remove();
						}
						$vContainer.get(0).innerHTML = '';
					},9);
                }
			}
		}
	
	});
	$.fn.extend({
		keycombi:function(combi,trig,fu){
			var pressed = [];
			$.each(combi,function(i){
				pressed[i] = false;
			});
			function handleKeycombi(e){
                $.each(combi,function(i){
                    if(e.keyCode == this)
						pressed[i] = (e.type == 'keydown')? true:false;
				});
				function combiPressed(){
					var returnwert = false;
					$.each(pressed,function(i){
						if(this == true)
							returnwert = true;
						else{
							returnwert = false;
							return false;
						}
					});
					return returnwert;
				}
				if(combiPressed() && e.keyCode == trig && e.type == 'keydown')
					$(this).trigger('keycombi');
			}
			return this.each(function(){
				$(this).bind('keycombi',fu).bind('keydown',handleKeycombi).bind('keyup',handleKeycombi);
			});
		},	

		/**
		 *  löscht den vorgegebenen Inhalt eines Eingabefeld bei focus und fügt ihn bei blur wieder ein, wenn das Feld leer gelassen wurde
		 *  Beispiel $('input').clearFillInput('Suchbegriff');
		 */
		clearFillInput: function(content) {
			return this.each(function(){
			    $(this).focus(function(){
					if($(this).val() == content)
						$(this).val('');
				}).blur(function(){
					var test = $(this).val();
					if(test == content || test == '')
						$(this).val(content);
				});
			});
		},
		doAnimate: function(prop, speed, easing, callback) {
			return this.each(function(){
			    if(!g_adavancedMode){
					$(this).animate(prop, speed, easing, callback);
				}else{
					$(this).css(prop);
					(typeof speed == 'function') ? speed.apply(this):(typeof easing == 'function')?easing.apply(this):(typeof callback == 'function')?callback.apply(this): '';
				}
			});
		},
		disableRadio: function(noAnimate) {
			noAnimate = noAnimate || false;
			return this.each(function(){
			    if(!g_adavancedMode){
					if ($.browser.msie && parseInt($.browser.version) < 7) 
						$(this).parent('label').css('display', 'none');
					else if (!noAnimate) {
						$(this).parent('label').fadeTo('fast', 0.25).addClass('fast');
					} else {
						
						$(this).parent('label').css({opacity: 0.25}).addClass('fast');
					}
				}
			});
		},
		enableRadio: function() {
			return this.each(function(){
			    if(!g_adavancedMode){
					if($.browser.msie && parseInt($.browser.version) < 7)
							$(this).parent('label').css('display','block');
						else
							$(this).parent('label').fadeTo('fast',0.99);
				}
			});
		},
		exists: function() {
			return ($(this).size()>0)?true:false;
		},
		copySelect: function() {
			return this.each(function(){
			   $(this).click(function(){
					$(this).get(0).select();
					/*try {
						$(this).get(0).createTextRange().execCommand("Copy");
					} catch(e) {
						return false;
					}*/
				});
			});
		},
		hideUncheck: function() {
			return this.each(function(){
			   if(!$(this).find('input:first').is('[@checked]'))
			   	$(this).hide();
			});
		}
	});
})(jQuery);


function scrollIT(selector)
{
	this.elem = $(selector);
	this.Inhalt = this.elem.html();
	var self = this;
	var direction = 'down';
	var timer;
	var looTimer = false;
	var alteVerschiebung = 0;
	this.startTimer = function(e,delta){
		timer = window.setTimeout(self.scroll,80);
	};
	this.closeTimer = function(){
		window.clearTimeout(timer);
		looTimer = false;
	};
	this.needToScroll = function(override){
		this.height = this.height || this.elem.height();
		this.innerHeight = this.innerHeight || this.elem.find('div.scrollInner').height();
		if(override || self.innerHeight > self.height){
			this.elem.find('span.upArrow,span.downArrow').css({opacity:'0.999',cursor:'pointer'});
			return true;
		}else{
			this.elem.find('span.upArrow,span.downArrow').css({opacity:'0.2',cursor:'default'});
			return false;
		}	
	};
	this.scroll = function(unit){
		self.top = parseInt(self.innerElm.css('top'));
		if(self.needToScroll()){
			unit = unit || 1;
	
			var verschiebung = self.top;
			var maxVerschiebung = self.height - self.innerHeight;
			
			if(direction == 'down'){
				verschiebung -= unit;
				
				if(verschiebung <= maxVerschiebung || verschiebung >= 0){
					verschiebung = maxVerschiebung;
					self.closeTimer();
				}
			}else if(direction == 'up'){
				verschiebung += unit;
				if(verschiebung >= 0 || verschiebung <= maxVerschiebung){
					verschiebung = 0;
					self.closeTimer();
				}
			}
			if((direction == 'up' && alteVerschiebung < verschiebung) || (direction == 'down' && alteVerschiebung > verschiebung))
				self.innerElm.css('top', verschiebung+'px');
			
			alteVerschiebung = verschiebung;
			if(looTimer)
				self.startTimer();
		}
	};
	this.getDirection = function(e,delta){

		if($(this).is('.upArrow') || (delta && delta > 0))
			direction = 'up';
		else if($(this).is('.downArrow') || (delta && delta < 0))
			direction = 'down';
		
		looTimer = (e && e.type == 'mousedown') ? true : false;	
		
		if(e && e.type == 'mouseup')
			self.closeTimer();
		else
			self.scroll(10);
			
	};
	
	this.elem.html(
		'<div class="scrollInner">'+this.Inhalt+'</div> <span title="nach oben" class="upArrow"></span> <span title="nach unten" class="downArrow"></span>'
		).css(
		{overflow:'hidden',position:'relative'}
		).find('span.upArrow,span.downArrow').mousedown(self.getDirection).mouseup(self.getDirection);
		
	this.elem.mousewheel(self.getDirection);
	this.innerElm = this.elem.find('div.scrollInner');
	this.top = this.innerElm.css('top');
	this.needToScroll();
}



/**
 *  Interval-Manager
 */
function IntervalManager(sec)
{
	this.functions = [];
	this.millisec = sec || 900;
	this.timeInterval = false;
	selfo = this;
	this.wrapperFu = function()
	{
		for (var idString in selfo.functions){
			selfo.functions[idString].call(arguments);		
		}
	};
	this.start = function()
	{
		selfo.timeInterval = window.setInterval(selfo.wrapperFu,selfo.millisec);
	};
}

IntervalManager.prototype.stop = function()
{
	 window.clearInterval(this.timeInterval);
	 this.timeInterval = false;
};
IntervalManager.prototype.isIn = function(id)
{
	var returnwert = false;
	if(typeof this.functions[id] != 'undefined' && this.functions[id]){
		returnwert = true;
		return true;
	}
	return returnwert;
};
IntervalManager.prototype.hasFus = function()
{
	var returnwert = 0;
	for (var idString in this.functions) {
		returnwert++;
	}
	return returnwert;
};
IntervalManager.prototype.bind = function(fu,id)
{
	if(typeof fu == 'function'){
		if(!this.hasFus()){
			this.functions[id] = fu;
			this.start();
		}else if(!this.isIn(id)){
			this.functions[id] = fu;
		}
	}
};
IntervalManager.prototype.unbind = function(id)
{
	delete this.functions[id];
	if(!(this.hasFus())){
		this.stop();
	}
};

/**
 *  This function parses comma-separated name=value argument pairs from
 *  the query string of the URL. It stores the name=value pairs in 
 *  properties of an object and returns that object.
 */
function getArgs() {
    var args = {};
    var query = location.search.substring(1);  // Get query string.
    var pairs = query.split("&");              // Break at comma.
    for(var i = 0; i < pairs.length; i++) {
	var pos = pairs[i].indexOf('=');       // Look for "name=value".
	if (pos == -1) continue;               // If not found, skip.
	var argname = pairs[i].substring(0,pos);  // Extract the name.
	var value = pairs[i].substring(pos+1); // Extract the value.
	args[argname] = unescape(value);          // Store as a property.
    }
    return args;                               // Return the object.
}


/**
 *  Tests bandwith...
 */
function dslTest()
{
	var self = this;
	var dsl = false;
	var tmp = new Date();
	var timeStart = tmp.getTime();

	if(typeof(g_testgifurl) == "undefined"){
		return;
	}
	var pictureurl = g_testgifurl+'?'+timeStart;
	var testpic = new Image();
	testpic.src = pictureurl;
	
	this.pictureloaded = function(){
		timeEnd = tmp.getTime();
		timeDuration = timeEnd - timeStart;
		var txt = ' <strong>(empfohlen)</strong>';
		var labelElm;
		if(timeDuration < 1){
			$("#dsl2000").parent('label').append(txt);
		}else if(timeDuration < 2){
			$("#dsl1000").parent('label').append(txt);
		}else {
			$("#isdn").parent('label').append(txt);
		}
		//labelElm.get(0).innerHTML = labelElm.html()+txt;	
	};
	testpic.onload = this.pictureloaded;
}

/**
 *  Methods for opening windows, one for popups and one for full windows.
 *  @param {String} url
 */
if(typeof openwindow == 'undefined') {
	function openwindow(url) {	
		g_windowHeight = $.browser.safari ? 704 : g_windowHeight;
		var yPos = (screen.availHeight-g_windowHeight) / 2;
		var xPos  = (screen.availWidth-g_windowWidth) / 2;
		g_ZDFmediathekWindow = window.open(url, "ZDFmediathek" + getTimestamp(), "width="+g_windowWidth+",height="+g_windowHeight+",left="+xPos+",top="+yPos+",location=no,menubar=no,resizable=yes,toolbar=no");
		if(g_ZDFmediathekWindow)
			g_ZDFmediathekWindow.focus();
	}
}
if(typeof openFullWindow == 'undefined') {
	function openFullWindow(url) {		
		var win = window.open(url, "ZDFmediathek2", "left=0,top=0,location=yes,menubar=yes,resizable=yes,toolbar=yes,scrollbars=yes");
		if(win)
			win.focus();
		
	}
}


var g_window = {
	resizeTo: function(width,height){
		if(g_Safari3) {
			height +=20;
			window.resizeTo(width,height);
		} else if (self.innerHeight) // all except Explorer
		{
			self.innerWidth = width;
			self.innerHeight = height;
			if(self.innerWidth != width){
				self.innerWidth = width;
				self.innerHeight = height;
			}
		}
		else
		{
		    if(navigator.userAgent.indexOf('NT 6.0') != -1) {
            	width += 10;
            	height += 62;
            }
            window.resizeTo(width,height);
		}
	},
	getInner: function(){
		var x,y;
		if (self.innerHeight) // all except Explorer
		{
			x = self.innerWidth;
			y = self.innerHeight;
		}
		else if (document.documentElement && document.documentElement.clientHeight)
			// Explorer 6 Strict Mode
		{
			x = document.documentElement.clientWidth;
			y = document.documentElement.clientHeight;
		}
		else if (document.body) // other Explorers
		{
			x = document.body.clientWidth;
			y = document.body.clientHeight;
		}
		return [x,y];
	}
};

function g_getStream(){
	if (typeof g_availableStream == 'undefined') {
		var scriptContainer = $('script', document.getElementById('ctrl-tab-settings'));
		if (!scriptContainer.exists()) {
			return false;
		}
		$.globalEval(scriptContainer);
		if (typeof g_availableStream == 'undefined') {
			return false;
		}
	}
	var streamtype, streambw, searchWin = /Win/,searchLinux = /Linux/, searchMac = /Mac/;
	var bwArray = ['dsl1000','isdn','dsl2000'];
	if(!g_availableStream.vlc) {
		g_availableStream.vlc = {};
	}
	g_availableStream.vlc = $.extend(g_availableStream.wmp,g_availableStream.vlc);
	var pluginArray = ['wmp','qtp','real'];
	if(g_mediaPlayer.plugin)
		streamtype = g_mediaPlayer.plugin;
	else{
		var platform = navigator.platform;
		if(searchWin.test(platform) && g_mediaPlayer.isPluginAvailable('wmp')){
			streamtype = 'wmp';
		}else if(searchLinux.test(platform) && g_mediaPlayer.isPluginAvailable('vlc')){
			streamtype = 'vlc';
		}else if(searchMac.test(platform) && g_mediaPlayer.isPluginAvailable('qtp')){
			streamtype = 'qtp';
		} else if(g_mediaPlayer.isPluginAvailable('wmp'))
			streamtype = 'wmp';
		else if(g_mediaPlayer.isPluginAvailable('qtp'))
			streamtype = 'qtp';
		else if(g_mediaPlayer.isPluginAvailable('real'))
			streamtype = 'real';
		else if(g_mediaPlayer.isPluginAvailable('vlc'))
			streamtype = 'vlc';
		else if(searchWin.test(platform))
			streamtype = 'wmp';
		else
			streamtype = 'qtp';
	}
	if(g_mediaPlayer.bandwidth)
		streambw = g_mediaPlayer.bandwidth;
	else
		streambw = 'dsl1000';
	g_mediaPlayer.plugin = streamtype;
	
	if(!g_availableStream[streamtype][streambw] || (streamtype == 'vlc' && !g_availableStream['wmp'][streambw])){
		var breakFor = false;
		if(g_availableStream[streamtype].dsl1000){
			streambw = 'dsl1000';
		} else if(g_availableStream[streamtype].isdn){
			streambw = 'isdn';
		} else if(g_availableStream[streamtype].dsl2000){
			streambw = 'dsl2000';
		} else {
			for(var i = 0; i < bwArray.length; ++i){
				for(var j = 0; j < pluginArray.length; ++j){
					if(g_availableStream[pluginArray[j]][bwArray[i]]){
						streambw = bwArray[i];
						streamtype = pluginArray[j];
						breakFor = true;
						break;
					}
				}
				if(breakFor)
					break;
			}
		}
	}
	g_mediaPlayer.plugin = streamtype;
	g_mediaPlayer.bandwidth = streambw;
	setCookies(g_mediaPlayer.plugin, g_mediaPlayer.bandwidth);
	return [streamtype,streambw];
}
