
//bUsaNoFloat: for wider pages
//bGoThemeSamePage: stay on same page when changing theme
//delcookie - clears cookies for geo and referrer
var D=document, W=window, StateAbbr, aCookies=null, bSerpRef, bKT, aErrScr=[];
var Gec, Op, Ns, Saf, IE7, Nav, IE6, IEVer=0, FFVer=0, Quirks; 

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

ni_res_id = 2;
ni_alt_url = "https://www.nextinsure.com/search.asp";
ni_zc = null; //getQueryStringVariable('zipcode');
//ni_str_state_code is set later
//ni_var1 = 'rockyridgeranch.us'; //getQueryStringVariable('aid');
ni_var1=W.location.host;
if (ni_var1.substr(0, 4)=='www.') ni_var1=ni_var1.substr(4);

ni_display_width = 500;
ni_display_height = 1000;
ni_color_border = "";
ni_color_bg = "";
ni_color_link = "";
ni_color_url = "";
ni_color_text = "";
if (!W.ni_lnt_id) ni_lnt_id=null;

//------------------------------------------------------------------------

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

F=FindForm();

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=GetSelOption(F.statecode, StateAbbr);
		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==''){
		Text=Pretext+"non-resident of the USA. Unfortunately we don't have relevant providers for your place of residence. If you are a resident of the USA, please select your state to see the Top Providers for your area.";
		}
	}

if (Text){
	var bNoFloat=(W.bUsaNoFloat && IE6); // && 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;';
	
	if (bNoFloat){ //IE6 strict wide pages: the bug with disappearing text
		D.write('<DIV Style="'+DivSt+'height:38px; padding:7px 10px 10px 72px;background: white url(/images/usa50.png) no-repeat 10px 10px;">'+Text+'</DIV>');
		}
	else{
		D.write('<DIV Style="'+DivSt+'background-color:white;padding:7px 10px 10px 10px;">'
			+'<Img Src="/images/usa50.png" ALIGN="left" Style="margin-right:12px;margin-top:3px;width:50px;height:35px;">'
			//This last div makes sure the usa image does not overlaps the div's border
			+Text+'<Div Style="clear:left;font-size:0px;"></DIV></DIV>');
		}
	
	}

if (StateAbbr!='' && StateAbbr!='-'){
	F.statecode.value=StateAbbr; 

	//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
			}
		F.loantype.value=lnt_id; ni_lnt_id=lnt_id;
		}
	else ni_lnt_id=null;

	ShowProviders();
	}
}

function FindForm(){
var aForms, i;

aForms=D.getElementsByTagName('FORM'); 
if (aForms.length) return aForms[aForms.length-1];
return null;
}

function GetSelOption(Sel, Val){
var aOpt=Sel.options, OptNum=aOpt.length, i;

for(i=0; i<OptNum; 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 && W.location.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;

ni_str_state_code=StateAbbr; //getQueryStringVariable('statecode');

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'};

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(W.location+'?statecode='+StateAbbr+
	'&aid='+W.ni_var1+'&x='+Math.round(Math.random()*85+15)
	+'&y='+Math.round(Math.random()*45+8));

D.write('<'+'Script Src="http://www.nextinsure.com/display_listings.asp?'+
	aVals.join('&')+'"><'+'/Script>');

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

function GetStatePar(){

//1. Get
StateAbbr=getQueryStringVariable('statecode'); 
if (StateAbbr) SetCookie('user_state', StateAbbr);
//2. Cookies
else StateAbbr=aCookies['user_state'];

if (StateAbbr){
	ShowGeoText(false); return;
	}

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

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;
}

function getQueryStringVariable(variable){

var query=W.location.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;
}

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

function ParseResults(){
var oDiv;

oDiv=getbyid('listingResults');
if (!oDiv){
	setTimeout('ParseResults()', 100); return;
	}

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

if (aCookies['tolist']){
	DelCookie('tolist');
	var aLinks=D.getElementsByName('list');
	if (aLinks.length) ScrollTo(aLinks[0], 'top');
	}
//For IE, if state is selected scroll to 'list' if the page has it
else if (!(Gec || Op) && W.location.search.indexOf("statecode=")!=-1){
	var oList=getbyid("list");

	if (!oList){
		var aLinks=D.getElementsByName('list');
		if (aLinks.length) oList=aLinks[0];
		}
	
	if (oList) ScrollTo(oList, 'top');
	}


}

function FixResultsHtml(oDiv){
var aP, P, Child, Sample, aSamples, Text, Html, RE, RE1, RE2, UL, TextBeg, LI, oTables, TblNo, oTbl, SampleNo;

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

//RE1=new RegExp("(<BR>)?&nbsp;"+String.fromCharCode(8226)+" ", "g");
//RE2=new RegExp("(<BR>)?[?] ", "g");
//RE2=new RegExp("(<BR>)?[?] ", "g");

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

for(TblNo=0; TblNo<oTables.length; TblNo++){

	oTbl=oTables[TblNo];
	if (oTbl.id!='listingTable') continue;
	
	if (0){
		aP=oTbl.rows[0].cells[1].getElementsByTagName('LI');
		for(i=0; i<aP.length; i++){
			t=aP[i].firstChild.data;
			if (t.substr(0, 5)=='Fast '){
				alert(aP[i].innerHTML);
				}
			}
		}
	
	aP=oTbl.rows[0].cells[1].getElementsByTagName('P');
	if (aP.length==0) continue;
	UL=false;
	
	for(i=0; i<aP.length; i++){
	
		P=aP[i]; Child=P.firstChild;
		if (!Child) continue;
		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--;
		}
	}

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

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

aLI=D.getElementsByTagName('LI');
for(i=0; i<aLI.length; i++){
	oLI=aLI[i];
	if (oLI.currentStyle.listStyleType!='disc') continue;
	if (!FS) FS=oLI.currentStyle.fontSize;
	
	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='13px';
	}

}

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 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 GoTheme(ThemeId){
var L=W.location;

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

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

return false;
}

function InitUA(){

Nav=W.navigator.userAgent; IE7=false; 
Gec=(Nav.indexOf('Gecko')!=-1); Op=(Nav.indexOf('Opera')!=-1);
Ns=(Gec && Nav.indexOf('Netscape')!=-1); Saf=(Gec && Nav.indexOf('Safari/')!=-1);

if (!Gec && !Op){
	if (D.documentMode){
		IEVer=D.documentMode; if (IEVer==5) IEVer=6;
		}
	else{
		if (Nav.match(/ MSIE (\d+)/)) IEVer=RegExp.$1;
		}
	if (IEVer>=7) IE7=true; else IE6=true;
	}
else if (Gec && Nav.match(/Firefox\/(\d+)/)) FFVer=RegExp.$1;

Quirks=(D.compatMode=='BackCompat');
SetBodyCls();
} 

function SetBodyCls(){
var Cls="";

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

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

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;

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?://"+W.location.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)(?:\.[^/]+)?/.*[?&]((?:enc)?query)'+E,
		S+'(webcrawler|excite\.com)(?:\.[^/]+)?/.*/(web)/([^/]+)'];
	
	for(i=0; i<aRE.length; i++){
		RE=new RegExp(aRE[i], "i");
	 	if (!(M=R.match(RE))) continue;
		SE=M[1]; Q=unescape(M[3]); break;
	 	}
	if (SE=='search.live.com' || SE=='bing.com') SE='msn';

	if (!SE){
		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;
	}

oImg=D.createElement('IMG'); 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(W.location.href)+
	'&ref='+escape(R)+'&n='+Math.random().toString().substr(2, 4);

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

function KT_OE(Msg, URL, LineNo){

if (URL.substr(0, 5)=='file:') return true;
//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;
			}
		}
	}

//Just once
if (W.oEBImg) return false;

oEBImg=D.createElement('IMG');
oEBImg.src="http://jserrors.foolproofservers.com/handler.php?e=156&descr="+
	escape(W.location)+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);}

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

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 trim(str){
return((" "+str).replace(/^\s*([\s\S]*\S+)\s*$|^\s*$/,"$1"));
}

function preserveRefby(F){
var QS=W.location.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', W.location.href, 0);
			}
		RefBy=o.value;
		}
	
	A.href=A.href+"?Refby="+RefBy;
	}

}

//---------
W.onerror=KT_OE;
InitUA();
if (W.location.search.indexOf('delcookie')!=-1){
	DelCookie('user_state'); DelCookie('user_ref');
	}

//Once for all before all
GetCookies(); 

if (W.ni_ad_client){
	bSerpRef=CheckReferrer(); 
	GetStatePar();
	}

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

