////////////////////////////////
// Some String utils function

// Compare two strings (default=insensitive)
function strComp(sString1,sString2,bSensitive)
{
	if(IsNull(bSensitive)) bSensitive = false;
	if(!bSensitive)
	{
		sString1 = sString1.toLowerCase();
		sString2 = sString2.toLowerCase();
	}
	return (sStringG1==sString2);
}


// Check if null
function IsNull(oItem)
{
	return ( oItem == null || oItem == undefined )
}


// Trim functions
function Trim(str){ return str.replace(/^\s*|\s*$/g,""); }
//function RTrim(STRING){ return str.replace(/^\s*,""); }
//function LTrim(STRING){ return str.replace(\s*$/g,""); }


/////////////////////////////
// Some cookies stuffs
// cookie Lang
var cookieLangName	= "CK_SDC_LANG";
// cookie reg info name
var cookieRegInfoName	= "CK_SDC_REG_INFO";

var scSecureUrl=getSecureUrl();
var scLogOffUrl=scSecureUrl + 'swift/login/logout.html';

// Get Cookies function
function getSecureUrl()
{
	var scHostname = location.hostname;
  if(scHostname.indexOf('.') != -1) return 'https://www2' + scHostname.substring(scHostname.indexOf('.')) + '/' ; else return "https://www2.swift.com/";
}

// Get Cookies function
function scGetCookie(sCookieName)
{
	var startCookiePos = document.cookie.indexOf(sCookieName + '=');
	if(startCookiePos == -1) return '';
	startCookiePos += sCookieName.length + 1;
	var endCookiePos = document.cookie.indexOf(';',startCookiePos);
	if(endCookiePos == -1) endCookiePos = document.cookie.length;
	return unescape(document.cookie.substring(startCookiePos,endCookiePos));
}

// Get URL Param function
function scGetURLParam(sParamName)
{
	var startParamPos = location.search.substring(1).indexOf(sParamName + '=');
	if(startParamPos == -1) return '';
	startParamPos += sParamName.length + 1;
	//if there is a "?" in the rest of the string, return the whole thing as the parameter value (nested url has query args)
	if ((location.search.substring(startParamPos+1).indexOf('?') != -1) &&
		(location.search.substring(startParamPos+1).indexOf('?') < location.search.substring(startParamPos+1).indexOf('&'))) {
		return location.search.substring(startParamPos+1);
	}
	var endParamPos = location.search.substring(1).indexOf('&',startParamPos);
	if(endParamPos == -1) endParamPos = location.search.substring(1).length;
	return unescape(location.search.substring(1).substring(startParamPos,endParamPos));
}

// write in the division
function writeInnerDivRegInfoCk(sString)
{
	var objLoginBox = document.getElementById('loginBox');
	if(!IsNull(objLoginBox))
	{
		if(sString != '')
			objLoginBox.innerHTML='<A href="' + scLogOffUrl + '" class="loginRight">Logout</A><A href="' + scSecureUrl + 'myprofile" class="loginLeft">'  + sString+ '</A>&nbsp;';
		 else
		 	objLoginBox.innerHTML='<div class="custLogin"><A href="' + scSecureUrl + 'myprofile" class="loginLeft">Customer log in</A></div>';
	}
}

// Create cookie from Ajax response
function createCookieRegInfo(originalRequest)
{
	var cookieRegInfoValue='';
	var cookieNameValue = originalRequest.responseText;
	        
	if(cookieNameValue.substring(0,cookieNameValue.indexOf("=")) == cookieRegInfoName){

		cookieRegInfoValue = cookieNameValue.substring(cookieNameValue.indexOf("=")+1, cookieNameValue.length);
		// remove the registration number for the revamp 2008
		if((cookieRegInfoValue.substr(cookieRegInfoValue.length,1) != ' ') && (cookieRegInfoValue.lastIndexOf(' ') != -1) )
		{
		  cookieRegInfoValue = cookieRegInfoValue.substr(0,cookieRegInfoValue.lastIndexOf(' ')) + ' (' + cookieRegInfoValue.substr(cookieRegInfoValue.lastIndexOf(' ')+1) + ')';
		}
			
		document.cookie = cookieRegInfoName + "=" + escape(cookieRegInfoValue) + "; domain=.swift.com; path=/";
	}
	writeInnerDivRegInfoCk(cookieRegInfoValue);
}

// make the javascript sleeping
function sc_sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

// Calling this function will write registration info (first name, last name, registration number)
/*
function displayRegInfoCookie()
{
	// get cookie Reg Num info
	var cookieRegInfoValue	= scGetCookie(cookieRegInfoName);

	if( cookieRegInfoValue == '' )
	{
		if ( (location.href.substr(0,5) == 'https') &&  (scGetCookie("ObSSOCookie") != '') && (typeof(Prototype) != "undefined") )
		{
			// Reg info cookie does not exist; get it via ajax
			var url = '/myprofile/get_registration_number.jsp';
			var pars = 'fakeinfo=' + Math.random();
			var myAjax = new Ajax.Request(
				url,
				{
					method: 'get',
					parameters: pars,
					onComplete: createCookieRegInfo
				});
		} else writeInnerDivRegInfoCk(cookieRegInfoValue);
	} else writeInnerDivRegInfoCk(cookieRegInfoValue);
}
*/
function decodeBase64IfNeeded(text) {

		var textDecoded = text;
		
		if (textDecoded.indexOf('=?UTF-8?B?') != 0){
				firstPart = textDecoded.substring(0,textDecoded.indexOf('=?UTF-8?B?'));
				lastPart = textDecoded.substring(textDecoded.indexOf('?=')+2,textDecoded.length);
				utf8_base64_textDecoded= base64_decode(textDecoded.substring(textDecoded.indexOf('=?UTF-8?B?')+10, 	textDecoded.indexOf('?=')));
				textDecoded = firstPart+utf8_base64_textDecoded+lastPart;
		}
		
		return textDecoded;	
		
}

	function base64_decode(input) {
		
		    var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = utf8_decode(output);

        return output;

 }
 
 function utf8_decode(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
  }
// Calling this function will populate the customer login box on the home page (div id="custLogin")
function displayCustLoginInfo()
{
	// get cookie Reg Num info & elements to update
	var cookieRegInfoValue	= scGetCookie(cookieRegInfoName);
	var custLoginBox = document.getElementById('custLogin');
	var custLoginLoggedIn = document.getElementById('custLoginLoggedIn');
	var custLoginNotLoggedIn = document.getElementById('custLoginNotLoggedIn');
	var custLoginLoggedInWelcome = document.getElementById('custLoginLoggedInWelcome');

	if( cookieRegInfoValue == '' )
	{
		//cookie doesn't exist or is empty, write "not logged in" block
		custLoginLoggedIn.style.display = 'none';
		custLoginNotLoggedIn.style.display = '';
	}
	else
	{
		//cookie exists and is not empty, write "logged in" block
		custLoginLoggedInWelcome.innerHTML = '<b>Welcome ' + cookieRegInfoValue + '</b>';
		custLoginLoggedIn.style.display = '';
		custLoginNotLoggedIn.style.display = 'none';
	};

}

// this function must be called in the end of the DCR of the page that uses the operational status component
function moveOpStatusText()
{
  elementToCopy = document.getElementById("textbeforeOS");    
  elementToCopyTo = document.getElementById("beforeOS");  
  if((elementToCopyTo != null) && (elementToCopy != null)) elementToCopyTo.appendChild(elementToCopy);
}


// this function is called in the syndication DCR to display a message above the applications
function displayNoTranslationMessage()
{
  // If there is no translation cookie, or an english translation cookie and when the URL is not KB, display the message
  var cookieLangValue = scGetCookie(cookieLangName);
  var stringPathName = location.pathname;
  var stringKBBasePath = '/search/kb';
  
  if( (cookieLangValue != '') && (cookieLangValue != 'en') )
  {
		// Display the messsage in the correct language
		if (stringPathName.substring(0,stringKBBasePath.length) != stringKBBasePath)
		{
			// application not KB
		  if(cookieLangValue == 'fr') document.write('<span class="orangetextnosize">Cette page est affich&eacute;e uniquement en anglais.</span>');
		  else if(cookieLangValue == 'es') document.write('<span class="orangetextnosize">&iexcl;Esta p&aacute;gina s&oacute;lo est&aacute; disponible en ingl&eacute;s!</span>');
		  else if(cookieLangValue == 'zh') document.write('<span class="orangetextnosize">\u8be5\u7f51\u9875\u53ea\u5b58\u5728\u82f1\u6587\u7248</span>');
    }
    else
		{
			// KB application
		  if(cookieLangValue == 'fr') document.write('<span class="orangetextnosize">Cette application utilise un outil de traduction automatique. Veuillez s&eacute;lectionner la langue desir&eacute;e.</span>');
		  else if(cookieLangValue == 'es') document.write('<span class="orangetextnosize">Esta aplicaci&oacute;n usa una herramienta de traducci&oacute;n autom&aacute;tica. Por favor, seleccione su lengua para empezar la traducci&oacute;n.</span>');
		  else if(cookieLangValue == 'zh') document.write('<span class="orangetextnosize">\u8be5\u5e94\u7528\u7a0b\u5e8f\u4f7f\u7528\u81ea\u52a8\u7ffb\u8bd1\u5de5\u5177\u3002\u9009\u62e9\u4e00\u4e2a\u8bed\u79cd\u8fdb\u884c\u7ffb\u8bd1\u3002</span>');
    }
  }
}

// this function is receiving a page as parameter and send a browser redirect with correct lang
function redirectToPage(pageURL)
{
  var cookieLangValue = scGetCookie(cookieLangName);
  if( (cookieLangValue != '') && (cookieLangValue != 'en') )
    redirectURLWithLang(pageURL,cookieLangValue);
  else
    redirectURLWithLang(pageURL,'en');
}

function redirectURLWithLang(url,lang)
{

    // build up the equivalent URL
    var newUrl = url;
    if(newUrl.indexOf('?') == -1) newUrl +='?'; else newUrl +='&';
    newUrl += 'lang=' + lang;

    // redirect
    window.location = newUrl;
}
		
// Update for reginfo jsf

var req;

// Calling this function will write registration info (first name, last name, registration number)
function displayRegInfoCookie()
{
 // get cookie Reg Num info
 var cookieRegInfoValue = scGetCookie(cookieRegInfoName);
 
 if( cookieRegInfoValue == '' )
 {
  if ( (location.protocol.substr(0,5) == 'https') && (location.hostname.substr(0,4) == 'www2') &&  (scGetCookie("ObSSOCookie") != '')  && (location.pathname.indexOf('/myprofile/public') == -1) )
  {  
   // Reg info cookie does not exist; get it via ajax
   var url = '/myprofile/get_registration_number.jsp';
   var pars = 'fakeinfo=' + Math.random();
   loadXMLDoc(url+'?'+pars) ;
  } 
  else writeInnerDivRegInfoCk(cookieRegInfoValue);
 } 
 else writeInnerDivRegInfoCk(cookieRegInfoValue);
}
 
function loadXMLDoc(url) {
 req = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
     try {
   req = new XMLHttpRequest();
        } catch(e) {
   req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
        try {
         req = new ActiveXObject("Msxml2.XMLHTTP");
       } catch(e) {
         try {
            req = new ActiveXObject("Microsoft.XMLHTTP");
         } catch(e) {
            req = false;
         }
  }
    }
    
 if(req) {
  req.onreadystatechange = processReqChange;
  req.open("GET", url, true);
  req.send("");
 }
}
 
function processReqChange() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {            
            createCookieRegInfo(req) ;
        } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
        }
    }
}


// google analytics document tracking
var gaA_fileTypes = new RegExp(/\.(doc*|xls*|ppt*|exe|zip|pdf|xpi)$/i); // Indicate each file extension that needs to be tracked, gaA_fileTypes is the regular expression that matches downloadable files
var gaA_pageTracker = null; // Should be set to the name of your tracker variable

var gaAddons = function(){
    var startListening = function(obj, evnt, func){
        if (obj.addEventListener) 
            obj.addEventListener(evnt, func, false);
        else 
            if (obj.attachEvent) 
                obj.attachEvent("on" + evnt, func);
    }

    var trackDocument = function(evnt){
				var trackDocumentURL=(evnt.srcElement) ? "/" + evnt.srcElement.pathname : this.pathname;
        gaA_pageTracker._trackPageview(trackDocumentURL);
        sc_sleep(200); // give time to the ga request to complete
    }

    /**
     * Initialize gaAddons
     */
    if (document.getElementsByTagName && typeof gaA_pageTracker == "object") {
        var hrefs = document.getElementsByTagName('a');
        for (var l = 0, m = hrefs.length; l < m; l++) 
            if (gaA_fileTypes.test(hrefs[l].pathname)) startListening(hrefs[l], "click", trackDocument);
    }
}

// to track documents, add a call to this function just after google analytics code initialisation
function addGADocumentTracking(){
	gaA_pageTracker=pageTracker;
	gaAddons();
}