/*
	@desc This file contains a number of functions that provide different services. Its a collection of unrelated funcions*
	
	$Log: functions.js,v $
	Revision 1.43  2010/10/07 11:00:07  cvsosir
	small fix
	
	Revision 1.42  2010/08/31 09:00:41  cvsosir
	*** empty log message ***
	
	Revision 1.41  2010/08/31 08:53:20  cvsosir
	*** empty log message ***
	
	Revision 1.40  2010/08/31 08:37:48  cvsosir
	*** empty log message ***
	
	Revision 1.39  2010/04/08 05:59:53  cvsosir
	fixed eTracker disclaimer feature
	
	Revision 1.38  2010/03/17 09:28:30  cvsosir
	http -> https kontaktformular
	
	Revision 1.37  2010/02/23 12:20:20  cvsosir
	*** empty log message ***
	
	Revision 1.36  2010/02/08 14:43:13  cvsosir
	*** empty log message ***
	
	Revision 1.35  2010/02/04 16:09:22  cvsosir
	broker-box
	
	Revision 1.34  2009/11/23 07:36:38  cvsosir
	new method
	
*/


/** This function cares for displaying a background image when the user moves the mouse over a main menue tab 
@param item The HTML element */
function showMenueTabBg(item)
{
	$(item.parentNode).addClassName('mouseOver');
}
function hideMenueTabBg(item)
{
	$(item.parentNode).removeClassName('mouseOver');
}
/* ========================================================== */
/** This function is called right on startup of the website. It can be used to initialize JS stuff. All
initialization functions should be called from here **/ 
function onStartupWebsite()
{


}
/** This function is called at the end of loading the website. All content should be loadad at this time... **/
function afterStartupWebsite()
{
	//intializing tab naviagtions
	new Control.Tabs('tabs');
	new Control.Tabs('servicetabs');
}
/* ========================================================== */

/** This function makes an AJAX call to search for instruments. It uses the field of form "frmSuche" as input **/ 
function searchInstruments()
{
	var searchString=document.frmSuche.kursSuche.value;
	
	if(searchString!= '')
	{
		var url='!ProcessPage';
		var params='CallType=Search&SearchString='+encodeURIComponent(searchString)+'&PageName=PageSearch';
		var contentId='content';
		
		var historyParams= url + '$' + params + '$' + contentId;
		historyAdd('Search',historyParams,contentId);

		var ajaxHelper = new AjaxHelper();	
		ajaxHelper.publicSend(url,params,contentId);
	}
}

/* ========================================================== */

/** This function cares for requesting the underlying selection
@param pageName
@param caller cats/init or props. Dependent on the checkbox that initiates the call
**/
function GetUnderlyingSelection( pageName, caller )
{
	if( !dontUpdateInReset) {
	gl.log('=== GetUnderlyingSelection(' + pageName + ',' + caller + ') ===','i');
	
	if ((caller == "cats") || (caller == "init")){
		// update properties   
		checkboxDependencies('categorySelection');
	};
	
	if (caller == "props" )
	{
		checkboxDependencies('propertySelection');
	};
	
	var url='!ProcessPage';

	var params=getUnderlyingParameter( pageName, 'Underlying' );
	
	var contentId='auswahl';

	var ajaxHelper=new AjaxHelper();
	ajaxHelper.publicSend(url,params,contentId);
	
	//changing the storage to callType=InitKursliste ; the storage is needed for IE
	params = getUnderlyingParameter( pageName, 'InitKursliste');
	
	var addParams = '';
	if (storageUnderlying){
		addParams = addParams + '&UseFirstCat=' + storageUnderlying['UseFirstCat'];
	}
	
	var historyParams=url +'$' + params +'$content';

	var historyParamsUnderlying=historyParams.replace("CallType=InitKursliste","CallType=SelectUnderlying");
	historyReplace('InitUnderlyingSelection',historyParamsUnderlying);
	gl.log('=== THE END GetUnderlyingSelection() ===','i');
	}
	
} 

/** This function retreives the slider values of all sliders upon the page
**/
function getSliderValues(){
 var sRes = '';
	if (!(document.getElementById( 'slider0' ))){
		var storage = document.getElementById( 'storage' );
		if (storage){
			sRes = storage.getAttribute( 'slider' );
			if (!sRes) sRes = "";
		}
	} else {
		for (var i= 0; i < 10; ++i){
			var fSlider = document.getElementById( 'slider' + i );
			if (fSlider){
				sRes = sRes + i + '/' + fSlider.getAttribute( 'svalue' ) + ',';
			}
		}
	}
	return ( sRes );
}
/** This function retreives the filter vlaue
**/
function getFilterValues(){
   
   var sRes = '';
   var filter = document.getElementById( 'filter' );
   if (filter)
   {
      sRes = filter.value;
   } else {

      var storage = document.getElementById( 'storage' );
      if (storage){
         sRes = storage.getAttribute( 'filter' );
         if (!sRes) sRes = "";
      }

   }
   return( sRes );
}

/** 
	This function retreives the filter vlaue (url param snipet) of a given field (by elementId)
	@todo upgrade this solution so not only checkboxes can be read but also other kinds of fields 
	
	@param elementId
	@return url Returns the part of the url params like elementId=true
**/
function getFilterValueByElement(elementId)
{   
   var res = '0';
   var filter = document.getElementById(elementId);
   var url='';
   
   //check if the elemt exists
   if (filter)
   {
        if (filter.checked)
        {
               res = '1';
		}
		
		//concating the URL param
		url=elementId+ '=' + res;	
   } 
   
   return( url );
}




/** 
	This function gathers all parameters that are needed to refresh the underlying selection view and returns
	the url parameters
	@param pageName
	@param callType
	@param cats
	@return url The parameters as url snipet 
*/
function getUnderlyingParameter( pageName, callType, cats ) 
{ 
	gl.log('=== getUnderlyingParameter(' + pageName + ',' + callType + ',' + cats +')','i');
   
    //reading all filter values;
    var filter = getFilterValues();   
    var slider = getSliderValues();
    //alert(slider);
    //@TODO repair
    var swxlisted=getFilterValueByElement('SWXListed');
    var paramSchwelle=getFilterValueByElement('filterSchwelle');
    var filterIntraday=getFilterValueByElement('filterIntraday');
   
   	var schwelleURL='';
	

	
   if (!cats)
      var cats = getCategories();

	
   var url = 'PageName=' + pageName + 
             '&Categories=' + cats +
             '&sessionId=' + GLOBALSESSIONID +
			  '&CallType=' + callType +
             '&Filter=' + filter + 
             '&Slider=' + slider +
             '&' +swxlisted +
             '&' + filterIntraday +
             '&' + paramSchwelle;
             
 
   /*well for some reasons I dont know atm we have two storages. One called storage (for kursliste) and one for
   underlying selection called storageUnderlying. you may want to put both together */         

   if (storageUnderlying)
   {
      url = url + '&UseFirstCat=' + storageUnderlying['UseFirstCat'];
 	}
   
   
   gl.log('=== THE END getUnderlyingParameter() ===','i');
   
   return( url ); 
}
/* ========================================================== */

/** This function toogles the display of the "Weitere Internetangebote" Menü**/
function toggleWeitereAngebote() {
	Effect.toggle('Weiteres','appear',{duration:0.25}); 
}

/**
 *  hides the "Weitere Internetangebote" Menü* overlay
 **/
function hideWeitereAngebote()  {
	var element = $('Weiteres');
	if (element.visible())
		Effect.toggle(element,'appear',{duration:0.25}); 
}

function toggleMenu( id ) {
	Effect.toggle( id,'appear',{duration:0.25}); 
}

function hideMenu( id )  {
	var element = $( id );
	if (element.visible())
		Effect.toggle(element,'appear',{duration:0.25}); 
}

function Ausblenden () 
{
	Effect.toggle('Weiteres','appear',{duration:0.25});
}
/* ========================================================== */

/** This function checks the content. When it begins with "*session_expired*" a redirect to the disclaimer
will be done
@param response The response of an AJAX call
@return true when session ok else false
**/ 
function isSessionExpired(response)
{
	
	var part=response.substring (0,17);
	var expired=false;

	if(part =='*session_expired*')
	{
		expired=true;
		window.location.reload(true);
	} 
	//when *HOME* is received as response the Homepage should be openend
	//when an Bookmark of TIP2 could not be matched with one in TIP3 
	if(part =='*HOME*')
	{
		var ajaxHelper=new AjaxHelper();
		ajaxHelper.publicSend('!ProcessPage','CallType=Homepage','content');
	
	}
	
	return expired;
}
/* ========================================================== */

/** This function sends a vote **/
function SendBewertung() 
{
		
		//reading form fields
		var note=$F('note');
		var bemerkung=$F('bemerkung');
		var email=$F('email');
		
		var params = "Subject=Bewertung HSBC-Zertifikate Webseite&Note=" + note + "&Bemerkung=" + bemerkung + "&email=" + email;
		
		CallEx('VoteMail', params);
}
	
/* ========================================================== */	
function Kontakt() 
{
	//global var for domain prefix. Changing between TEST and PROD
	//window.open(GLOBALLNPREFIX+ 'Wpt/feedback.nsf/WF1058?OpenForm','Kontakt','left=200,top=210,width=630,height=720,status=no,toolbar=no,menubar=no,resizable=no,dependent=yes,scrollbars=yes');
	window.open('https://www.HSBCTrinkaus.de/Wpt/feedback.nsf/WF1058?OpenForm','Kontakt','left=200,top=210,width=630,height=720,status=no,toolbar=no,menubar=no,resizable=no,dependent=yes,scrollbars=yes');
}
	
/* ========================================================== */	

var anpassungenCache = new Object();

/**
 * This method checks Nach-Nachtäger availiblity and returns
 * true if a pdf is availabe for the given date
 */
function checkAnpassungenValidity(myDate) {
    cmonth  = myDate.getMonth()+1;

	days    = (myDate.getDate() < 10) ? ("0"+myDate.getDate()) : (""+myDate.getDate());
	months  = (cmonth           < 10) ? ("0"+cmonth) : (""+cmonth);
	years   = myDate.getYear();
	if( years<1900 )
		years = years+1900;
	
	key = months+"."+years;
	formatedDate = days+"."+months+"."+years;

	anpassungenValidityCache = anpassungenCache[key];
	
	if( !anpassungenValidityCache ) {
  
		new Ajax.Request('/!GetNachNachtraegeAvailabilityList', { 
			method: 'get', 
			asynchronous: false,
			parameters: {
				sMonth: months,
				sYear: years
			},
			onSuccess: function(transport){
				anpassungenValidityCache = transport.responseText;
				anpassungenCache[key] = anpassungenValidityCache;
			},
			onException: function(e) { 
				anpassungenValidityCache = "";
			}
		});
	}
	
	if( !anpassungenValidityCache || anpassungenValidityCache.indexOf(formatedDate)!=-1 )
		return true;
	
	return false;
}	
	
/** the global cache for validity dates */
validityCache = new Object();

/** 
 *  method to check if a date is valid to be enabled / selected
 *  this is a callback from calendar
 *
 * @param day the day to check
 */
function checkValidity(date) {
	var map;
	var day = date.getDate();
	var month = date.getMonth() + 1;
	var year = date.getFullYear();
	var cacheKey = ""+year + "-" + month;
	var mapKey = "";
	
	if (day < 10)
		mapKey = mapKey + "0";
	mapKey = mapKey + day + ".";
	
	if (month < 10)
		mapKey = mapKey + "0";
	mapKey = mapKey + month + ".";
	mapKey = mapKey + year;
	
	
	if (!validityCache[cacheKey]) {
		// make call to fetch the data
		new Ajax.Request('/!DownloadDailyAvailabilityMap', { 
			method: 'get', 
			asynchronous: false,
			parameters: {
				sMonth: month,
				sYear: year
			},
			onSuccess: function(res){
				// we got the data from the server, now cache it locally
				if (res && res.responseJSON)
					validityCache[cacheKey] = res.responseJSON;
				else
					validityCache[cacheKey] = new Object();
			},
			onException: function(e) { 
				validityCache[cacheKey] = new Object();
			}
		});
	}
	
	map = validityCache[cacheKey];
	if (map && map[mapKey])
		return true;
	
	return false;
}
/** 
 * This function returns a random number between min and max
 * @param min  
 * @param max
 * @return random number
**/
function GetRandom( min, max ) {
	if( min > max ) {
		return( -1 );
	}
	if( min == max ) {
		return( min );
	}
	return( min + parseInt( Math.random() * ( max-min+1 ) ) );
}



/** 
 * This function feeds an image into the HTML DOM. It is used for webstatistics. 
 * Each image consists of a random number and the pageId. By checking the Apache logfile the 
 * page statistic can be produced
 * @param pageId A unique id for that page
**/
function createStatPic(pageId)
{
	ran=GetRandom(1,2000);
	var pageStats=$( 'pageStats' );

	var url = 'images/dummy.gif?ran=' + ran + '&pageId=' + pageId;

	var bild = new Element("img", { src: url });
	//pageStats.insert(bild);
}
/**
 * This function is used upon the disclaimer page to change the link to the website dependent on the country
 * chosen by the user.
 * @param sCountry The country that got chosen  
 **/
function selectCountry(sCountry) 
{
   oldURL=$('url').href;
   
   var indexOf=oldURL.indexOf("&Country=swiss");
    
   if(indexOf > 0) 
   {
   	newURL=oldURL.replace("&Country=swiss","&Country=" + sCountry);
   }
   else
   {
   	newURL=oldURL.replace("&Country=germany","&Country=" + sCountry);
   }
  
   $('url').href=newURL;  
}

/**
 * This function checks for a promoId within the bookmark part of the url and sets a call to the server to track 
 * this page view.
*/
function checkForPromoId()
{
	
	var currentHash=window.location.hash;
	var indexOf=currentHash.indexOf('$promoId=');
	
	//when found...
	if(indexOf!=-1)
	{
		var promoId= currentHash.substring(indexOf+9,currentHash.length);
		//load the dummy pic
		//concating the str _a to the promoId (a for accepted. cause the user did accept the disclaimer)
		createStatPic(promoId + '_a');
	}
}

/**
 * This code is responsible for the loading of ad-images
 * by checking the disclaimer-state
 */
 
var adImages = new Array(); // image-urls to be loaded
var adImagesCnt = 0;

/**
 * Loads images
 */
function loadAdImages() {
	
	if( adImagesCnt>0 ) {

		for( i=0; i<adImages.length; i++ ) {
			pixelurl = adImages[i];

			tmpImage = new Image(); 
			tmpImage.src = pixelurl+"&rand="+Math.random();
			
		}
	
		adImages = new Array();
		adImagesCnt = 0;
	}

}

/**
 * Delayed loading of ad-images
 */
function delayedLoadAdImages() {
	if( !disclaimerShown ) {		
		loadAdImages();
	}
	adTimerSet = false;
}

/**
 * Stores an image-url for delayed loading
 */
function registerAdImg( url ) {
	adImages[adImagesCnt++] = url;
	setTimeout( "delayedLoadAdImages()", 2500 );
}

/**
 * This is the disclaimer code. It uses events to activate the disclaimer-check method.
 * The disclaimer-accepted state will be stored in three ways:
 *  - by using an ajax call in the backend-session
 *  - by using a cookie
 *  - by storing the state in the dom (in case of cookie is disabled)
 */

var shadowDiv;
var disclaimerDiv;
var disclaimerShown = false;

function calcDisclaimerTimeout() {
	tomorrow = new Date();
	tomorrow.setTime(tomorrow.getTime() + (1000*3600*24));
	tomorrow.setSeconds(0);
	tomorrow.setMinutes(0);
	tomorrow.setHours(0);
	return tomorrow.getTime() - (new Date().getTime());
}

/**
 * Returns the value of a parameter given by parameterName
 */
function getRequestParameter( parameterName ) {
	queryString = window.top.location.search.toLowerCase();
	var parameterName = parameterName + "=";
	if ( queryString.length > 0 ) {

		begin = queryString.indexOf ( parameterName );

		if ( begin != -1 ) {
			begin += parameterName.length;
			end = queryString.indexOf ( "&" , begin );
			if ( end == -1 ) {
				end = queryString.length
			}
			return unescape ( queryString.substring ( begin, end ) );
		}
		
	}
}

/**
 * Checks wheter the cookie is set or not.
 */
function isDisclaimerCookieSet( country ) {
	return document.cookie && document.cookie.indexOf('DISCLAIMER_SHOWN_'+country+'=')!=-1;
}                                                      

/**
 * Deletes the element with the given id from the dom
 * This method is called by a timer.
 */
function deleteElement( id ) {
	if( document.getElementById(id) ) {
		document.getElementsByTagName("body")[0].removeChild( document.getElementById(id) );
	}
}

/**
 * This method stores the disclaimer accepted state into the DOM.
 */
function storeDisclaimerState( country, state ) {
								
	var dummy = null;
	if( document.getElementById(country) ) {
		dummy = document.getElementById(country);
	} else {
		dummy = document.createElement('p'); 
	}

	dummy.setAttribute('id',country);
	dummy.setAttribute('name',state);
	try {
		document.getElementsByTagName("body")[0].appendChild(dummy);
		setTimeout( "deleteElement('"+country+"');", calcDisclaimerTimeout() );
	} catch( err ) {  }

}

/**
 * Detects internet-explorer version
 */
function getInternetExplorerVersion() {
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer') {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

/**
 * Waits until 'schnellauswahl' object was loaded and
 * exchanges the selectbox with the fake-jpg.
 */
function waitForSchnellauswahl( cnt, action ) {

	if( cnt>0 ) {
		done = false;
		
		selectBoxes = document.getElementsByTagName('select');
		if( selectBoxes ) {
			for( n=0; n<selectBoxes.length; n++ ) {
				selectBox = selectBoxes[n];
				
				if( selectBox.id!='selLand' ) {

					if( selectBox.id ) {
						selectBoxId = selectBox.id;
					} else {
						selectBoxId = "sel"+n;
					}
						
					if( action=='hide' ) {
						if( document.getElementById(selectBoxId+"ref") ) { 
							document.getElementById(selectBoxId+"ref").style.display = 'inline';
						} else {
							newNode = document.createElement("div");
							newNode.id = selectBoxId+"ref";
							newNode.style.cssText = 'float: left; border: 1px solid #7f99a6; padding-left: 4px; padding-top: 1px; padding-right: 16px; padding-bottom: 2px; margin-top: 7px; margin-left: 5px; background-color: #e6e6e6; font-family: arial; font-size: 11px; background-image: url(images/disabled_select_generic.jpg);  background-repeat:no-repeat;background-position: top right;';
							newNode.style.width   = (selectBox.offsetWidth-21)+'px';
							newNode.appendChild(document.createTextNode(selectBox.options[selectBox.selectedIndex].text)); 
							selectBox.parentNode.insertBefore( newNode, selectBox.nextSibling );
						}
						selectBox.style.display = 'none';
					} else {
						document.getElementById(selectBoxId+"ref").style.display = 'none';
						selectBox.style.display = 'inline';
					}
					
					done = true;
				}
				
			}
			
			if( !done ) {
				cnt--;
				setTimeout( "waitForSchnellauswahl("+cnt+",'"+action+"');",500 );
			}
		}
	}	
	
}

/**
 * This method shows the disclaimer. The html-code is stored
 * in the page-dom. (Morpheus`WEB`TIP3`TEST`Mapping`Templates.Index2)
 */
function displayDisclaimer() {
	disclaimerShown = true;

	// hide the background by a transparent div

	document.getElementById('disclaimerWall').style.display="inline";
	
	// show the disclaimer

	document.getElementById('disclaimerWindow').style.display="inline";

	// IE6 Bug
	
	ieVersion = getInternetExplorerVersion();
	if( ieVersion!=-1 && ieVersion<7 ) {
		waitForSchnellauswahl(120,'hide');
	}
	
	// fix darkness on FireFox
	
	if( ieVersion==-1 ) {
		if( (FF=/a/[-1]=='a') || (FF3=(function x(){})[-5]=='x') || (FF2=(function x(){})[-6]=='x') ) {
			document.getElementById('disclaimerWall').style.opacity = '0.5';
		}
	}
	
	// select language
	
	country = getRequestParameter('country');
	if( !country ) country = "germany";
	
	selectBox = document.getElementById('selLand');
	for( i=0; i<selectBox.options.length; i++) {
		if( selectBox.options[i].value==country ) {
			selectBox.selectedIndex = i;
			break;
		}
	}
	
	// etracking
	
	//et_eC_Wrapper( GLOBAL_ETRACKERCODE, 'Disclaimer_Shown', 'Disclaimer', 0, '', '', 0, 0, 0, 0, 0, 0, 0);
	
	ET_Event.eventStart('Interaktion', 'Disclaimer', 'Anzeige', '');
	
}

/**
 * Checks the disclaimer-accepted state by testing cookie,
 * DOM and at least the backend.
 * If the disclaimer is not accepted, the displayDisclaimer()
 * is used to show the disclaimer to the enduser.
 */
function checkDisclaimer() {

	if( !disclaimerShown ) {
		
		if( this['GLOBALSESSIONID']!=undefined && GLOBALSESSIONID!="zA6q2xeffwVvbQCV6zy9TK4Gpassage" ) {
			country = getRequestParameter('country');
			if( !country ) country = "germany";

			if( !isDisclaimerCookieSet(country) ) {
			
				if( document.getElementById(country) && document.getElementById(country).name=='0' ) {
					displayDisclaimer();
				} else {

					if( !document.getElementById(country) ) {
					
						new Ajax.Request('!Disclaimer?command=test&country='+country+'&sessionId='+GLOBALSESSIONID, {
							method: 'get',
							encoding: 'WINDOWS-1252',
							asynchronous: false,
							onSuccess: function(transport) {
								storeDisclaimerState( country, transport.responseText );
								if( transport.responseText=='0' ) {
									displayDisclaimer();
								}
							}
						})
					
					}
					
				} 

			}
		}
	}
	
}

/**
 * Removes the disclaimer-divs from the screen
 */
function removeDisclaimer() {

	document.getElementById('disclaimerWall').style.display="none";
	document.getElementById('disclaimerWindow').style.display="none";
	ieVersion = getInternetExplorerVersion();
	if( ieVersion!=-1 && ieVersion<7 ) {
		waitForSchnellauswahl(120,'show');
	}
	disclaimerShown = false;

	//et_eC_Wrapper( GLOBAL_ETRACKERCODE, 'Disclaimer_Accepted', 'Disclaimer', 0, '', '', 0, 0, 0, 0, 0, 0, 0);
	
	ET_Event.eventStart('Interaktion', 'Disclaimer', 'Zustimmung', '');
	
}

/**
 * Timeout for removing cookie
 */
function removeCookie() {
	document.cookie="DISCLAIMER_SHOWN_"+selectedCountry+"=true;expires="+new Date().toGMTString()+";";
}

/**
 * Handles the dialog-action from the disclaimer-html.
 */
function acceptDisclaimer( selectBox ) {
	
    selectedCountry = selectBox.options[selectBox.selectedIndex].value;
   
    // setting disclaimer-cookie

	now = new Date();
	expires = new Date(now.getTime()+calcDisclaimerTimeout());
	document.cookie="DISCLAIMER_SHOWN_"+selectedCountry+"=true;expires="+expires.toGMTString()+";";
	
	if( !isDisclaimerCookieSet(selectedCountry) ) {
	
		var req = new Ajax.Request('!Disclaimer?command=accepted&country='+selectedCountry+'&sessionId='+GLOBALSESSIONID, {
				method: 'get',
				encoding: 'WINDOWS-1252',
				onSuccess: function(transport) {
				}
			}
		)
		
		storeDisclaimerState( selectedCountry, '1' );
		
	}
	
	// country-redirect
	
	currentCountry = getRequestParameter('country');
	if( !currentCountry ) currentCountry = 'germany';
	
	if( selectedCountry!=currentCountry ) {
		document.body.innerHTML='';
		window.location = "!GetDefaultIndexPage?sessionId="+GLOBALSESSIONID+"&Lang=D&Country="+selectedCountry;
	} else {
	
		// adisfaction statistic call
		
		loadAdImages();
		
		tmpImageDisclaimer = new Image();
		tmpImageDisclaimer.src = 'http://ad2.adfarm1.adition.com/track?tid=613&sid=2991';
				
		// remove disclaimer
	
		removeDisclaimer();
	}
}

// init some event-listeners for checking the disclaimer-state

if( typeof noDisclaimer == 'undefined' ) {

	if( IE='\v'=='v' ) { // for IE
		document.attachEvent( "onclick", checkDisclaimer );
	} else { // for the rest
		window.captureEvents(Event.MOUSEDOWN);
		window.onmousedown = checkDisclaimer;
	}

}

/**
 * Waits until the video-page is loaded and embedds the flash-player (flowplayer)
 */
function domReady( cnt, action) {
	if( cnt>0 ) {
		done = false;
		playerDiv = document.getElementById('player');
		if (playerDiv) {
			done = true;
			eval(action);
		}
		if( !done ) {
			cnt--;
			setTimeout( "domReady("+cnt+",'"+action+"');", 500 );
		}
	}
}

/**
 * Used by the select-box in the dynamic-banner landingpage to redirect to a target.
 */
function redirectSelector() {
	discountRedirector = document.getElementById('discountRedirector');
	selectedOption     = discountRedirector.options[discountRedirector.selectedIndex];
	if( selectedOption.value!='Discountbroker' )
		window.open('http://'+selectedOption.value,'','status=yes,toolbar=yes,location=yes,directories=yes,menubar=yes,resizable=yes,dependent=yes,scrollbars=yes');
}

function CallExAddImageExt(type,params,imgUrl) {

	if(type!='KnockedCallType') { //concating type and params so this data can be used to recover the history
		historyAdd('CallEx',type +'$' + params);
	}
	
	//adding the sessionId to every call
	params='sessionId=[sessionId]&' + params;
	params='Country=[Country]&' + params;

   	var regPageName = /PageName=(\w+)/;
	regPageName.exec( params );
   	var sPageName = RegExp.$1;

	//reporting

	var url = imgUrl+'&rand='+GetRandom(1,2000); //'images/dummy.gif?ran=' + GetRandom(1,2000) + '&linkId=testing';
	new Element("img", { src: url });
	
	var content = $('content');
	content.update('');
	// requesting page content
	
	var req = new Ajax.Request('[SERVER]!ProcessPage', {
		method: 'post', parameters:  params + '&CallType=' + type  ,
		onLoading:  Loading(), 
		encoding: 'WINDOWS-1252',
		onSuccess: function(transport) {
			var expired=isSessionExpired(transport.responseText);
			if(expired == false) {
				var content = $('content');
					content.update(transport.responseText);
				switch (type) {
					case "DerivateWissenCallType":
						DerivateWissen.init();
					break;
				}
			}
		}
	} );

}

function toggleHandelBox() {
	var brokerBox = document.getElementById('brokerBox');
	
	if( brokerBox.style.display!='inline' ) {
		brokerBox.style.display = 'inline';
	} else {
		brokerBox.style.display = 'none';
	}
	
}

function widgetError( message, elemId ) {
	inputElem = document.getElementById( elemId );
	inputElem.style.border = "1px solid red";
	inputElem.style.backgroundColor = '#ffc0c0';
	return true;
}

function widgetHideError( elemId ) {
	inputElem = document.getElementById( elemId );
	inputElem.style.border = "";
	inputElem.style.backgroundColor = '#ffffff';
}

function checkFormAndSubmit() {
	var error = false;
	
	var vorname = document.getElementById('widget_vorname').value;
	var name = document.getElementById('widget_name').value;
	var email = document.getElementById('widget_email').value;
	
	if( vorname=='' ) error = error || widgetError('Bitte geben Sie Ihren Vornamen an.','widget_vorname');
	else widgetHideError('widget_vorname');
	if( name=='' )    error = widgetError('Bitte geben Sie Ihren Nachnamen an.','widget_name') || error;
	else widgetHideError('widget_name');
	if( email=='' )   error = widgetError('Bitte geben Sie Ihre E-Mail-Adresse an.','widget_email') || error;
	else widgetHideError('widget_email');

    if(!error) document.getElementById('error_required').style.display = 'none';
	else document.getElementById('error_required').style.display = 'inline';
	
	var bewertung = 0;
	var isChecked = false;
	for( var n=0; n<5; n++ ) {
		isChecked = isChecked || document.getElementById('widget_bewertung'+n).checked;
		if( isChecked && bewertung==0 ) bewertung = n+1;
	}
	
	if( isChecked ) document.getElementById('error_bewertung').style.display = 'none';
	else document.getElementById('error_bewertung').style.display = 'inline';
	
	if( isChecked && !error ) {
	
		var postData = "CallType=WidgetFeedback" +
			"&name=" + name +
			"&vorname=" + vorname +
			"&email=" + email +
			"&bewertung=" + bewertung +
			"&comment=" + document.getElementById('widget_comment').value +
			"&firma=" + document.getElementById('widget_firma').value +
			"&strasse=" + document.getElementById('widget_strasse').value +
			"&hausnr=" + document.getElementById('widget_hausnr').value +
			"&plz=" + document.getElementById('widget_plz').value +
			"&ort=" + document.getElementById('widget_ort').value +
			"&sessionId=" + GLOBALSESSIONID;
				
		var ajaxHelper = new AjaxHelper();
		ajaxHelper.publicSend('!ProcessPage',postData,'widgetContentData');	
	
	}
	return false;
}

function postAndRedirect() {
	var url = "!ProcessWebinar?last_name=" + escape( document.getElementById('last_name').value ) +
	               "&first_name=" + escape( document.getElementById('first_name').value ) +
				   "&company=" + escape( document.getElementById('company').value ) +
				   "&email=" + escape( document.getElementById('email').value ) +
				   "&phone=" + escape( document.getElementById('phone').value );

	new Ajax.Request( url, { method: 'get' } );
	
	if( document.getElementById('last_name').value!='' ||
	    document.getElementById('first_name').value!='' ||
		document.getElementById('company').value!='' ||
		document.getElementById('email').value!='' ||
		document.getElementById('phone').value!='' )		
		document.getElementById('formContainer').innerHTML = 'Vielen Dank für die Angabe Ihrer Daten.';
	
	window.open('https://hsbc.anywhereconference.com/','anywhereconference','');
}
