/*
 *
 * Estructura del XML para mostrar las imagenes
 *
 * <?xml version='1.0' encoding='UTF-8' standalone='yes'?>
    <archivos>
          <archivo>
                <titulo>Automovil marca fiat, modelo punto</titulo>
                <url>http://nawc.telam:9090/images/photogalery/thumb/15</url>
                <epigrafe>Fiat punto gris</epigrafe>
                <tipo>imagen</tipo>
          </archivo>
          ..
          <archivo>
                <titulo>Automovil marca fiat, modelo punto</titulo>
                <url>http://nawc.telam:9090/images/photogalery/thumb/15</url>
                <epigrafe>Fiat punto gris</epigrafe>
                <tipo>imagen</tipo>
          </archivo>
    <archivos>
 *
 *
 */

//Class javascript 'multimediaSlide'
function multimediaSlide( idComponent, instanceName ) {
    this.urlXml = "";
    this.Xml = null;
    this.XmlLength = 0;
    this.actualNode = -1;
    this.componentId = idComponent;
    this.instanceName = instanceName;
    this.fileContentWidth = 400;
    this.fileContentHeight = 300;
    this.instanceName = instanceName; // ----> Again?
    this.styleHiddeTitle = "";
    this.paddingSize = "";
    this.linkText = "";
    this.buildLinks = false;
    
    /***
     * Link where the file is located, for download purposes
     */
    this.downloadLinkPrefix = "";
    
    /*
     * Si el set de imagenes que recibimos es de un tamaño diferente al marco qeu tenemos, podes corregir con esta
     * opcion.
     */
    this.adjustImagesSizeToFrame = false;
    this.imagen = new Image();

    this.readXml = function readXml(url) {//Leo y parseo el XML en un array
        this.urlXml = url;
        var xotree = new XML.ObjTree();

        var callbackResult = null;
        var myAjax = new Ajax.Request(
            url, {
                asynchronous:false,
                method: 'get',
                onComplete: function(transport){
                    callbackResult = ajaxCallBack(transport)
                }
            }
            );

        xotree.force_array = ['archivo'];
        tree = xotree.parseXML( myAjax.transport.responseText );

        //alert(tree.archivos)

        this.XmlLength = this.getXmlLength(tree);
        this.Xml = tree;
    //this.actualNode = -1;
    }

    /**
     * Obtengo la cantidad de registros que contiene el XML
     **/
    this.getXmlLength = function getXmlLength(tree){
        var tamanio = 0;
        try{
            //if (typeof (var) == 'string')
            tamanio = tree.archivos.archivo.size();
        }
        catch(err){
            //si no hay componentes seteo la cantida a CERO
            tamanio = 0;
        }
        return tamanio
    }

    /**
     * Funcion utilizada para asignar el resultado de la consulta echo via AJAX
     **/
    this.ajaxCallBack = function ajaxCallBack(elObjeto){
        var xotree = new XML.ObjTree();
        tree = xotree.parseXML( elObjeto.responseText );
        //this.XmlLength = tree.archivos.archivo.size();
        return tree;
    }

    /**
     *Seteo los tamaños del marco contenedor de las imagenes
     **/
    this.setFrameSize = function setFrameSize(objWidth, objHeight){
        if( !isNaN( objWidth ) ){
            this.fileContentWidth = objWidth;
        }
        if( !isNaN( objHeight ) ){
            this.fileContentHeight = objHeight;
        }
    //id='"+this.componentId+"_file'
    }


    /**
     *Seteo los tamaños del marco contenedor de las imagenes
     **/
    this.hiddeTitle = function hiddeTitle(){
        //Hide Title!
        this.styleHiddeTitle = "display:none";
    }

    /**
     *Seteo los tamaños del marco contenedor de las imagenes
     **/
    this.adjustImagesToFrame = function adjustImagesToFrame(){
        //Hide Title!
        this.adjustImagesSizeToFrame = true;
    }


    /**
     *Seteo los tamaños del marco contenedor de las imagenes
     **/
    this.filesWithLinks = function filesWithLinks(textLink){
        //Hide Title!
        if(textLink!=null || textLink!=null){
            this.linkText = textLink;
        }
        this.buildLinks = true;
    }


    /**
     *Seteo los tamaños del marco contenedor de las imagenes
     **/
    this.setPadding = function setPadding(tamPadding){
        //Hide Title!
        this.paddingSize = "padding:"+tamPadding+"px;";
    }

    /**
     * Muestra el HTML del componente
     **/
    this.displayComponent = function displayComponent() {//Muestra el componente en pantalla
        var styleLink = "";
        var strWidthStyle = "width:"+this.fileContentWidth+"px;";
        var strHeightStyle = "height:"+this.fileContentHeight+"px;";
        if(this.XmlLength>=1)
        {
            //Pregunto si debo crear los links
            if(this.buildLinks){
                styleLink = "visibility:visible;";
            }else{
                styleLink = "visibility:hidden;";}
            //
            // El componente tiene 2 partes dinámicas.
            // 1 - <p> que contiene el archivo expuesto
            // 2 - <div> que contiene la barra de navegacion
            document.write("<div id='"+this.componentId+"' class='fileContainer' style='" + strWidthStyle + "'>\n\
                            <p id='"+this.componentId+"_file' style='" + strWidthStyle + strHeightStyle + this.paddingSize + "' class='imageContainer'></p>\n\
                            <div class='panelDisplayimagenesbottom'>\n\
                                <input id='"+this.componentId+"_actualLink' type='hidden' >\n\
                                <span style='"+styleLink+"margin:12px 0 0 5px;float:left' class='readMore'>\n\
                                    <a style='position:relative' href='javascript:location.href=document.getElementById(\""+this.componentId+"_actualLink\").value'>"+this.linkText+"</a>\n\
                                </span>\n\
                                <a href='javascript:("+this.instanceName+".nextArchive())'>\n\
                                    <img src='/images/imagenbot-desp.gif' class='imgNavigate'>\n\
                                </a>\n\
                                <a href='javascript:"+this.instanceName+".previousArchive()'>\n\
                                    <img src='/images/imagenbot-ant.gif' class='imgNavigate'>\n\
                                </a>\n\
                                <span style='display:none'>\n\
                                    <span class='textNav' id='"+this.componentId+"_navigation_bar'>" + this.actualNode + "</span>/<span class='textNav'>"+this.XmlLength+"</span>\n\
                                </span>\n\
                            </div>\n\
                            <p id='"+this.componentId+"_Title' style='"+this.styleHiddeTitle+"' class='titleContainer'></p>\n\
                        </div>");
            this.initComponent();
        }else{
            document.write("<div id='"+this.componentId+"' style='display:none' class='fileContainer'><p style='height:100px'>&nbsp;</p></div>");
        }
        if(this.XmlLength == 0){
            document.getElementById(this.componentId).style.visibility="hidden"
        }
        return false;
    }

    /**
     * Muestra el componente anterior al visto actualmente
     **/
    this.previousArchive = function previousArchive( ){
        try
        {
            if( (this.actualNode) > 0 ){
                this.actualNode--;
            }
            document.getElementById(this.componentId+'_navigation_bar').innerHTML = this.actualNode+1;
            document.getElementById(this.componentId+'_file').innerHTML = "";
            document.getElementById(this.componentId+"_actualLink").value = this.getLink();
            this.insertFilePreview(this.componentId+'_file')
            document.getElementById(this.componentId+'_Title').innerHTML = this.getTitle();
        }
        catch(err)
        {
        //Handle errors here
        //alert(err)
        }
    }

    /**
     * Muestra el componente siguiente al visto actualmente
     **/
    this.nextArchive = function nextArchive( ){
        try
        {
            if( (this.actualNode) < this.XmlLength-1 ){
                this.actualNode++;
            }
            document.getElementById(this.componentId+'_navigation_bar').innerHTML = this.actualNode+1;
            document.getElementById(this.componentId+'_file').innerHTML = "";
            document.getElementById(this.componentId+"_actualLink").value = this.getLink();
            this.insertFilePreview(this.componentId+'_file')
            document.getElementById(this.componentId+'_Title').innerHTML = this.getTitle();
        }
        catch(err)
        {
        //Handle errors here
        //alert(err)
        }
    }
    
    /**
     *Inicia el componente. El objeto se inicia con la varaible 'actualNode' en '-1'.
     *Esta funcion avanza al primer elelmento del XML, y lo renderiza.
     **/
    this.initComponent = function initComponent(){
        this.nextArchive();
    }

    this.getTitle = function getTitle(  ){
        return this.Xml.archivos.archivo[this.actualNode].titulo + " ";
    }

    /**
     * Function to get the target link of file that can be downloaded (or not if hidden).
     * 
     * @return string
     */
    this.getLink = function getLink(){
    	var resultLink = null;
    	
    	// The link prefix is setted? Then we must use it!
    	if (this.downloadLinkPrefix != "")
    	{
    		resultLink = this.downloadLinkPrefix + "/" + this.Xml.archivos.archivo[this.actualNode].idFile;
    	}
    	else
    	{
    		// Otherwise, use the default
    		resultLink = this.Xml.archivos.archivo[this.actualNode].link + " ";
    	}
    	
        return resultLink;
    }

    this.resizeJsImage = function resizeJsImage(contenedor){
        this.imagen = this.correctImageSize(this.fileContentWidth, this.fileContentHeight, this.imagen);
        document.getElementById(contenedor).appendChild( this.imagen );
    }
    /**
     * Inserta el nodo actual, en el contenedor dado
     */
    this.insertFilePreview = function insertFilePreview( contenedor ){
        switch( this.Xml.archivos.archivo[this.actualNode].tipo ) {
            case '2':
            case 'mp3':
                //alert('es un archivo de audio')
                break;
            case '3':
            case 'imagen':
                //Inserto el elemento imagen dentro de su correspondiente contenedor, con el metodo asociado a este dato
                this.imagen = this.loadImage();
                if(this.adjustImagesSizeToFrame){
                    //Si debemos hacer un resize en el cliente via JS. Debemos llamar uan funcion que haga el resize
                    //despues de que al imagen ha sido cargada por el browser.
                    //Para eso llamamos al metodo resizeJsImage mediante setTimeout, mediante la isntancia del objeto.
                    //Utilizamos el miembro de clase this.imagen, como variable global.
                    setTimeout(this.instanceName + ".resizeJsImage('"+contenedor+"')", 300)
                }else{
                    //cargamos la iamgen normalmente
                    document.getElementById(contenedor).appendChild( this.imagen );
                }
                break;
            case '1':
            case 'video':
                //Inserto el elemento video dentro de su correspondiente contenedor, con el metodo asociado a este dato
                document.getElementById(contenedor).innerHTML = this.showVideo();
                break;
            default:
                break;
        }
        return true;
    }

    /**
     * Crea un objeto IMAGEN de JS, para luego asignarlo como un 'CHILD' al contenedor respectivo.
     */
    this.loadImage = function loadImage(){
        var imagen = new Image();
        imagen.src = this.Xml.archivos.archivo[this.actualNode].url;
        imagen.className = "imageObj";
        //var html = "<p class='imageFrame'><img style='position:relative;height:100%' src='"+this.Xml.archivos.archivo[this.actualNode].url+"'></p>";
        return imagen;
    }

    /**
     * Genera el HTML correspondiente para vizualizar un video FLV, con su FLASH player.
     */
    this.showVideo = function showVideo(){
        //asigno preview y video en el player
        return "<object class='videoObj' type='application/x-shockwave-flash' data='/swf/player_flv_maxi.swf?showvolume=1&showfullscreen=1'><param name='movie' value='/swf/player_flv_maxi.swf' /><param name='allowFullScreen' value='true' /><param name='FlashVars' value='flv=" + this.Xml.archivos.archivo[this.actualNode].urlFile + "&amp;title=Video&amp;startimage=" + this.Xml.archivos.archivo[this.actualNode].url + "' /></object>";
    }


    this.correctImageSize = function correctImageSize( maskWidth, maskHeight, imagen){ // originalProprotion, imgId ){
        var newWidth = maskWidth+0;
        var newHeight = maskHeight+0;

        var originalProprotion = imagen.width/imagen.height;
        var proportion = newWidth/newHeight;
        //alert("O W " + imagen.width)
        if( originalProprotion > proportion ){
            //la resta es +, por lo tanto la imagen es mas ancha que la proporcion del marco

            imagen.style.width = newWidth + "px";
            imagen.style.height = imagen.height * (Math.round((newWidth*100)/imagen.width)/100) + "px";
        }else{
            //la imagen es las alta que el marco original

            imagen.style.height = newHeight + "px";
            imagen.style.width = 0+(imagen.width * (Math.round((newHeight*100)/imagen.height)/100)) + "px";
        }
        //alert(imagen.style.height + " " + imagen.style.width)
        return imagen;
    }
    
    
    /**
     * Function to set the link ant text for downloadable files.
     * 
     * The text param set the string to be showed (localization) and the linkPrefix mark the URL-prefix where to
     * get the file. 
     * 
     * For example, if downloadLinkPrefix = "/free/site" then the final URL will be: "/free/site/{fileId}"
     * 
     * @param downloadLinkText
     * @param downloadLinkPrefix
     *
     * @return
     */
    this.setDownloadableFileInfo = function setDownloadableFileInfo(downloadLinkText, downloadLinkPrefix)
    {
    	// First, we must set the output in true, and the, set the text
    	this.buildLinks = true;
    	
    	this.linkText = downloadLinkText;
    	this.downloadLinkPrefix = downloadLinkPrefix;
    }
    
} 
