// npage.js - default functions for all pages
// Last Modifed:    27/09/2011
// History:         V01.01  TRM Added validateInput function
//					V01.02	CDC Added getCustRef & validateData - used by online PW resets


var rootdir = '/web/';

function preloadImages()
{
	var loadedImages = new Array;
	for (i=0; i < preloadImages.arguments.length; i++)
	{
		loadedImages[i] = new Image();
		loadedImages[i].src = preloadImages.arguments[i];
	}
}

function swapImage(targetImage, newImageSrc)
{
	if(document.images)
	{
		if (targetImage && targetImage.src)
		{
			targetImage.src = newImageSrc;
		}
	}
}

function textsubmit()
{
	document.forum.submit();
}

function toggle()
{
	var a = toggle.arguments;
	var id = a[0];
	var ul = "div_" + id;
    var img = "img_" + id;
    var icon = "icon_" + id;
	var ulElement = document.getElementById(ul);
    var imgElement = document.getElementById(img);
    var iconElement = document.getElementById(icon);
	if (ulElement)
	{
		if (ulElement.className == "closed")
		{
			ulElement.className = "open";
			if (imgElement)
				if (a.length > 2)
					imgElement.src = a[2];
				else
					imgElement.src = rootdir + "images/hide.gif";
			if (iconElement)
				iconElement.src = rootdir + "images/tsc_" + id + "_green.jpg";
		}
		else
		{
			ulElement.className = "closed";
			if (imgElement)
				if (a.length > 1)
					imgElement.src = a[1];
				else
					imgElement.src = rootdir + "images/more.gif";
			if (iconElement)
				iconElement.src = rootdir + "images/tsc_" + id + "_grey.jpg";
			window.location = "#" + id;
        }
    }
}
function toggle2(id)
{
	ul = "div_" + id;
    img = "img_" + id;
    icon = "icon_" + id;
	ulElement = document.getElementById(ul);
    imgElement = document.getElementById(img);
    iconElement = document.getElementById(icon);
	if (ulElement)
	{
		if (ulElement.className == 'closed')
		{
			ulElement.className = "open";
			imgElement.src = rootdir + "images/helpless.gif";
			if (iconElement)
				iconElement.src = rootdir + "images/tsc_" + id + "_green.jpg";
		}
		else
		{
			ulElement.className = "closed";
			imgElement.src = rootdir + "images/helpmore.gif";
			if (iconElement)
				iconElement.src = rootdir + "images/tsc_" + id + "_grey.jpg";
        }
    }
}
var mmwindow;
function MM_openBrWindow(theURL,winName,features) { //v2.0
	mmwindow = window.open(theURL,winName,features);
	if (window.focus) {mmwindow.focus();}
}
function locationcheck(oloc, nloc)
{
	// remove http(s)://domain part
	s = oloc.indexOf('//', 0);
	if (s > 0)
	{
		s = oloc.indexOf('/', s+2);
		oloc = oloc.substring(s, oloc.length);
	}
	return (oloc == nloc);
}
function randomString(string_length) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}
function pageload()
{
	// this should only trigger for a framed page
//	alert(window.location.search);
}

function exporttext()
{
	var text = document;
	print(text);
}
var newwindow;
function pophelp(url)
{
	newwindow = window.open(url,'name','height=200,width=300');
	if (window.focus) {newwindow.focus();}
}

function pophelp2(url)
{
	newwindow = window.open(url,'name','height=600,width=640,scrollbars=yes');
	if (window.focus) {newwindow.focus();}
}

var digitalwin;
function popdigital(site, path)
{
	var cl = "";
	cookie = getCookie("session");
	if (cookie != "" && cookie.substring(0, 4) != "you ")
		cl = "&cl=1";

	if (site == "d")
		url = 'http://sharecentre.digitallook.com/cgi-bin/digitalcorporate/sharecentre/security.cgi?ticker=' + path + cl;
	else
		url = site + path;
	digitalwin = window.open(url,'digital');
	if (window.focus) {digitalwin.focus();}
}

function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return "";
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}
function setCookie (name, value, expires, path, domain, secure) {
	document.cookie = name + "=" + escape(value) +

//	((expires) ? "; expires=" + expires : "") +

	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");

}

function putFocus(formInst, elementInst) {
	if (document.forms.length > 0) {
		document.forms[formInst].elements[elementInst].focus();
	}
}

function trash(limit)
{
	if (document.forms.length > 0)
	{
		form = document.getElementById('subtriggers')
		for (i = 0; i < form.elements.length; i++)
		{
			el = form.elements[i].name;
			if (el.substring(0,3) == limit+"_")
			{
				form.elements[i].value = "";
			}
		}
		form.submit();
	}
}
function checkselected(add_list)
{
	if (add_list.item.value == false )
	{
		alert('Please Select an option.')
		return false;
	}
	else
return true;
}
function checkrequiredjoin(which) {
	formx = document.forms[0];
	pw1 = formx.requiredpassword.value;
	pw2 = formx.requiredpasswordcheck.value;
	var invalid = " "; // Invalid character is a space
	var minLength = 8; // Minimum length
	var pass=true;

	if (document.images) {
		for (i=0;i<which.length;i++) {
			var tempobj=which.elements[i];
			if (tempobj.name.substring(0,8)=="required") {
				if (((tempobj.type=="text"||tempobj.type=="password"||tempobj.type=="textarea")&&
						tempobj.value=='')||(tempobj.type.toString().charAt(0)=="s"&&
						tempobj.selectedIndex==0)) {
					pass=false;
					break;
				}
			}
		}
	}

	if (!pass) {
		shortFieldName=tempobj.name.substring(8,30).toUpperCase();
		alert("Please make sure the "+shortFieldName+" field was properly completed.");
		return false;
	}
	else
		if (formx.requiredpassword.value.length < minLength) {
		alert('Your password must be at least ' + minLength + ' characters long. Try again.');
		return false;
	}
	else
		if (formx.requiredpassword.value.indexOf(invalid) > -1) {
		alert("Sorry, spaces are not allowed.");
		return false;
	}
	else
	if (pw1 != pw2) {
		alert ("\nYou did not enter the same new password twice. Please re-enter your password.")
		return false;
	}
	else
		return true;
}
function checkrequiredapply(which) {
	formx = document.forms[0];
	var invalid = " "; // Invalid character is a space
	var minLength = 8; // Minimum length
	var pass=true;
	if (document.images) {
		for (i=0;i<which.length;i++) {
			var tempobj=which.elements[i];
			if (tempobj.name.substring(0,8)=="required") {
				if (((tempobj.type=="text"||tempobj.type=="password"||tempobj.type=="textarea")&&
						tempobj.value=='')||(tempobj.type.toString().charAt(0)=="s"&&
						tempobj.selectedIndex==0)) {
					pass=false;
					break;
				}
			}
		}
	}

	if (!pass) {
		shortFieldName=tempobj.name.substring(8,30).toUpperCase();
		alert("Please make sure the "+shortFieldName+" field was properly completed.");
		return false;
	}
	else
		return true;
}
/*
function rndad()
{
	var a = rndad.arguments;
	var r = Math.round(Math.random()*(a.length-1));
	if (r+1 == a.length)
		r = r-1;
	var link = a[0];
	m = link.indexOf("|")
	if (m >= 0)
	{
		alt = link.substring(m+1,link.length);
		link = link.substring(0,m);
	}
	else
		alt = "";
	if (link == "")
		document.write('<img src="' + rootdir + 'images/' + a[r+1] + '" border="0" alt="' + alt + '">');
	else
	{
		if (link.indexOf(".pdf") > 0)
			tar = ' target="_blank"';
		else
			tar = '';
		document.write('<a href="' + link + '"' + tar + '><img src="' + rootdir + 'images/' + a[r+1] + '" border="0" alt="' + alt + '"></a>');
	}
}
function rndpick()
{
	var r = Math.round(Math.random()*6);
	if (rndpick.arguments.length == 0)
		document.write('<table width="100%" cellpadding="0" cellspacing="2">');
	switch (r)
	{
	case 0: return "123";
	case 1: return "231";
	case 2: return "312";
	case 3: return "321";
	case 4: return "213";
	case 5: return "132";
	}
	return "132";
}
// strval, strpos, link, graphic_link, ...
function rndad2()
{
	var r, p, tar;
	var a = rndad2.arguments;
	p = a[1];
	if (a[0].length < p)
		p = a[0].length - 1;
	if (p < 0)
		return;
	document.write('<tr><td>')
	var r = a[0].substring(p,p+1)*1 + 2;
	var link = a[2];
	m = link.indexOf("|")
	if (m >= 0)
	{
		alt = link.substring(m+1,link.length);
		link = link.substring(0,m);
	}
	else
		alt = "";

	if (r >= a.length)
		r = a.length - 1;
	if (link == "")
		document.write('<img src="' + rootdir + 'images/' + a[r] + '" border="0" alt="' + alt + '">');
	else
	{
		if (link.indexOf(".pdf") > 0)
			tar = ' target="_blank"';
		else
			tar = '';
		if (link.substring(0, 1) != '/'	&& link.substring(0,11) != 'javascript:')
			link = '/webp/' + link;
		document.write('<a href="' + link + '"' + tar + '><img src="' + rootdir + 'images/' + a[r] + '" border="0" alt="' + alt + '"></a>');
	}
	document.write('</td></tr>');
}
function rndad3()
{
	var r, p, tar;
	var a = rndad3.arguments;
	p = a[1];
	if (a[0].length < p)
		p = a[0].length - 1;
	if (p < 0)
		return;
	var r = a[0].substring(p,p+1)*1 + 2;
	var link = a[2];
	m = link.indexOf("|")
	if (m >= 0)
	{
		alt = link.substring(m+1,link.length);
		link = link.substring(0,m);
	}
	else
		alt = "";
	if (r >= a.length)
		r = a.length - 1;
	if (link == "")
		document.write('<img src="' + rootdir + 'images/' + a[r] + '" border="0" alt="' + alt + '">');
	else
	{
		if (link.indexOf(".pdf") > 0)
			tar = ' target="_blank"';
		else
			tar = '';
		document.write('<a href="' + link + '"' + tar + '><img src="' + rootdir + 'images/' + a[r] + '" border="0" alt="' + alt + '"></a>');
	}
}
function rndadend()
{
	document.write('</table>');
}
*/
function performance()
{
	cookie = getCookie("session");
	if (cookie != "" && cookie.substring(0, 4) != "you ")
	{
		url = 'http://sharecentre.digitallook.com/cgi-bin/digitalcorporate/sharecentre/share_filter.cgi?'
		var newwindow = window.open(url,'filter');
		window.location.href = "/webp/v_spick.htm";
		if (window.focus && newwindow) {newwindow.focus();}
	}
	else
	{
		window.location.href = "/webp/byperformance.htm";
	}
}
function salchange()
{
var ulElement = document.getElementById("sal_other");
var ival = document.details.salutation.options[document.details.salutation.selectedIndex].value;
	if (ival == "Other")
	{
		ulElement.className = "xopen";
	}
	else
	{
		ulElement.className = "xclosed";
	}
}
function radiodupyes()
{
var ulElement = document.getElementById("dnotes");
	ulElement.className = "xopen";
	ulElement = document.getElementById("duplicate_fao");
	ulElement.focus();
}
function radiodupno()
{
var ulElement = document.getElementById("dnotes");
	ulElement.className = "xclosed";
}
function currentyears()
{
var ulElement = document.getElementById("prev_ad");
var years = document.getElementById("years");
	if (years.value != "" && years.value < 3)
		ulElement.className = "xopen";
	else
		ulElement.className = "xclosed";
}
function currentmonths()
{
var ulElement = document.getElementById("prev_ad");
var years = document.getElementById("years");
var months = document.getElementById("months");
	if (years.value != "" && years.value < 3)
		ulElement.className = "xopen";
	else
		ulElement.className = "xclosed";
}
function showdate()
{
	var now = new Date();
	var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
	var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
	function fourdigits(number)	{
	return (number < 1000) ? number + 1900 : number;
								}
	today =  date + " " + months[now.getMonth()] + " " + (fourdigits(now.getYear())) ;
	document.write( today );
}
var isNS4 = (navigator.appName=="Netscape")?1:0;
function validkeys()
{
	if(!isNS4)
	{
		if (event.keyCode == 38 || event.keyCode == 60 || event.keyCode == 62)
			event.returnValue = false;
	}
	else
	{
		if (event.which == 38 || event.which == 60 || event.which == 62)
			return false;
	}
}
function xreplace(checkMe,toberep,repwith)
{
	var temp = checkMe;
	var i = temp.indexOf(toberep);
	while(i > -1)
	{
		temp = temp.replace(toberep, repwith);
		i = temp.indexOf(toberep, i + repwith.length);
	}
	return temp;
}

function debit_card_refresh()
{
	document.payerauth.submit();
}

function dosubmit(name)
{
	var form = document.getElementById(name);
	for (i=0; i < form.elements.length; i++)
	{
		var el = form.elements[i]
		if (el.type == 'text')
			el.value = xreplace(el.value, "&", "*and*");
	}
	return 0;
}

// special check for homepage redirection
if (locationcheck(window.location.href, "/webp/hometop.htm"))
{
//	if (cookie == "telegraph" && locationcheck(window.location.href, "/webp/hometop.htm"))
	cookie = getCookie("partner");
	if (cookie != "")
		window.location.href = '/webp/' + cookie + '.htm';
}

// special check for forms page redirection
cookie = getCookie("partner");
if (cookie == "bgi" && locationcheck(window.location.href, "/webp/forms.htm"))
{
	window.location.href = '/webp/bgi_forms.htm';
}

function initial()
{
}

//  Added Rik October 2008 for Web Trader
function wopen(url, name, w, h)
{
w += 32;
h += 96;
 var win = window.open(url,
  name,
  'width=' + w + ', height=' + h + ', ' +
  'location=no, menubar=no, ' +
  'status=yes, toolbar=no, scrollbars=yes, resizable=yes');
 win.resizeTo(w, h);
 win.focus();
}


// Clearforms and numbersonly added for V3 Debit Cards June 2009

function clearForms()
{
  var i;
  for (i = 0; (i < document.forms.length); i++) {
    document.forms[i].reset();
  }
}

// http://javascript.internet.com Copyright 1999 Idocs, Inc. http://www.idocs.com //

function numbersonly(myfield, e, dec) {
  var key;
  var keychar;

  if (window.event)
    key = window.event.keyCode;
  else if (e)
    key = e.which;
  else
    return true;
  keychar = String.fromCharCode(key);

  // control keys
    if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
    return true;

  // numbers
  else if ((("0123456789").indexOf(keychar) > -1))
    return true;

  // decimal point jump
  else if (dec && (keychar == ".")) {
    myfield.form.elements[dec].focus();
    return false;
  } else
    return false;
}

function fund_search_submit() {

/*
	fund-house
	ima
	fund-size
	fund-age
	quartile-ranking1
	quartile-ranking2
	yield
	performance-returns
	income								x
	accumulation						x
	initial-charge
	ter
	amc
	no-dealing-permission		x
	isa-eligible							x
*/

	var dotheredirect = true;

	try {
		if ( document.getElementById('P120').checked ){
			//	need to check if any other fields have been populated so we know where to re-direct to if nessisary..

			if (document.getElementById( 'fund-house' ).value != 1 ) dotheredirect = false
			if (document.form1.ima.value != 1) dotheredirect = false
			if (document.getElementById( 'fund-size' ).value != 1) dotheredirect = false
			if (document.getElementById( 'fund-age' ).value != 1) dotheredirect = false
			if (document.getElementById( 'quartile-ranking1' ).value != 1) dotheredirect = false
			if (document.getElementById( 'quartile-ranking2' ).value != 1) dotheredirect = false
			if (document.form1.yield.value != 1) dotheredirect = false
			if (document.getElementById( 'performance-returns' ).value != 1) dotheredirect = false
			if (document.form1.income.checked) dotheredirect = false
			if (document.form1.accumulation.checked) dotheredirect = false
			if (document.getElementById( 'initial-charge' ).value != 1) dotheredirect = false
			if (document.form1.ter.value != 1) dotheredirect = false
			if (document.form1.amc.value != 1) dotheredirect = false
			if (document.getElementById( 'no-dealing-commission' ).checked) dotheredirect = false
			if (document.getElementById( 'isa-eligible' ).checked) dotheredirect = false

			if ( dotheredirect ) {
				document.location.href="/cgi-bin/oicgi.exe/inet_raccount?function=platinum_120&param1=full_platinum_list";
			} else {
				document.form1.submit();
			}
		} else {
			document.form1.submit();
		}
	} catch(e) {
		//	didn't find the p120 item on the form.. ignore everything..
	}
}

function validateInput(checkType, fieldName) {
	var errortext = ''
    var reportError = false;
    switch (checkType) {
        case 'email':
            if (document.getElementById(fieldName).value.length > 0) {
                var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
                var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
                var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
                var sQuotedPair = '\\x5c[\\x00-\\x7f]';
                var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
                var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
                var sDomain_ref = sAtom;
                var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
                var sWord = '(' + sAtom + '|' + sQuotedString + ')';
                var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
                var sLocalPart = sWord + '(\\x2e' + sWord + ')*';
                var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
                var sValidEmail = '^' + sAddrSpec + '$'; // as whole string

                if (!RegExp(sValidEmail).test(document.getElementById(fieldName).value)) {
                    reportError = true;
                    errortext = 'The address you have provided is not in a valid format';
                }
            }
            else
            {
				reportError = true;
				errortext = 'We require a valid email address to ensure you receive our services electronically';
			}
    }

    // Sets the text colour to RED if failed check and sets focus back to itself
    // open the help tag
    // add a message showing that this fields is required / invalid
    if (reportError == true) {
		if (document.getElementById(fieldName).value.length > 0) {
	        document.getElementById(fieldName).style.color = 'RED';
		}
		else
		{
			document.getElementById(fieldName).style.color = 'BLACK';
		}
        document.getElementById(fieldName).focus();
        try{
        	document.getElementById('div_item1').className = 'xopen'
        	document.getElementById('div_email_error').innerHTML = '<p style="color: #FF0000; margin-top: 0px; padding-top: 0px; margin-bottom: 5px;">' + errortext + '</p>'
		}
		catch(e){
		}
    }
    else {
        document.getElementById(fieldName).style.color = 'BLACK';
        try{
        	document.getElementById('div_email_error').innerHTML = ''
		}
		catch(e){
		}
    }
    return reportError
}

function getCrn(){

	try{
		var clientno = document.getElementById('client').value;
	} catch(e){
		//alert(e);
	}
	try{
		var request = document.getElementById('request').value;
	} catch(e){
		//alert(e);
	}
	if (request == '') {
		request = "password"
	}

	var url = "/cgi-bin/oicgi.exe/inet_raccount?function=loginproblem&area=" + request + "&client=" + clientno;
	document.location.href = url;
}

function getCustRef(){
	try {

		var custref = document.getElementById('custrefinp').value;
		document.formrst.custref.value = custref;
		var clientno = document.getElementById('client').value;
		document.formrst.action.value = "cust_resets";
		document.formrst.area.value = 'password';

	} catch(e) {
		alert(e);
	}
	
	document.formrst.submit();
}

function validateData(){

	try{
		document.formrst.client.value = escape( document.formrst.client.value );
	} catch(e) {
		//alert(e);
	}

	var pCode1 = document.getElementById('pcode1').value;
	var pCode2 = document.getElementById('pcode2').value;
	var request = document.getElementById('request').value;
	var clientno = document.getElementById('client').value;
	//var username = document.getElementById('username').value;

	try {
		var mem1 = document.getElementById('f1').value;
		var mem2 = document.getElementById('f2').value;
		var mem3 = document.getElementById('f3').value;

		var memFields = document.getElementById('fields').value;

		alert("mem 1 :" + mem1 + " mem 2 :" + mem2 + " mem 3 :" + mem3);

	} catch(e) {
		alert(e);
	}
	
	document.formrst.action.value = "validate";
	document.formrst.submit();


}

function optionspagesubmit(){
	var submit = true;
	if ( validateInput( 'email', 'email') ) {
		submit = false;
	}
	return submit
}


