
//bUsaNoFloat: for wider pages
//bGoThemeSamePage: stay on same page when changing theme
var D=document, W=window, L=W.location, StateAbbr, aCookies, bKT, aErrScr, bSH, bDev, //bSerpRef, 
	oGrayDiv, oUKMsg, PageH, LoadTryNo=1, ResBase='', aD=[];
var E, EvSrc, Gec, Op, Ns, Saf, IE7Q, Nav, IEVer, FFVer, Quirks, Chrome, IEMob, SEQ, bLife, bHC, bSHNoUK;

//------------------------------------------------------------------------
//Results page part

function InitSH(){
//global params
var Host=L.hostname;

//bDev=(L.search.indexOf("test=1")!=-1);
if (Host.indexOf('.blogspot.com')!=-1) ResBase='htt'+'p://ww'+'w.auto-insu'+'rance-mate.com';
ResBase+='/commonres/';

if (Host.indexOf('.mylifeinsuranceplace.com')!=-1){
	bLife=true; return;
	}
bSHNoUK=(Host=='www.insuremyauto.co.uk');
ni_zc=getQueryStringVariable('zip');
if (!W.ni_lnt_id) ni_lnt_id=null;
ni_var1=Host;
if (ni_var1.substr(0, 4)=='www.') ni_var1=ni_var1.substr(4);
}

//------ Utils

function getbyid(id){return D.getElementById(id);}

function getat(o, at){
var val=o.getAttribute(at); if (Op && val=='') val=null; return val;
}

function setat(o, at, val){
if (Op && val==null) val=''; o.setAttribute(at, val);
}

function trim(str){
return((" "+str).replace(/^\s*([\s\S]*\S+)\s*$|^\s*$/,"$1"));
}

function EventInit(e){
E=(!Gec ? event : e); EvSrc=E[Gec ? 'target' : 'srcElement'];
if (Ns && EvSrc.nodeType==3) EvSrc=EvSrc.parentNode;
}

function InitUA(){
//This is the main InitUA()!

IEVer=0; FFVer=0; Nav=W.navigator.userAgent; 
Gec=(Nav.indexOf('Gecko')!=-1); 
Saf=(Nav.indexOf(' AppleWebKit/')!=-1 && Nav.indexOf(' Safari/')!=-1);
Op=(Nav.indexOf('Opera')!=-1); //Ns=(Gec && Nav.indexOf('Netscape')!=-1); 
Chrome=(Saf && Nav.indexOf(' Chrome/')!=-1);
Quirks=(D.compatMode=='BackCompat');

if (!Gec && !Op && !Saf){
	if (D.documentMode){
		IEVer=D.documentMode; if (IEVer==5) IEVer=6;
		}
	else{
		if (Nav.match(/ MSIE (\d+)/)) IEVer=RegExp.$1;
		if (IEVer==7 && Quirks) IE7Q=true; //IEVer=6; ?!
		}
	if (Nav.indexOf('IEMobile')!=-1) IEMob=true;
	}
else if (Gec && Nav.match(/Firefox\/(\d+)/)) FFVer=RegExp.$1;

SetBodyCls();
} 

function SetBodyCls(){
var Cls="";

if (Gec) Cls+=" FF"+(FFVer ? " FF"+FFVer : "");
if (Saf) Cls+=" Saf"+(Chrome ? " Chrome" : "");
if (IEVer) Cls+=" IE"+(" IE"+IEVer);
if (Quirks) Cls+=" Quirks";
//else if (Op) Cls+=" Op";

if (Cls) D.body.className+=Cls;
}

function DelCookie(Name, Path){
D.cookie=Name+"=;expires=Mon, 26 Jul 1997 05:00:00 GMT;path="+(Path ? Path : "/");
}

function GetPosRoot(){
return (D.getElementsByTagName((D.compatMode=='BackCompat') ? 'BODY' : 'HTML')[0]);
}

function AbsPos(O, Parent){
var X=0, Y=0, Next;

Next=O; if (Parent==null) Parent=D;
while (Next!=null && Next!==Parent){
	Y+=Next.offsetTop; X+=Next.offsetLeft; Next=Next.offsetParent;
	}
return [X, Y];
}

function ScrollTo(O, Where, NoFocus){
//Where={top, bottom, middle}
var Pos, Y, ObjH=O.offsetHeight, WinH=D.body.clientHeight, oRoot=GetPosRoot();

Pos=AbsPos(O); Y=Pos[1];

if (Where==null){
	if (Y<oRoot.scrollTop) Where='top';
	else if (Y+ObjH>oRoot.scrollTop+WinH) Where='bottom';
	}

if (Where=='middle'){
	if (ObjH>WinH) Where='top';
	else W.scrollTo(0, Y-Math.round((WinH-ObjH)/2));
	}
if (Where=='top') W.scrollTo(0, Y-1);
else if (Where=='bottom') W.scrollTo(0, Y+ObjH-WinH);

if (NoFocus!=true) W.focus(); return false;
}

function SetCookie(Name, Value, Time, Path){
var Res;

Value=Value.toString(); if (Value=="") Time=-1;
if (Time==null) Time=3600*24*30*3; //3 months
if (Path==null) Path="/";

Res=Name+"="+Value+
	(Time!=0 ? ";expires="+_CookieDate(Time) : "")+";path="+Path;
D.cookie=Res; return false;
}

function _CookieDate(Time){
var DT=new Date();

if (Time!=null){
	End=new Date(Date.UTC(DT.getUTCFullYear(), DT.getUTCMonth(),
		 DT.getUTCDate(), DT.getUTCHours(), DT.getUTCMinutes(),
		 DT.getUTCSeconds())+Time*1000);
	}
else End=DT;
return End.toGMTString();
}

function GetCookies(){
if (aCookies==null) aCookies=ReadCookies();
}

function ReadCookies(){
var Ck=D.cookie, i, Crumb, Len, Cookies; 

if (!Ck) return [];
Ck=Ck.split('; '); Len=Ck.length; Cookies=new Array(Len);

for (i=0; i<Len; i++){
	Crumb=Ck[i].split("="); 
	if (Crumb.length==1) continue;
	Cookies[Crumb[0]]=unescape(Crumb[1].replace(/\+/g, ' '));
	}
return Cookies;
}

//------ End - Utils

function ShowGeoTextInit(){

AddFormStyles();
if (W.CountryId==1 && !aCookies['showus'] && !W.bSHNoUK){
	AddUKStyles(); ShowUKMsg();
	}

if (!W.ni_ad_client){
	//Just select state
	if (W.bSH_AutoState){
		var F=FindForm();
		if (F && StateAbbr) F.statecode.value=StateAbbr;
		}
	return;
	}

return true;
}

function ShowGeoText(bAuto){
var Text='', State, Pretext, F, lnt_id, ImgCountry, aUKData, FlagLink;

//setTimeout("SendDebug()", 2000);
if (!ShowGeoTextInit()) return;
F=FindForm(); ImgCountry='usa'; 
//Debug("ShowGeoText: "+(bAuto ? "auto" : "manual"));

if (bAuto){
	Pretext="Dear Customer, We value your business and do our best to save your time and efforts. Our system automatically identified you as a ";
	
	if (StateAbbr!='' && StateAbbr!='-'){
		State=(W.USState ? USState : (F ? GetSelOption(F.statecode, StateAbbr) : 'USA'));
		Text=Pretext+"resident of "+State+". The Top Providers that you see below are delivered based on this information. If you are not a resident of "+State+", please select another state to see relevant offers.";
		}
	else if (StateAbbr=='' || StateAbbr=='-'){
		var EndText="select your state to see the Top Providers for your area.";
		var AfterText='If you are a resident of the USA, please '+EndText;
		
		if (StateAbbr==''){
			if (W.CountryId==1){
				aUKData=GetUKData(); ImgCountry='uk'; FlagLink='<A HREF="'+aUKData[0]+'" Target=_blank';
				Text=Pretext+" resident of UK. Please "+FlagLink+">click here</A> for "+aUKData[1]+
					" insurance quotes in UK. "+AfterText;
				}
			else{
				Text=Pretext+"non-resident of the USA. Unfortunately we don't have relevant providers for your place of residence. "+AfterText;
				}
			}
		else Text=Pretext+'resident of the USA. Please '+EndText;
		}
	}

if (Text){
	var bNoFloat=(W.bUsaNoFloat); //  && IEVer==6 // && D.all[0].data.toLowerCase().indexOf('strict.')!=-1
	var DivSt='border:1px dotted black;text-align:justify;margin-bottom:15px;margin-top:7px;color:black;font:11px Arial;';
	var ImgPath=ResBase+'images/'+ImgCountry+'-flag-sh.png';
	
	if (bNoFloat){ //IE6 strict wide pages: the bug with disappearing text
		D.write('<DIV Style="'+DivSt+'height1:38px;padding:7px 10px 7px 80px;background: white url('+
			ImgPath+') no-repeat 10px 10px;position:relative;" Id=FlagDiv>'+
			(!FlagLink ? '' : FlagLink+' Class=NoFloat></A>')+
			Text+'</DIV>');
		}
	else{
		D.write('<DIV Style="'+DivSt+'background-color:white;padding:7px 10px 10px 10px;" Id=FlagDiv>'
			+(!FlagLink ? '' : FlagLink+'>')
			+'<Img Src="'+ImgPath+'" ALIGN="left" Style="margin-right:12px;margin-top:3px;width:58px;height:35px;border:0;">'
			+(!FlagLink ? '' : '</A>')
			//This last div makes sure the usa image does not overlap the div's border
			+Text+'<Div Style="clear:left;font-size:0px;"></DIV></DIV>');
		}
	
	}

if ((StateAbbr!='' && StateAbbr!='-') || ni_zc){
	//Only for 1 account
	if (ni_ad_client==2667){
		lnt_id=getQueryStringVariable('loantype');
		if (lnt_id) SetCookie('user_lnt_id', lnt_id);
		else{
			lnt_id=aCookies['user_lnt_id'];
			if (!lnt_id) lnt_id=(W.ni_lnt_id ? W.ni_lnt_id : 1); //default
			}
		ni_lnt_id=lnt_id; F.loantype.value=lnt_id;
		}
	else ni_lnt_id=null;

	if (F && StateAbbr){
		F.statecode.value=StateAbbr; //Debug("OK: "+StateAbbr);
		}
	ShowProviders();
	}

if (!F) setTimeout('SH_FinishForm()', 250);
}

function SH_FinishForm(){
var F=FindForm();

if (!F){
	setTimeout('SH_FinishForm()', 250); return;
	}
F.statecode.value=StateAbbr; //Debug("SH_FinishForm: "+StateAbbr);
if (ni_ad_client==2667) F.loantype.value=ni_lnt_id;
FixStates();
}

function FindForm(){
var aForms, i, F;

aForms=D.getElementsByTagName('FORM'); 
for(i=0; i<aForms.length; i++){
	F=aForms[i];
	if (F.statecode) return F;
	}
return null;
}

function GetSelVal(Sel, O){
var aOpt=Sel.options, L=aOpt.length, i;
for(i=0; i<L; i++){if (aOpt[i].firstChild.data==O) return aOpt[i].value;}
return null;
}

function GetSelOption(Sel, Val){
var aOpt=Sel.options, L=aOpt.length, i;
for(i=0; i<L; i++){if (aOpt[i].value==Val) return aOpt[i].firstChild.data;}
return null;
}

function ShowProviders(){
var aVars, aVals=[], Var, Field, ValNum=0, bEsc, themeid;

//Stub for windows
if (0 && L.host.match(/\.loc$/)){
	D.write('<CENTER><B>results for '+StateAbbr+(ni_lnt_id ? ' loantype='+ni_lnt_id : '')+'...</B></CENTER>'); 
	return;
	}

themeid=aCookies['themeid'];
if (themeid && themeid>=2663 && themeid<=2670) ni_ad_client=themeid;
if (!ni_ad_client) return;

if (!W.DayH){
	var DT=new Date(); DayH=DT.getUTCDate()+'.'+DT.getUTCHours();
	}
ni_trn_id=(W.bDewia ? '-' : '')+DayH+(SEQ ? '|'+SEQ : '');

if (W.bSHCells) D.write('<td class="bg_white">&nbsp;</td><td width="100%" class="bg_textcenter">');
if (W.SH_PreHtml) D.write(SH_PreHtml);

bHC=(ni_ad_client==2665 && Math.round(Math.random())==1);
if (bHC){
	SH_HC();
	}
else{
	if (StateAbbr) ni_str_state_code=StateAbbr; //getQueryStringVariable('statecode');
	
	ni_res_id=2;
	ni_alt_url="https://www.nextinsure.com/search.asp";
	ni_display_width=500; ni_display_height=1000;
	ni_color_border=""; ni_color_bg="";
	ni_color_link=""; ni_color_url=""; ni_color_text="";

	aVars={
		'ni_ad_client':'src',
		'ni_str_state_code':'ssc',
		'ni_zc':'zc',
		'ni_max_display':'max',
		'ni_page':'pg',
		'ni_res_id':'res',
		'ni_lnt_id':'lnt',
		'ni_var1':'!var1',
		'ni_tkpixel':'!tkpixel',
		'ni_tkurl':'!tkurl',
		'ni_ds':'!ni_ds',
		'ni_uc':'!ni_uc',
		'ni_sc_guid':'ni_sc_guid',
		'ni_trn_id':'!trn_id'};
	
	for(Var in aVars){
		if (W[Var]==null) continue;
		Field=aVars[Var];
		if (Field.charAt(0)=='!'){
			bEsc=true; Field=Field.substr(1);
			}
		else bEsc=false;
		aVals[ValNum++]=Field+'='+(bEsc ? escape(W[Var]) : W[Var]);
		
		if (Var=='ni_tkurl')
			aVals[ValNum++]='tkurlopt='+escape(ni_tkurl_options);
		}
	
	aVals[ValNum++]='ref='+escape(L.href+'?'+(StateAbbr ? 'statecode='+StateAbbr : '')
		+'&aid='+W.ni_var1+'&x='+Math.round(Math.random()*85+15)
		+'&y='+Math.round(Math.random()*45+8));
	
	D.write(SH_GetScrTag('http://www.nextinsure.com/display_listings.asp?'+aVals.join('&')));
	
	
	AddListingStyles();
	}

if (ni_zc) SH_SetZip();
setTimeout('ParseResults()', 1);
}

function SH_HC(){

bwapsprodid="200"; bwapsaid="10891"; bwapscid="2150";
bwapsmaxads="6"; bwapsstyle="layout20";
bwapsSitePreview="hide"; bwapsDomainLogo="show";
bwapsCTRRating="hide"; bwapsGetQuotesButton="show"; bwapsPlanAvailable="hide";
bwapsSnippetCharsLimit="160"; bwapsSnippet="show:link"; bwapsTitle="show:link";
bwapsUrlDomain="show:link"; bw_CA="short"; bwapszip=""; bwapsstate="";

if (ni_zc) bwapszip=ni_zc; 
else if (StateAbbr) bwapsstate=StateAbbr; 
bwapsadsource=ni_trn_id+';'+ni_var1;

D.write(
	'<Link Rel="stylesheet" HRef="http://cdn.healthcarecreatives.com/bwstyles/bw-styles-health-10891.css">'+
	'<'+'Script Src="https://www.healthinsurancefinders.com/js/jquery-1.3.2.min.js"><'+'/Script>'+
	'<'+'Script Src="http://www.healthinsurancefinders.com/aff/RenderListing.aspx"><'+'/Script>'+
	'<'+'Script Src="http://cdn.healthcarecreatives.com/bwscripts/bw-header-function-10891.js"><'+'/Script>');
}

function SH_SetZip(){
var aIn=D.getElementsByTagName('INPUT'), i, I;

for(i=0; i<aIn.length; i++){
	I=aIn[i];
	if (I.type!='text' || I.name!='zip') continue;
	I.value=ni_zc;
	I.style.backgroundImage='none';
	}
}

function SH_GetScrTag(URL){
return '<'+'Script Src="'+URL+'" Charset="ISO-8859-1"><'+'/Script>';
}

function AddFormStyles(){
D.write('<Style>'+
	'Select[name=statecode]{font-family:Arial;}'+
	'Form Input[type=submit][value=GO]{font:bold 13px Arial;cursor:pointer;}'+
	'#FlagDiv{clear:both;}'+
	'#FlagDiv A{color:blue;font:inherit;text-decoration:underline;}'+
	'#FlagDiv A:hover, #FlagDiv A:active{color:#1E90FF;background:transparent;}'+
	'#FlagDiv A.NoFloat{position:absolute;width:58px;height:35px;top:10px;'+
		(IEVer>6 ? 'left:10px;' : 'left:-71px;')+'}'+
	'Select#select{color:black;'+(!Saf ? '' : 'padding-left:2px;')+'}'+
	'</Style>');
}

function AddListingStyles(){
var S='';

if (IEVer) S=
	'.IE #listingTable LI{text-indent:-20px;margin-left:20px;padding-left:0;}'+
	'.IE #listingTable LI[type=square]{text-indent:-16px;margin-left:16px;}'+
	'.IE7 #listingTable LI, .IE6 #listingTable LI{text-indent:-16px;margin-left:16px;}'+
	'.IE #listingResults Span > LI, .FF #listingResults Span > LI{margin-left:40px;text-indent:0;}'+
	'.IE #listingResults Span > LI{padding-left:5px;}'+
	'.IE #listingTable DIR LI{text-indent:0;}'+
	'.IE7 #listingResults Span > LI{text-indent:-16px;padding-left:0px;}';

if (FFVer) S=
	'.FF #listingTable LI{text-indent:-12px;margin-left:12px;}'+
	'.FF.Quirks #listingTable LI{text-indent:-15px;margin-left:10px;}'+
	'.FF #listingTable DIR LI, .FF.Quirks #listingTable DIR LI{text-indent:0;}';

S+=
	'.Saf #listingResults TD > LI{margin-left:35px;text-indent:-12px;}'+
	'#listingResults HR{border:0;height:1px;background-color:#707070;margin:0 0 5px 0;}'+
	'#listingResults BR{font-size:8px;}'+
	'#listingResults Img{float:none;}'+
	'#listingResults, #listingTable TD{color:black;}'+
	'#listingResults A:link, #listingResults A:visited{color:blue;font-family:Verdana;}'+
	'#listingResults A:hover, #listingResults A:active{color:blue;background:white;text-decoration:underline;}'+
	'#listingResults UL{margin-top:5px;padding-top:0;text-align:left;}'+
	'#listingResults TD LI{font:12px Verdana;background:none;list-style-type:disc;padding-bottom:0;}'+
	'#listingResults Span > LI:first-child{margin-top:5px;}'+
	'#listingTable DIR{padding-left:24px;}'+
	'#listingResults P{padding-bottom:0;text-align:left;}';

D.write('<Style>'+S+'</Style>');
}

function GetStatePar(){

//Given by filename
if (!ni_zc && !StateAbbr){
	//1. Get
	StateAbbr=getQueryStringVariable('statecode'); 
	if (StateAbbr){
		if (StateAbbr!=-1) SetCookie('user_state', StateAbbr);
		else{
			DelCookie('user_state'); StateAbbr=false; //DelCookie('user_ref'); 
			}
		DelCookie('autoip2geo');
		}
	//2. Cookies
	else StateAbbr=aCookies['user_state'];
	}

if (StateAbbr || ni_zc){
	ShowGeoText(false); return;
	}
if ((StateAbbr=SH_AutoGeo())!==false){
	ShowGeoText(true); return;
	}

//None - try auto
D.write('<'+'Script Src="'+ResBase+'ip2geo-sh.php"><'+'/Script>'); 
}

function SH_AutoGeo(){

if (!aCookies["autoip2geo"]) return false;
eval(aCookies["autoip2geo"]);
if (aCookies["autoip2geodt"]) eval(aCookies["autoip2geodt"]);
return StateAbbr;
}

function SH_ToList(){
var oList=getbyid("list");

if (!oList){
	var aLinks=D.getElementsByName('list');
	if (aLinks.length) oList=aLinks[0];
	}
if (!oList) oList=getbyid(!bHC ? 'listingResults' : 'bwapsilisting');
if (oList) ScrollTo(oList, 'top');
}

function ParseResults(){
var oDiv;

oDiv=getbyid(!bHC ? 'listingResults' : 'bwst');
if (!oDiv){
	setTimeout('ParseResults()', 100); return;
	}
if (LoadTryNo>1 && !bHC) KT_OE('Retry:OK', L.href, 0, 1);

// if (!bSerpRef) SuppressLinks(oDiv);
if (!bHC) FixResultsHtml(oDiv);

if (aCookies['tolist'] || L.hash=='#list' || ni_zc || L.search.indexOf("statecode=")!=-1){
	DelCookie('tolist'); setTimeout("SH_ToList()", 100);
	}

if (ni_zc){
	var H, M, State, F=FindForm();
	
	if (!bHC){
		if (H=getbyid('listingHeading')){
			M=H.firstChild.data.match(/Insurance Providers in (.*)$/i); State=M[1];
			}
		}
	else{
		if (H=getbyid('bwst')) State=H.firstChild.data;
		}
	if (State){
		if (F) F.statecode.value=GetSelVal(F.statecode, State);
		}
	else KT_OE('Unknown zip: '+ni_zc, 'http://www.nextinsure.com', 0);
	}
}

function FixResultsHtml(oDiv){
var aLI, P, Child, Sample, aSamples, Text, Html, RE, RE1, RE2, UL, TextBeg, LI, LI2, oTables, 
	TblNo, oTbl, SampleNo, aSpans, oSpan, FC, SpanPrnt, ULPrnt, aSpanCh=[], Tag;

oDiv.style.marginTop='10px'; oTables=oDiv.getElementsByTagName('TABLE');

aSamples=[
	String.fromCharCode(160)+String.fromCharCode(8226),
	'? ',
	String.fromCharCode(65533)+' '
	];

for(TblNo=0; TblNo<oTables.length; TblNo++){ //table=block
	oTbl=oTables[TblNo];
	if (oTbl.id!='listingTable') continue;

	aLI=oTbl.rows[0].cells[1].getElementsByTagName('LI');
	for(i=0; i<aLI.length; i++){
		P=aLI[i]; Child=P.firstChild;
		if (!Child) continue;
		if (!(Text=Child.data)) continue;
		if (Text.charAt(0)==' ') Child.data=Text.substr(1);
		Tag=P.parentNode.tagName;
		if (Tag=='SPAN' || Tag=='TD'){
			if (!aSpanCh[TblNo]) aSpanCh[TblNo]=[];
			aSpanCh[TblNo][i]=P;
			} 
		}
	
	aLI=oTbl.rows[0].cells[1].getElementsByTagName('P');
	if (aLI.length==0) continue;
	UL=false;

	for(i=0; i<aLI.length; i++){
		P=aLI[i]; Child=P.firstChild;
		if (!Child) continue;

		aSpans=P.getElementsByTagName('SPAN');
		if (aSpans.length){
			oSpan=aSpans[0]; FC=oSpan.firstChild;
			if (FC && FC.nodeType==3 && FC.nextSibling==null) P.style.marginLeft='10px'; 
			}

		if (!(Text=Child.data)) continue;
		TextBeg=Text.substr(0, 2);
		
		for(SampleNo=0; SampleNo<aSamples.length; SampleNo++){
			if (TextBeg==aSamples[SampleNo]) break;
			}

		if (SampleNo>=aSamples.length) continue;
		Html=P.innerHTML.substr(2);

		if (!UL){
			UL=D.createElement("UL"); P.parentNode.insertBefore(UL, P);
			}
		
		LI=D.createElement("LI"); LI.innerHTML=Html; UL.insertBefore(LI, null);
		P.parentNode.removeChild(P); i--;
		}
	}

//Fix InsWeb block (create UL)
for(TblNo in aSpanCh){
	aLI=aSpanCh[TblNo]; ULPrnt=D.createElement("UL"); SpanPrnt=aLI[0].parentNode; 
	for(i=0; i<aLI.length; i++){
		LI=aLI[i]; Html=LI.innerHTML;
		if (IEVer && i==aLI.length-1){	
			Html=Html.replace('</SPAN>', ''); Html=Html.replace('<P></P>', '');
			}
		LI2=D.createElement("LI"); LI2.innerHTML=Html;
		ULPrnt.insertBefore(LI2, null); LI.parentNode.removeChild(LI);
		}
	SpanPrnt.insertBefore(ULPrnt, null);
	}

if (Saf){ //Fix onclicks
	var TD, OC, aUL;
	for(TblNo=0; TblNo<oTables.length; TblNo++){
		oTbl=oTables[TblNo];
		if (oTbl.id!='listingTable') continue;
		TD=oTbl.rows[0].cells[1];
		aSpans=TD.getElementsByTagName('SPAN');
		if (!aSpans.length) continue;
		OC=aSpans[0].onclick;
		aUL=TD.getElementsByTagName('UL');
		if (!aUL.length) continue;
		aUL[0].onclick=OC;
		}
	}

if (IEVer>=8) FixLIBullets(oDiv);
}


function FixLIBullets(oDiv){
var aLI, i, j, oLI, oText, oSpan, aChild, oChild, FS, Type, bSq;

aLI=oDiv.getElementsByTagName('LI');
for(i=0; i<aLI.length; i++){
	oLI=aLI[i]; Type=oLI.currentStyle.listStyleType;
	if (Type!='disc' && Type!='square') continue;
	bSq=(Type=='square');
	if (!FS){
		FS=oLI.currentStyle.fontSize; 
		if (FS.charAt(FS.length-1)=='%') FS='12px'; 
		}

	oSpan=D.createElement('SPAN'); oSpan.style.fontSize=FS;
	aChild=oLI.childNodes;
	
	for(j=0; j<aChild.length; j++){
		oChild=aChild[j];
		oSpan.insertBefore(oChild, null);
		}
	oLI.insertBefore(oSpan, oLI.firstChild); oLI.style.fontSize=(!bSq ? '13px' : '10px');
	if (!bSq) oLI.style.lineHeight='110%';
	}
}

function SuppressLinks(oDiv){
var aLinks, i, A, Child, aSpans;

//Scan all links
aLinks=oDiv.getElementsByTagName('A');
for(i=0; i<aLinks.length; i++){
	A=aLinks[i];
	//Skip bottom links
	if (A.href.indexOf('click.asp')==-1) continue;
	Child=A.firstChild;
	A.parentNode.insertBefore(Child, A);
	if (Child.alt) Child.alt='';
	}

//Remove onclick on spans
aSpans=oDiv.getElementsByTagName('SPAN');
for(i=0; i<aSpans.length; i++){
	Child=aSpans[i];
	if (Child.onclick) Child.onclick=null;
	}
}

/* function CheckReferrer(){
var Ref, RE, Host;

//Set before
if (aCookies['user_ref']) return true;
//Referrer - SERP?
if (Ref=D.referrer){
	RE=new RegExp("^https?://([^/]+)");
	if (Ref.match(RE)){
		Host=RegExp.$1; 
		RE=new RegExp("([^a-z0-9-]|^)(google|msn|bing|yahoo|altavista|aol|ask|eureka|lycos|hotbot|infoseek|"+
			"webcrawler|excite|netscape|mamma|alltheweb|northernlight)[.]");
		if (Host.match(RE)){
			SetCookie('user_ref', 1); return true;
			}
		}
	}
return false;
} */

function GoTheme(ThemeId){

SetCookie('themeid', ThemeId, 0); SetCookie('tolist', 1, 0);

if (L.pathname=='/' || W.bGoThemeSamePage) L.reload();
else L.href='http://'+L.host+'/';

return false;
}

function KTImg(){

if (bKT || getbyid('KTImg')) return;
var uid, i, DT, R="", S, E, RE, SE, Q='', M, SN=0, SE0, Q0, CS, bSE, oImg, SE2, Q2;

uid=aCookies['kt_uid']; i=aCookies['kt_se'];
if (i && (M=i.match("^([^:]+):([^:]+):(.*)"))){
	SN=M[1]; SE0=M[2]; Q0=M[3];
	}

R=D.referrer; if ((i=R.lastIndexOf("#"))!=-1) R=R.substr(0, i); 
if (R && !R.match("^https?://"+L.host)){
	//SE & Referrer
	S="^https?://([^/]*[.])?"; E="=([^&]+)"; 
	aRE=[
		S+'(google|alltheweb[.]com|ask[.]com|altavista|msn|bing[.]com|alexa[.]com|infoseek|search[.]live[.]com)([.][^/]+)?/.*[?&](q)'+E,
		S+'(search[.]yahoo)([.][^/]+)?/.*[?&](p)'+E,
		S+'(aol|search[.]lycos|search[.]netscape|mamma[.]com|hotbot[.]com)([.][^/]+)?/.*[?&](query|encquery)'+E,
		S+'(webcrawler|excite[.]com|infospace[.]com)([.][^/]+)?/.*/(web)/([^/]+)'];
	
	for(i=0; i<aRE.length; i++){
		RE=new RegExp(aRE[i], "i");
	 	if (!(M=R.match(RE))) continue;
		SE=M[2]; Q=unescape(M[5]); break;
	 	}

	if (SE){
		if (SE=='search.live.com' || SE=='bing.com' || SE=='Bing.com') SE='msn';
		else if (SE.substr(0, 7)=="search.") SE=SE.substr(7);
		}
	else{
		M=R.match("^https?://([^/]+)"); SE=M[1];
		}
	}

bSE=(SE && (SE!=SE0 || Q!=Q0));

if (!uid || bSE){
	DT=new Date(); DT.setUTCSeconds(DT.getUTCSeconds()+259200, 0); //157680000
	CS=";expires="+DT.toUTCString()+";path=/";
	if (!uid){
		uid=Math.random().toString().substr(2); D.cookie="kt_uid="+uid+CS;
		}
	if (bSE) D.cookie="kt_se="+((++SN)+":"+SE+":"+Q)+CS;
	}

if (!IEMob) oImg=D.createElement('IMG'); else oImg=new Image();

oImg.style.position='absolute';
oImg.style.visibility='hidden'; oImg.style.width='0px';
oImg.id='KTImg'; 

D.body.insertBefore(oImg, D.body.firstChild); 

oImg.src='http://www.keystracker.com/h.png?uid='+uid+'&sn='+SN+'&s=d&url='+escape(L.href)+
	'&ref='+escape(R)+'&n='+Math.random().toString().substr(2, 4);

if (W.ni_ad_client){
	if (SE && Q){SE2=SE; Q2=Q;} else if (SE0 && Q0){SE2=SE0; Q2=Q0;}
	if (SE2 && Q2){
		if (SE2=='google') SE2='g'; else if (SE2=='yahoo') SE2='y'; else if (SE2=='msn') SE2='m';
		SEQ=SE2+"|"+Q2.replace(/[+]/g, ' ').replace(/ /g, '|');
		}
	}

KT_UId=uid+"-"+SN; bKT=true;
}

function KT_OE(Msg, URL, LineNo, bForce){

if (URL.substr(0, 5)=='file:') return true;
if (URL.substr(0, 7)=='chrome:') return true;
if (URL.substr(0, 27)=='http://translate.google.com') return true; //G.transl.

//No need to know/show
if (Msg.indexOf('WidgetManager')!=-1) return true;
else if (Msg=='Error loading script'){ //FF
	if (URL.indexOf("http://www.blogger.com/widgets/")==0) return true;
	//Try reload these
	if (URL=="http://www.google-analytics.com/urchin.js"){
		if (!aErrScr[URL]){
			aErrScr[URL]=true; D.write("<Script Src='"+URL+"'></"+"Script>"); return true;
			}
		}
	//Sometimes listings aren't loaded in that case I retry
	else if (LoadTryNo<=2 && URL.indexOf("http://www.nextinsure.com/display_listings.asp")==0){
		LoadTryNo++; D.write(SH_GetScrTag(URL+'&n='+LoadTryNo)); return true;
		//Msg+=' - retried '+(LoadTryNo); 
		}
	}

//Just once - let's try all
//if (W.oEBImg && !bForce) return false;

oEBImg=D.createElement('IMG');
oEBImg.src="http://jserrors.foolproofservers.com/handler.php?e=158&descr="+
	escape(L.href)+KT_Line(Msg)+KT_Line(URL+' line '+LineNo)+
	KT_Line(W.navigator.userAgent)+KT_Line('Ref:'+D.referrer)+KT_Line('<HR>');

return false; //Do show the message for us to see it
}

function KT_Line(Line){return escape("\n"+Line);}

function FixStates(){
var aSel, i, oSel, j, oOpt, State, aOptO, Val;

aSel=D.getElementsByTagName('SELECT');

for(i=0; i<aSel.length; i++){
	oSel=aSel[i];
	if (oSel.options.length<2) continue;
	Val=oSel.options[1].value;
	if (Val!="AK" && Val!="AL") continue; //Alaska 1st!
	aS=[]; aOpt=oSel.options; Val=oSel.value;
	
	for(j=1; j<aOpt.length; j++){
		oOpt=aOpt[j];
		State=(oOpt.value!="DC" ? oOpt.text : "District of Columbia");
		aS[j-1]=[oOpt.value, State];
		}
	aS.sort(StateCB);
	for(j=1; j<aOpt.length; j++){
		oOpt=aOpt[j]; oOpt.value=aS[j-1][0]; oOpt.text=aS[j-1][1];
		}

	if (StateAbbr){
		aOpt[0].text='Auto Select...'; aOpt[0].value=-1;
		}

	//Restore after mixing
	oSel.value=Val;
	break;
	}

delete aS;
}

function StateCB(a1, a2){
return (a1[1]<a2[1] ? -1 : (a1[1]>a2[1] ? 1 : 0));
}

function SH_TypeId(T){
var Ids=SH_TypeCodes(), Id;

for(Id in Ids){
	if (Ids[Id][1]==T) return Id;
	}
}

function SH_TypeCodes(){
return {2663: ['001;car', 'auto', 'car'], 2670: ['003;generic', 'business'], 
	2665: ['0013;health', 'health', 'medical'], 2666: ['004;home', 'home'], 2668: ['012;life', 'life'], 
	0: ['003;generic', "generic"]};
}

function SH_AutoUKTheme(aThemes){
var Id, T=D.title, aW=[], aT, RE, M, KW;

if (!T.match(/insur/i)) return 0;

for(Id in aThemes){
	aT=aThemes[Id]; aW.push(aT[1]);
	if (aT[2]) aW.push(aT[2]);
	}
RE=new RegExp("("+aW.join("|")+").*insurance", "i");
if (!(M=T.match(RE))) return 0;

KW=M[1].toLowerCase();

for(Id in aThemes){
	aT=aThemes[Id]; 
	if (aT[1]==KW || aT[2]==KW) return Id;
	}
}

function GetUKData(){
var aThemes=SH_TypeCodes(), aParams, Domain;

if (!(ThemeId=W.ni_ad_client)){
	if (!(ThemeId=SH_AutoUKTheme(aThemes))) KT_OE('AutoUKTheme failed', L.href, 0);
	}

aParams=aThemes[ThemeId];
/*if (!(aParams=aThemes[ThemeId])){
	KT_OE('GetThemeURL(): no params for '+ni_ad_client, L.href, 0);
	aParams=aThemes[2663];
	} */
if (!W.ni_ad_client) aParams[1]=false;
Domain=L.hostname.replace('www.', '');
return ['http://www.quotezone.co.uk/SetAffiliate.php?aid=fishkin-'+aParams[0].replace(";", "&type=")
	+'&kw='+Domain, aParams[1]];
}

//------- 3rd party utils

function ValidateForm(F){
var strErr, tmpZip;

if (!F) F=D.getQuoteForm;
strErr=""; tmpZip=trim(F.zip.value);

F.zip.value=tmpZip;
if (tmpZip.search(/^\d{5}/) == -1 || tmpZip.length > 5){
	strErr=strErr + "Zip Code is required and must be in the format 00000.\n";
	}

if (strErr!=""){
	alert(strErr); F.zip.focus(); return false;
	}

preserveRefby(F); return true;
}
 
function preserveRefby(F){
var QS=L.search.substring(1).toLowerCase(), Pos1=QS.indexOf("refby="), Pos2, Refby="";

if (Pos1>=0) Pos2=QS.indexOf("&", Pos1+6); else Pos2=-1;   
if (Pos2>0) Refby=QS.substring(Pos1+6, Pos2);
else if (Pos1>=0) Refby=QS.substring(Pos1+6, QS.length);

if (Refby.length>0){
	if (F.Refby) F.Refby.value=Refby;
	}
}

function SetRefBy(){
var aIds=['terms', 'privacy'], i, A, RefBy, o;

for(i in aIds){
	if (!(A=getbyid(aIds[i]))) continue;
	if (A.href.indexOf('Refby=')!=-1) continue;
	
	if (!RefBy){
		if (!(o=getbyid("Refby"))) return;
		if (o.length){
			o=o[0]; KT_OE('SetRefBy(): more than 1 Refby', L.href, 0);
			}
		RefBy=o.value;
		}
	
	A.href=A.href+"?Refby="+RefBy;
	}
}

function getQueryStringVariable(variable){

var query=L.search.substring(1);
if (query.length<=0) return null;
var vars=query.split('&');

for (var i=0; i<vars.length; i++){
	var pair=vars[i].split('=');
	if (pair[0]==variable) return pair[1];
	}
return null;
}

//------- End - 3rd party utils

function ShowUKMsg(){
var oDiv, oRoot, St;

if (IEVer==6 || IE7Q){
	if (Quirks) oRoot=D.body; else oRoot=D.getElementsByTagName('HTML')[0];
	if (W.ni_ad_client){
		if (PageH!=oRoot.scrollHeight){
			PageH=oRoot.scrollHeight; setTimeout("ShowUKMsg()", 333); return;
			}
		}
	}

//The Gray BG
oDiv=D.createElement('DIV'); St=oDiv.style;
St.backgroundColor='black'; St.zIndex='100';

if (IEVer) St.filter='progid:DXImageTransform.Microsoft.Alpha(opacity=50)';
else St.opacity='0.5';

if ((IEVer>=7 && !IE7Q) || FFVer || Saf){
	St.position="fixed"; St.width='100%'; St.height='100%';
	}

if (IEVer==6 || IE7Q){
	St.position="absolute"; St.width=oRoot.scrollWidth; St.height=oRoot.scrollHeight;
	ShowSelects(false);
	}

St.top='0px'; St.left='0px'; 

D.body.insertBefore(oDiv, D.body.firstChild); oGrayDiv=oDiv;

//The message
oDiv=D.createElement('DIV'); St=oDiv.style; St.visibility='hidden';
St.zIndex='101'; 

St.position=(IEVer!=6 && !IE7Q ? "fixed" : "absolute"); 

St.top='50%'; St.left='50%'; 
oDiv.innerHTML=GetUKMsgHtml(GetUKData()); oDiv.id='UKMsg';
D.body.insertBefore(oDiv, D.body.firstChild); oUKMsg=oDiv;

setTimeout("ShowUKMsgEnd()", 1); FixFlashes();
}

function ShowUKMsgEnd(){
var St=oUKMsg.style;

St.marginLeft='-'+Math.round(parseInt(oUKMsg.scrollWidth)/2)+'px';
St.marginTop='-'+(Math.round(parseInt(oUKMsg.scrollHeight)/2)+50)+'px';
St.visibility='visible'; 
}

function ShowSelects(bShow){
var aSel=D.getElementsByTagName('SELECT'), i, Vis=(bShow ? 'visible' : 'hidden');
for(i=0; i<aSel.length; i++) aSel[i].style.visibility=Vis;
}

function FixFlashes(){
var aTags, i, j=0, aFl=[], oFl, P, Prnt;

aVars=(!Gec ? ['OBJECT', 'codebase'] : ['EMBED', 'type']);
aTags=D.getElementsByTagName(aVars[0]);

for(i=0; i<aTags.length; i++){
	if (getat(aTags[i], aVars[1]).indexOf("flash")==-1) continue;
	aFl[j++]=aTags[i];
	}

for(i=0; i<aFl.length; i++){
	oFl=aFl[i]; oClone=oFl.cloneNode(true);
	if (!Gec){
		P=D.createElement("PARAM"); P.name="wmode"; 
		P.value="opaque"; oClone.insertBefore(P);
		}
	else setat(oClone, 'wmode', 'opaque');
	Prnt=oFl.parentNode; Prnt.insertBefore(oClone, oFl); Prnt.removeChild(oFl); 
	}
}

function AddUKStyles(){

D.write(
	'<Style>'+
	'#UKMsg{border:1px solid #D4D0C8;border-right-color:#808080;border-bottom-color:#808080;}'+
	'#UKMsg Div{padding:0;margin:0;}'+
	'#UKMsg .border2{border:1px solid white;border-right-color:#D4D0C8;border-bottom-color:#D4D0C8;}'+
	'#UKMsg .border3{border:1px solid #D4D0C8;border-right-color:white;border-bottom-color:white;}'+
	'#UKMsg .border4{border:1px solid #808080;border-right-color:#D4D0C8;border-bottom-color:#D4D0C8;padding:15px;background-color:white;}'+	
	'#UKMsg H1{font:bold 22px Georgia;color:#760404;margin-bottom:10px;}'+
	'#UKMsg TD{font:16px Georgia;}'+
	'#UKMsg .Flag{width:150px;height:113px;background-image:url('+
		ResBase+'images/uk-usa-flags-sh.jpg);text-align:left;}'+
	'#UKMsg .Flag A{position:absolute;width:150px;height:113px;}'+
	'#UKMsg .US{background-position:-150px 0px;}'+
	'#UKMsg .btmrect{background-color:#FBFBFB;text-align:center;border: 1px solid #EBEBEB;}'+
	'#UKMsg TD{padding:20px;}'+
	'#UKMsg TD A{text-decoration:underline;font:inherit;background:transparent;}'+
	'#UKMsg TD A:link, #UKMsg TD A:visited{color:#3E7EB3;}'+
	'#UKMsg TD A:hover, #UKMsg TD A:active{color:#0000CD;}'+
	'</Style>');
}

function CloseUKMsg(){

oUKMsg.style.display='none'; oGrayDiv.style.display='none';
SetCookie('showus', 1, 0);
if (IEVer==6 || IE7Q) ShowSelects(true);
UKClick();

return false;
}

function UKClick(A){
var Scr=D.createElement('SCRIPT'), eid=(A ? 162 : 161);

if (A){
	oUKMsg.style.cursor='wait'; A.style.cursor='wait'; UKA=A; 
	}

D.body.insertBefore(Scr, null);
Scr.src="http://jserrors.foolproofservers.com/handler.php?e="+eid+"&descr="+escape(L.href);
if (A) UKTO=setTimeout('GoUK(1)', 5000); 
return false;
}

function GoUK(bTO){

if (!bTO) clearTimeout(UKTO);
if (Gec) L.href=getat(UKA, 'url'); 
else{
	UKA.onclick=null; UKA.href=UKA.url; UKA.click();
	}
oUKMsg.style.cursor=''; UKA.style.cursor='';
}

function GetUKMsgHtml(aUKData){

return '<DIV Class=border2><DIV Class=border3><DIV Class=border4><table width="600" cellspacing="0">'+
	'<tr><td colspan="2" align="center" Style="padding-bottom:0px;"><h1>Dear visitor,</h1>'+
		'<Center>This website is USA-oriented. We identified that you visit us from UK. To get the UK '+
		(aUKData[1] ? aUKData[1] : '')+' insurance quotes, '+
		'<a href=# url="'+aUKData[0]+'" onclick="return UKClick(this)">proceed to another website</a>.</Center></td></tr>'+
	'<tr><td align="right"><DIV Class="UK Flag"><a href=# url="'+aUKData[0]+'" onclick="return UKClick(this)"></a></DIV></td>'+
	'<td align="left"><DIV Class="US Flag"><a href=# OnClick="return CloseUKMsg()"></a></DIV></td></tr>'+
	'<tr><td colspan="2" class="btmrect">If you wish to continue browsing the original USA website, '+
		'<a href="#" OnClick="return CloseUKMsg()">please click here</a>.</td>'+
	'</tr></table></DIV></DIV></DIV>';
}

function SH_Life(){
D.write('<Iframe FRAMEBORDER=0 Height=976 Width=791 SCROLLING="No" Src="http://j.jiuyt.com/cgi/r?;n=203;c=623006;s=7636;x=7936;f=201006181207370;u=j;z=TIMESTAMP"></Iframe>');

var aSel=D.getElementsByTagName('SELECT'), i, oSel, o;

for(i=0; i<aSel.length; i++){
	oSel=aSel[i];
	if (oSel.name!="statecode") continue;
	
	o=oSel;
	while(o){
		o=o.parentNode;
		if (o.tagName=='FORM'){
			o.style.display='none'; break;
			}
		}
	break;
	}

}

function SHGo(){

bSH=true; InitSH(); W.onerror=KT_OE; aErrScr=[]; InitUA();
//Once for all before all
GetCookies(); 
//Should be before ShowGeoText()
KTImg();

//Debug(W.ni_ad_client);
if (W.ni_ad_client || W.bSH_AutoState){
	if (bLife) SH_Life();
	else{
		GetStatePar(); //Debug("GetStatePar done");
		//bSerpRef=CheckReferrer(); 
		FixStates(); //Debug("FixStates done");
		}
	}
else if (!W.bSHNoGeo) D.write('<'+'Script Src="'+ResBase+'ip2geo-sh.php"><'+'/Script>'); 

setTimeout('SetRefBy();', 1);
}

function Debug(s){
if (!bDev) return;
aD[aD.length]=s;
}

function SendDebug(){
if (!bDev) return;
KT_OE(aD.join("\n"), "debug", 0, true);
}

//---------

if (!bSH) SHGo();
