﻿/*JS-VERSION:1.74.2.0*/
/*rosh:13.03.07: retrieve an element based on markup id - crossbrowser*/
function getElement(o){return document.all?document.all[o]:document.getElementById(o);}
/*rosh:13.03.07: toggles a div based on markup id - crossbrowser; to hide an element per default the div need to set: style='display:none'*/
function toggleDIV(v){var o = getElement(v);if(o.style){if(o.style.display != "none") o.style.display = "none"; else o.style.display = "";}}
/*xolh:13.03.07: toggles a Plus/Minus-CSS-Class on markup id - crossbrowser; to toggle an element per default the div need to set: class='plus'*/
function togglePlus(v){var o = getElement(v);if(o)      {if(o.className != "minus") o.className = "minus"; else o.className = "plus";}}
/* rosh:16.03.07:
function setDropDownValue(o,v) o:object v:value
selects the requested value in a dropdown list.
ex. setDropDownValue(document.getElementById('iLang'),'yourValue');*/
function setDropDownValue(o,v){if(!o) return; for (var i=0; i < o.options.length;++i){if (o.options[i].value == v) o.options[i].selected = true;}}
/*rosh:16.03.07: test if the user enables popups*/
function popUpTest(){
	if(popupChecked == true)
		return popupChecked;
	var success = false;
	var result = window.open("/_layouts/1033/popuptest.html", "popped", "left=1000,top=20, width=10, height=10, location=no, menubar=no, status=no, toolbar=no, scrollbars=no, resizable=no");
	window.focus();
	if (result != null) 
	{
		success = true;
		popupChecked = true;
		result.close();
	}
	else {success = false;}
	return success;
}
/* ROSH: 20.03.07: Cookie handle create */
function createCookie(name,value,days) {
//	if(value.toUpperCase() == 'ES' && name == cookieLanguageName)
//	{
//		// alert('Lang in es');
//		return;
//	}
		
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else expires = "";
	document.cookie = name+"="+value+expires+"; path=/; domain=" + cookieDomain;
}
/* ROSH: 20.03.07: Cookie handle read */
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;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);
	}
	return null;
}
/*rosh:13.03.07: restore markup form default data*/
function submitFormRestore(){
	$('aspnetForm').method		= formSubmitMethod;
	$('aspnetForm').action		= formSubmitAction;
	$('aspnetForm').onsubmit	= formSubmitOnSubmit;
}
/*rosh:13.03.07: set args as markup form parameters*/
function submitFormEdit(action, onsubmit, method)
{
	$('aspnetForm').method		= method;
	$('aspnetForm').action		= action;
	$('aspnetForm').onsubmit	= onsubmit;
}
/*
ROSH: 23.03.07
function replace(s, t, u)
Replace a token in a string
s:string to be processed
t:token to be found and removed
u:token to be inserted
returns new String
*/
function replace(s, t, u){i = s.indexOf(t);r = "";if (i == -1) return s;r += s.substring(0,i) + u;if ( i + t.length < s.length) r += replace(s.substring(i + t.length, s.length), t, u);return r;}

/*FLMO: 27.03.07 functions to setting css styles for active/deactive menu items*/
var navActive = false;

		function setActiveNav(item) {
			var nav = getElement('nav'+item);
			var counter = parseInt(item);
			if(nav) {
				if(counter == 0) {
					nav.className = "firstLi hi";
				}
				else
					nav.className = "hi";
			}
		}
		
		function setInactiveNav(item) {
			var nav = getElement('nav'+item);
			var counter = parseInt(item);
			if(nav) {
				if(counter == 0){
					nav.className = "firstLi";
				}
				else
					nav.className = "";
			}
		}
		 
		function compareStr(compareValue, item) {
			var docLoc = "";
			docLoc = document.location.href.toLowerCase();
            if (docLoc.indexOf(compareValue)!=-1) {
				setActiveNav(item);
				navActive = true;
			}
		    else {
			   setInactiveNav(item);
		    }	
		}
		//function called in Masterpage body onload
				function loadTopNavClass()
				 {
			var topSites = new Array("/offers/|/various/groups/","/bbf.htm|bba.htm|bbs.htm|bso.htm|page=khi|page=bbf|page=bba","/services/|/local_content/|tt.htm|adi.htm|sms.htm|nl.htm|pro.htm|dis.htm|my.htm|api.htm","/miles_and_more/","/about_swiss/","/career/");

			for (var i=0;i<topSites.length;i++) {

			    if (topSites[i].indexOf("|")!=-1) {
			        var str = topSites[i].split("|");
			          for (var j=0;j<str.length;j++) {
			          	compareStr(str[j], i);
			          	if(navActive)
			          		break;
			           }
			    }
				else {
					compareStr(topSites[i], i);
				}
			}
			InitSearchField();
			
		}		
	/* FLMO: 13.04.07 functions for enabling window.open() function via cms */	
	function enablePopup(){	
        a = document.getElementsByTagName("a");
        for (i=0; i<a.length; i++)
        {
            var id = a[i].getAttribute("id");
            if (id && id.indexOf("popup") != -1 && id.length > 5 && id.indexOf("x")){
                a[i].onclick = function(){
                    url = this.getAttribute("href");
                    id= this.id;
                    var x = id.substring(5);
                    var size = x.split("x");
                    var width = size[0];
                    var height = size[1];
                    window.open(url,id,'height=' + height + ',width=' + width + ',status=no,scrollbars=yes,toolbar=no,menubar=no,location=no,titlebar=no,resizable=yes');
                    return false;
                }
            }
            else if (id == "popup"){
                a[i].onclick = function(){
                
                url = this.getAttribute("href");
                window.open(url,'popup','height=200,width=400,status=no,scrollbars=yes,toolbar=no,menubar=no,location=no,titlebar=no,resizable=yes');
                return false;
                }
            }
        }
     }
     /*FLMO Function for printing the page */
     function varitext(text) {
        text=document
        print(text)
     }
     /*FLMO Function for forwarding page */
    function setForwardLink() {
	    var url = document.location.href;
	    var title = document.getElementsByTagName("title")[0].text;
	        if(title != null){
			    var link = "mailto:?subject=" + escape(title) + "&body=" + url;
			    var linkObject = getElement("forward");
			    linkObject = linkObject.getAttributeNode("href");
			    linkObject.nodeValue = link;
	        }
}
	/* End FLMO functions */
	
/*ROSH: 12.04.07 extract javascript exception details*/
function errorCatchHandler(ex)
{
	var err = 'name: ' + ex.name + '\n';
	err += 'message: ' + ex.message + '\n';
	
	if (ex instanceof TypeError)
	{
		err += 'info: ' + "Variable type problem, check your variable definitions!" + '\n';
	}
	else if (ex instanceof RangeError)
	{
		err += 'info: ' + "Number out of range!" + '\n';
	}
	else if (ex instanceof SyntaxError)
	{
		err += 'info: ' + "Syntax error in code!" + '\n';
	}
	else
	{
		err += 'info: ' + "An unspecified error occurred!" + '\n';
	}
	return err;
}

//FLMO 26.04.07 added functions from main.js
/* Popup 2 cols. Used in 601_personal_details.html to open popup_address popup */
function openPop_address(uri){
	popup = window.open(uri, "popup", "width=448,height=450");
	popup.focus();
	return false;
}

/* red plus */
function rp_toggleHi(elm){
	if(elm.parentNode.className == 'hi')
		elm.parentNode.className = '';
	else
		elm.parentNode.className = 'hi';
	return false;
}


/*ROSH 18.04.07: receive a number between 0 - 9  and returns 0X */
function formatDezimalNumberTo2Dig(data)
{
	try
	{
		var dd = parseInt(data);
		if(dd>9)
			return dd;
		else
			return '0'+dd;
	}
	catch(ex)
	{
		return data;
	}
}

/*ROSH 14.04.06: creates a new window and set's focus */
function openWindow(url, setFocus)
{
	if(url)
	{
		var result = window.open(unescape(url));
		if(result && setFocus)
		{
			result.focus();
		}
	}
}
/*
function urlHandler(url, lang, country)
ex: urlHandler('http://swrbslcms01:8086/web/DE/Pages/index.aspx#', 'EN')
result: 'http://swrbslcms01:8086/web/EN/Pages/index.aspx#
url: the string (url) to proceed on it
lang: the new language which will be replaced
returns a new string which used as location.href of the current window without the Country and lang parameter.
*/	
function urlHandler(url, lang, country)
{
	var result = url.replace("#","");
	var newLanguage = lang.toUpperCase();
	var newCountry = country.toUpperCase();
	var cacheIssue = (new Date()).getTime();
	var re = /\/(EN|FR|DE|IT|ES)\//i;	
    
    result = CutOutParameter(result, "country=", 2, 3);
    result = CutOutParameter(result, "lang=", 1, 2);
    
	// don't try to switch on local pages except the offer-page
	if(result.toLowerCase().indexOf("/countries/", 0) != -1)
	{
	    var offerPageDL = "local_content/Pages/offers.aspx";
	    // first we check if there is a language for this country
	    // /countries/CH = 14 characters
	    var charsToCheck = 14
	    // we check for "/XX/"
	    var checkString = result.substring(result.toLowerCase().indexOf("/countries/", 0) + 13, result.toLowerCase().indexOf("/countries/", 0) + 17).toUpperCase();
	    if (checkString.match(re))
	    {
	        charsToCheck += 3;
	    }
	    // now we check if its the offers-page
        if (result.toLowerCase().indexOf(offerPageDL.toLowerCase(), 0) != -1)
        {
            // /countries/ = 11 characters
            // cut out the country and language
            result = result.substring( 0, result.toLowerCase().indexOf("/countries/", 0) + 11 );
            result += newCountry + "/";
		    if (newCountry == "CH" || newCountry == "CA" || newCountry == "ROW")
		    {
		        result += newLanguage + "/";
		    }
		    result += offerPageDL;
		    return result;
		}
		else
		{
		    result = result.substring( 0, result.toLowerCase().indexOf("/countries/", 0) );
		    return result;
        }
	}

    if (result.match(re))
    {
        result = result.substring( 0, result.indexOf('?') == -1 ? result.length : result.indexOf('?') );
    	if((typeof(newCountry) != 'undefined') && (newCountry != null) && (newCountry != ''))
    	{
		    cacheIssue += "&Country=" + newCountry;
	    }
	    result = result.replace(re, '/'+newLanguage+'/') + '?' + cacheIssue;
        return result;
    } 

	if (result.toLowerCase().indexOf("tci=", 0) == -1)
	{
		var c = (result.indexOf('?') == -1) ? '?' : '&'; 
		result = result + c + 'tci=' + cacheIssue;
		return result;
	}
	else
	{
	    return result;
	}
}
/*THOK 09.11.07: function to cut out a parameter from the querystring */
function CutOutParameter(res, param, overheadOne, overheadTwo)
{
	var locationParam = res.toLowerCase().indexOf(param, 0);
	var locationQuestionmark = res.toLowerCase().indexOf("?", 0);
	var paramLength = param.length;
	// if the parameter exists
	if (locationParam != -1)
	{
        // If this parameter is the first one
	    if (locationQuestionmark == (locationParam - 1))
	    {
	        // is there just 1 parameter?
	        if (res.indexOf("&", 0) == -1)
	        {
	            res = res.substring(0, locationParam - 1);
	        }
	        // cut out the parameter with the overhead
	        // first check if the overhead is the first one, or the second one
	        else if (res.substring(locationParam + paramLength + overheadOne, locationParam + paramLength + overheadTwo) == "&")
            {
                res = res.substring(0, locationParam) + res.substring(locationParam + paramLength + overheadOne + 1, res.length);
            }
            else
            {
                res = res.substring(0, locationParam) + res.substring(locationParam + paramLength + overheadTwo + 1, res.length);
            }
	    }
	    // It's not the first one and not the last one?
	    else if (res.length > (locationParam + paramLength + overheadOne) && res.length > (locationParam + paramLength + overheadTwo))
        {
            if (res.substring(locationParam + paramLength + overheadOne, locationParam + paramLength + overheadTwo) == "&")
            {
                res = res.substring(0, locationParam) + res.substring(locationParam + paramLength + overheadOne + 1, res.length);
            }
            else
            {
                res = res.substring(0, locationParam) + res.substring(locationParam + paramLength + overheadTwo + 1, res.length);
            }	                
        }
        // it's the last one?
        else
        {
            res = res.substring(0, locationParam - 1);
        }
	}
	return res;
}

/*ROSH 18.04.06: function reads all data from the query string and returns the data of the specifc key.*/
function PageQuery(q) {
if(q.length > 1) this.q = q.substring(1, q.length);
else this.q = null;
this.keyValuePairs = new Array();
if(q) {
for(var i=0; i < this.q.split("&").length; i++) {
this.keyValuePairs[i] = this.q.split("&")[i];
}
}
this.getKeyValuePairs = function() { return this.keyValuePairs; }
this.getValue = function(s) {
for(var j=0; j < this.keyValuePairs.length; j++) {
if(this.keyValuePairs[j].split("=")[0] == s)
return this.keyValuePairs[j].split("=")[1];
}
return false;
}
this.getParameters = function() {
var a = new Array(this.getLength());
for(var j=0; j < this.keyValuePairs.length; j++) {
a[j] = this.keyValuePairs[j].split("=")[0];
}
return a;
}
this.getLength = function() { return this.keyValuePairs.length; } 
}

/*ROSH 18.04.06: receiving a key from the current QueryString; sample call: alert(queryString(sessionID));*/
function queryString(key){
var page = new PageQuery(window.location.search); 
return unescape(page.getValue(key)); 
}

/*ROSH 19.04.06: function reads all data from the query string and returns the data of the specifc key.*/
function parseCookie(q)
{
	if(q && q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if(q) {
		for(var i=0; i < this.q.split("&").length; i++){this.keyValuePairs[i] = this.q.split("&")[i];}
	}
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	this.getValue = function(s) {
		for(var j=0; j < this.keyValuePairs.length; j++){
			if(this.keyValuePairs[j].split("=")[0] == s)
			return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}
	this.getParameters = function(){
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++){
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}
	this.getLength = function() { return this.keyValuePairs.length; }
}

/*ROSH 19.04.06: receiving a key from the current cookie; sample call: getCookieValue('Youths',readCookie(name));*/
function getCookieValue(key,win){
	var page = new parseCookie(win);
	return unescape(page.getValue(key));
}

/*ROSH:20.04.07: post-load images for presenter*/
function applyPicture(picId)
{
	for(var n=1;n<imagePresenterArray.length;++n)
	{
		if(n==picId)
			if($('presenterImage'+n))
				$('presenterImage'+n).src = imagePresenterArray[n];
	}	
}

/*rosh:17.04.2007: retrieve the selected element id*/
function getRadioSelection(eleId)
{
	var selection = document.getElementsByName(eleId);
	var selected = '';
	for (i=0; i<selection.length; i++)
		if (selection[i].checked == true)
		{
			selected = selection[i].id;
		}
				
	return selected;
}



/*rosh:20.06.2007: define pre-defined elements to validate date input fields on start page*/
var digits = "0123456789";
var delimiters = ".,-/";
var maxLength = 8;

function isInteger(s)
{   
	var i;
  for (i = 0; i < s.length; i++)
  {   
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) 
		{
			return false;
		}
  }
  return true;
}
/*rosh:20.06.2007: strips out any chars, exceptions defind in array [digits]*/
function stripCharsInBag(s, bag)
{   
	var i;
	var returnString = "";
	for (i = 0; i < s.length; i++)
	{   
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) 
		{
			returnString += c;
		}
	}
	return returnString;
}
/*rosh:20.06.2007: main validation functionlity*/
function inputValidationDate(str)
{
	var s=stripCharsInBag(str,delimiters);
	return (isInteger(s) && s.length >= maxLength);
}
/*rosh:20.06.2007: formats date input*/
function formatInput(str)
{
	var formatted = new String();
	for (i = 0; i < str.length; i++)
  {   
		var c = str.charAt(i);
		if ( ((c >= "0") && (c <= "9")) || (delimiters.indexOf(c) != -1) ) 
		{
			formatted += c;
		}
  }
  return formatted;
}
/*rosh:20.06.2007: find pressed keycode from ASCII*/
function kc(e)
{
	var keycode;

	if (window.event)
		keycode = window.event.keyCode;

	else if (e)
		keycode = e.which;

	else
		return true;
	
	/* Numbers */
	if (47 < keycode && keycode < 58)
		return true;

	/* control chars [added 37,38,39,40] */
	var kcok = new Array(8, 10, 13, 46, 0, 37, 38, 39, 40);
	while (kcok.length > 0)
	{
		if (keycode == kcok.pop())
			return true;
	}

	return false;
}

/*rosh:20.06.2007: retrive pressed keycode*/
function getKeyCode(e)
{
	var keycode;

	if (window.event)
	{
		keycode = window.event.keyCode;
	}
	else
	{
		keycode = e.which;
	}
	return keycode;
}
/*rosh:20.06.2007: does some basic input checks */
function check4Numbers(ele, eve)
{
	ele.focus();
	
	var kcok = new Array(8, 10, 13, 46, 0, 37, 38, 39, 40);
	var kc = getKeyCode(eve);
	var contains = false;
	
	for(var i=0;i<kcok.length;++i)
	{
		if(kc == kcok[i])
		{
			contains = true;
			break;
		}	
	}
	
	if(contains)
		return true;
	else
		// debugger;

	if (inputValidationDate(ele.value)==false)
	{	
		ele.value = formatInput(ele.value);
		return true;
	}
	return true;
}

/*xlbr 20070810 maintain correct cursor position*/
function checkDateInput(ele, eve){
	var pos = getPos(ele);
	check4Numbers(ele, eve);
	setPos(ele, pos);
}

function setPos(ele, pos) {
	/* the way of the gecko */
	if(ele.selectionStart) {
		ele.focus();
        ele.setSelectionRange(pos, pos);
	}
	/* IE */
	if(ele.createTextRange) {
        var range = ele.createTextRange();
		range.move("character", pos);
		range.select();
	}
}

function getPos(ele) {
	var pos;

	ele.focus();
	if(ele.selectionStart) {
		pos = ele.selectionStart;
	}
	if(ele.createTextRange) {
		var range = document.selection.createRange();
		var moved = range.moveStart('character', -10);
		pos = range.text.length;
	}
	if (!pos) pos = 0;
	return pos;
}



/*
input -> output
5.7.2007 -> 05.07.2007 
5-7-2007 -> 05-07-2007 
5,7,2007 -> 05,07,2007 
5/7/2007 -> 05/07/2007 
*/
function formatDateFormat(ele)
{
	var result='';
	/*loop over delimiter options*/
	for(var d=0;d<delimiters.length;++d)
	{
		var tmp = ele.value.split(delimiters.charAt(d));
		if(tmp.length == 1)
			continue;
		/*create from day and month formatted numbers, e.g. 3.4.2008 => 03.04.2008*/
		for (var i=0;i<tmp.length-1;++i)
		{	
			result += fillNumber(tmp[i], delimiters.charAt(d))
		}
		var tmpDate = new Date();
		if(tmp[tmp.length-1].length == 2)
		{
			tmpDate = new Date('20'+tmp[tmp.length-1], tmpDate.getMonth()+1, tmpDate.getDate());
			tmp[tmp.length-1] = tmpDate.getFullYear();
		}		
		var nextYear = parseInt(tmpDate.getFullYear()) + 1;
		
		if( tmp[tmp.length-1] == nextYear.toString() ) {
			result += tmp[tmp.length-1];
		}
		else{
			result += tmpDate.getFullYear(); /*tmp[tmp.length-1];*/
		}
		
		ele.value = result;
		break;
	}	
	if(ele.value == '')
	{
		setDefaultValue(ele);
	}
	return false;
}

function setDefaultValue(ele)
{
	var now = new Date();
//		ele.value = 
//			fillNumber(now.getDate()+1, delimiters.charAt(0))
//			+
//			fillNumber((now.getMonth()+1), delimiters.charAt(0))
//			+
	//			now.getFullYear();
	ele.value =
			fillNumber(now.getDate(), delimiters.charAt(0))
			+
			fillNumber((now.getMonth() + 1), delimiters.charAt(0))
			+
			now.getFullYear();
}

function fillNumber(val, del)
{
	var result = '';
	if( parseInt(val) > 0 && parseInt(val) <= 9  )
	{
		result = '0'+parseInt(val)+delimiters.charAt(0);
	}
	else 
	{
		result = val + delimiters.charAt(0);
	}
	return result;
}

function InitSearchField()
{
//	var searchBox = document.getElementById('txtSearchBox');
//	if (searchBox != null)
//	{
//		//searchBox.value = decodeURI(unescape(oldValue));
//		//searchBox.value = unescape(oldValue);
//		oldValue = replace(oldValue, "%22", "\"");
//		searchBox.value = oldValue;
//	}
}

function doSearch() 
{
	var queryText = GetQueryText();
	var scopeLocal = "C_" + country;
    var scopeGlobal = "L_" + lang;
    var scopeFAQ = "F_" + lang;
    if (country == "CH" || country == "CA")
    {
		scopeLocal += "_" + lang;
    }
	var url = redirectUrl + "searchresults.aspx?q=" + encodeURIComponent(queryText) + "&sl=" + scopeLocal + "&sg=" + scopeGlobal + "&sf=" + scopeFAQ;
	window.location.href = url;
}

function GetQueryText() 
{
	var queryText = document.getElementById('txtSearchBox').value;
	if (queryText.indexOf("<script") >= 0)
		queryText= "";
	return (queryText);
}

function ValidateKey(e)
{
	var charCode = 0;
	charCode = getKeyCode(e);
	if (charCode == 13)
	{
        if (typeof( window.event ) != "undefined" )
        {
            // IE
            e.cancelBubble=true;
            e.returnValue = false; 
        }
        else 
        {
            // Firefox
            e.stopPropagation();
            e.preventDefault();
            e.returnValue = false; 
        }    	
		doSearch();
	}
	return true;
}

function toggleDIVAndChangeClassName(div, a)
{
    toggleDIV(div);
	var objA = getElement(a);
	if(objA != null)
	{
		if(objA.className != "hi") 
			objA.className = "hi"; 
		else 
			objA.className = "";
	}
}
function EventListener(obj, type, task){
	if (obj.addEventListener) {
		obj.addEventListener(type, task, false);
		return true;
	}
	else if (obj.attachEvent) {
		var r = obj.attachEvent('on' + type, task);
		return r;
	}
	else {
		return false;
	}
}
