﻿// 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 cookie
function setCookie(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.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 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 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 - 2);
    jQuery("." + tabStem).removeClass('tab_active');
    jQuery("#" + tabID).addClass('tab_active');
    jQuery("." + tabStem + "_c").hide();
    jQuery("#" + tabID + "_c").show();
}

// 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');
}

function twitterCallback2(twitters) {
    var statusHTML = [];
    for (var i = 0; i < twitters.length; i++) {
        var username = twitters[i].user.screen_name;
        var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
            return '<br /><a href="' + url + '" class="tb">' + url + '</a>';
        }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
            return reply.charAt(0) + '<br /><a href="http://twitter.com/' + reply.substring(1) + '">' + reply.substring(1) + '</a>';
        });
        statusHTML.push('<li>' + status + ' <a href="http://twitter.com/' + username + '/statuses/' + twitters[i].id + '" class="tb">' + relative_time(twitters[i].created_at) + '</a></li>');
    }
    document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
}

function relative_time(time_value) {
    var values = time_value.split(" ");
    time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    delta = delta + (relative_to.getTimezoneOffset() * 60);

    if (delta < 60) {
        return 'less than a minute ago';
    } else if (delta < 120) {
        return 'about a minute ago';
    } else if (delta < (60 * 60)) {
        return (parseInt(delta / 60)).toString() + ' minutes ago';
    } else if (delta < (120 * 60)) {
        return 'about an hour ago';
    } else if (delta < (24 * 60 * 60)) {
        return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
    } else if (delta < (48 * 60 * 60)) {
        return '1 day ago';
    } else {
        return (parseInt(delta / 86400)).toString() + ' days ago';
    }
}
