var wlForm=null;
var wlA=new Array(); // [ticker,price,change,perChange,tLow,tHigh,tVol,volume]
var wlNewA=new Array();
var wlAlert=new Array(); // [ticker,current value,target value, type]
var wlUpColor="green";
var wlDownColor="red";
var wlDataWin=null;
var wlColSym=0,wlColPrice=1,wlColChange=2,wlColPChange=3,wlColTLow=4,wlColTHi=5,wlColTVol=6,wlColVol=7;
var wlNewsNum=0; // news counter
var wlNewsA=new Array(); // news array
var wlNewsTimer=null;
var wlShowNews=true;
if(typeof(wlDefaultTickers)=='undefined') var wlDefaultTickers="XLY,XLP,XLE,XLF,XLV,XLI,XLB,XLK,XLU";
if(typeof(wlMiddleware)=='undefined') var wlMiddleware="/watchlist/?do=mw&";

function wlLoadLists(){
	var frm=document.wlManager;
	frm.watchlists.options.length=0;
	if(wlList.length<=1)
		frm.delWL.disabled=true;
	else
		frm.delWL.disabled=false;
	for (i=0;i<wlList.length;i++){
		if(wlList[i][0]==wlID)
			var sel=true;
		else
			var sel=false;
		frm.watchlists.options[i] = new Option("  "+wlList[i][1],wlList[i][0],false,sel);
	}
}

function wlUpdateList(wl,wlname){
	var exists=false;
	if(wlList.length){
		for (i=0;i<wlList.length;i++){
			if(wlList[i][0]==wl){
				exists=true;
				wlList.splice(i,1);
				break;
			}
		}
	}
	if(!exists) wlList.push(new Array(wl,wlname));
	wlLoadLists();
}

function wlAddNew(){
	var wlName=window.prompt("Enter a name for your new Watchlist:","");
	var alreadyExist=false;
	if(wlName==""){
		alert("Please enter a name for your watchlist or click 'Cancel'.");
		wlAddNew();
	} else if(wlName==null){
		return;
	}
	for(var i=0;i<wlList.length;i++){
		if(wlList[i][1]==wlName.trim()){
			alreadyExist=true;
			break;
		}
	}
	if(alreadyExist){
		alert(wlName+" already exists. Please enter a different name.");
		wlAddNew();
	}
	var resp=xmlHTTPRequest(wlMiddleware+'type=addwl&wlspdrID='+wlspdrID+'&r='+Math.round(Math.random()*10000)+'&wlname='+wlName,'GET');
	resp=resp.trim();
	if(resp.length) {
		try{
			wlProcessResp(resp);
			wlUpdateList(wlID,wlNewName);
			wlA=new Array();
			wlDataWin.wlBuild();
		} catch(e){}
	}
}

function wlDelete(){
	var wlName="";
	for(var i=0;i<wlList.length;i++){
		if(wlList[i][0]==wlID){
			wlName=wlList[i][1];
			break;
		}
	}
	if(window.confirm("Do you want to delete "+wlName+"?")){
		var resp=xmlHTTPRequest(wlMiddleware+'type=delwl&wlspdrID='+wlspdrID+'&r='+Math.round(Math.random()*10000)+'&wlid='+wlID,'GET');
		resp=resp.trim();
		if(resp.length) {
			try{
				wlProcessResp(resp);
				wlUpdateList(wlID);
				wlID="";
				wlLoad();
			} catch(e){}
		}
	}
}

function wlWrite(lay,str){ document.getElementById(lay).innerHTML=str; }

// Get list of tickers
function wlTickerList(){
	var tickList="";
	for(var i=0; i<wlA.length; i++){
		if(tickList.length) tickList=tickList+",";
		tickList=tickList+wlA[i][wlColSym];
	}
	return tickList;
}

// Add ticker to watchlist
function wlAddTicker(newSym,type){
	if(typeof(newSym)=='undefined') newSym=removeSpaces(wlForm.newTicker.value);
	if(typeof(ssLayer)!='undefined') ssLayer.style.visibility="visible";
	var addCt=0;
	var msg="";
	var ticks=new Array();
	// check to see if ticker is not null and it doesn't exist
	if(newSym.length) var symArray=newSym.split(/,/); else var symArray=new Array();
	if(symArray.length){
		for(var sym=0;sym<symArray.length;sym++){
			var add=true;
			var thisSym=symArray[sym].toUpperCase().trim();
			if(thisSym.length>0 && thisSym.length <= 7){
				for(var i=0; i<wlA.length; i++){ if(wlA[i][wlColSym]==thisSym){ add=false; break; } }
				if(add){	addCt++; wlA[wlA.length]=new Array(thisSym,'','','','','','',''); ticks[ticks.length]=thisSym; }
			}else if(thisSym.length > 7){
				msg='Can\'t be longer than 7 characters.';
			}
		}
		if(addCt>0){
			if(type!='init')
				wlAdd(ticks.join());
			else
				wlUpdate(ticks.join());
			wlDataWin.wlBuild();
			var addS=(addCt>1)?"s":"";
			if(type!='init'){ msg=addCt+' ticker'+addS+' added.'; wlDataWin.scroll(0,999999);}
		} else {
			if(!msg.length) msg='Ticker(s) already exist.';
		}
	} else {
		msg='Enter a ticker to add.';
	}
	wlForm.newTicker.value="";
	if(window.ssVis) ssVis(0);
	if(msg.length) wlWriteMsg(msg);
}

// Sorting functions
var wlColIdx=0;
var wlSortDir=0;
function wlSortFunc(a,b){
	if(a[wlColIdx-1]<b[wlColIdx-1]) return -1;
	if(a[wlColIdx-1]>b[wlColIdx-1]) return 1;
	return 0;
}

function wlSortNumFunc(a,b){
	var aa=parseFloat(a[wlColIdx-1]);
	if (isNaN(aa)) aa = 0;
	var bb=parseFloat(b[wlColIdx-1]);
	if (isNaN(bb)) bb = 0;
	return aa-bb;
}

function wlSort(clid){
	if(wlColIdx!=0) document.getElementById("head"+eval(wlColIdx-1)).className="sortheader";
	var sortfn=wlSortNumFunc;
	if(wlColIdx!=clid+1){
		if(clid+1 >=5) wlSortDir=1; else wlSortDir=0;
		wlColIdx=clid+1;
	}else{
		wlSortDir=(wlSortDir==0)?1:0;
	}
	document.getElementById("head"+clid).className="sortheader sortheaderOn";
	if(wlColIdx==1) sortfn=wlSortFunc;
	wlA.sort(sortfn);
	if(wlSortDir==1) wlA.reverse();
	wlDataWin.wlBuild();
	wlDataWin.scroll(0,0);
}

function wlChangeColors(el){
	var color=el.options[el.selectedIndex].value;
	switch(color){
		case '1': wlUpColor="green"; wlDownColor="red"; break;
		case '2': wlUpColor="#999900"; wlDownColor="blue"; break;
		case '3': wlUpColor="black"; wlDownColor="black"; break;
	}
	if(color!=0) wlDataWin.wlBuild();
}

// Delete ticker from array
function wlDelTicker(sym){
	for(var i=0; i<wlA.length; i++){
		if(wlA[i][wlColSym]==sym){
			wlA.splice(i,1);
			if(wlspdrID.length && wlID.length)
				xmlHTTPAsyncRequest(wlMiddleware+'type=delete&wlspdrID='+wlspdrID+'&wlid='+wlID+'&r='+Math.round(Math.random()*10000)+'&sym='+sym,'GET',"","wlLoadResp");
			else
				wlWriteMsg(sym+' removed. Log in to save changes.');
			break;
		}
	}
}

function wlProcessResp(resp){
	if(resp.length){
		try{
			eval(resp);
		}catch(e){/*alert(e.message);*/}
	}
}

function wlUpdateData(wlNewA,sameIndex){
	if(wlNewA.length){
		if(sameIndex){
			for(var i=0;i<wlA.length;i++){
				for(var j=0;j<4;j++){ wlA[i][j]=wlNewA[i][j]; }
				wlA[i][wlColVol]=wlNewA[i][4];
			}
		}else{
			for(var i=0;i<wlA.length;i++){
				for(var j=0;j<wlNewA.length;j++){
					if(wlA[i][wlColSym]==wlNewA[j][0]){
						wlA[i][wlColPrice]=wlNewA[j][1];
						wlA[i][wlColChange]=wlNewA[j][2];
						wlA[i][wlColPChange]=wlNewA[j][3];
						wlA[i][wlColVol]=wlNewA[j][4];
						break;
					}
				}
			}
		}
	}
}

// functions to retrieve data
function wlAdd(sym){
	var resp=xmlHTTPRequest(wlMiddleware+'type=add&wlspdrID='+wlspdrID+'&wlid='+wlID+'&r='+Math.round(Math.random()*10000)+'&sym='+sym,'GET').trim();
	if(resp.length){
		try{
			wlProcessResp(resp);
			wlUpdateData(wlNewA,false);
			wlDataWin.wlBuild();
		}catch(e){/*alert(e.message);*/}
	}
}

function wlLoad(){
	if(wlspdrID.length)
		xmlHTTPAsyncRequest(wlMiddleware+'type=load&r='+Math.round(Math.random()*10000)+'&wlspdrID='+wlspdrID+'&wlid='+wlID,'GET',"","wlLoadResp");
	else
		wlAddTicker(wlDefaultTickers,'init'); // default tickers
}

function wlLoadResp(){
	if (xmlhttp.readyState==4 && xmlhttp.status==200) {
		var resp=xmlhttp.responseText.trim();
		if(resp.length) {
			try{
				wlAlert=new Array();
				wlProcessResp(resp);
				wlUpdateData(wlNewA,false);
			}catch(e){/*alert(e.message);*/}
			wlDataWin.wlBuild();
			if(wlAlert.length)
				wlAlerts();
			else
				wlCheckTargets();
		}
  }
}

function wlUpdate(tList){
	if(typeof tList=='undefined') tList=wlTickerList();
	wlWrite('wlDate','Retrieving Data . . .'); 
	xmlHTTPAsyncRequest(wlMiddleware+'type=getData&wlspdrID='+wlspdrID+'&wlid='+wlID+'&r='+Math.round(Math.random()*10000)+'&wlTickers='+tList,'GET',"","wlUpdateResp","wlHTTPUpdate");
}

function wlUpdateResp(){
	if (wlHTTPUpdate.readyState==4 && wlHTTPUpdate.status==200) {
		var resp=wlHTTPUpdate.responseText.trim();
		if(resp.length) {
			try{
				wlProcessResp(resp);
				wlUpdateData(wlNewA,true);
			}catch(e){/*alert(e.message);*/}
			wlCheckTargets();
			wlDataWin.wlBuild();
		}
  }
}

function wlDispNews(){
	if(wlNewsA.length){
		if(wlNewsNum>=wlNewsA.length) wlNewsNum=0;
		if(wlNewsNum<0) wlNewsNum=wlNewsA.length-1;
		wlWrite('wlNews','<a href="'+wlNewsA[wlNewsNum][1]+'" target="_blank">'+wlNewsA[wlNewsNum][0]+'</a>'); 
	}
}

function wlShowAlert(sym,current,target,type){
	if(type=="lowPrice")
		alert(sym+" has a price of "+current+", which is below or equal to the target price of "+target+".");
	else if(type=="hiPrice")
		alert(sym+" has a price of "+current+", which is above or equal to the target price of "+target+".");
	else if(type=="hiVol")
		alert(sym+" has a volume of "+current+", which is above or equal to the target volume of "+target+".");
}

function wlWriteMsg(msg){
	wlWrite('wlMsg',msg);
	setTimeout("wlWrite('wlMsg','')",5000);
}

function wlAlerts(){
	var alertList="";
	wlWrite('wlAlertID',"");
	if(wlAlert.length){
		for(var i=0;i<wlAlert.length; i++){
			if(alertList.length) alertList+=", ";
			alertList+='<a href="javascript:wlShowAlert(\''+wlAlert[i][0]+'\',\''+wlAlert[i][1]+'\',\''+wlAlert[i][2]+'\',\''+wlAlert[i][3]+'\')"><b>'+wlAlert[i][0]+'</b></a>';
		}
		wlWrite('wlAlertID',alertList+" (Click on ticker to view alert.)");
	} else {
		wlWrite('wlAlertID',"None.");
	}
	wlDataWin.wlBuild();
}

function wlCheckTargets(){
	wlWrite('wlAlertID',"");
	wlAlert=new Array();
	for(var i=0;i<wlA.length;i++){
		if(wlA[i][wlColTLow] && (!isNaN(wlA[i][wlColPrice]) && !isNaN(wlA[i][wlColTLow])) && (parseFloat(wlA[i][wlColPrice]) <= parseFloat(wlA[i][wlColTLow]))) wlAlert[wlAlert.length]=new Array(wlA[i][wlColSym],wlA[i][wlColPrice],wlA[i][wlColTLow],'lowPrice');
		if(wlA[i][wlColTHi] && (!isNaN(wlA[i][wlColPrice]) && !isNaN(wlA[i][wlColTHi])) && (parseFloat(wlA[i][wlColPrice]) >= parseFloat(wlA[i][wlColTHi]))) wlAlert[wlAlert.length]=new Array(wlA[i][wlColSym],wlA[i][wlColPrice],wlA[i][wlColTHi],'hiPrice');
		if(wlA[i][wlColTVol] && (!isNaN(wlA[i][wlColVol]) && !isNaN(wlA[i][wlColTVol])) && (parseFloat(wlA[i][wlColVol]) >= parseFloat(wlA[i][wlColTVol]))) wlAlert[wlAlert.length]=new Array(wlA[i][wlColSym],wlA[i][wlColVol],wlA[i][wlColTVol],'hiVol');
	}
	wlAlerts();
}

// synchronize column widths
function syncWidths(cols){
	var t=document.getElementById('colHead');
	for(var i=1;i<cols.length;i++){
		t.rows[0].cells[i].style.width=cols[i]-4;
	}
}

function removeSpaces(str) {
	var tstr = "";
	str=''+str;
	splitstr=str.split(" ");
	for(var i=0;i<splitstr.length;i++)tstr += splitstr[i];
	return tstr;
}

// init function
function wlInit(frm){
	wlForm=document.forms[frm];
	wlDataWin=window.frames['wlFrame'];
	if(wlspdrID.length && wlPrem) wlLoadLists();
	wlLoad();
	window.setInterval("wlUpdate()",300000);
}
function wlCloseWin(){top.close(self)}


