//var xmlhttp=false;
var iGlobalCounter = 0; //needed for stoping the GetAjaxDataAndDraw

var sFinanceServiceURL = "/news/scripts/GlobalFinanceData_New.aspx?continent=";

var sGraphURL = "http://images.globes.co.il/chartDirector/finance/SChart.aspx?width=129&height=145&symbol="; //&feeder=0&style=w&exchange=";
var sDelim = "^";
var sDelim1 = "~";

var sTaTabName = "ta";
var sWSTabName = "ws";
var sUSATabName = "usa";
var sEuropeTabName = "europe";
var sAsiaTabName = "asia";

var iTabCount = 5;
var iInstrumentNameLength = 8;
var sQuotesReplaceSign = "~~";

//Create HTTPRequest
var xmlhttp = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest()

function objIndex(instrumentId,last,percentage){
    this.id = instrumentId;
    this.last = last;
    this.percentage = percentage;
    this.mark = false;
}
var arrIndex = new Array();
function PopulateArray(continent,type,rowNumber ,instrumentID,last,percentage)
{
    if( arrIndex.length-1 < rowNumber) {
        arrIndex[rowNumber] = new objIndex(instrumentID,last,percentage)
    }
    else {
        if(arrIndex[rowNumber].id == instrumentID ) {
            if(arrIndex[rowNumber].last!=last || arrIndex[rowNumber].percentage!=percentage) {
                arrIndex[rowNumber].mark = true;
            }
            arrIndex[rowNumber].last = last
            arrIndex[rowNumber].percentage = percentage;
        }
    }
}
function Marker(marker_id, isDefault)
{
    var oName = document.getElementById("tdName_" + marker_id)
    var oPercentage = document.getElementById("tdPercentage_" + marker_id)
    var oLast =  document.getElementById("tdLast_" + marker_id)
    if(oName==null) return;    
    var oNameClassName = oName.className
        
    if(isDefault && oNameClassName!="") {  //unmark
        if(oName.className=="TrayTopRightTD") {
            oPercentage.className = "TrayTopLeftTD";
           oLast.className = "TrayBottomLeftBlackTD" ;
        } 
        else{
            oPercentage.className = "TrayTopLeftTDOff";
            oLast.className = ""; 
        }
    }
    else{   //mark
        if(oNameClassName=="TrayTopRightTD") {//selected item
            oPercentage.className = "TrayTopLeftTDMark";
            oLast.className = "TrayBottomLeftBlackTDMark";
        }
        else {                                  //not selected items
            oPercentage.className = "TrayTopLeftTDOffMArk";
            oLast.className = "TrayTopLeftTDOffMArk";
        }
    }
    
}
function CheckPopulate()
{
    for(var i=0; i<arrIndex.length;i++)
    {
        if(arrIndex[i].mark == true)
        {
            Marker(i,false);
            setTimeout('Marker('+i+',true)',700);
            arrIndex[i].mark = false;
        }
    }
}


function setDefaultTab()
{//alert("zmira - setDefaultTab" )
    for(var itab = 1; itab <= iTabCount; itab++)
    {
        var sName = "tab1_inner" + itab;
        if(itab == 1)document.getElementById(sName).className = "G_PremiumTabsOn";
        else document.getElementById(sName).className = "G_PremiumTabsOff";
    }
}

//Get Array data 
function GetSelectedFinanceData(sContinent,sType,isDefault,tabID)
{
	
    iGlobalCounter++;
    try
    {
        var sArrRes = null;
        document.getElementById("imgGraph").style.display = "";
        document.getElementById("divPlaceHolder").style.display="none";
        document.getElementById("hidContinent").value = sContinent;
      
        for(var itab = 1; itab <= iTabCount; itab++)
        {
           var sMainTabId = "tab" + itab + "_" + itab;                
        }   
        try{   
            switch(sContinent)
            {
                case sTaTabName:
                    sArrRes = globalfinance_arrIndicesTA;  //array from .js file
                    break;
                case sWSTabName:
                    sArrRes = globalfinance_arrIndicesWS;  //array from .js file
                    break;
                case sUSATabName:
                    sArrRes = globalfinance_arrIndicesUSA;  //array from .js file
                    break;
                case sEuropeTabName:
                    sArrRes = globalfinance_arrIndicesEurope;  //array from .js file
                    break;
                 case sAsiaTabName:
                    sArrRes = globalfinance_arrIndicesAsia;  //array from .js file
                    break;
            }
        }
        catch(e){sArrRes = new Array();}
        if((sContinent==sTaTabName || sContinent==sWSTabName ) && sType=='IndicesItem') 
        {   
            DrawInnerTab(sType,tabID,0,1)
        }        
        else if(sArrRes != null)
        {
            DrawResultData(sArrRes,sContinent,isDefault,0);
        }
    }
    catch(ex){}
}

function ChangeBorderColor(tab_name,id)
{
    for(var itab = 1; itab <= iTabCount; itab++)
    {
       try
       {
           var sMainTabId = tab_name + itab;                
           if(itab == id){document.getElementById(sMainTabId).className = "G_WhiteBGColor";}    
           else{document.getElementById(sMainTabId).className = "G_GrayBGColor"; }
       }
       catch(e){} 
    }   
}

function SetDefaultBorderColor(tab_name)
{
    for(var itab = 1; itab <= iTabCount; itab++)
    {
       try
       {
           var sMainTabId = tab_name + itab;                
           if(itab == 1){document.getElementById(sMainTabId).className = "G_WhiteBGColor";}    
           else{document.getElementById(sMainTabId).className = "G_GrayBGColor"; }
       }
       catch(e){} 
    }   
}

//Draw Name,Graph,Last,PercentageChange,Flag
function ShowAllData(sSymbol,sFeeder,sLastPrice,rowID,sPercentage,sFlag,sCountry, sName, sBursa)
{

	var rowOBJ="tr_"+rowID;
	change_left_Border_Onmouseout();
	document.getElementById(rowOBJ).style.backgroundImage="url(../images/border_01.png)"


	try
    {
        var sGraphSource = sGraphURL + sSymbol + "&feeder=" + sFeeder + "&style=b" + (sFeeder!="0" ? "&exchange=" + sBursa : "") ;
        if(sSymbol != "") 
			{
			document.getElementById("imgGraph").src = sGraphSource;
			document.getElementById("imgGraph").width = "129";
			document.getElementById("imgGraph").height = "145";
			document.getElementById("imgGraph").style.paddingTop = "0px";
			}
        if(sName != "") {
            document.getElementById("imgGraph").title = "גרף " + sName;
            document.getElementById("imgGraph").alt = "גרף " + sName;
        }
        var sLastStyle = "OrangeTextB";
        //if(parseFloat(sPercentage) < 0) sLastStyle = "OrangeTextB";
        
        sCountry = sCountry.replace(sQuotesReplaceSign,"\"");
        if(sFlag == "israel") sCountry = "ישראל";
                 
        for(var j=0; j<5; j++)
        {
               
             var sTDName = "tdName_" + j;
             var sTDPercentage =  "tdPercentage_" + j;
             var sTDFlag = "tdFlag_" + j;
             var sTDLast = "tdLast_" + j;
        }
    }
    catch(e){}
}

// Get Array From .js file
function getResultArray(sContinent,sType)
{
    var arrRes = null;
    try
    {
        ////////////////////////////////TA////////////////////////////////////
        if(sContinent == sTaTabName  && sType == "IndicesItem")arrRes = globalfinance_arrIndicesTA;
        if(sContinent == sTaTabName  && sType == "WorkingItem")arrRes = globalfinance_arrWorkingItemTA;
        if(sContinent == sTaTabName  && sType == "IncreaseItem")arrRes = globalfinance_arrIncreaseItemTA;
        if(sContinent == sTaTabName  && sType == "DecreaseItem")arrRes = globalfinance_arrDecreaseItemTA;
        
        ////////////////////////////////WS////////////////////////////////////
        if(sContinent == sWSTabName  && sType == "IndicesItem")arrRes = globalfinance_arrIndicesWS;
        if(sContinent == sWSTabName  && sType == "WorkingItem")arrRes = globalfinance_arrWorkingItemWS;
        if(sContinent == sWSTabName  && sType == "IncreaseItem")arrRes = globalfinance_arrIncreaseItemWS;
        if(sContinent == sWSTabName  && sType == "DecreaseItem")arrRes = globalfinance_arrDecreaseItemWS;
        
        ////////////////////////////////USA////////////////////////////////////
        if(sContinent == sUSATabName  && sType == "IndicesItem")arrRes = globalfinance_arrIndicesUSA;
        if(sContinent == sUSATabName  && sType == "WorkingItem")arrRes = globalfinance_arrWorkingItemUSA;
        if(sContinent == sUSATabName  && sType == "IncreaseItem")arrRes = globalfinance_arrIncreaseItemUSA;
        if(sContinent == sUSATabName  && sType == "DecreaseItem")arrRes = globalfinance_arrDecreaseItemUSA;
        
        ////////////////////////////////EUROPE////////////////////////////////////
        if(sContinent == sEuropeTabName  && sType == "IndicesItem")arrRes = globalfinance_arrIndicesEurope;
        if(sContinent == sEuropeTabName  && sType == "WorkingItem")arrRes = globalfinance_arrWorkingItemEurope;
        if(sContinent == sEuropeTabName  && sType == "IncreaseItem")arrRes = globalfinance_arrIncreaseItemEurope;
        if(sContinent == sEuropeTabName  && sType == "DecreaseItem")arrRes = globalfinance_arrDecreaseItemEurope;
        
        ////////////////////////////////ASIA////////////////////////////////////
        if(sContinent == sAsiaTabName  && sType == "IndicesItem")arrRes = globalfinance_arrIndicesAsia;
        if(sContinent == sAsiaTabName  && sType == "WorkingItem")arrRes = globalfinance_arrWorkingItemAsia;
        if(sContinent == sAsiaTabName  && sType == "IncreaseItem")arrRes = globalfinance_arrIncreaseItemAsia;
        if(sContinent == sAsiaTabName  && sType == "DecreaseItem")arrRes = globalfinance_arrDecreaseItemAsia;
    }
    catch(e){arrRes = new Array();}
    return arrRes;
}

//Draw Inner Tabs
function SetFinanceBorderColor(tab_id)
{
    for(var itab = 1; itab <= iTabCount; itab++)
    {
        try
        {
            var sTabName = "tab1_inner" + itab;
            if(itab == tab_id){document.getElementById(sTabName).className = "G_PremiumTabsOn";}    
            else{document.getElementById(sTabName).className = "G_PremiumTabsOff";}
        }
        catch(e){}    
    }
}

function DrawPortfolioMessage()
{
    var strActiveTable  = '<iframe src="/pay/login.asp?mode=financeblock&p_backTo=/globessites/globes/portfolio/portfolio/Portfolio.aspx?default=true" width="100%" height=100 frameborder=0></iframe>'
                        
    document.getElementById("divDataTable").style.display="none";
    document.getElementById("divPlaceHolder").innerHTML = strActiveTable;
    document.getElementById("imgGraph").style.display="none";
    document.getElementById("divPlaceHolder").style.display="";
       
}

function DrawInnerTab(sType,id,isPortfolio,innerTabId)
{   
    innerTabId = (arguments.length>3 ? innerTabId : id )

    iGlobalCounter++;
		
    document.getElementById("divDataTable").innerHTML = "";
    document.getElementById("imgGraph").src = "../images/GTO_Loading.gif";
	document.getElementById("imgGraph").width = "32";
	document.getElementById("imgGraph").height = "32";
	document.getElementById("imgGraph").style.paddingTop = "50px";
	
    
    var userID = GetUserID();

	var sContinent = document.getElementById("hidContinent").value
    var today = new Date()
	
   //benny 6-7-2009
  	var sFullUrl ="http://www.globes.co.il" + sFinanceServiceURL + sContinent + "&type=" + sType + "&sid="+ today.getTime();

	
    document.getElementById("imgGraph").style.display="";
    document.getElementById("divPlaceHolder").style.display="none";
	
	
	
   /* if((sContinent == 'ta' || sContinent == 'usa' || sContinent == 'asia') && isPortfolio == 1 )
    {  
        if(userID != ""){sFullUrl = sFinanceServiceURL + sContinent + "&type=" + sType + "&uid=" + userID + "&sid="+ today.getTime();}
        else { return DrawPortfolioMessage() ; }        
    }
    else if((sContinent == 'ws' || sContinent == 'europe')&& isPortfolio == 1)
    {
        sFullUrl = sFinanceServiceURL + sContinent + "&type=workingisrael&sid="+today.getTime();
    }
    else if((sContinent == 'ta' || sContinent == 'ws') && sType == 'IndicesItem') //zmira
    {
        sFullUrl = sFinanceServiceURL + sContinent + "&type=" + sType + "&sid="; //set the time in the GetAjax function
    }
    else  // if not portfolio(not Tab 5)
    {
        var arrResult = getResultArray(sContinent,sType);
        DrawResultData(arrResult,sContinent,1,0);
        return;
    }
    GetAjaxDataAndDraw(sContinent,sType,sFullUrl,iGlobalCounter);*/
	
	var arrResult = getResultArray(sContinent,sType);
	DrawResultData(arrResult,sContinent,1,0);
	return;
}

function GetAjaxDataAndDraw(sContinent,sType,url,currCounter)
{  
    xmlhttp.abort();
    var today =  new Date()
    url = url.substring(0,url.indexOf("&sid=")+5) + today.getTime();
    if(currCounter != iGlobalCounter) {return }
    if((sContinent == 'ta' || sContinent == 'ws' ) && sType == 'IndicesItem') { 
           var secToNextTime = 1000 + ((60 - new Date().getSeconds()) % 30) * 1000 
          setTimeout('GetAjaxDataAndDraw("' + sContinent + '","IndicesItem","'+ url + '",'+ iGlobalCounter + ')', secToNextTime)
	}
	xmlhttp.open("GET", url , true);
	xmlhttp.onreadystatechange = function() { 
        if ( xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("imgGraph").style.display="";
            document.getElementById("divPlaceHolder").style.display="none";
            DrawResultData(xmlhttp.responseText,sContinent,1,1,sType);
    	    }
    	}
	if(xmlhttp && xmlhttp != null) {
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; language=he");
		xmlhttp.setRequestHeader("Content-Length", "0");
		xmlhttp.send(null);
    }
}

//Get UserID From Cookie For User Portfolio Data
function GetUserID()
{
   var result;
   if (document.cookie.length>0)
   {
        return ReadCookieData("UserID");
   }
   else result = "";
   return result;
}      

//Get Data From Array Or Ajax Request (split data array)
function DrawResultData(arrInput,sContinent,isDefault,isAjaxResult,sType)
{
	
    var sRes = "<div style='width:167px;'>";
    var numAfterDot = 2;
    var sfeeder = 1;
    
    var sDefaultSymbol = "";
    var sDefaultFeeder = "";
    
    var sDefaultCountry = "";
    var sDefaultFlag = "";
    var sDefaultLast = "";
    var sDefaultPercentage = "";
    var sDefaultName = "";
    var sDefaultBursaName = "";
    var sDefaultBursa = "";
       
    if(sContinent == sTaTabName) sfeeder = 0;
    
    var arrValueResult = arrInput;
    if(isAjaxResult == 1) arrValueResult = arrInput.split(sDelim);

    for(var i=0; i < arrValueResult.length; i++) 
    {
        try
        {
            var sArrString = arrValueResult[i];
            var sName = "";
            var sSymbol = "";
            var sPercentage = "";
            var sLast = "";
            var sFlag = "";
            var sCountry = "";
            var sInstrumentID = "";
            var sBursaName = "";
            var sFullName = "";
            var sBursa = "";
            
            if(sArrString != null)
            {
                if(isAjaxResult == 1)
                {
                    try{sArrResult = sArrString.split(sDelim1);}catch(e){}
                    try{sName = sArrResult[0]; }catch(e){}
                    try{sPercentage = sArrResult[1];}catch(e){}
                    try{sSymbol = sArrResult[2];}catch(e){}
                    try{sLast = sArrResult[3];}catch(e){}
                    try{sFlag = sArrResult[4];}catch(e){}
                    try{sCountry = sArrResult[5].replace("\"",sQuotesReplaceSign);}catch(e){}                       
                    try{sInstrumentID = sArrResult[6];}catch(e){}
                    try{sBursaName =  sArrResult[7];}catch(e){}
                    try{sBursa = sArrResult[8];}catch(e){}
                    try{sFullName = sArrResult[0].replace("-"," ");}catch(e){}
                   
                    try{sName = (sInstrumentID=='66707' && sfeeder==1)? sName.substr(0,iInstrumentNameLength+1): sName.substr(0,iInstrumentNameLength);
                        sName = sName.replace("-"," ");
                    }catch(e){}
                    
                    try
                    {
                        if(sContinent=="ta" && sType=="IndicesItem")
                            PopulateArray(sContinent,sType,i,sInstrumentID,sLast,sPercentage)
                    }
                    catch(e){alert("in catch"  + e.description)}
                     
                }
                else
                {
                    try{sName = sArrString[0].substr(0,iInstrumentNameLength);sName = sName.replace("-"," ");}catch(e){}
                    try{sSymbol = sArrString[1];}catch(e){}
                    try{sPercentage = sArrString[2];}catch(e){}
                    try{sLast = sArrString[3];}catch(e){}
                    try{sFlag = sArrString[4];}catch(e){}
                    //var sCountry = sArrString[5].replace("\"","&#034;");
                    try{sCountry = sArrString[5].replace("\"",sQuotesReplaceSign);}catch(e){}
                    try{sInstrumentID = sArrString[6];}catch(e){}
                    try{sBursaName = sArrString[7];}catch(e){}
                    try{sBursa = sArrString[8];}catch(e){}
                    try{sFullName = sArrString[0].replace("-"," ");}catch(e){}
                }
				if(sPercentage!="")
	                sPercentage = RoundNum(sPercentage.toString());
				else
					sPercentage=0;
				
                var sTempPercentage = sPercentage;
                var sGraphName = sFullName.replace("\"","``").replace("'","`")
                var linkTitle = sSymbol + "-" + sFullName + " , בורסת " + sBursaName.replace("\"","``").replace("'","`")
				
          		var rowbgcolor=""
				var styleofcolor=""
				
				if(sPercentage=="NaN.00")
					sPercentage=0
						
				
				if((i==0) || ((i%2)==0))
            		rowbgcolor="#141414";
				else
					rowbgcolor="#2a2a2a";

				if(sPercentage>0)
					{
					styleofcolor=" color:#00ff00;";
					}
				else if(sPercentage<0)
					{
					styleofcolor=" color:red;";
					sPercentage=Math.abs(sPercentage);
					sPercentage=sPercentage.toString()+"%"+"-";
					}
				else
					{
					styleofcolor=" color:#00ff00;";
					}
				

               sRes += "<div id='tr_"+i+"' style=' text-align:right; cursor:pointer; padding-top:3px; padding-right:1px; height:28px; background-image:url(../images/border_left_01.png); background-repeat:repeat-y; background-color:"+ rowbgcolor +"' onmouseover='ShowAllData(\"" + sSymbol + "\"," + sfeeder + ",\"" + sLast + "\"," + i + "," + sTempPercentage + ",\"" + sFlag + "\",\"" + sCountry + "\",\""+ sGraphName +  "\",\""+ sBursa + "\");'>";
               sRes += "<div style='float:right; height:28px;  width:67px;' id='tdName_" + i + "'>";
			   sRes += "<a style=' padding-right:5px; padding-top:3px; font-size:12px; "+ styleofcolor +"' >" + sName + "</a>";
			   sRes += "</div>";
               sRes += "<div style='float:right; height:28px; width:48px; text-align:center; font-size:11px;"+ styleofcolor +"' id='tdLast_" + i + "'>" + sLast + "</div>";
               sRes += "<div style='float:right; height:28px; width:48px; text-align:center; font-size:11px;"+ styleofcolor +"' id='tdPercentage_" + i + "'>" + sPercentage + "</div>";
               sRes += "</div>";

			   
                if(isDefault==1 && i==0)
                {
                    sDefaultSymbol= sSymbol;
                    sDefaultFeeder= sfeeder;
                    sDefaultCountry = sCountry;
                    sDefaultFlag = sFlag;
                    sDefaultLast = sLast;
                    sDefaultPercentage = sTempPercentage; 
                    sDefaultName =  sGraphName;
                    sDefaultBursaName = sBursaName;
                    sDefaultBursa = sBursa;
                }
            }
        }
        catch(e){}
    }
    
    sRes += "</div>";
    
    if(sRes.indexOf("<div") == -1)
		{
		document.getElementById("imgGraph").src = "http://images.globes.co.il/images/Site/Finance/Graph_NoData140.gif";
		}
    
    document.getElementById("divDataTable").innerHTML = sRes;
    document.getElementById("divDataTable").style.display= ""
    
    if(isDefault==1)
    {
        ShowAllData(sDefaultSymbol,sDefaultFeeder,sDefaultLast,0,sDefaultPercentage,sDefaultFlag,sDefaultCountry,sDefaultName,sDefaultBursa ); 
    }
    CheckPopulate()
}

//Round number: 2 digits after dot
function RoundNum(sPercentage)
{
    var numAfterDot = 2; 
    var ind = sPercentage.indexOf(".");
    sPercentage = Math.round(parseFloat(sPercentage.substr(0,ind + numAfterDot + 2)) * Math.pow(10,numAfterDot)) / Math.pow(10,numAfterDot);
                
    if(sPercentage.toString().indexOf(".") == -1)sPercentage = sPercentage.toString() + ".00";
                
    var arrPercentage = sPercentage.toString().split(".");
    if(arrPercentage.length == 2)
    {
       var sBeforeDot = arrPercentage[0];
       var sAfterDot = arrPercentage[1];
       if(sAfterDot.length == 1) sAfterDot += "0";
       sPercentage = sBeforeDot + "." + sAfterDot;
    }
    return sPercentage;
}

//Get Color Styles
function ColorValue(value)
{
   var sValue = "" 
   var sSign = "";
   var sClass = "";
   if (value>0){
       color = "#009900";
       sClass = "green"
       sSign = "+";
   }else if(value<0){
       color = "#CC0000";
      sClass = "red"
   }
   else
       color = "#000000";
       
   sValue = value
   var absValue = Math.abs(value)
   if(absValue>=10 && absValue<100)
        sValue = value.toString().substring(0,value.toString().length-1)
   else if(absValue>99)
        sValue = value.toString().substring(0,value.toString().length-3)
   
  
   value = "<h5 dir='ltr' style=\"white-space:nowrap;\"><span style='color:"+ color +";'>" + sSign + sValue + "%" + "<span></h5>";
   return value;
}

function ColorLast(last,percentage)
{
   var color="";
   if (percentage>0){
       color = "#009900";
   }else{
       color = "#CC0000";
   }                                   
   var value = "<h5 dir='ltr' style=\"white-space:nowrap;\">" + last + "</h5>";
   return value;
}

function change_left_Border_Onmouseout()
	{
	for(i=0;i<5;i++)
		{
		rowID="tr_"+i;
		document.getElementById(rowID).style.backgroundImage="url(../images/border_left_01.png)";
		}
	}	
