﻿function sysError(){return true;}
window.onerror = sysError;

//used for Expanding Quotes Arrays (L prefix used all around for Expanding Qc)
var Lbidarr
var Laskarr
var Lqnamearr 
var Lchangearr
var Lhigharr
var Llowarr
var Lprevhigharr
var Lprevlowarr
var Lqarrowarr

//used for close Quotes Arrays
var bidarr
var askarr
var qnamearr
var qarrowarr

//used for both expanding and close Qc
var fPoints

var loaded=false;
var timer1;
var prd = 3; // Day Trading by default
var wasRL = false;
var iu = new Image(9,5);
var id = new Image(9,5);
iu.src = "i/Forex.arrow_up.gif";
id.src = "i/Forex.arrow_down.gif";

function isLocked(index){
	return arrLockedItems[index];
}

var hasLockedItems = false;
function lockItem(cur1, cur2)
{
    if (qnamearr == null || qnamearr == "undefined") return false;
	hasLockedItems=true;
	var s1=cur1 + "/" + cur2;
	var s2=cur2 + "/" + cur1; 
	for(i=0; i < qnamearr.length; i++)
	{
		if(qnamearr[i].innerHTML == s1 || qnamearr[i].innerHTML == s2)
		{	
			arrLockedItems[i]=true;
			break;
		}
	}
}

function unlockAllItems()
{
	for(i=0; i < arrLockedItems.length; i++)
		arrLockedItems[i]=false;
	hasLockedItems=false;
}
function createlPopup()
{
    this.isOpen=false;
    this.Content;
    this.Coniframe1;
    this.Close=function()
    {
        isOpen=false;
        this.Content.style.display="none";
    }
    var checkload = function()
    {
        if (parent.window.gebi("LpopUp") != null)
        {
            inter=null;
            onloadCreate();
        }
        else
            inter = setTimeout(checkload,10); 
    }
    this.MakeArrQc=function()
    {
        bidarr = QcCreateIdsArray("bid","td");
        askarr = QcCreateIdsArray("ask","td");
        qnamearr = QcCreateIdsArray("qname","td");
        qarrowarr = QcCreateIdsArray("qarrow","img");
        fPoints = QcCreateIdsArray("fPoints","td");
    }
    this.MakeArrQcExpand=function()
    {
        Lbidarr = LpopcreateIdsArray("bid","td");
        Laskarr = LpopcreateIdsArray("ask","td");
        Lqnamearr = LpopcreateIdsArray("qname","td");
        Lchangearr  = LpopcreateIdsArray("change","td");
        Lhigharr  = LpopcreateIdsArray("high","td");
        Llowarr  = LpopcreateIdsArray("low","td");
        Lprevhigharr  = LpopcreateIdsArray("prevhigh","td");
        Lprevlowarr  = LpopcreateIdsArray("prevlow","td");
        Lqarrowarr = LpopcreateIdsArray("qarrow","img");
    }
    var onloadCreate = function()
    {
        lPopup.Content = parent.window.gebi("LpopUp");
		lPopup.Coniframe1= parent.window.gebi("Conifrm");
		//iframe1.src = "Forex.QuotesBoxExpand.aspx";
		lPopup.Coniframe1.style.backgroundColor="Transparent";
		lPopup.Content.style.position="absolute";
        lPopup.Content.style.top=eval(parent.window.findPosY(parent.window.gebi("_qBox"))+"-3.5") + "px";
        if(navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Safari") != -1)
        {
            lPopup.Coniframe1.style.height="247px";
            lPopup.Coniframe1.style.width="455px";
	        lPopup.Content.style.left=eval(parent.window.findPosX(parent.window.gebi("_qBox")) + "+" + parent.window.gebi("_qBox").clientWidth+"-" +lPopup.Coniframe1.style.width.replace("px","")+"+4") + "px";
	    }
	    else
	    {
	        lPopup.Coniframe1.style.height="240px";
	        lPopup.Coniframe1.style.width="455px";
	        lPopup.Content.style.left=eval(parent.window.findPosX(parent.window.gebi("_qBox")) + "+" + parent.window.gebi("_qBox").clientWidth+"-" +lPopup.Coniframe1.style.width.replace("px","")+"+5") + "px";
	    }
        lPopup.Content.style.backgroundColor="Transparent";
        lPopup.Content.style.display="none";
        lPopup.Content.style.zIndex="1000";
        lPopup.Content.style.margin="0px 0px 0px 0px";
        lPopup.isOpen = false;
        lPopup.MakeArrQc();
        inter=null;
		lPopup.buildPopUp();
	}
    this.Create = function()
    {
        inter = setTimeout(checkload,100);
    }
    var inter;
    this.buildPopUp=function()
    {
        if (lPopup)
        {
            if (lPopup.Coniframe1)
            {
                if (lPopup.Coniframe1.contentWindow.document.body!=null)
                {
                    if (lPopup.Coniframe1.contentWindow.document.body.innerHTML!="" && (lPopup.Coniframe1.contentWindow.document.body.innerHTML.indexOf('<TR>\r\n<TD>*</TD></TR>') != -1 || lPopup.Coniframe1.contentWindow.document.body.innerHTML.indexOf('<tr><td>*</td></tr>') != -1 ))
                    {
                        BuildRows();
                        afterLoad();
                    }
                    else
                        inter = setTimeout(lPopup.buildPopUp,100);
                }
                else
                    inter = setTimeout(lPopup.buildPopUp,100);
            }
            else
                inter = setTimeout(lPopup.buildPopUp,100);
        }
        else
            inter = setTimeout(lPopup.buildPopUp,100);
    };
    var afterLoad=function()
    {
        lPopup.MakeArrQcExpand();
    };
}

function setMode(p, curr1, curr2, mid_rate, half_spr)
{
	if(p && (p > 0 && p < 5)) 
	{
		prd=p;
		if(curr1 && curr2)
		{
			lockItem(curr1, curr2);
			var s1=curr1 + "/" + curr2;
			var s2=curr2 + "/" + curr1;
			if(mid_rate && half_spr)
			{
			    if (qnamearr == null || qnamearr == "undefined") return false;
			    var itr=0;
				for(itr=0; itr < qnamearr.length; itr++)
				{
					if(qnamearr[itr].innerHTML == s1 || qnamearr[itr].innerHTML == s2)
					{	
						arrSpreads[p-1][itr] = half_spr = Math.abs(half_spr);
						updateQuote(itr,mid_rate,half_spr);

						if(window.parent && window.parent.qbpuRef != null && window.parent.qbpuRef.updateQuote)
						{
							window.parent.qbpuRef.updateQuote(itr,mid_rate,half_spr);
						}
						break;
					}
				}
			}
		}
		else unlockAllItems();
	}
	else {prd=3; unlockAllItems();}	
}
var lPopup;
function pageOnLoad()
{
	if(save_mid.length > 0)
	{
	    lPopup = new createlPopup();
	    lPopup.Create();
		getQuotes();
	}
	
	loaded=true;
}

function msieVersion()
{
	var ua = window.navigator.userAgent;
	var msie = ua.indexOf ("MSIE ");
	if (msie > 0) return parseFloat(ua.substring(msie+5,ua.indexOf(";",msie)));
	else return 0;
}

function getQuotes()
{
     QuotesService.GetQuotes(cpList, ((lPopup != null && lPopup.isOpen) ? 2 : 1) , userId * 1, prd * 1, myCallback);
}

function myCallback(res)
{
    setQuotes(res.value);
    window.setTimeout(getQuotes,  upInt);
}

function setQuotes(resultStr)
{	
	if(resultStr == null || resultStr == "null" || wasRL) return;
	
	var results = resultStr.split("|");
	var qnameLength= document.getElementById("tlbForex").rows.length-2;
	
	if(results[0]*1 == -1)
	{
		if (!hasLockedItems)
		{
			wasRL=true;
			pageOnUnLoad();
			alert("Time out expiry. Press OK to return to home page.");
			if(parent && parent._Logout) parent._Logout();
		}
		return;
	}
	
	// Server Mode - Quotes box is closed (bid, ask)
    if(results.length == qnameLength * 2)
    {
	    for(i=0; i<qnameLength; i++)
	    {
		    if(!isLocked(i))
		    {
		        updateQuoteInServerMode(i, arrSpreads[prd-1][i*2] /*spread*/, results[i*2]*1/*bid*/, results[i*2+1]*1/*ask*/);
		    }
		}
    }

    // Server Mode - Quotes box is open (highMid, lowMid, change, prevHigh, prevMid, bid, ask)
    if(results.length == qnameLength * 7)
    {
	    for(i=0; i<qnameLength; i++)
	    {
		    var half_spr = arrSpreads[prd-1][i]*1;
		    var fp = fPoints[i].attributes["value"].value;
		    var old_html_bid = bidarr[i].innerHTML;
		    var old_html_ask = askarr[i].innerHTML;
			
		    if(!isLocked(i))
		    {
		        updateQuoteInServerMode(i, half_spr, results[i*7+5]*1 /*bid*/, results[i*7+6]*1 /*ask*/);
		    }
			
		    else if(bidarr[i].innerHTML == '')
		    {
			    bidarr[i].innerHTML = bid[i].innerHTML; 
			    askarr[i].innerHTML = ask[i].innerHTML; 
		    }
			
		    Lchangearr[i].innerHTML = '' + (results[i*7+2]*1 != 0 ? getFormatedNumber(results[i*7+2]*1, 2) : "0.00") + '&nbsp;%';
		    if(results[i*7+2]*1 == 0) Lchangearr[i].className = "black_value";
		    else Lchangearr[i].className = (results[i*7+2]*1 < 0 ? "red_value" : "green_value");

		    Lhigharr[i].innerHTML = '' + getFormatedNumber(results[i*7]*1 + half_spr, fp);
		    Llowarr[i].innerHTML = '' + getFormatedNumber(results[i*7+1]*1 - half_spr, fp);
			
		    Lprevhigharr[i].innerHTML = '' + getFormatedNumber(results[i*7+3]*1 + half_spr, fp);
		    Lprevlowarr[i].innerHTML = '' + getFormatedNumber(results[i*7+4]*1 - half_spr, fp);	
	    }		
    }
	
	// Client Mode - Quotes box is closed - 1 param (midRate)
    if(results.length == qnameLength) // midRate
    {
	    for(i=0; i<qnameLength; i++)
	    {
	        if(!isLocked(i))
	            updateQuote(i, results[i], arrSpreads[prd-1][i]/*spread*/);
        }
    }	

    // Client Mode - Quotes box is open - 6 params (midRate, highMid, lowMid, change, prevHigh, prevMid)
    if(results.length == qnameLength * 6)
    {
        
	    for(i=0; i<qnameLength; i++)
	    {
		    var half_spr = arrSpreads[prd-1][i]*1;
		    var fp = fPoints[i].attributes["value"].value;
		    var old_html_bid = bidarr[i].innerHTML;
		    var old_html_ask = askarr[i].innerHTML; 
			
		    if(!isLocked(i)) 
		        updateQuote(i, results[i*6], half_spr);

		    Lchangearr[i].innerHTML = '' + (results[i*6+3]*1 != 0 ? getFormatedNumber(results[i*6+3]*1, 2) : "0.00") + '&nbsp;%';
		    if(results[i*6+3]*1 == 0) Lchangearr[i].className = "black_value";
		    else Lchangearr[i].className = (results[i*6+3]*1 < 0 ? "red_value" : "green_value");
			
		    Lhigharr[i].innerHTML = '' + getFormatedNumber(results[i*6+1]*1 + half_spr, fp);
		    Llowarr[i].innerHTML = '' + getFormatedNumber(results[i*6+2]*1 - half_spr, fp);
			
		    Lprevhigharr[i].innerHTML = '' + getFormatedNumber(results[i*6+4]*1 + half_spr, fp);
		    Lprevlowarr[i].innerHTML = '' + getFormatedNumber(results[i*6+5]*1 - half_spr, fp);
	    }		
    }
}

function updateQuote(qindex, mid_rate, half_spr)
{
	if(save_mid[qindex]*1 > mid_rate*1)
	{
	    document.getElementById("tlbForex").rows[qindex + 2].cells[1].className = document.getElementById("tlbForex").rows[qindex + 2].cells[2].className = "red_value";
	    document.getElementById("tlbForex").rows[qindex + 2].cells[3].childNodes[0].src=id.src;
	}
	if(save_mid[qindex]*1 < mid_rate*1)
	{
	    document.getElementById("tlbForex").rows[qindex + 2].cells[1].className = "green_value";
	    document.getElementById("tlbForex").rows[qindex + 2].cells[2].className = "green_value";
	    document.getElementById("tlbForex").rows[qindex + 2].cells[3].childNodes[0].src=iu.src;
	}
	if(save_mid[qindex]*1 == mid_rate*1)
	{
	    document.getElementById("tlbForex").rows[qindex + 2].cells[1].className = "black_value";
	    document.getElementById("tlbForex").rows[qindex + 2].cells[2].className = "black_value";
	}
	save_mid[qindex] = mid_rate*1;
	
	document.getElementById("tlbForex").rows[qindex + 2].cells[1].innerHTML = '' + getFormatedNumber(mid_rate*1 - half_spr*1, document.getElementById("tlbForex").rows[qindex + 2].cells[3].attributes["value"].value*1);
	document.getElementById("tlbForex").rows[qindex + 2].cells[2].innerHTML = '' + getFormatedNumber(mid_rate*1 + half_spr*1, document.getElementById("tlbForex").rows[qindex + 2].cells[3].attributes["value"].value*1);
	
	if(lPopup != null && lPopup.isOpen)
	{
		Lbidarr[qindex].innerHTML = bidarr[qindex].innerHTML;
		Laskarr[qindex].innerHTML = askarr[qindex].innerHTML;
		Lbidarr[qindex].className = Laskarr[qindex].className = askarr[qindex].className;
		Lqarrowarr[qindex].src = qarrowarr[qindex].src;
	}
}

// This function is a test function for testing the stream of quotes that are being calculated in the server
function updateQuoteInServerMode(qindex, half_spr, bidValue, askValue)
{
    //Due to the differences between IE and FF (which can run this code before all initialization already finished,
    //Make sure all relevant arrays already created
    if (bidarr == undefined || fPoints == undefined)
        return; //pass current quotes Update if arrays are not ready yet
    
    // Calculating the midRate
    var newMid = (bidValue + askValue)/2;
    
	if(save_mid[qindex]*1 > newMid*1) {bidarr[qindex].className = askarr[qindex].className = "red_value"; qarrowarr[qindex].src=id.src;}
	if(save_mid[qindex]*1 < newMid*1) {bidarr[qindex].className = "green_value";askarr[qindex].className = "green_value";qarrowarr[qindex].src=iu.src;}
	if(save_mid[qindex]*1 == newMid*1){bidarr[qindex].className = "black_value";askarr[qindex].className = "black_value";}

	// Save current midRate
	save_mid[qindex] = newMid*1;	

    var fp = document.getElementById("tlbForex").rows[qindex + 2].cells[3].attributes["value"].value*1;
    
    bidarr[qindex].innerHTML = '' + getFormatedNumber(bidValue, fp);
    askarr[qindex].innerHTML = '' + getFormatedNumber(askValue, fp);

	
	if(lPopup != null && lPopup.isOpen)
	{
		Lbidarr[qindex].innerHTML = bidarr[qindex].innerHTML;
		Laskarr[qindex].innerHTML = askarr[qindex].innerHTML;
		Lbidarr[qindex].className = qarrowarr[qindex].className = askarr[qindex].className;
        
		Lqarrowarr[qindex].src = qarrowarr[qindex].src;
	}
	
}

function pageOnUnLoad(){}

function closeQBox()
{
	wasRL=true;
	pageOnUnLoad();
}

var lPopup = null;
function openFullQB()
{
	if(lPopup != null && lPopup.Content )
	{
		lPopup.Content.style.display="block";
		lPopup.isOpen=true;
		getQuotes();
		lPopup.Coniframe1.contentWindow.window.fixSize();
	}
}

function setBoxTitle()
{
    
	if(parent && parent._boxTitle) parent._boxTitle.innerHTML = boxTitle;
}


function BuildRows()
{
    var str = lPopup.Coniframe1.contentWindow.document.body.innerHTML;
    if(navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Safari") != -1)// FireFox
    {
        lPopup.Coniframe1.contentWindow.document.body.innerHTML = str.replace('<tr><td>*</td></tr>',popUpBodyInnerHTML)
        lPopup.Coniframe1.contentWindow.document.getElementById('ppp').height = 24;
    }
    else
    {
        lPopup.Coniframe1.contentWindow.document.body.innerHTML = str.replace('<TR>\r\n<TD>*</TD></TR>',popUpBodyInnerHTML)
        lPopup.Coniframe1.contentWindow.document.getElementById('ppp').height = 10;
    }
	lPopup.Coniframe1.contentWindow.document.getElementById('cng').innerHTML = changeDate;
	lPopup.Coniframe1.contentWindow.document.getElementById('prv').innerHTML = prevDate;
	
}

function popUpBodyInnerHTML()
{
	str="";
	
	for(i=0; i < qnamearr.length; i++){
		str +=
		'<tr bgcolor="' + ((i%2==0) ? "#E3DFDF" : "#FFFFFF") + '" align="center">' +
			'<td class="symbol" id="qname" align="left" >' + qnamearr[i].innerHTML + '</td>'+
			'<td id="bid" class="' + bidarr[i].className + '" UNSELECTABLE="on" onclick="window.parent.document.getElementById(\'_qBox\').contentWindow.bid_OnClick(this);"></td>' +
			'<td id="ask" class="' + askarr[i].className + '" UNSELECTABLE="on" onclick="window.parent.document.getElementById(\'_qBox\').contentWindow.ask_OnClick(this);"></td>' +
			'<td valign="middle" id="fPoints" align="left" UNSELECTABLE="on"><img id="qarrow" src="' + qarrowarr[i].src + '" border="0" WIDTH="9" HEIGHT="5"></td>' +
			'<td id="change" class="black_value" UNSELECTABLE="on"></td>' +
			'<td id="high" class="black_value" UNSELECTABLE="on"></td>' +
			'<td id="low" class="black_value" UNSELECTABLE="on"></td>' +
			'<td id="prevhigh" class="black_value" UNSELECTABLE="on"></td>' +
			'<td id="prevlow" class="black_value" UNSELECTABLE="on"></td>' +
		'</tr>';
	}
	return str;
}
function ECancelBubble(eventObj)
{
    if(navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Safari") != -1)// FireFox
    {
        eventObj.stopPropagation();  
        eventObj.preventDefault();
    }
    else    //IE 
    {
        event.cancelBubble = true;
        event.returnValue  = false;    
    }
    
    return false;
}
function disableEventBubble(e)
{
	 return ECancelBubble(e);
}

function bid_OnClick(tdBid)
{
    var cp = tdBid.parentNode.childNodes[0].innerHTML;
    if(cp != null)
    {
        var arrCurrs = cp.split("/");
        if(arrCurrs.length > 0)
        {
            var sellCurr = arrCurrs[0];
            var buyCurr = arrCurrs[1];
            switch(prd)
            {
                case 2:
                {
                    window.location.replace("Forex.ForwardsTrading.aspx?buyCurr=" + buyCurr + "&sellCurr=" + sellCurr);           
                    break;
                }
                case 3:
                {
                    window.location.replace("Forex.DayTrading.aspx?buyCurr=" + buyCurr + "&sellCurr=" + sellCurr);           
                    break;
                }
                case 4:
                {
                    window.location.replace("Forex.LimitsTrading.aspx?buyCurr=" + buyCurr + "&sellCurr=" + sellCurr);           
                    break;
                }
            }
        }
    }
}

function ask_OnClick(tdAsk)
{
    var cp = tdAsk.parentNode.childNodes[0].innerHTML;
    if(cp != null)
    {
        var arrCurrs = cp.split("/");
        if(arrCurrs.length > 0)
        {
            var sellCurr = arrCurrs[1];
            var buyCurr = arrCurrs[0];
            switch(prd)
            {
                case 2:
                {
                    window.location.replace("Forex.ForwardsTrading.aspx?buyCurr=" + buyCurr + "&sellCurr=" + sellCurr);           
                    break;
                }
                case 3:
                {
                    window.location.replace("Forex.DayTrading.aspx?buyCurr=" + buyCurr + "&sellCurr=" + sellCurr);           
                    break;
                }
                case 4:
                {
                    window.location.replace("Forex.LimitsTrading.aspx?buyCurr=" + buyCurr + "&sellCurr=" + sellCurr);           
                    break;
                }
            }
        }
    }
}


//Create an array from a tag for Expanded Qc iframe
function LpopcreateIdsArray(sid,tagename)
{ 
    var idsArray = new Array();
    var tArr = lPopup.Coniframe1.contentWindow.document.getElementsByTagName(tagename);
    var i=0;
    for(i=0; i<tArr.length;i++)
    {
        if(tArr[i].id == sid)
        {
            idsArray.push(tArr[i]);
        }
    }
    return idsArray; 
}

//Create an array from a tag for close Qc iframe
function QcCreateIdsArray(sid,tagename)
{ 
    var idsArray = new Array();
    var tArr = parent.parent.document.getElementById("_qBox").contentWindow.document.getElementsByTagName(tagename)
    var i=0;
    for(i=0; i<tArr.length;i++)
    {
        if(tArr[i].id == sid)
        {
            idsArray.push(tArr[i]);
        }
    }
    return idsArray; 
}
