var currentHost = document.location.host;
var currentProtocol = document.location.protocol;
var baseonlineGamePath = "/_games/index.html";
var returnFootnoteElement = $('body'); // default
var secureProtocol;
// ##################################
// ################################## LOGICS
// ##################################
// ################################## loaders
if ($.browser.msie) {
    $.ajaxSetup({
        async: false
    });

    $.getScript('/_js/general/ie_layout.js');
    $.ajaxSetup({
        async: true
    });
}

//load Basecontest lib


function originScript()
{
	var ori = document.location.host;
	var isKpn = {};
	isKpn.origin = false;
	isKpn.message = "We believe your visiting a wrong website. Please go to the official site: www.kpnoline.be\n\n" +
			  		"We geloven dat u op een ongeldige website surft. We raden u aan naar de officiële site www.kpnonline.be te surfen.\n\n" +
			  		"Nous pensons que vous êtes sur le mauvais site. Aller sur le site officiel http://www.kpnonline.be";
	
if ( ( ori.indexOf("kpnonline") != -1 ) || (ori.indexOf("localhost") != -1) || (ori.indexOf("") != -1) )
	{
		isKpn.origin = true;
	}
	return isKpn;
}


// ################################## init
jQuery(document).ready(function(){
    checkCookieLanguagePageInit();

    var or = originScript();
    if(!or.origin)
    {
    	document.location.href = "http://www.kpnonline.be";
    	return false;
    }
    
    netStats();

    setListNumbers();

    setTableOddEven();

    setFAQ();

    setProtocol();

    setFootNote();
 
  
});

// ------- PATCH FOR MASTERCARD GAME.

jQuery(window).load(function()
{
	if( $("#fakeDivPosition").length >  0 )
		{
			$("#fakeDivPosition").unbind("mouseenter" , mouseenterHandler );
			$("#fakeDivPosition").bind("mouseenter" , mouseenterHandlerChange );
			
			
			restoreToNormal = function(){
				$("#mastercardAnimation").css("z-index", -1);
				$("#fakeDivPosition").bind("mouseenter" , mouseenterHandlerChange );
			};
			
			updateBackgroundSize = function(){
				$("#mastercardAnimation").css("height",$("body").height() );
				$("#mastercardAnimation").css("width",$("body").width() );
			};
			
			var windowH = $(window).height();
			if(windowH < 930) windowH = 930;
			$(swfobject.getObjectById("mastercardApplication")).attr("height",windowH);
		}
});

function mouseenterHandlerChange()
{
	
	$("#mastercardAnimation").css("z-index", 4000);
	$("#fakeDivPosition").unbind("mouseenter" , mouseenterHandler );
}


function setFootNote(){
    $("a.footnoteBigHref").anchor('big');
    $("a.footnoteNormalHref").anchor('normal');
    $("span.backHref").returnAnchor();
}
//------- PATCH FOR MASTERCARD GAME.


/*******
 FROM >>>
 ***	Anchor Slider by Cedric Dugas   ***
 *** Http://www.position-absolute.com ***
 Never have an anchor jumping your content, slide it.
 Don't forget to put an id to your anchor !
 You can use and modify this script for any project you want, but please leave this comment as credit.
 *****/
jQuery.fn.returnAnchor = function(type){



    return this.each(function(){
        var element = $(this);

        element.click(function(event){

            event.preventDefault();


            $("html:not(:animated),body:not(:animated)").animate({
                scrollTop: $(returnFootnoteElement).offset().top
            }, 1000);
            return false;

        });
    });
}

jQuery.fn.anchor = function(type){
    return this.each(function(){

        var element = $(this);

        switch (type) {
            case 'big':
                $(element).before('<span class="footnoteBig">[</span>');
                $(element).after('<span class="footnoteBig">]</span>');
                break;

            case 'normal':

                $(element).before('<span class="footnoteNormal">[</span>');
                $(element).after('<span class="footnoteNormal">]</span>');
                break;
        }

        element.click(function(event){

            event.preventDefault();
            var locationHref = window.location.href
            var elementClick = $(element).attr("href")

            var destination = $(elementClick).offset().top;
            $("html:not(:animated),body:not(:animated)").animate({
                scrollTop: destination
            }, 1000, function(){
                window.location.hash = elementClick;
                returnFootnoteElement = $(element)
            });
            return false;

        });


    });
}


function setProtocol(){
    currentHost = document.location.host;

    if (currentHost.indexOf('localhost') != -1 || currentHost.indexOf('it') != -1) {
        secureProtocol = document.location.protocol.substring(0, document.location.protocol.length-1);
    }
    else {
        secureProtocol = "https";
    }
}


function setTableOddEven(){
    $('table tbody tr:odd').addClass('odd');
    $('table tbody tr:even').addClass('even');
}





function siteStatBannerClick(url, tagName){
    var urlPath;
    var urlSlash = "//";
    var urlProtocol;

    // check if we have an HTTP
    if (url.indexOf('http') == -1 && url.indexOf('https') == -1) {
        urlPath = currentHost;
        urlProtocol = currentProtocol;
    }
    else {
        urlPath = '';
        urlProtocol = '';
        urlSlash = '';
    }
    var urlE = 'http://be.sitestat.com/base/baseonline/s?' + tagName + '&ns_type=clickout&ns_url=[' + urlProtocol + urlSlash + urlPath + url + ']';
    document.location.href = urlE;
}








function clickTag(name){

}

function sitestat(ns_l) 
{
	// FromUrl v1.5 Copyright (c) 2001-2007 Nedstat B.V. All
	// rights reserved.

	var ns_type = ''; 	// leave empty for normal/ppc measurement, fill in for
						// clickin, clickout or pdf
	var r = ''; 		// yes=only parse url when there is a real document.referrer,
						// no=only parse url when there is no real document.referrer, empty=always
						// parse url
	var t = '?'; 		// tag in url where parameters follow; default '?' could be
						// replaced by "#"
	var p = new Array();
	var w = '';
	var l = '';
	var d = document;
	var n = navigator;
	var ns_0 = '';
	if (top != self) {
		if ('\u0041' == 'A') {
			var u = n.userAgent;
			if (u.indexOf('Safari') == -1) {
				var b = u.indexOf('Opera');
				if (b == -1 || (u.charAt(b + 6) + 0) > 5) {
					b = u.indexOf('Mozilla');
					var xb = b != -1 ? u.charAt(b + 8) > 4 : 1;
					if (u.indexOf('compatible') != -1 || xb) {
						var c = 'try{ns_0=top.document.referrer}catch(e){}';
						eval(c);
						c = 'try{l=top.document.location.href}catch(e){}';
						eval(c);
					}
				}
			}
		}
	} else {
		ns_0 = d.referrer;
		l = d.location.href;
	}
	if (ns_0.lastIndexOf('/') == ns_0.length - 1) {
		ns_0 = ns_0.substring(ns_0.lastIndexOf('/'), 0);
	}
	var f = ns_l.indexOf('?');
	if (f != -1) {
		var q = ns_l.substring(f + 1);
		ns_l = ns_l.substring(0, f);
		if (q) {
			var m = q.indexOf('&');
			w = q.substring(0, m == -1 ? q.length : m);
			if (w.indexOf('=') != -1) {
				w = '';
			}
			if (w) {
				q = q.substring(m == -1 ? q.length : m + 1);
				q += (q ? '&' : '') + 'ns_name=' + w;
			}
			if (ns_0.length > 0) {
				q += (q ? '&' : '') + 'ns_referrer=' + escape(ns_0);
			}
			var s = 0;
			var e = 0;
			while (q.length) {
				e = q.indexOf('&');
				if (e == -1) {
					e = q.length;
				}
				var o = q.substring(s, e);
				if (o.substring(0, 4) == 'amp;') {
					o = o.substring(4);
				}
				if (o)
					p[p.length] = o;
				q = q.substring(e + 1);
			}
		}
	}
	var a = l.indexOf(t);
	a = a == -1 ? 0 : l.substring(a + 1);
	var j;
	if (r == 'yes')
		j = ns_0.length;
	else if (r == 'no')
		j = !ns_0.length;
	else if (r == '')
		j = 1;
	if (a && j) {
		while (a.length) {
			var e = a.indexOf('&');
			if (e == -1) {
				e = a.length;
			}
			var k = a.substring(0, a.substring(0, e).indexOf('='));
			var v = a.substring(a.substring(0, e).indexOf('=') + 1, e);
			if (k.substring(0, 4) == 'amp;') {
				k = k.substring(4);
			}
			while (v.substring(0, 1) == '=') {
				v = v.substring(1);
			}
			if (k == 'ns_name') {
				w = v;
			} else if (k == 'ns_or') {
				var g = 'ns_referrer=';
				for ( var z = 0; z < p.length; z++) {
					if (p[z].substring(0, g.length) == g) {
						p[z] = 'ns_referrer=' + v;
					}
				}
			} else {
				if (k.substring(0, 3) == 'ns_' && v && k) {
					var h = 0;
					for ( var x = 0; x < p.length; x++) {
						if (p[x].substring(0, p[x].indexOf('=')) == k) {
							p[x] = k + "=" + v;
							h = 1
						}
					}
					if (!h) {
						p[p.length] = k + "=" + v;
					}
				}
			}
			a = a.substring(e + 1);
		}
	}
	if (!w) {
		return;
	}
	var s = '';
	var y = '';
	for ( var i = 0; i < p.length; i++)
		if (p[i].substring(0, 8) != 'ns_name=') {
			if (p[i].substring(0, 12) != 'ns_referrer=') {
				s += '&' + p[i];
			} else {
				y = '&' + p[i];
			}
		}
	s += ns_type ? '&ns_type=' + ns_type + '&ns_action=view' : '';
	ns_pixelUrl = ns_l + '?' + w + "&ns__t=" + (new Date()).getTime();
	ns_l = ns_pixelUrl + s + y;
	if (d.images) {
		ns_1 = new Image();
		ns_1.src = ns_l;
	} else {
		d.write('<img src=' + ns_l + ' width="1" height="1">');
	}
}



function netStats(){
               
                var str_sitestat = pageNameNew();
               
                if ( (currentHost.indexOf('kpnonline.be') != -1) || ( currentHost.indexOf('kpnonline.homebase.be') != -1))  {
                               if(str_sitestat != "nl.eShop" && str_sitestat != "fr.eShop" && str_sitestat != "en.eShop"){
                                               sitestat(window.location.protocol + '//be.sitestat.com/base/baseonline/s?' + pageNameNew());    
                               }
                }    
}

function netStatsEservices(urlStr){	

    if ( (currentHost.indexOf('kpnonline.be') != -1) || ( currentHost.indexOf('kpnonline.homebase.be') != -1))  {
        sitestat(window.location.protocol + '//be.sitestat.com/base/baseonline/s?' + urlStr );     
    }
}




function pageNameNew() {
	var str_url = location.pathname + location.search + location.hash;	
	
	
	// fixed value for root of domain
	if (str_url == "/") {
		return "selectLanguage";
	}	
	
	// remove leading slash, file extensions, "/index" & "app/"
	str_url = str_url.substr(1, str_url.length - 1);
	str_url = str_url.replace(".html", "").replace(".htm", "");
	str_url = str_url.replace("/index", "");
	str_url = str_url.replace("app/", "").replace("_app/","");
	
	// for flex Eshop/
	if ( str_url.indexOf("online_shop") != -1)
	{
		str_url = "eShop";			
	}	

	// replacements for online shop
	str_url = str_url.replace("online_shop_", "eShop.");
	str_url = str_url.replace("online_shop", "eShop.landing");

	// 01/02: additional replacements after feedback KBA
	str_url = str_url.replace("ebp", "postpaid.ebp");
	str_url = str_url.replace("myreloads", "prepaid.myreloads");
	str_url = str_url.replace("profile/directoryservices","postpaid.profile.directoryservices");
	str_url = str_url.replace("ps/services", "premiumservices.services");
	str_url = str_url.replace("/thirdparty_", ".premiumservices.");
	str_url = str_url.replace("cycling/catalog", "eShop.cycling.catalog");
	str_url = str_url.replace("atmloc/find.action", "atmlocator");
	str_url = str_url.replace("ATM_nl", "nl.prepaid.minisite");
	str_url = str_url.replace("ATM_fr", "fr.prepaid.minisite");
	str_url = str_url.replace("ATM_en", "en.prepaid.minisite");
	str_url = str_url.replace("cycling_shop", "eShop.cycling");

	// fixed values for homepages
	if (str_url.length <= 3) {
		str_url = str_url.substr(0, 2);
		str_url += ".homepage";
	}

	// replace slash or underscore by dot
	str_url = str_url.replace(/\//gi, ".");
	str_url = str_url.replace(/_/gi, ".");
 
	// remove information concerning Eservices.
	if (str_url.indexOf("?") != -1 && str_url.indexOf("=") != -1) 
	{			
		if ( str_url.indexOf("msisdn") != -1)
		{
			str_url = str_url.substr(0,str_url.indexOf("?"));			
		} else
		
		if ( str_url.indexOf("epay") != -1)
		{
			
			str_url = str_url.substr(0,str_url.indexOf("?"));			
		}else
		
		if ( str_url.indexOf("ereload") != -1)
		{
			str_url = str_url.substr(0,str_url.indexOf("?"));			
		}			
	} 			
	
	// in case we already have language
	var isL = (str_url.indexOf("en.") !=-1) || (str_url.indexOf("nl.")!=-1)  || (str_url.indexOf("fr.")!=-1);
	
	if ( !isL )
	{
		var language = ($.cookie('Lang'))?$.cookie('Lang').toLowerCase():'nl';
		str_url = language + "." + str_url;
	}		
	return str_url;

}





// ################################## checkCookieLanguagePageInit
function checkCookieLanguagePageInit(){
    var currentPath = window.location.href;
    var params = ["lang=fr", "lang=en", "lang=nl"]
    var urlString = ["/fr", "/nl", "/en"];
    for (var i in urlString) {
        if (currentPath.indexOf(urlString[i]) != -1) {
            switch (urlString[i]) {
                case "/fr":
                    $.cookie('Lang', null);
                    $.cookie('Lang', 'FR', {
                        expires: 90,
                        path: '/'
                    });
                    break;

                case "/nl":
                    $.cookie('Lang', null);
                    $.cookie('Lang', 'NL', {
                        expires: 90,
                        path: '/'
                    });
                    break;

                case "/en":
                    $.cookie('Lang', null);
                    $.cookie('Lang', 'EN', {
                        expires: 90,
                        path: '/'
                    });
                    break;
            }
        }
    }

    // 2nd Check
    for (var i in params) {
        if (currentPath.indexOf(params[i]) != -1) {
            switch (params[i]) {
                case "lang=fr":
                    $.cookie('Lang', null);
                    $.cookie('Lang', 'FR', {
                        expires: 90,
                        path: '/'
                    });
                    break;

                case "lang=en":
                    $.cookie('Lang', null);
                    $.cookie('Lang', 'EN', {
                        expires: 90,
                        path: '/'
                    });
                    break;

                case "lang=nl":
                    $.cookie('Lang', null);
                    $.cookie('Lang', 'NL', {
                        expires: 90,
                        path: '/'
                    });
                    break;
            }
        }
    }
}

// ################################## changeLanguage
function changeLang(lang){
    var currentPath = window.location.pathname;
    var path;
    if (currentPath.indexOf('/app') >= 0) {
		var queryString = window.location.search.substring(1);
		
		var params = queryString.split('&');
		
		var rewrite = '';
		
		for (i=0; i<params.length;i++) {
			if (params[i].indexOf('lang') == -1) { // Do not rewrite the existing lang parameter
				if (rewrite !== '') {
	 				rewrite += '&' + params[i];
				}else {
					rewrite += '?' + params[i];
				}
			}
		}
		
		if (rewrite == '') {
	        path = rewrite + '?lang=' + lang;
		}else {
			path = rewrite + '&lang=' + lang;
		}		
    }
    else {
        var currentLang = currentPath.substring(0, currentPath.indexOf('/', 1));
        path = currentPath.replace(currentLang, '/' + lang + '');
    }

    $.cookie('Lang', null);
    $.cookie('Lang', lang.toUpperCase(), {
        expires: 90,
        path: '/'
    })
    window.location.href = path;
}

// ##################################
// ################################## GLOBAL EFFECTS
// ##################################
// ################################## changeLanguage

//function createTopMenuAnimation()
//{
//   $("li.all").bind("mouseenter", mouseenterHandler );
//}
//
//function mouseenterHandler(e)
//{
//	$(".hiddenBlock").show(600);
//	$(document).bind("mousemove",mouseMoveHandler)
//}
//
//function showAllPartners(){
//    
//	
//	$(document).bind("mousemove",mouseMoveHandler);
//}
//
//function mouseMoveHandler(e)
//{
//	
//	 if (e.pageY > 85) 
//	 {
//		
//		  $(document).unbind("mousemove",mouseMoveHandler);
//      
//		  $(".hiddenBlock").hide(120);
//        
//     }
//}

function setListNumbers(){

    $('ul.numbers').each(function(){
        var i = 1;
        $(this).find('li:not(li li)').each(function(){
            $(this).addClass('n_' + i);
            i++;
        });
    });

}

// ##################################
// ################################## ONLINE APPLICATIONS
// ##################################
// ##################################

/**
 * Starts a window pop up launcher. Always center the popUp.
 *
 * @param  param
 *         url
 *         popupHeight
 *         popupWidth
 *
 *
 */
function launchGame(type){
    var popUpwindow;
    var urlSiteStat;
    urlSiteStat = "http://be.sitestat.com/base/baseonline/s?baseonlineGame_" + type + "_" + $.cookie('Lang').toLowerCase() + "&amp;ns_type=clickout&amp;ns_url=[http://" + currentHost + baseonlineGamePath + "?lg=" + $.cookie('Lang').toLowerCase() + "&type=" + type + "]";

    var scrW = screen.width;
    var scrH = screen.height;
    var settings = 'height=' + scrH + ',';
    settings += 'width=' + scrW + ',';
    settings += 'top=0,';
    settings += 'left=0,';
    settings += 'resizeable=0,';
    settings += 'location=0,status=0,scrollbars=0,directories=0,titlebar=0';
    popUpwindow = window.open(urlSiteStat, type, settings);
    popUpwindow.moveTo(0, 0);
}


function ATM_minisite(lg){
    var url = "/_app/ATM/index_" + lg + ".html";
    var name = "ATMminisite";
    var settings = "width=980,height=680,location=0,status=0,resizeable=0,scrollbars=0,directories=0,titlebar=0";
    var popup = window.open(url, name, settings);
}


function startEasy(lg)
{
	var url = "https://ezpay.liquix.eu/WebReloadSolution/index.jsp?provider=basebe&merchant=basebe&mode=VOUCHER&language=" + lg;
	 var popup = window.open(url, 'app_easy', 'width=770,height=549,toolbar=no,scrollbars=yes,resizable=yes,left=10,top=10');
}


function startSMSRegistration(lg){
    var url = "http://be.sitestat.com/base/baseonline/s?app_ezswitch_base_" + lg + "&amp;ns_type=clickout&amp;ns_url=[https://ezpay.liquix.eu/EzPayRegistration/index.jsp?lang=" + lg + "&provider=base&register=true]";
    var popup = window.open(url, 'app_ezswitch_base', 'width=770,height=549,toolbar=no,scrollbars=yes,resizable=yes,left=10,top=10');
}


function startAutoRegistration(lg){
    var url = "http://be.sitestat.com/base/baseonline/s?app_ezswitch_base_auto" + lg + "&amp;ns_type=clickout&amp;ns_url=[https://ezpay.liquix.eu/EzPayRegistration/index.jsp?lang=" + lg + "&provider=base&register=true&mode=autoreload]";
    var popup = window.open(url, 'app_ezswitch_base_auto', 'width=770,height=549,toolbar=no,scrollbars=yes,resizable=yes,left=10,top=10');
}

function startAutoManage(lg){
    var url = "http://be.sitestat.com/base/baseonline/s?app_ezswitch_base_automanage" + lg + "&amp;ns_type=clickout&amp;ns_url=[https://ezpay.liquix.eu/EzPayRegistration/index.jsp?lang=" + lg + "&provider=base&mode=autoreload]";
    var popup = window.open(url, 'app_ezswitch_base_automanage', 'width=770,height=549,toolbar=no,scrollbars=yes,resizable=yes,left=10,top=10');
}

function startSMSRegistration(lg){
    var url = "http://be.sitestat.com/base/baseonline/s?app_ezswitch_base_" + lg + "&amp;ns_type=clickout&amp;ns_url=[https://ezpay.liquix.eu/EzPayRegistration/index.jsp?lang=" + lg + "&provider=base&register=true]";
    var popup = window.open(url, 'app_ezswitch_base', 'width=770,height=549,toolbar=no,scrollbars=yes,resizable=yes,left=10,top=10');
}

/**
 * Starts the webreload application for an MSISDN with the specified language
 * The MSISDN should be available in a input field with name 'msisdn'
 *
 * @param lg the current language
 */
function startwebreload_msisdn(lg){
    var numberEntered = $('input[name="msisdn"]').val();
    var fromBaseonline = '';
    if ($('input[name="baseonline"]').val() && $('input[name="baseonline"]').val() == "true") {
        fromBaseonline = "&baseonline=true";
    }

    var protocol = parent.location.protocol;

	var urlWebreload = protocol + "//" + currentHost + "/app/eservices/ereload/index.htm?msisdn=" + numberEntered + fromBaseonline;

    window.location = urlWebreload;
}

/**
 * Starts the webpay application for an MSISDN with the specified language
 * The MSISDN should be available in a input field with name 'msisdn'
 *
 * @param lg the current language
 * @param balance the balance to set on the url
 */
function startWebPaymentPostpaid_msisdn(lg, balance){
    var numberEntered = $('input[name="msisdn"]').val();

    var protocol = parent.location.protocol;

	var urlWebpayment = protocol + "//" + currentHost + "/app/eservices/epay/index.htm?msisdn=" + numberEntered + "&lang="+lg;

	if (balance) {
		urlWebpayment = urlWebpayment + ('&amount=' + balance);
	}

	var fromBaseonline = '';
	if ($('input[name="baseonline"]').val() && $('input[name="baseonline"]').val() == "true") {
        urlWebpayment += ("&baseonline=true");
    }

    window.location = urlWebpayment;
}




/**
 * Starts the AutoRegistration application for an MSISDN with the specified language
 *
 * @param lg the current language
 */
function startAutoRegistration(lg){
    var url = "http://be.sitestat.com/base/baseonline/s?app_ezswitch_base_auto" + lg + "&amp;ns_type=clickout&amp;ns_url=[https://ezpay.liquix.eu/EzPayRegistration/index.jsp?lang=" + lg + "&provider=base&register=true&mode=autoreload]";
    var popup = window.open(url, 'app_ezswitch_base_auto', 'width=768,height=640,toolbar=no,scrollbars=yes,resizable=no,left=10,top=10');
}

/**
 * Starts the Epay registration application for an MSISDN with the specified language
 *
 * @param lg the current language
 */
function startSMSManage(lg){
    var url = "http://be.sitestat.com/base/baseonline/s?app_ezswitch_base_manage" + lg + "&amp;ns_type=clickout&amp;ns_url=[https://ezpay.liquix.eu/EzPayRegistration/index.jsp?lang=" + lg + "&provider=base]";
    var popup = window.open(url, 'app_ezswitch_base_manage', 'width=770,height=549,toolbar=no,scrollbars=yes,resizable=no,left=10,top=10');
}


/**
 * Starts the webreload application for an MSISDN with the specified language
 * The MSISDN should be available in a input field with name 'msisdn'
 *
 * @param lg the current language ; origin the current origin of asking ; code postal code entered by the user ; option which one you want.
 */
function openATMApplication(lg, origin, code, option){
    (code) ? code = '&zipCd=' + code : '';
    (origin) ? origin = '&origin=' + origin : '';
    (option) ? option = '&option=' + option : '';

    var url = "http://be.sitestat.com/base/baseonline/s?app_atm_locator" + lg + "&amp;ns_type=clickout&amp;ns_url=[http://" + currentHost + "/app/atmloc/find.action?lang=" + lg + code + origin + option + "]";
    var popup = window.open(url, '', 'width=1000,height=750,toolbar=no,scrollbars=yes,resizable=no,left=10,top=10');
}


/**
 * Starts the MC conditions
 *
 * @param lg the current language ; origin the current origin of asking ; code postal code entered by the user ; option which one you want.
 */
function startMCconditions(lg){
    var url = "http://be.sitestat.com/base/baseonline/s?pdf_basemc_conditions_" + lg + "&amp;ns_type=clickout&amp;ns_url=[http://" + currentHost + "/_pdf/basemc_" + lg + ".pdf]";
    var popup = window.open(url);
}


function startLoginMyPrepaid(lg, form){

    form.action = secureProtocol + "://" + currentHost + "/app/myreloads/secure_login";
    form.submit();
}

function startLoginEBP(lg, form){

    form.action = secureProtocol + "://" + currentHost + "/app/ebp/secure_login";
    form.submit();

}



function removeError(){
    var error = $('#error_overlay');
    if ($.browser.msie) {
        error.remove();
    }
    else {
        error.fadeOut('fast', function(){
            error.remove();
        });
    }
}

function showError(title, content, target, position){
    //position: right,top,bottom

    if ($.browser.msie && (jQuery.browser.version.substr(0, 1) == "6")) {
        error.pngFix();
    }

    if (!position) {
        position = 'right';
    }

    var target = $(target);

    if (target.length > 0) {

        removeError();

        var errorDiv = '<div id="error_overlay" class="' + position + '">';

        if (position == 'bottom' || position == 'eservicesError') {
            errorDiv += '<img src="/_img/general/error_overlay_top_arrow.png" alt="" />';
        }
        else {
            errorDiv += '<img src="/_img/general/error_overlay_top.png" alt="" />';
        }

        errorDiv += '<div><em>!</em>';
        if (title) {
            errorDiv += '<h3>' + title + '</h3>'
        }
        errorDiv += '<p>' + content + '</p>';
        errorDiv += '<img src="/_img/general/ok_grey.gif" alt="OK" class="ok" /></div>';

        if (position == 'top') {
            errorDiv += '<img src="/_img/general/error_overlay_bottom_arrow.png" alt="" />';
        }
        else {
            errorDiv += '<img src="/_img/general/error_overlay_bottom.png" alt="" />';
        }

        errorDiv += '</div>';

        $('body').append(errorDiv);

        var error = $('#error_overlay');
        var targetOffset = target.offset();
		var targetPosition = target.position();
        var targetHeight = target.height();
        var contentOffset = $('#wrapper').offset();
        var height = error.height();

        var top = 0;
        var left = 0;

        switch (position) {

            case 'right':

                top = targetOffset.top - ((height + targetHeight) / 2) + 15;
                left = contentOffset.left + 165;

                break;

            case 'top':

                top = targetOffset.top - height + 15;
                left = contentOffset.left + 207;
                jQuery('html,body').animate({
                    scrollTop: (targetOffset.top - height)
                });

                break;

            case 'bottom':

                top = targetOffset.top + targetHeight - 15;
				// if problem add left = contentOffset.left + 207;
                left = contentOffset.left;


                jQuery('html,body').animate({
                    scrollTop: (targetOffset.top + targetHeight + height)
                });

				break;

			case 'eservicesError':
				 top = targetOffset.top + targetHeight - 15;
				 left = targetPosition.left -  ( $("#error_overlay").innerWidth() / 2 ) + ( target.innerWidth() / 2 )

				  jQuery('html,body').animate({
                    scrollTop: (targetOffset.top + targetHeight + height)
                });

			break;



        }

        error.css({
            'top': top + 'px',
            'left': left + 'px'
        });

        error.find('.ok').click(function(){
            removeError();
        });



    }

}


function showErrorHomepage(title, content, target, position){
    //position: right,top,bottom


    var target = $(target);
    //alert(target.height());

    if (target.length > 0) {
        removeError();
        var errorDiv = '<div id="error_overlay" class="' + position + '">';
        errorDiv += '<img src="/_img/general/error_overlay_top.png" alt="" />';
        errorDiv += '<div><em>!</em>';
        errorDiv += '<p>' + content + '</p>';
        errorDiv += '<img src="/_img/general/ok_grey.gif" alt="OK" class="ok" /></div>';
        errorDiv += '<img src="/_img/general/error_overlay_bottom_arrow.png" alt="" />';
        errorDiv += '</div>';
        $('body').append(errorDiv);

        var error = $('#error_overlay');
        var targetOffset = target.offset();
        var targetHeight = target.height();
        var contentOffset = $('#wrapper').offset();
        var height = error.height();
        var width = error.width()

        var top = 0;
        var left = 0;

        top = target.offset().top - error.height();
        left = target.offset().left - error.width() / 2;

        error.css({
            'top': top + 'px',
            'left': left + 'px'
        });

        error.find('.ok').click(function(){
            removeError();
        });

        if ($.browser.msie && (jQuery.browser.version.substr(0, 1) == "6")) {
            error.pngFix();
        }
    }
}

// ##################################
// ################################## FORM CHECKING
// ##################################
// ##################################
function checkAlpha(str){
    var Regxp = /([a-zA-Z0-9_-éùèàçûüîïöôêë\s])$/;

    if (Regxp.test(str)) {
        return true;
    }

    else {
        return false;
    }
}

function isEmpty(ob){
    if (ob.value.length < 1) {
        return true;
    }
    else {
        return false;
    }
}

function checkNum(str){
    var RegxpNum = /([0-9])$/;
    if (RegxpNum.test(str)) {
        return true;
    }
    else {
        return false;
    }
}

function aslength(ob, num){
    if (ob.value.length == num) {
        return true;
    }
    else {
        return false;
    }
}

function isEqual(str1, str2){
    if (str1 == str2) {
        return true;
    }
    else {
        return false;
    }
}

function IsNumeric(sText){
    var ValidChars = "0123456789";
    var IsNumber = true;
    var Char;

    if ((sText.value.length < 10) || (sText.value.length > 11)) {
        IsNumber = false;
        displayError(sText);

    }
    else {
        for (i = 0; i < sText.value.length && IsNumber == true; i++) {
            Char = sText.value.charAt(i);
            if (ValidChars.indexOf(Char) == -1) {
                IsNumber = false;
                displayError(sText);
            }
            else {
                deleteError(sText);
            }
        }
    }

    return IsNumber;
}

function IsPostalCode(sText){
    var isPostalCode = true;
    var Char;
    if ((sText.value.length < 4)) {
        isPostalCode = false;
        displayError(sText);
    }
    else {
        var RegxpNum = /([0-9])$/;
        if (RegxpNum.test(sText.value)) {
            deleteError(sText);
            isPostalCode = true;
        }
        else {
            displayError(sText);
            isPostalCode = false;
        }
    }

    return isPostalCode;
}


function validLoginHomepage(formElement, target, errorMessage){
    if ($('#outageEnabled').val() == "true") {
        return false;
    }

    var errorMessages = ''
    var login;
    (!formElement) ? login = document.forms[0] : login = formElement;

    var loginConfirm = true;
    if (checkAlpha(login['j_username'].value) && !isEmpty(login['j_username'])) {
        deleteError(login['j_username'])
    }
    else {
        displayError(login['j_username']);
        loginConfirm = false;

        errorMessages += $('#jsErrEBP_UsernameInvalid').text() + '<br />';
    }

    if (checkAlpha(login['j_password'].value) && !isEmpty(login['j_password'])) {
        deleteError(login['j_password'])
    }
    else {
        displayError(login['j_password']);
        loginConfirm = false;

        errorMessages += $('#jsErrEBP_PasswordInvalid').text() + '<br />';
    }

    if (!loginConfirm) {
        showErrorHomepage(null, errorMessages, target);
    }

    return loginConfirm;
}



function atLeastLength(ob, num){
    if (ob.value.length >= num) {
        return true
    }
    else {
        return false;
    }
}

function isValidUrl(value) {
	var urlPattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	
	return urlPattern.test(value);
}

function isValidEmail(value) {
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
   	
   	return emailPattern.test(value);
}

function trim(sString){
    while (sString.substring(0, 1) == ' ') {
        sString = sString.substring(1, sString.length);
    }
    while (sString.substring(sString.length - 1, sString.length) == ' ') {
        sString = sString.substring(0, sString.length - 1);
    }
    return sString;
}

function deleteError(ob){
    if (ob.type == "checkbox") {
        ob.style.border = "1px solid #ffffff";
    }
    else {
        $(ob).removeClass('error')
    }
}

function displayError(ob){
    if (ob.type == "checkbox") {
        ob.style.border = "2px solid red";
    }
    else {
        $(ob).addClass('error')
    }
}

function addBookmark(bookmarkurl, bookmarktitle){
    var ua = navigator.userAgent.toLowerCase();
    var isSafari = (ua.indexOf('webkit') != -1);
    var isMac = (ua.indexOf('mac') != -1);
    var buttonStr = isMac ? 'Command/Cmd' : 'CTRL';

    if (window.sidebar) { // Mozilla Firefox Bookmark
        window.sidebar.addPanel(bookmarktitle, bookmarkurl, "");
    }
    else
        if (window.external) { // IE Favorite
            window.external.AddFavorite(bookmarkurl, bookmarktitle);
        }
        else
            if (window.home || isSafari) { // Netscape, Safari, iCab
                alert('You need to press ' + buttonStr + ' + D to bookmark this page');
            }
            else
                if (!window.print || isMac) { // IE5/Mac and Safari 1.0
                    alert('You need to press Command/Cmd + D to bookmark this page');
                }
                else { // All other browsers
                    alert('In order to bookmark this page you need to do so manually through your browser');
                }
}

function setFAQ(){

    $('div.faq').css('cursor', 'pointer').each(function(){
        var div = $(this);
        var divContent = div.find('div').hide();
        div.bind("click", function(e){

            var i = e.target.toString();
            if (i.indexOf('http://') == -1)
                divContent.toggle('blind');
        });
    });

}


function placeBullet(state){
    var addValue = 170;

    $('#percent').hide();
    $('#percent div').hide();

    if (state == "on") {
        addValue = addValue + 57
    }

    $('#percent').css("top", $('#home').position().top + addValue);
    $('#percent').css("left", $('#home').position().left + $('h4:first').width() + 30);

    $('#percent div').css("top", $('#percent').position().top - 43);
    $('#percent div').css("left", $('#percent').position().left + 30);

    $('#percent').mouseenter(function(){
        (jQuery.browser.msie) ? $('#percent div').show() : $('#percent div').show("slow");
    });

    $('#percent').mouseleave(function(){
        $('#percent div').hide();
    });

    (jQuery.browser.msie) ? $('#percent').show() : $('#percent').show("slow");
}




function enterBaseonline(lang){
    switch (lang) {
        case "fr":
            $.cookie('Lang', 'FR');
            document.location.href = "/fr/";
            break;

        case "nl":
            $.cookie('Lang', 'NL');
            document.location.href = "/nl/";
            break;

        case "en":
            $.cookie('Lang', 'EN');
            document.location.href = "/en/";
            break;

        default:
            $.cookie('Lang', 'NL');
            document.location.href = "/nl/";
            break;
    }
}

function getToken(){
    var token = "?token=";
    var tokenN = Math.floor(Math.random() * 50000);
    token += tokenN.toString();
    return token
}


// Util functions for binding / unbinding on a button (including the image in front and on the end)
function bindOnActionButton(el, event, func) {
	if ($(el)) {
		$(el).prev().bind(event, func);
		$(el).bind(event, func);
		$(el).next().bind(event, func);
	}
}

function unbindOnActionButton(el, event) {
	if ($(el)) {
		$(el).prev().unbind(event);
		$(el).unbind(event);
		$(el).next().unbind(event);
	}
}

function formatMsisdn(value)
    {
      // First remove the unnecessary characters
      var tempVal = '';
      for (i=0; i< value.length; i++) {
        var Char = value.charAt(i);

        if ((Char !== ' ') && (Char !== '.') && (Char !== '/')) {
        tempVal += Char;
      }
      }

      var formattedMsisdn = '';
      // for a number like 0486 xx xx xx
      if ( tempVal.length == 10)
      {
        formattedMsisdn = tempVal.substr(0,4) + "&nbsp;" +  tempVal.substr(4,2) + "&nbsp;" + tempVal.substr(6,2) + "&nbsp;" + tempVal.substr(8,2);
      } else
      if( tempVal.length == 11)
      {
        formattedMsisdn = tempVal.substr(0,2) + "&nbsp;" +  tempVal.substr(2,3) + "&nbsp;" + tempVal.substr(5,2) + "&nbsp;" + tempVal.substr(7,2) + "&nbsp;" + tempVal.substr(9,2);
      } else
	  {
	  	formattedMsisdn = value;
	  }
      return formattedMsisdn;
    }

