log4javascript.setEnabled(false);
var	log = log4javascript.getDefaultLogger();

function  isOldBrowser(  ) 
{
//    return true;
    return typeof document.body.style.maxHeight == "undefined";
}

function rightTrim(sString) 
{
    while (sString.substring(sString.length-1, sString.length) == ' ')
        sString = sString.substring(0,sString.length-1);
    return sString;
}

function leftTrim(sString) 
{
    while (sString.substring(0,1) == ' ')
        sString = sString.substring(1, sString.length);
    return sString;
}

function trimAll(sString) 
{
    while (sString.substring(0,1) == ' ')
        sString = sString.substring(1, sString.length);
    while (sString.substring(sString.length-1, sString.length) == ' ')
        sString = sString.substring(0,sString.length-1);
    return sString;
}

var tooltipTimeoutId; // Variabile globale che aggancia il timeout per la chiusura del tooltip
var theToolTip;       // Riferimento all'elemento DIV che visualizza il tooltip
var theShadow;        // Riferimento all'elemento DIV che visualizza l'ombra sotto al tooltip

function ShowToolTip(element, width, offsetX, offsetY, shadow)
{
    if (typeof(element)!="object")
    {
      alert("RichToolTip: the value of the parameter 'element' is undefined or is not an object!");
      return;
    }

    if (typeof(width)!="string") width = "";
    if (typeof(offsetX)!="number") offsetX = 15;
    if (typeof(offsetY)!="number") offsetY = 5;
    if (typeof(shadow)!="boolean") shadow = true;

    var x = findPosX(element);
    var y = findPosY(element);
    var html = element.nextSibling.innerHTML;

    if (html == '')
    {
      //evita di mostrare il tooltip se il messaggio è vuoto
      return;
    }

    if (!ToolTipCreated()) 
        CreateToolTip();

    x += offsetX;
    y += offsetY;
    theToolTip.innerHTML = html;
    theToolTip.style.display = "";
    theToolTip.style.left = x + "px";
    theToolTip.style.top = y + "px";
    theToolTip.style.width = width;

    x += 3;
    y += 3;
    theShadow.innerHTML = html;
    theShadow.style.display = shadow ? "" : "none";
    theShadow.style.left = x + "px";
    theShadow.style.top = y + "px";
    theShadow.style.width = width;

    ResetTooltipTimeout();
}

function ToolTipCreated()
{
   if (typeof(theToolTip)=="undefined" | typeof(theShadow)=="undefined")
      return false;
   else
      return true;
}

function CreateToolTip()
{
    CreateToolTip('');
}

function CreateToolTip(idDiv)
{
   theToolTip = document.createElement("div");
   if(idDiv != '')
        theToolTip.id = 'div_'+idDiv;
   theToolTip.style.position = "absolute";
   theToolTip.style.border = "1px solid darkslategray";
   theToolTip.style.padding = "5px";
   theToolTip.style.backgroundColor = "lightyellow";
   theToolTip.style.zIndex = 1000;
   theToolTip.className = "normal";
   theToolTip.onmousemove = ResetTooltipTimeout;
   document.body.appendChild(theToolTip);

   theShadow = document.createElement("div");
   if(idDiv != '')
        theShadow.id = 'div_'+idDiv+'_shadow';
   theShadow.style.position = "absolute";
   theShadow.style.border = "1px solid gray";
   theShadow.style.padding = "5px";
   theShadow.style.color = "gray";
   theShadow.style.backgroundColor = "gray";
   theShadow.style.zIndex = 999;
   theShadow.className = "normal";
   document.body.appendChild(theShadow);
}

function HideToolTip()
{
   if (!ToolTipCreated()) CreateToolTip();

   theToolTip.style.display = "none";
   theShadow.style.display = "none";
}

function ResetTooltipTimeout()
{
   window.clearTimeout(tooltipTimeoutId);
   tooltipTimeoutId = window.setTimeout(HideToolTip, 3000);
}

function findPosX(obj)
{
var curleft = 0;
if(obj.offsetParent)
    while(1) 
    {
      curleft += obj.offsetLeft;
      if(!obj.offsetParent)
        break;
      obj = obj.offsetParent;
    }
else if(obj.x)
    curleft += obj.x;
return curleft;
}
  
function findPosY(obj)
{
var curtop = 0;
if(obj.offsetParent)
    while(1)
    {
      curtop += obj.offsetTop;
      if(!obj.offsetParent)
        break;
      obj = obj.offsetParent;
    }
else if(obj.y)
    curtop += obj.y;
return curtop;
}

function HideShowElements() 
{
    for(i=0;i<arguments.length;i=i+3) 
    { 
        var spanContainer = dnn.dom.getById(arguments[i]);
        if(spanContainer != null) 
        {
            switch(arguments[i+1]) 
            {
                case "show":
                    spanContainer.style.display = "inline";
                break;
                case "hide":
                    spanContainer.style.display = "none";
                break;
                case "switch":
                    if(spanContainer.style.display == "none") 
                        spanContainer.style.display = "inline";
                    else 
                        spanContainer.style.display = "none";
                break;
                case "showFloater":                        
                    //qui viene creato il floater (se non è già stato fatto) e mostrato
                    myFloater = GetjFloater(spanContainer.id, spanContainer, arguments[i+2]);
                    myFloater.ShowToolTip();
                break;
                case "hideFloater":                        
                    //qui viene nascosto il floater
                    myFloater = DirectGetjFloater(spanContainer.id);

                    if( myFloater!=null)
                        myFloater.HideToolTip();
                break;
                case "switchFloat":    
                    //equivalento allo switch show/hide di Nemo ma fatto sul floater            
                    myFloater = DirectGetjFloater(spanContainer.id);
                    if( myFloater!=null )
                        myFloater.ToggleToolTip(arguments[i+2]);
                    else
                    {
                        myFloater = GetjFloater(spanContainer.id, spanContainer, arguments[i+2]);
                        myFloater.ShowToolTip();
                    }
                break;
            }
        }
    }
}

function SetContentBlank(moduleId) 
{
    var spanContainer = dnn.dom.getById("__Container_" + moduleId);
    var nemoModuleContent = $get("ContentElement_" + moduleId);
    var nemoContainerContent = $get("ContainerContentElement_" + moduleId);

    // la condizione nemoModuleContent != null serve per identificare il modulo come dataviewer
    if(nemoModuleContent != null) 
    {
        if(spanContainer.style.display == "none") 
            nemoModuleContent.innerHTML = '&nbsp;';
     }
     if(nemoContainerContent != null) {
        if(spanContainer.style.display == "none") 
            nemoContainerContent.style.display = "none"; 
     }
}

// questa funzione non verifcia se il floater è già hide    oppure no, viene fatto esternamente
function SetContentBlankFloater(moduleId) 
{
    log.debug("=========================================");
    log.debug("SetContentBlankFloater(moduleid: " + moduleId + ")");
    var nemoModuleContent = $get("ContentElement_" + moduleId);
    var nemoContainerContent = $get("ContainerContentElement_" + moduleId);
    if(nemoModuleContent != null) 
        nemoModuleContent.innerHTML = '&nbsp;';
     if(nemoContainerContent != null)
        nemoContainerContent.style.display = "none"; 
}

function HideShowNemoModules() 
{
    var strArgs = "";
    for(var n=0;n<arguments.length;n=n+3) 
    {
        strArgs += ",moduleid: " + arguments[n];
        strArgs += ",operation: " + arguments[n+1];
        strArgs += ",floatersettings: " + arguments[n+2];
    }    
    log.debug("=========================================");
    log.debug("HideShowNemoModules("+strArgs+")");
    for(var i=0;i<arguments.length;i=i+3) 
    { 
        var moduleId = arguments[i];
        var spanContainer = dnn.dom.getById("__Container_" + moduleId);
        var nemoModuleContent = $get("ContentElement_" + moduleId);
        if(spanContainer != null) 
        {
            switch(arguments[i+1]) 
            {
                case "show":
                    SetContentBlank(moduleId);
                    spanContainer.style.display = "inline";
                break;
                case "hide":
                    spanContainer.style.display = "none";
                break;
                case "switch":
                    if(spanContainer.style.display == "none")  
                    {
                        SetContentBlank(moduleId);
                        spanContainer.style.display = "inline";
                    }
                    else 
                        spanContainer.style.display = "none";
                break;
                case "showFloater":                        
                    myFloater = GetjFloater(spanContainer.id, spanContainer, arguments[i+2]);
                    if(myFloater.status == "hide")
                        SetContentBlankFloater(moduleId);
                    myFloater.ShowToolTip();
                break;
                case "hideFloater":                        
                    myFloater = DirectGetjFloater(spanContainer.id);
                    if( myFloater!=null)
                        myFloater.HideToolTip();
                break;
                case "switchFloat":                
                    myFloater = DirectGetjFloater(spanContainer.id);
                    if( myFloater!=null )
                        myFloater.ToggleToolTip(arguments[i+2]);
                    else
                    {
                        myFloater = GetjFloater(spanContainer.id, spanContainer, arguments[i+2]);
                        if(myFloater.status == "hide")
                            SetContentBlankFloater(moduleId);
                        myFloater.ShowToolTip();
                    }
                break;
            }
        }
    }
}

function doNothing() 
{
}

function GetTextValue(controlId) 
{
    var myControl = dnn.dom.getById(controlId);
    if(myControl != null)  
    {
        if(myControl.type=="textarea")
        {
            return myControl.value;
        }
        if(myControl.type=="hidden")
        {
            return myControl.value;
        }
        if(myControl.type=="password")
        {
            return myControl.value; 
        }
        if(myControl.type=="select-multiple")
        {
            var str = "";
            for(z=0;z<myControl.length;z++) {
                if(myControl.options[z].selected)
                    str += myControl.options[z].value + "," }
            return str.substring(0,str.length-1);
        }
        if(myControl.type=="checkbox")
            return myControl.checked;
        if(myControl.type=="text")
            return myControl.value;
        if(myControl.type=="select-one")
            if(myControl.selectedIndex == -1)
                return "";
            else
                return myControl.item(myControl.selectedIndex).value;
    }
    var myControl2 = dnn.dom.getById(controlId + "_0");
    if(myControl2 != null) 
    {
        if(myControl2.type=="radio") 
        {
            for(j=0; j<1000; j++) 
            {
                var myControl3 = dnn.dom.getById(controlId + "_" + j);
                if(myControl3 == null)
                    break;
                if(myControl3.checked)
                    return myControl3.value
            }
        }
        if(myControl2.type=="checkbox") 
        {
            var str = "";
            for(j=0; j<1000; j++) 
            {
                var myControl3 = dnn.dom.getById(controlId + "_" + j);
                if(myControl3 == null)
                    break;
                if(myControl3.checked)
                    str += j + "-esimo,";
            }
            return str.substring(0,str.length-1);
        }
    }
    return "";
}
function GetXmlVariableNode(variableName, nodeControl) {
    var s = "\t<variable>\n\r";
    s = s + "\t\t<name>";
    s = s + variableName;
    s = s + "</name>\n\r";
    s = s + "\t\t<value>";
    s = s + getXmlString(GetTextValue(nodeControl));
    s = s + "</value>\n\r";
    s = s + "\t</variable>\n\r";
    return s;
}
function BuildXml() {
    args = arguments;
    var x = "<variables>\n\r";
    for(i=0; i<args.length; i+=2) {
        x = x + GetXmlVariableNode(args[i],args[i+1]);
    }
    x = x + "</variables>";
    return x;
}

function GetDirectXmlVariableNode(variableName, variableValue) {
    var s = "\t<variable>\n\r";
    s = s + "\t\t<name>";
    s = s + variableName; 
    s = s + "</name>\n\r";
    s = s + "\t\t<value>";
    s = s + getXmlString(variableValue);
    s = s + "</value>\n\r";
    s = s + "\t</variable>\n\r";
    return s;
}
function BuildDirectXml() {
    args = arguments[0];
    var x = "<variables>\n\r";
    for(i=0; i<args.length; i+=2) {
        x = x + GetDirectXmlVariableNode(args[i],args[i+1]);
    }
    x = x + "</variables>";
    return x;
}

function ClientCallBackError() 
{
    var language=(navigator["language"])?navigator["language"]:navigator["userLanguage"];
    if(language == "it")
        alert("Si e' verificato un errore nella richiesta oppure la sessione e' scaduta.\nEseguire nuovamente il login.");
    else
        alert("An error occurred while executing the request or the session may become invalid.\nPlease try to login again.");
}
function getXmlString(str) 
{
    return (''+str)
    .replace(/%/g,'%25')
    .replace(/\+/g,'%2B')
    .replace(/&/g,'&amp;')
    .replace(/</g,'&lt;')
    .replace(/>/g,'&gt;')
    .replace(/"/g,'&quot;')
    .replace(/'/g,'&apos;'); 
}

/* support to queued update panel reload */

// elemento che ha causato il postback
var elem;
// javascript da eseguire in coda ai comandi ospitati dagli user control
var nemoEvals = new Array();

// array dei comandi javascript da eseguire in sequenza
var NemoJsArray = new Array();

// variabile globale: indice del prossimo comando da eseguire
var queuedNemoCommandIndex = 0;

// variabile globale: indica se una sequenza di esecuzione di js in coda è già in corso, non
// possono esserne eseguite altr contemporaneamente
var isExecutingQueuedNemoCommand = false;
log.debug("=========================================");
log.debug("var isExecutingQueuedNemoCommand = false;");

// esegue il javascript in sequenza
function execQueuedNemoCommand() 
{
    log.debug("=========================================");
    log.debug("execQueuedNemoCommand");
    var strNemoJsArray = "";
    for(var n=0; n<NemoJsArray.length; n++) 
        log.debug("n: " + n + " command: " + NemoJsArray[n]);
    if(NemoJsArray != null && queuedNemoCommandIndex < NemoJsArray.length) 
    {
        do 
        {
            eval(NemoJsArray[queuedNemoCommandIndex]);
            log.debug("queuedNemoCommandIndex: " + queuedNemoCommandIndex + " command: " + NemoJsArray[queuedNemoCommandIndex]);    
            queuedNemoCommandIndex = queuedNemoCommandIndex + 1;
            isExecutingQueuedNemoCommand = true;
            log.debug("isExecutingQueuedNemoCommand = true");
            
           if(queuedNemoCommandIndex>= NemoJsArray.length )
            {
                queuedNemoCommandIndex = 0;
                NemoJsArray = new Array();
                isExecutingQueuedNemoCommand = false;
                log.debug("isExecutingQueuedNemoCommand = false");
                return;
            }
            if(NemoJsArray[queuedNemoCommandIndex-1].substring(0,12) == "__doPostBack") 
                return;
        }
        while(queuedNemoCommandIndex < NemoJsArray.length /* && NemoJsArray[queuedNemoCommandIndex].substring(0,12) != "__doPostBack" */);
    }
    else 
    {
        queuedNemoCommandIndex = 0;
        NemoJsArray = new Array();
        isExecutingQueuedNemoCommand = false;
        log.debug("isExecutingQueuedNemoCommand = false");
    }
}
var ScreenMaskTimeout;
var ScreenMaskImageUrl;
var ScreenMaskEnabled;

// funzione eseguita al caricamento della pagina, 
// ce ne può essere solo una di questo tipo di funzioni
function pageLoad(sender, args) 
{
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    if(prm != null && !prm.get_isInAsyncPostBack())
    {

        prm.add_beginRequest(BeginRequestHandler);
        prm.add_endRequest(EndRequestHandler);

        if(typeof(NemoStartUpCommands)!="undefined")
            for(NemoStartUpCommandsConuter=0; NemoStartUpCommandsConuter<NemoStartUpCommands.length; NemoStartUpCommandsConuter++ )
                eval(NemoStartUpCommands[NemoStartUpCommandsConuter]);
        
        ScreenMaskTimeout = $get("ScreenMaskTimeout").value;
        ScreenMaskImageUrl = $get("ScreenMaskImageUrl").value;
        ScreenMaskEnabled = $get("ScreenMaskEnabled").value;

        if(ScreenMaskEnabled == "true")
            setTimeout("AppendScreenMaskImage()",0);
    }
}

function AppendScreenMaskImage() {
/*    $j("<div onclick='return null' id='UpdateInProgressScreenMask' style='z-index:2000; background-color:#EEE; position:absolute; top:0; left:0; width:100; heigth:100; display:none; filter:alpha(opacity=50); filter: alpha(opacity:50);-moz-opacity: 0.50;opacity: 0.50;'><img src='" + ScreenMaskImageUrl + "'></div>")
        .appendTo("body"); */
    $j("<div onclick='return null' id='UpdateInProgressScreenMask' style='z-index:2000; background-color:#EEE; position:absolute; top:0; left:0; width:100; heigth:100; display:none; filter:alpha(opacity=0); filter: alpha(opacity:0);-moz-opacity: 0;opacity: 0;'><img src='" + ScreenMaskImageUrl + "'></div>")
        .appendTo("body");
}

var UpdateInProgressScreenMaskTimeoutId;
function BeginRequestHandler(sender, args) 
{
    log.debug("=========================================");
    log.debug("BeginRequestHandler");
    elem = args.get_postBackElement();
    if(ScreenMaskEnabled == "true")
        UpdateInProgressScreenMaskTimeoutId = setTimeout('ShowMask()',ScreenMaskTimeout);
    
}
function EndRequestHandler(sender, args) 
{
    if(ScreenMaskEnabled == "true") 
    {
        clearTimeout(UpdateInProgressScreenMaskTimeoutId);
        HideMask();
    }
    log.debug("=========================================");
    log.debug("EndRequestHandler");
    log.debug("elem.id: " + elem.id);
    log.debug("nemoEvals[elem.id]: " + nemoEvals[elem.id]);
    eval(nemoEvals[elem.id]);
    execQueuedNemoCommand();
    if(!isOldBrowser())
        return;
    if(typeof(myjFloater) == 'undefined')
        return;
    if(myjFloater == null)
        return;
}

function ShowMask() {
    var doc = $j(window);
    $j("#UpdateInProgressScreenMask")
        .css("top", doc.scrollTop() + "px")
        .css("left", doc.scrollLeft() + "px")
        .css("width",doc.width())
        .css("height",doc.height())
        .show();
}

function HideMask() 
{
    $j("#UpdateInProgressScreenMask").hide();
}

function ShowRefreshIcon(elementId) {
    if (typeof (document.RefreshTimerObjects) == "undefined")
        document.RefreshTimerObjects = new Object();
        
    if (typeof (document.RefreshTimerObjects[elementId]) == "undefined") {
        document.RefreshTimerObjects[elementId] = new Object();
        document.RefreshTimerObjects[elementId].timerAccendi = -1;
        document.RefreshTimerObjects[elementId].timerSpegni = -1;
    }
    if (document.RefreshTimerObjects[elementId].timerAccendi == -1)
        document.RefreshTimerObjects[elementId].timerAccendi = setTimeout('$j("#' + elementId + '").show();document.RefreshTimerObjects["' + elementId + '"].timerAccendi=-1', 1000);
    if (document.RefreshTimerObjects[elementId].timerSpegni != -1) {
        clearTimeout(document.RefreshTimerObjects[elementId].timerSpegni);
        document.RefreshTimerObjects[elementId].timerSpegni = -1;
    }
}

function HideRefreshIcon(elementId) {
    if (typeof (document.RefreshTimerObjects) == "undefined")
        document.RefreshTimerObjects = new Object();
    if (typeof (document.RefreshTimerObjects[elementId]) == "undefined") {
        document.RefreshTimerObjects[elementId] = new Object();
        document.RefreshTimerObjects[elementId].timerAccendi = -1;
        document.RefreshTimerObjects[elementId].timerSpegni = -1;
    }
    if (document.RefreshTimerObjects[elementId].timerSpegni == -1)
        document.RefreshTimerObjects[elementId].timerSpegni = setTimeout('$j("#' + elementId + '").hide();document.RefreshTimerObjects["' + elementId + '"].timerSpegni=-1', 1000);
    if (document.RefreshTimerObjects[elementId].timerAccendi != -1) {
        clearTimeout(document.RefreshTimerObjects[elementId].timerAccendi);
        document.RefreshTimerObjects[elementId].timerAccendi = -1;
    }
}

function GetSyncResponse(url, postData) {
    var xmlhttp = null;
    if (window.XMLHttpRequest)
        xmlhttp = new XMLHttpRequest();
    else if (window.ActiveXObject) {
        if (new ActiveXObject("Microsoft.XMLHTTP"))
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        else
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    // to be ensure non-cached version of response
    url = url + "?rnd=" + Math.random();

    xmlhttp.open("POST", url, false); //false means synchronous
    xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    xmlhttp.send(postData);
    var responseText = xmlhttp.responseText;
    return eval('(' + responseText + ')');
}

// Mette il focus sull'elemento (se visibile ed abilitato) di
// cui trova l'id in un campo nascosto di cui riceve l'id
//function SetFocusOnReferredElement(hiddenFieldId)
//{
//    var hiddenField = $get(hiddenFieldId);
//    if (hiddenField == null) return;

//    var targetId = hiddenField.value;
//    if (targetId == "") return;

//    var targetElement = $get(targetId);
//    if (targetElement == null) return;

//    try { targetElement.focus(); }
//    catch (exc) {}
//}
