
//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, oPKT, oKTImg;

//------------------------------------------------------------------------
//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 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(){

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);
FF3=(Gec && Nav.indexOf('Firefox/3')!=-1);

if (!Gec && !Op){
	Nav.match(/ MSIE (\d+)/);
	if (RegExp.$1>=7) IE7=true;
	if (!IE7) D.execCommand("BackgroundImageCache", false, true);
	if (Nav.indexOf('IEMobile')!=-1) IEMob=true;
	}

}

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_SetHandlers(); 
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_KTImg(oMinTbl);
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;

PLS_KTImg(PLTbl);

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(oParent){

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

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

R=D.referrer; if ((i=R.lastIndexOf("#"))!=-1) R=R.substr(0, i); 
if (R && !R.match("^https?://"+W.location.host)){
	//Copies: pricelistsimple.js, stm31.js, rxcash
	//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)([.][^/]+)?/.*[?&](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);
		KT_SE=SE;
		}
	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'); 
	oImg.style.position='absolute'; oImg.style.visibility='hidden'; 
	oImg.style.width='0px'; oImg.id='KTImg'; 
	oParent.parentNode.insertBefore(oImg, oParent); 
	}
else oImg=new Image();

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

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';
	oImg.seinfo=Q2+":"+SE2;
	}

oKTImg=oImg; KT_UId=uid+"-"+SN;
}

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_OMD(e){
var f;

PLS_EventInit(e);
if (oPKT[E.type]){
	f=oPKT[E.type]; 
	if (PLS_OMD.caller==f || PLS_OMD==f) return;
	f(e);
	}

while(true){

	if (EvSrc.tagName!='A'){
		if (!EvSrc.tagName) break;
		if (EvSrc.parentNode.tagName=='A') EvSrc=EvSrc.parentNode;
		else break; 
		}
	var HRef=EvSrc.href;

	if (HRef.indexOf('.sopserver.com/go2pharmacy.')==-1) break;
	if (HRef.indexOf('&u=')!=-1) break;

	var Host=W.location.host;
	if (Host.substr(0, 4).toLowerCase()=='www.') Host=Host.substr(4);
	EvSrc.href=HRef+'&h='+Host+'&u='+KT_UId+(oKTImg.seinfo ? '&qse='+oKTImg.seinfo : '');

	break;
	}

}

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

function PLS_SetHandlers(){
oPKT={Time:0, Delay:125, aEvents:['onmousedown', (!Gec ? 'onactivate' : (FF3 ? 'onkeydown' : 'onfocus'))]};
PLS_WatchHandlers();
} 

function PLS_WatchHandlers(){
var i, EvName, aEvents=oPKT.aEvents;

for(i=0; i<aEvents.length; i++){
	EvName=aEvents[i];
	if (D[EvName]!=PLS_OMD) PLS_SetHandler(EvName);
	}

oPKT.Time+=oPKT.Delay;
if (oPKT.Time>=7500) return;
setTimeout('PLS_WatchHandlers()', oPKT.Delay);
}

function PLS_SetHandler(EvName){
if (D[EvName] && D[EvName].toString()==PLS_OMD.toString()) return;
oPKT[EvName.substr(2)]=D[EvName]; D[EvName]=PLS_OMD;
}

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

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