// Adds email links via JS
////////////////////////////////////////////////////////////////////////
function insertContact (theName, linkText)
{	
	var theDomain = ('carringtongroup' + '.' + 'co.uk');
	
	theAddress = (theName + '&#064' + theDomain);
	if(linkText=='me'){
		linkText = theAddress;
	}
	document.write('<a href="mailto:' + theAddress +'">' + linkText + '<\/a>');
}


// Popup windows
////////////////////////////////////////////////////////////////////////
function popUp(URL)
{
	var w=500;
	var h=600;
	leftPos = (screen.width) ? (screen.width-w)/2 : 0;
	topPos = (screen.height) ? (screen.height-h)/2 : 0;
	popup = window.open(URL,'GoogleMap','height='+h+',width='+w+',menubar=0,scrollbars,resizable=0, status=0,titlebar=0,toolbar=0,left='+leftPos+',top='+topPos+'');
	popup.focus();
}


// JS to set login window bg text:
// Toby T 2007
////////////////////////////////////////////////////////////////////////
function setBackgroundImage (id, imageURL)
{
  if (document.layers)
    document[id].background.src = imageURL == 'none' ? null : imageURL;
  else if (document.all)
    document.all[id].style.backgroundImage = imageURL == 'none' ? 'none' : 'url(' + imageURL + ')';
  else if (document.getElementById)
    document.getElementById(id).style.backgroundImage = imageURL == 'none' ? 'none' : 'url(' + imageURL + ')';
}


// Events Management Functions
////////////////////////////////////////////////////////////////////////
function addEvent(elm, evType, fn, useCapture)
{
	if(elm.addEventListener){
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}else if (elm.attachEvent){
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	}else{
		elm['on' + evType] = fn;
	}
}
function getEvent()
{
	if(window.event) {
		return this.window.event;
	}else{
		return getEvent.caller.arguments[0];
	}
}


// Set value of input fields which need labelling.
// the toLabel key relates to <key>field in the input id
// value is used as the colour for field
// background image referenced input-<key>-bg.gif
////////////////////////////////////////////////////////////////////////
var toLabel = new Object();
toLabel['emailblu'] = 'blu';
toLabel['pwordblu'] = 'blu';
toLabel['emailgrn'] = 'grn';
toLabel['pwordgrn'] = 'grn';


// Functions for labelling
////////////////////////////////////////////////////////////////////////
function toggleInputBG()
{
	var oEvent = getEvent();
	var oTarget = (oEvent.target || oEvent.srcElement);
	//alert(oTarget.id);
	if(oTarget.id){
		for ( keyVar in toLabel ) {
			if( oTarget.id.indexOf(keyVar)==0){
				if(oEvent.type=="blur" && oTarget.value==''){
					//found key to image
					setBackgroundImage (oTarget.name, 'assets/templates/carrington/images/input-' + keyVar + '-bg.gif');
				}else if(oEvent.type=="focus"){
					//alert(oTarget.id);
					setBackgroundImage (oTarget.name, 'assets/templates/carrington/images/input-' + toLabel[keyVar] + '-bg.gif');
				}
			}
		}
	}
}


// ...
////////////////////////////////////////////////////////////////////////
function setInputs()
{
	// Label all the input text fields with background image
	for ( keyVar in toLabel ) {
		//alert(keyVar);
		var tt_input = document.getElementById(keyVar + 'field');
		if(tt_input){
			addEvent(tt_input, 'focus', toggleInputBG, false);
			addEvent(tt_input, 'blur', toggleInputBG, false);
			
			if(tt_input.value == '') {
				setBackgroundImage (keyVar + 'field', 'assets/templates/carrington/images/input-' + keyVar + '-bg.gif');
			}else{
				setBackgroundImage (keyVar + 'field', 'assets/templates/carrington/images/input-' + toLabel[keyVar] + '-bg.gif');
			}
		}
	}
}
addEvent(window, 'load', setInputs, false);




// show first one to begin and always show one (in the document flow, below the list) 
// http://bonrouge.com/br.php?page=togglit
////////////////////////////////////////////////////////////////////////
function switchNext2(el,tname,first) {
	var selcn="selected";
	var parent=el.parentNode;
	var tags=parent.getElementsByTagName(tname);
	var next=el.nextSibling;
	var last=parent.lastChild;
	while(last.nodeType != 1) last = last.previousSibling;
	while(next.nodeType != 1) next = next.nextSibling;
	next.style.display="none";
	if (first!=1){
		for (i=0; i<tags.length; i++) {
			var tohide=tags[i].nextSibling;
			while(tohide.nodeType != 1) tohide = tohide.nextSibling;
			if (tohide!=next){tohide.style.display="none";}
			tags[i].className=tags[i].className.replace(new RegExp(selcn+"\\b"), "");
			if (tags[i]==el){
				var rEx = new RegExp("(^|\\s)" + selcn + "(\\s|$)");
				if (rEx.test(tags[i].className)==false) {tags[i].className+=" "+selcn;}
			}
		}	
		var clone=next.cloneNode(true);
		clone.style.display="block";
		parent.removeChild(last);
		parent.appendChild(clone);
	}
	else {
		var firstone=tags[0].nextSibling;
		while(firstone.nodeType != 1) firstone = firstone.nextSibling;
		var clone=firstone.cloneNode(true);
		clone.style.display="block";
		if (last.innerHTML!=clone.innerHTML){parent.appendChild(clone);}
		var rEx = new RegExp("(^|\\s)" + selcn + "(\\s|$)");
		if (rEx.test(tags[0].className)==false) {tags[0].className+=" "+selcn;}
	}
}

function switchNextByIdAndTag2(el,tname) {
	if(document.getElementById(el)!=null){
		//element exists in page.
		clickers=document.getElementById(el).getElementsByTagName(tname);
		var ccn="clicker";
		for (i=0; i<clickers.length; i++) {
			clickers[i].className+=" "+ccn;
			clickers[i].onclick=function() {switchNext2(this,tname)}
			switchNext2(clickers[i],tname,1);
		}
	}else{
		return false;
	}
}

//addEvent(window, 'load', switchNextByIdAndTag2('marketgraphs','dt'), false);
window.onload=function()
{
	switchNextByIdAndTag2('marketgraphs','dt')
}


// Preload css/js images
////////////////////////////////////////////////////////////////////////
if (document.images)
{
  pic1= new Image(110,24); 
  pic1.src="assets/templates/carrington/images/input-grn-bg.gif"; 

  pic2= new Image(110,24); 
  pic2.src="assets/templates/carrington/images/input-blu-bg.gif"; 
  
  pic3= new Image(110,24); 
  pic3.src="assets/templates/carrington/images/input-emailblu-bg.gif"; 

  pic4= new Image(110,24); 
  pic4.src="assets/templates/carrington/images/input-pwordblu-bg.gif";

  pic5= new Image(110,24); 
  pic5.src="assets/templates/carrington/images/input-emailgrn-bg.gif"; 
  
  pic6= new Image(110,24); 
  pic6.src="assets/templates/carrington/images/input-pwordgrn-bg.gif";   
}


// Find rel="external" popups
// Nabbed from: http://www.thefutureoftheweb.com/blog/submit-a-form-in-ie-with-enter
////////////////////////////////////////////////////////////////////////
function findPopUps()
{
	var popups = document.getElementsByTagName("a");
	for (i=0;i<popups.length;i++)
	{
		if (popups[i].rel.indexOf("external")!=-1)
		{
			// attach popup behaviour
			popups[i].target = '_blank';
			//popups[i].onclick = doPopUp;
			// add info to title attribute to alert fact that it's a pop-up window
			popups[i].title = popups[i].title + " [Opens in new window]";
		}
		else if (popups[i].rel.indexOf("home page")!=-1)
		{
			// attach popup behaviour
			popups[i].target = '_top';
		}
	}
}
addEvent(window, 'load', findPopUps, false);


// Determine the domain of the supplied URL
////////////////////////////////////////////////////////////////////////
function determineDomain(currentURL)
{
	var protocolDelimiter = "://";
	var protocolIndex = currentURL.indexOf(protocolDelimiter);
	var serverIndex = currentURL.indexOf("/", protocolIndex + protocolDelimiter.length + 1); // Find closing slash (/) NB: Domain name must be at least 1 char!
	
	// Determine the domain
	var currentDomain = "";
	if(protocolIndex == -1) {
		// Could not find the protocol, pass back the full url
		currentDomain = currentURL;
	}
	else {
		// We have a valid protocol...
		if(serverIndex != -1) {
			// ...and we have an serverIndex endpoint
			currentDomain = currentURL.substring(protocolIndex + protocolDelimiter.length, serverIndex);
		} else {
			// ...but not a serverIndex endpoint, use the full length of the currentURL
			currentDomain = currentURL.substring(protocolIndex + protocolDelimiter.length);
		}
	}
	return currentDomain;
}


// Check each time a link is clicked if we are going to an external website
// (NB: this requires jQuery)
////////////////////////////////////////////////////////////////////////
$(document).ready(function() {
	$('a').click(function() {
		// Only check this link if it does NOT have the ignore class
		if(!$(this).hasClass("ignore"))
		{
			// Determine the domains of the current site, and target site
			var targetDomain = determineDomain(this.href);
			var currentDomain = determineDomain(location.href);
			
			// Look out for mailto: links, don't want to notify users if they click on one.
			var ignoreDomain = (targetDomain.indexOf("mailto:") == 0);
			if(!ignoreDomain)
			{
				// Determine the name of the website from its domain
				// NB: we will only alert the user if they are leaving the investments/accountancy website (not the group site)
				var website_name = "";
				if(currentDomain.toLowerCase().indexOf("carringtoninvestments") != -1) {
					website_name = "Carrington Investments";
				}
				else if(currentDomain.toLowerCase().indexOf("carringtonaccountancy") != -1) {
					website_name = "Carrington Accountancy";
				}
				
				// Now, if the domains do not match AND we have a valid website name we will warn the user they are leaving the site.
				//var debugtxt = "t: "+targetDomain+"\nc: "+currentDomain+"\ni: "+ignoreDomain+"\n";
				if(targetDomain != currentDomain && website_name != "") {
					if(!confirm("You are now leaving the "+website_name+" website.\n\nDo you wish to continue?")) {
						// User said no to confirmation message, do not allow link to execute.
						return false;
					}
				}
			}
		}
	});
});