﻿// Click correct button on enter. Primarily for non-Microsoft browsers.
// Used on public pages that have multiple form areas and search box.
function entersubmit(id, argument, e)
{
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	if (code == 13)
	{
		__doPostBack(id,argument);
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
	}
}

// Click correct button on enter. Primarily for non-Microsoft browsers.
// Used on public pages that have multiple form areas and search box.
function enternosubmit(e)
{
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	if (code == 13)
	{
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
	}
}

// Function used to stop the input of < and > on all input pages.
function safeinput(e)
{
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	if (code == 60 || code == 62)
	    return false;
}

// Set the text size
function setPref(name, value)
{
    var cookieValue = ""; // to hold the cookie value
    if (readCookie("PREF"))
    {
        var pref = unescape(readCookie("PREF"));
        var prefSplit = pref.split("&");
        for (var i=0; i<prefSplit.length; i++) // keep whatever was there already
        {
            var vp = prefSplit[i].split("="); // name-vlaue pair
            if (vp[0] != name) // existing value is different
            {
                cookieValue += vp[0] + "=" + vp[1] + "&";
            }
        }
    }
    // Now add the requested name value pair
    cookieValue = cookieValue + name + "=" + value;
    setPrefCookie("PREF", cookieValue, new Date("December 31, 2010 23:59:59"),"/");
    location.reload();
}

// Read specific preference from PREFS cookie
function readPrefs(name)
{
    if (!readCookie("PREF"))
        return "x";
	var prefs = unescape(readCookie("PREF"));
    var prefSplit = prefs.split("&");
    for (var i=0; i<prefSplit.length; i++) // Step through each name-value pair
    {
        var vp = prefSplit[i].split("="); // name-vlaue pair
        if (vp[0] == name) // this was requested
        {
            return vp[1];
        }
    }
    return "x";
}

// Set cookie
function setPrefCookie(name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + value +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
    document.cookie = curCookie;
}

// Read cookie
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;
}

// Return the string padded to the left with the requested character.
String.prototype.padLeft = function(nLength, cChar)
{
    if( this.length < nLength )
    {
        var nExtraLen = nLength - this.length;
        var cTemp = "";
        for( var i = 0; i < nExtraLen; i++ )
        {
            cTemp += cChar;
        }
        cTemp += this;
    }
    else
    {
        cTemp = this;
    }
    return cTemp;
}

// Get elements by class name instead of ID.
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

// Function to get elements by attribute instead of ID / ClassName.
// [string attributeName],[string attributeValue],[boolean isCommaSeparatedList:false]
function getElementsByAttribute(attrN,attrV,multi)
{
    attrV=attrV.replace(/\|/g,'\\|').replace(/\[/g,'\\[').replace(/\(/g,'\\(').replace(/\+/g,'\\+').replace(/\./g,'\\.').replace(/\*/g,'\\*').replace(/\?/g,'\\?').replace(/\//g,'\\/');
    var multi=typeof multi!='undefined'?
            multi:
            false,
        cIterate=typeof document.all!='undefined'?
            document.all:
            document.getElementsByTagName('*'),
        aResponse=[],
        re=new RegExp(multi?
            '\\b'+attrV+'\\b':
            '^'+attrV+'$'),
        i=0,
        elm;
    while((elm=cIterate.item(i++)))
    {
        if(re.test(elm.getAttribute(attrN)||''))
            aResponse[aResponse.length]=elm;
    }
    return aResponse;
}

// Cross browser compatible "get element" function.
function returnObjById(id)
{
    if (document.getElementById)
        var returnVar = document.getElementById(id);
    else if (document.all)
        var returnVar = document.all[id];
    else if (document.layers)
        var returnVar = document.layers[id];
    return returnVar;
}

// Focus on specified element
function focus(id)
{
    if (returnObjById(id))
    {
	    returnObjById(id).focus();
	}
}

// Add a number of days to a date.
function addDays(myDate, days)
{
    return new Date(myDate.getTime() + days*24*60*60*1000);
}

// Function to return selected text
function getSelText()
{
    var txt = '';
    if (window.getSelection)
        txt = window.getSelection();
    //else if (document.getSelection)
    //    txt = document.getSelection();
    else if (document.selection)
        txt = document.selection.createRange().text;
    return txt;
}

// Function to populate value of FCK editor
function populateEditor()
{
	this.UpdateEditorFormValue = function()
	{
		for ( i = 0; i < parent.frames.length; ++i )
			if ( parent.frames[i].FCK )
				parent.frames[i].FCK.UpdateLinkedField();
	}
}

// Function to check width of browser and apply appropriate stylesheet
function setPagePreferences()
{
    // First set the text size, for which there is no auto-detect
    if (readPrefs('text') == "1")
        setStylesheet("text_medium.css","text");
    else if (readPrefs('text') == "2")
        setStylesheet("text_large.css","text");
        
    // Now set the screen width
    if (readPrefs('settings') == "user") // User defined settings
    {
        if (readPrefs('screen') == "0")
            setStylesheet("screen_800.css","screen");
        else if (readPrefs('screen') == "2")
            setStylesheet("screen_1280.css","screen");
    }
    else // Autodetect browser width for best fit
    {
        var theWidth = getBrowserWidth();
	    if (theWidth < 1024)
		    setStylesheet("screen_800.css","screen");
	    else if (theWidth >= 1280)
		    setStylesheet("screen_1280.css","screen");
		else
		    setStylesheet("none.css","screen");
    }
	return true;
};

// Function to remove the "default TP page" link if already set for this page
function checkPageDefault()
{
    if (readPrefs('default') != returnObjById("siteArea").innerHTML)
    {
        if (returnObjById("topDefaultPageLink")) returnObjById("topDefaultPageLink").style.display = "inline";
        if (returnObjById("topDefaultPageLink2")) returnObjById("topDefaultPageLink2").style.display = "inline";
        if (returnObjById("bottomDefaultPageLink")) returnObjById("bottomDefaultPageLink").style.display = "inline";
        if (returnObjById("bottomDefaultPageLink2")) returnObjById("bottomDefaultPageLink2").style.display = "inline";
        if (returnObjById("topDefaultPageOptions")) returnObjById("topDefaultPageOptions").style.display = "inline";
        if (returnObjById("topDefaultPageOptions2")) returnObjById("topDefaultPageOptions2").style.display = "inline";
        if (returnObjById("bottomDefaultPageOptions")) returnObjById("bottomDefaultPageOptions").style.display = "inline";
        if (returnObjById("bottomDefaultPageOptions2")) returnObjById("bottomDefaultPageOptions2").style.display = "inline";
    }
}

// Cross-browser function to get width of browser
function getBrowserWidth()
{
	if (window.innerWidth)
		return window.innerWidth;
	else if (document.documentElement && document.documentElement.clientWidth != 0)
		return document.documentElement.clientWidth;
	else if (document.body)
		return document.body.clientWidth;
	return 0;
};

// Function to change stylesheet of page
function setStylesheet(styleTitle, styleType)
{
	var currTag;
	if (document.getElementsByTagName)
	{
		for (var i=0; (currTag = document.getElementsByTagName("link")[i]); i++)
		{
			if (currTag.getAttribute("rel").indexOf("style") != -1 && currTag.id.indexOf(styleType) != -1)
			{
			    currTag.setAttribute("href","http://www.telecompaper.com/style/"+styleTitle);
			}
		}
	}
	return true;
};


// Function to add load listener
function addLoadListener(fn)
{
	if (typeof window.addEventListener != 'undefined')
		window.addEventListener('load', fn, false);
	else if (typeof document.addEventListener != 'undefined')
		document.addEventListener('load', fn, false);
	else if (typeof window.attachEvent != 'undefined')
		window.attachEvent('onload', fn);
	else
		return false;
	return true;
};

// Function to add event listener
function attachEventListener(target, eventType, functionRef, capture)
{
    if (typeof target.addEventListener != "undefined")
        target.addEventListener(eventType, functionRef, capture);
    else if (typeof target.attachEvent != "undefined")
        target.attachEvent("on" + eventType, functionRef);
    else
        return false;
    return true;
};

// Function to hide the status bar message
function hidestatus()
{
    window.status='';
    return true;
}

// Function to show the status bar message
function showstatus()
{
    window.status='';
    return true;
}

// Function to launch example newsletters in a new window
function Sample(Report)
{
    var windowName = "nieuwwindowWin";
    var windowOptions = "toolbar=no, location=no menubar=no resizable=no left=50 top=100, scrollbars=yes, width=680, height=500";
    var windowLocation = "samples/";
    
    switch (Report)
    {
        case "GT":
            windowLocation += "GermanTelecom.pdf";
            break;
        case "DT":
            windowLocation += "DutchTelecom.pdf";
            break;
        case "WET":
            windowLocation += "WesternEuropeanTelecom.pdf";
            break;
        case "EET":
            windowLocation += "EasternEuropeanTelecom.pdf";
            break;
        case "VOI":
            windowLocation += "VoIPInsider.pdf";    
            break;
        case "VOI":
            windowLocation += "VoIPInsider.pdf";    
            break;
        case "MPU":
            windowLocation += "MobilePaymentsUpdate.pdf";
            break;
        default:
            return false;
    }
    newwindow = window.open(windowLocation, windowName, windowOptions);
}

// Function to add an option to a select list
function addOption(selectbox, text, value)
{
    var optn = document.createElement("option");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}

// Function to trim whitespace from a string
function trim(str)
{
    str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--)
	{
		if (/\S/.test(str.charAt(i)))
		{
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}

// Function to show correct tab for multi-tabbed side boxes
function ShowTab(tabID)
{
    var tabStem = tabID.substring(0,tabID.length-1);
    var tabNum = tabID.substring(tabID.length-1);
    var color = ""
    for (var i=0; i<10; i++)
    {
        if (returnObjById(tabStem + "_head" + i))
        {
            color = returnObjById(tabStem + "_head" + i).style.borderTopColor;
            break;
        }
    }
    for (var i=0; i<10; i++)
    {
        if (returnObjById(tabStem + i))
            returnObjById(tabStem + i).style.display = "none";
        if (returnObjById(tabStem + "_head" + i))
            returnObjById(tabStem + "_head" + i).style.borderBottomColor = color;
    }
    if (returnObjById(tabID))
        returnObjById(tabID).style.display = "block";
    if (returnObjById(tabStem + "_head" + tabNum))
        returnObjById(tabStem + "_head" + tabNum).style.borderBottomColor = "#ffffff";
}

// Function to toggle the display of an element
function toggle(id)
{
    if (returnObjById(id))
    {
        if (returnObjById(id).style.display == "block")
            returnObjById(id).style.display = "none";
        else
            returnObjById(id).style.display = "block";
    }
}

//Function to return position of element on page in array [left,top]
function findPosition(oElement)
{
    if(typeof(oElement.offsetParent) != 'undefined')
    {
        for(var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent)
        {
            posX += oElement.offsetLeft;
            posY += oElement.offsetTop;
        }
        return [posX, posY];
    }
    else
        return [oElement.x, oElement.y];
}

//Function that sets autocomplete off for an element. Used to stop corruption partial page rendering 
//corruption of client form fields in Firefox.
function setAutoCompleteOff(id) 
{
    var elem = returnObjById(id);
    if(elem)
        elem.setAttribute('autocomplete', 'off');
}