
//vars/func should be named differently from code.js!
var W=window, D=document, F, E, EvSrc, ETo, Gec, Op, Ns, Saf, IE7, FF3, Nav, B, IEMob;
var oPLS, oKTImg, qseid, CS;

//------------------------------------------------------------------------
//Util

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

function GetText(o){

while(o){
	if (o.nodeType==3) break;
	o=o.firstChild;
	}
if (!o) return '';
return o.data;
}

function AddText(o, Txt, Before){
if (!Before) Before=null;
o.insertBefore(D.createTextNode(Txt), Before);
}

function SetText(o, Text){
if (o.firstChild) o.firstChild.data=Text; else AddText(o, Text);
}

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

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

function Contains(o, Ch){
while(Ch && Ch!==o && Ch!==D) Ch=Ch.parentNode;
return (Ch===o);
}

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


function createXMLHttp(){

if (typeof(XMLHttpRequest)!="undefined") return new XMLHttpRequest();

var aVersions=["MSXML2.XMLHttp.5.0",
	"MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0",
	"MSXML2.XMLHttp","Microsoft.XMLHttp"];

for (var i=0; i<aVersions.length; i++){
	try {
		var oXmlHttp=new ActiveXObject(aVersions[i]);
		return oXmlHttp;
		}
	catch (oError){}
	}

return false;
}

function PLS_Init(){
oPLS={oReq:null, oTbl:null};
}

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

function PLS_Load(Drugs){
var oReq, URL, Script, Type, Page;

oReq=createXMLHttp(); oPLS.oReq=oReq; 

if (PLS_Params.indexOf('pkgids')!=-1) Type='simple';
else if (PLS_Params.indexOf('meds')!=-1) Type='small';
else return;

Script="/commonres/pricelistsub.php?"+Type+"=1&"; oPLS.Type=Type;

if (W.location.host.indexOf(".loc")==-1) URL="http://"+W.location.host+Script;
else URL="http://"+W.location.host+"/price-list"+Script;
//else URL="http://price-list.sopserver.com"+Script;

Page=W.location.pathname; 

if (PLS_Params.indexOf("&min=0")==-1){
	oPLS.bMin=!(Page=="/" || Page.match(/index\.html$/));
	URL+=PLS_Params; if (oPLS.bMin) URL+="&min=1";
	}
else{
	oPLS.bMin=false; URL+=PLS_Params.replace('&min=0', '');
	}

oPLS.bMin=(URL.indexOf("&min=1")!=-1);
oPLS.PLS_Params=PLS_Params;

oReq.open('GET', URL, true);
oReq.onreadystatechange=PLS_OnLoad;
oReq.send(''); 
}

function PLS_OnLoad(){
var oReq=oPLS.oReq;

if (oReq.readyState!=4) return;
if (oReq.status!=200 && oReq.status!=304) return;
PLS_KTImg();
if (!oPLS.bMin) PLS_ShowPrices(); else PLS_ShowMinOnly();
}

function PLS_ShowMinOnly(){
var oMinTbl, Response;

//Exactly what has to be done to show the min price only
if (!(oMinTbl=getbyid("minprice"))){
	setTimeout("PLS_ShowMinOnly()", 250); return;
	}

if (!(Response=PLS_GetResponse())) return;
eval(Response);

PLS_ShowMinPrice(oMinTbl, PLS_MinPrice[0], PLS_MinPrice[1]);
}

function PLS_GetResponse(){
var Response;

Response=oPLS.oReq.responseText; delete oPLS.oReq;
if (Response.substr(0, 4)!="//Ok") return false;
else return Response;
}

function PLS_ShowPrices(){
var PLTbl, Response, aSIds, M, RowNo, aRows, oRow, oCell, 
	Title, bPL, PkgId, aPrices, SupNo, SupId, aPrice, A;

if (!(PLTbl=getbyid(PLS_TblId))){
	setTimeout("PLS_ShowPrices()", 250); return;
	}

if (!W.PLS_Empty) PLS_Empty=String.fromCharCode(160);

if (!(Response=PLS_GetResponse())) return false;
eval(Response); 

M=PLS_Params.match("supids=([0-9,]+)&");
if (M) aSIds=M[1].split(","); 
aRows=PLTbl.rows;

if (oPLS.Type=='small'){
	if (!aSIds) return PLS_ShowPricesSmallAll(aRows, PLS_Prices, PLS_Suppliers, PLS_Drugs);
	return PLS_ShowPricesSmall(PLS_Prices, aRows, aSIds);
	}

for(RowNo=0; RowNo<aRows.length; RowNo++){
	oRow=aRows[RowNo]; 

	PkgId=getat(oRow, "PkgId"); if (!PkgId) continue;
	aPrices=PLS_Prices[PkgId];

	for(SupNo=0; SupNo<aSIds.length; SupNo++){
		SupId=aSIds[SupNo]; oCell=oRow.cells[SupNo+1];
		if (aPrices) aPrice=aPrices[SupId]; 
		else aPrice=null;
		
		if (aPrice!=null){
			A=D.createElement("A");
			A.href=PLS_GetPriceHRef(aPrice[1]); A.target='_blank';
			AddText(oCell, " ", oCell.firstChild);
			AddText(A, "$"+aPrice[0]);
			oCell.insertBefore(A, oCell.firstChild);
			}
		else{
			ClearCell(oCell); AddText(oCell, PLS_Empty); //n/a
			}
		}
	
	}

}

function PLS_KTImg(){

if (!D.body){
	setTimeout("PLS_KTImg()", 100); return;
	}

if (oPLS.bKT || getbyid('KTImg')) return;
var C=D.cookie.split('; '), uid, i, R="", S, E, RE, SE, Q='', M, SN=0, SE0, Q0, bSE, SE2, Q2;

R=D.referrer; if ((i=R.lastIndexOf("#"))!=-1) R=R.substr(0, i); 
if (R && !R.match("^https?://"+W.location.host)){
	//Copies: code.js, pricelistsimple.js, stm31.js, rxcash, surehits.js
	//Fixed for IE5: (?:) removed
	//SE & Referrer
	S="^https?://([^/]*[.])?"; E="=([^&]+)"; 
	aRE=[
		S+'(google|alltheweb[.]com|ask[.]com|altavista|msn|bing[.]com|alexa[.]com|infoseek|search[.]live[.]com'+
			'|search[.]comcast[.]net)([.][^/]+)?/.*[?&](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=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];
		}
	}

//Cookies
for(i=0; i<C.length; i++){
	c=C[i].split("=");
	if (c[0]=='kt_uid') uid=c[1];
	else if (c[0]=='kt_se' && (M=c[1].match("^([^:]+):([^:]+):(.*)"))){
		SN=M[1]; SE0=M[2]; Q0=M[3];
		}
	else if (c[0]=='kt_qseid') qseid=c[1];
	}

bSE=(SE && (SE!=SE0 || Q!=Q0));
if (!uid || bSE){
	if (!uid){
		uid=Math.random().toString().substr(2); KT_SetC("kt_uid", uid);
		}
	if (bSE){
		KT_SetC("kt_se", (++SN)+":"+SE+":"+Q); qseid=0;
		}
	}

if (!Gec && IEVer<9) oKTImg=D.createElement('<'+'Script Defer>'); //IE<=8
else{
	oKTImg=D.createElement('SCRIPT'); setat(oKTImg, "Defer", 1); setat(oKTImg, "Async", 1);
	}

if (SE && Q){SE2=SE; Q2=Q; R="";}
else if (SE0 && Q0 && !SE && !qseid){SE2=SE0; Q2=Q0;}
if (SE2 && Q2){
	if (SE2=='google') SE2='g'; else if (SE2=='yahoo') SE2='y'; else if (SE2=='msn') SE2='m';
	oKTImg.QSe=Q2+":"+SE2;
	}

oKTImg.id='KTImg'; D.body.insertBefore(oKTImg, D.body.firstChild); 
oKTImg.src='http://www.keyst'+'racker.com/h.php'+'?uid='+uid+'&sn='+SN+'&s=a&url='+
	escape(W.location.href)+'&ref='+escape(R)+'&n='+
	Math.random().toString().substr(2, 4)+(oKTImg.QSe ? '&qse='+oKTImg.QSe : '')+(qseid ? '&qseid=1' : '');

KT_UId=uid+"-"+SN; oPLS.bKT=true; PLS_SetHandlers(D.body);
}

function KT_QSEId(i){
KT_SetC('kt_qseid', i); qseid=i;
}

function KT_SetC(c, v){

if (!CS){
	var DT=new Date(); DT.setUTCSeconds(DT.getUTCSeconds()+259200, 0);
	CS=";expires="+DT.toUTCString()+";path=/";
	}
D.cookie=c+"="+v+CS;
}

function PLS_GetPriceHRef(PId){
return "http://price-list.sopserver.com/go2pharmacy.php?pr="+PId;
}

function PLS_ShowPricesSmallAll(aRows, PLS_Prices, PLS_Suppliers, PLS_Drugs){
var PLTbl=getbyid(PLS_TblId), SupId, aPrices, DrugId, aPrice, 
	A, Pharm, oRow, SupBody, PriceBody, PLType, PRInd, Cell0,
	bAddPharmBody, bAddPriceBody, aTBodies, BodyNo, oBody, bAst,
	oMinTbl=getbyid('minprice'), MinPrice=1000, MinPriceId, Price, PriceRowNo, LineNum=0, Drug;

bAst=(W.location.host=='www.ultramhelp.com');
//First generate enough tbodies for pharmacies and prices
//This is the only way to copy table content in IE without recursion

if (!PLTbl.tBodies){
	oPLS.bMin=true; return; //PLS_ShowMinOnly(); 
	}

SupBody=PLTbl.tBodies[0]; PriceBody=PLTbl.tBodies[1];

if (SupBody.rows.length==1 && PriceBody.rows.length==2) PLType=2;
else PLType=1;

if (PLType==1) PRInd=1; else if (PLType==2) PRInd=0;

for(SupId in PLS_Prices){
	if (bAddPharmBody) PLTbl.insertBefore(SupBody.cloneNode(true), null);
	bAddPharmBody=true; LineNum++;

	aPrices=PLS_Prices[SupId];
	for(DrugId in aPrices){
		if (bAddPriceBody) PLTbl.insertBefore(PriceBody.cloneNode(true), null);
		bAddPriceBody=true; LineNum++;
		if (!Drug) Drug=PLS_Drugs[DrugId];
		}
	}

if (PLType==1 && FF3 && LineNum==2){
	oBody=SupBody.cloneNode(true); oBody.style.visibility='hidden';
	PLTbl.insertBefore(oBody, null);

	oBody=PriceBody.cloneNode(true); oBody.style.visibility='hidden';
	PLTbl.insertBefore(oBody, null);
	}

//Then fill them with content
aTBodies=PLTbl.tBodies; BodyNo=0;
for(SupId in PLS_Prices){
	oBody=aTBodies[BodyNo++];
	
	Pharm=PLS_Suppliers[SupId];
	if (Pharm.indexOf('harmacy')==-1) Pharm+=' Pharmacy';

	A=oBody.getElementsByTagName('A')[0];
	SetText(A, Pharm);
	A.href='http://price-list.sopserver.com/pharmacy.php?sid='+SupId+'&dr='+Drug;

	A.onmouseover=new Function('return PL_SupMouse("'+Pharm+'")');
	A.onmouseout=function(){PL_Status(''); return true;};
	A.onclick=function(){return PL_SupDescr(this)};
	
	if (bAst) PLS_ShowAst(oBody, SupId);

	aPrices=PLS_Prices[SupId]; PriceRowNo=0;

	for(DrugId in aPrices){

		if (PriceRowNo>0) oBody.removeChild(oBody.rows[oBody.rows.length-1]);

		oBody=aTBodies[BodyNo++]; aPrice=aPrices[DrugId];
		oRow=oBody.rows[PRInd]; Cell0=oRow.cells[0];

		if (PLType==1){
			SetText(Cell0, PLS_Drugs[DrugId]);
			SetText(oRow.cells[1], '$'+aPrice[0]+' per Pill');
			}
		else if (PLType==2){
			SetText(Cell0.firstChild, PLS_Drugs[DrugId]);
			SetText(Cell0.childNodes[2], '$'+aPrice[0]);
			}

		A=oBody.getElementsByTagName('A')[0]; A.target="_blank";
		A.href='http://price-list.sopserver.com/go2pharmacy.php?pr='+aPrice[1];

		if (PLType==1 && PriceRowNo>0) oBody.removeChild(oBody.rows[0]);
		
		if (oMinTbl){
			Price=parseFloat(aPrice[0]);
			if (Price<MinPrice){
				MinPrice=Price; MinPriceId=aPrice[1];
				}
			}
		
		PriceRowNo++; 
		}
	
	}

if (PLType==1 && FF3 && LineNum==2){
	oBody=aTBodies[2]; A=oBody.getElementsByTagName('A')[0];
	SetText(A, String.fromCharCode(160)); setTimeout("PLS_FixTbl()", 1);
	}

PLTbl.style.display=(!Gec ? 'block' : 'table');
if (MinPriceId) PLS_ShowMinPrice(oMinTbl, MinPrice, MinPriceId);
}

function PLS_FixTbl(){
var PLTbl=getbyid(PLS_TblId); var aTBodies=PLTbl.tBodies;
aTBodies[2].style.display='none'; aTBodies[3].style.display='none';
}

function PLS_ShowAst(oBody, SupId){
var aSpans, oSpan;

aSpans=oBody.getElementsByTagName('SPAN');
for(i=0; i<aSpans.length; i++){
	oSpan=aSpans[i];
	if (oSpan.className!='Ast') continue;
	oSpan.style.display=(SupId=='17' || SupId=='40' ? 'inline' : 'none');
	break;
	}
}

function PLS_ShowPricesSmall(PLS_Prices, aRows, aSIds){
var RowNo, oRow, oCell, SupNo=-1, SupId, MedId, aPrices, aPrice, Str, A, 
	aNAIds=[], oMinTbl=getbyid('minprice'), MinPrice=1000, MinPriceId, Price;

for(RowNo=0; RowNo<aRows.length; RowNo++){
	oRow=aRows[RowNo]; oCell=oRow.cells[0];
	
	if (oCell.colSpan>1 && oRow.cells.length==1){
		//No tables no links - image row
		if (!oCell.getElementsByTagName('TABLE').length && !oCell.getElementsByTagName('A').length) continue;
		SupNo++; SupId=aSIds[SupNo]; aPrices=PLS_Prices[SupId]; 
		continue;
		}
	
	oCell=oRow.cells[1];
	if (aPrices){
		MedId=getat(oRow, "MedId"); if (!MedId) continue;
		aPrice=aPrices[MedId];
		
		if (aPrice){
			SetText(oCell, "$"+aPrice[0]+" per Pill");
			oCell=oRow.cells[2]; 
			A=oCell.getElementsByTagName('A')[0];
			if (A) A.href=PLS_GetPriceHRef(aPrice[1]);
			
			if (oMinTbl){
				Price=parseFloat(aPrice[0]);
				if (Price<MinPrice){
					MinPrice=Price; MinPriceId=aPrice[1];
					}
				}
			
			}
		else{
			aNAIds[aNAIds.length]=SupId+","+MedId;
			}

		}
	else{
		SetText(oCell, "n/a"); ClearCell(oRow.cells[2]);
		aNAIds[aNAIds.length]=SupId;
		}
	}

if (MinPriceId) PLS_ShowMinPrice(oMinTbl, MinPrice, MinPriceId);

/*if (aNAIds.length){
	//For Errorsbase
	oPLS.ErrImg=D.createElement("IMG");
	oPLS.ErrImg.src="http://price-list.sopserver.com/pricenotfound.php?data="+aNAIds.join(";")+"&host="+W.location.host;
	} */
}

function ClearCell(oCell){
var aNodes=oCell.childNodes, i;
for(i=aNodes.length-1; i>=0; i--) oCell.removeChild(aNodes[i]);
}

function PLS_ShowMinPrice(oMinTbl, MinPrice, MinPriceId){
var oRow, oCell, oTbl, aTbls, aLinks, i;

aTbls=oMinTbl.getElementsByTagName('TABLE');
if (aTbls.length) oTbl=aTbls[0]; else oTbl=oMinTbl;
oRow=oTbl.rows[0]; SetText(oRow.cells[0], '$'+MinPrice);
aLinks=oMinTbl.getElementsByTagName('A');

for(i=0; i<aLinks.length; i++){
	aLinks[i].href=PLS_GetPriceHRef(MinPriceId);
	aLinks[i].target='_blank';
	}

}

function PL_SupMouse(Sup){
PL_Status('Learn about '+Sup); return true;
}

function PL_Status(Msg){W.status=Msg;}

function PL_SupDescr(A){
var oScreen=W.screen;

W.open(A.href, '_blank', 'width=780,height='+Math.round(oScreen.height/1.5)+',left='+(780/4)+
	',top='+Math.round(oScreen.height/8)+',scrollbars=yes,toolbar=no,menubar=no,status=no,resizable=yes');
//IE!
if (!Gec && W.event) W.event.cancelBubble=true;

return false;
}

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

function PLS_OMDown(e){
var p, Tag, HRef, bChg, Host;

PLS_EventInit(e); Tag=EvSrc.tagName;
if (Tag!='A' && Tag!='AREA'){
	if (!Tag) return;
	Tag=EvSrc.parentNode.tagName;
	if (Tag!='A' && Tag!='AREA') return;
	EvSrc=EvSrc.parentNode;
	}

if (oPLS.LastEvSrc==EvSrc) return;
oPLS.LastEvSrc=EvSrc;

HRef=EvSrc.href;
if ((p=HRef.indexOf('#http:'))!=-1){
	HRef=HRef.substr(p+1); bChg=true;
	}
else if (HRef.indexOf('/go2phar'+'macy.php')!=-1){
	if (HRef.indexOf(KT_UId)!=-1) return;

	if (!qseid){
		Host=W.location.host;
		if (Host.substr(0, 4).toLowerCase()=='www.') Host=Host.substr(4);
		}
	
	EvSrc.href+='&u='+KT_UId+(qseid ? '&qseid='+qseid : '&h='+Host+(oKTImg.QSe ? '&qse='+oKTImg.QSe : ''));
	return;
	}

while(true){
	if (!qseid) break;
	if (HRef.indexOf("="+qseid)!=-1) break;
	HRef=HRef.replace(/([&?])(said|tid|data1|keywords|s)=\d+/, "$1$2="+qseid); bChg=true; //?
	break;
	}

if (bChg) EvSrc.href=HRef;
}

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

function PLS_SetHandlers(PLDiv){

if (oPLS.bHandle) return;
PLS_SetH("onmousedown", PLS_OMDown, PLDiv);
PLS_SetH((!Gec ? 'onactivate' : (FFVer>=3 ? 'onkeydown' : 'onfocus')), PLS_OMDown, PLDiv);
oPLS.bHandle=1;
} 

function PLS_SetH(Ev, F, O){
if (!O) O=D;
if (O.attachEvent) O.attachEvent(Ev, F); else O.addEventListener(Ev.substr(2), F, false);
}

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

InitUA(); PLS_Init(); 
if (W.PLS_Params) PLS_Load(PLS_Params);

