﻿		/*JSON odgovor od HttpPush server je 
		dojo.io.script.jsonp_dojoIoScript1740._jsonpCallback
( 
 [
	{"channel":"/meta/connect",
	"clientId":"204e42c5-387d-4b7a-909f-2fa81209eafb",
	"advice":{"interval":1000,"multipleClients":false,"reconnect":"retry"},
	"id":"1758","successful":true},
	
	{"channel":"/teletrader/symbols/458757/",
	"clientId":"204e42c5-387d-4b7a-909f-2fa81209eafb",
"data":{"last":"25.61","dateTime":""10.06.2009 11:33:23.614"","volume":"497496","symbolId":458757,"timestamp":"09.06.2009 13:49:25.197"}}
 ]
 
 ZA Markt Depth:
 <script>d{"channel":"/teletrader/symbols/4261621/",
 "clientId":"86a849e2-febf-4432-8b27-5cc307f1f6cf",
 "data":{"askSize":"2609","bidSize":"2469","bid":"11.73","ask":"11.79",
 "marketDepthBid":[{"Count":4,"Price"
:11.73,"Size":2469},{"Count":1,"Price":11.72,"Size":2500},{"Count":5,"Price":11.7,"Size":3575},{"Count"
:2,"Price":11.6,"Size":4930},{"Count":4,"Price":11.5,"Size":3943},{"Count":1,"Price":11.1,"Size":500
},{"Count":1,"Price":11.02,"Size":1000},{"Count":1,"Price":11.01,"Size":1000},{"Count":4,"Price":11.0
,"Size":1387},{"Count":1,"Price":10.9,"Size":400}],
"marketDepthAsk":[{"Count":2,"Price":11.79,"Size"
:2609},{"Count":1,"Price":11.8,"Size":2000},{"Count":1,"Price":11.81,"Size":211},{"Count":2,"Price":11
.82,"Size":1098},{"Count":1,"Price":11.83,"Size":2750},{"Count":2,"Price":11.84,"Size":400},{"Count"
:1,"Price":11.85,"Size":700},{"Count":2,"Price":11.9,"Size":580},{"Count":1,"Price":11.92,"Size":2353
},{"Count":1,"Price":11.94,"Size":2500}],
"symbolId":4261621,"timestamp":"08.09.2009 15:08:15.043"}}]
);</script></body></html><script>d([{"channel":"/teletrader/symbols/4261621/","clientId":"86a849e2-febf-4432-8b27-5cc307f1f6cf".....
,"
)
		*/
		
	// for stream httpPush
      var domainparts = document.domain.split(".");
      if(domainparts.length>1) 
        document.domain = domainparts[domainparts.length-2] + "." + domainparts[domainparts.length-1];
      else
        document.domain = domainparts;
      //document.domain = "teletrader.local";//"teletrader.local"; ttweb.net
	  dojo.require("dojox.cometd");
      dojo.require('dojo.fx');
      var debugTick = false;
      
      var noDecimals;//use for quote data that we must show all decimals that we get from push (bid, ask, last, marketDepthBid.Price, marketDepthAsk.Price)      
      var exchange1118 = false; //flag for manipulate with decimals and trailing zero
      var defineNoDecimals = false; //flag
      /*if(typeof stockExchangeID != 'undefined'){ // !! NOTE: Must be set on asp age that include this js file.
          if(stockExchangeID != '1118')
            noDecimals = 5;
          else{
            noDecimals = 3;        
            exchange1118 = true;
            }
      }*/
      //for writting Messages variable
      if(window.location.href.indexOf('debugTick=true') > 0) debugTick=true;
      var Messages = "";
        
      function addMessage(str)
			{
				Messages += str +"<br>"
			}
			
        var blinkDuration = 800;
		function updateRow(msg)//showProperty(obj)
		{
		    setQuotesDecimalPlaces();
		    for (var prop in msg.data){
		        if(prop == "marketDepthBid" || prop == "marketDepthAsk"){
		            if(msg.data[prop].length>0){
		                     for( var i = 0; i < msg.data[prop].length; i++ ) {
			                     var mde = msg.data[prop][i];
			                     for(var fidProp in mde){
			                        if(fidProp !='Count')
			                            tickITMD(msg.data.symbolId, prop, fidProp, mde[fidProp], i);
			                     }
						     }
		             }
		        }
		        else
		            showValueAndBlink(msg.data.symbolId, prop, msg.data[prop], msg.data.last);
		    }  
		 //   showValueAndBlink(msg.data);		          			
        } 
		
		function showValueAndBlink(symbolId, prop, propValue, last)//(obj)//msg.data. 
		{
		   var fontColorNew = "white";
		   var cell;
		   var symbolName = 'tts-'+symbolId;
	       var blink = false;

	       if(prop != 'dateTime')
	          cell = dojo.byId(symbolName + prop); 
	       else
	          {
	          cell = dojo.byId(symbolName + 'date');         	  
	          }
	       var newValue = Number(propValue);//not work for dateTime data because it is format: "09.06.2009 15:16:05"
	       var numberOfDecimals = (prop=='volume' || prop=='askSize' || prop=='bidSize' || prop  == 'Size')?0:2;
	       if( prop == 'ask' || prop == 'bid' || prop == 'last'){//we get exact number of decimals from push, and we don't need to reformat number from push
	        numberOfDecimals = noDecimals;
	       }
            if (cell != null)
            {
                
                var oldValue = cell.innerHTML;	//*** this is because of detail page and ask/bid, that have &nbsp; ***
                var detailPageTabCharacters = '';
	            if ( prop == 'ask' || prop == 'bid'){
		            var position = oldValue.indexOf("/")//("&nbsp;"); Don't use this because of Opera don't recognize it in comming string that we have "&nbsp;"
		            if(position>0)
		                {
		                detailPageTabCharacters = '&nbsp;/&nbsp;';
		                oldValue = oldValue.slice(0,position);
		                }
	            }
                
                 if ( prop == 'ask' || prop == 'bid' || prop == 'last' || prop == 'change' || prop == 'changePercent' || prop == 'bidSize' || prop == 'askSize')//this will BLINK
	             {
			        var propChange = newValue - getNumber(oldValue);//( cell.innerHTML );
			        blink = true;
	             }
	
	            switch ( prop )
	            {
		            case 'dateTime':
		                var objDate = getDateObject(propValue);
			            if(compareDates(cell,objDate))//if there is deference between page and tick date 	
			            {
				            cell.innerHTML = formatDate(objDate);
			            }
			            var cellTime = dojo.byId(symbolName + 'time');
			            if ( cellTime != null){	
				            cellTime.innerHTML = formatTime(objDate);//formatTime(newValue);       
				        }
			            break;
		            case 'last':	 
				        if (cell != null) cell.innerHTML = formatNumber(newValue, numberOfDecimals);	//formatNumberDynamic					        
			            var IDArrow = String(symbolName) + "arrow";
			            var elementArrow = document.getElementById(IDArrow);
			            //var valArrow = getNumber(propKeyItem[symbol]) - getNumber(element.innerHTML);
				            if (elementArrow != null) elementArrow.innerHTML = getArrow(propChange);
			            break;
		            case 'changePercent':
			            //Because we must check if HistoricClose is actual	            
			            if(HistoricCloseFlag[symbolName] != null || HistoricCloseFlag[symbolName] != 'undefined')
				                changeHistoricCloseCell(newValue,last, symbolName, numberOfDecimals);//(changeFeed,lastFeed, symbol, numberOfDecimals)
			            cell.innerHTML = ColorizeFont(newValue, numberOfDecimals, "%", prop+symbolName);
			            break;
		            case 'change':				
			            cell.innerHTML = ColorizeFont(newValue, numberOfDecimals, "" , prop+symbolName);
			            break;
		            case 'volume':					
		                //var adValue = newValue + getNumber( oldValue );
		                //console.debug(symbolId +" | " + newValue + " || "+getNumber(oldValue) + " || " + adValue);
		                //cell.innerHTML = formatNumber(adValue, numberOfDecimals);
		                cell.innerHTML = formatNumber(newValue, numberOfDecimals);
		            break;	
		            case 'bid':
		                cell.innerHTML = formatNumber(newValue, numberOfDecimals)+detailPageTabCharacters;
		                break;
		            case 'ask':
		                cell.innerHTML = formatNumber(newValue, numberOfDecimals)+detailPageTabCharacters;
		                break;					
		            default:	
			            cell.innerHTML = formatNumber(newValue, numberOfDecimals);					            
			            break;
	            }			
	            if (blink)
	            {
	                if (cell != null && propChange != undefined) 
	                { 
                        var fontColor = _getRowStyle(cell, 'color');
                         if(prop =='changePercent' || prop == 'change')
                        {
                            var span = dojo.byId(prop + symbolName);
                            fontColor = dojo.style(span, 'color');
                            //dojo.style(span, 'display', 'block');
                            //cellID = span.id
                        }
	                    var color = _getRowStyle(cell, 'backgroundColor');//get initial color of tr , set as initial in CSS class of 'tr'
                        var bgColorNew = getBlinkColor(propChange)
                        
                        if(prop =='changePercent' || prop == 'change'){// || prop == 'change'
	                        span.style.color = '#fff';
	                        cell.style.backgroundColor = bgColorNew;
	                        timerID = setTimeout("clearElementChangePercent('" + symbolName + "','" + prop + "','" +color+ "','" +fontColor+ "')", blinkDuration );
                        }
                        else {
                            cell.style.color='#fff';
	                        cell.style.backgroundColor = bgColorNew;
	                        timerID = setTimeout("clearElement('" + symbolName + prop + "', '" +color+ "')", blinkDuration );
                        }
	                }
	            }		            
            }//if (cell != null)
		}
		
      function tickITMD(symbol,fid, propFeed, propFeedValue, pos)//Count, Price, Size
		{	
				var newValue =Number(propFeedValue);
				var numberOfDecimals = (propFeed=='Size')?0:2;
				if( propFeed == 'Price'){//we get exact number of decimals from push, and we don't need to reformat number from push
	             numberOfDecimals = noDecimals;
	           }
				var ID = 'tts-'+String(symbol) + String(fid) + "_" + propFeed+pos ;
				var cell = document.getElementById(ID);
				var detailPageTabCharacters = '&nbsp;&nbsp;/&nbsp;&nbsp; ';
				if (cell !=null){	
					if(!isNaN(newValue) && newValue>0)
					{
						var oldValue = 	cell.innerHTML;
						if (propFeed=='Price'){		
							var position = oldValue.indexOf("&nbsp")-1;
							oldValue = oldValue.slice(0,position);
							cell.innerHTML = formatNumber(newValue, numberOfDecimals)+ detailPageTabCharacters;
						}else
							cell.innerHTML = formatNumber(newValue, numberOfDecimals);	
									
						var feedChange = newValue - getNumber( oldValue );  
						
						if(feedChange != undefined){
							var fontColor = _getRowStyle(cell, 'color');
		                    var color = _getRowStyle(cell, 'backgroundColor');//get initial color of tr , set as initial in CSS class of 'tr'
                            var bgColorNew = getBlinkColor(feedChange);
	                        cell.style.color='#fff';
	                        cell.style.backgroundColor = bgColorNew;
	                        timerID = setTimeout("clearElement('" + ID + "', '" +color+ "')", blinkDuration );
						}	
					}
					else 
					{
						newValue = '-';
						if (propFeed=='Price') element.innerHTML = newValue+ detailPageTabCharacters;
						else element.innerHTML = newValue;
					}
				}		
		}
      //******************
      //Business function
      
      function setQuotesDecimalPlaces(){//for: prop == 'ask', prop == 'bid', prop == 'last'
          if(!defineNoDecimals){
              defineNoDecimals = true;
              if(typeof stockExchangeID != 'undefined'){
                  if(stockExchangeID != '1118')
                    noDecimals = 5;
                  else{
                    noDecimals = 3;        
                    exchange1118 = true;
                  }
              }
          }
      }
      function clearElement(ID, backgroundColor)
			{	
				var element = document.getElementById(ID);
				element.style.backgroundColor = backgroundColor;//'';
				element.style.color="#000";
			}
	  function clearElementChangePercent(sName, prop, backgroundColor, fontColor)
			{
				var cell = dojo.byId(sName+prop);
				var elSpan = dojo.byId(prop+sName);
				cell.style.backgroundColor = backgroundColor;
				elSpan.style.color = fontColor;
			}
      function changeHistoricCloseCell(changePercent, last, symbolName, decimal)
		{
			var ID = String(symbolName) + 'historicClose';
			var element = document.getElementById(ID);
			var historicCloseFeedCalculated;
			if(element !=null)
			{
				var historicClose  = getNumber( element.innerHTML );
				if(changePercent!=undefined & changePercent!=NaN & last!=undefined)
				{
					historicCloseFeedCalculated = last /((changePercent/100)+1);
					historicCloseFeedCalculated = ( Math.round(historicCloseFeedCalculated*Math.pow(10, decimal)) )/Math.pow(10, decimal );
					if(historicClose!=historicCloseFeedCalculated)
						{
						element.innerHTML = formatNumber(historicCloseFeedCalculated, decimal);
						//element.style.backgroundColor = 'blue';//for testing
						}
					HistoricCloseFlag[symbolName]=1;
				}
			}
		}
      
      function getBlinkColor ( val ) {//only for new value, didn't used current value to get "current - new" to get positive or negativ change

          if ( val == 0 ) {
            return blue;
          }
          else if ( val == '' ) {
            return blue;
          }
          else if ( val > 0 ) {
            return green;
          }
          else if (val < 0 ) {
            return red;
          }
          else if ( val == NaN ) {
          return blue;
          }
          else if ( val == '' ) {
            return blue;
          }
          else
            return blue;
      }
      
      function _getRowStyle(cell, name)
        {
            var trHolder = cell;
            while (cell.nodeName != "TR") {
				    cell = cell.parentNode;
			    }
            //return trHolder.className;        
            return getStyle(cell, name);        
        }
        
     // Get a style property (name) of a specific element (elem)
        function getStyle( elem, name ) {
            // If the property exists in style[], then it's been set
            // recently (and is current)
            if (elem.style[name])
                return elem.style[name];
            // Otherwise, try to use IE's method
            else if (elem.currentStyle)
             return elem.currentStyle[name];
            // Or the W3C's method, if it exists
            else if (document.defaultView && document.defaultView.getComputedStyle) {
                // It uses the traditional 'text-align' style of rule writing,
                // instead of textAlign
                name = name.replace(/([A-Z])/g,"-$1");
                name = name.toLowerCase();
                // Get the style object and get the value of the property (if it exists)
                var s = document.defaultView.getComputedStyle(elem,"");
                return s && s.getPropertyValue(name);
                // Otherwise, we're using some other browser
            } else
            return null;
        }
      //*****************
      
      
      // Formater  
      
      function getDateObject(strDateTime)//19.06.2009 13:03:49.328
      {
          var arrDateTime = strDateTime.split(" ");
          var arrDate = arrDateTime[0].split(".");
          var arrTime = arrDateTime[1].split(":");
          var arrSec= arrTime[2].split(".");
          var milSec = 0;
          if (arrSec.length > 1) milSec = arrSec[1];
          var newDate = new Date(arrDate[2], arrDate[1]-1, arrDate[0], arrTime[0], arrTime[1], arrSec[0], milSec);//For month is zero based, so if you set that for month is 6.th, it will be 7.th month noth 6.th month, thet why we set "arrDate[1]-1" on month part
          var dtNow = new Date();
          return newDate;
          
      }
      
      function formatTime(val)
			{
				var lastDatetime = new Date(val);
				//var timeZoneOffset = ( new Date().getTimezoneOffset()/60 )*-1  ; Only when data (server with data) is not in time zone as user
				var timeZoneOffset = 0;
				return lastDatetime.getHours() + timeZoneOffset + ':' + formatTwoDigits(lastDatetime.getMinutes() ) + ':' + formatTwoDigits(lastDatetime.getSeconds() )
			}

		function formatDate(val)
			{
				var lastDatetime = new Date(val);
				var newYear = lastDatetime.getFullYear().toString();
				newYear = newYear.substring(2,4);
				return formatTwoDigits( lastDatetime.getDate() ) + '.' + formatTwoDigits( lastDatetime.getMonth() + 1 ) + '.'  +  newYear;//For month is zero based, so if you set that for month is 6.th, it will be 7.th month noth 6.th month
			}
			
		function compareDates(dateElement,newVal)
		{
		//var newValueMiliseconds = Number(newVal);
		//var dateElement = document.getElementById(String(symbol)+'Date');
					var arrayTokens = dateElement.innerHTML.split('.');//28.01.08
					var dateElementDate = new Date('20'+arrayTokens[2], arrayTokens[1], arrayTokens[0]);
					var dateElementMiliseconds = Date.parse('20'+arrayTokens[2]+'/'+arrayTokens[1]+'/'+arrayTokens[0]);//for 00:00:00 hour
					var newElementMiliseconds =  Date.parse(newVal.getFullYear() +'/'+(newVal.getMonth()+1) +'/'+newVal.getDate());//since 00:00:00 hour. For month is zero based, so if you set that for month is 6.th, it will be 7.th month noth 6.th month
					if(newElementMiliseconds!=dateElementMiliseconds)
					{return true;}
					else
					{return false;}
		}	
		
		function getNumber(fieldString)
		{
			fieldString = fieldString.replace( /\./gi, "" );
			if ( fieldString.indexOf(",") != -1 ){
						fieldString = fieldString.replace( /,/ , "." );	
			}
			if (isNaN(fieldString)) fieldString = '0';
			return Number(fieldString);
		}
			
		function formatNumber(val, decimals)
			{
			    var numb;
			    if (decimals!=noDecimals){
				    numb = ( Math.round(val*Math.pow(10, decimals)) )/Math.pow(10, decimals );
				    numb = numb.toString().replace( /\./gi , "," );
				    //return ( addGroupSeparator(numb, decimals) );
				}
				else{
				    numb = val.toString().replace( /\./gi , "," );
				    //return ( addGroupSeparator(numb, decimals) );
				}
				return ( addGroupSeparator(numb, decimals) );;				    				    
			}			
			
	    function formatNumberDynamic(value, decimals)
			{
			    var svalue;
			    var lastChar;
			    var temp;
			    svalue = formatNumber(value, decimals);
			    temp = svalue;
			    //lastChar = svalue.slice(svalue.length-1, svalue.length); 
			    //if(lastChar == "0" && decimals>3)
			        //temp =  formatNumberDynamic(svalue.substring(0,svalue.length-1), decimals-1);			        			    
                return temp;			    			    
			}
		function formatTwoDigits(val)
			{
				var tmp = val.toString();
				return (tmp.length<2)? '0'+tmp : tmp;
			}
			
		function addGroupSeparator( numb, decimals)
			{
				var sgn = '';
				var firstPart;
				var secondPart;
				var pos;
				var splitString = new Array(2);

				if (numb.indexOf(",") == -1) {
					splitString[0] = numb;
					splitString[1] = '00';
				} else {
					splitString = numb.split(",", 2);
				}
			
				if ( splitString[0].substring(0,1) == '-' ) 
				{
					sgn = '-' ;
					firstPart = splitString[0].substr( 1 );
				}
				else firstPart = splitString[0];
				
				secondPart= splitString[1];
				
				pos = firstPart.length;
				while (pos > 0) {
					pos -= 3;
					if (pos <= 0) break;
					firstPart = firstPart.substring(0,pos) + "." + firstPart.substring(pos,firstPart.length);
				}
				
				numb = sgn + firstPart ;
				
				if ( decimals != 0 ){
				    
				    //!! Add logic with stockEchangeID = 1118 because of three decimal places in that case
					if(exchange1118){
					    if(decimals - secondPart.length > 0){
					        var intLoop = decimals - secondPart.length;
					        for(var i = 0; i <= intLoop; i++){
					        secondPart = secondPart.toString()+'0';
					        }
					    }
                    }
                    else{/*old logic*/
					    if(secondPart.length==1)
					        secondPart = secondPart.toString()+'0';
					    }
					
					  /*if(secondPart.length==2)
					    console.log ("," + secondPart.substring(0,decimals));
					  if(secondPart.length==3)
					    console.log ("," + secondPart.substring(0,decimals));*/
					numb += "," + secondPart.substring(0,decimals);
				}
				return numb;
			}
			
		function  getArrow( val)
			{
				if(arrow1 != 'undefined' && arrow2 != 'undefined' && arrow3 != 'undefined')
				{
				    if ( val == 0 ) {
					    return arrow2;// same
				    }
				    else if ( val < 0 ) {
					    return arrow1;// down
				    }
				    else if ( val > 0 ) {
					    return arrow3;// up
				    }
				    else if ( isNaN(val)) {//this can happen when innerHTML for 'Last' is not numeric (&nbsp;)
					    return arrow2;
				    }				
				    else if ( val == '' ) {
					    return arrow2;
				    }
				    else 
					    return arrow2;
			    }
			}
			
			function ColorizeFont ( val, numberOfDecimals, procent, idName)//, class )
		    {		
			    if ( val == 0 ) {
				    return ('<span id="'+idName+'" class="textXsmall">' + formatNumber(val, numberOfDecimals) + procent +'</span>');//class="trend_nochange"
			    }
			    else if ( val < 0 ) {
				    return ('<span id="'+idName+'" class="textXsmallrot">' + formatNumber(val, numberOfDecimals) + procent +'</span>');//class="trend_red"
			    }
			    else if ( val > 0 ) {
				    return ('<span id="'+idName+'" class="textXsmallgruen">+' + formatNumber(val, numberOfDecimals) + procent +'</span>');//class="trend_green"
			    }
			    /*else if (val =='White'){
				    return ('<span id="cPercent" style="color:#000000;">+' + formatNumber(val, numberOfDecimals) + '%</span>');//style="color:#FFFFFF;"
			    }*/
			    else if ( val == NaN ) {
				    return ('<span id="'+idName+'" class="textXsmall">' + formatNumber(val, numberOfDecimals) + procent +'</span>');//class="trend_nochange"
			    }				
			    else if ( val == '' ) {
				    return ('<span id="'+idName+'" class="textXsmall"></span>' + formatNumber(val, numberOfDecimals) + procent +'</span>');//class="trend_nochange"
			    }
			    else 
				    return ('<span id="'+idName+'" class="textXsmall">' + formatNumber(val, numberOfDecimals) + procent +'</span>');//class="trend_nochange"
		    }
		    
		//*****************
		
		// Show/Hide anim gif for connection (DoJo HttpPush) status
		function onPushConnected(ok, not, connecting){
			showElement(ok)//('fild');
			//hideElements ('notfild','errfild');
			hideElements(connecting, not);

		}
		function onPushDisconnected(ok, not, connecting){//ok, not, connecting
			hideElements(ok, connecting);
			showElement(not);
		}
		function hideElement(elem) {
			var objElem = document.getElementById(elem);	
			if(objElem !=undefined)	objElem.style.display = 'none';	
		}
		function showElement(elem) {
			var objElem = document.getElementById(elem);
			if(objElem !=undefined)	objElem.style.display = 'block';
		}
		function hideElements( elem, elem1 ) {
			var objElem = document.getElementById(elem);
			var objElem1 = document.getElementById(elem1);			
			//Set the display to none (hiding the element)
			if(objElem !=undefined && objElem1 !=undefined){
			objElem.style.display = 'none';
			objElem1.style.display = 'none';		
			}
		}
		function showElements( elem, elem1 ) {
			var objElem = document.getElementById(elem);
			var objElem1 = document.getElementById(elem1);			
			if(objElem !=undefined && objElem1 !=undefined){
			objElem.style.display = 'block';
			objElem1.style.display = 'block';
			}
		}
		//*****************
