﻿function OnlineManager(serviceUrl)
{
    OnlineManager.prototype.RegisterControl = OnlineManager_RegisterControl; 
    OnlineManager.prototype.UnregisterControl = OnlineManager_UnregisterControl; 
    OnlineManager.prototype.IsRegistered = OnlineManager_IsRegistered; 
    OnlineManager.prototype.InitDataLoad = OnlineManager_InitDataLoad;
    OnlineManager.prototype.UpdateControl = OnlineManager_UpdateControl;
    OnlineManager.prototype.SetRefreshTimeForControl = OnlineManager_SetRefreshTimeForControl;
    var documentObject;
    var request;
    var controlCollection = new ControlCollection();
    var webServiceUrl = serviceUrl;
    var minTimerTick = 0;
    var actualElapsedTime = 0;
    var maxTimerTick = 0;

    function OnlineManager_SetRefreshTimeForControl(control, value)
    {
        var index = controlCollection.IndexOf(control);

        var cnt = controlCollection.Get(index);
        if (cnt != null) 
        {
            cnt.SetRefreshTimeInterval(value);
            controlCollection.Remove(cnt);
            controlCollection.Add(cnt);
        }
    }
    
    function OnlineManager_RegisterControl(control)
    {
        controlCollection.Add(control)
    }
    
    function OnlineManager_IsRegistered(control){            
        return controlCollection.IsRegistered(control);
    }

    function OnlineManager_UnregisterControl(control)
    {
        controlCollection.Remove(control);                
    }

    function OnlineManager_InitDataLoad()
    {
        for(i=0;i < controlCollection.Count(); i++)
        {
            var control = controlCollection.Get(i);
            if(control != null)
            {
                control.SetNextFireTime(control.GetRefreshTimeInterval());
                if(minTimerTick == 0 || minTimerTick > control.GetRefreshTimeInterval())
                {
                    minTimerTick = control.GetRefreshTimeInterval();
                }
                if(maxTimerTick == 0 || maxTimerTick < control.GetRefreshTimeInterval())
                {
                    maxTimerTick = control.GetRefreshTimeInterval();
                }
            }
        }
        if(minTimerTick > 0)
        {
            actualElapsedTime = minTimerTick;
            window.setTimeout(OnlineManager_LoadData,minTimerTick);
        }
    }
    
    function OnlineManager_UpdateControl( control )
    {
        if (( control == null ) || ( control == 'undefined' ))
        {
            return ;
        }        
        try{
            request = getXMLHTTPRequest();        
            if( request == null ){
                return false;
            }
            var soap = OnlineManager_GetSoapEnvelope( control );
            if ( soap == null ){
                return false;
            }            
            request.onreadystatechange = OnlineManager_OnDataIncomming;
            request.open("POST", webServiceUrl, true);        
            request.setRequestHeader("Content-Type", "application/soap+xml; charset=utf-8");
            request.setRequestHeader("Content-Length", soap.length);        
            request.send(soap);
            return true;
        }
        catch(ex){
            return false;
        }
    }    
    
    function OnlineManager_LoadData()
    {
        request = getXMLHTTPRequest();
        if( request == null ){            
            return false;
        }
        var soap = OnlineManager_GetSoapEnvelope( null );
        request.onreadystatechange = OnlineManager_OnData;
        request.open("POST", webServiceUrl, true);
        request.setRequestHeader("Content-Type", "application/soap+xml; charset=utf-8");
        request.setRequestHeader("Content-Length", soap.length);        
        try{
            request.send(soap);          
        }catch(exception){}
    }
    
    function OnlineManager_OnDataIncomming()
    {
        if(request.readyState == 4)
	    {	        
		    if(request.status == "200")
		    {
		        var ie = false;
		        
		        var xml = request.responseXML; 
		        if ( xml == null ) xml = request.responseText;		        
		        if ( xml == null ) return;		        
		        var xmlDoc = "";
                try
                {
                    try{
                        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                        xmlDoc.loadXML(request.responseText);                    
                        xmlDoc.setProperty('SelectionLanguage','XPath');
                        xmlDoc.setProperty("SelectionNamespaces","xmlns:soap='http://www.w3.org/2003/05/soap-envelope' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns='http://tempuri.org/'");
                        ie = true;
                    } catch(ex){
                        if(xml != null)
                        {
                            xmlDoc = xml;
                        }
                        else
                        {
                            var oParser = new DOMParser();                        
                            xmlDoc = oParser.parseFromString( xml, "text/xml" );
                            /*if(document.implementation.createDocument) {//Firefox
                                xmlDocument = document.implementation.createDocument('', '', null);
                                xmlDocument.innerXml = xml; 
                            }*/
                        }
                    }
                }
                catch(exception){
                }                
	            for(i=0;i < controlCollection.Count(); i++)
                {                    
                    if ( ( xmlDoc==null) || (xmlDoc.documentElement==null)) break;                    
                    var control = controlCollection.Get(i);
                    if((control != null) && ((actualElapsedTime >= control.GetNextFireTime()) || ( control.UpdateCall )))
                    { 
                        control.SetNextFireTime(control.GetRefreshTimeInterval());
                        if ( control.UpdateCall ) control.UpdateCall = false;
                        var node = null;
                        if(!ie)
                        {
                            var nodes = xmlDoc.getElementsByTagName(control.GetDataNodeName())
                            for(j=0;j<nodes.length;j++)
                            {
                                var processNode = nodes[j];
                                var isLookedNode = false;
                                var newtimestamp = "";
                                for(k=0;k<processNode.attributes.length;k++)
                                {      
                                    //if((processNode.attributes[k].name == "timeStampOld") && (processNode.attributes[k].nodeValue == control.GetLastTimestamp()))
                                    if((processNode.attributes[k].name == "timeStampOld") && (processNode.attributes[k].nodeValue == control.GetLastTimestamp()))
                                    { 
                                        isLookedNode = true;
                                        //break;
                                    }
                                    if (processNode.attributes[k].name == "timeStamp"){
                                        newtimestamp = processNode.attributes[k].nodeValue;
                                    }                                    
                                }
                                                                
                                if ( ( newtimestamp == control.GetLastTimestamp() ) && ( newtimestamp != "" ) )
                                {
                                    isLookedNode = false;
                                }                                
                                if(isLookedNode)
                                {                                    
                                    node = processNode;
                                    break;
                                }
                            }
                        }
                        else
                        {   
                            node = xmlDoc.documentElement.selectSingleNode('//'+control.GetDataNodeName()+'[@timeStampOld="'+control.GetLastTimestamp()+'"]');     
                        }                        
                        if(node !=null)
                        {
                            var falldown = true;
                            var timestamp;
                            for(j=0;j<node.attributes.length;j++)
                            {
                                if(node.attributes[j].name == "timeStamp")
                                {
                                    timestamp = node.attributes[j].nodeValue;
                                    control.ResponseArrived();                                    
                                    if (( timestamp == "" ) || ( control.GetLastTimestamp() != timestamp ) )
                                    {                                       
                                        falldown = false;
                                    }
                                }                                
                            }
                            if( falldown == false ){
                                control.SetLastTimestamp(timestamp);
                                var text = Trim(node.text); 
                                if(text.length > 0)
                                {
                                    try{                                    
                                        eval(control.GetSwitchContentFunction()+'; '+control.GetSwitchContentFunctionName()+'(\''+control.ControlObjectName+'\',\''+control.GetId()+'\',\''+escape(text)+'\');');                             
                                    } catch( ex ){                                    
                                    }
                                }
                            }
                        }
                    }
                }
		    }
		    delete request;	
	    }
    }		    
		    
    function OnlineManager_OnData()
    {       
        if(request.readyState == 4)
	    {	        
		    if(request.status == "200")
		    {
		        OnlineManager_OnDataIncomming();
		    }	
            actualElapsedTime += minTimerTick;
		    delete request;
		    window.setTimeout(OnlineManager_LoadData,minTimerTick);		    
	    }
    }    
    
    function getXMLHTTPRequest()
    {
	    var xmlHttp = null;
	    try
	    {
		    xmlHttp = new ActiveXObject("Msxml2.XMLHttp");
	    }
	    catch(e)
	    {
		    try
		    {		 
		        var tp = '.' + typeof(ActiveXObject) + '.';		    
		        if ( tp!='.undefined.' ){		            
			        xmlHttp = new ActiveXObject("Microsoft.XMLHttp");			        
			    }
		    }
		    catch(e2)
		    {
		    }
	    }
    	
	    if(xmlHttp == undefined && (typeof XMLHttpRequest != 'undefined'))
	    {
		    xmlHttp = new XMLHttpRequest();
	    }
    	
	    return xmlHttp;
	    

    }    
    
    function OnlineManager_GetSoapEnvelope( ctrl )
    {
        var dataToLoad="";
        var soap = '<?xml version="1.0" encoding="utf-8"?>'
        + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">'
        + '<soap12:Body><GetData xmlns="http://tempuri.org/"><requestsCollection>';
        if ( ctrl == null ){
            for(i=0;i < controlCollection.Count(); i++)
            {
                var control = controlCollection.Get(i);
                if(control != null)
                {                
                    dd = ';;'+control.GetLastTimestamp()+'|'+control.GetAssemblyName()+'|'+control.GetObjectName()+'|'+control.GetDataNodeName()+';;';
                    jj = dataToLoad.indexOf(';;'+control.GetLastTimestamp()+'|'+control.GetAssemblyName()+'|'+control.GetObjectName()+'|'+control.GetDataNodeName()+';;');
                }
                if(control != null && actualElapsedTime >= control.GetNextFireTime() && !(dataToLoad.indexOf(';;'+control.GetLastTimestamp()+'|'+control.GetAssemblyName()+'|'+control.GetObjectName()+'|'+control.GetDataNodeName()+';;') > -1))
                {                    
                    soap +='<OnlineRequest>';
                    soap +='<NodeName>'+control.GetDataNodeName()+'</NodeName>';
                    soap +='<AssemblyName>'+control.GetAssemblyName()+'</AssemblyName>';
                    soap +='<ObjectName>'+control.GetObjectName()+'</ObjectName>';
                    soap +='<TimeStamp>'+control.GetLastTimestamp()+'</TimeStamp>';
                    soap +='<RequestSettings>'+control.GetRequestSettings()+'</RequestSettings>';
                    soap +='<PropertySettings>'+control.GetPropertySettings()+'</PropertySettings>';
                    soap +='</OnlineRequest>';
                    dataToLoad +=';;'+control.GetLastTimestamp()+'|'+control.GetAssemblyName()+'|'+control.GetObjectName()+'|'+control.GetDataNodeName()+';;';
                    
                }
            }        
        }
        else
        {
            var arr = ctrl;
            try{                
                var str = arr.GetId();
                // ctrl neni pole objektu ale jen jeden               
                arr = new Array( ctrl );
            }catch(ex){
            }   
            for( var f = 0; f < arr.length; f++ ){
                try{
                    control = arr[f];
                    if(control == 'undefined'){
                    }                    
                    else
                    {                        
                        dd = ';;'+control.GetLastTimestamp()+'|'+control.GetAssemblyName()+'|'+control.GetObjectName()+'|'+control.GetDataNodeName()+';;';
                        jj = dataToLoad.indexOf(';;'+control.GetLastTimestamp()+'|'+control.GetAssemblyName()+'|'+control.GetObjectName()+'|'+control.GetDataNodeName()+';;');                        
                        if ( controlCollection.IsRegistered( control ) ){       
                            control.UpdateCall = true; 
                            control.SetNextFireTime(control.GetRefreshTimeInterval());                                                                            
                            soap +='<OnlineRequest>';
                            soap +='<NodeName>'+control.GetDataNodeName()+'</NodeName>';
                            soap +='<AssemblyName>'+control.GetAssemblyName()+'</AssemblyName>';
                            soap +='<ObjectName>'+control.GetObjectName()+'</ObjectName>';
                            soap +='<TimeStamp>'+control.GetLastTimestamp()+'</TimeStamp>';
                            soap +='<RequestSettings>'+control.GetRequestSettings()+'</RequestSettings>';
                            soap +='<PropertySettings>'+control.GetPropertySettings()+'</PropertySettings>';
                            soap +='</OnlineRequest>';
                            dataToLoad +=';;'+control.GetLastTimestamp()+'|'+control.GetAssemblyName()+'|'+control.GetObjectName()+'|'+control.GetDataNodeName()+';;';                        
                        }
                    }
                }catch(ex){                
                }
            }
        }
        soap += '</requestsCollection></GetData></soap12:Body></soap12:Envelope>';        
        return soap;
    }
}

function ControlCollection()
{
    ControlCollection.prototype.Add = ControlCollection_Add;
    ControlCollection.prototype.Remove = ControlCollection_Remove;
    ControlCollection.prototype.RemoveAll = ControlCollection_RemoveAll;
    ControlCollection.prototype.IsRegistered = ControlCollection_IsRegistered;    
    ControlCollection.prototype.Get = ControlCollection_Get;
    ControlCollection.prototype.Count = ControlCollection_Count;
    ControlCollection.prototype.IndexOf = indexOf;
        
    this.increment = 10;
    this.data = new Array(this.increment);
    this.size = 0;
    
    this.getSize = function()
    {
	    return this.size;
    }
    
    this.resize = function() {
	    newData = new Array(this.data.length + this.increment);
	    for	(var i=0; i< this.data.length; i++) {
		    newData[i] = this.data[i];
	    }
	    this.data = newData;
    }
    
    function indexOf(obj) {
	    for (var i=0; i<this.getSize(); i++) {
		    if (this.data[i] == obj) {
			    return i;
		    }
	    }
	    return -1;
    }
    
    function ControlCollection_Count()
    {
	    return this.data.length;
    }
    
    function ControlCollection_IsRegistered(control)
    {
        var index = this.IndexOf(control);
	    if(index < 0) return false;
	    return true;
    }
    
    function ControlCollection_Add(object)
    {
    	if(this.getSize() == this.data.length)
    	{
	        this.resize();
	    }
	    this.data[this.size++] = object;
    }
    
    function ControlCollection_Remove(object) {
	    try {	        
	        var index = this.IndexOf(object);	        
	        if(index < 0) return;
		    var element = this.data[index];
		    this.data[index] = null;
		    for(var i=index; i<(this.getSize()-1); i++) {
			    this.data[i] = this.data[i+1];
		    }
		    this.data[getSize()-1] = null;
		    this.size--;
		    return element;
	    }
	    catch(e) {	        
		    return "Invalid index " + index;
	    }
    } 

    function ControlCollection_RemoveAll() {
	    this.size = 0;
    	
	    for (var i=0; i<this.data.length; i++) {
		    this.data[i] = null;
	    }
    }
    
    function ControlCollection_Get(i)
    {
	    try {
		    return this.data[i];
	    } 
	    catch (e) {
		    return "Exception " + e + " occured when accessing " + i;	
	    }	
    }   
}

function Control()
{
    Control.prototype.SetId = Control_SetId;
    Control.prototype.SetRefreshTimeInterval = Control_SetRefreshTimeInterval;
    Control.prototype.SetLastTimestamp = Control_SetLastTimestamp;
    Control.prototype.SetSwitchContentFunction = Control_SetSwitchContentFunction;
    Control.prototype.SetSwitchContentFunctionName = Control_SetSwitchContentFunctionName;
    Control.prototype.SetDataNodeName = Control_SetDataNodeName;
    Control.prototype.SetAssemblyName = Control_SetAssemblyName;
    Control.prototype.SetObjectName = Control_SetObjectName;
    Control.prototype.SetNextFireTime = Control_SetNextFireTime;
    Control.prototype.GetId = Control_GetId;
    Control.prototype.GetRefreshTimeInterval = Control_GetRefreshTimeInterval;
    Control.prototype.GetLastTimestamp = Control_GetLastTimestamp;
    Control.prototype.GetSwitchContentFunction = Control_GetSwitchContentFunction;
    Control.prototype.GetSwitchContentFunctionName = Control_GetSwitchContentFunctionName;
    Control.prototype.GetDataNodeName = Control_GetDataNodeName;
    Control.prototype.GetAssemblyName = Control_GetAssemblyName;
    Control.prototype.GetObjectName = Control_GetObjectName;
    Control.prototype.GetNextFireTime = Control_GetNextFireTime;
    Control.prototype.GetRequestSettings = Control_GetRequestSettings;
    Control.prototype.SetRequestSettings = Control_SetRequestSettings;
    Control.prototype.GetPropertySettings = Control_GetPropertySettings;
    Control.prototype.SetPropertySettings = Control_SetPropertySettings;
    Control.prototype.ResponseArrived = Control_ResponseArrived;
    
    this.id="";
    this.refreshTimeInterval=0;
    this.nextFireTime = 0;
    this.lastTimestamp="";
    this.switchContentFunction;
    this.switchContentFunctionName;
    this.dataNodeName="";
    this.assemblyName="";
    this.objectName="";
    this.requestSettings="";
    this.propertySettings="";
    this.ControlObjectName="";
    this.UpdateCall=false;
    this.LastResponseTime = new Date().getTime();
    
    function Control_SetId(value)
    {
        this.id = value;
    }
    
    function Control_SetRefreshTimeInterval(value)
    {
        this.refreshTimeInterval = value;
    }
    
    function Control_SetLastTimestamp(value)
    {        
        this.lastTimestamp = value;
        this.LastResponseTime = new Date().getTime();
    }
    
    function Control_SetSwitchContentFunction(value)
    {
        this.switchContentFunction = value;
    }

    function Control_SetSwitchContentFunctionName(value)
    {
        this.switchContentFunctionName = value;
    }

    function Control_SetDataNodeName(value)
    {
        this.dataNodeName = value;
    }

    function Control_SetAssemblyName(value)
    {
        this.assemblyName = value;
    }
    
    function Control_SetObjectName(value)
    {
        this.objectName = value;
    }

    function Control_SetNextFireTime(value)
    {
        this.nextFireTime += value;
    }
    
    function Control_GetId()
    {
        return this.id;
    }
    
    function Control_GetRefreshTimeInterval()
    {
        return this.refreshTimeInterval;
    }
    
    function Control_ResponseArrived()
    {
        this.LastResponseTime = new Date().getTime();        
    }
    
    function Control_GetLastTimestamp()
    {
        var now = new Date().getTime();
        if (( now-this.LastResponseTime ) > (5*this.refreshTimeInterval))
        {   // data ze serveru uz jsou prilis stara            
            return '';
        }
        return this.lastTimestamp;
    }
    
    function Control_GetSwitchContentFunction()
    {
        return this.switchContentFunction;
    }

    function Control_GetSwitchContentFunctionName()
    {
        return this.switchContentFunctionName;
    }
    
    function Control_GetDataNodeName()
    {
        return this.dataNodeName;
    }
    
    function Control_GetAssemblyName()
    {
        return this.assemblyName;
    }
    
    function Control_GetObjectName()
    {
        return this.objectName;
    }

    function Control_GetNextFireTime()
    {
        return this.nextFireTime;
    }
    
    function Control_GetRequestSettings()
    {
        return this.requestSettings;
    };
    function Control_SetRequestSettings(value)
    {
        this.requestSettings = value;
        this.lastTimestamp = "";
    };
    function Control_GetPropertySettings()
    {
        return this.propertySettings;
    };
    function Control_SetPropertySettings(value)
    {
        this.propertySettings = value;
    };
}
