

function isMac(){
	if( navigator && navigator.userAgent ){
		if( navigator.userAgent.indexOf("Mac") >=0  )
			return true;
	}//if
	return false;
}//fn

function isIE( version ){
	if( navigator && navigator.userAgent ){
		var ua=navigator.userAgent ;
		var idx=ua.indexOf( " MSIE "+version +"." );
		if( idx >=0 )
			return true;
	}//if
	return false;
}//fn

function storeCookie(key,val) { 
	var age =  100*24*3600 * 1000;	// ms in 100 days
	storeCookieKey( key, val, age, true );
}//storeCookie
	
function storeCookie(key,val,age,reloadPg){ 
	var domainData="; path=/";
	if( document.domain.indexOf(".independent.co.uk") > 0  )
		domainData="; domain=independent.co.uk; path=/"; 

	var expDate = new Date();
	var expTime = expDate.getTime()  + age;
	expDate.setTime( expTime );
	document.cookie = key +"="+ val + "; expires="+ expDate.toGMTString() + domainData ;
	
	
	if( reloadPg )
		window.location.reload();
}//storeCookie
	
function getCookieVal( key ){
	var cookiesText = document.cookie;
	var keyAt = cookiesText.indexOf(key);		//get position of key
 	//window.alert("Cookie Key: "+key+" is at "+ keyAt );
  if (keyAt == -1) return null;
	var sepAt = cookiesText.indexOf("=", keyAt );					
	if( sepAt == -1) return null;
	var endAt = cookiesText.indexOf(";", sepAt );					
	if (endAt == -1) 	  endAt = cookiesText.length; 			
	var val = cookiesText.substring( 1+ sepAt, endAt);
	if( val =="null" ) val=null;
	
	return val;
}//func

function setENavLink( nodeRef, chnFdrId, relUrl, storyId){
	nodeRef.inukChannel= chnFdrId;
	nodeRef.inukFolder= relUrl;
	nodeRef.inukStory= storyId;
	return false;
}//fn

function interceptClickBuyStory( nodeRef, premUrl, premQS, jumpUrl, cookieKey  ){
	var showSumms = document.showSummaries;
	if( cookieKey ){	
		var portfolioCookie = getCookieVal( cookieKey );
		showSumms = (portfolioCookie == null) || (portfolioCookie== "1") ;
	}//if
	displayClickBuyStory( nodeRef, showSumms, premUrl, premQS, jumpUrl);
	return false;
}//func

function displayClickBuyStory( nodeRef, showSummaries,  premUrl, premQS, jumpUrl  ){
	var doJump=false;
	if( premUrl.length > 0 ){
		if( showSummaries ){
			if( (jumpUrl=="[[ENAV]]") && nodeRef ){
				eNav( nodeRef.inukChannel, nodeRef.inukFolder, nodeRef.inukStor );
				doJump=false;
			}else
				doJump=true;
		}else{
			var btAppend = "$$$javascript:self.close();";    // ensure c&b back button functions properly.
			var styleQS = "&"+ document.styleKey +"="+ getCookieVal( document.styleKey );
			newWindow = window.open( premUrl + "?"+ premQS + styleQS + btAppend, "portfolio_window");
			newWindow.focus();
			doJump=false;
		}//else
	}else
		doJump=true;

	if( doJump )
		location.href=jumpUrl;
}//fn


function openPremXwordWin( xword, printable){		//xword is the crossword filename, printable is flag (true/false)
	var goDirect= ! document.showSummaries;
	var htmlPos = xword.lastIndexOf("cryptic.html");
	if( htmlPos > 0 )
		xword=xword.substring(0,htmlPos);

	htmlPos = xword.lastIndexOf("printable.html");
	if( htmlPos > 0 )
		xword=xword.substring(0,htmlPos);
	
	var url="/crosswords/crossword.jsp";
	if( goDirect )
		url = document.premXWordUrl;
	if( printable )
		url += "?printable=true";
   	else
	    url += "?cryptic=true";
	
	url += "&crossword="+ xword;
	url += "&cb_content_name="+ escape( "Cryptic Crossword: "+ xword );

	if( goDirect )
		xwordWin  = window.open(url,"xwordWin",'toolbar=1,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=750,height=750');
	else
		window.location=url;
	
	return false; //must return false to link
}//fn


function getDateString(){ 
	var months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");	
	var today  = new Date();
	var year  = today.getYear() , 	month = today.getMonth(),
	dayOfWk  = today.getDay(), dayOfMonth=today.getDate() ,
	hh  = today.getHours(),	mm = today.getMinutes();

	if(year < 1000)             year += 1900;         
	if (hh < 10 ) 	   hh= "0" + hh; 
	if (mm< 10 )   mm = "0" + mm; 

	var dateStr = dayOfMonth + " "+ months[month] + " "+ year;
	return dateStr;	
}//function


function openWin1 (url){	openNewWin(url,520,600);	}

function openNewWin(url, w, h){
	var atts =  'width='+w+',height='+h+',menubar=yes,scrollable=yes,resizable=no,toolbar=no,location=no,directories=no,status=0,toolbar=0,menubar=0,scrollbars=1,resizable=0';
	var newWindow = open (url, '_blank',atts);
	newWindow.focus ();
	if (document.layers)
		open (location, '_self')
}



DEFAULT_STYLE_KEY = "SMALL";
function setStyleSheet(){
	var key = getCookieVal( document.styleKey );
	if( key==null )
		key=DEFAULT_STYLE_KEY;
	var cssId = "css"+key;
	var css=getNode( cssId );			
	css.disabled=false;
	return css;
}//fn

function timeStampPage( refTime, timeStamp ){
		var debug = getCookieVal( document.debugKey );
		if( debug != "1" ) return;
		var requestTime  =  new Date( refTime ), nowTime=new Date();
		var nowTimeStamp = nowTime.getDate() + " / "+ ( nowTime.getMonth()+1)  + " / "+  new String( nowTime.getYear() ).substr(2);
		var diff = ( nowTime.getTime() - requestTime.getTime() ) / 1000;
		var ndIdx=getNode('indexContent');
		if( !ndIdx ) return;
	
		ndIdx.appendChild( timeStamp );
		timeStamp.style.visibility="visible";
		ndIdx.appendChild( document.createElement("br") );
		var nd=document.createTextNode( "Local time is "+ nowTimeStamp + " --- elapsed: " + Math.round( diff )  );
		ndIdx.appendChild(nd);
}//fn



function getNode( id ){	return document.getElementById( id );		}

function cutNode(id){ 
	var nd=getNode(id);
	if( nd && nd.parentNode )
		nd.parentNode.removeChild( getNode(id) );		
	return nd;
}//fn
	
function attachColsToParent( leftCol, rightCol, hdrCtr ){
					
	var articleHead = getNode("articleHead");		
	articleHead.parentNode.removeChild( articleHead );
	hdrCtr.appendChild( articleHead );
	articleHead.style.display="block";
	var c1=getNode("content1"),c2=getNode("content2");
	if(c1) leftCol.appendChild( c1.parentNode.removeChild( c1 ) );
	if(c2) rightCol.appendChild( c2.parentNode.removeChild( c2 ) );
}//fn

var linkLimit = 24, httpRE = /http[s]?:\/\/(\w+\.)+\w{2,}/ ;
var emailRE= /.*@.*\..*/;

function findLinkedTextNode(rootNode){
	var ref = null;
	if( ! rootNode.hasChildNodes() )
		return ref;
	for( var n=0; n < (rootNode.childNodes.length); n++ ){
		var node = rootNode.childNodes[n];
		if( node.nodeType == document.TEXT_NODE )
			ref = node;
		else if( node.nodeType == document.ELEMENT_NODE ){
			var nestedRef = findLinkedTextNode(node);
			if( nestedRef != null )
				ref = nestedRef;
		}//else-if
	}//for
	return ref;	
}//fn

function verifyParent( nd, ptId ){
	var v=false;
	while( nd.parentNode && !v ){
		nd=nd.parentNode;
		if(nd.id)
			v=(nd.id==ptId);
	}//wh
	return v;
}//fn


function fixLongLinks(){
	var links= document.links;
	for( l=0; l< links.length; l++ ){		
		var linkRef = links.item( l );
		if( ! (verifyParent(linkRef,'content1') || verifyParent(linkRef,'content2')) )
			continue;	
		if( httpRE.test( linkRef.href ) )
			linkRef.setAttribute("uk.co.independent.LINK_TYPE","HTTP");
		else if( emailRE.test( linkRef.href ) )
			linkRef.setAttribute("uk.co.independent.LINK_TYPE","MAIL");
		else
			continue;
		
		var textRef = findLinkedTextNode( links.item( l ) );
		if( textRef == null )		continue;
		linkRef.setAttribute("title",textRef.nodeValue);
				
		var refVal=textRef.nodeValue, reWritten="", newLen=0, splits=null;
		if( refVal.length <= linkLimit )		continue;
		var linkType = linkRef.getAttribute("uk.co.independent.LINK_TYPE");
		if( linkType == null )	continue;
		
		
		if( linkType == "HTTP" ){
			var httpEnd = refVal.indexOf("://");
			reWritten = refVal.substring( 0, httpEnd ),
			splits = refVal.substr( httpEnd ).split("/");
			for( var s=0; s<splits.length; s++ ){
				if( s> 0 )	reWritten += "/ ";
				reWritten += splits[s];
				if( splits[s].length > newLen )
					newLen=splits[s].length;
			}//for
	
		}else if ( linkType == "MAIL" ){
			var atPos = refVal.indexOf("@", 1 );	//cannot be first char
			if( atPos > 0 )
				reWritten = refVal.substring( 0, atPos+1 ) + "\n" + refVal.substring( atPos+1 );
			newLen = atPos;
			if( newLen < (refVal.length-atPos))
				newLen=refVal.length-atPos;
		}//else
		
		if( newLen > linkLimit ){	
			refVal=reWritten, reWritten="";
			splits = refVal.split(".");
			for( var s=0; s<splits.length; s++ ){
				if( s> 0 )	reWritten += ". ";
					reWritten += splits[s];
			}//for
		}//if
		
		textRef.nodeValue = reWritten;
	}//for
}//fn



var adList = "", debug="";
var copyableAtts = new Array("align","alt","border","color","class","className","clear","height","href","src","style","target","title","valign","vspace","width");

function copyNode( sourceNode, copyScriptTags){
	var newNode = null, type = sourceNode.nodeType;
	if( type == document.TEXT_NODE ){
		newNode = document.createTextNode( sourceNode.nodeValue );			
	}else if ( type == document.ELEMENT_NODE ){	
		if(  (sourceNode.tagName.toLowerCase() == "script")  &&  ! copyScriptTags  	)
			return null;

		newNode = document.createElement( sourceNode.tagName );	
		
		for( var a=0; a<copyableAtts.length; a++){
			var attName = copyableAtts[a];
			var attVal = sourceNode.getAttribute( attName );
			try{					
				if( (attVal != null) && (attVal.length > 0) )
					newNode.setAttribute( attName, attVal );
			}catch(err){ debug += ("\n"+ err.message +"\n attName: "+ attName ); }	
		}//for	
	}//elseif
	return newNode;
}//fn
	
	
function treeCopy( sourceRootNode,  destRootNode, copyScriptTags  ){
	if( sourceRootNode.nodeType != document.ELEMENT_NODE )
		return;
	for( var c=0; c< sourceRootNode.childNodes.length; c++ ){
		var node = sourceRootNode.childNodes[c]; 
		var copiedNode = copyNode( node, copyScriptTags );
		if( copiedNode != null ){
			if( node.nodeType == document.ELEMENT_NODE )
				treeCopy( node , copiedNode );
			try{
				destRootNode.appendChild( copiedNode );
			}catch(e){	alert( e.message + "\n when copying "+ copiedNode.nodeName + "\n into: "+ destRootNode.nodeName  );			}
			
		}//if
	}//for
		
}//fn

function appendAdData( adData ){			adList += adData;	}

function displayAd( destinationId, rootElNode ){
	var destNode = document.getElementById( destinationId );	
	if( (destNode != null) && (rootElNode != null ) )
		treeCopy( rootElNode, destNode, false );		
}//fn

function resizeAd( srcNode, tgtFrameId, tgtElId ){	
	
	displayAd( tgtElId, srcNode );
}//fn

function setAdHeight( contID, newHeight ){
	var contRef = document.getElementById( contID );
	contRef.style.height = newHeight+"px";
}//fn

function queryAds(){	alert("The following ads were called: \n"+ adList );	}

function rmvFirstPara( el ){		
	var nd=getFirstPara(el);
	if( nd )
		nd = el.removeChild( nd );
	return nd;	
}//fn

function getFirstPara(el){
	var nd=null,nodeName=null;
	for( var n=0; n< el.childNodes.length; n++ ){	
		nd = el.childNodes[n];
		nodeName= nd.nodeName.toLowerCase();
		if( (nodeName=="p") )
			break;		
		else
			nd = null;
	}//for
	return nd;	
}//fn


function modColLengths( c1, c2 ){
	if( ! c1.offsetHeight || ! c2.offsetHeight )	
		return false;	
	while( c1.offsetHeight < c2.offsetHeight ){
		var fp = rmvFirstPara( c2 ); 
		if( fp == null )
			break;
		c1.appendChild( fp );
	}//while	
}//fn


function getTextLength( el, chCt ){
	if( el.nodeType != document.ELEMENT_NODE ) return chCt;
	
	for( var t=0; t< el.childNodes.length; t++ ){
		var nd=el.childNodes[t];
		if( nd.nodeType == document.ELEMENT_NODE )
			chCt = getTextLength( nd, chCt );
		else if( nd.nodeType == document.TEXT_NODE )		
			chCt += nd.nodeValue.length;
	}//fr
	return chCt;
}//fn


function cutNpasteParas( cSrc, cDest, canSplit, cutAll ){
	if( cSrc.nodeType != document.ELEMENT_NODE ) return "NO ELEMENTS";
	var totCt=0, n=0, pCt=0, chCts=new Array( cSrc.childNodes.length );
	
	for( n=0; n< chCts.length; n++ ){
		var nd=cSrc.childNodes[n];
		if( "p" == nd.nodeName.toLowerCase() ){
			var ln=getTextLength( nd, 0 );
			chCts[pCt] = ln;
			totCt +=ln;
			pCt ++;
		}//if
	}//fr
	
	if( pCt >1 ){
		var hw= totCt/2, totCt=0;				
		for( n=0; n< pCt; n++ ){
			var firstPara = rmvFirstPara(cSrc);
			if( firstPara )
				cDest.appendChild( firstPara );
			totCt += chCts[n];
			if( !cutAll && (totCt >= hw) ) 
				break;
		}//fr
	}//if
	return pCt;
}//fn



function notifyEdsChoice( nodes, adData ){
	appendAdData( adData );
	if( ! nodes )	return;
	if( nodes.length > 0 )
		resizeAd( nodes[0], "edsLinksIF", "editorschoicelinks");
	if( nodes.length > 1 )
		resizeAd( nodes[1], "edsLinksIF", "editorschoicelinks");
	if( nodes.length > 2 )
		resizeAd( nodes[2], "edsLinksIF", "editorschoicelinks");
		
	var udCt =  ( getNode("relatedlinksIF")  ) ? 1 : document.ecCount;		
	document.ecCount -= udCt;	

	var edLinks = getNode("editoriallinks");	
	if( (document.ecCount == 0) && edLinks  )
		edLinks.style.visibility="visible";

}//fn

function showPicture( linkNd ){
	var winSrc = "/imagePop.jsp?imgUrl="+ escape( linkNd.href );	
	var newWin=window.open( winSrc,"popWin","left=100,top=100,width=600,height=420,scrollbars=0,toolbar=0,location=0,resizable=1");
	newWin.focus();
}//fn






