﻿/// <reference path="jquery.intellisense.js"/>

var currentjFloaterId = null;

/***********************************************************************************************************/
/*    
 *   Dictionary dei jFloater
 */

// array indicizzato per id di oggetti di tipo jFloater
var alljFloaters = new Object();

// array di tutti i floater (usato per gestire lo zindex dei floater
var jFloaterArray = new Array();

/*
 * Accesso per id del div del floater (senza creazione)
 * ottengo un flaoter essitente, ritorna null se non esiste  
 */
function DirectGetjFloater(elementId)
{
    myjFloater = null;
    myjFloater = alljFloaters[elementId];
    return myjFloater;
}

/*
 * Accesso per id del div del floater (con eventuale creazione)
 * crea il floater se non esiste
 */
function GetjFloater(elementId, spanContainer, xmlSettings)
{
    myjFloater = null;
    myjFloater = alljFloaters[elementId];
    
    if(typeof(myjFloater)=="undefined")
    {            
        myjFloater = new jFloater(elementId);
        spanContainer.style.display = "";
        alljFloaters[elementId] = myjFloater;
        
        jFloaterArray[ jFloaterArray.length ] = myjFloater;
    }
    
    //i parametri vanno sempre settati ex novo
    if(typeof(xmlSettings)!="undefined")
        myjFloater.SetParameters(spanContainer, xmlSettings);
        
    return myjFloater;
}

/*
 *   Accesso tramite il div contenuto nel floater
 */
function GetjFloaterByDiv(divElement)
{
    myjFloater = null;
    myjFloater = alljFloaters[divElement.id.replace('jFloaterDiv_','')];
    if(typeof(myjFloater)=="undefined")
    {            
        myjFloater = new jFloater(elementId, "");
        alljFloaters[elementId] = myjFloater;
        
        jFloaterArray[ jFloaterArray.length ] = myjFloater;
    }
    return myjFloater;
}

/*    
 *   Oggetto jFloater
 */
var myjFloater;

/*
 *   costruttore
 */
function jFloater(id)
{
    this.id = id;
    this.status = "hide";
    
    this.centerToScreen = "false";
    
    this.mainDiv = $j("<div id='jFloaterDiv_"+id+"'></div>");
        
    //aggiunta delle funzioni OnMouseIn e OnMouseOut tramite jQuery
    this.mainDiv.hover(
        function() {
            var tmpjFloater = GetjFloaterByDiv(this);
            tmpjFloater.StopTimeout();
        },
        function() {
            var tmpjFloater = GetjFloaterByDiv(this);
            tmpjFloater.StartTimeout();
        }
    )
    
    //style tooltip
    this.mainDiv.css("zIndex", "999");
    this.mainDiv.css("float", "left");
    this.mainDiv.css("clear", "left");
    this.mainDiv.css("margin", "15px 0px 0px 15px");
    this.mainDiv.css("position", "absolute");
    
    this.mainDiv.appendTo("form");
	
	this.tooltipTimeoutId = new Array();
}

/*
 * posizione il floater in base alla posizione nella pagina del mouse, può essere richiamata più volte
 */
jFloater.prototype.MoveIntoScreen = function(moveToMouse)
{
    if(moveToMouse == true) {
        this.yMousePosInitial = yMousePos;
        this.xMousePosInitial = xMousePos; }
	
	var doc = $j(window);
	var x, y;

	if(this.centerToScreen == "true") 
	{
	    x = (doc.width() - this.mainDiv.outerWidth({ margin: true })) / 2 + doc.scrollLeft();
	    y = (doc.height() - this.mainDiv.outerHeight({ margin: true }) ) / 2 + doc.scrollTop();
	}
    else 
    {
	    y = computePositionInScreen(
	        this.yMousePosInitial, 
	        this.mainDiv.outerHeight({ margin: true }), 
	        doc.scrollTop()+doc.height() );		
	    x = computePositionInScreen(
	        this.xMousePosInitial, 
	        this.mainDiv.outerWidth({ margin: true }), 
	        doc.scrollLeft()+doc.width() );
    }
    this.mainDiv.css( "top", y+"px" );
    this.mainDiv.css( "left", x+"px" );
    
    
    // Se IE6 dimensiona l'iframe sottostante
    if ($j.browser.msie && $j.browser.version=="6.0")
    {
        var moduleId = this.id.replace("__Container_","");
        var w = this.mainDiv.width()-5;
        var h = this.mainDiv.height()-5;
        $j("#BackgroundIFrame__" + moduleId).width(w).height(h);
        //alert("Assegnato w=" + w + " h=" + h);
    }
}

/*
 *   Effettua lo show del tooltip e lo riposiziona
 */
jFloater.prototype.ShowToolTip = function()
{
    currentjFloaterId = this.id;

    this.status = "show";

    var nemoModuleContent = $get("ContentElement_" +  this.id);
    if(nemoModuleContent != null)
        spanContainer.style.display == "inline";

	this.mainDiv.show();
    this.MoveIntoScreen(true);    
        
    //i filtri per l'animazione di apertura vanno bene solo IE7
    if( $j.browser.msie && this.mainDiv.attr( "filters" ).length>0 ) 
    {
	    this.mainDiv.hide();
	    this.mainDiv.attr( "filters" )[0].Apply();
	    this.mainDiv.show();
	    this.mainDiv.attr( "filters" )[0].Play(); 
	}
	
	this.StopTimeout();
	//richiamo l'hide a meno che non sia effettuato un reset timeout	
    this.StartTimeout();
    
    //porta in primo piano se stesso
    for(cursor=0;cursor<jFloaterArray.length;cursor++)
    {
        if(jFloaterArray[cursor]!=this) 
        {
            var div = jFloaterArray[cursor].mainDiv.eq(0).contents().eq(0);
            div.css("zIndex", Number(div.css("zIndex"))-1);
            jFloaterArray[cursor].mainDiv.css("zIndex", Number(jFloaterArray[cursor].mainDiv.css("zIndex"))-1); 
        }
        else 
        {
            this.mainDiv.css("zIndex", "999");
            this.mainDiv.eq(0).contents().eq(0).css("zIndex", "1000"); 
        }
    }
}

/*
 *   Effettua l'hide del tooltip
 */
jFloater.prototype.HideToolTip = function()
{        
    currentjFloaterId = null;

    this.status = "hide";
    var nemoModuleContent = $get("ContentElement_" + this.id);
    if(nemoModuleContent != null)
    spanContainer.style.display == "none";

    this.StopTimeout();
    this.mainDiv.hide();

    //porta in primo piano tutti gli altri
    for(cursor=0;cursor<jFloaterArray.length;cursor++)
    if(jFloaterArray[cursor]!=this)
    {
        var internalDiv = jFloaterArray[cursor].mainDiv.eq(0).contents().eq(0);
        internalDiv.css("zIndex", Number(internalDiv.css("zIndex"))+1);
        jFloaterArray[cursor].mainDiv.css("zIndex", Number(jFloaterArray[cursor].mainDiv.css("zIndex"))-1);
    }
    myjFloater = null;
}

/*
 *   Effettua lo switch del tooltip (richiama show/hide alternativamente)
 */
jFloater.prototype.ToggleToolTip = function(xmlSettings)
{
    if( this.mainDiv.css("display") == "none" )
    {
        this.RefreshParameters(xmlSettings);
        this.ShowToolTip();
    }
    else
        this.HideToolTip();
}

/*
 *   Fa partire il timeout di chiusura
 */
jFloater.prototype.StartTimeout = function()
{
    /*
    * questa funzione viene richiamata in seguito ad un evento su un div 
    */
    if( this.closeDelayTime!=0 )
    {
        var tooltipId = window.setTimeout("GetjFloater('"+this.id+"').HideToolTip();", this.closeDelayTime);
        this.tooltipTimeoutId[this.tooltipTimeoutId.length] = tooltipId;
    }   
}

/*
 *   Ferma il timeout di chiusura
 */
jFloater.prototype.StopTimeout = function()
{
    /*
    * questa funzione viene richiamata in seguito ad un evento su un div
    */
    if( this.closeDelayTime!=0 )
    {
        //cancello tutti i timeout attivi attualmente
        for(var i=0;i<this.tooltipTimeoutId.length;i++)
        {
            tooltipId = this.tooltipTimeoutId[i];
            window.clearTimeout(tooltipId);
        }
        this.tooltipTimeoutId = new Array();
    }
}

/*
 *   Riscrive i settings (animazione di apertura, pulsante di chiusura, etc) del floater senza spostare il contenuto
 */
jFloater.prototype.RefreshParameters = function(xmlSettings)
{
    this.SetParameters( null, xmlSettings );
}

/*
 *   Scrive i settings (animazione di apertura, pulsante di chiusura, etc) del floater e sposta il contenuto dentro il floater
 */
jFloater.prototype.SetParameters = function(spanContainer, xmlSettings)
{
    //importo le impostazioni
    var xmlDoc = importXML(htmlDecode(xmlSettings));
    
    this.mainDiv.css("background", "url(" + 
        ( (xmlDoc.getElementsByTagName("Shadow1ImagePath").length!=0)?
             xmlDoc.getElementsByTagName("Shadow1ImagePath")[0].childNodes[0].nodeValue:"" )
         + ") no-repeat bottom right");
    this.mainDiv.css("background", "url(" + 
        ( (xmlDoc.getElementsByTagName("Shadow2ImagePath").length!=0)?
             xmlDoc.getElementsByTagName("Shadow2ImagePath")[0].childNodes[0].nodeValue:"" )
         + ") no-repeat bottom right");
    
    //elimino l'eventuale br messo dopo il dv
    if( spanContainer!=null && spanContainer.childNodes.length>1 )
        if( spanContainer.childNodes[1].nodeName=="BR" )
            spanContainer.removeChild( spanContainer.childNodes[1] );

    var floaterWidth =  xmlDoc.getElementsByTagName("Width").length!=0 && xmlDoc.getElementsByTagName("Width")[0].childNodes.length != 0 ? xmlDoc.getElementsByTagName("Width")[0].childNodes[0].nodeValue : "";
    var floaterHeight = xmlDoc.getElementsByTagName("Height").length!=0 && xmlDoc.getElementsByTagName("Height")[0].childNodes.length != 0 ? xmlDoc.getElementsByTagName("Height")[0].childNodes[0].nodeValue : "";
    this.centerToScreen = xmlDoc.getElementsByTagName("CenterToScreen").length!=0?xmlDoc.getElementsByTagName("CenterToScreen")[0].childNodes[0].nodeValue : "false";
    
    dnn.dom.getById("FloaterSupport_"+this.id.replace("__Container_","")).style.width = floaterWidth;
    dnn.dom.getById("FloaterSupport_"+this.id.replace("__Container_","")).style.height = floaterHeight;

    // determina il ModuleId
    var moduleId = this.id.replace("__Container_","");

    var img = null;
    var table =  $j("#"+this.mainDiv.attr("id")+" > div").contents();
    if( table.length>0 )
    {
        //la tabella è già stata creata, basta recuperare l'immagine
        img = $j('#closeImg_' + moduleId);
        
        var imagePath = xmlDoc.getElementsByTagName("CloseImagePath")[0].childNodes[0].nodeValue;
        img.attr( "src", imagePath );
        
        //div con classi di stile
        var internalDiv = this.mainDiv.eq(0).contents().eq(0);
        internalDiv.css("zIndex", "1000");
        internalDiv.css("margin", "0px 5px 5px 0px");
        internalDiv.css("position", "relative"); //FZ

        var cssNode = xmlDoc.getElementsByTagName("FloaterCssClass");
        if(this.oldFloaterCssClass!=null)
            internalDiv.removeClass( this.oldFloaterCssClass );
        if(cssNode[0].childNodes.length!=0)
        {
            internalDiv.addClass( cssNode[0].childNodes[0].nodeValue );
            this.oldFloaterCssClass = cssNode[0].childNodes[0].nodeValue;
        }
        else
            this.oldFloaterCssClass = null;
        var customCss = xmlDoc.getElementsByTagName("CustomCssClass");
        if(this.oldCustomCss!=null)
        {
            var oldAttrib = GetCssAttribList(this.oldCustomCss);
            for(i=0;i<oldAttrib.length;i++)
                if(oldAttrib[i].length>1)
                    internalDiv.css(oldAttrib[i][0],"");
        }
        if(customCss[0].childNodes.length!=0)
        {
            var newAttrib = GetCssAttribList(customCss[0].childNodes[0].nodeValue);
            for(i=0;i<newAttrib.length;i++)
                if(newAttrib[i].length>1)
                    internalDiv.css( newAttrib[i][0], newAttrib[i][1] );
            this.oldCustomCss = customCss[0].childNodes[0].nodeValue;
        }
        else   
            this.oldCustomCss = null;
    }
    else
    {
        var closeLink = "javascript:GetjFloater('"+this.id+"').HideToolTip();";
        table = $j("<table></table>"); // --> oggetto jQuery contenente un nuovo elemento HTML table
        var imagePath = xmlDoc.getElementsByTagName("CloseImagePath")[0].childNodes[0].nodeValue;
        img = $j("<img src='" + imagePath + "' border=0 id='closeImg_" + moduleId + "'>");
        var a = $j("<a></a>").append( img );
        a.attr( "href", closeLink );
        
        // ORIGINALE:
//        table.append( $j("<tr></tr>").append("<td></td>").append( $j("<td style='text-align:right;'></td>").append( a ) ).append("<td></td>") );
        // FEDE:
        var spacerPath = xmlDoc.getElementsByTagName("SpacerImagePath")[0].childNodes[0].nodeValue;
        //alert("spacerPath: " + spacerPath);
        var centerTd = $j("<td style='text-align:right' id='handle_" + moduleId + "'><img src='" + spacerPath + "' /></td>").append( a );
        table.append( $j("<tr></tr>").append("<td></td>").append( centerTd ).append("<td></td>") );  

        //alert(table.html());
        var internalDiv = $j("<div ></div>");
        internalDiv.css("zIndex", "1000");
        internalDiv.css("margin", "0px 5px 5px 0px");
        internalDiv.css("position", "relative"); //FZ
        
        var cssNode = xmlDoc.getElementsByTagName("FloaterCssClass");
        if(cssNode[0].childNodes.length!=0)
        {
            // nome della classe di stile (Floater/FloaterBorder)
            //var floaterCssClass = cssNode[0].childNodes[0].nodeValue;
            //alert("floaterCssClass: " + floaterCssClass);
            internalDiv.addClass( cssNode[0].childNodes[0].nodeValue );
            this.oldFloaterCssClass = cssNode[0].childNodes[0].nodeValue;
        }
        else
            this.oldFloaterCssClass = null;
            
        var customCss = xmlDoc.getElementsByTagName("CustomCssClass");
        var newStyle = internalDiv.attr( "style" );
        if(customCss[0].childNodes.length!=0)
        {
            // eventuale stile personalizzato
            //var customCssClass = customCss[0].childNodes[0].nodeValue;
            //alert("customCssClass: " + customCssClass);
            newStyle += "; " + customCss[0].childNodes[0].nodeValue;
            this.oldCustomCss = customCss[0].childNodes[0].nodeValue;
        }
        else   
            this.oldCustomCss = null;
        internalDiv.attr( "style", newStyle );

        this.mainDiv.append( internalDiv.append(
            table.append( $j("<tr></tr>").append("<td></td>").append( $j("<td></td>").append(spanContainer) ).append("<td></td>") )
        ) );


        // Se IE6 per nascondere le SELECT sottostanti inserisce
        // un iframe dentro mainDiv ma sotto internalDiv
        if ($j.browser.msie && $j.browser.version=="6.0")
        {
            //alert("Stai usando IE6.");
            var innerDiv = this.mainDiv.eq(0).contents().eq(0);
            var htmlIFrame = "<iframe id='BackgroundIFrame__" + moduleId + "' style=';position:absolute;z-index:900;left:0;top:0;height:300;width:500' frameborder='no'></iframe>";
            //alert(htmlIFrame);
            this.mainDiv.append( $j(htmlIFrame) );
        }
    }
//    alert(table.html());

    
    // nasconde il pulsante di chiusura
    if( xmlDoc.getElementsByTagName("ShowCloseButton")[0].childNodes[0].nodeValue!="true" )
        img.hide();

    //imposto l'animazione
    var transitionNode = xmlDoc.getElementsByTagName("OpeningAnimation")
    if(transitionNode[0].childNodes.length!=0)
        this.mainDiv.css( "filter", transitionNode[0].childNodes[0].nodeValue );
    else
        this.mainDiv.css( "filter", "" );
        
    //imposto il draggable        
    if(xmlDoc.getElementsByTagName("RenderMode")[0].childNodes[0].nodeValue == "Movable")
    {
        // imposta il TD come barra di trascinamento
        this.mainDiv.draggable({
            handle: "#handle_" + moduleId
        });
        $j("#handle_" + moduleId).css({
            cursor: "pointer"
//            borderWidth: "1px",
//            borderStyle: "solid",
//            borderColor: "LightGrey"    
        });
        // per dare alla barra l'altezza di 12px anche se il pulsante di chiusura è invisibile
        if( xmlDoc.getElementsByTagName("ShowCloseButton")[0].childNodes[0].nodeValue!="true" )
            $j("#handle_" + moduleId + ' img').css("height", "12px");
    }

    //imposto il timeout
    this.closeDelayTime = xmlDoc.getElementsByTagName("CloseDelayTime")[0].childNodes[0].nodeValue;
}


