var req;
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function BidingSession(SessionArray)
{
    
    
    
    if (SessionArray[7]=='Y' ||SessionArray[7]=='I'  )
    {
    
        
        var innerHTMLCell;

        innerHTMLCell = "   Đợt " + SessionArray[8] + ":    <span style='color: #000066'>" +"Vn Index: " + "</span>" ;

        //innerHTMLCell = "   Đợt " + SessionArray[8] + ":    <span style='color: #000066'>" +"Vn Index: " + "</span>" ;
        var ChangePercent = RoundNumber( parseFloat( 100*parseFloat( SessionArray[1])/ parseFloat( SessionArray[2])),2) ;
        if (parseFloat( SessionArray[1])>0)
        {
            innerHTMLCell = innerHTMLCell + "<span style='color: #009933'>" +( parseFloat( SessionArray[0])) + "  ▲" + ( parseFloat( SessionArray[1])) + " (" + ChangePercent +  "%)</span>" ;
        }
        else
        {
            if (parseFloat( SessionArray[1])<0)
            {
                innerHTMLCell = innerHTMLCell + "<span style='color: red'>" + (parseFloat(SessionArray[0] ))+  "  ▼" + ( parseFloat( SessionArray[1])) + " (" + ChangePercent +  "%)</span>" ;
            }
            else
            {
                innerHTMLCell = innerHTMLCell + "<span style='color: #ffff00'>" + (parseFloat(SessionArray[0])) +  " " + ( parseFloat( SessionArray[1])) + " (" + ChangePercent +  "%)</span>" ;
            }
        }
        
        
        innerHTMLCell =innerHTMLCell + "  <span style='color: #000066'>" +"KLGD: " + "<span style='color: blue'>" +  (SessionArray[4]) + "</span></span>" ;
        innerHTMLCell = innerHTMLCell + "   " + "<span style='color: #000066'>" +"GTGD: " + "<span style='color: blue'>" +  (SessionArray[5]) + " VNĐ</span></span>" ;
        
        return innerHTMLCell;
        //alert(1);
        
        
    }
    return "";
    
}

function myResultTotalMKT(totalNKTresult)
{
    
    if (totalNKTresult!=null){
    var LiveTotal = new Array();
    var MktRs = totalNKTresult + '';
    LiveTotal = MktRs.split("**");
    
    
    if (LiveTotal.length >0)
    {
        var MaxSession, dRow=new Array();
        
        var MktTab = document.getElementById("RsTotalMKT");
        var NewestRow;
        dRow = LiveTotal[LiveTotal.length-1].split("|");
   
        var iSession;
        var SessionRsText="";
        var dRow = new Array();
        for (iSession = 0;iSession<LiveTotal.length ; iSession++)
        {
            
           dRow = LiveTotal[iSession].split("|");
           SessionRsText=SessionRsText+ BidingSession(dRow)+"<br>";
        }
        
        var objTextTotal = document.getElementById ("TblTotalRs");
        var objCell = objTextTotal.rows[0];
        
        objCell.cells[0].innerHTML = SessionRsText;
        
        
        NewestRow = MktTab.rows[0];
        if (parseFloat(dRow[1] )>0)
        {
            NewestRow.cells[0].innerHTML =  "Vn Index: <span style='color: #009933'>" +  dRow[0] + "</span>" ;
            NewestRow.cells[1].innerHTML = ": <span style='color: #009933'>" +  "▲ " +  dRow[1] + " (" +  RoundNumber (parseFloat (  100*parseFloat(dRow[1])/parseFloat(dRow[2]) ) ,2)  + "%)" + "</span>";
        }
        else
        {
            if (parseFloat( dRow[1])<0)
            {
                NewestRow.cells[0].innerHTML =  "Vn Index: <span style='color:red'>" + dRow[0] + "</span>" ;
                NewestRow.cells[1].innerHTML = ": <span style='color:red'>" + "▼ " + dRow[1] + " (" +  RoundNumber (parseFloat (  100*parseFloat(dRow[1])/parseFloat(dRow[2]) ) ,2)  + "%)" + "</span>";
            }
            else
            {
                NewestRow.cells[0].innerHTML =  "Vn Index: <span style='color: #ffff00'>" + dRow[0] + "</span>" ;
                NewestRow.cells[1].innerHTML = ": <span style='color: #ffff00'>" +  dRow[1]  + " (" +  RoundNumber (parseFloat (  100*parseFloat(dRow[1])/parseFloat(dRow[2]) ) ,2)  + "%)" + "</span>";
            }
        }
        NewestRow.cells[2].innerHTML = " GD: " +  dRow[3];
        NewestRow.cells[3].innerHTML = "KLGD: " +   dRow[4];
        NewestRow.cells[4].innerHTML = "GTGD: " +   dRow[5] + " VNĐ";
        NewestRow.cells[5].innerHTML = "Ngày: " + dRow[6].substring(0,10);
        
        if (dRow[7]=='Y')
        {
            var LiveTab = document.getElementById("RsQuotes");
            var LiveRow = LiveTab.rows[0];
            SessionID = dRow[8];
            
            LiveRow.cells[5].innerHTML = " (" + SessionID + ")" ;
            
    
            SetTableInDoneMode(true);
        }
        else
        {
            var LiveTab = document.getElementById("RsQuotes");
            var LiveRow = LiveTab.rows[0];
            SessionID = dRow[8];
            
            LiveRow.cells[5].innerHTML = " (" + SessionID + ")" ;
            SetTableInDoneMode(false);
             
        }
    }

}

}

function myResultsSecurityData(result)
{

if (result!=null){


    NewLiveStockSymbol = new Array();
    var SecRs = result + '';
    NewLiveStockSymbol = SecRs.split("**");
    
    if (NewLiveStockSymbol.length>0)
    {
        
        var ItemRow = new Array();
        if (LiveStockSecurity==null){
            LiveStockSecurity = new Array(NewLiveStockSymbol.length );
            
        }
        var iItem;
        if (FirstTime)
        {
            totalLine = NewLiveStockSymbol.length;
            pageSize=totalLine;
            for (iItem=0;iItem<NewLiveStockSymbol.length;iItem++)
            {
                ItemRow = NewLiveStockSymbol[iItem].split("|");
                LiveStockSecurity[iItem] = new Array(ItemRow.length);
                
                LiveStockSecurity[iItem] = new Array(23);
                CopyArrayData(ItemRow,LiveStockSecurity[iItem],23);
             
                
            }
            
            MakingHeader();
            MakingContent();
        }
        else
        {
            for (iItem=0;iItem<NewLiveStockSymbol.length;iItem++)
            {
                ItemRow = NewLiveStockSymbol[iItem].split("|");
                SynchLiveSecurity(ItemRow);
        
             
            }
            
            
        }
        FirstTime=false;
        ShowNextInterval();
    }
    else
    {
     
        
            
        ShowNextInterval();
        
        
    }
    
}
else
{
    
    ShowNextInterval(); 
    
}

}




//Thiet lap trang thai cua Table trong che do khop lenh
function SetTableInDoneMode(SecurityStat)
{
    var LiveTab = document.getElementById("RsQuotes");
    var iRow, dRow;
    //alert(1);
  
    
    
    if (SecurityStat)
    {
        dRow = LiveTab.rows[1];
        dRow.cells[7].innerText = "KL";


      //  LiveTab.cells[15].setAttribute('width','4%' );
        //LiveTab.cells[16].setAttribute('width','6%' );
        
    }
    
    else
    {
        dRow = LiveTab.rows[1];
        dRow.cells[7].innerText = "";
//        LiveTab.cells[15].setAttribute('width','10%' );
  //      LiveTab.cells[16].setAttribute('width','0px' );
       
    }
     

}

function ShowNextInterval()
{

    if (pageSize<LiveStockSecurity.length )
        {
            BindingData(HeaderStock,1,0,0);
            pageRow = pageRow+pageSize-HeaderStock.length ;
            if (pageRow>LiveStockSecurity.length )
            {
                pageRow=0;
            }
            
            BindingData(ContentStock,2,pageRow,pageSize);
        }
        else
        {
            BindingData(ContentStock,2,0,pageSize);
        }

}


function NumberFormat_999(number)
{
    if (number!=null)
    {
        var NumberToString = number + '';
        var lengthNumber = NumberToString.length;
        var LenPart = Math.ceil(parseInt( lengthNumber)/3)-1;
        var DivPart;
        var iPart = 0;
        var Rs="";
        DivPart = lengthNumber%3;
        
        if (DivPart>0)
        {
            Rs = NumberToString.substring(0,DivPart);
            
        }else
        {
            LenPart=LenPart+1;
        }
        while (iPart<LenPart)
        {
            if (Rs=="")
            {
                Rs = NumberToString.substring(3*iPart+DivPart,3*(iPart +1)+DivPart);
                
            }
            else
            {
                Rs = Rs + ',' + NumberToString.substring(3*iPart+DivPart,3*(iPart +1)+DivPart);
                
            }
            iPart = iPart+1;
        }
        return Rs;
    }
    return "";

}

function UpdateDataView(DataRows, DataItem, fTime)
{
    var jCol;
    var DataRowRs=new Array(23);
    for (jCol=0; jCol<23; jCol++)
    {
        switch (jCol)
        {
            case 1: case 2: case 3:
                DataRowRs[jCol] = RoundNumber(DataItem[jCol] ,1);
                break;
            case 10: case 19: case 21:
                    
                var PriorCPrice = parseFloat( DataItem[1]);
                if (PriorCPrice==0)
                {
                    PriorCPrice = parseFloat( DataItem[10]);
                }
                DataRowRs[jCol] = GetColorStyle(PriorCPrice,DataItem[jCol],DataItem[jCol]==' '?' ':RoundNumber( DataItem[jCol],1),2,"#66ff66","red","#ffff66","");
                break;
            case 12:
            
                var textPre="";
                
                if (parseFloat(DataItem[10])== parseFloat(DataItem[2]))
                {
                    textPre = "CE";
                }
                else
                {
                    if (parseFloat(DataItem[10])== parseFloat(DataItem[3]))
                    {
                        textPre = "FL";
                    }
                    else
                    {
                        textPre = "";
                    }
                }
                //alert(textPre);
                textPre = textPre +"";
                var ChangePrice;
                
                ChangePrice=parseFloat( getChangePrice(DataItem));
                
                if (ChangePrice>0)
                {
                    textPre = textPre + "▲" + ChangePrice;
                }
                else
                {
                    if (ChangePrice<0)
                    {
                        textPre = textPre + "▼" + ChangePrice;
                    }
                    else
                    {
                        textPre=textPre+ChangePrice;
                    }
                }
                
                DataRowRs[jCol] = GetColorStyle(0,ChangePrice,textPre,2,"#66ff66","red","#ffff66","");
                break;
            case 5: case 7: case 9: case 14: case 16: case 18: 
                if (fTime)
                {
                    DataRowRs[jCol] =DataItem[jCol]==' '?' ': NumberFormat_999(DataItem[jCol]);
                }
                else
                {
                    DataRowRs[jCol]= GetColorStyle(DataRows[jCol],DataItem[jCol],NumberFormat_999(DataItem[jCol]),3,"#000000","","","#ffffff");
                }            
                break;
            case 4: case 6: case 8: case 13: case 15: case 17:
            
                if (fTime)
                {
                    DataRowRs[jCol] = DataItem[jCol]==' '?' ':DataItem[jCol];
                }
                else
                {
                    DataRowRs[jCol]= GetColorStyle(DataRows[jCol],DataItem[jCol],DataItem[jCol],3,"#000000","","","#ffffff");
                }
                break;
            case 11: case 20: case 22:
                DataRowRs[jCol] = NumberFormat_999( DataItem[jCol]);
                
                break;
            default:

                DataRowRs[jCol] = DataItem[jCol];
        }
    }
    
    return DataRowRs;
}



function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}



function isDate18(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	
	//var strMonth=dtStr.substring(0,pos1)
	//var strDay=dtStr.substring(pos1+1,pos2)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strDay=dtStr.substring(0,pos1)	
	
	var strYear=dtStr.substring(pos2+1)

	var currentTime = new Date()
	//var month = currentTime.getMonth() + 1
	//var day = currentTime.getDate()
	var nam = currentTime.getFullYear()
	
	if ((nam - strYear) < 18)
	{
		alert("Chua du 18 tuoi")
		return false		
	}
	return true
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	
	//var strMonth=dtStr.substring(0,pos1)
	//var strDay=dtStr.substring(pos1+1,pos2)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strDay=dtStr.substring(0,pos1)	
	
	var strYear=dtStr.substring(pos2+1)
	
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : dd/mm/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}


function Initialize()
{
	try
	{
		req=new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			req=new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(oc)
		{
			req=null;
		}
	}

	if(!req&&typeof XMLHttpRequest!="undefined")
	{
		req=new XMLHttpRequest();
	}
	
}


function SetCookie(v, name_c) {
CurrentCookie = v;
document.cookie = name_c + '=' + v;
}

function GetCookie(name_c) {
var c_content = '';
if(document.cookie.length > 0) {
   var c_name = name_c + '=';
   var c_begin = document.cookie.indexOf(c_name);
   var c_end = 0;
   if(c_begin > -1) {
      c_begin += c_name.length;
      c_end = document.cookie.indexOf(";",c_begin);
      if(c_end < c_begin) { c_end = document.cookie.length; }
      c_content = document.cookie.substring(c_begin,c_end);
      }
   }
   //alert(c_content);
return c_content;
}


function getChangePrice(DataRow)
{
    var CPriceRs;
    
    if (parseFloat( DataRow[1])==0)
    {
        CPriceRs = parseFloat( RoundNumber(parseFloat(DataRow[10]),1));
    }
    else
    {
            
        CPriceRs = parseFloat( RoundNumber( parseFloat(DataRow[10]) - parseFloat(DataRow[1]),1));
        
    }
    
    return CPriceRs;
}

function RoundNumber(number,percision)
{
    if (number !=null || number !="" || number!='')
    {
        var theNumberString = parseFloat(Math.round(parseFloat(number)*10))/10 + ''; // force a string
        
        
        var PointPixel =theNumberString.lastIndexOf('.');
        if (PointPixel>=0)
        {
            //alert(theNumberString + ' ' + PointPixel);
            
            return theNumberString.substring(0,PointPixel + percision +1);
        }
        else
        {
            
            return theNumberString;
        }
     }
     else
     {
        return 0;
     }

}


//Copy mang Source vao Des
function CopyArrayData(SourceArray, DesArray, nSize)
{
    var jcol;
    for (jcol=0; jcol<nSize; jcol++)
    {
        DesArray[jcol] = SourceArray[jcol] ;
        if (parseInt(DesArray[jcol] )==0)
        {
            DesArray[jcol]=' ';
        }
    }
}


//Tim MCK trong mang da cho	   
function FindDataInArray(MCK, DataRows)
{
    var aLen = DataRows.length;
    var jRow;
    for (iRow=0; iRow<aLen; iRow++)
    {
        if (MCK == DataRows[iRow][0])
        {
            return iRow;
        
        }
    }
    return -1;
}

function ClearText(){
	document.Timkiem.tim.value = '';
}

function searchAll() {
	
	var params = "";	
	// check to see which checkboxes are checked and append them to the string.
	//if (document.getElementById('checkBox1').checked == true) {
	//params += "cuong"
	//}
	// more here
	
	params = "act=mn_search";
	
	//if (document.getElementById('tim').value == '')
	//{
	//	alert('Chua  thong so tim kiem !');
	//	document.getElementById('tim').focus();
	//	return false;
	//}
	//else
	//{
	//	params = params + "&tim=" + document.getElementById('tim').value;
	//}

	if (document.Timkiem.tim.value=='')
	{    
			alert('Chua  nhap gia tri tim kiem !');
			document.Timkiem.tim.focus();  
			return false;
	}
	else
	{
		if (document.Timkiem.tim.value.length <=2)
		{
			alert('Nhap tu 3 ky tu tro len !');
			document.Timkiem.tim.focus();  
			return false;		
		}
		else
		{
		
			params = params + "&tim=" + document.Timkiem.tim.value;
		}
	}
	
	params = params + "&lgid=" + document.Timkiem.lgid.value;
	
	retrieveURL1("t_5b6db47c7e807c2953a3b62cd24bf4e7.php", params);
	//alert(params);
	return true;
}

function logindownload() {
	
	var params = "";		
	params = "at=haidanggsm.com.vn_download";
	
	if (document.truynhap.username1.value=='')
	{    
			alert('Chua  nhap ten !');
			document.truynhap.username1.focus();  
			return false;
	}
	else
	{
			params = params + "&u=" + document.truynhap.username1.value;
	}

	if (document.truynhap.password1.value=='')
	{    
			alert('Chua  nhap mat khau !');
			document.truynhap.password1.focus();  
			return false;
	}
	else
	{
			params = params + "&p=" + document.truynhap.password1.value;
	}

	if (document.truynhap.mabaove.value=='')
	{    
			alert('Chua  nhap mabaove !');
			document.truynhap.mabaove.focus();  
			return false;
	}
	else
	{
			params = params + "&mbv=" + document.truynhap.mabaove.value;
	}
			
	
	retrieveURL1("cmd.php", params);
	return true;
}

function Subtmitt() {
	
	var params = "";		
	params = "act=mn_xldangky";
	
	if (document.truynhap.hoten.value=='')
	{    
			alert('Chua  nhap ten !');
			document.truynhap.hoten.focus();  
			return false;
	}
	else
	{
			params = params + "&hoten=" + document.truynhap.hoten.value;
	}

	if (document.truynhap.dienthoai.value=='')
	{    
			alert('Chua  nhap dien thoai !');
			document.truynhap.dienthoai.focus();  
			return false;
	}
	else
	{
			params = params + "&dienthoai=" + document.truynhap.dienthoai.value;
	}

	if (document.truynhap.mbv.value=='')
	{    
			alert('Chua  nhap mabaove !');
			document.truynhap.mbv.focus();  
			return false;
	}
	else
	{
			params = params + "&mbv=" + document.truynhap.mbv.value;
	}
			
	if (document.truynhap.thu.value=='')
	{    
			alert('Chua  nhap email !');
			document.truynhap.thu.focus();  
			return false;
	}
	else
	{
			params = params + "&thu=" + document.truynhap.thu.value;
	}			
	
	params = params + "&diachi=" + document.truynhap.diachi.value;
	params = params + "&loaitin=" + document.truynhap.loaitin.value;
	params = params + "&noidung=" + document.truynhap.noidung.value;
	
	retrieveURL1("t_5b6db47c7e807c2953a3b62cd24bf4e7.php", params);
	return true;
}

function contact() 
{
	
	var params = "";		
	params = "act=ree_ct_pro";
	
	if (document.Timkiem1.hoten.value=="")
	{
		alert("Chua nhap ho ten");
		document.Timkiem1.hoten.focus();
		return false;		
	}
	if (document.Timkiem1.chucdanh.value=="")
	{
		alert("Chua nhap chuc danh");
		document.Timkiem1.chucdanh.focus();
		return false;		
	}
	

	if (document.Timkiem1.congty.value=="")
	{
		alert("Chua nhap Cong ty");
		document.Timkiem1.congty.focus();
		return false;		
	}
	if (document.Timkiem1.diachi.value=="")
	{
		alert("Chua nhap dia chi");
		document.Timkiem1.diachi.focus();
		return false;		
	}
	if (document.Timkiem1.dienthoai.value=="")
	{
		alert("Chua nhap dien thoai");
		document.Timkiem1.dienthoai.focus();
		return false;		
	}
	if (document.Timkiem1.thu.value=="")
	{
		alert("Chua nhap email");
		document.Timkiem1.thu.focus();
		return false;		
	}
	if (document.Timkiem1.noidung.value=="")
	{
		alert("Chua nhap noi dung");
		document.Timkiem1.noidung.focus();
		return false;		
	}

	var ivt = "";
	var radios = document.getElementById ('radios');
	if (radios) {
	  var inputs = radios.getElementsByTagName ('input');
	  if (inputs) {
	    for (var i = 0; i < inputs.length; ++i) {
	      if (inputs[i].type == 'radio' && inputs[i].name == 'gioitinh')
	      if (inputs[i].checked)
	      {
	      	ivt = inputs[i].value;
	      	//alert(ivt);
	      }	      	      	        
	    }
	  }
	}	
	params = params + "&gioitinh=" + ivt;
	
	
	params = params + "&hoten=" + document.Timkiem1.hoten.value;
	params = params + "&chucdanh=" + document.Timkiem1.chucdanh.value;
	params = params + "&congty=" + document.Timkiem1.congty.value;
	params = params + "&diachi=" + document.Timkiem1.diachi.value;
	params = params + "&dienthoai=" + document.Timkiem1.dienthoai.value;
	params = params + "&thu=" + document.Timkiem1.thu.value;
	params = params + "&fax=" + document.Timkiem1.fax.value;
	params = params + "&noidung=" + document.Timkiem1.noidung.value;
	params = params + "&lgid=" + document.Timkiem1.lgid.value;
	params = params + "&idm=" + document.Timkiem1.idm.value;

	//alert(params)
		
	retrieveURL1("t_5b6db47c7e807c2953a3b62cd24bf4e7.php", params);
	return true;
}

function displayItems(par1) {
	
	var params = par1;	
	// check to see which checkboxes are checked and append them to the string.
	//if (document.getElementById('checkBox1').checked == true) {
	//params += "cuong"
	//}
	// more here
	retrieveURL("t_5b6db47c7e807c2953a3b62cd24bf4e7.php", params);
	return true;
}

function retrieveURL1(url, pars) {
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = processStateChange;
try {
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(pars);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processStateChange;
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(pars);
//req.send();
}
}
}


function retrieveURL(url, pars) {
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = processStateChange;
try {
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", pars.length);
//req.setRequestHeader("Content-length", "0");
req.send(pars);
} catch (e) {
alert(e);
}
req.send(null);
//req.send(1);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processStateChange;
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", pars.length);
req.send(pars);
//req.send();
}
}
}


function processStateChange() {
if (req.readyState == 4) 
{ // Complete
	if (req.status == 200) 
	{ // OK response
			//document.getElementById("thetable").innerHTML = req.responseText;		
			var t1 = req.responseText;
			var tim;
			var kq;
			tim=/@@/i;
			kq = t1.search(tim);
			
			checkok = new Array();

			
			if (kq === -1)
			{
				document.getElementById("thetable").innerHTML =req.responseText;
			}
			else
			{
				checkok = t1.split("@@");
				if (checkok[0].length >= 1)
				{
					document.getElementById("thetable").innerHTML =checkok[0];
				}
								
				if (checkok[1]!='-' && checkok[1]!='')
				{
					//document.getElementById("piccenter").innerHTML ="<img border=0 src='images/imgupload/"+checkok[1]+"' width=298 height=269>";					
					//document.getElementById("piccenter").innerHTML =checkok[1];					
				}
			}			
	}
	bb_save_state();	
}
else
{

	var load1= "<table border=1 width=100% cellSpacing=0 cellPadding=0  bordercolor=#C0C0C0 style='border-collapse: collapse'>";
	load1 = load1 + "<tr><td><table border=0 width=100% cellSpacing=0 cellPadding=0><tr><td width=100% bgcolor=#FFFFFF valigb=middle style='PADDING-RIGHT: 2px; PADDING-LEFT: 2px; PADDING-BOTTOM: 2px; PADDING-TOP: 2px' noWrap width=99% height=10>";
	load1 = load1 + "</td></tr><TR><TD height=2></TD></TR><tr><td width=100% height=50 bgcolor=#FFFFFF valigb=middle><div align=center><img src=images/loading.gif></div>";
	load1 = load1 + "</td></tr></table></td></tr></table>";				            	
	document.getElementById("thetable").innerHTML = load1;			

}
}

	   
//Dong bo lai danh sach sau khi nhan duoc du lieu moi

function SynchLiveSecurity(DataRow)
{
    var iRow, iCol;
    var found=0; 
    var iHeader = -1, iContent=-1;
    iHeader =  FindDataInArray(DataRow[0],HeaderStock);
    if (iHeader<0)
    {
        iContent = FindDataInArray(DataRow[0],ContentStock );
    }
    if (LiveStockSecurity.length>0 ){
    
        for (iRow=0; iRow<LiveStockSecurity.length  ;iRow++)
        {
            if (DataRow[0]==LiveStockSecurity[iRow][0])
            {
                found=1;
                if (iHeader>=0)
                {
                    CopyArrayData(UpdateDataView(LiveStockSecurity[iRow],DataRow,false) ,HeaderStock[iHeader],23)
                }
                else
                {
                    if (iContent>=0)
                    {
                        CopyArrayData(UpdateDataView(LiveStockSecurity[iRow],DataRow,false) ,ContentStock[iContent],23)
                    }
                    else
                    {
                        var NewItemToContent = new Array(23);
                        CopyArrayData(DataRow,NewItemToContent,23);
                        ContentStock.push(NewItemToContent);
                   
                    }
                    
                }
                CopyArrayData(DataRow,LiveStockSecurity[iRow],23);
                return found;
            }
            
        }
        if (found ==0)
        {
            LiveStockSecurity.push(DataRow);
        }
    }
}

//Lay ten cua class phuc vu cho cell
function GetClassName(irow,jcol)
{
    var rowType = parseInt(irow)%2;
    var cName="";
    if (rowType==0)
    {
        switch (jcol)
        {
            
            case 1:
                cName="PriorClosePrice";
                break;
            case 0:
            case 10:
            case 11:
            case 12:
            case 19: case 20: case 21: case 22:
                cName = "EvenRow1";
                break;
            case 2:
                cName = "EvenColCeiling";
                break;
            case 3:
                cName = "EvenColFloor";
                break;
            
            case 4: case 5: case 6: case 7: case 8: case 9:
            case 13: case 14: case 15: case 16: case 18: case 17:
                cName = "EvenRow2";
                break;
            
        }
    }
    else
    {
        switch (jcol)
        {
            case 1:
                cName="PriorClosePrice";
                break;
            case 0:
            
            case 10:
            case 11:
            case 12:
            case 19: case 20: case 21: case 22:
                cName = "OddRow1";
                break;
            case 2:
                cName = "OddColCeiling";
                break;
            case 3:
                cName = "OddColFloor";
                break;
            
            case 4: case 5: case 6: case 7: case 8: case 9:
            case 13: case 14: case 15: case 16: case 18: case 17:
                cName = "OddRow2";
                break;
            
        }    
    }
    return cName;
}

//Dua du lieu vao luoi, dua tren mang Header va Content
//type = 1: HeaderBind
//type = 2: ContentBind
function BindingData(DataRows, type, startRow, sizePage)
{
    var i, j, dRow, cell, maxRow, maxLen, rowStart;
    var dTab = document.getElementById('RsQuotes');
    maxRow=dTab.rows.length;
    maxLen = DataRows.length
    rowStart=2;
    switch (type)
    {
        case 1:
            rowStart = 2;
        break;
        case 2:
            rowStart = 2+ HeaderStock.length ;
            maxLen = sizePage - HeaderStock.length ;
            if ((startRow+maxLen)>ContentStock.length )
            {
                maxLen = ContentStock.length - startRow;
            }
            //alert(maxLen);
        break;
    }
    
    var isNewRow;
    
    for (i=0; i<maxLen; i++)
    {
        if ((rowStart+i)<maxRow)
        {
            drow = dTab.rows[rowStart+i];
            IsNewRow=false;
        }
        else
        {
            drow = dTab.insertRow(rowStart+i);
            maxRow = maxRow+1;
            IsNewRow=true;
        }
        drow.height = 18;
        for (j=0;j<23;j++)
        {
            if (IsNewRow)
            {
                cell = drow.insertCell(j);
                cell.className = GetClassName(rowStart+i + startRow,j);
                cell.innerHTML = DataRows[i][j];
            }else
            {
                if (type==1)
                {
                    drow.cells[j].innerHTML = DataRows[i][j];
                }
                else
                {
                    drow.cells[j].innerHTML = DataRows[i+startRow][j];
                }
                
            }
        }
        
    }
    if (type ==2)
    {
        
        while (dTab.rows.length>pageSize+2)
        {
            dTab.deleteRow(pageSize+2);
        }
    }
    
}

function findenter(e)
{
	if (e.keyCode == 13)
	{		
		searchAll();
		return false;
	}
}


//Tao danh sach cac chung khoan o phan header
function MakingHeader(){

    /*if (HeaderStock==null)
    {
        HeaderStock = new Array(CountCheckStock());
    }*/
    if (HeaderStock!=null)
    {
        HeaderStock.splice(0,HeaderStock.length); 
    }
    HeaderStock = new Array(CountCheckStock());
    var ChkListBox = new Array();
    var i,iHeader=0;
    ChkListBox=document.forms["form1"].ChkStock;
    
    //for (i=0; i<totalLine ;i++)
    for (i=0; i<totalLine ;i++)
    {
        //if (ChkListBox[i].checked)
        if (0==1)
        {
           //HeaderStock.push( LiveStockSecurity[i]);
           HeaderStock[iHeader] = new Array(23);
           /*var jcol=0;
           for (jcol=0;jcol<23;jcol++)
           {
                HeaderStock[iHeader][jcol] = LiveStockSecurity[i][jcol];
           }*/
           CopyArrayData(LiveStockSecurity[i],HeaderStock[iHeader],23);
           
           
           HeaderStock[iHeader]=UpdateDataView(HeaderStock[iHeader],LiveStockSecurity[i],false);
           iHeader = iHeader+1;
        }
    }

}

//Dem so chung khoan check trong danh sach cac list check box
function CountCheckStock(){
//    var numberChecked=0, i;
//    var ChkListBox = new Array();
//    
//    //ChkListBox=document.form1.ChkStock;
//    ChkListBox=document.forms["form1"].ChkStock;
//    for (i=0; i<ChkListBox.length ;i++)
//    {
//        if (ChkListBox[i].checked)
//        {
//           numberChecked=numberChecked+1;
//        }
//    }
    return 0;
    
}


//Tao danh sach cac chung khoan trong phan content
function MakingContent(){
    /*if (ContentStoc==null)
    {
        ContentStock  = new Array(LiveStockSecurity.length-CountCheckStock());
    }*/
    if (ContentStock!=null)
    {
        ContentStock.splice(0,ContentStock.length); 
    }
    ContentStock  = new Array(LiveStockSecurity.length-CountCheckStock());
    var ChkListBox = new Array();
    var i, iContent=0;
    //ChkListBox=document.form1.ChkStock;
    ChkListBox=document.forms["form1"].ChkStock;
    //for (i=0; i<ChkListBox.length ;i++)
    for (i=0; i<totalLine ;i++)
    {
        //if (!ChkListBox[i].checked)
        if (1)
        {
           //ContentStock.push( LiveStockSecurity[i]);
           ContentStock[iContent] = new Array(23);
           /*var jcol=0;
           for (jcol=0;jcol<23;jcol++)
           {
                ContentStock[iContent][jcol]= LiveStockSecurity[i][jcol];
           }*/
           
           CopyArrayData(LiveStockSecurity[i],ContentStock[iContent],23);
           
           
           ContentStock[iContent]= UpdateDataView(ContentStock[iContent],LiveStockSecurity[i],false);
           iContent = iContent+1;
        }
    }        
}

//Tao hieu ung mau sac cho mot cell
//type: Neu = 1, tuc la khong phu thuoc vao oldCell, text hien thi la newData
//type: Neu = 2, tuc la phu thuoc vao oldCell, text hien thi la newData, co mau Text va khong co bgColor
//type: Neu = 3, tuc la phu thuoc vao oldCell, text hien thi la newData, co mau text va bgColor
//TextColor = TextColor Ins
function GetColorStyle(oldData, newData, textValue, type, Textcolor, TextColorDesc, TextColorNo, BgColor )
{
    var innerTextRs="";
    
    switch (type)
    {
        case 1:
            innerTextRs = "<span style='color:" + Textcolor +"'>" + textValue + "</span>";
            break;
        case 2:
        
            if (parseFloat(newData)>parseFloat(oldData))
            {
                innerTextRs = "<span style='color:" + Textcolor +"'>" + textValue + "</span>";
            }
            else
            {
                if (parseFloat(newData)<parseFloat(oldData))
                {
                    innerTextRs = "<span style='color:" + TextColorDesc +"'>" + textValue + "</span>";
                }
                else
                {
                    innerTextRs = "<span style='color:" + TextColorNo +"'>" + textValue + "</span>";
                } 
            }
            break;
        case 3:
            var oldDataVal,newDataVal;
            oldDataVal=(oldData==' '?0:oldData);
            newDataVal=(newData==' '?0:newData);
            //if (parseFloat(oldData)!=parseFloat(newData))
            if (parseFloat(oldDataVal)!=parseFloat(newDataVal))
            {
                
                innerTextRs = "<table cellpadding='0' cellspacing='0' width= 100% height=100%><tr>" + "<td style='color:" + Textcolor + "; FONT-SIZE: 14px; background-color:" + BgColor + ";'>" + textValue + "</td></tr></table>";
               
            }
            else
            {
                innerTextRs = textValue;
                
            }
            break;
    }
    
    return innerTextRs;
}

var bb_count = 0;
var bb_curr_idx = "";
var bb_cache = new Array;
//var bb_debug = false;
var bb_debug = true;
var bb_iframe_script = "store.php";
var bb_iframe_loaded = false;
var bb_target_div = "";



function bb_debug_update (str) {
    if (bb_debug) {
        var divBBDebug = document.getElementById("divBBDebug");        
    }
}



function bb_check_state (  ) {

    if (bb_iframe_loaded == false) {
        return;
    }

    var doc =  window.frames['bbFrame1'].document;
    var new_idx = doc.getElementById('divFrameCount').innerHTML;
	
    if (new_idx != bb_curr_idx) {

        var debug_msg = "IFRAME changed. Was " 
                        + bb_curr_idx 
                        + ", now " 
                        + new_idx;

        //Pull a previous state from the cache (if it exists).
			
        if (bb_cache[new_idx]) {
            var body1 = document.getElementById("body1");
            body1.innerHTML = bb_cache[new_idx];

            debug_msg += " [pulled " 
                         + new_idx 
                         + " from cache]";
        }
        bb_curr_idx = new_idx;

        bb_debug_update (debug_msg);
    }
}

//Called by child IFRAME.

function bb_done_loading () {
    bb_iframe_loaded = true;
}

//Update the hidden IFRAME.

function bb_loadframe (  ) {
    var bbFrame1 = document.getElementById("bbFrame1");
    bb_iframe_loaded = false;
    bbFrame1.src = bb_iframe_script + "?vt=" + bb_count;
	//alert(bbFrame1.src);
	
}

//When requested, save the current state
//in a cache.

function bb_save_state (  ) {
    //Store the new contents in the cache.
    var div_to_cache = document.getElementById(bb_target_div);
    bb_count++;
    bb_cache[bb_count] = div_to_cache.innerHTML;

    //bb_debug_update ("Added " + bb_count + " to cache");		
    //Load the new page into the IFRAME.
    bb_loadframe();

    bb_curr_idx = bb_count;
}

//Load the hidden IFRAME and start an interval timer.

function bb_init (div_name, debug_val) {
	
    bb_target_div = div_name;
    bb_debug = debug_val;

    bb_loadframe (  );
    window.setInterval ('bb_check_state()', 1000);
    bb_save_state (  );	
}

function ApplySettings()
{
    var CheckedStocks = CountCheckStock();
    pageSize = parseInt( document.getElementById("txtPageSize").value);
    
    if (pageSize<CheckedStocks)
    {
        pageSize = CheckedStocks;
    }
    if (pageSize<15)
    {
        pageSize = 15;
    }
    if (pageSize>LiveStockSecurity.length )
    {
        pageSize = LiveStockSecurity.length ;
    }
    document.getElementById("txtPageSize").value = pageSize;
    MakingHeader();
    MakingContent();
    ShowNextInterval();
}


function CheckAll() {

    if (document.getElementById("ChkAll").checked)
    {
        document.getElementById("BtOK").disabled  = true;
        document.getElementById("txtPageSize").value =parseInt( LiveStockSecurity.length);
        pageSize = parseInt( LiveStockSecurity.length);
        SetListChkBox(true);
        document.getElementById("ChkDefault").checked = false;
        ShowNextInterval();
    } 
    else
    {
        SetListChkBox(false);
        document.getElementById("BtOK").disabled  = false;
    }
    
}

function SetListChkBox(value)
{
    var numberChecked=0, i;
    var ChkListBox = new Array();
    
    ChkListBox=document.forms["form1"].ChkStock;
    for (i=0; i<ChkListBox.length ;i++)
    {
        ChkListBox[i].checked=value;
    }
 
    
}

function mouseOverAll(kieu){
	kieu.style.textDecoration='underline';
	kieu.style.backgroundImage='url(images/menu_02.gif)';
	kieu.style.color='white';
}

function mouseOverOut(kieu){
	kieu.style.textDecoration='none';	
	kieu.style.color='#006699';
	kieu.style.backgroundImage='url(images/menu_04.gif)';
}

function mouseOverAll1(kieu){
	kieu.style.color='red';
	kieu.style.textDecoration='underline';
}

function mouseOverOut1(kieu){
	kieu.style.color='#006699';
	kieu.style.textDecoration='none';
}

function mouseOverAllTitle(kieu){
	//kieu.style.color='024E88'; 
	kieu.style.textDecoration='underline';
}

function mouseOverOutTitle(kieu){
	//kieu.style.color='024E88'; 
	kieu.style.textDecoration='none';
}

function mouseOverAllqc(kieu){
	kieu.style.color='FFFFFF'; 
	kieu.style.textDecoration='underline';
}

function mouseOverOutqc(kieu){
	kieu.style.color='FFFFFF'; 
	kieu.style.textDecoration='none';
}

function mouseOverBgr(kieu){
	kieu.style.color='ffffff'; 
	kieu.style.textDecoration='underline';
	kieu.style.backgroundColor='024E88';
}

function mouseOverOutBgr(kieu){
	kieu.style.color='ffffff'; 
	kieu.style.textDecoration='none';
	kieu.style.backgroundColor='318224';
}

function SetDefaultSettings() {

    if (document.getElementById("ChkDefault").checked)
    {
        document.getElementById("BtOK").disabled  = false;
        document.getElementById("txtPageSize").value =20;
        pageSize = 20;
        SetListChkBox(false);
        document.getElementById("ChkAll").checked = false;
        
        ShowNextInterval();
      
    } 

    
}

