﻿var AjaxQueue = new Array();
var LockScrollEvents = false;
var SendCommandTime;
var SuspendDocumentResize = false;
var AsyncAjaxCall = false;
var SessionLifeTime = "";
var HTTPServerURL = "";
var ProcessName = "";
var ServiceURI = "";
var KillingBrowser = false;
var ExecuteBrowserClose = false;
var DocumentExited = false;
var MouseX = 0;
var MouseY = 0;
var AjaxCallRetries = 0;
var ConnectionErrorLayerShown = false;
var GoogleMapsAPILoaded = false;

function DocumentMouseMove(e)
{
    MouseX = e.clientX;
    MouseY = e.clientY;
        
    if (!DocumentMouseMoveing)
    {
        DocumentMouseMoveing = true;
    
        if (FormMoveStarted)
        {
            FormMoveExecute(e, FormMoveHandle);
        }
        else if (FormResizeStarted)
        {
            FormResizeExecute(e, FormResizeHandle);    
            if (navigator.userAgent.indexOf('MSIE')>=0)
            {
                try
                {                
                    document.selection.empty(); 
                }
                catch (e)
                {}
            }
        }
        else if (SplitterMoveStarted)
        {
            SplitterMoveExecute(e, SplitterMoveHandle);
            if (navigator.userAgent.indexOf('MSIE')>=0)
            {
                try
                {                
                    document.selection.empty(); 
                }
                catch (e)
                {}
            }
        }
        else if (DragPreStarted)
        {
            ControlPreDragCheck(e);    
        }
        else if (DragStarted)
        {
            ControlDragExecute(e);
        }
        else if (ImagesViewerHostedControlDragStarted)
        {
            ImagesViewerHostedControlMouseMove(e);
        }        
        
        DocumentMouseMoveing = false;
    }
}

function DocumentMouseUp(e)
{    

    if (FormMoveStarted)
    {
        FormMoveStop(e, FormMoveHandle);
    }
    else if (FormResizeStarted)
    {
        FormResizeStop(e, FormResizeHandle);    
    }
    else if (SplitterMoveStarted)
    {
        SplitterMoveStop(e, SplitterMoveHandle);
    }
    else if (DragPreStarted)
    {
        ControlDragAbort(true);
    }
    else if (DragStarted)
    {
        ControlDragEnd(e);
    }
    else if (ImagesViewerHostedControlDragStarted)
    {
        ImagesViewerHostedControlMouseUp(e);
    }
}

function DocumentKeyDown(e)
{
    var tElement;
    var tKeyCode;
    var tLeftArrowKey = 37;
    var tBackSpaceKey = 8;
    var tEscKey = 27;        
    
    if ((DragStarted) && (e.keyCode == 27))
    {
        ControlDragAbort(true);
    }
    else
    {
        tKeyCode = e.keyCode;        
        if(((e.altKey) && (tKeyCode == tLeftArrowKey)) || (tKeyCode == tEscKey) || (tKeyCode == tBackSpaceKey))
        {    
            if(e.srcElement)
                tElement = e.srcElement;
            else
                tElement = e.target;
                
            if((tElement != null) && (!(tElement.type) || ((tElement.type !='text') && (tElement.type !='textarea') && (tElement.type !='file') && (tElement.type !='password')) || (tElement.readOnly)))
                e.returnValue = false;    
       }
    }        
}

function SendCommand(parSessionId, parHandle, parCommandType, parCommandName, parCommandValue)
{
    // Invia un Command all'applicazione server tramite Ajax in modalità sincrona

    // parSessionId     -> Id della Session corrente
    // parHandle        -> Handle del Control mittente
    // parCommandType   -> Tipo di comando : 1-Metodo; 2-Proprietà
    // parCommandName   -> Nome del comando (Metodo/Proprietà)
    // parCommandValue  -> Se metodo    : parametro/i del metodo (separati da ¯)
    //                     Se proprietà : valore da impostare


    SendCommandInternal(parSessionId, parHandle, parCommandType, parCommandName, parCommandValue, false);
}

function SendCommandInternal(parSessionId, parHandle, parCommandType, parCommandName, parCommandValue, parAsynchRequest)
{
    // Invia un Command all'applicazione server tramite Ajax
    
    // parSessionId     -> Id della Session corrente
    // parHandle        -> Handle del Control mittente
    // parCommandType   -> Tipo di comando : 1-Metodo; 2-Proprietà
    // parCommandName   -> Nome del comando (Metodo/Proprietà)
    // parCommandValue  -> Se metodo    : parametro/i del metodo (separati da ¯)
    //                     Se proprietà : valore da impostare
    // parAsynchRequest -> Indica se la richiesta deve essere effettuata in modalità asincrona
 
    var tAjax;
    var tCommand;
    var tUrl;        
    var tCommandValue;
    
    // Imposta il valore del comando sostituendo '+' e '&'
    tCommandValue = parCommandValue.toString();
    if (tCommandValue!="")
        tCommandValue = tCommandValue.replace(/\+/g, "§P§").replace(/\&/g,"§A§").replace(/\</g,"$MIN$").replace(/\>/g,"$MAX$");        
       
    // Preleva l'indirizzo
    if (HTTPServerURL == "")
        HTTPServerURL = document.getElementById("HTTPServerURL").value;
    
    // Preleva il nome del processo che dovrà eseguire la richiesta
    if (ProcessName == "")
        ProcessName = document.getElementById("ProcessName").value;
        
    // Preleva l'URI del processo che dovrà eseguire la richiesta
    if (ServiceURI == "")
        ServiceURI = document.getElementById("ServiceURI").value;
        
    // Crea il Command (QueryString) da inviare all'applicazione server tramite Ajax
    tCommand = '';
    tCommand += "?SId=" + parSessionId;    
    tCommand += "&H=" + parHandle;
    tCommand += "&CT=" + parCommandType;
    tCommand += "&CN=" + parCommandName;
    tCommand += "&CV=" + tCommandValue;
    tCommand += "&RV=" + parseInt(Math.random()*99999999);
    tCommand += "&PN=" + ProcessName;
    tCommand += "&SU=" + ServiceURI;
    
    // Compila l'Url da chiamare
    tUrl = encodeURI(HTTPServerURL + 'Services/GUI.aspx' + tCommand);
    
    // Aggiunge il comando da eseguire alla coda di esecuzione
    if (!parAsynchRequest)
        AjaxQueue.push(tUrl);
    
    // Esegue il comando nel caso la coda contenga un solo elemento
    if ((AjaxQueue.length==1) || (parAsynchRequest))
        ExecuteCommand(parAsynchRequest, tUrl, false);    
}

function ExecuteCommand(parAsynchRequest, parUrl, parRetring)
{
    // Esegue il comando all'indice zero dalla coda

    var tAjax;
    var tUrl;
    var tAjaxAsyncCall;
    var tAjaxReadyStateChangedHandler;           

    if ((AjaxQueue.length>0) || (parAsynchRequest) || (parRetring))
    {
        // Preleva il primo elemento della coda
        if ((!parAsynchRequest) && (!parRetring))
        {
            while (AjaxQueue.length > 0)
            {
                tUrl = AjaxQueue[0];
                if (tUrl == "")
                    AjaxQueue.shift();
                else
                {
                    AjaxQueue[0] = "";           
                    break;
                }
            }                       
        }
        else
            tUrl = parUrl;
    
        if (tUrl != "")
        {    
            // Preleva l'instanza di Ajax
            tAjax = GetAjax();
            
            // Definisce il metodo di risposta alla chiamata Ajax
            tAjaxReadyStateChangedHandler = function () 
            {
                var tRetry;
            
                if (tAjax.readyState==4)
                {
                    if ((tAjax.status>=200) && (tAjax.status<300))
                    {
                        // Rimuove l'eventuale layer (div) di segnalazione di errore di connessione
                        RemoveConnectionErrorLayer();
                    
                        ExecuteResponses(tAjax.responseText, parAsynchRequest);
                        tAjax = null;
                    }
                    else
                    {
                        AjaxCallRetries++;
                        
                        if (AjaxCallRetries<3)
                            tRetry = true;                                
                        else
                        {
                            // Visualizza il layer (div) di segnalazione di errore di connessione                        
                            CreateConnectionErrorLayer();
                        
                            tRetry = confirm(QuestionComunicationError);
                            AjaxCallRetries = 0;
                        }
                        
                        if (tRetry)
                            ExecuteCommand(parAsynchRequest, parUrl, true);
                        else
                        {
                            KillingBrowser = true;
                            ExecuteBrowserClose = true;
                            DocumentExit();
                        }
                    }
                }                
            }            
                            
            // Determina se la chiamata Ajax dovrà essere sincrona o asincrona
            tAjaxAsyncCall = (AsyncAjaxCall || parAsynchRequest);            
            
            // Si collega all'evento di OnReadyStateChange, solo se la chiamata Ajax che verrà effettuata è asincrona
            if(tAjaxAsyncCall)
                tAjax.onreadystatechange = tAjaxReadyStateChangedHandler;
                    
            // Preleva il SessionLifeTime        
            if (SessionLifeTime == "")
                SessionLifeTime = document.getElementById("SessionLifeTime").value;
            
            // Preleva il nome del processo che dovrà eseguire la richiesta
            //if (ProcessName == "")
            //    ProcessName = document.getElementById("ProcessName").value;
                
            // Preleva l'URI del processo che dovrà eseguire la richiesta
            //if (ServiceURI == "")
            //    ServiceURI = document.getElementById("ServiceURI").value;
            
            //tUrl += "&PN=" + ProcessName;
            //tUrl += "&SU=" + ServiceURI;
            tUrl += "&SLT=" + SessionLifeTime;
            
            if (!parRetring)
                AjaxCallRetries = 0;

            //document.title = 'ax' + (tAjaxAsyncCall) + 'x' + AjaxQueue.length;
            
            // Esegue la chiamata Ajax            
            tAjax.open('GET', tUrl, tAjaxAsyncCall);
            AsyncAjaxCall = false;
            try
            {
                tAjax.send(null);
            }
            catch (e)
            {
            }
            
            // Se la chiamata Ajax eseguita era di tipo sincrono, chiama manualmente il metodo di risposta            
            if(!tAjaxAsyncCall)
            //    if(tAjax.onreadystatechange == null)
                    tAjaxReadyStateChangedHandler();
            
            return false;
        }            
    }
}

function ExecuteResponses(parResponses, parAsynchRequest)
{
    // Esegue le operazioni contenute nella stringa di Responses passata

    var tResponses;
    var iResponse;
    var tResponse;
    var tResponseOptions;
    var tAction;
    var tHandle;
    var tParentHandle;
    var tSubHandle;
    var tHTML;
    var tPropertyName;
    var tPropertyValue;
    var tMethodName;
    var tElementId;
    var tMethodParameter;
    var tTime1;
    var tTime2;

    //tTime1 = new Date();
             
    if (parResponses!="")
    {        
        // Esegue lo split principale per separare i diversi Response
        tResponses = parResponses.split('¤');
        
        // Scorre l'array di Responses
        for (iResponse = 0; iResponse < tResponses.length; iResponse++)
        {            
            tResponse = tResponses[iResponse];
               
            if (tResponse.length>0)
            {                            
                // Esegue lo split sulle opzioni del Response
                tResponseOptions = tResponse.split('¯');
                
                if (tResponseOptions.length>0)
                {                                        
                    // Preleva Action, Handle ed eventuale HTML del Response
                    tAction = tResponseOptions[0];
                    
                    switch (tAction)
                    {
                        case "A":                            
                           
                            // Preleva le informazione del Response
                            tHandle = tResponseOptions[1];                            
                            tHTML = tResponseOptions[2];
                            
                            // Aggiunge l'elemento                            
                            AddHandle(tHandle, tHTML);
                            
                            break;
                        case "E":
                        
                            // Preleva le informazione del Response
                            tHandle = tResponseOptions[1];                            
                            tParentHandle = tResponseOptions[2];
                            tHTML = tResponseOptions[3];
                                                        
                            // Modifiche l'elemento
                            EditHandle(tHandle, tParentHandle, tHTML);
                                                    
                            break;
                        case "R":                        

                            // Preleva le informazione del Response
                            tHandle = tResponseOptions[1];
                            
                            // Rimuove l'elemento
                            RemoveHandle(tHandle);
                        
                            break;
                        case "V":
                        
                            // Preleva le informazione del Response
                            tParentHandle = tResponseOptions[1];                            
                            tHandle = tResponseOptions[2];
                            
                            // Aggiunge l'elemento                            
                            MoveHandle(tParentHandle, tHandle);
                        
                            break;
                            
                        case "P":
                        
                            // Preleva le informazioni del Response
                            tSubHandle = tResponseOptions[1];
                            tPropertyName = tResponseOptions[2];
                            tPropertyValue = tResponseOptions[3];
                            
                            // Assegna la proprietà
                            //SetHandleProperty(tSubHandle, tPropertyName, tPropertyValue);
                            SetHandleProperty(tSubHandle, tPropertyName, tPropertyValue);
                                                    
                            break;
                            
                        case "M":
                        
                            // Preleva le informazioni del Response
                            tMethodName = tResponseOptions[1];
                            tElementId = tResponseOptions[2];
                            tMethodParameter = tResponseOptions[3];

                            // Esegue il metodo
                            ExecuteMethod(tMethodName, tElementId, tMethodParameter);
                        
                            break;
                    }
                }                
            }
        }
        
        //tTime2 = new Date();
    
        //document.title = "Tempo trasferimento dati : " + Math.ceil(tTime1.getTime() - SendCommandTime.getTime()) + " - Tempo elaborazione locale : " + Math.ceil(tTime2.getTime() - tTime1.getTime());
    }
    
    // Rimuove l'elemento all'indice zero della coda
    //if ((AjaxQueue.length>0) && (!parAsynchRequest))
    //    AjaxQueue.shift();

    // Esegue il comando successivo (se presente in coda)
    ExecuteCommand(false, "", false);    
}

function AddHandle(parParentHandle, parHTML)
{
    // Aggiunge al Handle passato il codice HTML

    // parParentHandle  -> Handle padre
    // parHTML          -> Codice HTML da inserire

    var tElement;
    var tChildElement;
    var tRange;
    var tContextualFragment;
    var tParentHandle;
    var tRow;
    var tCell;
    var tOldWidth;
    var tVisible;
    
    // Preleva il puntatore all'elemento padre
    tElement = document.getElementById(parParentHandle);
    
    if (tElement != null)
    {
        if (document.createRange)
        {
            // Crea il Range e seleziona l'elemento da modificare
            tRange = document.createRange();
            tRange.selectNode(tElement);

            // Crea il ContextualFragment dell'elemento modificato
            tContextualFragment = tRange.createContextualFragment(parHTML);

            // Aggiunge il codice HTML dell'elemento
            tElement.appendChild(tContextualFragment);
        }
        else
        {    
            if (document.createElement)
            {                   
                // Crea il nodo principale dell'elemento da aggiungere
                tChildElement = document.createElement("");
            
                // Aggiunge il nodo principale dell'elemento
                tElement.appendChild(tChildElement);
                
                // Sostituisce l'intero codice HTML dell'elemento
                tChildElement.outerHTML = parHTML;                                
            }
            else
            {
                tElement.innerHTML += parHTML;
            }
        }                
    }                
}

function EditHandle(parHandle, parParentHandle, parHTML)
{
    // Aggiorna l'elemento passato con l'HTML passato

    // parHandle    -> Handle di riferimento
    // parParentHandle  -> Handle padre
    // parHTML      -> Codice HTML aggiornato

    var tElement;
    var tRange;
    var tContextualFragment;

    // Preleva il puntatore all'elemento da modificare
    tElement = document.getElementById(parHandle);
    
    if (tElement!=null)
    {    
        // Se il browser gestisce la proprietà outerHTML ...
        if (tElement.outerHTML)                            
        {                                    
            // ... sostituisce l'intero codice HTML dell'elemento
            tElement.outerHTML = parHTML;
        }
        else
        {
            // ... utiliza il metodo replaceChild dell'elemento padre
            
            // Crea il Range e seleziona l'elemento da modificare
            tRange = document.createRange();
            tRange.selectNode(tElement);
            
            // Crea il ContextualFragment dell'elemento modificato
            tContextualFragment = tRange.createContextualFragment(parHTML);
            
            // Sostituisce il codice HTML dell'elemento
            tElement.parentNode.replaceChild(tContextualFragment, tElement);                                                           
            
            // Libera le risorse
            tContextualFragment = null;
            tRange = null;                                    
        }
    }
    else
        AddHandle(parParentHandle, parHTML);

    // Libera le risorse
    tElement = null;

}

function RemoveHandle(parHandle)
{
    // Elimina l'elemento passato    
    
    // parHandle    -> Handle dell'elemento da eliminare
    
    var tElement
    var tParentNode;
    var tRow;
    var tCell;
    var tOldWidth;
    var tVisible;
    var iRow;       
    var tFocusTempFocusField;               
    
    // Inizializzazione variabili locali
    //tFocusTempFocusField = false;
    
    // Preleva il puntatore all'elemento da modificare
    tElement = document.getElementById(parHandle);

    if (tElement!=null)
    {    
        // Controlla se l'ActiveElement è figlio dell'Element da rimuovere
        //tFocusTempFocusField = IsChildElement(tElement, document.activeElement);
    
        tParentNode = tElement.parentNode;
    
        // ... utiliza il metodo removeChild dell'elemento padre
        tParentNode.removeChild(tElement);    
                
        // Libera le risorse
        tParentNode = null;
    }
                                    
    // Libera le risorse
    tElement = null;                    
    
    // Imposta il focus sul TempFocusField se l'ActiveElement era figlio dell'Element rimosso
    try
    {    
        if ((document.activeElement != null) && (document.activeElement.tagName != "INPUT"))
            document.getElementById("TempFocusField").focus();
    }
    catch (e)
    {
    }
}

function MoveHandle(parParentHandle, parHandle)
{
    // Sposta un Handle esistente in un nuovo ParentHandle
    
    // parParentHandle  -> Handle padre
    // parHandle        -> Handle di riferimento
    
    var tElement;
    var tParentElement;

    // Preleva il puntatore all'elemento da spostare    
    tElement = document.getElementById(parHandle);
    if (tElement!=null)
    {
        // Preleva il puntatore all'element padre a cui aggiungere l'elemento da spostare
        tParentElement = document.getElementById(parParentHandle);               
        
        // Aggiunge l'elemento al nuovo padre
        if (tParentElement != null)
        {
            if (tElement.parentNode != tParentElement)
                tParentElement.appendChild(tElement);
        }
        
        // Libera le risorse
        tParentElement = null;
    }

    // Libera le risorse    
    tElement = null;    
}

function SetHandleProperty(parSubHandle, parPropertyName, parPropertyValue)
{
    // Assegna il valore alla proprietà del controllo di riferimento
    
    // parSubHandle     -> Id dell'elemento da aggiornare
    // parPropertyName  -> Nome della proprietà da impostare
    // parPropertyValue -> Valore della proprietà

    var tElement;
    var tParentElement;
    var tSubElement;
    var tOldWidth;
    var tCell;
    var tRow;

    // Preleva il puntatore all'elemento da modificare   
    tElement = document.getElementById(parSubHandle);

    if (tElement!=null)
    {   
        switch (parPropertyName)
        {
            case "VALUE":
                        
                tElement.value = parPropertyValue;
                break;
                
            case "TOP":
                tElement.style.top = parPropertyValue + "px";
                break;
                
            case "LEFT":
                tElement.style.left = parPropertyValue + "px";
                break;
                
            case "WIDTH":
                if (parseInt(parPropertyValue)>=0)
                    tElement.style.width = parPropertyValue + "px";                
                break;
                
            case "HEIGHT":
                if (parseInt(parPropertyValue)>=0)
                    tElement.style.height = parPropertyValue + "px";                           
                break;        
                
            case "VISIBLE":
            
                tElement.style.visibility = (parPropertyValue=="0"?"hidden":"inherit");
                tElement.style.display = (parPropertyValue=="0"?"none":"");
                                
                break;

            case "VISIBLEONLY":
            
                tElement.style.visibility = (parPropertyValue=="0"?"hidden":"inherit");
                tElement.style.display = "";
                                
                break;
                
            case "READONLY":
            
                try
                {                
                    tElement.readOnly = (parPropertyValue=="0"?false:true);            
                    
                    if (tElement == document.activeElement)
                        tElement.select();
                }
                catch (e)
                {}
                
                break;
                
            case "ENABLED":
                
                tElement.disabled = (parPropertyValue=="0"?true:false);
                break;
                
            case "ZORDER":
            
                tElement.style.zIndex = parPropertyValue;
                break;
                
            case "INNERHTML":
                
                tElement.innerHTML = parPropertyValue;
                break;
                
            case "TITLE":
            
                tElement.title = parPropertyValue;
                break;                
                
            case "SCROLLTOP":
                
                tElement.scrollTop = parPropertyValue;
                break;

            case "SCROLLLEFT":
                
                //LockScrollEvents = true;
                tElement.scrollLeft = parPropertyValue;
                break;
                
            case "CURSOR":
            
                tElement.style.cursor = parPropertyValue;
                break;
                
            case "BACKCOLOR":
                                
                GridHostedControlResetBackgroundColor();
                tElement.style.backgroundColor = parPropertyValue;
                break;

            case "FORECOLOR":
                
                tElement.style.color = parPropertyValue;
                break;

            case "BORDERCOLOR":
                
                if (parPropertyValue == "transparent")
                    tElement.style.border = "none 0px";
                else
                    tElement.style.border = "solid 1px " + parPropertyValue;                
                break;
                
            case "BACKGROUNDIMAGE":
            
                tElement.style.backgroundImage = parPropertyValue;
                break;
                
            case "PADDINGTOP":
            
                tElement.style.paddingTop = parPropertyValue;
                break;

            case "PADDINGLEFT":
            
                tElement.style.paddingLeft = parPropertyValue;
                break;
                
            case "PADDINGRIGHT":
            
                tElement.style.paddingRight = parPropertyValue;
                break;
                
            case "PADDINGBOTTOM":
            
                tElement.style.paddingBottom = parPropertyValue;
                break;
        }
        
        // Libera le risorse
        tElement = null;        
    }
}

function ExecuteMethod(parMethodName, parElementId, parMethodParameter)
{
    // Esegue il metodo
    
    // parMethodName        -> Nome del metodo da eseguire
    // parElementId         -> Elemento di riferimento
    // parMethodParameter   -> Parametro del metodo
    
    var tThreadAjax;
    var tElement;
    var tExecuteCommandOptions;
    var tSessionId;
    var tSessionLifeTime;
    var tProcessName;
    var tServiceURI;
    var tHTTPServerURL;
    var tAbsoluteTop;
    var tAbsoluteLeft;
    var tMethodParameters;
    var tCookieResult;
    var tCookieExpireDate;
    
    switch (parMethodName)
    {
        case "REMOVEELEMENT":
            
            RemoveHandle(parElementId);        
            break;
            
        case "FOCUS":
        
            tElement = document.getElementById(parElementId);
        
            if (tElement!=null)
            {
                if (tElement.style.visibility != "hidden")
                {
                    try
                    {
                        tElement.focus();                        
                    }
                    catch (e)
                    {}
                }
            }
                
            tElement = null;
            break;
        
        case "BLUR":
                        
            tElement = document.getElementById(parMethodParameter);
        
            if (tElement!=null)
            {
                // Preleva il SessionId corrente
                tSessionId = document.getElementById("SessionId").value;
            
                // Invia le coordinate assolute al server
                SendCommand(tSessionId, parElementId, 1, "OnBlurResponse", tElement.value);
            }
                
            tElement = null;
            break;
            
        case "EXIT":

            ExecuteBrowserClose = true;            
            DocumentExit();                
            
            break;
            
        case "SETTITLE":
        
            document.title = parMethodParameter;            
            break;
            
        case "SHOWALERT":
            
            alert(parMethodParameter);
            break;
            
        case "GRIDROWSELECTED":
        
            GridHostedControlResetBackgroundColor();
            break;
            
        case "FLUSHRESPONSE":

            window.setTimeout("ExecuteFlushResponse()", 50);
            break; 
            
        case "SENDABSOLUTELOCATION":

            // Preleva il SessionId corrente
            tSessionId = document.getElementById("SessionId").value;

            tElement = document.getElementById(parElementId);
            
            if (tElement != null)
            {        
                // Calcola le posizione Top e Left assolute    
                tAbsoluteTop = GetAbsoluteTop(tElement);
                tAbsoluteLeft = GetAbsoluteLeft(tElement);
                
                // Invia le coordinate assolute al server
                SendCommand(tSessionId, parElementId, 1, "OnAbsoluteLocation", tAbsoluteLeft + "|;" + tAbsoluteTop);
                
                tElement = null;
            }            
            break;
            
        case "INVOKESCROLLMETHOD":
            
            // Preleva il SessionId corrente
            tSessionId = document.getElementById("SessionId").value;

            tElement = document.getElementById(parElementId);
            
            if (tElement != null)
            {        
                Control_Scroll(tElement, tSessionId, tElement.id, parMethodParameter);            
                tElement = null;
            }
            break;
            
        case "STARTTHREADCALLER":
        
            // Preleva il SessionId corrente
            tSessionId = document.getElementById("SessionId").value;
            tSessionLifeTime = document.getElementById("SessionLifeTime").value;
            tProcessName = document.getElementById("ProcessName").value;
            tServiceURI = document.getElementById("ServiceURI").value;
            tHTTPServerURL = document.getElementById("HTTPServerURL").value;
        
            // Preleva l'instanza di Ajax
            tThreadAjax = GetAjax();
                        
            // Imposta il metodo di risposta alla chiamata Ajax
            tThreadAjax.onreadystatechange = 
            
                // Metodo di risposta        
                function() 
                {
                    //if (tThreadAjax.readyState==4)
                    //    document.title = tThreadAjax.status;
                
                    if (tThreadAjax.readyState==4)
                    {
                        if ((tThreadAjax.status>=200) && (tThreadAjax.status<300))
                        {
                            SendCommandInternal(tSessionId, 0, 1, "OnThreadFlushResponse", "", false);
                            tThreadAjax = null;
                        }
                        else
                        {
                            // Riesegue la chiamata in caso di errore 500 (Internal Server Error)
                            // rilevato durante chiamate 'parallele' tra i due Ajax in funzione
                            ExecuteMethod("STARTTHREADCALLER", "", "");
                        }
                    }
                }
              
            // Esegue la chiamata Ajax
            tThreadAjax.open('GET', tHTTPServerURL + "Services/ThreadCaller.aspx?SessionId=" + tSessionId + "&PN=" + tProcessName + "&SU=" + tServiceURI + "&SLT=" + tSessionLifeTime + "&RandomValue=" + parseInt(Math.random()*99999999), true);
            tThreadAjax.send(null);

            break;                       
            
        case "FORMMOVESTART":
        
            tMethodParameters = parMethodParameter.split("<par>");        
            FormMoveStart(tMethodParameters[0], tMethodParameters[1], tMethodParameters[2]);
        
            break; 
            
        case "FORMRESIZESTART":
        
            tMethodParameters = parMethodParameter.split("<par>");
            FormResizeStart(tMethodParameters[0], tMethodParameters[1], tMethodParameters[2], tMethodParameters[3], tMethodParameters[4], tMethodParameters[5], tMethodParameters[6], tMethodParameters[7], tMethodParameters[8], tMethodParameters[9]);
        
            break;
            
        case "SETFONT":
        
            tElement = document.getElementById(parElementId);
            
            if (tElement != null)
            {        
                tMethodParameters = parMethodParameter.split("<par>");
                
                tElement.style.fontFamily = tMethodParameters[0];
                tElement.style.fontSize = tMethodParameters[1] + "px";
                tElement.style.fontWeight = tMethodParameters[2];
                tElement.style.fontStyle = tMethodParameters[3];
            }                   
        
            tElement = null;
            break;
            
        case "SETCOOKIE":
        
            // Scrive il Cookie        
            tMethodParameters = parMethodParameter.split("<par>");
            tCookieExpireDate = new Date();
            tCookieExpireDate.setTime(tCookieExpireDate.getTime() + (365 * 24 * 60 * 60 * 1000));
            document.cookie = tMethodParameters[0] + "=" + escape(tMethodParameters[1]) + "; path=/; expires=" + tCookieExpireDate.toGMTString();
            
            break;
            
        case "GETCOOKIE":                              
        
            // Cerca il Cookie richiesto
            tCookieResult = document.cookie.match ( parMethodParameter + '=(.*?)(;|$)' );
            
            if (tCookieResult)
            {
                // Preleva il SessionId corrente
                tSessionId = document.getElementById("SessionId").value;
            
                // Invia il comando di risposta di lettura del Cookie
                SendCommand(tSessionId, 0, 1, "OnGetCookieResponse", unescape(tCookieResult[1]));
            }        
            break;
                
        case "SUSPENDDOCUMENTRESIZE":
        
            SuspendDocumentResize = true;        
            break;
            
        case "RESUMEDOCUMENTRESIZE":
        
            SuspendDocumentResize = false;            
            break;
            
        case "EXECUTENEXTAJAXCALLASYNC":
        
            AsyncAjaxCall = true;
            break;
            
        case "KILLBROWSER":
            
            if (!DocumentExited)
            {
                // Imposta la sessione in stato di KillingBrowser
                KillingBrowser = true;
                ExecuteBrowserClose = true;
                DocumentExited = true;
                
                // Visualizza il messaggio di chiusura
                if (parMethodParameter != "")
                    alert(parMethodParameter);
                
                // Chiude il browser    
                DocumentExit();
            }
            
            break;
        case "DRAGSTART":
        
            ControlDragStart(parMethodParameter);
            break;
            
        case "DRAGABORT":
            
            ControlDragAbort(true);        
            break;
            
        case "CHECKISMOUSEOVER":
            
            CheckIsMouseOver(parElementId);
            break;
                                            
        case "MAPVIEWERREFRESH":
            
            MapViewer.ExecuteCommand(parElementId, parMethodParameter);
            break;
            
        case "DRAGINITIALIZE":
            
            tMethodParameters = parMethodParameter.split("<par>");
            ControlDragInitialize(parElementId, tMethodParameters[0], tMethodParameters[1], true, tMethodParameters[2]);
            break;
            
        case "RESTARTREQUEST":
            if (confirm(RestartRequest))
            {
                // Invia il comando di chiusura della sessione
                SendCommand(document.getElementById('SessionId').value, 0, 1, "Exit", "");
                
                // Riforza un load della RunWedApplication
                location.href = location.href;
            }
            break;
            
       case "FADE":
            
            tMethodParameters = parMethodParameter.split("<par>");                
            Control_Fade(document.getElementById('SessionId').value, parElementId, tMethodParameters[0], tMethodParameters[1], tMethodParameters[2]);
            break;
    }
}

function ExecuteFlushResponse()
{
    // Esegue la ri-chiamata del comando di Flush

    // Preleva il SessionId corrente
    tSessionId = document.getElementById("SessionId").value;

    // Esegue il comando richiesto
    SendCommand(tSessionId, 0, 1, "OnFlushResponse", "");
}

function DocumentLoad(parSessionId, parGoogleMapsAPILoaded)
{
    // Preleva le informazioni iniziali del Browser e le segnala alla GUI
    
    // parSessionId     -> Id della Session corrente
    
    var tDecimalSeparator;
    var tShortDateFormat;
    var tClientWidth;
    var tClientHeight;
    var tClientMouseEnterEventName;
    var tClientMouseLeaveEventName;
    var tWritingModeEnabled;
    var tUserAgent;
    
    // Memorizza il fatto che le API di GoogleMaps siano state inizializzate o meno
    GoogleMapsAPILoaded = parGoogleMapsAPILoaded;
    
    // Preleva il carattere utilizzato come separatore dei decimali nelle impostazioni locali
    tDecimalSeparator = GetDecimalSeparator();
    
    // Preleva la stringa di formattazione per i campi data
    tShortDateFormat = GetShortDateFormat();
    
    // Preleva le dimensioni dell'area client del Browser
    tClientWidth = GetClientWidth();
    tClientHeight = GetClientHeight();      
    
    if (navigator.userAgent.indexOf('MSIE')<0)
    {
        tClientMouseEnterEventName = "onmouseover";
        tClientMouseLeaveEventName = "onmouseout";
        tWritingModeEnabled = 0;
    }
    else
    {
        tClientMouseEnterEventName = "onmouseenter";
        tClientMouseLeaveEventName = "onmouseleave";
        tWritingModeEnabled = 1;
    }    
    
    // Preleva la stringa UserAgent
    tUserAgent = navigator.userAgent;
    
    // Invia il comando di impostazione delle impostazioni locali
    SendCommand(parSessionId, 0, 1, "RunApplication", tDecimalSeparator + "|;" + tShortDateFormat + "|;" + tClientWidth + "|;" + tClientHeight + "|;" + tClientMouseEnterEventName + "|;" + tClientMouseLeaveEventName + "|;" + tWritingModeEnabled + "|;" + tUserAgent);
    
    // Esegue il precaricamento dell'immagine di ConnectionError    
    AddHandle("ApplicationLayer", "<img id=ConnectionErrorImage src=\"Images/ConnectionError.gif\" style=\"display:none\" onload=\"return RemoveHandle('ConnectionErrorImage')\"/>");
}

function DocumentResize(parSessionId, parHandle)
{
    // Imposta la dimensione della GUI
    
    // parSessionId     -> Id della Session corrente
    // parHandle        -> Handle del MainControl della GUI
    
    var tClientWidth;
    var tClientHeight;    
    
    if (!SuspendDocumentResize)
    {
        // Preleva le dimensioni dell'area client del Browser
        tClientWidth = GetClientWidth();
        tClientHeight = GetClientHeight();
            
        // Invia il comando di impostazione della dimensione del browser
        SendCommand(parSessionId, parHandle, 1, "SetLocationAndSize", "0|;0|;" + tClientWidth + "|;" + tClientHeight);
    }
}

function DocumentExit()
{
    // Esegue la chiusura del browser in modo silenzioso

    var tWindow;

    if (!KillingBrowser)
        SendCommand(document.getElementById('SessionId').value, 0, 1, "Exit", "");
        
    if (ExecuteBrowserClose)
    {
        ExecuteBrowserClose = false;
    
        if(GoogleMapsAPILoaded)        
            GUnload();
        
        if(MapViewer != null)
        {
            MapViewer.Dispose();
            MapViewer = null;
        }
    
        RemoveHandle("H_1");

        if (navigator.userAgent.indexOf('MSIE')>=0)
        {    
            tWindow = top;
            tWindow.opener = top;
            tWindow.close();       
        }        
    }
}

function CheckIsMouseOver(parElementId)
{
    // Controlla se il mouse si trova sopra all'element corrispondente all'ElementId passato
    
    // parElementId -> ElementId di riferimento
    
    var tElement;
    var tTop;
    var tLeft;
    var tIsMouseOver;
    
    tIsMouseOver = "0";
    
    tElement = document.getElementById(parElementId);
    if (tElement != null)
    {
        tTop = GetAbsoluteTop(tElement);
        tLeft = GetAbsoluteLeft(tElement);
        
        if ((MouseX >= tLeft) && (MouseX <= tLeft + tElement.offsetWidth) && (MouseY >= tTop) && (MouseY <= tTop + tElement.offsetHeight))
        {
            tIsMouseOver = "1";                   
        }
    }    
    
    SendCommand(document.getElementById("SessionId").value, parElementId, 1, "OnCheckIsMouseOver", tIsMouseOver);
}

function CreateConnectionErrorLayer()
{
    // Crea il layer (div) per la segnalazione di problemi di connessione
    // solo in caso non sia già presente
    
    var tHTML;
            
    if (!ConnectionErrorLayerShown)
    {
        tHTML = "";
        tHTML += "<div id=ConnectionError style=\"";
        tHTML += "position:absolute;overflow:hidden;";
        tHTML += "top:0px;";
        tHTML += "left:0px;";
        tHTML += "width:" + GetClientWidth() + "px;";
        tHTML += "height:" + GetClientHeight() + "px;";
        tHTML += "border: none 0px;";
        tHTML += "background-color:gray;";
        tHTML += "filter:alpha(opacity=70);opacity:.70;";
        tHTML += "z-index: 10000;";
        tHTML += "\" contenteditable=false unselectable=on>";
        tHTML += "<img src=\"Images/ConnectionError.gif\" />";
        tHTML += "</div>";        
        
        AddHandle("H_1", tHTML);
        
        ConnectionErrorLayerShown = true;
    }
}

function RemoveConnectionErrorLayer()
{
    // Rimuove il layer (div) per la segnalazione di problemi di connessione
    // solo in caso sia presente
    
    if (ConnectionErrorLayerShown)
    {
        RemoveHandle("ConnectionError");
        
        ConnectionErrorLayerShown = false;
    }
}

function ExecuteValidate(parEvent, parSessionId)
{
    // Esegue la validazione di tutti i controlli presenti nella coda del ValidateManager

    // parEvent     -> Evento
    // parSessionId -> SessionId di riferimento    

    if(parEvent.toElement == null)
        SendCommand(parSessionId, 0, 1, "ExecuteValidate", "");
}
